text:
using System;
using System.Linq;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Shipping;
using Nop.Tests;
using NUnit.Framework;

namespace Nop.Data.Tests.Shipping
{
    [TestFixture]
    public class ShipmentPersistenceTests : PersistenceTest
    {
        [Test]
        public void Can_save_and_load_shipment()
        {
            var shipment = new Shipment
            {
                Order = GetTestOrder(),
                TrackingNumber = "TrackingNumber 1",
                TotalWeight = 9.87M,
                ShippedDateUtc = new DateTime(2010, 01, 01),
                DeliveryDateUtc = new DateTime(2010, 01, 02),
                AdminComment = "AdminComment 1",
                CreatedOnUtc = new DateTime(2010, 01, 03),
            };

            var fromDb = SaveAndLoadEntity(shipment);
            fromDb.ShouldNotBeNull();
            fromDb.TrackingNumber.ShouldEqual("TrackingNumber 1");
            fromDb.TotalWeight.ShouldEqual(9.87M);
            fromDb.ShippedDateUtc.ShouldEqual(new DateTime(2010, 01, 01));
            fromDb.DeliveryDateUtc.ShouldEqual(new DateTime(2010, 01, 02));
            fromDb.AdminComment.ShouldEqual("AdminComment 1");
            fromDb.CreatedOnUtc.ShouldEqual(new DateTime(2010, 01, 03));
        }

        [Test]
        public void Can_save_and_load_shipment_with_items()
        {
            var shipment = new Shipment
            {
                Order = GetTestOrder(),
                TrackingNumber = "TrackingNumber 1",
                ShippedDateUtc = new DateTime(2010, 01, 01),
                DeliveryDateUtc = new DateTime(2010, 01, 02),
                CreatedOnUtc = new DateTime(2010, 01, 03),
            };
            shipment.ShipmentItems.Add(new ShipmentItem
            {
                OrderItemId = 1,
                Quantity = 2,
            });

            var fromDb = SaveAndLoadEntity(shipment);
            fromDb.ShouldNotBeNull();

            fromDb.ShipmentItems.ShouldNotBeNull();
            (fromDb.ShipmentItems.Count == 1).ShouldBeTrue();
            fromDb.ShipmentItems.First().Quantity.ShouldEqual(2);
        }

        protected Customer GetTestCustomer()
        {
            return new Customer
            {
                CustomerGuid = Guid.NewGuid(),
                AdminComment = "some comment here",
                Active = true,
                Deleted = false,
                CreatedOnUtc = new DateTime(2010, 01, 01),
                LastActivityDateUtc = new DateTime(2010, 01, 02)
            };
        }

        protected Order GetTestOrder()
        {
            return new Order
            {
                OrderGuid = Guid.NewGuid(),
                Customer = GetTestCustomer(),
                BillingAddress = new Address
                {
                    Country = new Country
                    {
                        Name = "United States",
                        TwoLetterIsoCode = "US",
                        ThreeLetterIsoCode = "USA",
                    },
                    CreatedOnUtc = new DateTime(2010, 01, 01),
                },
                Deleted = true,
                CreatedOnUtc = new DateTime(2010, 05, 06)
            };
        }
    }
}


text:
'use strict';

angular.module('authAdminPanel')
  .controller('MainController', ['$scope', '$state', 'UserIdentityService', function ($scope, $state, UserIdentityService) {

      var vm = this;
      UserIdentityService.getUser().then(function (data) {
          $scope.currentUser.userName = data.username;
          if (data.organizationId < 1){
              $state.go("index.organization_new");
              return;
          }
          $scope.currentUser.organizationId = data.organizationId;
          $scope.currentUser.organizationName = data.organizationName;
          vm.helloText = 'Welcome in Admin Auth Panel';
          vm.descriptionText = 'This is a Angular web-app';
      }, function () {
          $scope.error = 'unable to retrieve the user';
      });

      function setCurrentOrganization(id, name) {
          vm.organizationId = id;
          vm.organizationName = name;
      }
  }]);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150331185117 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE users ADD instagram_id VARCHAR(64) DEFAULT NULL');
        $this->addSql('ALTER TABLE users ADD activated TINYINT(1) DEFAULT \'1\' NOT NULL, ADD activation_token VARCHAR(64) DEFAULT NULL');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE users DROP activated, DROP activation_token');
        $this->addSql('ALTER TABLE users DROP instagram_id');
    }
}


text:
<?php declare(strict_types=1);

namespace Wnx\LaravelStats\Tests\Classifiers;

use Wnx\LaravelStats\Classifiers\ObserverClassifier;
use Wnx\LaravelStats\Tests\Stubs\Models\User;
use Wnx\LaravelStats\Tests\Stubs\Observers\UserObserver;
use Wnx\LaravelStats\Tests\TestCase;
use Wnx\LaravelStats\ReflectionClass;

class ObserverClassifierTest extends TestCase
{

    /** @test */
    public function it_returns_true_if_given_class_is_a_registered_observer()
    {
        User::observe(UserObserver::class);

        $this->assertTrue(
            (new ObserverClassifier())->satisfies(
                new ReflectionClass(UserObserver::class)
            )
        );
    }
}


text:
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(UIPlayAnimation))]
public class UIPlayAnimationEditor : Editor
{
	enum ResetOnPlay
	{
		ContinueFromCurrent,
		RestartAnimation,
	}

	enum SelectedObject
	{
		KeepCurrent,
		SetToNothing,
	}

	public override void OnInspectorGUI ()
	{
		NGUIEditorTools.SetLabelWidth(120f);
		UIPlayAnimation pa = target as UIPlayAnimation;
		GUILayout.Space(6f);

		GUI.changed = false;

		EditorGUI.BeginDisabledGroup(pa.target);
		Animator animator = (Animator)EditorGUILayout.ObjectField("Animator", pa.animator, typeof(Animator), true);
		EditorGUI.EndDisabledGroup();
		EditorGUI.BeginDisabledGroup(pa.animator);
		Animation anim = (Animation)EditorGUILayout.ObjectField("Animation", pa.target, typeof(Animation), true);

		EditorGUI.EndDisabledGroup();
		EditorGUI.BeginDisabledGroup(anim == null && animator == null);
		string clipName = EditorGUILayout.TextField("State Name", pa.clipName);

		AnimationOrTween.Trigger trigger = (AnimationOrTween.Trigger)EditorGUILayout.EnumPopup("Trigger condition", pa.trigger);

		EditorGUI.BeginDisabledGroup(animator != null && !string.IsNullOrEmpty(clipName));
		AnimationOrTween.Direction dir = (AnimationOrTween.Direction)EditorGUILayout.EnumPopup("Play direction", pa.playDirection);
		EditorGUI.EndDisabledGroup();

		SelectedObject so = pa.clearSelection ? SelectedObject.SetToNothing : SelectedObject.KeepCurrent;
		bool clear = (SelectedObject)EditorGUILayout.EnumPopup("Selected object", so) == SelectedObject.SetToNothing;
		AnimationOrTween.EnableCondition enab = (AnimationOrTween.EnableCondition)EditorGUILayout.EnumPopup("If disabled on start", pa.ifDisabledOnPlay);
		ResetOnPlay rs = pa.resetOnPlay ? ResetOnPlay.RestartAnimation : ResetOnPlay.ContinueFromCurrent;
		bool reset = (ResetOnPlay)EditorGUILayout.EnumPopup("On activation", rs) == ResetOnPlay.RestartAnimation;
		AnimationOrTween.DisableCondition dis = (AnimationOrTween.DisableCondition)EditorGUILayout.EnumPopup("When finished", pa.disableWhenFinished);
		EditorGUI.EndDisabledGroup();

		if (GUI.changed)
		{
			NGUIEditorTools.RegisterUndo("PlayAnimation Change", pa);
			pa.target = anim;
			pa.animator = animator;
			pa.clipName = clipName;
			pa.trigger = trigger;
			pa.playDirection = dir;
			pa.clearSelection = clear;
			pa.ifDisabledOnPlay = enab;
			pa.resetOnPlay = reset;
			pa.disableWhenFinished = dis;
			NGUITools.SetDirty(pa);
		}

		NGUIEditorTools.SetLabelWidth(80f);
		NGUIEditorTools.DrawEvents("On Finished", pa, pa.onFinished);
	}
}


text:
					Rapor Penilaian Keseluruhan

				<form action="#" method="post" class="form-horizontal">

						Periode

							<select name="periode" id="periode" class="form-control" onchange="set()">
								<option value="">-- Pilih Periode --</option>
								<?php
									foreach ($periode as $periode) {
										echo "<option value='".$periode->ID_PERIODE2."'>".ucfirst(strtolower($periode->NAMA_PERIODE))."</option>";
									}
								?>
							</select>

						Outlet

							<select name="outlet" id="outlet" class="form-control" onchange="cek()">
								<option value="">-- Pilih Outlet --</option>
								<?php
									foreach ($outlet as $outlet) {
										echo "<option value='".$outlet->ID_OUTLET."'>".ucfirst(strtolower($outlet->NAMA_OUTLET))."</option>";
									}
								?>
							</select>

							<button type="submit" class="btn blue" name="submit">Lihat Laporan</button>

				</form>


text:
#include "stdafx.h"

#include "../xapo/ParameterizedProcessor.h"

#include "EffectDescriptor.h"

const IID IID_CXAPOBase = __uuidof(IXAPO);

using namespace SlimDX::XAPO;

namespace SlimDX
{
namespace XAudio2
{
	XAUDIO2_EFFECT_DESCRIPTOR EffectDescriptor::ToUnmanaged()
	{
		XAUDIO2_EFFECT_DESCRIPTOR desc;
		desc.InitialState = InitiallyStarted;
		desc.OutputChannels = OutputChannelCount;

		ParameterizedProcessor^ pp = dynamic_cast<ParameterizedProcessor^>(Effect);
		if (pp != nullptr)
			desc.pEffect = static_cast<IXAPOParameters*>(pp->ParamPointer);
		else
		{
			BaseProcessor^ bp = dynamic_cast<BaseProcessor^>(Effect);
			if (bp != nullptr)
				desc.pEffect = bp->ImplPointer;
			else
			{
				shim = new XAPOShim(Effect);
				desc.pEffect = static_cast<IXAPOParameters*>(shim);
			}
		}

		return desc;
	}

	void EffectDescriptor::Free()
	{
		if (shim != NULL)
			shim->Release();
		shim = NULL;
	}
}
}


text:
namespace llvm {
struct ExportedSymbol {
  llvm::MachO::SymbolKind Kind;
  std::string Name;
  bool WeakDefined;
  bool ThreadLocalValue;
};

using ExportedSymbolSeq = std::vector<ExportedSymbol>;
using UUIDs = std::vector<std::pair<llvm::MachO::Target, std::string>>;

inline bool operator<(const ExportedSymbol &LHS, const ExportedSymbol &RHS) {
  return std::tie(LHS.Kind, LHS.Name) < std::tie(RHS.Kind, RHS.Name);
}

inline bool operator==(const ExportedSymbol &LHS, const ExportedSymbol &RHS) {
  return std::tie(LHS.Kind, LHS.Name, LHS.WeakDefined, LHS.ThreadLocalValue) ==
         std::tie(RHS.Kind, RHS.Name, RHS.WeakDefined, RHS.ThreadLocalValue);
}

inline std::string stripWhitespace(std::string S) {
  S.erase(std::remove_if(S.begin(), S.end(), ::isspace), S.end());
  return S;
}
} // namespace llvm
#endif


text:
NAMESPACE_XBOX_HTTP_CLIENT_TEST_BEGIN

TEST_MODULE_INITIALIZE(ModuleInitialize)
{
    Logger::WriteMessage("Started unit test");
}

TEST_MODULE_CLEANUP(ModuleCleanup)
{
    Logger::WriteMessage("Stopped unit test");
}

std::wstring FormatString(LPCWSTR strMsg, ...)
{
    WCHAR strBuffer[2048];

    va_list args;
    va_start(args, strMsg);
    StringCchVPrintfW(strBuffer, 2048, strMsg, args);
    strBuffer[2047] = L'\0';

    va_end(args);

    return std::wstring(strBuffer);
}

NAMESPACE_XBOX_HTTP_CLIENT_TEST_END


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
play.libs.ws (Play! API)
</TITLE>

<META NAME="date" CONTENT="2010-11-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

play.libs.ws

Classes

WSAsync

WSAsync.HttpAsyncResponse

WSUrlFetch

WSUrlFetch.HttpUrlfetchResponse


text:
<?xml version="1.0" encoding="UTF-8" ?>
<pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel" version="11.1.2.64.36" id="openBugsAssignedtoMePageDef"
                Package="mybugdb.mobile.pageDefs">
  <parameters/>
  <executables>
    <variableIterator id="variables"/>
    <iterator Binds="root" RangeSize="25" DataControl="managerBean" id="managerBeanIterator"/>
    <accessorIterator MasterBinding="managerBeanIterator" Binds="assignedBug" RangeSize="25" DataControl="managerBean"
                      BeanClass="java.lang.String" id="assignedBugIterator"/>
  </executables>
  <bindings>
    <tree IterBinding="assignedBugIterator" id="assignedBug">
      <nodeDefinition Name="assignedBug0">
        <AttrNames>
          <Item Value="element"/>
        </AttrNames>
      </nodeDefinition>
    </tree>
    <tree IterBinding="assignedBugIterator" id="assignedBug1">
      <nodeDefinition DefName="mybugdb.mobile.Bug" Name="assignedBug10">
        <AttrNames>
          <Item Value="bugNumber"/>
          <Item Value="text"/>
        </AttrNames>
      </nodeDefinition>
    </tree>
    <tree IterBinding="assignedBugIterator" id="assignedBug2">
      <nodeDefinition DefName="mybugdb.mobile.Bug" Name="assignedBug20">
        <AttrNames>
          <Item Value="bugNumber"/>
          <Item Value="text"/>
        </AttrNames>
      </nodeDefinition>
    </tree>
    <tree IterBinding="assignedBugIterator" id="assignedBug3">
      <nodeDefinition DefName="mybugdb.mobile.Bug" Name="assignedBug30">
        <AttrNames>
          <Item Value="bugNumber"/>
          <Item Value="text"/>
        </AttrNames>
      </nodeDefinition>
    </tree>
  </bindings>
</pageDefinition>


text:
package app

import (
	"fmt"
	"strings"

	"github.com/Sirupsen/logrus"
	"github.com/urfave/cli"

	// install kubernetes api
	_ "k8s.io/kubernetes/pkg/api/install"
	_ "k8s.io/kubernetes/pkg/apis/extensions/install"

	// install OpenShift api
	_ "github.com/openshift/origin/pkg/deploy/api/install"
	_ "github.com/openshift/origin/pkg/image/api/install"

	"github.com/kubernetes-incubator/kompose/pkg/kobject"
	"github.com/kubernetes-incubator/kompose/pkg/loader"
	"github.com/kubernetes-incubator/kompose/pkg/transformer"
	"github.com/kubernetes-incubator/kompose/pkg/transformer/kubernetes"
	"github.com/kubernetes-incubator/kompose/pkg/transformer/openshift"
)

const (
	DefaultComposeFile = "docker-compose.yml"
	DefaultProvider    = "kubernetes"
)

var inputFormat = "compose"

func validateFlags(c *cli.Context, opt *kobject.ConvertOptions) {

	if opt.OutFile == "-" {
		opt.ToStdout = true
		opt.OutFile = ""
	}

	if len(opt.OutFile) != 0 && opt.ToStdout {
		logrus.Fatalf("Error: --out and --stdout can't be set at the same time")
	}

	if opt.CreateChart && opt.ToStdout {
		logrus.Fatalf("Error: chart cannot be generated when --stdout is specified")
	}

	if opt.Replicas < 0 {
		logrus.Fatalf("Error: --replicas cannot be negative")
	}

	dabFile := c.GlobalString("bundle")

	if len(dabFile) > 0 {
		inputFormat = "bundle"
		opt.InputFile = dabFile
	}

	if len(dabFile) > 0 && c.GlobalIsSet("file") {
		logrus.Fatalf("Error: 'compose' file and 'dab' file cannot be specified at the same time")
	}

	if len(c.Args()) != 0 {
		logrus.Fatal("Unknown Argument(s): ", strings.Join(c.Args(), ","))
	}
}

func validateControllers(opt *kobject.ConvertOptions) {

	singleOutput := len(opt.OutFile) != 0 || opt.OutFile == "-" || opt.ToStdout

	if opt.Provider == "kubernetes" {
		// create deployment by default if no controller has been set
		if !opt.CreateD && !opt.CreateDS && !opt.CreateRC {
			opt.CreateD = true
		}
		if singleOutput {
			count := 0
			if opt.CreateD {
				count++
			}
			if opt.CreateDS {
				count++
			}
			if opt.CreateRC {
				count++
			}
			if count > 1 {
				logrus.Fatalf("Error: only one kind of Kubernetes resource can be generated when --out or --stdout is specified")
			}
		}

	} else if opt.Provider == "openshift" {
		// create deploymentconfig by default if no controller has been set
		if !opt.CreateDeploymentConfig {
			opt.CreateDeploymentConfig = true
		}
		if singleOutput {
			count := 0
			if opt.CreateDeploymentConfig {
				count++
			}
			// Add more controllers here once they are available in OpenShift
			// if opt.foo {count++}

			if count > 1 {
				logrus.Fatalf("Error: only one kind of OpenShift resource can be generated when --out or --stdout is specified")
			}
		}
	}
}

// Convert transforms docker compose or dab file to k8s objects
func Convert(c *cli.Context) {
	opt := kobject.ConvertOptions{
		ToStdout:               c.BoolT("stdout"),
		CreateChart:            c.BoolT("chart"),
		GenerateYaml:           c.BoolT("yaml"),
		Replicas:               c.Int("replicas"),
		InputFile:              c.GlobalString("file"),
		OutFile:                c.String("out"),
		Provider:               strings.ToLower(c.GlobalString("provider")),
		CreateD:                c.BoolT("deployment"),
		CreateDS:               c.BoolT("daemonset"),
		CreateRC:               c.BoolT("replicationcontroller"),
		CreateDeploymentConfig: c.BoolT("deploymentconfig"),
		EmptyVols:              c.BoolT("emptyvols"),
	}

	validateFlags(c, &opt)
	validateControllers(&opt)

	// loader parses input from file into komposeObject.
	l, err := loader.GetLoader(inputFormat)
	if err != nil {
		logrus.Fatal(err)
	}

	komposeObject := kobject.KomposeObject{
		ServiceConfigs: make(map[string]kobject.ServiceConfig),
	}
	komposeObject = l.LoadFile(opt.InputFile)

	// Get a transformer that maps komposeObject to provider's primitives
	t := getTransformer(opt)

	// Do the transformation
	objects := t.Transform(komposeObject, opt)

	// Print output
	kubernetes.PrintList(objects, opt)
}

// Up brings up deployment, svc.
func Up(c *cli.Context) {
	opt := kobject.ConvertOptions{
		InputFile: c.GlobalString("file"),
		Replicas:  1,
		Provider:  strings.ToLower(c.GlobalString("provider")),
		EmptyVols: c.BoolT("emptyvols"),
	}
	validateFlags(c, &opt)
	validateControllers(&opt)

	// loader parses input from file into komposeObject.
	l, err := loader.GetLoader(inputFormat)
	if err != nil {
		logrus.Fatal(err)
	}

	komposeObject := kobject.KomposeObject{
		ServiceConfigs: make(map[string]kobject.ServiceConfig),
	}
	komposeObject = l.LoadFile(opt.InputFile)

	// Get the transformer
	t := getTransformer(opt)

	//Submit objects to provider
	errDeploy := t.Deploy(komposeObject, opt)
	if errDeploy != nil {
		logrus.Fatalf("Error while deploying application: %s", errDeploy)
	}
}

// Down deletes all deployment, svc.
func Down(c *cli.Context) {
	opt := kobject.ConvertOptions{
		InputFile: c.GlobalString("file"),
		Replicas:  1,
		Provider:  strings.ToLower(c.GlobalString("provider")),
		EmptyVols: c.BoolT("emptyvols"),
	}
	validateFlags(c, &opt)
	validateControllers(&opt)

	// loader parses input from file into komposeObject.
	l, err := loader.GetLoader(inputFormat)
	if err != nil {
		logrus.Fatal(err)
	}

	komposeObject := kobject.KomposeObject{
		ServiceConfigs: make(map[string]kobject.ServiceConfig),
	}
	komposeObject = l.LoadFile(opt.InputFile)

	// Get the transformer
	t := getTransformer(opt)

	//Remove deployed application
	errUndeploy := t.Undeploy(komposeObject, opt)
	if errUndeploy != nil {
		logrus.Fatalf("Error while deleting application: %s", errUndeploy)
	}

}

// Convenience method to return the appropriate Transformer based on
// what provider we are using.
func getTransformer(opt kobject.ConvertOptions) transformer.Transformer {
	var t transformer.Transformer
	if opt.Provider == "kubernetes" {
		// Create/Init new Kubernetes object with CLI opts
		t = &kubernetes.Kubernetes{Opt: opt}
	} else {
		// Create/Init new OpenShift object that is initialized with a newly
		// created Kubernetes object. Openshift inherits from Kubernetes
		t = &openshift.OpenShift{Kubernetes: kubernetes.Kubernetes{Opt: opt}}
	}
	return t
}

func askForConfirmation() bool {
	var response string
	_, err := fmt.Scanln(&response)
	if err != nil {
		logrus.Fatal(err)
	}
	if response == "yes" {
		return true
	} else if response == "no" {
		return false
	} else {
		fmt.Println("Please type yes or no and then press enter:")
		return askForConfirmation()
	}
}


text:
package http

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"go-common/app/infra/config/model"
	"go-common/library/ecode"
	"go-common/library/log"
	bm "go-common/library/net/http/blademaster"
)

// versions client versions which the configuration is complete
func versions2(c *bm.Context) {
	var (
		err   error
		svr   string
		data  *model.Versions
		bver  string
		token string
		env   string
		zone  string
	)
	query := c.Request.URL.Query()
	// params
	svr = query.Get("service")
	if svr == "" {
		token = query.Get("token")
		zone = query.Get("zone")
		env = query.Get("env")
		if zone == "" || env == "" || token == "" {
			c.JSON(nil, ecode.RequestErr)
			return
		}
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	if bver = query.Get("build"); bver == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	if data, err = confSvc2.VersionSuccess(c, svr, bver); err != nil {
		c.JSON(nil, err)
		return
	}
	c.JSON(data, nil)
}

// config get config file
func config2(c *bm.Context) {
	var (
		err      error
		svr      string
		buildVer string
		version  int64
		token    string
		ids      []int64
		zone     string
		env      string
	)
	query := c.Request.URL.Query()
	// params
	if token = query.Get("token"); token == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	svr = query.Get("service")
	if svr == "" {
		zone = query.Get("zone")
		env = query.Get("env")
		if zone == "" || env == "" || token == "" {
			c.JSON(nil, ecode.RequestErr)
			return
		}
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	if buildVer = query.Get("build"); buildVer == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	if version, err = strconv.ParseInt(query.Get("version"), 10, 64); err != nil {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	if idsStr := query.Get("ids"); len(idsStr) != 0 {
		if err = json.Unmarshal([]byte(query.Get("ids")), &ids); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	data, err := confSvc2.Config(c, svr, token, version, ids)
	if err != nil {
		c.JSON(nil, err)
		return
	}
	c.JSON(data, nil)
}

// file get one file value
func file2(c *bm.Context) {
	var (
		err      error
		svr      string
		buildVer string
		token    string
		file     string
		ver      int64
		treeID   string
		env      string
		zone     string
		data     string
	)

	query := c.Request.URL.Query()
	// params
	if verStr := query.Get("version"); verStr == "" {
		ver = model.UnknownVersion
	} else {
		if ver, err = strconv.ParseInt(verStr, 10, 64); err != nil {
			data = "version must be num"
		}
	}
	if env = query.Get("env"); env == "" {
		data = "env is null"
	}
	if zone = query.Get("zone"); zone == "" {
		data = "zone is null"
	}
	if token = query.Get("token"); token == "" {
		data = "token is null"
	}
	if treeID = query.Get("treeid"); treeID == "" {
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			data = "appid is null"
		}
	} else {
		svr = fmt.Sprintf("%s_%s_%s", treeID, env, zone)
	}
	if buildVer = query.Get("build"); buildVer == "" {
		data = "build is null"
	}
	if file = query.Get("fileName"); file == "" {
		data = "fileName is null"
	}
	service := &model.Service{Name: svr, BuildVersion: buildVer, File: file, Token: token, Version: ver}
	if data == "" {
		if data, err = confSvc2.File(c, service); err != nil {
			data = err.Error()
			c.AbortWithStatus(http.StatusInternalServerError)
		}
	} else {
		c.AbortWithStatus(http.StatusBadRequest)
	}
	if _, err = c.Writer.Write([]byte(data)); err != nil {
		log.Error("Response().Write(%v) error(%v)", data, err)
	}
}

// check check config version
func check2(c *bm.Context) {
	var (
		err      error
		svr      string
		host     string
		buildVer string
		ip       string
		ver      int64
		token    string
		appoint  int64
		zone     string
		env      string
		query    = c.Request.URL.Query()
	)
	// params
	if token = query.Get("token"); token == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	svr = query.Get("service")
	if svr == "" {
		zone = query.Get("zone")
		env = query.Get("env")
		if zone == "" || env == "" || token == "" {
			c.JSON(nil, ecode.RequestErr)
			return
		}
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	if ip = query.Get("ip"); ip == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	if host = query.Get("hostname"); host == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	if buildVer = query.Get("build"); buildVer == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	if ver, err = strconv.ParseInt(query.Get("version"), 10, 64); err != nil {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	appoint, _ = strconv.ParseInt(query.Get("appoint"), 10, 64)
	// check config version
	rhost := &model.Host{Service: svr, Name: host, BuildVersion: buildVer, IP: ip, ConfigVersion: ver, Appoint: appoint, Customize: query.Get("customize")}
	evt, err := confSvc2.CheckVersion(c, rhost, token)
	if err != nil {
		c.JSON(nil, err)
		return
	}
	// wait for version change
	select {
	case e := <-evt:
		c.JSON(e, nil)
	case <-time.After(time.Duration(cnf.PollTimeout)):
		c.JSON(nil, ecode.NotModified)
	case <-c.Writer.(http.CloseNotifier).CloseNotify():
		c.JSON(nil, ecode.NotModified)
	}
	confSvc2.Unsub(svr, host)
}

//clear  host in redis
func clearhost2(c *bm.Context) {
	var (
		svr   string
		zone  string
		env   string
		token string
		err   error
	)
	query := c.Request.Form
	svr = query.Get("service")
	if svr == "" {
		token = query.Get("token")
		zone = query.Get("zone")
		env = query.Get("env")
		if zone == "" || env == "" || token == "" {
			c.JSON(nil, ecode.RequestErr)
			return
		}
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	c.JSON(nil, confSvc2.ClearHost(c, svr))
}

// versions client versions which the configuration is complete
func builds2(c *bm.Context) {
	var (
		err   error
		svr   string
		data  []string
		token string
		env   string
		zone  string
	)
	query := c.Request.URL.Query()
	// params
	svr = query.Get("service")
	if svr == "" {
		token = query.Get("token")
		zone = query.Get("zone")
		env = query.Get("env")
		if zone == "" || env == "" || token == "" {
			c.JSON(nil, ecode.RequestErr)
			return
		}
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	if data, err = confSvc2.Builds(c, svr); err != nil {
		c.JSON(nil, err)
		return
	}
	c.JSON(data, nil)
}

// config get config file
func latest(c *bm.Context) {
	var (
		err      error
		svr      string
		buildVer string
		version  int64
		token    string
		ids      []int64
		zone     string
		env      string
		verStr   string
	)
	query := c.Request.URL.Query()
	// params
	if token = query.Get("token"); token == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	svr = query.Get("service")
	if svr == "" {
		zone = query.Get("zone")
		env = query.Get("env")
		if zone == "" || env == "" || token == "" {
			c.JSON(nil, ecode.RequestErr)
			return
		}
		if svr, err = confSvc2.AppService(zone, env, token); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	}
	if buildVer = query.Get("build"); buildVer == "" {
		c.JSON(nil, ecode.RequestErr)
		return
	}
	verStr = query.Get("version")
	if len(verStr) > 0 {
		if version, err = strconv.ParseInt(verStr, 10, 64); err != nil {
			c.JSON(nil, ecode.RequestErr)
			return
		}
	} else {
		rhost := &model.Host{Service: svr, BuildVersion: buildVer}
		version, err = confSvc2.CheckLatest(c, rhost, token)
		if err != nil {
			c.JSON(nil, err)
			return
		}
	}
	data, err := confSvc2.ConfigCheck(c, svr, token, version, ids)
	if err != nil {
		c.JSON(nil, err)
		return
	}
	c.JSON(data, nil)
}


text:
angular
	.module("ngCordovaFallback.plugins.actionSheet", [])
	.factory("$cordovaFallbackActionSheet", [
		"$q",
		"$ionicPopup",
		function ($q, $ionicPopup) {
			function setUnlessNull(dest, src, key) {
				if (!src[key]) { return; }

				dest[key] = src[key];
			}
			return {
				show: function (options) {
					var ionicPopupOptions = {}, q = $q.defer();

					// title
					// [buttonLabels]                // standard buttons
					// addCancelButtonWithLabel      // cancel button
					// addDestructiveButtonWithLabel // e.g., delete button
					// > androidEnableCancelButton
					// > winphoneEnableCancelButton

					setUnlessNull(ionicPopupOptions, options, "title");
					setUnlessNull(ionicPopupOptions, options, "subTitle");
					setUnlessNull(ionicPopupOptions, options, "template");

					ionicPopupOptions.buttons = [];

					angular.forEach(options.buttonLabels, function (label) {
						if (!label) { return; }

						ionicPopupOptions.buttons.push({
							text: label,
							type: "button-positive",
							onTap: function (e) {
								q.resolve(label);
							}
						});
					});

					if (options.addDestructiveButtonWithLabel) {
						ionicPopupOptions.buttons.push({
							text: options.addDestructiveButtonWithLabel,
							type: "button-assertive",
							onTap: function (e) {
								q.resolve(options.addDestructiveButtonWithLabel);
							}
						});
					}

					if (options.addCancelButtonWithLabel) {
						ionicPopupOptions.buttons.push({
							text: options.addCancelButtonWithLabel,
							type: "button-stable",
							onTap: function (e) {
								q.reject(options.addCancelButtonWithLabel);
							}
						});
					}

					$ionicPopup.show(ionicPopupOptions);

					return q.promise;
				},
				hide: function () {
					// return $window.plugins.actionsheet.hide();
				}
			};
		}
	]);


text:
#include "vice.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "charset.h"
#include "diskcontents.h"
#include "imagecontents.h"
#include "lib.h"
#include "tapecontents.h"
#include "types.h"
#include "util.h"

/* ------------------------------------------------------------------------- */

image_contents_t *image_contents_new(void)
{
    image_contents_t *newimg;

    newimg = lib_calloc(1, sizeof(image_contents_t));

    newimg->blocks_free = -1;
    newimg->file_list = NULL;

    return newimg;
}

void image_contents_destroy(image_contents_t *contents)
{
    image_contents_file_list_t *p, *h;

    for (p = contents->file_list; p != NULL; h = p, p = p->next, lib_free(h));

    lib_free(contents);
}

void image_contents_screencode_destroy(image_contents_screencode_t *c)
{
    image_contents_screencode_t *h;

    while (c != NULL) {
        h = c->next;
        lib_free(c->line);
        lib_free(c);
        c = h;
    }
}

image_contents_screencode_t *image_contents_to_screencode(image_contents_t
                                                          *contents)
{
    BYTE *buf, rawline[50];
    unsigned int len, i;
    image_contents_screencode_t *image_contents_screencode, *screencode_ptr;
    image_contents_file_list_t *p;

    image_contents_screencode = lib_malloc(sizeof(image_contents_screencode_t));

    screencode_ptr = image_contents_screencode;

    sprintf((char *)rawline, "0 \"%s\" %s", contents->name, contents->id);
    charset_petcii_to_screencode_line(rawline, &buf, &len);
    screencode_ptr->line = buf;
    screencode_ptr->length = len;
    screencode_ptr->next = NULL;

    /*
     I removed this for OS/2 because I want to have an output
     which looks like a directory listing which you can load in
     the emulator.
     */
#ifndef __OS2__
    if (contents->file_list == NULL) {
        charset_petcii_to_screencode_line((BYTE *)"(eMPTY IMAGE.)", &buf, &len);
        screencode_ptr->next = lib_malloc(sizeof(image_contents_screencode_t));
        screencode_ptr = screencode_ptr->next;

        screencode_ptr->line = buf;
        screencode_ptr->length = len;
        screencode_ptr->next = NULL;
    }
#endif

    for (p = contents->file_list; p != NULL; p = p->next) {

        sprintf((char *)rawline, "%-5d \"                  ", p->size);
        memcpy(&rawline[7], p->name, IMAGE_CONTENTS_FILE_NAME_LEN);

        for (i = 0; i < IMAGE_CONTENTS_FILE_NAME_LEN; i++) {
            if (rawline[7 + i] == 0xa0) {
                rawline[7 + i] = '"';
                break;
            }
        }

        if (i == IMAGE_CONTENTS_FILE_NAME_LEN)
            rawline[7 + IMAGE_CONTENTS_FILE_NAME_LEN] = '"';

        memcpy(&rawline[7 + IMAGE_CONTENTS_FILE_NAME_LEN + 2], p->type, 5);
        charset_petcii_to_screencode_line(rawline, &buf, &len);

        screencode_ptr->next = lib_malloc(sizeof(image_contents_screencode_t));
        screencode_ptr = screencode_ptr->next;

        screencode_ptr->line = buf;
        screencode_ptr->length = len;
        screencode_ptr->next = NULL;
    }

    if (contents->blocks_free >= 0) {
        sprintf((char *)rawline, "%d BLOCKS FREE.", contents->blocks_free);
        charset_petcii_to_screencode_line(rawline, &buf, &len);

        screencode_ptr->next = lib_malloc(sizeof(image_contents_screencode_t));
        screencode_ptr = screencode_ptr->next;

        screencode_ptr->line = buf;
        screencode_ptr->length = len;
        screencode_ptr->next = NULL;
    }

    return image_contents_screencode;
}

char *image_contents_to_string(image_contents_t * contents,
                               char convert_to_ascii)
{
    char *string = lib_msprintf("0 \"%s\" %s", contents->name, contents->id);
    if (convert_to_ascii)
        charset_petconvstring((unsigned char *)string, 1);

    return string;
}

static char *image_contents_get_filename(image_contents_file_list_t * p)
{
    int i;
    static char print_name[IMAGE_CONTENTS_FILE_NAME_LEN + 3] = { 0 };
    char encountered_a0 = 0;

    memset(print_name, 0x20, sizeof(print_name)-1); /* redundant? better safe than sorry */
    print_name[0] = '\"';

    for (i = 0; i < IMAGE_CONTENTS_FILE_NAME_LEN; i++) {
        if (p->name[i] == 0) { /* a 0x00 would mess a dir on real thing anyway */
            print_name[i+1] = '?'; /* better than showing a reversed @ */
        } else if (p->name[i] == 0xa0) {
            encountered_a0++;
            if(encountered_a0 == 1) {
                print_name[i+1] = '\"';
            } else {
                print_name[i+1] = 0x20;
            }
        } else {
            print_name[i+1] = (char)p->name[i];
        }
    }

    if (!encountered_a0) {
        print_name[i+1] = '\"';
    }

    return print_name;
}

char *image_contents_filename_to_string(image_contents_file_list_t * p,
                                    char convert_to_ascii)
{
    char *print_name;
    char *string;

    print_name = image_contents_get_filename(p);
    string = strdup(print_name);

    if (convert_to_ascii) {
        charset_petconvstring((unsigned char *)string, 1);
    }

    return string;
}

char *image_contents_file_to_string(image_contents_file_list_t * p,
                                    char convert_to_ascii)
{
    char *print_name;
    char *string;

    print_name = image_contents_get_filename(p);
    string = lib_msprintf("%-5d %s %s", p->size, print_name, p->type);

    if (convert_to_ascii) {
        charset_petconvstring((unsigned char *)string, 1);
    }

    return string;
}

char *image_contents_filename_by_number(image_contents_t *contents,
                                        unsigned int file_index)
{
    image_contents_file_list_t *current;
    char *s = NULL;

    if (contents == NULL)
        return NULL;

    if (file_index != 0) {
        current = contents->file_list;
        file_index--;
        while ((file_index != 0) && (current != NULL)) {
            current = current->next;
            file_index--;
        }
        if (current != NULL) {
            s = lib_stralloc((char *)(current->name));
        }
    }

    image_contents_destroy(contents);

    return s;
}


text:
<?php declare(strict_types=1);
/**
 * @license MIT
 * @author Samuel Adeshina <samueladeshina73@gmail.calculhmac(clent, data)om>
 *
 * This file is part of the EmmetBlue project, please read the license document
 * available in the root level of the project
 */
namespace EmmetBlue\Plugins\AccountsBiller;

use EmmetBlue\Core\Builder\BuilderFactory as Builder;
use EmmetBlue\Core\Factory\DatabaseConnectionFactory as DBConnectionFactory;
use EmmetBlue\Core\Builder\QueryBuilder\QueryBuilder as QB;
use EmmetBlue\Core\Exception\SQLException;
use EmmetBlue\Core\Exception\UndefinedValueException;
use EmmetBlue\Core\Session\Session;
use EmmetBlue\Core\Logger\DatabaseLog;
use EmmetBlue\Core\Logger\ErrorLog;
use EmmetBlue\Core\Constant;

/**
 * class AccountsCustomerCategory.
 *
 * AccountsCustomerCategory Controller
 *
 * @author Samuel Adeshina <samueladeshina73@gmail.com>
 * @since v0.0.1 08/06/2016 14:20
 */
class CustomerCategory
{
	public static function newCustomerCategory(array $data)
	{
		return CustomerCategory\CustomerCategory::create($data);
	}

	public static function viewCustomerCategory(int $resourceId=0, array $data = [])
	{
		return CustomerCategory\CustomerCategory::view($resourceId, $data);
	}

	public static function deleteCustomerCategory(int $resourceId)
	{
		return CustomerCategory\CustomerCategory::delete($resourceId);
	}

	public static function editCustomerCategory(int $resourceId, array $data)
    {
        $result = CustomerCategory\CustomerCategory::edit($resourceId, $data);

        return $result;
    }
}


text:
/*
 * twemproxy - A fast and lightweight proxy for memcached protocol.
 * Copyright (C) 2011 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <unistd.h>

#include "dyn_core.h"
#include "dyn_server.h"
#include "dyn_conf.h"
#include "dyn_token.h"

void
server_ref(struct conn *conn, void *owner)
{
	struct server *server = owner;

	ASSERT(!conn->client && !conn->proxy);
	ASSERT(conn->owner == NULL);

	conn->family = server->family;
	conn->addrlen = server->addrlen;
	conn->addr = server->addr;

	server->ns_conn_q++;
	TAILQ_INSERT_TAIL(&server->s_conn_q, conn, conn_tqe);

	conn->owner = owner;

	log_debug(LOG_VVERB, "ref conn %p owner %p into '%.*s", conn, server,
			server->pname.len, server->pname.data);
}

void
server_unref(struct conn *conn)
{
	struct server *server;

	ASSERT(!conn->client && !conn->proxy);
	ASSERT(conn->owner != NULL);

	server = conn->owner;
	conn->owner = NULL;

	ASSERT(server->ns_conn_q != 0);
	server->ns_conn_q--;
	TAILQ_REMOVE(&server->s_conn_q, conn, conn_tqe);

	log_debug(LOG_VVERB, "unref conn %p owner %p from '%.*s'", conn, server,
			server->pname.len, server->pname.data);
}

int
server_timeout(struct conn *conn)
{
	struct server *server;
	struct server_pool *pool;

	ASSERT(!conn->client && !conn->proxy);

	server = conn->owner;
	pool = server->owner;

	return pool->timeout;
}

bool
server_active(struct conn *conn)
{
	ASSERT(!conn->client && !conn->proxy);

	if (!TAILQ_EMPTY(&conn->imsg_q)) {
		log_debug(LOG_VVERB, "s %d is active", conn->sd);
		return true;
	}

	if (!TAILQ_EMPTY(&conn->omsg_q)) {
		log_debug(LOG_VVERB, "s %d is active", conn->sd);
		return true;
	}

	if (conn->rmsg != NULL) {
		log_debug(LOG_VVERB, "s %d is active", conn->sd);
		return true;
	}

	if (conn->smsg != NULL) {
		log_debug(LOG_VVERB, "s %d is active", conn->sd);
		return true;
	}

	log_debug(LOG_VVERB, "s %d is inactive", conn->sd);

	return false;
}

static rstatus_t
server_each_set_owner(void *elem, void *data)
{
	struct server *s = elem;
	struct server_pool *sp = data;

	s->owner = sp;

	return DN_OK;
}

rstatus_t
server_init(struct array *servers, struct array *conf_server,
		struct server_pool *sp)
{
	rstatus_t status;
	uint32_t nserver;

	nserver = array_n(conf_server);
	ASSERT(nserver != 0);
	ASSERT(array_n(servers) == 0);

	status = array_init(servers, nserver, sizeof(struct server));
	if (status != DN_OK) {
		return status;
	}

	/* transform conf server to server */
	status = array_each(conf_server, conf_server_each_transform, servers);
	if (status != DN_OK) {
		server_deinit(servers);
		return status;
	}
	ASSERT(array_n(servers) == nserver);

	/* set server owner */
	status = array_each(servers, server_each_set_owner, sp);
	if (status != DN_OK) {
		server_deinit(servers);
		return status;
	}

	log_debug(LOG_DEBUG, "init %"PRIu32" servers in pool %"PRIu32" '%.*s'",
			nserver, sp->idx, sp->name.len, sp->name.data);

	return DN_OK;
}

void
server_deinit(struct array *server)
{
	uint32_t i, nserver;

	for (i = 0, nserver = array_n(server); i < nserver; i++) {
		struct server *s = array_pop(server);
		ASSERT(TAILQ_EMPTY(&s->s_conn_q) && s->ns_conn_q == 0);
	}
	array_deinit(server);
}

struct conn *
server_conn(struct server *server)
{
	struct server_pool *pool;
	struct conn *conn;

	pool = server->owner;

	/*
	 * FIXME: handle multiple server connections per server and do load
	 * balancing on it. Support multiple algorithms for
	 * 'server_connections:' > 0 key
	 */

	if (server->ns_conn_q < pool->server_connections) {
		return conn_get(server, false, pool->redis);
	}
	ASSERT(server->ns_conn_q == pool->server_connections);

	/*
	 * Pick a server connection from the head of the queue and insert
	 * it back into the tail of queue to maintain the lru order
	 */
	conn = TAILQ_FIRST(&server->s_conn_q);
	ASSERT(!conn->client && !conn->proxy);

	TAILQ_REMOVE(&server->s_conn_q, conn, conn_tqe);
	TAILQ_INSERT_TAIL(&server->s_conn_q, conn, conn_tqe);

	return conn;
}

static rstatus_t
server_each_preconnect(void *elem, void *data)
{
	rstatus_t status;
	struct server *server;
	struct server_pool *pool;
	struct conn *conn;

	server = elem;
	pool = server->owner;

	conn = server_conn(server);
	if (conn == NULL) {
		return DN_ENOMEM;
	}

	status = server_connect(pool->ctx, server, conn);
	if (status != DN_OK) {
		log_warn("connect to server '%.*s' failed, ignored: %s",
				server->pname.len, server->pname.data, strerror(errno));
		server_close(pool->ctx, conn);
	}

	return DN_OK;
}

static rstatus_t
server_each_disconnect(void *elem, void *data)
{
	struct server *server;
	struct server_pool *pool;

	server = elem;
	pool = server->owner;

	while (!TAILQ_EMPTY(&server->s_conn_q)) {
		struct conn *conn;

		ASSERT(server->ns_conn_q > 0);

		conn = TAILQ_FIRST(&server->s_conn_q);
		conn->close(pool->ctx, conn);
	}

	return DN_OK;
}

static void
server_failure(struct context *ctx, struct server *server)
{
	struct server_pool *pool = server->owner;
	int64_t now, next;
	rstatus_t status;

	if (!pool->auto_eject_hosts) {
		return;
	}

	server->failure_count++;

	log_debug(LOG_VERB, "server '%.*s' failure count %"PRIu32" limit %"PRIu32,
			server->pname.len, server->pname.data, server->failure_count,
			pool->server_failure_limit);

	if (server->failure_count < pool->server_failure_limit) {
		return;
	}

	now = dn_usec_now();
	if (now < 0) {
		return;
	}

	stats_server_set_ts(ctx, server, server_ejected_at, now);

	next = now + pool->server_retry_timeout;

	log_debug(LOG_INFO, "update pool %"PRIu32" '%.*s' to delete server '%.*s' "
			"for next %"PRIu32" secs", pool->idx, pool->name.len,
			pool->name.data, server->pname.len, server->pname.data,
			pool->server_retry_timeout / 1000 / 1000);

	stats_pool_incr(ctx, pool, server_ejects);

	server->failure_count = 0;
	server->next_retry = next;

	status = server_pool_run(pool);
	if (status != DN_OK) {
		log_error("updating pool %"PRIu32" '%.*s' failed: %s", pool->idx,
				pool->name.len, pool->name.data, strerror(errno));
	}
}

static void
server_close_stats(struct context *ctx, struct server *server, err_t err,
		unsigned eof, unsigned connected)
{
	if (connected) {
		stats_server_decr(ctx, server, server_connections);
	}

	if (eof) {
		stats_server_incr(ctx, server, server_eof);
		return;
	}

	switch (err) {
	case ETIMEDOUT:
		stats_server_incr(ctx, server, server_timedout);
		break;
	case EPIPE:
	case ECONNRESET:
	case ECONNABORTED:
	case ECONNREFUSED:
	case ENOTCONN:
	case ENETDOWN:
	case ENETUNREACH:
	case EHOSTDOWN:
	case EHOSTUNREACH:
	default:
		stats_server_incr(ctx, server, server_err);
		break;
	}
}

void
server_close(struct context *ctx, struct conn *conn)
{
	rstatus_t status;
	struct msg *msg, *nmsg; /* current and next message */
	struct conn *c_conn;    /* peer client connection */

	ASSERT(!conn->client && !conn->proxy);

	server_close_stats(ctx, conn->owner, conn->err, conn->eof,
			conn->connected);

	if (conn->sd < 0) {
		server_failure(ctx, conn->owner);
		conn->unref(conn);
		conn_put(conn);
		return;
	}

	for (msg = TAILQ_FIRST(&conn->imsg_q); msg != NULL; msg = nmsg) {
		nmsg = TAILQ_NEXT(msg, s_tqe);

		/* dequeue the message (request) from server inq */
		conn->dequeue_inq(ctx, conn, msg);

		/*
		 * Don't send any error response, if
		 * 1. request is tagged as noreply or,
		 * 2. client has already closed its connection
		 */
		if (msg->swallow || msg->noreply) {
			log_debug(LOG_INFO, "close s %d swallow req %"PRIu64" len %"PRIu32
					" type %d", conn->sd, msg->id, msg->mlen, msg->type);
			req_put(msg);
		} else {
			c_conn = msg->owner;
			//ASSERT(c_conn->client && !c_conn->proxy);

			msg->done = 1;
			msg->error = 1;
			msg->err = conn->err;
			msg->dyn_error = STORAGE_CONNECTION_REFUSE;

			if (req_done(c_conn, TAILQ_FIRST(&c_conn->omsg_q))) {
				event_add_out(ctx->evb, msg->owner);
			}

			log_debug(LOG_INFO, "close s %d schedule error for req %"PRIu64" "
					"len %"PRIu32" type %d from c %d%c %s", conn->sd, msg->id,
					msg->mlen, msg->type, c_conn->sd, conn->err ? ':' : ' ',
							conn->err ? strerror(conn->err): " ");
		}

		stats_server_incr(ctx, conn->owner, server_dropped_requests);
	}
	ASSERT(TAILQ_EMPTY(&conn->imsg_q));

	for (msg = TAILQ_FIRST(&conn->omsg_q); msg != NULL; msg = nmsg) {
		nmsg = TAILQ_NEXT(msg, s_tqe);

		/* dequeue the message (request) from server outq */
		conn->dequeue_outq(ctx, conn, msg);

		if (msg->swallow) {
			log_debug(LOG_INFO, "close s %d swallow req %"PRIu64" len %"PRIu32
					" type %d", conn->sd, msg->id, msg->mlen, msg->type);
			req_put(msg);
		} else {
			c_conn = msg->owner;
			//ASSERT(c_conn->client && !c_conn->proxy);

			msg->done = 1;
			msg->error = 1;
			msg->err = conn->err;

			if (req_done(c_conn, TAILQ_FIRST(&c_conn->omsg_q))) {
				event_add_out(ctx->evb, msg->owner);
			}

			log_debug(LOG_INFO, "close s %d schedule error for req %"PRIu64" "
					"len %"PRIu32" type %d from c %d%c %s", conn->sd, msg->id,
					msg->mlen, msg->type, c_conn->sd, conn->err ? ':' : ' ',
							conn->err ? strerror(conn->err): " ");
		}
	}
	ASSERT(TAILQ_EMPTY(&conn->omsg_q));

	msg = conn->rmsg;
	if (msg != NULL) {
		conn->rmsg = NULL;

		ASSERT(!msg->request);
		ASSERT(msg->peer == NULL);

		rsp_put(msg);

		log_debug(LOG_INFO, "close s %d discarding rsp %"PRIu64" len %"PRIu32" "
				"in error", conn->sd, msg->id, msg->mlen);
	}

	ASSERT(conn->smsg == NULL);

	server_failure(ctx, conn->owner);

	conn->unref(conn);

	status = close(conn->sd);
	if (status < 0) {
		log_error("close s %d failed, ignored: %s", conn->sd, strerror(errno));
	}
	conn->sd = -1;

	conn_put(conn);
}

rstatus_t
server_connect(struct context *ctx, struct server *server, struct conn *conn)
{
	rstatus_t status;

	ASSERT(!conn->client && !conn->proxy);

	if (conn->sd > 0) {
		/* already connected on server connection */
		return DN_OK;
	}

        if (log_loggable(LOG_VVERB)) {
	   log_debug(LOG_VVERB, "connect to server '%.*s'", server->pname.len,
		   	server->pname.data);
        }

	conn->sd = socket(conn->family, SOCK_STREAM, 0);
	if (conn->sd < 0) {
		log_error("socket for server '%.*s' failed: %s", server->pname.len,
				server->pname.data, strerror(errno));
		status = DN_ERROR;
		goto error;
	}

	status = dn_set_nonblocking(conn->sd);
	if (status != DN_OK) {
		log_error("set nonblock on s %d for server '%.*s' failed: %s",
				conn->sd,  server->pname.len, server->pname.data,
				strerror(errno));
		goto error;
	}

	if (server->pname.data[0] != '/') {
		status = dn_set_tcpnodelay(conn->sd);
		if (status != DN_OK) {
			log_warn("set tcpnodelay on s %d for server '%.*s' failed, ignored: %s",
					conn->sd, server->pname.len, server->pname.data,
					strerror(errno));
		}
	}

	status = event_add_conn(ctx->evb, conn);
	if (status != DN_OK) {
		log_error("event add conn s %d for server '%.*s' failed: %s",
				conn->sd, server->pname.len, server->pname.data,
				strerror(errno));
		goto error;
	}

	ASSERT(!conn->connecting && !conn->connected);

	status = connect(conn->sd, conn->addr, conn->addrlen);
	if (status != DN_OK) {
		if (errno == EINPROGRESS) {
			conn->connecting = 1;
			log_debug(LOG_DEBUG, "connecting on s %d to server '%.*s'",
					conn->sd, server->pname.len, server->pname.data);
			return DN_OK;
		}

		log_error("connect on s %d to server '%.*s' failed: %s", conn->sd,
				server->pname.len, server->pname.data, strerror(errno));

		goto error;
	}

	ASSERT(!conn->connecting);
	conn->connected = 1;
	log_debug(LOG_INFO, "connected on s %d to server '%.*s'", conn->sd,
			server->pname.len, server->pname.data);

	return DN_OK;

	error:
	conn->err = errno;
	return status;
}

void
server_connected(struct context *ctx, struct conn *conn)
{
	struct server *server = conn->owner;

	ASSERT(!conn->client && !conn->proxy);
	ASSERT(conn->connecting && !conn->connected);

	stats_server_incr(ctx, server, server_connections);

	conn->connecting = 0;
	conn->connected = 1;

        if (log_loggable(LOG_INFO)) {
	   log_debug(LOG_INFO, "connected on s %d to server '%.*s'", conn->sd,
		   	server->pname.len, server->pname.data);
        }
}

void
server_ok(struct context *ctx, struct conn *conn)
{
	struct server *server = conn->owner;

	ASSERT(!conn->client && !conn->proxy);
	ASSERT(conn->connected);

	if (server->failure_count != 0) {
           if (log_loggable(LOG_VERB)) {
		   log_debug(LOG_VERB, "reset server '%.*s' failure count from %"PRIu32
				 " to 0", server->pname.len, server->pname.data,
				 server->failure_count);
           }
           server->failure_count = 0;
           server->next_retry = 0LL;
	}
}

static rstatus_t
server_pool_update(struct server_pool *pool)
{
	rstatus_t status;
	int64_t now;
	uint32_t pnlive_server; /* prev # live server */

	if (!pool->auto_eject_hosts) {
		return DN_OK;
	}

	if (pool->next_rebuild == 0LL) {
		return DN_OK;
	}

	now = dn_usec_now();
	if (now < 0) {
		return DN_ERROR;
	}

	if (now <= pool->next_rebuild) {
		if (pool->nlive_server == 0) {
			errno = ECONNREFUSED;
			return DN_ERROR;
		}
		return DN_OK;
	}

	pnlive_server = pool->nlive_server;

	status = server_pool_run(pool);
	if (status != DN_OK) {
		log_error("updating pool %"PRIu32" with dist %d failed: %s", pool->idx,
				pool->dist_type, strerror(errno));
		return status;
	}

	log_debug(LOG_INFO, "update pool %"PRIu32" '%.*s' to add %"PRIu32" servers",
			pool->idx, pool->name.len, pool->name.data,
			pool->nlive_server - pnlive_server);

	return DN_OK;
}

static struct server *
server_pool_server(struct server_pool *pool, uint8_t *key, uint32_t keylen)
{
	struct server *server;

	ASSERT(array_n(&pool->server) != 0);

	//just return the first (memcache) entry in the array
	server = array_get(&pool->server, 0);

	return server;
}

struct conn *
server_pool_conn(struct context *ctx, struct server_pool *pool, uint8_t *key,
		uint32_t keylen)
{
	rstatus_t status;
	struct server *server;
	struct conn *conn;

	status = server_pool_update(pool);
	if (status != DN_OK) {
		return NULL;
	}

	/* from a given {key, keylen} pick a server from pool */
	server = server_pool_server(pool, key, keylen);
	if (server == NULL) {
		return NULL;
	}

	/* pick a connection to a given server */
	conn = server_conn(server);
	if (conn == NULL) {
		return NULL;
	}

	status = server_connect(ctx, server, conn);
	if (status != DN_OK) {
		server_close(ctx, conn);
		return NULL;
	}

	return conn;
}

static rstatus_t
server_pool_each_preconnect(void *elem, void *data)
{
	rstatus_t status;
	struct server_pool *sp = elem;

	if (!sp->preconnect) {
		return DN_OK;
	}

	status = array_each(&sp->server, server_each_preconnect, NULL);
	if (status != DN_OK) {
		return status;
	}

	return DN_OK;
}

rstatus_t
server_pool_preconnect(struct context *ctx)
{
	rstatus_t status;

	status = array_each(&ctx->pool, server_pool_each_preconnect, NULL);
	if (status != DN_OK) {
		return status;
	}

	return DN_OK;
}

static rstatus_t
server_pool_each_disconnect(void *elem, void *data)
{
	rstatus_t status;
	struct server_pool *sp = elem;

	status = array_each(&sp->server, server_each_disconnect, NULL);
	if (status != DN_OK) {
		return status;
	}

	return DN_OK;
}

void
server_pool_disconnect(struct context *ctx)
{
	array_each(&ctx->pool, server_pool_each_disconnect, NULL);
}

static rstatus_t
server_pool_each_set_owner(void *elem, void *data)
{
	struct server_pool *sp = elem;
	struct context *ctx = data;

	sp->ctx = ctx;

	return DN_OK;
}

rstatus_t
server_pool_run(struct server_pool *pool)
{
	ASSERT(array_n(&pool->server) != 0);

	switch (pool->dist_type) {
	case DIST_KETAMA:
		return ketama_update(pool);

	case DIST_VNODE:
		//return vnode_update(pool);
		break;

	case DIST_MODULA:
		return modula_update(pool);

	case DIST_RANDOM:
		return random_update(pool);

	case DIST_SINGLE:
		return DN_OK;

	default:
		NOT_REACHED();
		return DN_ERROR;
	}

	return DN_OK;
}

static rstatus_t
server_pool_each_run(void *elem, void *data)
{
	return server_pool_run(elem);
}

rstatus_t
server_pool_init(struct array *server_pool, struct array *conf_pool,
		struct context *ctx)
{
	rstatus_t status;
	uint32_t npool;

	npool = array_n(conf_pool);
	ASSERT(npool != 0);
	ASSERT(array_n(server_pool) == 0);

	status = array_init(server_pool, npool, sizeof(struct server_pool));
	if (status != DN_OK) {
		return status;
	}

	/* transform conf pool to server pool */
	status = array_each(conf_pool, conf_pool_each_transform, server_pool);
	if (status != DN_OK) {
		server_pool_deinit(server_pool);
		return status;
	}
	ASSERT(array_n(server_pool) == npool);

	/* set ctx as the server pool owner */
	status = array_each(server_pool, server_pool_each_set_owner, ctx);
	if (status != DN_OK) {
		server_pool_deinit(server_pool);
		return status;
	}

	/* update server pool continuum */
	status = array_each(server_pool, server_pool_each_run, NULL);
	if (status != DN_OK) {
		server_pool_deinit(server_pool);
		return status;
	}

	log_debug(LOG_DEBUG, "init %"PRIu32" pools", npool);

	return DN_OK;
}

void
server_pool_deinit(struct array *server_pool)
{
	uint32_t i, npool;

	for (i = 0, npool = array_n(server_pool); i < npool; i++) {
		struct server_pool *sp;

		sp = array_pop(server_pool);
		ASSERT(sp->p_conn == NULL);
		ASSERT(TAILQ_EMPTY(&sp->c_conn_q) && sp->dn_conn_q == 0);

		server_deinit(&sp->server);

		sp->nlive_server = 0;

		log_debug(LOG_DEBUG, "deinit pool %"PRIu32" '%.*s'", sp->idx,
				sp->name.len, sp->name.data);
	}

	array_deinit(server_pool);

	log_debug(LOG_DEBUG, "deinit %"PRIu32" pools", npool);
}

dictType dc_string_dict_type = {
		dict_string_hash,            /* hash function */
		NULL,                        /* key dup */
		NULL,                        /* val dup */
		dict_string_key_compare,     /* key compare */
		dict_string_destructor,      /* key destructor */
		NULL                         /* val destructor */
};

rstatus_t
rack_init(struct rack *rack)
{
	rack->continuum = dn_alloc(sizeof(struct continuum));
	rack->ncontinuum = 0;
	rack->nserver_continuum = 0;
	rack->name = dn_alloc(sizeof(struct string));
	string_init(rack->name);

	rack->dc = dn_alloc(sizeof(struct string));
	string_init(rack->dc);

	return DN_OK;
}

rstatus_t
rack_deinit(struct rack *rack)
{
	if (rack->continuum != NULL) {
		dn_free(rack->continuum);
	}

	return DN_OK;
}

rstatus_t dc_init(struct datacenter *dc)
{
	rstatus_t status;

	dc->dict_rack = dictCreate(&dc_string_dict_type, NULL);
	dc->name = dn_alloc(sizeof(struct string));
	string_init(dc->name);

	status = array_init(&dc->racks, 3, sizeof(struct rack));

	return status;
}

rstatus_t
dc_deinit(struct datacenter *dc)
{
	array_each(&dc->racks, rack_destroy, NULL);
	string_deinit(dc->name);
	//dictRelease(dc->dict_rack);
	return DN_OK;
}

rstatus_t
rack_destroy(void *elem, void *data)
{
	struct rack *rack = elem;
	return rack_deinit(rack);
}

rstatus_t
datacenter_destroy(void *elem, void *data)
{
	struct datacenter *dc = elem;
	dc_deinit(dc);

	return DN_OK;
}

struct datacenter *
server_get_dc(struct server_pool *pool, struct string *dcname)
{
	struct datacenter *dc;
	uint32_t i, len;

	if (log_loggable(LOG_DEBUG)) {
		log_debug(LOG_DEBUG, "server_get_dc pool  '%.*s'",
				dcname->len, dcname->data);
	}

	for (i = 0, len = array_n(&pool->datacenters); i < len; i++) {
		dc = (struct datacenter *) array_get(&pool->datacenters, i);
		ASSERT(dc != NULL);
		ASSERT(dc->name != NULL);

		if (string_compare(dc->name, dcname) == 0) {
			return dc;
		}
	}

	dc = array_push(&pool->datacenters);
	dc_init(dc);
	string_copy(dc->name, dcname->data, dcname->len);

	if (log_loggable(LOG_DEBUG)) {
		log_debug(LOG_DEBUG, "server_get_dc pool about to exit  '%.*s'",
				dc->name->len, dc->name->data);
	}

	return dc;
}

struct rack *
server_get_rack(struct datacenter *dc, struct string *rackname)
{
	ASSERT(dc != NULL);
	ASSERT(dc->dict_rack != NULL);
	ASSERT(dc->name != NULL);

	if (log_loggable(LOG_DEBUG)) {
		log_debug(LOG_DEBUG, "server_get_rack   '%.*s'", rackname->len, rackname->data);
	}
	/*
   struct rack *rack = dictFetchValue(dc->dict_rack, rackname);
   if (rack == NULL) {
      rack = array_push(&dc->racks);
      rack_init(rack);
      string_copy(rack->name, rackname->data, rackname->len);
      string_copy(rack->dc, dc->name->data, dc->name->len);
      rack->continuum = dn_alloc(sizeof(struct continuum));

   	dictAdd(dc->dict_rack, rackname, rack);
   }
	 */

	struct rack *rack;
	uint32_t i, len;
	for (i = 0, len = array_n(&dc->racks); i < len; i++) {
		rack = (struct rack *) array_get(&dc->racks, i);

		if (string_compare(rack->name, rackname) == 0) {
			return rack;
		}
	}

	rack = array_push(&dc->racks);
	rack_init(rack);
	string_copy(rack->name, rackname->data, rackname->len);
	string_copy(rack->dc, dc->name->data, dc->name->len);

	if (log_loggable(LOG_DEBUG)) {
		log_debug(LOG_DEBUG, "server_get_rack exiting  '%.*s'",
				rack->name->len, rack->name->data);
	}

	return rack;
}

struct rack *
server_get_rack_by_dc_rack(struct server_pool *sp, struct string *rackname, struct string *dcname)
{
	struct datacenter *dc = server_get_dc(sp, dcname);
	return server_get_rack(dc, rackname);
}


text:
namespace GLibSharp {

	using System;
	using System.Runtime.InteropServices;

#region Autogenerated code
	[GLib.CDeclCallback]
	internal delegate bool IOSchedulerJobFuncNative(IntPtr job, IntPtr cancellable, IntPtr user_data);

	internal class IOSchedulerJobFuncInvoker {

		IOSchedulerJobFuncNative native_cb;
		IntPtr __data;
		GLib.DestroyNotify __notify;

		~IOSchedulerJobFuncInvoker ()
		{
			if (__notify == null)
				return;
			__notify (__data);
		}

		internal IOSchedulerJobFuncInvoker (IOSchedulerJobFuncNative native_cb) : this (native_cb, IntPtr.Zero, null) {}

		internal IOSchedulerJobFuncInvoker (IOSchedulerJobFuncNative native_cb, IntPtr data) : this (native_cb, data, null) {}

		internal IOSchedulerJobFuncInvoker (IOSchedulerJobFuncNative native_cb, IntPtr data, GLib.DestroyNotify notify)
		{
			this.native_cb = native_cb;
			__data = data;
			__notify = notify;
		}

		internal GLib.IOSchedulerJobFunc Handler {
			get {
				return new GLib.IOSchedulerJobFunc(InvokeNative);
			}
		}

		bool InvokeNative (GLib.IOSchedulerJob job, GLib.Cancellable cancellable)
		{
			bool result = native_cb (job == null ? IntPtr.Zero : job.Handle, cancellable == null ? IntPtr.Zero : cancellable.Handle, __data);
			return result;
		}
	}

	internal class IOSchedulerJobFuncWrapper {

		public bool NativeCallback (IntPtr job, IntPtr cancellable, IntPtr user_data)
		{
			try {
				bool __ret = managed (job == IntPtr.Zero ? null : (GLib.IOSchedulerJob) GLib.Opaque.GetOpaque (job, typeof (GLib.IOSchedulerJob), false), GLib.Object.GetObject(cancellable) as GLib.Cancellable);
				if (release_on_call)
					gch.Free ();
				return __ret;
			} catch (Exception e) {
				GLib.ExceptionManager.RaiseUnhandledException (e, false);
				return false;
			}
		}

		bool release_on_call = false;
		GCHandle gch;

		public void PersistUntilCalled ()
		{
			release_on_call = true;
			gch = GCHandle.Alloc (this);
		}

		internal IOSchedulerJobFuncNative NativeDelegate;
		GLib.IOSchedulerJobFunc managed;

		public IOSchedulerJobFuncWrapper (GLib.IOSchedulerJobFunc managed)
		{
			this.managed = managed;
			if (managed != null)
				NativeDelegate = new IOSchedulerJobFuncNative (NativeCallback);
		}

		public static GLib.IOSchedulerJobFunc GetManagedDelegate (IOSchedulerJobFuncNative native)
		{
			if (native == null)
				return null;
			IOSchedulerJobFuncWrapper wrapper = (IOSchedulerJobFuncWrapper) native.Target;
			if (wrapper == null)
				return null;
			return wrapper.managed;
		}
	}
#endregion
}


text:
/* ------------------------------------------------------------------------ */

/*
 * dll.h: Handle dynamically linked libraries
 *
 * Rob McCool
 */

#ifndef _DLL_H
#define _DLL_H

#include "systems.h"

#if defined(DLL_CAPABLE)

/* --------------------------- Data structures ---------------------------- */

#if defined(USE_NSPR)
#include <nspr/prlink.h>
typedef int DLHANDLE;

#elif defined(DLL_DLOPEN)
#include <dlfcn.h>
typedef void *DLHANDLE;  /* DLOPEN */

#elif defined(DLL_HPSHL)
#include <dl.h>
typedef shl_t DLHANDLE;  /* HP_SHL */

#elif defined(DLL_WIN32)
typedef HINSTANCE DLHANDLE; /* WIN32 */
#endif

/* ------------------------------ Prototypes ------------------------------ */

/*
 * dll_open loads the library at the given path into memory, and returns
 * a handle to be used in later calls to dll_findsym and dll_close.
 */
#if defined(USE_NSPR)
#define dll_open(libfn) PR_LoadLibrary(libfn)

#elif defined(DLL_DLOPEN)
#define dll_open(libfn) dlopen(libfn, DLL_DLOPEN_FLAGS)

#elif defined(DLL_HPSHL)
#define dll_open(libfn) shl_load((libfn), BIND_IMMEDIATE, 0)

#elif defined(DLL_WIN32)
DLHANDLE dll_open(char *libfn);
#endif

/*
 * dll_findsym looks for a symbol with the given name in the library
 * pointed to by the given handle. Returns a pointer to the named function.
 */

#if defined(USE_NSPR)
#define dll_findsym(dlp, name) PR_FindSymbol(name)

#elif defined(DLL_DLOPEN)
#define dll_findsym(dlp, name) dlsym(dlp, name)

#elif defined(DLL_HPSHL)
void *dll_findsym(DLHANDLE dlp, char *name);

#elif defined(DLL_WIN32)
#define dll_findsym(dlp, name) GetProcAddress(dlp, name)
#endif

/*
 * dll_error returns a string describing the last error on the given handle
 */
#if defined(USE_NSPR)
#define dll_error(dlp) system_errmsg(0)

#elif defined(DLL_DLOPEN)
#define dll_error(dlp) dlerror()

#elif defined(DLL_HPSHL)
#define dll_error(dlp) system_errmsg(0)

#elif defined(DLL_WIN32)
#define dll_error(dlp) system_errmsg(0)
#endif

/*
 * dll_close closes the previously opened library given by handle
 */
#if defined(USE_NSPR)
int dll_close(void *arg);

#elif defined(DLL_DLOPEN)
#define dll_close dlclose

#elif defined (DLL_HPSHL)
#define dll_close shl_unload

#elif defined(DLL_WIN32)
#define dll_close FreeLibrary
#endif

#endif /* DLL_CAPABLE */
#endif


text:
Votes

				Posted on

				by

    	No Votes yet, why don't you create one?


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.uff.ic.oceano.view;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author DanCastellani
 */
public class SelectableItem<T> {

    private boolean selected = false;
    private T item;

    public SelectableItem(T item) {
        this.item = item;
    }

    public SelectableItem(T item, boolean selected) {
        this.item = item;
        this.selected = selected;
    }

    /**
     * @return the selected
     */
    public boolean isSelected() {
        return selected;
    }

    /**
     * @param selected the selected to set
     */
    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    /**
     * @return the item
     */
    public <T> T getItem() {
        return (T) item;
    }

    /**
     * @param item the item to set
     */
    public void setItem(T item) {
        this.item = item;
    }
    /**
     *
     * @param List<T>
     * @return uma lista de SelectableItem do tipo T  a partir de uma lista qualquer
     */
    public static <T> List<SelectableItem<T>> getListaSelecao(List<T> listaSelecao){
        final List<SelectableItem<T>> lista = new ArrayList(listaSelecao.size());
        for (T obj : listaSelecao) {
            lista.add(new SelectableItem(obj));
        }
        return lista;
    }

    /**
     *
     * @param List de SelectableItem tipo T
     * @return retorna um (List de SelectableItem tipo T) com os selecionados
     */
    public static <T> List<SelectableItem<T>> getListaSelecaoSelecionados(List<SelectableItem<T>> listaSelecao){
        final List<SelectableItem<T>> lista = new ArrayList(listaSelecao.size());
        for (SelectableItem obj : listaSelecao) {
            if(obj.selected) lista.add(obj);
        }
        return lista;
    }

    /**
     *
     * @param List de SelectableItem tipo T
     * @return retorna um (List de T) dos objetos selecionados
     */
    public static <T> List<T> getListaObjetosSelecionados(List<SelectableItem<T>> listaSelecao){
        final List<T> lista = new ArrayList<T>(listaSelecao.size());
        for (SelectableItem<T> obj : listaSelecao) {
            if(obj.selected) lista.add(obj.item);
        }
        return lista;
    }

    /**
     *
     * @param List de SelectableItem tipo T
     * @return retorna um (List de T) completa dos objetos decorados
     */
    public static <T> List<T> getListaObjetosCompleta(List<SelectableItem<T>> listaSelecao){
        final List<T> lista = new ArrayList<T>(listaSelecao.size());
        for (SelectableItem<T> obj : listaSelecao) {
            lista.add(obj.item);
        }
        return lista;
    }

    /**
     *
     * @param T
     * @return faz o equals do objeto decorado
     */

    @Override
    public boolean equals(Object obj) {
        return item.equals(((SelectableItem<T>)obj).item);
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 67 * hash + (this.item != null ? this.item.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return item == null ? "Objeto Não Informado" : item.toString();
    }

}


text:
package internalversion

import (
	internalinterfaces "github.com/openshift/origin/pkg/user/generated/informers/internalversion/internalinterfaces"
)

// Interface provides access to all the informers in this group version.
type Interface interface {
	// Users returns a UserInformer.
	Users() UserInformer
}

type version struct {
	internalinterfaces.SharedInformerFactory
}

// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory) Interface {
	return &version{f}
}

// Users returns a UserInformer.
func (v *version) Users() UserInformer {
	return &userInformer{factory: v.SharedInformerFactory}
}


text:
import logging
import re

# Don't need this for testing
logging.disable('LOG')

def _check_for_exact_apache(start, lines):
    """Check for the Apache 2.0 license header.

    We strip all the newlines and extra spaces so this license string
    should work regardless of indentation in the file.
    """
    APACHE2 = """
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License."""

    # out of all the formatting I've seen, a 12 line version seems to be the
    # longest in the source tree. So just take the 12 lines starting with where
    # the Apache starting words were found, strip all the '#' and collapse the
    # spaces.
    content = ''.join(lines[start:(start + 12)])
    content = re.sub('\#', '', content)
    content = re.sub('\s+', ' ', content)
    stripped_apache2 = re.sub('\s+', ' ', APACHE2)

    if stripped_apache2 in content:
        return True
    else:
        print ("<license>!=<apache2>:\n'%s' !=\n'%s'" %
               (stripped_apache2, content))
        return False

def _project_is_apache():
    """Determine if a project is Apache.

    Look for a key string in a set of possible license files to figure out
    if a project looks to be Apache. This is used as a precondition for
    enforcing license headers.
    """

    license_files = ["LICENSE"]
    for filename in license_files:
        try:
            with open(filename, "r") as file:
                for line in file:
                    if re.search('Apache License', line):
                        return True
        except IOError:
            pass
    return False

def hacking_has_license(physical_line, filename, lines, line_number):
    """Check for Apache 2.0 license.

    H102 license header not found
    """
    # don't work about init files for now
    # TODO(sdague): enforce license in init file if it's not empty of content
    license_found = False

    # skip files that are < 10 lines, which isn't enough for a license to fit
    # this allows us to handle empty files, as well as not fail on the Okay
    # doctests.
    if _project_is_apache() and not line_number > 1 and len(lines) > 10:
        for idx, line in enumerate(lines):
            # if it's more than 10 characters in, it's probably not in the
            # header
            if 0 < line.find('Licensed under the Apache License') < 10:
                license_found = True
        if not license_found:
            return (0, "H102: Apache 2.0 license header not found")

def hacking_has_correct_license(physical_line, filename, lines, line_number):
    """Check for Apache 2.0 license.

    H103 header does not match Apache 2.0 License notice
    """
    # don't work about init files for now
    # TODO(sdague): enforce license in init file if it's not empty of content

    # skip files that are < 10 lines, which isn't enough for a license to fit
    # this allows us to handle empty files, as well as not fail on the Okay
    # doctests.
    if _project_is_apache() and not line_number > 1 and len(lines) > 10:
        for idx, line in enumerate(lines):
            # if it's more than 10 characters in, it's probably not in the
            # header
            if (0 < line.find('Licensed under the Apache License') < 10
                    and not _check_for_exact_apache(idx, lines)):
                return (idx, "H103: Header does not match Apache 2.0 "
                             "License notice")

def factory(register):
    register(hacking_has_license)
    register(hacking_has_correct_license)


text:
import React from 'react';

export default ({ className = '', ...props }) => (
  <i className={`${className} fa fa-plus`} {...props} />
);


text:
package com.lightd.ideap.maven.navigation;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.util.indexing.FileBasedIndex;

import java.util.BitSet;

public abstract class IdFilter {
    public static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.DefaultFileNavigationContributor");

    public static IdFilter getProjectIdFilter(Project project, boolean includeNonProjectItems) {
        long started = System.currentTimeMillis();
        final BitSet idSet = new BitSet();

        ContentIterator iterator = new ContentIterator() {
            @Override
            public boolean processFile(VirtualFile fileOrDir) {
                int id = ((VirtualFileWithId) fileOrDir).getId();
                if (id < 0) id = -id; // workaround for encountering invalid files, see EA-49915, EA-50599
                idSet.set(id);
                ProgressManager.checkCanceled();
                return true;
            }
        };

        if (!includeNonProjectItems) {
            ProjectRootManager.getInstance(project).getFileIndex().iterateContent(iterator);
        } else {
            FileBasedIndex.getInstance().iterateIndexableFiles(iterator, project, null);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Done filter " + (System.currentTimeMillis() - started) + ":" + idSet.size());
        }
        return new IdFilter() {
            @Override
            public boolean containsFileId(int id) {
                return id >= 0 && idSet.get(id);
            }
        };
    }

    public abstract boolean containsFileId(int id);
}


text:
package org.entrementes.pudim.services;

import java.util.List;

import org.entrementes.pudim.model.Configuration;

public interface ConfigurationService {

	List<Configuration> getConfigurations();

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>giddy.rank.Tau_Local_Neighbor — giddy v2.3.3 Manual</title>
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/pysal-styles.css" />

    <link rel="shortcut icon" href="../_static/pysal_favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="giddy.rank.Tau_Local_Neighborhood" href="giddy.rank.Tau_Local_Neighborhood.html" />
    <link rel="prev" title="giddy.rank.Tau_Local" href="giddy.rank.Tau_Local.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          giddy
        2.3.3

Installation

Tutorial

API

References

  Site

Contents:

Installation

Installing released version

Installing development version

Tutorial

Spatially Explicit Markov Methods

Full Rank Markov and Geographic Rank Markov

Measures of Income Mobility

Directional Analysis of Dynamic LISAs

Rank based Methods

Alignment-based sequence methods

API

Markov Methods

Directional LISA

Economic Mobility Indices

Exchange Mobility Methods

Alignment-based Sequence Methods

Utility Functions

References

  Page

giddy.rank.Tau_Local_Neighbor

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

giddy.rank.Tau_Local_Neighbor¶

class giddy.rank.Tau_Local_Neighbor(x, y, w, permutations=0)[source]¶

Neighbor set LIMA.

Local concordance relationships between a focal unit and its
neighbors. A decomposition of local Tau into neighbor and
non-neighbor components.

Parameters

xarray

(n, ), first variable.

yarray

(n, ), second variable.

wW

spatial weights object.

permutationsint

number of random spatial permutations for
computationally based inference.

Notes

The equation for calculating neighbor set LIMA statistic can be
found in [Rey16] Equation (16).

Examples

>>> import libpysal as ps
>>> import numpy as np
>>> from giddy.rank import Tau_Local_Neighbor, SpatialTau
>>> np.random.seed(10)
>>> f = ps.io.open(ps.examples.get_path("mexico.csv"))
>>> vnames = ["pcgdp%d"%dec for dec in range(1940, 2010, 10)]
>>> y = np.transpose(np.array([f.by_col[v] for v in vnames]))
>>> r = y / y.mean(axis=0)
>>> regime = np.array(f.by_col['esquivel99'])
>>> w = ps.weights.block_weights(regime)
>>> res = Tau_Local_Neighbor(r[:,0], r[:,1], w, permutations=999)
>>> res.tau_ln
array([-0.2       ,  1.        ,  1.        ,  1.        ,  0.33333333,
        0.6       ,  0.6       , -0.5       ,  1.        ,  1.        ,
        0.2       ,  0.33333333,  0.33333333,  0.5       ,  1.        ,
        1.        ,  1.        ,  0.        ,  0.6       , -0.33333333,
       -0.33333333, -0.6       ,  1.        ,  0.2       ,  0.        ,
        0.2       ,  1.        ,  0.6       ,  0.33333333,  0.5       ,
        0.5       , -0.2       ])
>>> res.tau_ln_weights
array([0.03968254, 0.03968254, 0.03174603, 0.03174603, 0.02380952,
       0.03968254, 0.03968254, 0.03174603, 0.00793651, 0.03968254,
       0.03968254, 0.02380952, 0.02380952, 0.03174603, 0.00793651,
       0.02380952, 0.02380952, 0.03174603, 0.03968254, 0.02380952,
       0.02380952, 0.03968254, 0.03174603, 0.03968254, 0.03174603,
       0.03968254, 0.03174603, 0.03968254, 0.02380952, 0.03174603,
       0.03174603, 0.03968254])
>>> res.tau_ln_pvalues
array([0.541, 0.852, 0.668, 0.568, 0.11 , 0.539, 0.609, 0.058, 1.   ,
       0.255, 0.125, 0.087, 0.393, 0.433, 0.908, 0.657, 0.447, 0.128,
       0.531, 0.033, 0.12 , 0.271, 0.868, 0.234, 0.124, 0.387, 0.859,
       0.697, 0.349, 0.664, 0.596, 0.041])
>>> res.sign
array([-1,  1,  1,  1,  1,  1,  1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
        1,  1, -1, -1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1, -1])
>>> (res.tau_ln * res.tau_ln_weights).sum() #global spatial tau
0.39682539682539675
>>> res1 = SpatialTau(r[:,0],r[:,1],w,permutations=999)
>>> res1.tau_spatial
0.3968253968253968

Attributes

nint

number of observations.

tau_localarray

(n, ), local concordance (local version of the
classic tau).

Sarray

(n ,n), concordance matrix, s_{i,j}=1 if
observation i and j are concordant, s_{i,
j}=-1 if observation i and j are discordant,
and s_{i,j}=0 otherwise.

tau_lnarray

(n, ), observed neighbor set LIMA values.

tau_ln_weightsarray

(n, ), weights for neighbor set LIMA at each
location. GIMA is the weighted average of
neighbor set LIMA.

tau_ln_simarray

(n, permutations), neighbor set LIMA values for
permuted samples (if permutations>0).

tau_ln_pvaluesarray

(n, ), one-sided pseudo p-values for observed neighbor
set LIMA values under the null that concordance
relationship between the focal state and itsn
eighbors is not different from what could be
expected from randomly distributed rank changes.

signarray

(n, ), values indicate concordant or
disconcordant: 1 concordant, -1 disconcordant

__init__(x, y, w, permutations=0)[source]¶

Initialize self.  See help(type(self)) for accurate signature.

Methods

<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>

__init__(x, y, w[, permutations])

Initialize self.

      Back to top

  Source

        © Copyright 2018-, pysal developers.

      Created using Sphinx 3.4.3.


text:
import { mount } from "enzyme";
import { testSlider } from "./testUtils";

describe("SimpleSlider with combinations of possibilities", function() {
  // try around several possibilities
  let _noOfSlides = [2, 5, 12];
  let _slidesToShow = [2, 5, 10];
  let _slidesToScroll = [1, 2, 3, 10];
  if (true) {
    // for switching real quick to lesser/easier tests for simplicity
    _noOfSlides = [5];
    _slidesToShow = [2];
    _slidesToScroll = [1, 2];
  }

  for (let noOfSlides of _noOfSlides) {
    for (let slidesToShow of _slidesToShow) {
      for (let slidesToScroll of _slidesToScroll) {
        // following restrictions may not be 100% correct, and there may be more restrictions
        if (slidesToShow > noOfSlides || slidesToScroll > slidesToShow) {
          continue;
        }
        if (noOfSlides === slidesToShow) {
          // temporary, jquery slick disables arrows in this case, so the tests fail
          continue;
        }
        if (slidesToShow === slidesToScroll) {
          // temporary, active-class is not being assigned properly, so tests fail
          continue;
        }
        const settings1 = {
          infinite: true,
          speed: 0,
          noOfSlides,
          slidesToShow,
          slidesToScroll,
          useCSS: false
        };
        test(`Test with settings => noOfSlides: ${noOfSlides}, slidesToShow: ${slidesToShow}, slidesToScroll: ${slidesToScroll}`, function() {
          testSlider(settings1);
        });
      }
    }
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 * Copyright (C) 2007-2008 OpenIntents.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

-->
<resources>

    <!--
         ***************************
	     About information
	     ***************************

    -->

    <!-- Automatically filled in by Launchpad: -->
    <string name="about_translators">Launchpad Contributions:
  Carl Fredrik Sima https://launchpad.net/~cf-sima</string>

    <!-- Short explanation of the application (max. 80 characters) -->
    <string name="about_comments">Hantera filer på SD-kort med OI File Manager.</string>

    <!--
         ***************************
	     Applicatio-specific strings
	     ***************************

    -->
    <!-- Name of application. Can be localized. OI = OpenIntents should stay unmodified. -->
    <string name="app_name">OI File Manager</string>
    <string name="menu_delete">Ta Bort</string>
    <string name="menu_rename">Byt Namn</string>

    <string name="menu_send">Skicka</string>
    <string name="menu_open">Öppna</string>
    <string name="menu_move">Cut</string>
    <string name="menu_copy">Kopiera</string>
    <string name="menu_details">Detaljer</string>
    <string name="menu_more">Mera</string>
    <string name="menu_compress">Komprimera (ZIP)</string>
    <string name="menu_extract">Extrahera (ZIP)</string>
    <string name="menu_include_in_media_scan">Inkludera i mediasökning</string>
    <string name="menu_exclude_from_media_scan">Exkludera i mediasökning</string>
    <string name="menu_bookmark">Bookmark</string>
    <string name="create_new_folder">Skapa ny mapp</string>
    <string name="folder_name">Mappnamn</string>
    <string name="this_folder_is_empty">Den här mappen är tom.</string>
    <string name="really_delete">Vill du verkligen ta bort %s?</string>
    <string name="title_warning_some_may_not_work">Varning</string>
    <string name="warning_some_may_not_work">Några av följande alternativ kanske inte fungerar.</string>
    <string name="show_warning_again">Visa varning igen</string>

    <!-- Strings for a multi select feature -->
    <string name="really_delete_multiselect">Vill du verkligen ta bort %d filer?</string>
    <string name="multiselect_title">Välj flera filer</string>
    <string name="pick_title">File picker</string>

    <!-- Strings for details table -->
    <string name="details_type">Typ</string>
    <string name="details_type_folder">Mapp</string>
    <string name="details_type_file">Fil</string>
    <string name="details_type_other">Annat</string>
    <string name="details_size">Storlek</string>
    <string name="details_permissions">Behörigheter</string>
    <string name="details_hidden">Dold</string>
    <string name="details_lastmodified">Senast modifierad</string>
    <string name="details_yes">Ja</string>
    <string name="details_no">Nej</string>

    <!-- Construct a unique file name of a file called %s. -->
    <string name="copied_file_name">Kopiering av %s</string>

    <!-- Construct a unique file name with number %1$d of a file called %2$s. -->
    <string name="copied_file_name_2">Kopierar %1$d av %2$s</string>
    <string name="media_scan_included">Den här mappen blir inkluderad i nästa multimedia scanning.</string>
    <string name="media_scan_excluded">Den här mappen blir exkluderad i nästa multimedia scanning.</string>
    <string name="error_generic">Ett fel uppstod:</string>
    <string name="error_media_scan">Kunde inte ändra media scanningsinställningar.</string>
    <string name="send_not_available">Ingen applikation tillgänglig för sändning.</string>
    <string name="application_not_available">Applikationen ej tillgänglig</string>

    <!--
         ***************************
	     Preferences
	     ***************************

    -->
    <!-- Menu item for Settings -->
    <string name="settings">Inställningar</string>

    <!-- Category for preferences. -->
    <string name="preference_advanced_features">Avancerade funktioner</string>
    <string name="preference_mediascan_title">Exkludera i mediasökning</string>
    <string name="preference_mediascan_summary_on">Visa menyknapp för att exkludera mappar från media scanning.</string>
    <string name="preference_mediascan_summary_off">Dölj menyknapp för att exkludera mappar från media scanning.</string>
    <string name="preference_showallwarning_title">Visa alla varningar</string>
    <string name="preference_showallwarning_summary_on">Visa alla varningsmeddelanden</string>
    <string name="preference_showallwarning_summary_off">Visa ej varningsmeddelanden</string>
    <string name="preference_displayhiddenfiles_title">Visa dolda filer</string>
    <string name="preference_displayhiddenfiles_summary_on">Visa dolda filer</string>
    <string name="preference_displayhiddenfiles_summary_off">Dölj dolda filer</string>
    <string name="preference_sort_settings">Sorteringsinställningar</string>
    <string name="preference_sortby">Sortera i</string>
    <string name="preference_sortby_ascending">Stigande ordning</string>
    <string name="preference_sortby_ascending_summary_on">Sortera i stigande följd</string>
    <string name="preference_sortby_ascending_summary_off">Sortera i nedstigande följd</string>

    <string-array name="preference_sortby_names">
        <item>Namn</item>
        <item>Storlek</item>
        <item>Senast modifierad</item>
        <item>File extension</item>
    </string-array>

    <string name="preference_usedarktheme_title">Use dark theme (Requires restart of app)</string>
    <string name="preference_usedarktheme_summary_on">Dark theme selected</string>
    <string name="preference_usedarktheme_summary_off">Light theme selected</string>

    <!--
         ***************************
   		 Strings for the \'Save as\' feature
    	 ***************************

    -->
    <string name="saveas_no_file_picked">Du har inte valt någon fil.</string>
    <string name="saveas_error">Ett fel uppstod.</string>
    <string name="saveas_file_saved">Fil sparad!</string>

    <!--
         ***************************
             Strings for the \'Compressing\' and \'Extracting\' feature
          ***************************

    -->
    <string name="compressing_success">Komprimering sluförd</string>
    <string name="compressing_error">Kunde ej komprimera</string>
    <string name="extracting_success">Extrahering slutförd</string>
    <string name="extracting_error">Kunde ej extrahera</string>
    <string name="extracting">Extracting…</string>
    <string name="compressing">Compressing…</string>

    <!-- new menu strings -->
    <string name="menu_bookmarks">Bokmärken</string>
    <string name="menu_search">Search</string>
    <string name="menu_create_folder">Create folder</string>
    <string name="menu_paste">Paste</string>
    <string name="menu_multiselect">Multiselect</string>
    <string name="menu_settings">Inställningar</string>
    <string name="menu_donate">Donate</string>
    <string name="menu_create_shortcut">Create shortcut</string>
    <string name="send_chooser_title">Send using:</string>
    <string name="menu_check_all">Check all</string>
    <string name="menu_uncheck_all">Uncheck all</string>

    <!-- Multi selection action strings -->
    <string name="selected">selected</string>
    <string name="no_selection">No items checked</string>
    <string name="bookmark_empty">No bookmarks added.</string>
    <string name="bookmark_added">Bokmärke tillagt</string>
    <string name="bookmark_already_exists">Den här filen är redan sparat som ett bokmärke</string>
    <string name="bookmarks">Bokmärken</string>

    <!-- Search related -->
    <string name="search_hint">Search files</string>
    <string name="query_error">Query error</string>
    <string name="search_settings_descr">Files and folders in storage</string>
    <string name="preference_search_title">Clear history</string>
    <string name="preference_search_category">Search</string>
    <string name="preference_search_dialog_message">Clear search history?</string>
    <string name="search_history_cleared">Search history cleared</string>

    <!-- icon content description -->
    <string name="item_icon">Item icon</string>

    <!-- list layout -->
    <string name="scanning">Scanning…</string>

    <!-- Dialogs -->
    <string name="delete_success">Successfully deleted</string>
    <string name="delete_failure">Some files not deleted</string>
    <string name="deleting">Deleting…</string>
    <string name="rename_success">Successfully renamed</string>
    <string name="rename_failure">Couldn\'t rename</string>
    <string name="loading">Loading…</string>
    <string name="create_dir_success">Successfully created directory</string>
    <string name="create_dir_failure">Couldn\'t create directory</string>
    <string name="compressed_file_name">Zip file name</string>
    <string name="file_exists">File exists</string>
    <string name="overwrite_question">Overwrite old file?</string>
    <string name="directory_pick">Select current directory</string>
    <string name="filename_hint">File name</string>
    <string name="choose_filename">File name can\'t be empty!</string>
    <string name="pick_button_default">Pick file</string>

    <!-- CopyHelper statuses -->
    <string name="copying">Copying…</string>
    <string name="copied">Successfully copied</string>
    <string name="copy_error">Some or all items couldn\'t be copied!</string>
    <string name="moving">Moving…</string>
    <string name="moved">Successfully moved</string>
    <string name="move_error">Some or all items couldn\'t be moved!</string>
    <string name="nothing_to_paste">Nothing to paste. Copy or cut files first.</string>

    <plurals name="clipboard_info_items_to_copy">
        <item quantity="one">%1$d item to copy</item>
        <item quantity="other">%1$d items to copy</item>
    </plurals>
    <plurals name="clipboard_info_items_to_move">
        <item quantity="one">%1$d item to move</item>
        <item quantity="other">%1$d items to move</item>
    </plurals>

    <string name="clipboard_undo">Undo</string>
    <string name="clipboard_dismiss">Dismiss</string>
    <string name="preference_usebestmatch_title">Use best app for icons</string>
    <string name="preference_usebestmatch_summary_off">use most recently installed app</string>
    <string name="preference_usebestmatch_summary_on">use most suitable app</string>

</resources>


text:
/**
 * Package for test calculate task.
 * @author Alexandr Trifonov (mailto:a.trifonov7@yandex.ru)
 * @version $Id$
 * @since 0.1
 */
 package ru.jobj;


text:
package com.example.mynews.Contants;

public class RequestURL {
}


text:
package org.wikipedia.dataclient.restbase;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.wikipedia.json.annotations.Required;

import java.util.Map;

public class RbDefinition {
    @Required @NonNull private Map<String, Usage[]> usagesByLang;

    public RbDefinition(@NonNull Map<String, RbDefinition.Usage[]> usages) {
        usagesByLang = usages;
    }

    @Nullable public Usage[] getUsagesForLang(String langCode) {
        return usagesByLang.get(langCode);
    }

    public static class Usage {
        @Required @NonNull private String partOfSpeech;
        @Required @NonNull private Definition[] definitions;

        public Usage(@NonNull String partOfSpeech, @NonNull Definition[] definitions) {
            this.partOfSpeech = partOfSpeech;
            this.definitions = definitions;
        }

        @NonNull public String getPartOfSpeech() {
            return partOfSpeech;
        }

        @NonNull public Definition[] getDefinitions() {
            return definitions;
        }
    }

    public static class Definition {
        @Required @NonNull private String definition;
        @Nullable private String[] examples;

        public Definition(@NonNull String definition, @Nullable String[] examples) {
            this.definition = definition;
            this.examples = examples;
        }

        @NonNull public String getDefinition() {
            return definition;
        }

        @Nullable public String[] getExamples() {
            return examples;
        }
    }
}


text:
package hugolib

import (
	"path/filepath"
	"runtime"
	"testing"

	"github.com/spf13/hugo/deps"
	"github.com/stretchr/testify/require"
)

const pageWithAlias = `---
title: Has Alias
aliases: ["foo/bar/"]
---
For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke.
`

const pageWithAliasMultipleOutputs = `---
title: Has Alias for HTML and AMP
aliases: ["foo/bar/"]
outputs: ["HTML", "AMP", "JSON"]
---
For some moments the old man did not reply. He stood with bowed head, buried in deep thought. But at last he spoke.
`

const basicTemplate = "{{.Content}}"
const aliasTemplate = "ALIASTEMPLATE"

func TestAlias(t *testing.T) {
	t.Parallel()

	var (
		cfg, fs = newTestCfg()
		th      = testHelper{cfg, fs, t}
	)

	writeSource(t, fs, filepath.Join("content", "page.md"), pageWithAlias)
	writeSource(t, fs, filepath.Join("layouts", "_default", "single.html"), basicTemplate)

	buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})

	// the real page
	th.assertFileContent(filepath.Join("public", "page", "index.html"), "For some moments the old man")
	// the alias redirector
	th.assertFileContent(filepath.Join("public", "foo", "bar", "index.html"), "<meta http-equiv=\"refresh\" content=\"0; ")
}

func TestAliasMultipleOutputFormats(t *testing.T) {
	t.Parallel()

	var (
		cfg, fs = newTestCfg()
		th      = testHelper{cfg, fs, t}
	)

	writeSource(t, fs, filepath.Join("content", "page.md"), pageWithAliasMultipleOutputs)
	writeSource(t, fs, filepath.Join("layouts", "_default", "single.html"), basicTemplate)
	writeSource(t, fs, filepath.Join("layouts", "_default", "single.amp.html"), basicTemplate)
	writeSource(t, fs, filepath.Join("layouts", "_default", "single.json"), basicTemplate)

	buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})

	// the real pages
	th.assertFileContent(filepath.Join("public", "page", "index.html"), "For some moments the old man")
	th.assertFileContent(filepath.Join("public", "amp", "page", "index.html"), "For some moments the old man")
	th.assertFileContent(filepath.Join("public", "page", "index.json"), "For some moments the old man")

	// the alias redirectors
	th.assertFileContent(filepath.Join("public", "foo", "bar", "index.html"), "<meta http-equiv=\"refresh\" content=\"0; ")
	th.assertFileContent(filepath.Join("public", "foo", "bar", "amp", "index.html"), "<meta http-equiv=\"refresh\" content=\"0; ")
	require.False(t, destinationExists(th.Fs, filepath.Join("public", "foo", "bar", "index.json")))
}

func TestAliasTemplate(t *testing.T) {
	t.Parallel()

	var (
		cfg, fs = newTestCfg()
		th      = testHelper{cfg, fs, t}
	)

	writeSource(t, fs, filepath.Join("content", "page.md"), pageWithAlias)
	writeSource(t, fs, filepath.Join("layouts", "_default", "single.html"), basicTemplate)
	writeSource(t, fs, filepath.Join("layouts", "alias.html"), aliasTemplate)

	sites, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg})

	require.NoError(t, err)

	require.NoError(t, sites.Build(BuildCfg{}))

	// the real page
	th.assertFileContent(filepath.Join("public", "page", "index.html"), "For some moments the old man")
	// the alias redirector
	th.assertFileContent(filepath.Join("public", "foo", "bar", "index.html"), "ALIASTEMPLATE")
}

func TestTargetPathHTMLRedirectAlias(t *testing.T) {
	h := newAliasHandler(nil, newErrorLogger(), false)

	errIsNilForThisOS := runtime.GOOS != "windows"

	tests := []struct {
		value    string
		expected string
		errIsNil bool
	}{
		{"", "", false},
		{"s", filepath.FromSlash("s/index.html"), true},
		{"/", "", false},
		{"alias 1", filepath.FromSlash("alias 1/index.html"), true},
		{"alias 2/", filepath.FromSlash("alias 2/index.html"), true},
		{"alias 3.html", "alias 3.html", true},
		{"alias4.html", "alias4.html", true},
		{"/alias 5.html", "alias 5.html", true},
		{"/трям.html", "трям.html", true},
		{"../../../../tmp/passwd", "", false},
		{"/foo/../../../../tmp/passwd", filepath.FromSlash("tmp/passwd/index.html"), true},
		{"foo/../../../../tmp/passwd", "", false},
		{"C:\\Windows", filepath.FromSlash("C:\\Windows/index.html"), errIsNilForThisOS},
		{"/trailing-space /", filepath.FromSlash("trailing-space /index.html"), errIsNilForThisOS},
		{"/trailing-period./", filepath.FromSlash("trailing-period./index.html"), errIsNilForThisOS},
		{"/tab\tseparated/", filepath.FromSlash("tab\tseparated/index.html"), errIsNilForThisOS},
		{"/chrome/?p=help&ctx=keyboard#topic=3227046", filepath.FromSlash("chrome/?p=help&ctx=keyboard#topic=3227046/index.html"), errIsNilForThisOS},
		{"/LPT1/Printer/", filepath.FromSlash("LPT1/Printer/index.html"), errIsNilForThisOS},
	}

	for _, test := range tests {
		path, err := h.targetPathAlias(test.value)
		if (err == nil) != test.errIsNil {
			t.Errorf("Expected err == nil => %t, got: %t. err: %s", test.errIsNil, err == nil, err)
			continue
		}
		if err == nil && path != test.expected {
			t.Errorf("Expected: \"%s\", got: \"%s\"", test.expected, path)
		}
	}
}