text:
using Microsoft.Azure.Commands.WebApps.Models;
using Microsoft.Azure.Management.Internal.Resources.Utilities;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using Microsoft.Azure.Management.WebSites.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Microsoft.Azure.Commands.WebApps.Utilities
{
    public static class CmdletHelpers
    {
        public static HashSet<string> SiteConfigParameters = new HashSet<string>
            {
                "DefaultDocuments",
                "NetFrameworkVersion",
                "PhpVersion",
                "RequestTracingEnabled",
                "HttpLoggingEnabled",
                "DetailedErrorLoggingEnabled",
                "HandlerMappings",
                "ManagedPipelineMode",
                "WebSocketsEnabled",
                "Use32BitWorkerProcess",
                "AutoSwapSlotName",
                "NumberOfWorkers"
            };

        public static HashSet<string> SiteParameters = new HashSet<string>
            {
                "HttpsOnly",
                "AssignIdentity"
            };

        private static readonly Regex AppWithSlotNameRegex = new Regex(@"^(?<siteName>[^\(]+)/(?<slotName>[^\)]+)$");

        private static readonly Regex WebAppResourceIdRegex =
            new Regex(@"^\/subscriptions\/(?<subscriptionName>[^\/]+)\/resourceGroups\/(?<resourceGroupName>[^\/]+)\/providers\/Microsoft.Web\/sites\/(?<siteName>[^\/]+)$", RegexOptions.IgnoreCase);

        private static readonly Regex WebAppSlotResourceIdRegex =
           new Regex(@"^\/subscriptions\/(?<subscriptionName>[^\/]+)\/resourceGroups\/(?<resourceGroupName>[^\/]+)\/providers\/Microsoft.Web\/sites\/(?<siteName>[^\/]+)\/slots\/(?<slotName>[^\/]+)$", RegexOptions.IgnoreCase);

        private static readonly Regex AppServicePlanResourceIdRegex =
           new Regex(@"^\/subscriptions\/(?<subscriptionName>[^\/]+)\/resourceGroups\/(?<resourceGroupName>[^\/]+)\/providers\/Microsoft.Web\/serverFarms\/(?<serverFarmName>[^\/]+)$", RegexOptions.IgnoreCase);

        private static readonly Dictionary<string, int> WorkerSizes = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { { "Small", 1 }, { "Medium", 2 }, { "Large", 3 }, { "ExtraLarge", 4 } };

        private const string ProductionSlotName = "Production";

        private const string FmtSiteWithSlotName = "{0}({1})";
        public const string ApplicationServiceEnvironmentResourcesName = "hostingEnvironments";
        private const string ApplicationServiceEnvironmentResourceIdFormat =
            "/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.Web/{2}/{3}";

		public const string DocerRegistryServerUrl = "DOCKER_REGISTRY_SERVER_URL";
		public const string DocerRegistryServerUserName = "DOCKER_REGISTRY_SERVER_USERNAME";
		public const string DocerRegistryServerPassword = "DOCKER_REGISTRY_SERVER_PASSWORD";
		public const string DockerEnableCI = "DOCKER_ENABLE_CI";
		public const string DockerImagePrefix = "DOCKER|";

		public static Dictionary<string, string> ConvertToStringDictionary(this Hashtable hashtable)
        {
            return hashtable == null ? null : hashtable.Cast<DictionaryEntry>()
                .ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString(), StringComparer.Ordinal);
        }

        public static Dictionary<string, ConnStringValueTypePair> ConvertToConnectionStringDictionary(this Hashtable hashtable)
        {
            return hashtable == null ? null : hashtable.Cast<DictionaryEntry>()
                .ToDictionary(
                kvp => kvp.Key.ToString(), kvp =>
                {
                    var typeValuePair = new Hashtable((Hashtable)kvp.Value, StringComparer.OrdinalIgnoreCase);
                    var type = (ConnectionStringType)Enum.Parse(typeof(ConnectionStringType), typeValuePair["Type"].ToString(), true);
                    return new ConnStringValueTypePair
                    {
                        Type = type,
                        Value = typeValuePair["Value"].ToString()
                    };
                });
        }

        internal static bool ShouldUseDeploymentSlot(string webSiteName, string slotName, out string qualifiedSiteName)
        {
            bool result = false;
            qualifiedSiteName = webSiteName;
#if !NETSTANDARD
            var siteNamePattern = "{0}({1})";
#else
            var siteNamePattern = "{0}/{1}";
#endif
            if (!string.IsNullOrEmpty(slotName) && !string.Equals(slotName, "Production", StringComparison.OrdinalIgnoreCase))
            {
                result = true;
                qualifiedSiteName = string.Format(siteNamePattern, webSiteName, slotName);
            }

            return result;
        }

        internal static HostingEnvironmentProfile CreateHostingEnvironmentProfile(string subscriptionId, string resourceGroupName, string aseResourceGroupName, string aseName)
        {
            var rg = string.IsNullOrEmpty(aseResourceGroupName) ? resourceGroupName : aseResourceGroupName;
            var aseResourceId = CmdletHelpers.GetApplicationServiceEnvironmentResourceId(subscriptionId, rg, aseName);
            return new HostingEnvironmentProfile(
                aseResourceId,
                CmdletHelpers.ApplicationServiceEnvironmentResourcesName,
                aseName);
        }

        internal static string BuildMetricFilter(DateTime? startTime, DateTime? endTime, string timeGrain, IReadOnlyList<string> metricNames)
        {
            var dateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
            var filter = "";
            if (metricNames != null && metricNames.Count > 0)
            {
                if (metricNames.Count == 1)
                {
                    filter = "name.value eq '" + metricNames[0] + "'";
                }
                else
                {
                    filter = "(name.value eq '" + string.Join("' or name.value eq '", metricNames) + "')";
                }
            }

            if (startTime.HasValue)
            {
                filter += string.Format("and startTime eq {0}", startTime.Value.ToString(dateTimeFormat));
            }

            if (endTime.HasValue)
            {
                filter += string.Format("and endTime eq {0}", endTime.Value.ToString(dateTimeFormat));
            }

            if (!string.IsNullOrWhiteSpace(timeGrain))
            {
                filter += string.Format("and timeGrain eq duration'{0}'", timeGrain);
            }

            return filter;
        }

        internal static bool TryParseWebAppMetadataFromResourceId(string resourceId, out string resourceGroupName,
            out string webAppName, out string slotName, bool failIfSlot = false)
        {
            var match = WebAppSlotResourceIdRegex.Match(resourceId);
            if (match.Success)
            {
                resourceGroupName = match.Groups["resourceGroupName"].Value;
                webAppName = match.Groups["siteName"].Value;
                slotName = match.Groups["slotName"].Value;

                return !failIfSlot & true;
            }

            match = WebAppResourceIdRegex.Match(resourceId);
            if (match.Success)
            {
                resourceGroupName = match.Groups["resourceGroupName"].Value;
                webAppName = match.Groups["siteName"].Value;
                slotName = null;

                return true;
            }

            resourceGroupName = null;
            webAppName = null;
            slotName = null;

            return false;
        }

        internal static bool TryParseAppServicePlanMetadataFromResourceId(string resourceId, out string resourceGroupName,
            out string appServicePlanName)
        {
            var match = AppServicePlanResourceIdRegex.Match(resourceId);
            if (match.Success)
            {
                resourceGroupName = match.Groups["resourceGroupName"].Value;
                appServicePlanName = match.Groups["serverFarmName"].Value;

                return true;
            }

            resourceGroupName = null;
            appServicePlanName = null;

            return false;
        }

        internal static string GetSkuName(string tier, int workerSize)
        {
            string sku;
            if (string.Equals("Shared", tier, StringComparison.OrdinalIgnoreCase))
            {
                sku = "D";
            }
            else if (string.Equals("PremiumV2", tier, StringComparison.OrdinalIgnoreCase))
            {
                sku = "P" + workerSize + "V2";
                return sku;
            }
			else if (string.Equals("PremiumContainer", tier, StringComparison.OrdinalIgnoreCase))
			{
				sku = "PC" + (workerSize + 1);
				return sku;
			}
			else
			{
                sku = string.Empty + tier[0];
            }

            sku += workerSize;
            return sku;
        }

        internal static string GetSkuName(string tier, string workerSize)
        {
            string sku;
			if (string.Equals("Shared", tier, StringComparison.OrdinalIgnoreCase))
			{
				sku = "D";
			}
			else if (string.Equals("PremiumV2", tier, StringComparison.OrdinalIgnoreCase))
			{
				sku = "P" + WorkerSizes[workerSize] + "V2";
				return sku;
			}
			else if (string.Equals("PremiumContainer", tier, StringComparison.OrdinalIgnoreCase))
			{
				sku = "PC" + (WorkerSizes[workerSize] + 1);
				return sku;
			}
			else
			{
				sku = string.Empty + tier[0];
			}

            sku += WorkerSizes[workerSize];
            return sku;
        }

        internal static bool IsDeploymentSlot(string name)
        {
            return AppWithSlotNameRegex.IsMatch(name);
        }

        internal static bool TryParseAppAndSlotNames(string name, out string webAppName, out string slotName)
        {
            var match = AppWithSlotNameRegex.Match(name);
            if (match.Success)
            {
                webAppName = match.Groups["siteName"].Value;
                slotName = match.Groups["slotName"].Value;
                return true;
            }

            webAppName = name;
            slotName = null;

            return false;
        }

        public static string GenerateSiteWithSlotName(string siteName, string slotName)
        {
            if (!string.IsNullOrEmpty(slotName) && !string.Equals(slotName, ProductionSlotName, StringComparison.OrdinalIgnoreCase))
            {
                return string.Format(FmtSiteWithSlotName, siteName, slotName);
            }

            return siteName;
        }

        internal static string GetApplicationServiceEnvironmentResourceId(string subscriptionId, string resourceGroupName, string applicationServiceEnvironmentName)
        {
            return string.Format(ApplicationServiceEnvironmentResourceIdFormat, subscriptionId, resourceGroupName, ApplicationServiceEnvironmentResourcesName,
                applicationServiceEnvironmentName);
        }

        internal static HostNameSslState[] GetHostNameSslStatesFromSiteResponse(Site site, string hostName = null)
        {
            var hostNameSslState = new HostNameSslState[0];
            if (site.HostNameSslStates != null)
            {
                hostNameSslState = site.HostNameSslStates.Where(h => h.SslState.HasValue && h.SslState.Value != SslState.Disabled).ToArray();
                if (!string.IsNullOrEmpty(hostName))
                {
                    hostNameSslState = hostNameSslState.Where(h => string.Equals(h.Name, hostName)).ToArray();
                }
            }
            return hostNameSslState;
        }

        internal static string GetResourceGroupFromResourceId(string resourceId)
        {
            return new ResourceIdentifier(resourceId).ResourceGroupName;
        }

        internal static void ExtractWebAppPropertiesFromWebApp(Site webapp, out string resourceGroupName, out string webAppName, out string slot)
        {
            resourceGroupName = GetResourceGroupFromResourceId(webapp.Id);

            string webAppNameTemp, slotNameTemp;
            if (TryParseAppAndSlotNames(
                webapp.Name,
                out webAppNameTemp,
                out slotNameTemp))
            {
                webAppName = webAppNameTemp;
                slot = slotNameTemp;
            }
            else
            {
                webAppName = webapp.Name;
                slot = null;
            }
        }

        internal static Certificate[] GetCertificates(ResourceClient resourceClient, WebsitesClient websitesClient, string resourceGroupName, string thumbPrint)
        {
            var certificateResources = resourceClient.ResourceManagementClient.FilterResources(new FilterResourcesOptions()
            {
                ResourceType = "Microsoft.Web/Certificates"
            }).ToArray();

            if (!string.IsNullOrEmpty(resourceGroupName))
            {
                certificateResources = certificateResources.Where(c => string.Equals(c.ResourceGroupName, resourceGroupName, StringComparison.OrdinalIgnoreCase)).ToArray();
            }

            var certificates =
                certificateResources.Select(
                    certificateResource =>
                    websitesClient.GetCertificate(certificateResource.ResourceGroupName ?? GetResourceGroupFromResourceId(certificateResource.Id), certificateResource.Name));

            if (!string.IsNullOrEmpty(thumbPrint))
            {
                certificates = certificates.Where(c => string.Equals(c.Thumbprint, thumbPrint, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            return certificates.ToArray();
        }

        internal static SiteConfigResource ConvertToSiteConfigResource(this SiteConfig config)
        {
            return new SiteConfigResource()
            {
                AlwaysOn = config.AlwaysOn,
                ApiDefinition = config.ApiDefinition,
                AppCommandLine = config.AppCommandLine,
                AppSettings = config.AppSettings,
                AutoHealEnabled = config.AutoHealEnabled,
                AutoHealRules = config.AutoHealRules,
                AutoSwapSlotName = config.AutoSwapSlotName,
                ConnectionStrings = config.ConnectionStrings,
                Cors = config.Cors,
                DefaultDocuments = config.DefaultDocuments,
                DetailedErrorLoggingEnabled = config.DetailedErrorLoggingEnabled,
                DocumentRoot = config.DocumentRoot,
                Experiments = config.Experiments,
                HandlerMappings = config.HandlerMappings,
                HttpLoggingEnabled = config.HttpLoggingEnabled,
                IpSecurityRestrictions = config.IpSecurityRestrictions,
                JavaContainer = config.JavaContainer,
                JavaContainerVersion = config.JavaContainerVersion,
                JavaVersion = config.JavaVersion,
                Limits = config.Limits,
                LinuxFxVersion = config.LinuxFxVersion,
                LoadBalancing = config.LoadBalancing,
                LocalMySqlEnabled = config.LocalMySqlEnabled,
                LogsDirectorySizeLimit = config.LogsDirectorySizeLimit,
                ManagedPipelineMode = config.ManagedPipelineMode,
                NetFrameworkVersion = config.NetFrameworkVersion,
                NodeVersion = config.NodeVersion,
                NumberOfWorkers = config.NumberOfWorkers,
                PhpVersion = config.PhpVersion,
                PublishingUsername = config.PublishingUsername,
                Push = config.Push,
                PythonVersion = config.PythonVersion,
                RemoteDebuggingEnabled = config.RemoteDebuggingEnabled,
                RemoteDebuggingVersion = config.RemoteDebuggingVersion,
                RequestTracingEnabled = config.RequestTracingEnabled,
                RequestTracingExpirationTime = config.RequestTracingExpirationTime,
                ScmType = config.ScmType,
                TracingOptions = config.TracingOptions,
                Use32BitWorkerProcess = config.Use32BitWorkerProcess,
                VirtualApplications = config.VirtualApplications,
                VnetName = config.VnetName,
                WebSocketsEnabled = config.WebSocketsEnabled,
				WindowsFxVersion = config.WindowsFxVersion
            };
        }

        internal static SiteConfig ConvertToSiteConfig(this SiteConfigResource config)
        {
            return new SiteConfig()
            {
                AlwaysOn = config.AlwaysOn,
                ApiDefinition = config.ApiDefinition,
                AppCommandLine = config.AppCommandLine,
                AppSettings = config.AppSettings,
                AutoHealEnabled = config.AutoHealEnabled,
                AutoHealRules = config.AutoHealRules,
                AutoSwapSlotName = config.AutoSwapSlotName,
                ConnectionStrings = config.ConnectionStrings,
                Cors = config.Cors,
                DefaultDocuments = config.DefaultDocuments,
                DetailedErrorLoggingEnabled = config.DetailedErrorLoggingEnabled,
                DocumentRoot = config.DocumentRoot,
                Experiments = config.Experiments,
                HandlerMappings = config.HandlerMappings,
                HttpLoggingEnabled = config.HttpLoggingEnabled,
                IpSecurityRestrictions = config.IpSecurityRestrictions,
                JavaContainer = config.JavaContainer,
                JavaContainerVersion = config.JavaContainerVersion,
                JavaVersion = config.JavaVersion,
                Limits = config.Limits,
                LinuxFxVersion = config.LinuxFxVersion,
                LoadBalancing = config.LoadBalancing,
                LocalMySqlEnabled = config.LocalMySqlEnabled,
                LogsDirectorySizeLimit = config.LogsDirectorySizeLimit,
                ManagedPipelineMode = config.ManagedPipelineMode,
                NetFrameworkVersion = config.NetFrameworkVersion,
                NodeVersion = config.NodeVersion,
                NumberOfWorkers = config.NumberOfWorkers,
                PhpVersion = config.PhpVersion,
                PublishingUsername = config.PublishingUsername,
                Push = config.Push,
                PythonVersion = config.PythonVersion,
                RemoteDebuggingEnabled = config.RemoteDebuggingEnabled,
                RemoteDebuggingVersion = config.RemoteDebuggingVersion,
                RequestTracingEnabled = config.RequestTracingEnabled,
                RequestTracingExpirationTime = config.RequestTracingExpirationTime,
                ScmType = config.ScmType,
                TracingOptions = config.TracingOptions,
                Use32BitWorkerProcess = config.Use32BitWorkerProcess,
                VirtualApplications = config.VirtualApplications,
                VnetName = config.VnetName,
                WebSocketsEnabled = config.WebSocketsEnabled,
				WindowsFxVersion = config.WindowsFxVersion,
			};
        }
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15">

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

  underline line-through overline

redpajama_set_name: RedPajamaGithub


text:
Nikola, a Static Site and Blog Generator
========================================

In goes content, out comes a website, ready to deploy.

.. image:: http://img.shields.io/pypi/v/Nikola.svg
   :target: https://pypi.python.org/pypi/Nikola

.. image:: https://img.shields.io/requires/github/getnikola/nikola.svg
   :target: https://requires.io/github/getnikola/nikola/requirements/?branch=master

.. image:: http://img.shields.io/travis/getnikola/nikola.svg
   :target: https://travis-ci.org/getnikola/nikola

.. image:: http://img.shields.io/coveralls/getnikola/nikola.png
  :target: https://coveralls.io/r/getnikola/nikola?branch=master

.. image:: http://img.shields.io/badge/license-MIT-green.svg
   :target: https://github.com/getnikola/nikola/blob/master/LICENSE.txt

.. image:: https://build.snapcraft.io/badge/getnikola/nikola.svg
   :target: https://build.snapcraft.io/user/getnikola/nikola

Why Static Websites?
--------------------

Static websites are safer, use fewer resources, and avoid vendor and platform lock-in.
You can read more about this in the `Nikola Handbook`_

What Can Nikola Do?
-------------------

It has many features, but here are some of the nicer ones:

* `Blogs, with tags, feeds, archives, comments, etc.`__
* `Themable`_
* Fast builds, thanks to `doit`_
* Flexible, extensible via the dozens of `available plugins`_
* Small codebase (programmers can understand all of Nikola core in a day)
* `reStructuredText`_ or Markdown as input language (also Wiki, BBCode, Textile, and HTML)
* Easy `image galleries`_ (just drop files in a folder!)
* Syntax highlighting for almost any programming language or markup
* Multilingual sites, `translated to 50 languages.`__
* Doesn't reinvent wheels, leverages existing tools.
* Python 3.3+ compatible.

.. _Nikola Handbook: https://getnikola.com/handbook.html#why-static
__ https://users.getnikola.com/
.. _Themable: https://themes.getnikola.com
.. _doit: http://pydoit.org
.. _available plugins: https://plugins.getnikola.com/
.. _reStructuredText: https://getnikola.com/quickstart.html
.. _image galleries: https://getnikola.com/galleries/demo/
__ https://www.transifex.com/projects/p/nikola/

Nikola Architecture
-------------------

.. image:: https://getnikola.com/images/architecture.png

Installation Instructions
-------------------------

Assuming you have pip installed::

    pip install Nikola

For optional features::

    pip install "Nikola[extras]"

For tests (see tests/README.rst for more details)::

    pip install "Nikola[extras,tests]"

For more information, see https://getnikola.com/


text:
package com.example.tests;

import org.testng.annotations.Test;
import com.example.tests.TestBase;

public class ContactRemovalTests extends TestBase{

	//private TestBase testBase;

	@Test
	public void deleteSomeContact(){
		app.getNavigationHelper().openMainPage();
		//app.getNavigationHelper().goToContactPage();

		app.getContactHelper().deleteContact(1);

		app.getContactHelper().returnToContactListPage();

	}
}


text:
layout: post
title: Missing your own party
date: 2010-02-12 19:36:35.000000000 -08:00
categories:
- general news
tags: []
status: publish
type: post
published: true
meta:
  _edit_last: '1'
author:
  login: ckelty
  email: ckelty@socgen.ucla.edu
  display_name: ckelty
  first_name: Christopher
  last_name: Kelty
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---

The largest spike in attention for this book came and went without me noticing.

The problem with having too much to do and too many different projects is it becomes impossible to keep on top of all the relevant discussions.  Two Bits was reviewed on Lambda The Ultimate, a weblog about programming languages.  There are some great comments, including an extensive one about how I am wrong (though I think it is more accurately about how the poster is right than it is about my book being wrong, but that often happens).  Metafilter picked it up.  The spike in traffic was an order of magnitute larger than anything I've gotten since the book was published, and I only just noticed :)

sorry I missed the discussion...


text:
package org.drools.workbench.models.guided.dtable.shared.auditlog;

import org.drools.workbench.models.guided.dtable.shared.model.BaseColumn;

/**
 * Basic details of a column
 */
public class ColumnDetails {

    private static final long serialVersionUID = -2111038793296621482L;

    private String columnHeader;

    public ColumnDetails() {
    }

    public ColumnDetails( final BaseColumn column ) {
        this.columnHeader = column.getHeader();
    }

    public String getColumnHeader() {
        return columnHeader;
    }

}


text:
<!DOCTYPE html>

    <title></title>

    <link href="acute/lib/bootstrap.min.css" rel="stylesheet" />
    <link href="acute/acute.select/acute.select.css" rel="stylesheet" />

                You can either input or selct the value:

                <select class="ac-select" ac-model="selectedState" ac-options="s for s in allStates" ac-change="stateSelected(value)"></select>

 "selectedState" value is: {{selectedState}}


text:
module Forem
  class Subscription
         include Mongoid::Document
    include Mongoid::Timestamps

  field :subscriber_id
   field :topic_id
    belongs_to :topic
    belongs_to :subscriber, :class_name => Forem.user_class.to_s
    validates_presence_of :subscriber_id

    def send_notification(post_id)
      SubscriptionMailer.topic_reply(post_id, self.subscriber.id).deliver
    end
  end
end


text:
/* ==============================================================================
 * 功能描述:FrequSort
 * 创 建 者:gz
 * 创建日期:2017/5/10 18:05:01
 * ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Given a string, sort it in decreasing order based on the frequency of characters.

//Example 1:

//Input:
//"tree"

//Output:
//"eert"

//Explanation:
//'e' appears twice while 'r' and 't' both appear once.
//So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
//Example 2:

//Input:
//"cccaaa"

//Output:
//"cccaaa"

//Explanation:
//Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
//Note that "cacaca" is incorrect, as the same characters must be together.
//Example 3:

//Input:
//"Aabb"

//Output:
//"bbAa"

//Explanation:
//"bbaA" is also a valid answer, but "Aabb" is incorrect.
//Note that 'A' and 'a' are treated as two different characters.
namespace FrequencySortSln
{
    /// <summary>
    /// FrequSort
    /// </summary>
    public class FrequSortSln
    {
        public string FrequencySort(string s)
        {
            Dictionary<char, int> freq = new Dictionary<char, int>();
            string[] buckets = new string[s.Length+1]; //索引用作字符个数,最大的个数索引也为最大
            //count char frequency
            foreach (var c in s)
            {
                if (!freq.ContainsKey(c))
                    freq.Add(c, 1);
                else freq[c]++;
            }
            //put char to buckets
            foreach (var item in freq)
            {
                int n = item.Value;
                char c = item.Key;
                StringBuilder builder = new StringBuilder();
                buckets[n] += builder.Append(c, n).ToString();
            }
            StringBuilder builder2 = new StringBuilder();
            //form string
            for (int i = s.Length; i > 0; i--)
            {
                if (buckets[i] != null)
                    builder2.Append(buckets[i]);
            }
            return builder2.ToString();
        }

    }
}


text:
<!DOCTYPE html>

	<title>segurodahora</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

pronto!

agora é so esperar.
em breve traremos novidades
sobre seguros para você!

		<form method = "post" id="form_cadastro">

			<?php //
<button  class="btn btn-success btn-block" style="background-color:#60b78c;border-radius: 0;"role="button" type="submit" name = "submit" value="inscricao">voltar para o site</button>

			?>

		</form>


text:
require "rails_helper"

RSpec.describe Waggle::Adapters::Solr::Search::FacetValue do
  let(:row) { ["Bob Bobbers", 10] }

  subject { described_class.new(row) }

  describe "value" do
    it "is the row value" do
      expect(subject.value).to eq(row[0])
    end
  end

  describe "name" do
    it "is the value" do
      expect(subject.name).to eq(subject.value)
    end
  end

  describe "count" do
    it "is the row count" do
      expect(subject.count).to eq(row[1])
    end
  end
end


text:
package org.iotivity.service.easysetup.mediator.enums;

/**
 * It defines various states of the cloud provisioning during easy setup process
 */
public enum ESCloudProvState {

    /**
     * Some error occurs during cloud data provisioning
     */
    ES_CLOUD_PROVISIONING_ERROR(-1),

    /**
     * Cloud data provisioning is successfully done
     */
    ES_CLOUD_PROVISIONING_SUCCESS(0),

    /**
     * Target enrollee which needs a cloud provisioning is found in a network
     */
    ES_CLOUD_ENROLLEE_FOUND(1),

    /**
     * Target enrollee which needs a cloud provisioning is NOT found in a network
     */
    ES_CLOUD_ENROLLEE_NOT_FOUND(2);

    private int value;

    private ESCloudProvState(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static ESCloudProvState fromInt(int i) {
        for (ESCloudProvState b : ESCloudProvState.values()) {
            if (b.getValue() == i) { return b; }
        }
        return null;
    }
};


text:
<resources>

    <string name="app_name">API.AI Commons</string>

    <string name="btn_add_agent">Add Agent</string>

    <string name="agents_list_title">Existed agents</string>
    <string name="prompt_no_agents">No agents available yet.</string>

    <string name="dialog_remove_title">Confirm</string>
    <string name="dialog_remove_message">Remove this agent permanently?</string>

    <string name="hint_apiai_agent_id">Put agent ID here.</string>

</resources>


text:
We have used a new types of design technique called `deep design` which is inspired from flat design and symbolize colors and icons.

##Code
You will find the entire code in the [gh-pages](../../tree/gh-pages) branch.

##How did we design?
Coming soon.


text:
package org.apereo.portal.utils;

import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.apereo.portal.utils.hibernate4.dialects.MySQL5InnoDBCompressedDialect;
import org.apereo.portal.utils.hibernate4.dialects.Oracle12ForceClobDialect;
import org.apereo.portal.utils.hibernate4.dialects.PostgreSQL81Dialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.SQLServer2005Dialect;
import org.hibernate.service.jdbc.dialect.internal.AbstractDialectResolver;

/** */
public class PortalDialectResolver extends AbstractDialectResolver {
    private static final long serialVersionUID = 1L;

    @Override
    protected final Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
        final String databaseName = metaData.getDatabaseProductName();
        final int databaseMajorVersion = metaData.getDatabaseMajorVersion();
        final int databaseMinorVersion = metaData.getDatabaseMinorVersion();

        if ("MySQL".equals(databaseName) && 5 == databaseMajorVersion) {
            return new MySQL5InnoDBCompressedDialect();
        }

        if ("PostgreSQL".equals(databaseName)
                && 8 == databaseMajorVersion
                && databaseMinorVersion <= 1) {
            return new PostgreSQL81Dialect();
        }

        // Ensure long varchar columns are forced to clob instead of long.
        if ("Oracle".equals(databaseName) && 12 >= databaseMajorVersion) {
            return new Oracle12ForceClobDialect();
        }

        // This is due to a jTDS not supporting SQL Server 2008+, hence does not support some new
        // types like TIME.
        if ("Microsoft SQL Server".equals(databaseName) && databaseMajorVersion > 9) {
            return new SQLServer2005Dialect();
        }

        return null;
    }
}


text:
export const MODULES_ANALYTICS = 'modules/analytics';

// A special Account ID value used for the "Set up a new account" option.
export const ACCOUNT_CREATE = 'account_create';
// A special Property ID value used for the "Set up a new property" option.
export const PROPERTY_CREATE = 'property_create';
// A special Profile ID value used for the "Set up a new profile" option.
export const PROFILE_CREATE = 'profile_create';
// Form ID for the account creation form.
export const FORM_ACCOUNT_CREATE = 'analyticsAccountCreate';
// Form ID for the module setup form.
export const FORM_SETUP = 'analyticsSetup';

// OAuth scope required for provisioning a Google Analytics account.
export const PROVISIONING_SCOPE =
	'https://www.googleapis.com/auth/analytics.provision';
export const EDIT_SCOPE = 'https://www.googleapis.com/auth/analytics.edit';

// Date range offset days for Analytics report requests.
export const DATE_RANGE_OFFSET = 1;

export const UI_DIMENSION_NAME = 'dashboardAllTrafficWidgetDimensionName';
export const UI_DIMENSION_COLOR = 'dashboardAllTrafficWidgetDimensionColor';
export const UI_DIMENSION_VALUE = 'dashboardAllTrafficWidgetDimensionValue';
export const UI_ACTIVE_ROW_INDEX = 'dashboardAllTrafficWidgetActiveRowIndex';
export const UI_ALL_TRAFFIC_LOADED = 'dashboardAllTrafficWidgetLoaded';

// Setup modes for Analytics based on UA/GA4 properties and
// GA4 API availability.
export const SETUP_FLOW_MODE_LEGACY = 'legacy';
export const SETUP_FLOW_MODE_UA = 'ua';
export const SETUP_FLOW_MODE_GA4 = 'ga4';
export const SETUP_FLOW_MODE_GA4_TRANSITIONAL = 'ga4-transitional';

export const PROPERTY_TYPE_UA = 'ua';
export const PROPERTY_TYPE_GA4 = 'ga4';


text:
from functools import partial

from kaio import Options

opts = Options()
get = partial(opts.get, section='Debug')

class DebugMixin(object):
    """Debug base settings"""

    @property
    def DEBUG(self):
        return get('DEBUG', False)

    @property
    def TEMPLATE_DEBUG(self):
        debug = get('TEMPLATE_DEBUG', self.DEBUG)
        for template in self.TEMPLATES:
            if template['BACKEND'] == 'django.template.backends.django.DjangoTemplates':
                template['OPTIONS']['debug'] = debug

    # https://django-debug-toolbar.readthedocs.io/en/stable/installation.html#explicit-setup
    DEBUG_TOOLBAR_PATCH_SETTINGS = False
    DEBUG_TOOLBAR_MIDDLEWARE = 'debug_toolbar.middleware.DebugToolbarMiddleware'

    @property
    def ENABLE_DEBUG_TOOLBAR(self):
        enabled = get('ENABLE_DEBUG_TOOLBAR', self.DEBUG)
        if enabled:
            try:
                import debug_toolbar  # noqa: F401
            except ImportError:
                return False
            else:
                self._add_debug_toolbar_to_installed_apps()
                self._add_debug_toolbar_to_middleware()

        return enabled

    @property
    def INTERNAL_IPS(self):
        ips = [ip.strip() for ip in get('INTERNAL_IPS', '127.0.0.1').split(',') if ip]
        # For Docker: https://django-debug-toolbar.readthedocs.io/en/stable/installation.html#configure-internal-ips
        if self.ENABLE_DEBUG_TOOLBAR:
            import socket
            _hostname, _aliases, docker_ips = socket.gethostbyname_ex(socket.gethostname())
            ips += [ip[:-1] + '1' for ip in docker_ips]
        return ips

    def _add_debug_toolbar_to_installed_apps(self):
        if 'debug_toolbar' not in self.INSTALLED_APPS:
            self.INSTALLED_APPS.append('debug_toolbar')

    def _add_debug_toolbar_to_middleware(self):
        middlewares_settings = (
            'MIDDLEWARE',  # django >= 1.10
            'MIDDLEWARE_CLASSES',  # django < 1.10
        )
        for middleware_setting in middlewares_settings:
            middlewares = getattr(self, middleware_setting, None)
            if middlewares is not None:
                if self.DEBUG_TOOLBAR_MIDDLEWARE not in middlewares:
                    middlewares.insert(0, self.DEBUG_TOOLBAR_MIDDLEWARE)


text:
#ifndef _VX_KHR_OPENCL_H_
#define _VX_KHR_OPENCL_H_

/*! \file
 * \brief The OpenVX to OpenCL Inter-op Extension Header.
 * \author Erik Rainey <erik.rainey@gmail.com>
 *
 * \defgroup group_cl_api API
 * \brief The API used by Clients to add OpenCL Kernels as <tt>vx_kernel</tt>.
 * \details
 *
 * \defgroup group_cl_def Extension Defines
 * \brief The Extension defines and constants.
 *
 * \defgroup group_cl_image Images
 * \brief OpenVX Images
 * \details Depending on whether the OpenCL implementation supports images, <tt>vx_image</tt>
 * may map to an <tt>image2d_t</tt> or a OpenCL buffer.
 *
 * \defgroup group_cl_array Arrays
 * \brief OpenVX Arrays
 *
 * \defgroup group_cl_convolution Convolutions
 * \brief OpenVX Convolutions
 *
 * \defgroup group_cl_distribution Distributions
 * \brief OpenVX Distributions
 *
 * \defgroup group_cl_matrix Matricies
 * \brief OpenVX Matrix
 *
 * \defgroup group_cl_types OpenVX to OpenCL Atomic Types
 * \brief Atomic Types
 * \details OpenVX types map to OpenCL types through this table:
 * | VX       | OpenCL|
 * |:---------|:------|
 * |<tt>vx_uint8</tt>  |<tt>uchar</tt>  |
 * |<tt>vx_int8</tt>   |<tt>char</tt>   |
 * |<tt>vx_uint16</tt> |<tt>ushort</tt> |
 * |<tt>vx_int16</tt>  |<tt>short</tt>  |
 * |<tt>vx_uint32</tt> |<tt>uint</tt>   |
 * |<tt>vx_int32</tt>  |<tt>int</tt>    |
 * |<tt>vx_uint64</tt> |<tt>ulong</tt>  |
 * |<tt>vx_int64</tt>  |<tt>long</tt>   |
 * |<tt>vx_float32</tt>|<tt>float</tt>  |
 * |<tt>vx_float64</tt>|<tt>double</tt> |
 * |<tt>vx_size</tt>   |<tt>size_t</tt> |
 *
 * \note <tt>size_t</tt> can not be used as a parameter to a <tt>__kernel</tt>.
 */

#ifndef VX_SCALE_UNITY
#define VX_SCALE_UNITY  (1024)
#endif

/*!\brief The maximum number of planes an image may have which is compatible across both
 * API.
 * \ingroup group_cl_def
 */
#define VX_CL_MAX_PLANES (4)

#if defined(VX_CL_DOCUMENTATION) || !defined(VX_CL_KERNEL)

#if defined(__APPLE__) || defined(DARWIN)
#include <OpenCL/OpenCL.h>
#else
#include <CL/cl.h>
#endif

#if (!defined(__APPLE__)) && defined(CL_USE_LUMINANCE)
#define CL_USE_IMAGES
#endif

/*! \brief The string name of this extension to match for in the extensions list
 * \ingroup group_cl_def
 */
#define OPENVX_KHR_OPENCL "vx_khr_opencl"

/*! \brief Adds an OpenCL Kernel as source code into the OpenVX implementation.
 * \param [in] context The OpenVX Context.
 * \param [in] name The name of the kernel in OpenVX nomenclature.
 * \param [in] enumeration The OpenVX kernel enumeration used to identify this kernel.
 * \param [in] source The array of source line pointers.
 * \param [in] line_lengths The array of lines lengths for each line of source.
 * \param [in] num_lines the number of lines in both the sources array and line_lengths array.
 * \param [in] symbol_name The name of the kernel to call in the program.
 * \param [in] numParams The number of parameters to the OpenVX kernel.
 * \param [in] input The input validator.
 * \param [in] output The output validator.
 * \see <tt>vxAddParameterToKernel</tt> to configure the specific parameter attributes.
 * \ingroup group_cl_api
 */
VX_API_ENTRY vx_kernel VX_API_CALL vxAddOpenCLAsSourceKernel(vx_context context,
                                    vx_char name[VX_MAX_KERNEL_NAME],
                                    vx_enum enumeration,
                                    char *source[],
                                    size_t line_lengths[],
                                    size_t num_lines,
                                    char symbol_name[],
                                    vx_uint32 numParams,
                                    vx_kernel_input_validate_f input,
                                    vx_kernel_output_validate_f output);

/*! \brief Adds an OpenCL Kernel as binary program into the OpenVX implementation.
 * \param [in] context The OpenVX Context.
 * \param [in] name The name of the kernel in OpenVX nomenclature.
 * \param [in] enumeration The OpenVX kernel enumeration used to identify this kernel.
 * \param [in] program The OpenCL Program which contains the kernel (either pre-compiled or compiled by user).
 * \param [in] symbol_name The name of the kernel to call in the program.
 * \param [in] numParams The number of parameters to the OpenVX kernel.
 * \param [in] input The input validator.
 * \param [in] output The output validator.
 * \see <tt>vxAddParameterToKernel</tt> to configure the specific parameter attributes.
 * \ingroup group_cl_api
 */
VX_API_ENTRY vx_kernel VX_API_CALL vxAddOpenCLAsBinaryKernel(vx_context context,
                                    vx_char name[VX_MAX_KERNEL_NAME],
                                    vx_enum enumeration,
                                    cl_program program,
                                    char symbol_name[],
                                    vx_uint32 numParams,
                                    vx_kernel_input_validate_f input,
                                    vx_kernel_output_validate_f output);

#endif // External API

#if defined(VX_CL_DOCUMENTATION) || defined(VX_CL_KERNEL)

#if defined(__IMAGE_SUPPORT__) && defined(CL_USE_LUMINANCE)
#define CL_USE_IMAGES
#endif

/*! \brief Allows access to an image pixel as a typecast pointer deference.
 * \param type The OpenCL single element type
 * \param ptr The <tt>__global</tt> pointer to the base of the image.
 * \param x The x coordinate.
 * \param y The y coordinate.
 * \param sx The x stride.
 * \param sy The y stride.
 * \ingroup group_cl_image
 */
#define vxImagePixel(type, ptr, x, y, sx, sy) \
    (*(type *)(&((uchar *)ptr)[((y) * sy) + ((x) * sx)]))

/*!
 * \brief Allows access to an array item as a typecast pointer deference.
 * \param type The OpenCL single element type or structure type.
 * \param ptr The <tt>__global</tt> pointer to the base of the array.
 * \param index The index of the element to access.
 * \param stride The stride in bytes between two adjacent elements.
 * \ingroup group_cl_array
 */
#define vxArrayItem(type, ptr, index, stride) \
    (*(type *)(&((uchar *)ptr)[index*stride]))

/*! \brief Allows access to a matrix element \f$ M_{ij} \f$ where i is the column and j is the row.
 * \param type The OpenCL single element type of the matrix.
 * \param ptr The <tt>__global</tt> pointer to the base of the array.
 * \param columns The number of columns in the matrix.
 * \param i The column index
 * \param j The row index
 * \ingroup group_cl_matrix
 */
#define vxMatrixElement(type, ptr, columns, i, j) (((type *)ptr)[columns*j + i])

/*! \brief Allows access to a convolution element \f$ C_{ij} \f$ where i is the column and j is the row.
 * \note Convolution elements are always of type <tt>short</tt>.
 * \param ptr The <tt>__global</tt> pointer to the base of the array.
 * \param columns The number of columns in the matrix.
 * \param i The column index
 * \param j The row index
 * \ingroup group_cl_convolution
 */
#define vxConvolveElement(ptr, columns, i, j) (((short *)ptr)[columns*j + i])

/*! \brief Allows access to a distribution frequency counter.
 * \param ptr The <tt>__global</tt> pointer to the base of the distribution.
 * \param value The value to retrive the frequency count for.
 * \param offset The offset within the input domain.
 * \param range The total range within the domain starting from offset.
 * \param window_size The window size of the bin.
 * \ingroup group_cl_distribution
 */
#define vxGetFrequency(ptr, value, offset, range, window_size) \
    ((offset <= value) && (value <= (range+offset)) ? ptr[(value-offset)/window_size] : 0)

/*! \brief Increments a distribution frequency counter for a value.
 * \param ptr The <tt>__global</tt> pointer to the base of the distribution.
 * \param value The value to increment the frequency count for.
 * \param offset The offset within the input domain.
 * \param range The total range within the domain starting from offset.
 * \param window_size The window size of the bin.
 * \ingroup group_cl_distribution
 */
#define vxIncFrequency(ptr, value, offset, range, window_size) \
    ((offset <= value) && (value <= (range+offset)) ? ++ptr[(value-offset)/window_size] : 0)

/*! \brief Decrements a distribution frequency counter for a value.
 * \param ptr The <tt>__global</tt> pointer to the base of the distribution.
 * \param value The value to decrement the frequency count for.
 * \param offset The offset within the input domain.
 * \param range The total range within the domain starting from offset.
 * \param window_size The window size of the bin.
 * \ingroup group_cl_distribution
 */
#define vxDecFrequency(ptr, value, offset, range, window_size) \
    ((offset <= value) && (value <= (range+offset)) ? --ptr[(value-offset)/window_size] : 0)

#endif

#endif


text:
package org.apache.hyracks.dataflow.std.map;

import java.util.Random;

import org.apache.hyracks.api.dataflow.IDataWriter;
import org.apache.hyracks.api.exceptions.HyracksDataException;

public class SamplerDeserializedMapperFactory implements IDeserializedMapperFactory {
    private static final long serialVersionUID = 1L;
    private final float sampleRatio;

    public SamplerDeserializedMapperFactory(float sampleRatio) {
        this.sampleRatio = sampleRatio;
    }

    @Override
    public IDeserializedMapper createMapper() throws HyracksDataException {
        return new IDeserializedMapper() {
            private Random random = new Random();

            @Override
            public void map(Object[] data, IDataWriter<Object[]> writer) throws HyracksDataException {
                if (random.nextFloat() <= sampleRatio) {
                    writer.writeData(data);
                }
            }
        };
    }
}


text:
class C_BaseDoor : public C_BaseEntity
{
public:
	DECLARE_CLASS( C_BaseDoor, C_BaseEntity );
	DECLARE_CLIENTCLASS();

	C_BaseDoor( void );
	~C_BaseDoor( void );

public:
	float		m_flWaveHeight;
};

#endif // C_BASEDOOR_H


text:
package com.cloud.legacymodel.vm;

public class VmStatsEntry implements VmStats {

    double cpuUtilization;
    double networkReadKBs;
    double networkWriteKBs;
    double diskReadIOs;
    double diskWriteIOs;
    double diskReadKBs;
    double diskWriteKBs;
    int numCPUs;
    String entityType;

    public VmStatsEntry() {
    }

    public VmStatsEntry(final double cpuUtilization, final double networkReadKBs, final double networkWriteKBs, final int numCPUs, final String entityType) {
        this.cpuUtilization = cpuUtilization;
        this.networkReadKBs = networkReadKBs;
        this.networkWriteKBs = networkWriteKBs;
        this.numCPUs = numCPUs;
        this.entityType = entityType;
    }

    public VmStatsEntry(final double cpuUtilization, final double networkReadKBs, final double networkWriteKBs, final double diskReadKBs, final double diskWriteKBs, final int
            numCPUs, final String entityType) {
        this.cpuUtilization = cpuUtilization;
        this.networkReadKBs = networkReadKBs;
        this.networkWriteKBs = networkWriteKBs;
        this.diskReadKBs = diskReadKBs;
        this.diskWriteKBs = diskWriteKBs;
        this.numCPUs = numCPUs;
        this.entityType = entityType;
    }

    @Override
    public double getCPUUtilization() {
        return cpuUtilization;
    }

    public void setCPUUtilization(final double cpuUtilization) {
        this.cpuUtilization = cpuUtilization;
    }

    @Override
    public double getNetworkReadKBs() {
        return networkReadKBs;
    }

    public void setNetworkReadKBs(final double networkReadKBs) {
        this.networkReadKBs = networkReadKBs;
    }

    @Override
    public double getNetworkWriteKBs() {
        return networkWriteKBs;
    }

    public void setNetworkWriteKBs(final double networkWriteKBs) {
        this.networkWriteKBs = networkWriteKBs;
    }

    @Override
    public double getDiskReadIOs() {
        return diskReadIOs;
    }

    public void setDiskReadIOs(final double diskReadIOs) {
        this.diskReadIOs = diskReadIOs;
    }

    @Override
    public double getDiskWriteIOs() {
        return diskWriteIOs;
    }

    public void setDiskWriteIOs(final double diskWriteIOs) {
        this.diskWriteIOs = diskWriteIOs;
    }

    @Override
    public double getDiskReadKBs() {
        return diskReadKBs;
    }

    public void setDiskReadKBs(final double diskReadKBs) {
        this.diskReadKBs = diskReadKBs;
    }

    @Override
    public double getDiskWriteKBs() {
        return diskWriteKBs;
    }

    public void setDiskWriteKBs(final double diskWriteKBs) {
        this.diskWriteKBs = diskWriteKBs;
    }

    public int getNumCPUs() {
        return numCPUs;
    }

    public void setNumCPUs(final int numCPUs) {
        this.numCPUs = numCPUs;
    }

    public String getEntityType() {
        return this.entityType;
    }

    public void setEntityType(final String entityType) {
        this.entityType = entityType;
    }
}


text:
#include "ReadWriteXMLString.h"
#include "XMLReadingMachine.h"
#include "XMLWritingMachine.h"

namespace Open3DMotion
{
	void ReadWriteXMLString::WriteValue(XMLWritingMachine& writer, const TreeValue* value) const
	{
		writer.WriteTextNode( static_cast<const TreeString*>( value )->Value() );
	}

	TreeValue* ReadWriteXMLString::ReadValue(XMLReadingMachine& reader, const pugi::xml_node& element) const
	{
		std::string text;
		reader.ReadTextNode(text, element);
		if (text.size() == 0)
			return NULL;
		else
			return new TreeString(text.c_str());
	}
}


text:
Hi <?php echo $username;?>!

Someone has requested a link to change your password, and you can do this through the link below:

  <a href="<?php echo $uri; ?>">
    Change my password

If you didn't request this, please ignore this email.

Your password won't change until you access the link above and create a new one.


text:
package org.apache.syncope.core.persistence.jpa.validation.entity;

import javax.validation.ConstraintValidatorContext;
import org.apache.syncope.common.lib.types.EntityViolationType;
import org.apache.syncope.core.persistence.api.dao.AllowedSchemas;
import org.apache.syncope.core.persistence.api.entity.Any;
import org.apache.syncope.core.persistence.api.entity.AnyUtilsFactory;
import org.apache.syncope.core.persistence.api.entity.GroupableRelatable;
import org.apache.syncope.core.persistence.api.entity.Membership;
import org.apache.syncope.core.persistence.api.entity.PlainAttr;
import org.apache.syncope.core.persistence.api.entity.PlainSchema;
import org.apache.syncope.core.persistence.api.entity.group.Group;
import org.apache.syncope.core.spring.ApplicationContextProvider;

@SuppressWarnings("rawtypes")
public class AnyValidator extends AbstractValidator<AnyCheck, Any> {

    private static boolean raiseNotAllowedViolation(
            final ConstraintValidatorContext context,
            final String schema,
            final Group group) {

        if (group == null) {
            context.buildConstraintViolationWithTemplate(
                    getTemplate(EntityViolationType.InvalidPlainAttr,
                            schema + " not allowed for this instance")).
                    addPropertyNode("plainAttrs").addConstraintViolation();
        } else {
            context.buildConstraintViolationWithTemplate(
                    getTemplate(EntityViolationType.InvalidPlainAttr,
                            schema + " not allowed for membership of group " + group.getName())).
                    addPropertyNode("plainAttrs").addConstraintViolation();
        }
        return false;
    }

    @Override
    public boolean isValid(final Any any, final ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();

        AllowedSchemas<PlainSchema> allowedPlainSchemas =
                ApplicationContextProvider.getApplicationContext().getBean(AnyUtilsFactory.class).
                        getInstance(any.getType().getKind()).dao().findAllowedSchemas(any, PlainSchema.class);

        for (PlainAttr<?> attr : ((Any<?>) any).getPlainAttrs()) {
            if (attr != null && !allowedPlainSchemas.forSelfContains(attr.getSchema().getKey())) {
                return raiseNotAllowedViolation(context, attr.getSchema().getKey(), null);
            }
        }
        if (any instanceof GroupableRelatable) {
            for (Membership<?> membership : ((GroupableRelatable<?, ?, ?, ?, ?>) any).getMemberships()) {
                for (PlainAttr<?> attr : ((GroupableRelatable<?, ?, ?, ?, ?>) any).getPlainAttrs(membership)) {
                    if (attr != null && !allowedPlainSchemas.forMembershipsContains(
                            membership.getRightEnd(), attr.getSchema().getKey())) {

                        return raiseNotAllowedViolation(
                                context, attr.getSchema().getKey(), membership.getRightEnd());
                    }
                }
            }
        }

        return true;
    }
}


text:
import React, { PureComponent } from 'react';
import { func, number, object, string } from 'prop-types';
import { calculateInitialState, calculateNextState } from './Utils';

export default class Icon extends PureComponent {
  static displayName = 'Icon';

  static propTypes = {
    _onClick: func,
    alt: string,
    className: string,
    height: number.isRequired,
    src: string.isRequired,
    style: object,
    width: number.isRequired,
  }

  static defaultProps = {
    _onClick: () => {},
    alt: '',
    className: '',
    style: {},
  }

  constructor(props) {
    super(props);
    this.state = {
      style: {},
    };
  }

  componentWillMount() {
    this.setState(calculateInitialState.call(this, diffProps));
  }

  componentWillReceiveProps(nextProps) {
    const nextState = calculateNextState.call(this, nextProps, diffProps);
    if (Object.keys(nextState).length) {
      this.setState(nextState);
    }
  }

  calculateStyle({ style }) {
    return { ...styles.button, ...style };
  }

  render() {
    const { _onClick, alt, className, height, src, width } = this.props;
    const { style } = this.state;

    return (
      <button
        className={className}
        style={style}
        onClick={_onClick}
      >
        <img
          className={`${className}_img`}
          height={height}
          width={width}
          src={src}
          alt={alt}
        />
      </button>
    );
  }
}

const styles = {
  button: {
    border: 'none',
    outline: 'none',
    background: 'transparent',
    padding: 0,
    margin: 0,
    cursor: 'pointer',
  },
};

const diffProps = {
  style: ['style'],
};


text:
from setuptools import setup
import os
import re

# Lovingly adapted from https://github.com/kennethreitz/requests/blob/39d693548892057adad703fda630f925e61ee557/setup.py#L50-L55
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pusher/version.py'), 'r') as fd:
    VERSION = re.search(r'^VERSION = [\']([^\']*)[\']',
                        fd.read(), re.MULTILINE).group(1)

if not VERSION:
    raise RuntimeError('Ensure `VERSION` is correctly set in ./pusher/version.py')

setup(
    name='pusher',
    version=VERSION,
    description='A Python library to interract with the Pusher Channels API',
    long_description='A Python library to interract with the Pusher Channels API',
    long_description_type='text/x-rst',
    url='https://github.com/pusher/pusher-http-python',
    author='Pusher',
    author_email='support@pusher.com',
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Internet :: WWW/HTTP',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    keywords='pusher rest realtime websockets service',
    license='MIT',

    packages=[
        'pusher'
    ],

    install_requires=[
        'six',
        'requests>=2.3.0',
        'urllib3',
        'pyopenssl',
        'ndg-httpsclient',
        'pyasn1',
        'pynacl'
    ],

    tests_require=['nose', 'mock', 'HTTPretty'],

    extras_require={
        'aiohttp': ['aiohttp>=0.20.0'],
        'tornado': ['tornado>=5.0.0']
    },

    package_data={
        'pusher': ['cacert.pem']
    },

    test_suite='pusher_tests',
)


text:
package com.ckkloverdos.topsort.util

import com.ckkloverdos.topsort.event.PrintStreamListener

/**
 * Convenience methods to create a graph of symbols from a simple
 * textual representation.
 * The motivation is to help debugging.
 */
object SymbolGraph {
  final type SymbolGraph = SimpleGraph[Symbol]

  def Empty: SymbolGraph = SimpleGraph[Symbol]()

  //////////////////////////////////////////////
  // ~ approximate implementation ~
  //////////////////////////////////////////////
  //   graph  ::= fromto (';'  fromto)*
  //           |  fromto ('\n' fromto)*
  //   fromto ::= node '->' node (',' node)*
  //   node   ::= symbol
  //////////////////////////////////////////////
  def apply(source: String): SymbolGraph = {
    val fromtoArray = source.
      replaceAll("""/\*.+?\*/""", ""). // comments (!)
      split("\n|;").
      map(_.trim).
      filterNot(_.isEmpty)

    def parseFromTo(fromto: String): SymbolGraph = {
      val split = fromto.
        split("->|→"). // Separate by "->"
        map(_.trim).           // Trim results
        filterNot(_.isEmpty)   // Keep only non empty strings

      split match {
        case Array(from, to) ⇒
          val fromSymbol = Symbol(from)
          val toSymbols = LSet[Symbol]() ++ to.
            split(",").
            map(_.trim).
            filterNot(_.isEmpty).
            map(Symbol(_))

          val initialGraph: SymbolGraph = Empty ++ (fromSymbol, toSymbols)

          // The initial graph (zero element in foldLeft)
          // is the one with the dependencies and then we
          // create one empty mapping for each dependency (`toSymbols`).
          toSymbols.foldLeft(initialGraph)(_ + _)
      }
    }

    fromtoArray.
      map(parseFromTo).
      foldLeft(Empty)(_ ++ _)
  }

  val AGraph: SymbolGraph = Empty +
    ('A → 'C) +
          ('C → 'D) +
    ('A → 'D) +
          ('D → 'B)

  val BGraphStr =
    """
      | A → B
      | A → C
      | A → D
      | C → D
      | D → A
    """.stripMargin
  val BGraph: SymbolGraph = SymbolGraph(BGraphStr)

  def main(args: Array[String]): Unit = {
    println(AGraph)
    println("+======= A Graph =======")
    val printListener = PrintStreamListener.StdOut[Symbol]
    println(AGraph.topSort(printListener))
    println("-======= A Graph =======")
//    println("+======= B Graph =======")
//    println(BGraph.topSortResult(printListener))
//    println("-======= B Graph =======")
  }
}


text:
from . import calls, modules

commands = {
    'calls': calls,
    'modules': modules
}


text:
/**
 * Esta clase es el scena world de la scena numero 4
 * creacion manual de los componentes de la escena
 * establece coordenadas y rectangulos de interseccion
 * implements ActionListener
 *
 * @author: Mario Josue Grieco Villamizar Universidad Nacional Experimental del
 * Tachira
 * @version: 0.1
 */

package ScenasWorld;

import Windows.Screem;
import static Windows.Screem.heigth;
import static Windows.Screem.width;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import javafx.scene.shape.Polyline;
import javax.imageio.ImageIO;

/**
 *
 * COMO EN LOS ENGINES TODO LA CONSTRUCCION DEL MUNDO ES MANUAL OBJETO POR
 * OBJETO NADA DINAMICO
 * Esta clase es el scena world de la scena numero 4
 * creacion manual de los componentes de la escena
 * establece coordenadas y rectangulos de interseccion
 * implements ActionListener
 */

public class Scena4World implements Screem {

    /**
     * Arreglos de las imagenes que se usaran en la scena
     */
    public Image fondo[];
    /**
     * Coordenadas x y, ancho y alto de cada una de las imagenes
     */
    public int border[][];
    /**
     * Collecion de imagenes del cocodrilo
     */
    public Image alligator[];
    /**
     * El estado del cocodrilo ( cual imagen se mostrara)
     */
    public int alligatorState = 0;

    /**
     * Coordenadas relativas de la escena y sus componentes en el mapa
     */
    public int relativeCoord = 0;
    /**
     * orientacion de cocodrino normalmente es 1 derecaha -1 izquierda esta esta
     * invertida
     */
    public int cocodriloOrientation = 1; // esta invertida

    /**
     * constructor
     */
    public Scena4World() {

        fondo = new Image[3];
        alligator = new Image[9];
        border = new int[4][4];

        try {
            fondo[0] = ImageIO.read(new File("src/level1/s4/Fondo/1.png"));
            border[0][0] = 0;
            border[0][1] = 0;
            border[0][2] = width;
            border[0][3] = heigth;

            fondo[1] = ImageIO.read(new File("src/level1/s4/Fondo/2.png"));
            border[1][0] = 0;
            border[1][1] = heigth - 181;
            border[1][2] = width;
            border[1][3] = 181;

            fondo[2] = ImageIO.read(new File("src/level1/s4/Fondo/3.png"));
            border[2][0] = (width / 2) - (width / 4);
            border[2][1] = heigth - 181;
            border[2][2] = (width / 2);
            border[2][3] = 181;

            alligator[0] = ImageIO.read(new File("src/level1/s4/Fondo/alligator0.png"));
            alligator[1] = ImageIO.read(new File("src/level1/s4/Fondo/alligator1.png"));
            alligator[2] = ImageIO.read(new File("src/level1/s4/Fondo/alligator2.png"));
            alligator[3] = ImageIO.read(new File("src/level1/s4/Fondo/alligator3.png"));
            alligator[4] = ImageIO.read(new File("src/level1/s4/Fondo/alligator4.png"));
            alligator[5] = ImageIO.read(new File("src/level1/s4/Fondo/alligator5.png"));
            alligator[6] = ImageIO.read(new File("src/level1/s4/Fondo/alligator6.png"));

            border[3][0] = (width / 2) - 150;
            border[3][1] = heigth - 320;
            border[3][2] = 260;
            border[3][3] = 220;

        } catch (IOException err) {
            System.out.println("ScenasWorld.Scena3World.<init>()");
        }
    }

    /**
     * retorna cada Rectangulo que se pide
     *
     * @param x numero del rectangulo ( imagen de fondo o objeto)
     * @return Rectangle2D.Double
     */
    public Rectangle2D getRectangle(int x) {
        if (x == 9) {
            return new Rectangle2D.Double((border[2][0] + 50), border[2][1] + 6, border[2][2] - 100, border[2][3]);
        }
        if (x == 3) {
            return new Rectangle2D.Double(border[x][0] + 70, border[x][1] + 133, border[x][2] - 140, border[x][3] - 100);
        }
        return new Rectangle2D.Double(border[x][0], border[x][1], border[x][2], border[x][3]);
    }

    /**
     * Establece las coordenadas relativas
     *
     * @param x determina las coordenadas relativas
     */
    public void SetRelativeObjects(int x) {
        relativeCoord += x;

        for (int i = 0; i < 4; i++) {
            border[i][0] += relativeCoord;
        }

    }
}


text:
TimerAbort::TimerAbort(int seconds)
{
	m_timeout.tv_sec = seconds;
	m_timeout.tv_nsec = 0;
}

void TimerAbort::GetDelay(struct timespec *ts)
{
	*ts = m_timeout;
}

void TimerAbort::TimerExpired(Timers *timers, ITimer *timer)
{
	abort();
}


text:
package io.tehtotalpwnage.pvptoggle.listeners;

import java.util.UUID;

import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import io.tehtotalpwnage.pvptoggle.configs.PlayerList;
import io.tehtotalpwnage.pvptoggle.utils.TranslationHelper;
import ninja.leaping.configurate.ConfigurationNode;

public class LoginListener {

	@Listener
	public void onClientConnection(ClientConnectionEvent.Join event) {
		Player player = event.getTargetEntity();
		UUID uuid = player.getUniqueId();
		ConfigurationNode node = PlayerList.getInstance().getNode();
		if (node.getNode("players", uuid, "pvp").isVirtual()) {
			node.getNode("players", uuid, "pvp").setValue(false);
			PlayerList.getInstance().save();
			player.sendMessage(TranslationHelper.t("text.player.disabled", player.getLocale()));
			player.sendMessage(TranslationHelper.t("text.player.toggle", player.getLocale()));
		} else {
			if (node.getNode("players", uuid, "pvp").getBoolean()) {
				player.sendMessage(TranslationHelper.t("text.player.enabled", player.getLocale()));
				player.sendMessage(TranslationHelper.t("text.player.toggle", player.getLocale()));
			} else {
				player.sendMessage(TranslationHelper.t("text.player.disabled", player.getLocale()));
				player.sendMessage(TranslationHelper.t("text.player.toggle", player.getLocale()));
			}
		}
	}
}


text:
./scripts/admin-clean.sh $@
./scripts/admin-update.sh $@


text:
import configparser
from subprocess import call, check_output
import sys
import datetime
import time
import json
import requests

pimat_api_endpoint = 'http://localhost/api/v1/relay/logger'

relay_file = '/opt/pimat/relays.ini'
relay_config = configparser.ConfigParser()
relay_config.read(relay_file)

def get_now():
    # get the current date and time as a string
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""
    # yyyy-MM-dd'T'HH:mm:ss.SSS    strict_date_hour_minute_second_millis
    if isinstance(obj, datetime):
        tz_string = "Z"
        serial = "%s.%03d" % (
            obj.strftime("%Y-%m-%dT%H:%M:%S"),
            int(obj.microsecond / 1000))
        return serial
    raise TypeError("Type not serializable")

def get_pin_status(pin):
    status = check_output(['gpio', 'read', pin])

    if status[0] == '0':
        return 'ON'

    elif status[0] == '1':
        return 'OFF'

    else:
        return None

class Relays(object):
    def __init__(self, relay, pin):
        self.relay = relay
        self.pin = pin

    def start(self):
        call(['gpio', 'mode', self.pin, 'out'])
        call(['gpio', 'write', self.pin, '0'])
        relay_config.set('status', self.relay, '1')

        with open(relay_file, 'w') as ini_file:
            relay_config.write(ini_file)

        json_data = dict()
        json_data['timestamp'] = get_now()
        json_data['relay'] = self.relay
        json_data['pin'] = self.pin
        json_data['action'] = 'start'
        json_data['value'] = '1'
        json_data['source'] = 'pimat-client-1'

        retries = 4
        while retries > 1:
            retries -= 1
            try:
                requests.post(pimat_api_endpoint, data=json.dumps(json_data, default=json_serial),
                      headers={'content-type': 'application/json'})
            except requests.ConnectionError:
                time.sleep(3)

        return 'started'

    def stop(self):
        call(['gpio', 'mode', self.pin, 'out'])
        call(['gpio', 'write', self.pin, '1'])
        relay_config.set('status', self.relay, '0')

        with open(relay_file, 'w') as ini_file:
            relay_config.write(ini_file)

        json_data = dict()
        json_data['timestamp'] = get_now()
        json_data['relay'] = self.relay
        json_data['pin'] = self.pin
        json_data['action'] = 'stop'
        json_data['value'] = '0'
        json_data['source'] = 'pimat-client-1'

        retries = 4
        while retries > 1:
            retries -= 1
            try:
                requests.post(pimat_api_endpoint, data=json.dumps(json_data, default=json_serial),
                              headers={'content-type': 'application/json'})
            except requests.ConnectionError:
                time.sleep(3)

        return 'stopped'

    def set_mode(self, mode='out'):
        call(['gpio', 'mode', self.pin, mode])

        json_data = dict()
        json_data['timestamp'] = get_now()
        json_data['relay'] = self.relay
        json_data['pin'] = self.pin
        json_data['action'] = 'mode'
        json_data['value'] = mode
        json_data['source'] = 'pimat-client-1'

        return mode

def main():
    action = sys.argv[1]
    relay = sys.argv[2]
    relay_list = []

    for each in relay_config['pins']:
        relay_list.append(each)

    print action

    if relay in relay_list:
        pin = relay_config['pins'][relay]
        relay_object = Relays(relay, pin)

        if action == 'start':
            relay_object.set_mode()
            relay_object.start()

        elif action == 'stop':
            relay_object.set_mode()
            relay_object.stop()

        else:
            print('Wrong command line args use stop or start')
            sys.exit(1)

    else:
        print('Relay ID does not exist must be between 1 and 4')
        sys.exit(1)

if __name__ == '__main__':
    main()


text:
//-----------------------------------------------------------------------
// <copyright file="FlowInterleaveSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Util.Internal;
using FluentAssertions;
using Reactive.Streams;
using Xunit;

// ReSharper disable InvokeAsExtensionMethod

namespace Akka.Streams.Tests.Dsl
{
    public class FlowInterleaveSpec : BaseTwoStreamsSetup<int>
    {
        protected override TestSubscriber.Probe<int> Setup(IPublisher<int> p1, IPublisher<int> p2)
        {
            var subscriber = this.CreateSubscriberProbe<int>();
            Source.FromPublisher(p1)
                .Interleave(Source.FromPublisher(p2), 2)
                .RunWith(Sink.FromSubscriber(subscriber), Materializer);
            return subscriber;
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_in_the_happy_case()
        {
            this.AssertAllStagesStopped(() =>
            {
                var probe = this.CreateManualSubscriberProbe<int>();

                Source.From(Enumerable.Range(0, 4))
                    .Interleave(Source.From(Enumerable.Range(4, 3)), 2)
                    .Interleave(Source.From(Enumerable.Range(7, 5)), 3)
                    .RunWith(Sink.FromSubscriber(probe), Materializer);

                var subscription = probe.ExpectSubscription();

                var collected = new List<int>();
                for (var i = 1; i <= 12; i++)
                {
                    subscription.Request(1);
                    collected.Add(probe.ExpectNext());
                }

                collected.ShouldAllBeEquivalentTo(new[] {0, 1, 4, 7, 8, 9, 5, 2, 3, 10, 11, 6});
                probe.ExpectComplete();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_when_segmentSize_is_not_equal_elements_in_stream()
        {
            this.AssertAllStagesStopped(() =>
            {
                var probe = this.CreateManualSubscriberProbe<int>();

                Source.From(Enumerable.Range(0, 3))
                    .Interleave(Source.From(Enumerable.Range(3, 3)), 2)
                    .RunWith(Sink.FromSubscriber(probe), Materializer);

                probe.ExpectSubscription().Request(10);
                probe.ExpectNext(0, 1, 3, 4, 2, 5);
                probe.ExpectComplete();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_with_segmentSize_1()
        {
            this.AssertAllStagesStopped(() =>
            {
                var probe = this.CreateManualSubscriberProbe<int>();

                Source.From(Enumerable.Range(0, 3))
                    .Interleave(Source.From(Enumerable.Range(3, 3)), 1)
                    .RunWith(Sink.FromSubscriber(probe), Materializer);

                probe.ExpectSubscription().Request(10);
                probe.ExpectNext(0, 3, 1, 4, 2, 5);
                probe.ExpectComplete();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_not_work_with_segmentSize_0()
        {
            this.AssertAllStagesStopped(() =>
            {
                var source = Source.From(Enumerable.Range(0, 3));
                source.Invoking(s => s.Interleave(Source.From(Enumerable.Range(3, 3)), 0))
                    .ShouldThrow<ArgumentException>();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_when_segmentSize_is_greater_than_stream_elements()
        {
            this.AssertAllStagesStopped(() =>
            {
                var probe = this.CreateManualSubscriberProbe<int>();
                Source.From(Enumerable.Range(0, 3))
                    .Interleave(Source.From(Enumerable.Range(3, 13)), 10)
                    .RunWith(Sink.FromSubscriber(probe), Materializer);

                probe.ExpectSubscription().Request(25);
                Enumerable.Range(0, 16).ForEach(i => probe.ExpectNext(i));
                probe.ExpectComplete();

                var probe2 = this.CreateManualSubscriberProbe<int>();
                Source.From(Enumerable.Range(1, 20))
                    .Interleave(Source.From(Enumerable.Range(21, 5)), 10)
                    .RunWith(Sink.FromSubscriber(probe2), Materializer);

                probe2.ExpectSubscription().Request(100);
                Enumerable.Range(1, 10).ForEach(i => probe2.ExpectNext(i));
                Enumerable.Range(21, 5).ForEach(i => probe2.ExpectNext(i));
                Enumerable.Range(11, 10).ForEach(i => probe2.ExpectNext(i));
                probe2.ExpectComplete();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_with_one_immediately_completed_and_one_nonempty_publisher()
        {
            this.AssertAllStagesStopped(() =>
            {
                var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
                var subscription1 = subscriber1.ExpectSubscription();
                subscription1.Request(4);
                Enumerable.Range(1, 4).ForEach(i => subscriber1.ExpectNext(i));
                subscriber1.ExpectComplete();

                var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>());
                var subscription2 = subscriber2.ExpectSubscription();
                subscription2.Request(4);
                Enumerable.Range(1, 4).ForEach(i => subscriber2.ExpectNext(i));
                subscriber2.ExpectComplete();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_with_one_delayed_completed_and_one_nonempty_publisher()
        {
            this.AssertAllStagesStopped(() =>
            {
                var subscriber1 = Setup(SoonToCompletePublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
                var subscription1 = subscriber1.ExpectSubscription();
                subscription1.Request(4);
                Enumerable.Range(1, 4).ForEach(i => subscriber1.ExpectNext(i));
                subscriber1.ExpectComplete();

                var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToCompletePublisher<int>());
                var subscription2 = subscriber2.ExpectSubscription();
                subscription2.Request(4);
                Enumerable.Range(1, 4).ForEach(i => subscriber2.ExpectNext(i));
                subscriber2.ExpectComplete();
            }, Materializer);
        }

        [Fact]
        public void An_Interleave_for_Flow_must_work_with_one_immediately_failed_and_one_nonempty_publisher()
        {
            var subscriber1 = Setup(FailedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
            var subscription1 = subscriber1.ExpectSubscription();
            subscription1.Request(4);
            subscriber1.ExpectError().Should().Be(TestException());

            var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), FailedPublisher<int>());
            var subscription2 = subscriber2.ExpectSubscription();
            subscription2.Request(4);
            var result = subscriber2.ExpectNextOrError();

            if (result is int)
                result.Should().Be(1);
            else
            {
                result.Should().Be(TestException());
                return;
            }

            result = subscriber2.ExpectNextOrError();
            if (result is int)
                result.Should().Be(1);
            else
            {
                result.Should().Be(TestException());
                return;
            }

            subscriber2.ExpectError().Should().Be(TestException());
        }

        [Fact(Skip = "This is non-deterministic, multiple scenarios can happen")]
        public void An_Interleave_for_Flow_must_work_with_one_delayed_failed_and_one_nonempty_publisher()
        {
        }

        [Fact]
        public void An_Interleave_for_Flow_must_pass_along_early_cancellation()
        {
            this.AssertAllStagesStopped(() =>
            {
                var up1 = this.CreateManualPublisherProbe<int>();
                var up2 = this.CreateManualPublisherProbe<int>();
                var down = this.CreateManualSubscriberProbe<int>();

                var t = Source.AsSubscriber<int>()
                    .InterleaveMaterialized(Source.AsSubscriber<int>(), 2, ValueTuple.Create)
                    .ToMaterialized(Sink.FromSubscriber(down), Keep.Left)
                    .Run(Materializer);
                var graphSubscriber1 = t.Item1;
                var graphSubscriber2 = t.Item2;

                var downstream = down.ExpectSubscription();
                downstream.Cancel();
                up1.Subscribe(graphSubscriber1);
                up2.Subscribe(graphSubscriber2);
                up1.ExpectSubscription().ExpectCancellation();
                up2.ExpectSubscription().ExpectCancellation();
            }, Materializer);
        }
    }
}


text:
package bt.torrent.selector;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * A class that has shuffle utility functions
 */
public class ShuffleUtils {

    public static void shuffle(int[] arr) {
        shuffle(arr, ThreadLocalRandom.current());
    }

    /**
     * Shuffle the passed in int array in-place with the specified Random
     *
     * @param arr the array to shuffle
     * @param rnd the instance of random to use
     */
    public static void shuffle(int[] arr, Random rnd) {
        for (int k = arr.length - 1; k > 0; k--) {
            int i = rnd.nextInt(k + 1);
            int a = arr[i];
            arr[i] = arr[k];
            arr[k] = a;
        }
    }
}


text:
var Router = require("gourdian");

exports.router_accurately_determines_if_http_or_socket_server_is_needed = function(test) {
  var router = new Gourdian.Router();

  router.routes = null;
  test.ok(!router.need_socket_server);
  test.ok(!router.need_http_server);

  router.routes = {};
  test.ok(!router.need_http_server);
  test.ok(!router.need_socket_server);

  router.routes = { http: [ { something: 1 } ]};
  test.ok(router.need_http_server);
  test.ok(!router.need_socket_server);

  router.routes = { socket: [ { something: 1 } ]};
  test.ok(!router.need_http_server);
  test.ok(router.need_socket_server);

  router.routes = { socket: [ { something: 1 } ] , http: [ { something: 1 } ] };
  test.ok(router.need_http_server);
  test.ok(router.need_socket_server);

  test.done();
}

exports.root_file_is_accurate = function(test) {
  var router = new Gourdian.Router();

  router.routes = null;
  test.ok(!router.root);

  test.done();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.maxcriser.hw_activities">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".ZeroActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">
        </activity>
        <activity android:name=".FirstActivity">
        </activity>
        <activity android:name=".SecondActivity">
        </activity>
        <activity android:name=".ThirdActivity">
        </activity>
        <activity android:name=".FourthActivity">
        </activity>
        <activity android:name=".FifthActivity">
        </activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>


text:
#import "JNWTestImplementation.h"

NSInteger const kTestDataSourceNumberOfItems = 20;
NSInteger const kTestDataSourceNumberOfSections = 3;
NSString * const kTestDataSourceCellIdentifier = @"cell";
NSString * const kTestDataSourceHeaderIdentifier = @"header";
NSString * const kTestDataSourceFooterIdentifier = @"footer";

@implementation JNWTestDataSource

- (NSUInteger)collectionView:(JNWCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return kTestDataSourceNumberOfItems;
}

- (JNWCollectionViewCell *)collectionView:(JNWCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	JNWCollectionViewCell *cell = [collectionView dequeueReusableCellWithIdentifier:kTestDataSourceCellIdentifier];
	return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(JNWCollectionView *)collectionView {
	return kTestDataSourceNumberOfSections;
}

- (JNWCollectionViewReusableView *)collectionView:(JNWCollectionView *)collectionView viewForSupplementaryViewOfKind:(NSString *)kind inSection:(NSInteger)section {
	if ([kind isEqualToString:JNWCollectionViewListLayoutHeaderKind]) {
		JNWCollectionViewReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifer:kTestDataSourceHeaderIdentifier];
		return header;
	} else {
		JNWCollectionViewReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifer:kTestDataSourceFooterIdentifier];
		return footer;
	}
}

@end

@implementation JNWTestDelegate

@end

@implementation JNWTestListLayoutDelegate

@end

@implementation JNWTestGridLayoutDelegate

@end


text:
<?php

namespace actsmart\actsmart\Sensors\Slack\Events;

use actsmart\actsmart\Sensors\UtteranceEvent;
use actsmart\actsmart\Utils\RegularExpressionHelper;
use actsmart\actsmart\Utils\Literals;
use Ds\Map;

class SlackMessageActionEvent extends SlackEvent implements UtteranceEvent
{
    use RegularExpressionHelper;

    const EVENT_NAME = 'event.slack.messageaction';

    private $workspace_id;

    private $channel_id;

    private $channel_name;

    private $callback_id;

    private $response_url;

    private $team_domain;

    private $text;

    private $token;

    private $trigger_id;

    private $user_id;

    private $username;

    public function __construct($subject, $arguments = [])
    {
        parent::__construct($subject, $arguments);
        $this->workspace_id = $subject->team->id ?? null;
        $this->channel_id = $subject->channel->id ?? null;
        $this->channel_name = $subject->chanel->name ?? null;
        $this->callback_id = $subject->callback_id ?? null;
        $this->response_url = $subject->response_url ?? null;
        $this->team_domain =  $subject->team->domain ?? null;
        $this->text = $subject->message->text ?? null;
        $this->token = $subject->token ?? null;
        $this->trigger_id = $subject->trigger_id ?? null;
        $this->user_id = $subject->user->id ?? null;
        $this->username = $subject->user->name ?? null;
    }

    public function getKey()
    {
        return SELF::EVENT_NAME;
    }

    public function getUtterance() : Map
    {
        /* @var \Ds\Map */
        $utterance = new Map();
        $utterance->put(Literals::TYPE, Literals::SLACK_MESSAGE_ACTION);
        $utterance->put(Literals::TEXT, '');
        $utterance->put(Literals::WORKSPACE_ID, $this->getWorkspaceId());
        $utterance->put(Literals::USER_ID, $this->getUserId());
        $utterance->put(Literals::CHANNEL_ID, $this->getChannelId());
        $utterance->put(Literals::TIMESTAMP, $this->getTimestamp());
        $utterance->put(Literals::CALLBACK_ID, $this->getCallbackId());
        $utterance->put(Literals::TOKEN, $this->getToken());
        $utterance->put(Literals::TRIGGER_ID, $this->getTriggerId());
        return $utterance;
    }

    /**
     * @return string | null
     */
    public function getWorkspaceId()
    {
        return $this->workspace_id;
    }

    /**
     * @return string | null
     */
    public function getChannelId()
    {
        return $this->channel_id;
    }

    /**
     * @return string | null
     */
    public function getChannelName()
    {
        return $this->channel_name;
    }

    /**
     * @return string | null
     */
    public function getCallbackId()
    {
        return $this->callback_id;
    }

    /**
     * @return string | null
     */
    public function getResponseUrl()
    {
        return $this->response_url;
    }

    /**
     * @return string | null
     */
    public function getTeamDomain()
    {
        return $this->team_domain;
    }

    /**
     * @return string | null
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * @return string | null
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @return string | null
     */
    public function getTriggerId()
    {
        return $this->trigger_id;
    }

    /**
     * @return string | null
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    /**
     * @return string | null
     */
    public function getUserName()
    {
        return $this->username;
    }

    /**
     * Returns the time the command was called.
     *
     * @return int
     */
    public function getTimestamp()
    {
        return time();
    }
}


text:
<?php

namespace Sylius\Behat\Page\Admin\ShippingMethod;

use Behat\Mink\Session;
use Sylius\Behat\Page\SymfonyPage;
use Sylius\Behat\TableManipulatorInterface;
use Symfony\Component\Routing\RouterInterface;

/**
 * @author Jan Góralski <jan.goralski@lakion.com>
 */
class IndexPage extends SymfonyPage implements IndexPageInterface
{
    /**
     * @var TableManipulatorInterface
     */
    private $tableManipulator;

    /**
     * {@inheritdoc}
     *
     * @param TableManipulatorInterface $tableManipulator
     */
    public function __construct(
        Session $session,
        array $parameters,
        RouterInterface $router,
        TableManipulatorInterface $tableManipulator
    ) {
        parent::__construct($session, $parameters, $router);

        $this->tableManipulator = $tableManipulator;
    }

    /**
     * {@inheritdoc}
     */
    public function isThereShippingMethodNamed($name)
    {
        if (null === $table = $this->getDocument()->find('css', 'table')) {
            return false;
        }

        try {
            $row = $this->tableManipulator->getRowWithFields($table, ['name' => $name]);
        } catch (\InvalidArgumentException $exception) {
            return false;
        }

        return 1 === $row;
    }

    /**
     * {@inheritdoc}
     */
    protected function getRouteName()
    {
        return 'sylius_backend_shipping_method_index';
    }
}


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../fixtures/classes', __FILE__)

describe "SimpleDelegator.new" do
  before :all do
    @simple = DelegateSpecs::Simple.new
    @delegate = SimpleDelegator.new(@simple)
  end

  it "forwards public method calls" do
    @delegate.pub.should == :foo
  end

  it "forwards protected method calls" do
    lambda{ @delegate.prot }.should raise_error( NoMethodError )
  end

  it "doesn't forward private method calls" do
    lambda{ @delegate.priv }.should raise_error( NoMethodError )
  end

  it "doesn't forward private method calls even via send or __send__" do
    lambda{ @delegate.send(:priv, 42)     }.should raise_error( NoMethodError )
    lambda{ @delegate.__send__(:priv, 42) }.should raise_error( NoMethodError )
  end
end


text:
Hi, my name is Christoph Wanders

I make thing for the Web w/ Ruby, Javascript and

        <input type="submit" value="Blog">
        <input type="submit" value="Work">


text:
const
  http = require('http'),
  log = require('../utils/log'),
  requestEvent = require('./events/on-request'),
  env = process.env;

let server = http.createServer(function (req, res) {
  log.info('server > createServer');
  requestEvent.trigger(req, res);
});

server.listen(env.NODE_PORT || 3000, env.NODE_IP || 'localhost', function () {
  console.log(`worker ${process.pid} started...`);
});