text:
using System;
using System.Globalization;
using System.Net;
using System.Net.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SeafClient.Requests.Libraries;
using SeafClient.Types;

namespace SeafClient.Tests
{
    [TestClass]
    public class LibraryTests : SeafTestClassBase
    {
        [TestMethod]
        public void Test_GetDefaultLibrary_Success()
        {
            var request = new GetDefaultLibraryRequest(FakeToken);

            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(
                    @"{
                   ""repo_id"": ""691b3e24-d05e-43cd-a9f2-6f32bd6b800e"",
                   ""exists"": true
                }")
            };

            Assert.IsTrue(request.WasSuccessful(message));
            var result = ExecuteSync(() => request.ParseResponseAsync(message));
            Assert.IsTrue(result.Exists);
            Assert.AreEqual("691b3e24-d05e-43cd-a9f2-6f32bd6b800e", result.LibraryId);
        }

        [TestMethod]
        public void Test_GetLibraryInfo_Success()
        {
            var request = new GetLibraryInfoRequest(FakeToken, FakeRepoId);

            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(
                    @"{
                    ""encrypted"": false,
                    ""password_need"": null,
                    ""mtime"": null,
                    ""owner"": ""self"",
                    ""id"": ""632ab8a8-ecf9-4435-93bf-f495d5bfe975"",
                    ""size"": 1356155,
                    ""name"": ""org"",
                    ""root"": ""b5227040de360dd22c5717f9563628fe5510cbce"",
                    ""desc"": ""org file"",
                    ""type"": ""repo""
                }")
            };

            Assert.IsTrue(request.WasSuccessful(message));
            var library = ExecuteSync(() => request.ParseResponseAsync(message));

            Assert.AreEqual("632ab8a8-ecf9-4435-93bf-f495d5bfe975", library.Id);
            Assert.AreEqual(null, library.Timestamp);
        }

        [TestMethod]
        public void Test_ListLibraries_HttpRequest()
        {
            var request = new ListLibrariesRequest(FakeToken);
            var httpRequest = TestConnection.CreateHttpRequestMessage(DummyServerUri, request);

            Assert.AreEqual(HttpMethod.Get, httpRequest.Method);
            Assert.AreEqual(DummyServerUri + "api2/repos/", httpRequest.RequestUri.ToString());
        }

        [TestMethod]
        public void Test_ListLibraries_Success()
        {
            var request = new ListLibrariesRequest(FakeToken);

            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"[{
                    ""permission"": ""r"",
                    ""encrypted"": false,
                    ""mtime"": 1400054900,
                    ""owner"": ""user@mail.com"",
                    ""id"": ""f158d1dd-cc19-412c-b143-2ac83f352290"",
                    ""size"": 0,
                    ""name"": ""foo"",
                    ""type"": ""repo"",
                    ""virtual"": false,
                    ""desc"": ""new library"",
                    ""root"": ""0000000000000000000000000000000000000000""
                    },{
                    ""permission"": ""rw"",
                    ""encrypted"": false,
                    ""mtime"": 1400054802,
                    ""owner"": ""user@mail.com"",
                    ""id"": ""0536b11a-a5fd-4482-9314-728cb3472f54"",
                    ""size"": 0,
                    ""name"": ""foo"",
                    ""type"": ""repo"",
                    ""virtual"": false,
                    ""desc"": ""new library"",
                    ""root"": ""0000000000000000000000000000000000000000""
                    }]")
            };

            Assert.IsTrue(request.WasSuccessful(message));
            var result = ExecuteSync(() => request.ParseResponseAsync(message));
            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("foo", result[0].Name);
            Assert.AreEqual("0536b11a-a5fd-4482-9314-728cb3472f54", result[1].Id);
            Assert.AreEqual(SeafPermission.ReadOnly, result[0].Permission);
            Assert.AreEqual(SeafPermission.ReadAndWrite, result[1].Permission);
            // converted the timestamp 1400054900 using http://www.onlineconversion.com/unix_time.htm
            // note: comparison is done in local time
            Assert.AreEqual(DateTime.Parse("Wed, 14 May 2014 08:08:20 GMT", CultureInfo.InvariantCulture), result[0].Timestamp);
        }

        [TestMethod]
        public void Test_ListSharedLibraries_HttpRequest()
        {
            var req = new ListSharedLibrariesRequest(FakeToken);

            var httpReq = TestConnection.CreateHttpRequestMessage(DummyServerUri, req);

            Assert.AreEqual(HttpMethod.Get, httpReq.Method);
            Assert.AreEqual(DummyServerUri + "api2/shared-repos/", httpReq.RequestUri.ToString());
        }

        [TestMethod]
        public void Test_ListSharedLibraries_Success()
        {
            var req = new ListSharedLibrariesRequest(FakeToken);

            var m = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"[{
                    ""repo_id"": ""7d42522b-1f6f-465d-b9c9-879f8eed7c6c"",
                    ""share_type"": ""personal"",
                    ""permission"": ""r"",
                    ""encrypted"": false,
                    ""user"": ""user@example.com"",
                    ""last_modified"": 1361072500,
                    ""repo_desc"": ""ff"",
                    ""group_id"": 0,
                    ""repo_name"": ""\u6d4b\u8bd5\u4e2d\u6587pdf""
                    },{
                    ""repo_id"": ""79bb29cd-b683-4844-abaf-433952723ca5"",
                    ""share_type"": ""group"",
                    ""permission"": ""rw"",
                    ""encrypted"": false,
                    ""user"": ""user@example.com"",
                    ""last_modified"": 1359182468,
                    ""repo_desc"": ""test"",
                    ""group_id"": 1,
                    ""repo_name"": ""test_enc""
                    }]")
            };

            Assert.IsTrue(req.WasSuccessful(m));
            var result = ExecuteSync(() => req.ParseResponseAsync(m));
            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("user@example.com", result[0].Owner);
            Assert.AreEqual("\u6d4b\u8bd5\u4e2d\u6587pdf", result[0].Name);
            Assert.AreEqual("79bb29cd-b683-4844-abaf-433952723ca5", result[1].Id);
            Assert.AreEqual(SeafPermission.ReadOnly, result[0].Permission);
            Assert.AreEqual(SeafPermission.ReadAndWrite, result[1].Permission);
            // converted the timestamp 1400054900 using http://www.onlineconversion.com/unix_time.htm
            // note: comparison is done in local time
            Assert.AreEqual(DateTime.Parse("Sun, 17 Feb 2013 03:41:40 GMT", CultureInfo.InvariantCulture), result[0].Timestamp);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using ServiceStack;
using ServiceStack.Redis;

namespace FunWithRedis
{
    class Program
    {
        static void Main(string[] args)
        {
            //using (IRedisNativeClient client = new RedisClient())
            //{

            //    client.Set("urn:messages:1", Encoding.UTF8.GetBytes("Hello C# World"));
            //}

            //using (IRedisNativeClient client = new RedisClient())
            //{

            //   var result = Encoding.UTF8.GetString(client.Get("urn:messages:1"));
            //   Console.WriteLine("Message: {0}", result);
            //}

            //using (IRedisClient client = new RedisClient())
            //{
            //    var customerNames = client.Lists["urncustomerNames"];
            //    customerNames.Clear();
            //    customerNames.Add("Joe");
            //    customerNames.Add("Mary");
            //    customerNames.Add("Bob");
            //}

            //using (IRedisClient client = new RedisClient())
            //{
            //    var customerNames = client.Lists["urn:customernames"];
            //    foreach (var customerName in customerNames)
            //    {
            //        Console.WriteLine("Customer: {0}", customerNames);
            //    }
            //}

            long lastId = 0;
            using (IRedisClient client = new RedisClient())
            {
                var customerClient = client.As<Customer>();
                var customer = new Customer()
                {
                    Id = customerClient.GetNextSequence(),
                    Address = "123 Main Street",
                    Name = "Bob Tabor",
                    Orders = new List<Order>
                    {
                        new Order {OrderNumber = "ABC"},
                        new Order {OrderNumber = "AB13243"}
                    }

                };
                var storedCustomer = customerClient.Store(customer);
                lastId = storedCustomer.Id;
            }

            using (IRedisClient client = new RedisClient())
            {
                var customerClient = client.As<Customer>();
                var customer = customerClient.GetById(lastId);
                Console.WriteLine("Got Customer {0}, with name {1}", customer.Id, customer.Name);
            }

            using (IRedisClient client = new RedisClient())
            {

                client.PublishMessage("debug", "Hello C#");
            }

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public List<Order> Orders { get; set; }
    }

    public class Order
    {
        public string OrderNumber { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from oslo_config import cfg
from st2common.util import isotime
from st2common.models.api.base import BaseAPI
from st2common.models.db.auth import UserDB, TokenDB
from st2common import log as logging

LOG = logging.getLogger(__name__)

def get_system_username():
    return cfg.CONF.system_user.user

class UserAPI(BaseAPI):
    model = UserDB
    schema = {
        "title": "User",
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "required": True
            }
        },
        "additionalProperties": False
    }

    @classmethod
    def to_model(cls, user):
        name = user.name
        model = cls.model(name=name)
        return model

class TokenAPI(BaseAPI):
    model = TokenDB
    schema = {
        "title": "Token",
        "type": "object",
        "properties": {
            "id": {
                "type": "string"
            },
            "user": {
                "type": ["string", "null"]
            },
            "token": {
                "type": ["string", "null"]
            },
            "ttl": {
                "type": "integer",
                "minimum": 1
            },
            "expiry": {
                "type": ["string", "null"],
                "pattern": isotime.ISO8601_UTC_REGEX
            },
            "metadata": {
                "type": ["object", "null"]
            }
        },
        "additionalProperties": False
    }

    @classmethod
    def from_model(cls, model, mask_secrets=False):
        doc = super(cls, cls)._from_model(model, mask_secrets=mask_secrets)
        doc['expiry'] = isotime.format(model.expiry, offset=False) if model.expiry else None
        return cls(**doc)

    @classmethod
    def to_model(cls, instance):
        user = str(instance.user) if instance.user else None
        token = str(instance.token) if instance.token else None
        expiry = isotime.parse(instance.expiry) if instance.expiry else None

        model = cls.model(user=user, token=token, expiry=expiry)
        return model


text:
LuCI - Lua Configuration Interface

Copyright 2011 Jo-Philipp Wich <xm@subsignal.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
]]--

local map, section, net = ...

local encaps, atmdev, vci, vpi, username, password
local ipv6, defaultroute, metric, peerdns, dns,
      keepalive_failure, keepalive_interval, demand

encaps = section:taboption("general", ListValue, "encaps", translate("PPPoA Encapsulation"))
encaps:value("vc", "VC-Mux")
encaps:value("llc", "LLC")

atmdev = section:taboption("general", Value, "atmdev", translate("ATM device number"))
atmdev.default  = "0"
atmdev.datatype = "uinteger"

vci = section:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vci.default  = "35"
vci.datatype = "uinteger"

vpi = section:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
vpi.default  = "8"
vpi.datatype = "uinteger"

username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))

password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true

if luci.model.network:has_ipv6() then

	ipv6 = section:taboption("advanced", Flag, "ipv6",
		translate("Enable IPv6 negotiation on the PPP link"))

	ipv6.default = ipv6.disabled

end

defaultroute = section:taboption("advanced", Flag, "defaultroute",
	translate("Use default gateway"),
	translate("If unchecked, no default route is configured"))

defaultroute.default = defaultroute.enabled

metric = section:taboption("advanced", Value, "metric",
	translate("Use gateway metric"))

metric.placeholder = "0"
metric.datatype    = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)

peerdns = section:taboption("advanced", Flag, "peerdns",
	translate("Use DNS servers advertised by peer"),
	translate("If unchecked, the advertised DNS server addresses are ignored"))

peerdns.default = peerdns.enabled

dns = section:taboption("advanced", DynamicList, "dns",
	translate("Use custom DNS servers"))

dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast     = "string"

keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
	translate("LCP echo failure threshold"),
	translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))

function keepalive_failure.cfgvalue(self, section)
	local v = m:get(section, "keepalive")
	if v and #v > 0 then
		return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
	end
end

function keepalive_failure.write() end
function keepalive_failure.remove() end

keepalive_failure.placeholder = "0"
keepalive_failure.datatype    = "uinteger"

keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
	translate("LCP echo interval"),
	translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))

function keepalive_interval.cfgvalue(self, section)
	local v = m:get(section, "keepalive")
	if v and #v > 0 then
		return tonumber(v:match("^%d+[ ,]+(%d+)"))
	end
end

function keepalive_interval.write(self, section, value)
	local f = tonumber(keepalive_failure:formvalue(section)) or 0
	local i = tonumber(value) or 5
	if i < 1 then i = 1 end
	if f > 0 then
		m:set(section, "keepalive", "%d %d" %{ f, i })
	else
		m:del(section, "keepalive")
	end
end

keepalive_interval.remove      = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype    = "min(1)"

demand = section:taboption("advanced", Value, "demand",
	translate("Inactivity timeout"),
	translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))

demand.placeholder = "0"
demand.datatype    = "uinteger"


text:
class RcControlsViewController < UITableViewController

        DISPLAY_CELL_ID = 'DisplayCellID'
  SOURCE_CELL_ID = 'SourceCellID'

  PROGRESS_INDICATOR_SIZE = 40.0
  PROGRESS_BAR_HEIGHT = 24.0
  PROGRESS_BAR_WIDTH = 160.0

  SLIDER_HEIGHT = 7.0
  VIEW_TAG = 1

  attr_accessor :progressIndSavedColor

  def viewDidLoad
    super

    self.title = 'ControlsTitle'.localized

    @data_source_array = [
      {
        :title => 'UISwitch', :label => 'Standard Switch',
        :source => "rc_controls_view_controller.rb:\n switch_control",
        :view => self.switch_control
      },
      {
        :title => 'UISlider', :label => 'Standard Slider',
        :source => "rc_controls_view_controller.rb:\n slider_control",
        :view => self.slider_control
      },
      {
        :title => 'UISlider', :label => 'Customized Slider',
        :source => "rc_controls_view_controller.rb:\n custom_slider_control",
        :view => self.custom_slider_control
      },
      {
        :title => 'UIPageControl', :label => 'Ten Pages',
        :source => "rc_controls_view_controller.rb:\n page_control",
        :view => self.page_control
      },
      {
        :title => 'UIActivityIndicatorView', :label => 'Style Gray',
        :source => "rc_controls_view_controller.rb:\n progress_indicator",
        :view => self.progress_indicator
      },
      {
        :title => 'UIProgressView', :label => 'Style Default',
        :source => "rc_controls_view_controller.rb:\n progress_bar",
        :view => self.progress_bar
      },
      {
        :title => 'UIStepper', :label => 'Stepper 1 to 10',
        :source => "rc_controls_view_controller.rb:\n stepper",
        :view => self.stepper
      }
    ]

    tintButton = UIBarButtonItem.alloc.initWithTitle('Tinted',
                                                     style: UIBarButtonItemStyleBordered,
                                                     target: self,
                                                     action: 'tint_action:')
    self.navigationItem.rightBarButtonItem = tintButton

    self.tableView.registerClass(UITableViewCell, :forCellReuseIdentifier => DISPLAY_CELL_ID)
    self.tableView.registerClass(UITableViewCell, :forCellReuseIdentifier => SOURCE_CELL_ID)
  end

  # -----------------------------
  # Table View Delegates
  # -----------------------------

  def numberOfSectionsInTableView(table_view)
    @data_source_array.count
  end

  def tableView(table_view, titleForHeaderInSection:section)
    @data_source_array[section][:title]
  end

  def tableView(table_view, numberOfRowsInSection:section)
    2
  end

  def tableView(table_view, heightForRowAtIndexPath:index_path)
    index_path.row == 0 ? 50.0 : 38.0
  end

  def tableView(table_view, cellForRowAtIndexPath: index_path)
    cell = nil

    if (index_path.row == 0)
      cell = table_view.dequeueReusableCellWithIdentifier(DISPLAY_CELL_ID, forIndexPath: index_path)
      cell.selectionStyle = UITableViewCellSelectionStyleNone

      if viewToRemove = cell.contentView.viewWithTag(VIEW_TAG)
       viewToRemove.removeFromSuperview
      end

      cell.textLabel.text = @data_source_array[index_path.section][:label]

      control = @data_source_array[index_path.section][:view]

      # make sure this control is right-justified to the right side of the cell
      newFrame = control.frame;
      newFrame.origin.x = CGRectGetWidth(cell.contentView.frame) - CGRectGetWidth(newFrame) - 10.0
      control.frame = newFrame

      # if the cell is ever resized, keep the control over to the right
      control.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin

      cell.contentView.addSubview(control)

      if (control == self.progress_indicator)
        self.progress_indicator.startAnimating  # UIActivityIndicatorView needs to re-animate
      end
    else
      cell = table_view.dequeueReusableCellWithIdentifier(SOURCE_CELL_ID, forIndexPath: index_path)
      cell.selectionStyle = UITableViewCellSelectionStyleNone
      cell.textLabel.opaque = false
      cell.textLabel.textAlignment = NSTextAlignmentCenter
      cell.textLabel.textColor = UIColor.grayColor
      cell.textLabel.numberOfLines = 2
      cell.textLabel.highlightedTextColor = UIColor.blackColor
      cell.textLabel.font = UIFont.systemFontOfSize(12.0)

      cell.textLabel.text = @data_source_array[index_path.section][:source]
    end

    cell
  end

  protected

  # -----------------------------
  # UI Control Rendering
  # -----------------------------

  def switch_control
    @switch_control ||= begin
      UISwitch.alloc.initWithFrame(CGRectMake(0.0, 12.0, 94.0, 27.0)).tap do |control|
        control.addTarget(self,
                          action: 'switch_action:',
                          forControlEvents: UIControlEventValueChanged)
        control.backgroundColor = UIColor.clearColor # in case the parent view draws with a custom color or gradient, use a transparent color
        control.setAccessibilityLabel('Standard Switch')
        control.tag = VIEW_TAG        # tag this view for later so we can remove it from recycled table cells
      end
    end
  end

  def slider_control
    @slider_control ||= begin
      UISlider.alloc.initWithFrame(CGRectMake(0.0, 12.0, 120.0, SLIDER_HEIGHT)).tap do |control|
        control.addTarget(self,
                          action: 'slider_action:',
                          forControlEvents: UIControlEventValueChanged)
        control.backgroundColor = UIColor.clearColor # in case the parent view draws with a custom color or gradient, use a transparent color
        control.setAccessibilityLabel('Standard Slider')
        control.minimumValue = 0.0
        control.maximumValue = 100.0
        control.continuous = true
        control.value = 50.0
        control.tag = VIEW_TAG
      end
    end
  end

  def custom_slider_control
    @custom_slider_control ||= begin
      UISlider.alloc.initWithFrame(CGRectMake(0.0, 12.0, 120.0, SLIDER_HEIGHT)).tap do |control|
        control.addTarget(self,
                          action: 'slider_action:',
                          forControlEvents: UIControlEventValueChanged)
        control.backgroundColor = UIColor.clearColor

        stetchLeftTrack = UIImage.imageNamed('/images/orangeslide.png').stretchableImageWithLeftCapWidth(10.0, topCapHeight: 0.0)
        stetchRightTrack = UIImage.imageNamed('/images/yellowslide.png').stretchableImageWithLeftCapWidth(10.0, topCapHeight: 0.0)

        control.setThumbImage(UIImage.imageNamed('/images/slider_ball.png'), forState: UIControlStateNormal)
        control.setMinimumTrackImage(stetchLeftTrack, forState: UIControlStateNormal)
        control.setMaximumTrackImage(stetchRightTrack, forState: UIControlStateNormal)
        control.minimumValue = 0.0
        control.maximumValue = 100.0
        control.continuous = true
        control.value = 50.0
        control.setAccessibilityLabel('Custom Slider')
        control.tag = VIEW_TAG
      end
    end
  end

  def page_control
    @page_control ||= begin
      UIPageControl.alloc.initWithFrame(CGRectMake(0.0, 14.0, 178.0, 20.0)).tap do |control|
        control.addTarget(self,
                          action: 'page_action:',
                          forControlEvents: UIControlEventTouchUpInside)
        control.backgroundColor = UIColor.grayColor
        control.numberOfPages = 10
        control.tag = VIEW_TAG
        end
      end
  end

  def progress_indicator
    @progress_indicator ||= begin
      UIActivityIndicatorView.alloc.initWithActivityIndicatorStyle(UIActivityIndicatorViewStyleGray).tap do |indicator|
        self.progressIndSavedColor = indicator.color

        indicator.frame = CGRectMake(0.0, 12.0, PROGRESS_INDICATOR_SIZE, PROGRESS_INDICATOR_SIZE)
        indicator.sizeToFit
        indicator.tag = VIEW_TAG
        indicator.startAnimating
      end
    end
  end

  def progress_bar
    @progress_bar ||= begin
      UIProgressView.alloc.initWithFrame(CGRectMake(0.0, 20.0, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT)).tap do |bar|
        bar.progressViewStyle = UIProgressViewStyleDefault
        bar.progress = 0.5
        bar.tag = VIEW_TAG
      end
    end
  end

  def stepper
    @stepper ||= begin
      UIStepper.alloc.initWithFrame(CGRectMake(0.0, 10.0, 0.0, 0.0)).tap do |stepper|
        stepper.sizeToFit
        stepper.tag = VIEW_TAG
        stepper.value = 0
        stepper.minimumValue = 0
        stepper.maximumValue = 10
        stepper.stepValue = 1
        stepper.addTarget(self,
                          action: 'stepper_action:',
                          forControlEvents: UIControlEventValueChanged)
      end
    end
  end

  # -----------------------------
  # UI Control Actions
  # -----------------------------

  def tint_action(sender)
    tintColor = self.progress_bar.progressTintColor ? nil : UIColor.blueColor

    self.progress_bar.progressTintColor = tintColor
    self.progress_bar.trackTintColor = tintColor
    self.slider_control.minimumTrackTintColor = tintColor
    self.slider_control.thumbTintColor = tintColor
    self.switch_control.onTintColor = tintColor
    self.stepper.tintColor = tintColor

    self.switch_control.thumbTintColor = self.switch_control.thumbTintColor ? nil : UIColor.redColor

    self.progress_indicator.color = (self.progress_indicator.color != self.progressIndSavedColor) ? self.progressIndSavedColor : UIColor.blueColor
  end

  def switch_action(sender);end
  def slider_action(sender);end
  def page_action(sender);end
  def stepper_action(sender);end

end


text:
package i5.las2peer.execution;

import i5.las2peer.security.AgentException;

/**
 * basic exception thrown on service (invocation) problems
 * @author Holger Janßen
 *
 */
public class L2pServiceException extends AgentException {
	/**
	 *
	 */
	private static final long serialVersionUID = -2266707294292209691L;

	public L2pServiceException ( String message) {
		super ( message );
	}

	public L2pServiceException ( String message, Throwable cause) {
		super ( message, cause);
	}
}


text:
package e2e

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"os"
	"strings"

	"github.com/coreos/etcd/etcdserver"
)

const etcdProcessBasePort = 20000

type clientConnType int

const (
	clientNonTLS clientConnType = iota
	clientTLS
	clientTLSAndNonTLS
)

var (
	configNoTLS = etcdProcessClusterConfig{
		clusterSize:  3,
		initialToken: "new",
	}
	configAutoTLS = etcdProcessClusterConfig{
		clusterSize:   3,
		isPeerTLS:     true,
		isPeerAutoTLS: true,
		initialToken:  "new",
	}
	configTLS = etcdProcessClusterConfig{
		clusterSize:  3,
		clientTLS:    clientTLS,
		isPeerTLS:    true,
		initialToken: "new",
	}
	configClientTLS = etcdProcessClusterConfig{
		clusterSize:  3,
		clientTLS:    clientTLS,
		initialToken: "new",
	}
	configClientBoth = etcdProcessClusterConfig{
		clusterSize:  1,
		clientTLS:    clientTLSAndNonTLS,
		initialToken: "new",
	}
	configClientAutoTLS = etcdProcessClusterConfig{
		clusterSize:     1,
		isClientAutoTLS: true,
		clientTLS:       clientTLS,
		initialToken:    "new",
	}
	configPeerTLS = etcdProcessClusterConfig{
		clusterSize:  3,
		isPeerTLS:    true,
		initialToken: "new",
	}
	configClientTLSCertAuth = etcdProcessClusterConfig{
		clusterSize:           1,
		clientTLS:             clientTLS,
		initialToken:          "new",
		clientCertAuthEnabled: true,
	}
	configJWT = etcdProcessClusterConfig{
		clusterSize:   1,
		initialToken:  "new",
		authTokenOpts: "jwt,pub-key=../../integration/fixtures/server.crt,priv-key=../../integration/fixtures/server.key.insecure,sign-method=RS256,ttl=1s",
	}
)

func configStandalone(cfg etcdProcessClusterConfig) *etcdProcessClusterConfig {
	ret := cfg
	ret.clusterSize = 1
	return &ret
}

type etcdProcessCluster struct {
	cfg   *etcdProcessClusterConfig
	procs []etcdProcess
}

type etcdProcessClusterConfig struct {
	execPath    string
	dataDirPath string
	keepDataDir bool

	clusterSize int

	baseScheme string
	basePort   int

	metricsURLScheme string

	snapshotCount int // default is 10000

	clientTLS             clientConnType
	clientCertAuthEnabled bool
	isPeerTLS             bool
	isPeerAutoTLS         bool
	isClientAutoTLS       bool
	isClientCRL           bool

	cipherSuites []string

	forceNewCluster     bool
	initialToken        string
	quotaBackendBytes   int64
	noStrictReconfig    bool
	initialCorruptCheck bool
	authTokenOpts       string
}

// newEtcdProcessCluster launches a new cluster from etcd processes, returning
// a new etcdProcessCluster once all nodes are ready to accept client requests.
func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
	etcdCfgs := cfg.etcdServerProcessConfigs()
	epc := &etcdProcessCluster{
		cfg:   cfg,
		procs: make([]etcdProcess, cfg.clusterSize),
	}

	// launch etcd processes
	for i := range etcdCfgs {
		proc, err := newEtcdProcess(etcdCfgs[i])
		if err != nil {
			epc.Close()
			return nil, err
		}
		epc.procs[i] = proc
	}

	if err := epc.Start(); err != nil {
		return nil, err
	}
	return epc, nil
}

func (cfg *etcdProcessClusterConfig) clientScheme() string {
	if cfg.clientTLS == clientTLS {
		return "https"
	}
	return "http"
}

func (cfg *etcdProcessClusterConfig) peerScheme() string {
	peerScheme := cfg.baseScheme
	if peerScheme == "" {
		peerScheme = "http"
	}
	if cfg.isPeerTLS {
		peerScheme += "s"
	}
	return peerScheme
}

func (cfg *etcdProcessClusterConfig) etcdServerProcessConfigs() []*etcdServerProcessConfig {
	if cfg.basePort == 0 {
		cfg.basePort = etcdProcessBasePort
	}
	if cfg.execPath == "" {
		cfg.execPath = binPath
	}
	if cfg.snapshotCount == 0 {
		cfg.snapshotCount = etcdserver.DefaultSnapshotCount
	}

	etcdCfgs := make([]*etcdServerProcessConfig, cfg.clusterSize)
	initialCluster := make([]string, cfg.clusterSize)
	for i := 0; i < cfg.clusterSize; i++ {
		var curls []string
		var curl, curltls string
		port := cfg.basePort + 5*i
		curlHost := fmt.Sprintf("localhost:%d", port)

		switch cfg.clientTLS {
		case clientNonTLS, clientTLS:
			curl = (&url.URL{Scheme: cfg.clientScheme(), Host: curlHost}).String()
			curls = []string{curl}
		case clientTLSAndNonTLS:
			curl = (&url.URL{Scheme: "http", Host: curlHost}).String()
			curltls = (&url.URL{Scheme: "https", Host: curlHost}).String()
			curls = []string{curl, curltls}
		}

		purl := url.URL{Scheme: cfg.peerScheme(), Host: fmt.Sprintf("localhost:%d", port+1)}
		name := fmt.Sprintf("testname%d", i)
		dataDirPath := cfg.dataDirPath
		if cfg.dataDirPath == "" {
			var derr error
			dataDirPath, derr = ioutil.TempDir("", name+".etcd")
			if derr != nil {
				panic(fmt.Sprintf("could not get tempdir for datadir: %s", derr))
			}
		}
		initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())

		args := []string{
			"--name", name,
			"--listen-client-urls", strings.Join(curls, ","),
			"--advertise-client-urls", strings.Join(curls, ","),
			"--listen-peer-urls", purl.String(),
			"--initial-advertise-peer-urls", purl.String(),
			"--initial-cluster-token", cfg.initialToken,
			"--data-dir", dataDirPath,
			"--snapshot-count", fmt.Sprintf("%d", cfg.snapshotCount),
		}
		args = addV2Args(args)
		if cfg.forceNewCluster {
			args = append(args, "--force-new-cluster")
		}
		if cfg.quotaBackendBytes > 0 {
			args = append(args,
				"--quota-backend-bytes", fmt.Sprintf("%d", cfg.quotaBackendBytes),
			)
		}
		if cfg.noStrictReconfig {
			args = append(args, "--strict-reconfig-check=false")
		}
		if cfg.initialCorruptCheck {
			args = append(args, "--experimental-initial-corrupt-check")
		}
		var murl string
		if cfg.metricsURLScheme != "" {
			murl = (&url.URL{
				Scheme: cfg.metricsURLScheme,
				Host:   fmt.Sprintf("localhost:%d", port+2),
			}).String()
			args = append(args, "--listen-metrics-urls", murl)
		}

		args = append(args, cfg.tlsArgs()...)

		if cfg.authTokenOpts != "" {
			args = append(args, "--auth-token", cfg.authTokenOpts)
		}

		etcdCfgs[i] = &etcdServerProcessConfig{
			execPath:     cfg.execPath,
			args:         args,
			tlsArgs:      cfg.tlsArgs(),
			dataDirPath:  dataDirPath,
			keepDataDir:  cfg.keepDataDir,
			name:         name,
			purl:         purl,
			acurl:        curl,
			murl:         murl,
			initialToken: cfg.initialToken,
		}
	}

	initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
	for i := range etcdCfgs {
		etcdCfgs[i].initialCluster = strings.Join(initialCluster, ",")
		etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
	}

	return etcdCfgs
}

func (cfg *etcdProcessClusterConfig) tlsArgs() (args []string) {
	if cfg.clientTLS != clientNonTLS {
		if cfg.isClientAutoTLS {
			args = append(args, "--auto-tls")
		} else {
			tlsClientArgs := []string{
				"--cert-file", certPath,
				"--key-file", privateKeyPath,
				"--trusted-ca-file", caPath,
			}
			args = append(args, tlsClientArgs...)

			if cfg.clientCertAuthEnabled {
				args = append(args, "--client-cert-auth")
			}
		}
	}

	if cfg.isPeerTLS {
		if cfg.isPeerAutoTLS {
			args = append(args, "--peer-auto-tls")
		} else {
			tlsPeerArgs := []string{
				"--peer-cert-file", certPath,
				"--peer-key-file", privateKeyPath,
				"--peer-trusted-ca-file", caPath,
			}
			args = append(args, tlsPeerArgs...)
		}
	}

	if cfg.isClientCRL {
		args = append(args, "--client-crl-file", crlPath, "--client-cert-auth")
	}

	if len(cfg.cipherSuites) > 0 {
		args = append(args, "--cipher-suites", strings.Join(cfg.cipherSuites, ","))
	}

	return args
}

func (epc *etcdProcessCluster) EndpointsV2() []string {
	return epc.endpoints(func(ep etcdProcess) []string { return ep.EndpointsV2() })
}

func (epc *etcdProcessCluster) EndpointsV3() []string {
	return epc.endpoints(func(ep etcdProcess) []string { return ep.EndpointsV3() })
}

func (epc *etcdProcessCluster) endpoints(f func(ep etcdProcess) []string) (ret []string) {
	for _, p := range epc.procs {
		ret = append(ret, f(p)...)
	}
	return ret
}

func (epc *etcdProcessCluster) Start() error {
	return epc.start(func(ep etcdProcess) error { return ep.Start() })
}

func (epc *etcdProcessCluster) Restart() error {
	return epc.start(func(ep etcdProcess) error { return ep.Restart() })
}

func (epc *etcdProcessCluster) start(f func(ep etcdProcess) error) error {
	readyC := make(chan error, len(epc.procs))
	for i := range epc.procs {
		go func(n int) { readyC <- f(epc.procs[n]) }(i)
	}
	for range epc.procs {
		if err := <-readyC; err != nil {
			epc.Close()
			return err
		}
	}
	return nil
}

func (epc *etcdProcessCluster) Stop() (err error) {
	for _, p := range epc.procs {
		if p == nil {
			continue
		}
		if curErr := p.Stop(); curErr != nil {
			if err != nil {
				err = fmt.Errorf("%v; %v", err, curErr)
			} else {
				err = curErr
			}
		}
	}
	return err
}

func (epc *etcdProcessCluster) Close() error {
	err := epc.Stop()
	for _, p := range epc.procs {
		// p is nil when newEtcdProcess fails in the middle
		// Close still gets called to clean up test data
		if p == nil {
			continue
		}
		if cerr := p.Close(); cerr != nil {
			err = cerr
		}
	}
	return err
}

func (epc *etcdProcessCluster) WithStopSignal(sig os.Signal) (ret os.Signal) {
	for _, p := range epc.procs {
		ret = p.WithStopSignal(sig)
	}
	return ret
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /home/vhs/test/webroot/composer/vendor/yiisoft/yii/framework/logging/CLogRoute.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/home/vhs/test/webroot/composer /

vendor /

yiisoft /

yii /

framework /

logging /

CLogRoute.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

0.00%

0 / 3

      CRAP

0.00%

0 / 13

      CLogRoute

0.00%

0 / 1

25.00%

1 / 4

      90

0.00%

0 / 13

       init()

0.00%

0 / 1

      2

0.00%

0 / 1

       formatLogMessage($message,$level,$category,$time)

0.00%

0 / 1

      2

0.00%

0 / 1

       collectLogs($logger, $processLogs=false)

0.00%

0 / 1

      42

0.00%

0 / 11

       processLogs($logs)

100.00%

1 / 1

      1

1
	<?php

2

10

11
	/**

12
	 * CLogRoute is the base class for all log route classes.

13
	 *

14
	 * A log route object retrieves log messages from a logger and sends it

15
	 * somewhere, such as files, emails.

16
	 * The messages being retrieved may be filtered first before being sent

17
	 * to the destination. The filters include log level filter and log category filter.

18
	 *

19
	 * To specify level filter, set {@link levels} property,

20
	 * which takes a string of comma-separated desired level names (e.g. 'Error, Debug').

21
	 * To specify category filter, set {@link categories} property,

22
	 * which takes a string of comma-separated desired category names (e.g. 'System.Web, System.IO').

23
	 *

24
	 * Level filter and category filter are combinational, i.e., only messages

25
	 * satisfying both filter conditions will they be returned.

26
	 *

27
	 * @author Qiang Xue <qiang.xue@gmail.com>

28
	 * @package system.logging

29
	 * @since 1.0

30
	 */

31
	abstract class CLogRoute extends CComponent

32
	{

33
	    /**

34
	     * @var boolean whether to enable this log route. Defaults to true.

35
	     */

36
	    public $enabled=true;

37
	    /**

38
	     * @var string list of levels separated by comma or space. Defaults to empty, meaning all levels.

39
	     */

40
	    public $levels='';

41
	    /**

42
	     * @var mixed array of categories, or string list separated by comma or space.

43
	     * Defaults to empty array, meaning all categories.

44
	     */

45
	    public $categories=array();

46
	    /**

47
	     * @var mixed array of categories, or string list separated by comma or space, to EXCLUDE from logs.

48
	     * Defaults to empty array, meaning no categories are excluded.

49
	     * This will exclude any categories after $categories has been ran.

50
	     */

51
	    public $except=array();

52
	    /**

53
	     * @var mixed the additional filter (eg {@link CLogFilter}) that can be applied to the log messages.

54
	     * The value of this property will be passed to {@link Yii::createComponent} to create

55
	     * a log filter object. As a result, this can be either a string representing the

56
	     * filter class name or an array representing the filter configuration.

57
	     * In general, the log filter class should implement {@link ILogFilter} interface.

58
	     * If you want to apply multiple filters you can use {@link CChainedLogFilter} to do so.

59
	     * Defaults to null, meaning no filter will be used.

60
	     */

61
	    public $filter;

62
	    /**

63
	     * @var array the logs that are collected so far by this log route.

64
	     * @since 1.1.0

65
	     */

66
	    public $logs=array();

67

68

69
	    /**

70
	     * Initializes the route.

71
	     * This method is invoked after the route is created by the route manager.

72
	     */

73
	    public function init()

74
	    {

75
	    }

76

77
	    /**

78
	     * Formats a log message given different fields.

79
	     * @param string $message message content

80
	     * @param integer $level message level

81
	     * @param string $category message category

82
	     * @param integer $time timestamp

83
	     * @return string formatted message

84
	     */

85
	    protected function formatLogMessage($message,$level,$category,$time)

86
	    {

87
	        return @date('Y/m/d H:i:s',$time)." [$level] [$category] $message\n";

88
	    }

89

90
	    /**

91
	     * Retrieves filtered log messages from logger for further processing.

92
	     * @param CLogger $logger logger instance

93
	     * @param boolean $processLogs whether to process the logs after they are collected from the logger

94
	     */

95
	    public function collectLogs($logger, $processLogs=false)

96
	    {

97
	        $logs=$logger->getLogs($this->levels,$this->categories,$this->except);

98
	        $this->logs=empty($this->logs) ? $logs : array_merge($this->logs,$logs);

99
	        if($processLogs && !empty($this->logs))

100
	        {

101
	            if($this->filter!==null)

102
	                Yii::createComponent($this->filter)->filter($this->logs);

103
	            if($this->logs!==array())

104
	                $this->processLogs($this->logs);

105
	            $this->logs=array();

106
	        }

107
	    }

108

109
	    /**

110
	     * Processes log messages and sends them to specific destination.

111
	     * Derived child classes must implement this method.

112
	     * @param array $logs list of messages. Each array element represents one message

113
	     * with the following structure:

114
	     * array(

115
	     *   [0] => message (string)

116
	     *   [1] => level (string)

117
	     *   [2] => category (string)

118
	     *   [3] => timestamp (float, obtained by microtime(true));

119
	     */

120
	    abstract protected function processLogs($logs);

121
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.4.4-14+deb7u14 and PHPUnit 3.7.28 at Tue Sep 23 12:36:15 CEST 2014.


text:
(function(root) {
  'use strict';

  function isSubchars(chars, string) {
    if (typeof chars === 'number') {
      chars = chars.toString();
    }
    if (typeof chars === 'number') {
      string = string.toString();
    }
    if (!(typeof chars === 'string' && typeof string === 'string')) {
      return false;
    }

    var cs = [].slice.call(chars.replace(/\s+/,''));
    var s = [].slice.call(string.replace(/\s+/,''));
    var l = cs.length;

    while (l--) {
      var i = s.indexOf(cs[l]);

      if (i === -1) {
        return false;
      } else {
        s.splice(i, 1);
      }
    }

    return true;
  }

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = isSubchars;
    }
    exports.isSubchars = isSubchars;
  } else if (typeof define === 'function' && define.amd) {
    define([], function() {
      return isSubchars;
    });
  } else {
    root.isSubchars = isSubchars;
  }

})(this);


text:
module.exports = function (server) {
    var io = require('socket.io')(server);

    io.on('connection', function(socket) {
        console.log('new connection made');

        socket.on('join', function(args) {

            var name = args.roomName;

            console.log('join ', args);
            socket.join(name);

            socket.emit('join-success', {
                roomName: name
            });

        });

        socket.on('chat', function (args) {
            console.log('received chat: ', args);
            // console.log(_roomName);
            io.to(args.roomName).emit('new-chat', args );
        });

        socket.on('disconnect', function(a,b,c) {
            console.log('disconnect');
        });

    });

    return {
        addNewConnection: addNewConnection
    }

    function addNewConnection() {
        var id = 1;
    }

}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;

namespace osu.Game.Users.Drawables
{
    /// <summary>
    /// An avatar which can update to a new user when needed.
    /// </summary>
    public class UpdateableAvatar : ModelBackedDrawable<User>
    {
        public User User
        {
            get => Model;
            set => Model = value;
        }

        public new bool Masking
        {
            get => base.Masking;
            set => base.Masking = value;
        }

        public new float CornerRadius
        {
            get => base.CornerRadius;
            set => base.CornerRadius = value;
        }

        public new EdgeEffectParameters EdgeEffect
        {
            get => base.EdgeEffect;
            set => base.EdgeEffect = value;
        }

        /// <summary>
        /// Whether to show a default guest representation on null user (as opposed to nothing).
        /// </summary>
        public bool ShowGuestOnNull = true;

        /// <summary>
        /// Whether to open the user's profile when clicked.
        /// </summary>
        public readonly BindableBool OpenOnClick = new BindableBool(true);

        public UpdateableAvatar(User user = null)
        {
            User = user;
        }

        protected override Drawable CreateDrawable(User user)
        {
            if (user == null && !ShowGuestOnNull)
                return null;

            var avatar = new DrawableAvatar(user)
            {
                RelativeSizeAxes = Axes.Both,
            };

            avatar.OnLoadComplete += d => d.FadeInFromZero(300, Easing.OutQuint);
            avatar.OpenOnClick.BindTo(OpenOnClick);

            return avatar;
        }
    }
}


text:
using dx10StateUtils::operator==;

dx10SamplerStateCache SSManager;

dx10SamplerStateCache::dx10SamplerStateCache() : m_uiMaxAnisotropy(1) {
    static const int iMaxRSStates = 10;
    m_StateArray.reserve(iMaxRSStates);
    ResetDeviceState();
}

dx10SamplerStateCache::~dx10SamplerStateCache() { ClearStateArray(); }

dx10SamplerStateCache::SHandle dx10SamplerStateCache::GetState(D3D_SAMPLER_DESC& desc) {
    SHandle hResult;

    //	MaxAnisitropy is reset by ValidateState if not aplicable
    //	to the filter mode used.
    desc.MaxAnisotropy = m_uiMaxAnisotropy;

    dx10StateUtils::ValidateState(desc);

    u32 crc = dx10StateUtils::GetHash(desc);

    hResult = FindState(desc, crc);

    if (hResult == hInvalidHandle) {
        StateRecord rec;
        rec.m_crc = crc;
        CreateState(desc, &rec.m_pState);
        hResult = m_StateArray.size();
        m_StateArray.push_back(rec);
    }

    return hResult;
}

void dx10SamplerStateCache::CreateState(StateDecs desc, IDeviceState** ppIState) {
    CHK_DX(HW.pDevice->CreateSamplerState(&desc, ppIState));
}

dx10SamplerStateCache::SHandle dx10SamplerStateCache::FindState(const StateDecs& desc,
                                                                u32 StateCRC) {
    u32 res = 0xffffffff;
    u32 i = 0;
    for (; i < m_StateArray.size(); ++i) {
        if (m_StateArray[i].m_crc == StateCRC) {
            StateDecs descCandidate;
            m_StateArray[i].m_pState->GetDesc(&descCandidate);
            if (descCandidate == desc)
            // return i;
            //	TEST
            {
                // return i;
                res = i;
                break;
            }
            // else
            //{
            //	VERIFY(0);
            //}
        }
    }

    return res != 0xffffffff ? i : (u32)hInvalidHandle;
}

void dx10SamplerStateCache::ClearStateArray() {
    for (u32 i = 0; i < m_StateArray.size(); ++i) {
        _RELEASE(m_StateArray[i].m_pState);
    }

    m_StateArray.clear();
}

void dx10SamplerStateCache::PrepareSamplerStates(
    HArray& samplers, ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT],
    SHandle pCurrentState[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT], u32& uiMin, u32& uiMax) const {
    //	It seems that sizeof pSS is 4 wor win32!
    std::memset(pSS, 0, sizeof(pSS[0]) * (16));

    for (u32 i = 0; i < samplers.size(); ++i) {
        if (samplers[i] != hInvalidHandle) {
            VERIFY(samplers[i] < m_StateArray.size());
            pSS[i] = m_StateArray[samplers[i]].m_pState;
        }
    }

    uiMin = 0;
    uiMax = D3D_COMMONSHADER_SAMPLER_SLOT_COUNT - 1;
}

void dx10SamplerStateCache::VSApplySamplers(HArray& samplers) {
    ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT];
    u32 uiMin;
    u32 uiMax;
    PrepareSamplerStates(samplers, pSS, m_aVSSamplers, uiMin, uiMax);
    HW.pContext->VSSetSamplers(uiMin, uiMax - uiMin + 1, &pSS[uiMin]);
}

void dx10SamplerStateCache::PSApplySamplers(HArray& samplers) {
    ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT];
    u32 uiMin;
    u32 uiMax;
    PrepareSamplerStates(samplers, pSS, m_aPSSamplers, uiMin, uiMax);
    HW.pContext->PSSetSamplers(uiMin, uiMax - uiMin + 1, &pSS[uiMin]);
}

void dx10SamplerStateCache::GSApplySamplers(HArray& samplers) {
    ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT];
    u32 uiMin;
    u32 uiMax;
    PrepareSamplerStates(samplers, pSS, m_aGSSamplers, uiMin, uiMax);
    HW.pContext->GSSetSamplers(uiMin, uiMax - uiMin + 1, &pSS[uiMin]);
}

#ifdef USE_DX11
void dx10SamplerStateCache::HSApplySamplers(HArray& samplers) {
    ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT];
    u32 uiMin;
    u32 uiMax;
    PrepareSamplerStates(samplers, pSS, m_aHSSamplers, uiMin, uiMax);
    HW.pContext->HSSetSamplers(uiMin, uiMax - uiMin + 1, &pSS[uiMin]);
}

void dx10SamplerStateCache::DSApplySamplers(HArray& samplers) {
    ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT];
    u32 uiMin;
    u32 uiMax;
    PrepareSamplerStates(samplers, pSS, m_aDSSamplers, uiMin, uiMax);
    HW.pContext->DSSetSamplers(uiMin, uiMax - uiMin + 1, &pSS[uiMin]);
}

void dx10SamplerStateCache::CSApplySamplers(HArray& samplers) {
    ID3DSamplerState* pSS[D3D_COMMONSHADER_SAMPLER_SLOT_COUNT];
    u32 uiMin;
    u32 uiMax;
    PrepareSamplerStates(samplers, pSS, m_aCSSamplers, uiMin, uiMax);
    HW.pContext->CSSetSamplers(uiMin, uiMax - uiMin + 1, &pSS[uiMin]);
}
#endif

void dx10SamplerStateCache::SetMaxAnisotropy(UINT uiMaxAniso) {
    clamp(uiMaxAniso, (u32)1, (u32)16);

    if (m_uiMaxAnisotropy == uiMaxAniso)
        return;

    m_uiMaxAnisotropy = uiMaxAniso;

    for (u32 i = 0; i < m_StateArray.size(); ++i) {
        StateRecord& rec = m_StateArray[i];
        StateDecs desc;

        rec.m_pState->GetDesc(&desc);

        //	MaxAnisitropy is reset by ValidateState if not aplicable
        //	to the filter mode used.
        //	Reason: all checks for aniso applicability are done
        //	in ValidateState.
        desc.MaxAnisotropy = m_uiMaxAnisotropy;
        dx10StateUtils::ValidateState(desc);

        //	This can cause fragmentation if called too often
        rec.m_pState->Release();
        CreateState(desc, &rec.m_pState);
    }
}

void dx10SamplerStateCache::ResetDeviceState() {
    for (int i = 0; i < sizeof(m_aPSSamplers) / sizeof(m_aPSSamplers[0]); ++i) {
        m_aPSSamplers[i] = (SHandle)hInvalidHandle;
        m_aVSSamplers[i] = (SHandle)hInvalidHandle;
        m_aGSSamplers[i] = (SHandle)hInvalidHandle;
#ifdef USE_DX11
        m_aHSSamplers[i] = (SHandle)hInvalidHandle;
        m_aDSSamplers[i] = (SHandle)hInvalidHandle;
        m_aCSSamplers[i] = (SHandle)hInvalidHandle;
#endif
    }
}


text:
package org.apache.drill.exec.store.http.paginator;

import okhttp3.HttpUrl.Builder;
import org.apache.commons.lang3.StringUtils;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.exec.store.http.HttpPaginatorConfig.PaginatorMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.NoSuchElementException;

public class IndexPaginator extends Paginator {

  private static final Logger logger = LoggerFactory.getLogger(IndexPaginator.class);
  private final String hasMoreParam;
  private final String indexParam;
  private final String nextPageParam;

  private String indexValue;
  private String lastIndexValue;
  private Boolean hasMoreValue;
  private String nextPageValue;
  private int pageCount;

  public IndexPaginator(Builder builder, int pageSize, int limit, String hasMoreParam, String indexParam, String nextPageParam) {
    super(builder, PaginatorMethod.INDEX, pageSize, limit);
    this.hasMoreParam = hasMoreParam;
    this.indexParam = indexParam;
    this.nextPageParam = nextPageParam;
    pageCount = 0;
  }

  @Override
  public boolean hasNext() {
    return !partialPageReceived;

  }

  public String getIndexParam() {
    return this.indexParam;
  }

  public String getHasMoreParam() {
    return this.hasMoreParam;
  }

  public String getNextPageParam() {
    return this.nextPageParam;
  }

  public void setHasMoreValue(Boolean hasMoreValue) {
    this.hasMoreValue = hasMoreValue;
  }

  public void setIndexValue(String indexValue) {
    if (StringUtils.isNumeric(indexValue)) {

    }
    this.indexValue = indexValue;
  }

  public void setNextPageValue(String nextPageValue) {
    this.lastIndexValue = this.nextPageValue;
    this.nextPageValue = nextPageValue;
  }

  public String getLastIndexValue() {
    return lastIndexValue;
  }

  public boolean isFirstPage() {
    return pageCount < 1;
  }

  @Override
  public String next() {
    // If the paginator has never been run before, just return the base URL.
    if (pageCount == 0) {
      pageCount++;
      return builder.build().url().toString();
    }

    if (!hasNext()) {
      throw new NoSuchElementException();
    }

    if (StringUtils.isNotEmpty(indexValue)) {
      try {
        indexValue = URLEncoder.encode(indexValue, StandardCharsets.UTF_8.name());
      } catch (UnsupportedEncodingException e) {
        // Should never happen
        throw UserException.internalError()
          .message(e.getMessage())
          .build(logger);
      }
      builder.removeAllEncodedQueryParameters(indexParam);
      builder.addQueryParameter(indexParam, indexValue);
    }
    pageCount++;
    return builder.build().url().toString();
  }
}


text:
"use strict";
var path_1 = require('path');
var logger_1 = require('./logger/logger');
var config_1 = require('./util/config');
var Constants = require('./util/constants');
var errors_1 = require('./util/errors');
var helpers_1 = require('./util/helpers');
var webpack_1 = require('./webpack');
var decorators_1 = require('./optimization/decorators');
var treeshake_1 = require('./optimization/treeshake');
function optimization(context, configFile) {
    var logger = new logger_1.Logger("optimization");
    return optimizationWorker(context, configFile).then(function () {
        logger.finish();
    })
        .catch(function (err) {
        var error = new errors_1.BuildError(err.message);
        error.isFatal = true;
        throw logger.fail(error);
    });
}
exports.optimization = optimization;
function optimizationWorker(context, configFile) {
    var webpackConfig = getConfig(context, configFile);
    var dependencyMap = null;
    return webpack_1.runWebpackFullBuild(webpackConfig).then(function (stats) {
        dependencyMap = helpers_1.webpackStatsToDependencyMap(context, stats);
        if (helpers_1.getBooleanPropertyValue(Constants.ENV_PRINT_ORIGINAL_DEPENDENCY_TREE)) {
            logger_1.Logger.debug('Original Dependency Map Start');
            helpers_1.printDependencyMap(dependencyMap);
            logger_1.Logger.debug('Original Dependency Map End');
        }
        return deleteOptimizationJsFile(path_1.join(webpackConfig.output.path, webpackConfig.output.filename));
    }).then(function () {
        return doOptimizations(context, dependencyMap);
    });
}
function deleteOptimizationJsFile(fileToDelete) {
    return helpers_1.unlinkAsync(fileToDelete);
}
exports.deleteOptimizationJsFile = deleteOptimizationJsFile;
function doOptimizations(context, dependencyMap) {
    // remove decorators
    var modifiedMap = new Map(dependencyMap);
    if (helpers_1.getBooleanPropertyValue(Constants.ENV_EXPERIMENTAL_PURGE_DECORATORS)) {
        removeDecorators(context);
    }
    // remove unused component imports
    if (helpers_1.getBooleanPropertyValue(Constants.ENV_EXPERIMENTAL_MANUAL_TREESHAKING)) {
        var results = treeshake_1.calculateUnusedComponents(modifiedMap);
        purgeUnusedImports(context, results.purgedModules);
    }
    if (helpers_1.getBooleanPropertyValue(Constants.ENV_PRINT_MODIFIED_DEPENDENCY_TREE)) {
        logger_1.Logger.debug('Modified Dependency Map Start');
        helpers_1.printDependencyMap(modifiedMap);
        logger_1.Logger.debug('Modified Dependency Map End');
    }
    return modifiedMap;
}
exports.doOptimizations = doOptimizations;
function removeDecorators(context) {
    var jsFiles = context.fileCache.getAll().filter(function (file) { return path_1.extname(file.path) === '.js'; });
    jsFiles.forEach(function (jsFile) {
        jsFile.content = decorators_1.purgeDecorators(jsFile.path, jsFile.content);
    });
}
function purgeUnusedImports(context, purgeDependencyMap) {
    // for now, restrict this to components in the ionic-angular/index.js file
    var indexFilePath = process.env[Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT];
    var file = context.fileCache.get(indexFilePath);
    if (!file) {
        throw new Error("Could not find ionic-angular index file " + indexFilePath);
    }
    var modulesToPurge = [];
    purgeDependencyMap.forEach(function (set, moduleToPurge) {
        modulesToPurge.push(moduleToPurge);
    });
    var updatedFileContent = treeshake_1.purgeUnusedImportsAndExportsFromIndex(indexFilePath, file.content, modulesToPurge);
    context.fileCache.set(indexFilePath, { path: indexFilePath, content: updatedFileContent });
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_ACTION_SHEET_CONTROLLER_PATH], process.env[Constants.ENV_ACTION_SHEET_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_ACTION_SHEET_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_ACTION_SHEET_CONTROLLER_CLASSNAME]);
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_ALERT_CONTROLLER_PATH], process.env[Constants.ENV_ALERT_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_ALERT_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_ALERT_CONTROLLER_CLASSNAME]);
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_LOADING_CONTROLLER_PATH], process.env[Constants.ENV_LOADING_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_LOADING_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_LOADING_CONTROLLER_CLASSNAME]);
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_MODAL_CONTROLLER_PATH], process.env[Constants.ENV_MODAL_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_MODAL_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_MODAL_CONTROLLER_CLASSNAME]);
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_PICKER_CONTROLLER_PATH], process.env[Constants.ENV_PICKER_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_PICKER_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_PICKER_CONTROLLER_CLASSNAME]);
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_POPOVER_CONTROLLER_PATH], process.env[Constants.ENV_POPOVER_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_POPOVER_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_POPOVER_CONTROLLER_CLASSNAME]);
    attemptToPurgeUnusedProvider(context, purgeDependencyMap, process.env[Constants.ENV_TOAST_CONTROLLER_PATH], process.env[Constants.ENV_TOAST_VIEW_CONTROLLER_PATH], process.env[Constants.ENV_TOAST_COMPONENT_FACTORY_PATH], process.env[Constants.ENV_TOAST_CONTROLLER_CLASSNAME]);
}
function attemptToPurgeUnusedProvider(context, dependencyMap, providerPath, providerComponentPath, providerComponentFactoryPath, providerClassName) {
    if (dependencyMap.has(providerPath)) {
        // awwww yissssssss
        // first, get the content of the app module ngfactory file
        var appModuleNgFactoryPath = treeshake_1.getAppModuleNgFactoryPath();
        var file = context.fileCache.get(appModuleNgFactoryPath);
        if (!file) {
            return;
        }
        var updatedContent = treeshake_1.purgeComponentNgFactoryImportAndUsage(file.path, file.content, providerComponentFactoryPath);
        updatedContent = treeshake_1.purgeProviderControllerImportAndUsage(file.path, updatedContent, providerPath);
        context.fileCache.set(appModuleNgFactoryPath, { path: appModuleNgFactoryPath, content: updatedContent });
        // purge the provider name from the forRoot method providers list
        var indexFilePath = process.env[Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT];
        var ionicIndexFile = context.fileCache.get(indexFilePath);
        var newIndexFileContent = treeshake_1.purgeProviderClassNameFromIonicModuleForRoot(ionicIndexFile.content, providerClassName);
        // purge the component from the index file
        context.fileCache.set(indexFilePath, { path: indexFilePath, content: newIndexFileContent });
    }
}
function getConfig(context, configFile) {
    configFile = config_1.getUserConfigFile(context, taskInfo, configFile);
    var webpackConfig = config_1.fillConfigDefaults(configFile, taskInfo.defaultConfigFile);
    webpackConfig.entry = config_1.replacePathVars(context, webpackConfig.entry);
    webpackConfig.output.path = config_1.replacePathVars(context, webpackConfig.output.path);
    return webpackConfig;
}
exports.getConfig = getConfig;
var taskInfo = {
    fullArg: '--optimization',
    shortArg: '-dt',
    envVar: 'IONIC_DEPENDENCY_TREE',
    packageConfig: 'ionic_dependency_tree',
    defaultConfigFile: 'optimization.config'
};


text:
<?php
namespace Altair\Tests\Structure\Pair;

trait _empty
{
    public function testPropertyEmptyKey()
    {
        $pair = $this->getPair('a', 1);
        $this->assertFalse(empty($pair->key));
        $this->assertTrue(empty($pair->nope));

        $pair = $this->getPair(false, 1);
        $this->assertTrue(empty($pair->key));
    }

    public function testPropertyEmptyValue()
    {
        $pair = $this->getPair('a', 1);
        $this->assertFalse(empty($pair->value));
        $this->assertTrue(empty($pair->nope));

        $pair = $this->getPair('a', false);
        $this->assertTrue(empty($pair->value));
    }
}


text:
Google Play View Pager And Tabs Module

Copyright

This module is base on the android module from Astuetz with some changes

Thanks astuetz for greate solution.

Description

This module is like Google Play tabs and ViewPager whit:

Support RTL ( Right To Left )

Customizing color of ( Indicator, Underline, Text, Tabs Background, Separator )

Add or Remove tabs in runtime

Changed all color in runtime

Using custom font and style ( Appcelerator font object )

Set current tab ( only creation time yet )

show tabs in two style ( Scrolling, Adjust with screen width )

set padding

4 events supported ( Touch, Page Scrolled, Page Selected, Page Scroll State Changed )

Supported all UI element that it extends of View object except Ti.UI.Window ( ex. TextField, Button, View, Scroll View, etc. )

Set Tab height

supported android theme resource like Holo theme for all colors

if you like the module please donate.

BitCoint Address:
1NLwq7hGahzHHnsAAD6P7kZ9RSKk4ReBCH

Accessing the tabs Module

To access this module from JavaScript, you would do the following:

var module = require("com.navid.tabs");
var tabs = module.createPagerTabs();

The module variable is a reference to the Module object.

The tabs variable is a instance of viewpager

Reference

This module use https://github.com/astuetz/PagerSlidingTabStrip with some changes

Fork repository is here:
https://github.com/dreamlearn/PagerSlidingTabStrip

module.createPagerTabs

var win = Ti.UI.createWindow();
win.open();
var module = require('com.navid.tabs');
var tabs = tabs.createPagerTabs();
win.add(tabs);

module.property

tab ( Object)

color ( Text color )

colorResource ( Android resource string, ex. "holo_blue_dark" )

indicatorColor

indicatorResource

underlineColor

underlineResource

dividerColor

dividerResource

backgroundColor

backgroundResource

indicatorHeight

underlineHeight

dividerPadding

upperCase ( if set true all tabs title will show capital case, default is false )

shouldExpand ( if set true the width tabs adjusted with screen width, if set false the tab enabled scrolling. default is false )

padding  ( only right padding and left padding )

alignment ( module.ALIGNMENT_RIGHT or module.ALIGNMENT_LEFT, default is  module.ALIGNMENT_LEFT )

font ( same as Appcelerator font object )

views

array

[0]

title ( Title of tab )

view ( Object of Appcelerator view ( Button, Label, View, ImageView and etc... except Window )

current ( set current tab in first time, if alignment set with ALIGNMENT_RIGHT detects itself and select tab from right to left, ex. the 1 index is first tab in right )

The priority of color and color resource is with Color, if color not set use its resource if it set
ex.

{
   color: "red",
  colorResource: "holo_blue_light"
}

text will be red and colorResource will be ignored
}

Usage

var win = Ti.UI.createWindow();
win.open();

var tabs = require('com.navid.tabs');

var text = Ti.UI.createTableView({
    title: "NAVID",
    backgroundColor: "white",
    data: [
        {title: "1"},
        {title: "2"},
        {title: "3"},
        {title: "4"},
        {title: "5"}
    ]
});

var text2 = Ti.UI.createTableView({
    title: "NAVID",
    backgroundColor: "white",
    data: [
        {title: "1"},
        {title: "2"},
        {title: "3"},
        {title: "4"},
        {title: "5"},
        {title: "6"}
    ]
});

var text3 = Ti.UI.createTableView({
    title: "NAVID",
    backgroundColor: "white",
    data: [
        {title: "1"},
        {title: "2"}
    ]
});

var tabs = tabs.createPagerTabs({
    current: 4,
    tab: {
        indicatorResource: "holo_blue_light",
        colorResource: "holo_blue_light",
        backgroundColor: "white",
        alignment: tabs.ALIGNMENT_RIGHT
    },
    views: [
        {
            title: "Test1",
            view: text
        },
        {
            title: "Test2",
            view: text2
        },
        {
            title: "Test3",
            view: text3
        }
    ]
});

tabs.add("Dynamic Tab", Ti.UI.createLabel({text:"Label 1"}));
tabs.add("Dynamic Tab 2", Ti.UI.createLabel({text:"Position 2"}));

proxy.addEventListener(tabs.PAGE_SCROLLED_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});
proxy.addEventListener(tabs.PAGE_SELECTED_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});
proxy.addEventListener(tabs.PAGE_SCROLL_STATE_CHANGED_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});
proxy.addEventListener(tabs.CLICK_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});
proxy.addEventListener(tabs.LONG_CLICK_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});
proxy.addEventListener(tabs.TOUCH_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});
proxy.addEventListener(tabs.FOCUS_CHANGE_EVENT_NAME, function () {
    Ti.API.info("TAG: ", arguments.length, JSON.stringify(arguments));
});

win.add(tabs);

Author

Full Name: Navid Ghahramani

Email: ghahramani.navid@gmail.com

Please fill free to contact and share your idea with me ( Add new feature, fixing bug, get some help and etc... )

License

It's open source and it's under Apache licenses


text:
import faker from 'faker';

export const getFakeReduxFormProps = () => {
	return {
		input: {
			name: faker.lorem.word(),
			value: ""
		},
		meta: {
			visited: false,
			touched: false,
			active: false,
			asyncValidating: false,
			autofilled: false,
			dirty: false,
			error: "",
			invalid: false,
			pristine: true,
			submitting: false,
			valid: true
		}
	}
}


text:
namespace blink {

LayoutPagedFlowThread* LayoutPagedFlowThread::createAnonymous(Document& document, const LayoutStyle& parentStyle)
{
    LayoutPagedFlowThread* renderer = new LayoutPagedFlowThread();
    renderer->setDocumentForAnonymous(&document);
    renderer->setStyle(LayoutStyle::createAnonymousStyleWithDisplay(parentStyle, BLOCK));
    return renderer;
}

bool LayoutPagedFlowThread::needsNewWidth() const
{
    return progressionIsInline() != pagedBlockFlow()->style()->hasInlinePaginationAxis();
}

void LayoutPagedFlowThread::updateLogicalWidth()
{
    // As long as we inherit from LayoutMultiColumnFlowThread, we need to bypass its implementation
    // here. We're not split into columns, so the flow thread width will just be whatever is
    // available in the containing block.
    LayoutFlowThread::updateLogicalWidth();
}

void LayoutPagedFlowThread::layout()
{
    setProgressionIsInline(pagedBlockFlow()->style()->hasInlinePaginationAxis());
    LayoutMultiColumnFlowThread::layout();
}

} // namespace blink


text:
<?php

/** @var Ffcms\Templex\Template\Template $this */
/** @var $useCaptcha bool */
/** @var \Apps\Model\Front\User\FormPasswordChange $model */

$this->layout('_layouts/default', [
    'title' => __('Recovery password')
]);
?>

<?php $this->start('body') ?>

<?= __('Set / Recovery password') ?>

<?= $this->insert('user/_menu/tabs') ?>

<?php $form = $this->form($model) ?>
<?= $form->start() ?>

<?= $form->fieldset()->text('password', null, __('Enter new password for account: 8 or more symbols, chars & numbers, at least one uppercase symbol')) ?>
<?= $form->fieldset()->text('repassword', null, __('Repeat new password for your account')) ?>

<?= $this->insert('_core/form/fieldset/captcha', ['form' => $form]) ?>

<?= $form->button()->submit(__('Reset password'), ['class' => 'btn btn-primary']) ?>

<?= $form->stop() ?>

<?php $this->stop() ?>

<?php $this->push('javascript') ?>

<?php $this->stop() ?>


text:
"use strict";

global.SexMachine = class SexMachine {

  // The SexMachineFactory should be used to build the SexMachine. It's
  // responsible for determining the initial state of all the characters.
  constructor(data) {
    this._logger = new Logger('SexMachine', 'rgb(200,150,100)');
    this._logger.info('Starting Sex Machine');

    this._situation = data.situation || 'normal';
    this._player_id = Game.current.getPlayerID();
    this._commanding_id = data.commanding;
    this._characterStates = data.characterStates;
    this._characters = {};
    this._giving = data.giving;
    this._taking = data.taking;
    this._accessCache = {};
    this._actionCache = {};
    this._consentCache = {};
    this._clothesPile = {};
    this._fitCodes = {};

    each(this._characterStates, (state, id) => {
      let character = Character.find(id);

      this._characters[id] = character;
      this._accessCache[character.id] = AccessSupport.calculateAccess({ character:character });
      this.setMood(state, id, state.mood);
    });
  }

  get logger() { return this._logger; }

  getCharacterIDs() { return ObjectUtility.keys(this._characterStates); }
  getCharacterCount() { return this.getCharacterIDs().length; }
  getPlayerState() { return this._characterStates[this._player_id]; }
  getPlayer() { return this.getCharacter(this._player_id); }
  getCharacterStates() { return this._characterStates; }
  getCharacterState(id) { return this._characterStates[id]; }
  getCharacters() { return this._characters; }
  getCharacter(id) { return this._characters[id]; }
  getSituation() { return this._situation; }

  availableActions() { return SexMachine.Actions.availableActions(this); }
  availableItemActions() { return SexMachine.Actions.availableItemActions(this); }
  getFitCode(actionCode) { return this._fitCodes[actionCode]; }
  setFitCode(actionCode, fitCode) { this._fitCodes[actionCode] = fitCode; }

  getCachedActions(key) { return this._actionCache[key]; }
  setCachedActions(key, actions) { this._actionCache[key] = actions; }
  clearCachedActions() { this._actionCache = {}; }

  cacheConsent(code, consent) { this._consentCache[code] = consent; }
  recallConsent(code) { return this._consentCache[code]; }
  clearConsentCache() { this._consentCache = {}; }

  getCommanding() {
    if (this._commanding_id) { return this.getCharacter(this._commanding_id); }

    if (this._commanding_id == null) {
      if (this.getPlayerState().role != 'bottom') {
        this.logger.info(`Commander set to Player`);
        this._commanding_id = this._player_id;
      }
    }

    if (this._commanding_id == null) {
      each(this.getCharacterStates(), (state, id) => {
        if (this._commanding_id == null && state.role == 'top') {
          this.logger.info(`Commander set to first top [${id}]`);
          this._commanding_id = id;
        }
      });
    }

    if (this._commanding_id == null) {
      each(this.getCharacterStates(), (state, id) => {
        if (this._commanding_id == null && state.role == 'switch') {
          this.logger.info(`Commander set to first switch [${id}]`);
          this._commanding_id = id;
        }
      });
    }

    if (this._commanding_id) {
      return this.getCommanding();
    }
  }

  // ===========================================================================
  // Posture | Giving and Taking
  // ===========================================================================

  removeFromGiving(id) { ArrayUtility.remove(this._giving, id); }
  removeFromTaking(id) { ArrayUtility.remove(this._taking, id); }
  isGiving(id) { return this._giving.indexOf(id) >= 0 }
  isTaking(id) { return this._taking.indexOf(id) >= 0 }
  getGiving() { return this._giving; }
  getTaking() { return this._taking; }

  clearGiveAndTake() {
    this._giving = [];
    this._taking = [];
  }

  addToGiving(id) {
    if (this.isTaking(id)) { this.removeFromTaking(id); }
    if (this.isGiving(id) == false) {
      this._giving.push(id);
    }
  }

  addToTaking(id) {
    if (this.isGiving(id)) { this.removeFromGiving(id); }
    if (this.isTaking(id) == false) {
      this._taking.push(id);
    }
  }

  postureCode() {
    if (this._giving.length == 0 && this._taking.length == 0) { return 'empty'; }
    if (this._giving.length == 0) { return 'taking-waiting'; }

    // A character acting alone with either be acting of their own volition,
    // or if they're in the bottom role, will be doing as told by the commander.
    if (this._giving.length == 1 && this._taking.length == 0) {
      return (this.getCharacterState(this._giving[0]).role == 'bottom') ? 'solo-told' : 'solo';
    }

    // If all the characters giving are in the bottom role, then they are all
    // being told to act. If the commander is not acting then they are being
    // directed to act by the commander, otherwise they are being told to act
    // by at least one of the takers.
    if (this.allGivingAreBottom()) {
      if (this._taking.length == 0) { return 'solo-told'; }
      return (this.isCommanderActing() == false) ? 'directed' : 'told'
    }

    // There must be a mix of characters, rather than having them all do solo
    // actions, which could be confusing, have them wait for a target.
    if (this._taking.length == 0) { return 'giving-waiting' }

    // At this point treat the action as being in the normal posture, even if
    // some characters are tops or bottoms.
    return 'normal';
  }

  isSolo() {
    return ['solo-told','solo'].indexOf(this.postureCode()) >= 0;
  }

  isCommanderActing() {
    return this.isGiving(this._commanding_id) || this.isTaking(this._commanding_id);
  }

  allTakingAreBottom() {
    let roles = this._taking.map((id) => { return this.getCharacterState(id).role });
    return (roles.indexOf('top') == -1) && (roles.indexOf('switch') == -1);
  }

  allGivingAreBottom() {
    let roles = this._giving.map((id) => { return this.getCharacterState(id).role });
    return (roles.indexOf('top') == -1) && (roles.indexOf('switch') == -1);
  }

  // ===========================================================================
  // Mood
  // ===========================================================================

  setPlayerMood(mood) {
    this.setMood(this.getPlayerState(), this._player_id, mood);
  }

  setCharacterMood(id, mood) {
    this.setMood(this.getCharacterState(id), id, mood);
  }

  // TODO: Mood change should also change the commander.

  setMood(state, id, mood) {
    state.mood = mood;
    state.consentBaseline = MoodSupport.lookup(mood).consentBaseline;
    this.logger.info(`Setting Mood [${id}] > ${mood}`);

    if (MoodSupport.lookup(mood).canGive && state.role == 'bottom') {
      this.logger.info(`New mood now allows character to act if they wish.`);
      state.role = state.defaultPosition || 'switch';
    }
    if (MoodSupport.lookup(mood).canGive == false && state.role != 'bottom') {
      this.logger.info(`New mood prevents character from acting and are being forced to bottom.`);
      state.role = 'bottom';
      if (this.isGiving(id)) {
        this.removeFromGiving(id);
        this.addToTaking(id);
      }
    }
  }

  // ===========================================================================
  // Equipment
  // ===========================================================================

  // Sex Actions that modify what a character is using or wearing should go
  // though these methods rather than the character's loadout directly. Any
  // clothing changes made during a sex scene should be reverted after the
  // scene. All usable equipment is non persistant.

  getAccess(character) { return this._accessCache[character.id] || {}; }
  getClothesPile() { return this._clothesPile; }

  canWearEquipment(equipment, character, options) {
    return character.getLoadout().canWear(equipment, this.getAccess(character), options);
  }

  canUseEquipment(equipment, character, options) {
    return character.getLoadout().canUse(equipment, this.getAccess(character), options);
  }

  wearEquipment(equipment, character, options = {}) {
    character.getLoadout().wear(equipment, this.getAccess(character), extend(options, { persistant:false }));
    this._accessCache[character.id] = AccessSupport.calculateAccess({ character:character });
  }

  useEquipment(equipment, character) {
    character.getLoadout().use(equipment, this.getAccess(character));
    this._accessCache[character.id] = AccessSupport.calculateAccess({ character:character });
  }

  // TODO: When removing an item of clothing we should allow an event or
  //       message to be queued that describe the removal.
  removeEquipment(equipment, character) {
    let loadout = character.getLoadout();
    let state = loadout.getState(equipment.id);
    if (state.persistant) {
      if (this._clothesPile[character.id] == null) { this._clothesPile[character.id] = {}; }
      this._clothesPile[character.id][equipment.id] = { wornOn:state.wornOn };
    }
    loadout.remove(equipment);
    this._accessCache[character.id] = AccessSupport.calculateAccess({ character:character });
  }

  // The revert function first loops through the current equipment, removing
  // anything not persistantly equipped and all usable equipment. Then all of
  // the equipment in the clothes pile is reapplied to the original character
  // in the original slot.
  revertEquipment() {
    each(this.getCharacters(), (character) => {
      each(character.getLoadout().getEquipment(), (equipmentState, equipmentID) => {
        if (equipmentState.persistant == false || equipmentState.usedIn) {
          character.getLoadout().remove(equipmentID);
        }
      });
    });

    each(this.getClothesPile(), (pile, characterID) => {
      each(pile, (state, equipmentID) => {
        this.getCharacter(characterID).getLoadout().wear(equipmentID, {}, state);
      });
    });
  }

  // This function is used by the availableActions() function to get the used
  // equipment if there is currently a single giver selected. Currently I'm
  // only allowing equipment actions to have a single giver. One item, one
  // person using that item. I think most equipment actions will be persistant
  // at least, so you can still have four people fucking someone with four
  // dildos, but each action has to be applied individually.
  getEquipmentUsedBySingleGiver() {
    if (this.getGiving().length == 1) {
      let equipmentID = this.getCharacter(this.getGiving()[0]).getLoadout().getUsed();
      if (equipmentID != null) {
        return Equipment.find(equipmentID);
      }
    }
    return null;
  }

  // ===========================================================================
  // Execute Actions
  // ===========================================================================

  setCurrentAction(action) { this._currentAction = action; }
  getCurrentAction() { return this._currentAction; }

  setCurrentConsent(consent) { this._currentConsent = consent; }
  hasCurrentConsent() { return this._currentConsent; }
  getCurrentConsentMode() { return this._currentConsent ? 'consent' : 'rape'; }

  setCurrentAccessMap(access) { this._currentAccess = access; }
  getCurrentAccessMap() { return this._currentAccess; }
  getCurrentAccess(id) { return this._currentAccess[id]; }

  setCurrentResults(results) { this._currentResults = results; }
  getCurrentResults() { return this._currentResults; }

  executeAction(action, continuous, consent) {
    this.setCurrentAction(action);
    this.setCurrentConsent(consent);
    this.setCurrentAccessMap(AccessSupport.applyAccess(this, action))
    this.setCurrentResults(SexMachine.Results.determineResults(this, action));

    each(this.getCurrentResults(), (result) => {
      let character = this.getCharacter(result.getReceiver());
      each(result.getRewards(), (value, code) => {
        this._characterStates[character.id].orbs[code] += value;
      });
    });

    this.clearConsentCache();
    this.clearCachedActions();
  }

}


text:
package panda.interpreter.syntax.type;

import org.jetbrains.annotations.Nullable;
import panda.interpreter.architecture.module.Imports;
import panda.interpreter.architecture.type.Reference;
import panda.interpreter.architecture.type.signature.GenericSignature;
import panda.interpreter.architecture.type.signature.Relation;
import panda.interpreter.architecture.type.signature.Signature;
import panda.interpreter.architecture.type.signature.TypedSignature;
import panda.interpreter.parser.Context;
import panda.interpreter.parser.Contextual;
import panda.interpreter.parser.PandaParserFailure;
import panda.interpreter.parser.Parser;
import panda.interpreter.token.PandaSourceStream;
import panda.interpreter.token.Snippet;
import panda.interpreter.token.SourceStream;
import panda.interpreter.resource.syntax.separator.Separators;
import panda.interpreter.syntax.PandaSourceReader;
import panda.std.Option;
import panda.std.Pair;
import panda.std.Result;

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

public final class SignatureParser implements Parser {

    @Override
    public String name() {
        return "signature";
    }

    public Signature parse(Contextual<?> contextual, SignatureSource signatureSource, boolean root, @Nullable Signature signatureContextValue) {
        Context<?> context = contextual.toContext();
        Imports imports = context.getImports();

        Option<Signature> signatureContext = Option.of(signatureContextValue);
        String name = signatureSource.getName().getValue();

        Result<Reference, Signature> type = imports.forType(name)
                .map(importedType -> {
                    //noinspection Convert2MethodRef
                    return Result.<Reference, Signature> ok(importedType);
                })
                .orElseGet(() -> {
                    if (!name.equals(name.toUpperCase())) {
                        throw new PandaParserFailure(context, signatureSource.getName(), "Abstract generic name has to be declared uppercase");
                    }

                    Signature signature = signatureContext
                            .flatMap(ctx -> ctx.findGeneric(name))
                            .map(Pair::getSecond)
                            .orElseGet(() -> new GenericSignature(context.getTypeLoader(), signatureContextValue, name, null, new Signature[0], Relation.DIRECT, signatureSource.getName()));

                    return Result.error(signature);
                });

        Signature subParent = (!root && signatureContext.isEmpty() && type.isOk())
                ? type.get().fetchType().getSignature()
                : signatureContextValue;

        Signature[] generics = signatureSource.getGenerics().stream()
                .map(genericSignature -> parse(context, genericSignature, root, signatureContextValue))
                .toArray(Signature[]::new);

        return type
                .map(reference -> (Signature) new TypedSignature(subParent, reference, generics, Relation.DIRECT, signatureSource.getName()))
                .orElseGet(genericSignature -> genericSignature);
    }

    public List<SignatureSource> readSignatures(Snippet source) {
        Snippet[] sources = source.split(Separators.COMMA);
        List<SignatureSource> signatures = new ArrayList<>((source.size() / 3) + 1);

        for (Snippet signatureSource : sources) {
            SourceStream signatureSourceStream = new PandaSourceStream(signatureSource);
            PandaSourceReader signatureReader = new PandaSourceReader(signatureSourceStream);

            signatures.add(signatureReader.readSignature().orThrow(() -> {
                throw new PandaParserFailure(source, signatureSource, "Invalid signature");
            }));
        }

        return signatures;
    }

}


text:
module Algorithmable
  module Cache
    autoload :Imp, 'algorithmable/cache/imp'
    autoload :Methods, 'algorithmable/cache/methods'
    autoload :PrimitiveMinHeap, 'algorithmable/cache/primitive_min_heap'
    autoload :PrimitiveMaxHeap, 'algorithmable/cache/primitive_max_heap'

    private_constant :Imp

    def new_lru_cache(size, heap = PrimitiveMaxHeap.new)
      Imp.new size, heap
    end

    def new_mru_cache(size, heap = PrimitiveMinHeap.new)
      Imp.new size, heap
    end
  end
end


text:
import unittest
from six import string_types
from pandas.core.series import Series

from opengrid.library.belpex import *

class BelpexTest(unittest.TestCase):
    """
    Class for testing the belpex web scraper
    """

    def setUp(self):
        self.website = fetch_website(date=dt.datetime.today())

    def test_fetch_website(self):
        self.assertIsInstance(self.website, string_types)

    def test_parse_html(self):
        parsed = parse_html(self.website)
        self.assertIsInstance(parsed, tuple)

        dates, values = parsed
        self.assertIsInstance(dates, list)
        self.assertIsInstance(values, list)
        self.assertEqual(len(dates), len(values))
        self.assertIsInstance(dates[0], dt.datetime)
        self.assertIsInstance(values[0], float)

        website_err = fetch_website(date=dt.datetime.today() + dt.timedelta(days=5))
        with self.assertRaises(KeyError):
            parse_html(website_err)

    def test_get_belpex_day(self):
        series = get_belpex_day(date=dt.datetime.today())
        self.assertIsInstance(series, Series)

        self.assertIsNone(get_belpex_day(date=dt.datetime.today() + dt.timedelta(days=5)))

    def test_get_belpex(self):
        series = get_belpex(start=dt.datetime.today() - dt.timedelta(days=1), end=dt.datetime.today())
        self.assertIsInstance(series, Series)

if __name__ == '__main__':
    unittest.main()


text:
package cn.eoe.FileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
public class SDFileHandle {
	private static String SDPath=Environment.getExternalStorageDirectory().
			getAbsolutePath();
	/**
	 * 判断SD卡是否可用
	 * @return
	 */
	public static boolean SDCanOperate(){
		// SD Card Ready

        if (Environment.getExternalStorageState().
        		equals(Environment.MEDIA_MOUNTED)) {
        		return true;
        }
        else{
        	return false;

        }
	}
	 /**
     * 获取程序私有路径
     * @return
     */
    public static String getDataPath(){
    	return "/data/data/com.main.jiami/temp";
    }
	/**
	 * 判断文件路径是否在SD卡中
	 * @param filename
	 * @return
	 */
    public static boolean FileInSD(String filename){
    	return filename.startsWith(
    			Environment.getExternalStorageDirectory().
    			getAbsolutePath());
    }
    /**
     * 获取SD卡根路径
     * @return
     */
    public static String getSDPath(){
    	return SDPath;
    }

    /**
	*
	* @param path 文件夹路径
	* 判断文件夹是否存在,如果不存在则创建文件夹
	*/
	public static void isExist(String path) {
	File file = new File(path);
	//判断文件夹是否存在,如果不存在则创建文件夹
	if (!file.exists()) {
	file.mkdir();
	}
	}

	 /**
	  *    * 创建文件       *
	  *         * @throws IOException
	  *              */
	public static File creatFile(String fileName) throws IOException {
		File file = new File(fileName);
		file.createNewFile();
		return file;
		}
	/**
	 *    * 删除文件       *
	 *       * @param fileName
	 *          */
	public static boolean delFile(String fileName) {
		File file = new File(fileName);
		if (file == null || !file.exists() || file.isDirectory())
			return false;
		file.delete();
		return true;
		}
	/**
	 *  * 创建目录       *
	 *       * @param dirName
	 *        */
	public static File creatDir(String dirName) {
		File dir = new File(dirName);
		dir.mkdir();
		return dir;
		}
	/**
	 *  * 修改文件或目录名       * @param fileName
	 *        */
	public boolean renameSDFile(String oldfileName, String newFileName) {
		File oleFile = new File(SDPath+"//"+oldfileName);
		File newnewFile = new File(SDPath+"//"+newFileName);
		return oleFile.renameTo(newnewFile);
		}

	 /* 删除一个文件       *
	  *  * @param file
	  *      * @return
	  *           */
	public boolean delSDFile(File file) {
		if (file.isDirectory())
			return false;
		return file.delete();
		}
	/**
	 *   * 删除一个目录(可以是非空目录)
	 *      * @param dir
	 *         */
	public boolean delSDDir(File dir) {
		if (dir == null || !dir.exists() || dir.isFile()) {
            return false;
            }
		for (File file : dir.listFiles()) {
			if (file.isFile()) {
				file.delete();
				} else if (file.isDirectory()) {
					delSDDir(file);
					// 递归
					}
					}
			dir.delete();
			return true;
			}

	 public static void writeFile(String fileName,byte[] data) throws IOException{
	        //FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

	       FileOutputStream fout = new FileOutputStream(fileName);
	        fout.write(data);
	         fout.close();
	   }

}


text:
/*******************************************************************************
 * \file attitude_error_estimator.c
 *
 * \author MAV'RIC Team
 * \author Julien Lecoeur
 *
 * \brief A quaternion-based attitude-error estimator, takes a reference
 * quaternion as input and provides angular errors for roll, pitch and yaw in
 * the local frame.
 *
 * \details  WARNING: For optimisation purpose, the computed errors are not in
 * radians:
 * With \f$ e_{roll} , e_{pitch}, e_{yaw} \f$ the true errors in radians around
 * the local roll, pitch and yaw axes,
 * this estimator returns
 * \f$ 2.sin( e_{roll} / 2 ), 2.sin( e_{pitch} / 2 ), 2.sin( e_{yaw} / 2 ) \f$
 *
 * For small angular errors, this approximation is sensible.
 *
 ******************************************************************************/

#include "attitude_error_estimator.h"
#include "coord_conventions.h"

void attitude_error_estimator_init(attitude_error_estimator_t* estimator, const ahrs_t* ahrs)
{
	// Init ref to quat_attitude
	estimator->ahrs = ahrs;

	// Init quat_ref
	estimator->quat_ref.s = 1;
	estimator->quat_ref.v[0] = 0;
	estimator->quat_ref.v[1] = 0;
	estimator->quat_ref.v[2] = 0;

	// Init output
	estimator->rpy_errors[0] = 0;
	estimator->rpy_errors[1] = 0;
	estimator->rpy_errors[2] = 0;
}

void attitude_error_estimator_set_quat_ref(attitude_error_estimator_t* estimator, const quat_t quat_ref)
{
	estimator->quat_ref = quat_ref;
}

void attitude_error_estimator_set_quat_ref_from_aero(attitude_error_estimator_t* estimator, const aero_attitude_t aero)
{
	estimator->quat_ref = coord_conventions_quaternion_from_aero(aero);
}

void attitude_error_estimator_set_quat_ref_from_rpy(attitude_error_estimator_t* estimator, const float rpy[3])
{
	aero_attitude_t aero;
	aero.rpy[0] = rpy[0];
	aero.rpy[1] = rpy[1];
	aero.rpy[2] = rpy[2];

	estimator->quat_ref = coord_conventions_quaternion_from_aero(aero);
}

void attitude_error_estimator_update(attitude_error_estimator_t* estimator)
{
	quat_t quat_attitude = estimator->ahrs->qe;
	quat_t quat_ref = estimator->quat_ref;
	quat_t quat_error;

	// Compute quaternioin error in global frame
	quat_error = quaternions_multiply(quat_ref, quaternions_inverse(quat_attitude));

	// Express error in local coordinates
	quat_error = quaternions_multiply(	quaternions_inverse(quat_attitude),
										quaternions_multiply(quat_error,
															 quat_attitude)  );

	// Find shortest rotation
	if (quat_error.s < 0)
	{
		quat_error = quaternions_inverse(quat_error);
	}

	// Approximate roll pitch and yaw errors with quat_error vector part
	estimator->rpy_errors[0] = 2 * quat_error.v[0];
	estimator->rpy_errors[1] = 2 * quat_error.v[1];
	estimator->rpy_errors[2] = 2 * quat_error.v[2];
}


text:
<?php

namespace Magento\Customer\Controller\Account;

use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Exception\State\InvalidTransitionException;

class Confirmation extends \Magento\Customer\Controller\AbstractAccount
{
    /** @var StoreManagerInterface */
    protected $storeManager;

    /** @var AccountManagementInterface  */
    protected $customerAccountManagement;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Context $context
     * @param Session $customerSession
     * @param PageFactory $resultPageFactory
     * @param StoreManagerInterface $storeManager
     * @param AccountManagementInterface $customerAccountManagement
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        PageFactory $resultPageFactory,
        StoreManagerInterface $storeManager,
        AccountManagementInterface $customerAccountManagement
    ) {
        $this->session = $customerSession;
        $this->resultPageFactory = $resultPageFactory;
        $this->storeManager = $storeManager;
        $this->customerAccountManagement = $customerAccountManagement;
        parent::__construct($context);
    }

    /**
     * Send confirmation link to specified email
     *
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        if ($this->session->isLoggedIn()) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*/');
            return $resultRedirect;
        }

        // try to confirm by email
        $email = $this->getRequest()->getPost('email');
        if ($email) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();

            try {
                $this->customerAccountManagement->resendConfirmation(
                    $email,
                    $this->storeManager->getStore()->getWebsiteId()
                );
                $this->messageManager->addSuccess(__('Please check your email for confirmation key.'));
            } catch (InvalidTransitionException $e) {
                $this->messageManager->addSuccess(__('This email does not require confirmation.'));
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Wrong email.'));
                $resultRedirect->setPath('*/*/*', ['email' => $email, '_secure' => true]);
                return $resultRedirect;
            }
            $this->session->setUsername($email);
            $resultRedirect->setPath('*/*/index', ['_secure' => true]);
            return $resultRedirect;
        }

        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getLayout()->getBlock('accountConfirmation')->setEmail(
            $this->getRequest()->getParam('email', $email)
        );
        return $resultPage;
    }
}