text:
/*                                                                      *\
** Squants                                                              **
**                                                                      **
** Scala Quantities and Units of Measure Library and DSL                **
** (c) 2013-2015, Gary Keorkunian                                       **
**                                                                      **
\*                                                                      */

package squants.time

import squants._

import scala.concurrent.duration.{ DAYS, Duration, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, SECONDS }
import scala.language.implicitConversions

/**
 * Represents a quantity of Time
 *
 * @author  garyKeorkunian
 * @since   0.1
 *
 * @param value value in [[squants.time.Milliseconds]]
 */
final class Time private (val value: Double, val unit: TimeUnit)
    extends Quantity[Time] {

  def dimension = Time

  def millis = toMilliseconds.toLong

  def *[A <: squants.Quantity[A] with squants.time.TimeIntegral[_]](that: TimeDerivative[A]): A = that * this

  def *(that: Time) = TimeSquared(this, that)
  def squared = TimeSquared(this)

  def toNanoseconds = to(Nanoseconds)
  def toMicroseconds = to(Microseconds)
  def toMilliseconds = to(Milliseconds)
  def toSeconds = to(Seconds)
  def toMinutes = to(Minutes)
  def toHours = to(Hours)
  def toDays = to(Days)
}

object Time extends Dimension[Time] with BaseDimension {
  val NanosecondsPerSecond = 1.0e9
  val MicrosecondsPerSecond = 1.0e6
  val MillisecondsPerNanosecond = 1.0e-6
  val MillisecondsPerMicrosecond = 1.0e-3
  val MillisecondsPerSecond = 1e3
  val MillisecondsPerMinute = MillisecondsPerSecond * 60d
  val MillisecondsPerHour = MillisecondsPerMinute * 60d
  val MillisecondsPerDay = MillisecondsPerHour * 24d
  val SecondsPerMinute = 60d
  val SecondsPerHour = SecondsPerMinute * 60d
  val SecondsPerDay = SecondsPerHour * 24
  val MinutesPerHour = 60d
  val HoursPerDay = 24d

  private[time] def apply[A](n: A, unit: TimeUnit)(implicit num: Numeric[A]) = new Time(num.toDouble(n), unit)
  def apply = parse _
  def apply(duration: Duration): Time = duration.unit match {
    case NANOSECONDS  ⇒ Nanoseconds(duration.length)
    case MICROSECONDS ⇒ Microseconds(duration.length)
    case MILLISECONDS ⇒ Milliseconds(duration.length)
    case SECONDS      ⇒ Seconds(duration.length)
    case MINUTES      ⇒ Minutes(duration.length)
    case HOURS        ⇒ Hours(duration.length)
    case DAYS         ⇒ Days(duration.length)
  }

  def name = "Time"
  def primaryUnit = Milliseconds
  def siUnit = Seconds
  def units = Set(Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days)
  def dimensionSymbol = "T"
}

trait TimeUnit extends UnitOfMeasure[Time] with UnitConverter {
  def apply[A](n: A)(implicit num: Numeric[A]) = Time(n, this)
}

object Nanoseconds extends TimeUnit {
  val conversionFactor = Milliseconds.conversionFactor / Time.MicrosecondsPerSecond
  val symbol = "ns"
}

object Microseconds extends TimeUnit {
  val conversionFactor = Milliseconds.conversionFactor / Time.MillisecondsPerSecond
  val symbol = "µs"
}

object Milliseconds extends TimeUnit with PrimaryUnit {
  val symbol = "ms"
}

object Seconds extends TimeUnit with SiBaseUnit {
  val conversionFactor = Milliseconds.conversionFactor * Time.MillisecondsPerSecond
  val symbol = "s"
}

object Minutes extends TimeUnit {
  val conversionFactor = Seconds.conversionFactor * Time.SecondsPerMinute
  val symbol = "m"
}

object Hours extends TimeUnit {
  val conversionFactor = Minutes.conversionFactor * Time.MinutesPerHour
  val symbol = "h"
}

object Days extends TimeUnit {
  val conversionFactor = Hours.conversionFactor * Time.HoursPerDay
  val symbol = "d"
}

object TimeConversions {
  lazy val nanosecond = Nanoseconds(1)
  lazy val microsecond = Microseconds(1)
  lazy val millisecond = Milliseconds(1)
  lazy val second = Seconds(1)
  lazy val minute = Minutes(1)
  lazy val halfHour = Minutes(30)
  lazy val hour = Hours(1)
  lazy val day = Days(1)

  implicit class TimeConversions[A](n: A)(implicit num: Numeric[A]) {
    def nanoseconds = Nanoseconds(n)
    def microseconds = Microseconds(n)
    def milliseconds = Milliseconds(n)
    def seconds = Seconds(n)
    def minutes = Minutes(n)
    def hours = Hours(n)
    def days = Days(n)
  }

  implicit class TimeStringConversions(s: String) {
    def toTime = Time(s)
  }

  implicit object TimeNumeric extends AbstractQuantityNumeric[Time](Time.primaryUnit)

  /**
   * Converts a Squants Time to Scala Duration
   *
   * NOTE - Because Scala Durations require a Long, the Squants Time value most be converted / rounded
   *
   * @param time
   * @return
   */
  implicit def timeToScalaDuration(time: Time): Duration = time.unit match {
    case Nanoseconds  ⇒ Duration(time.value.toLong, NANOSECONDS)
    case Microseconds ⇒ Duration(time.value.toLong, MICROSECONDS)
    case Milliseconds ⇒ Duration(time.value.toLong, MILLISECONDS)
    case Seconds      ⇒ Duration(time.value.toLong, SECONDS)
    case Minutes      ⇒ Duration(time.value.toLong, MINUTES)
    case Hours        ⇒ Duration(time.value.toLong, HOURS)
    case Days         ⇒ Duration(time.value.toLong, DAYS)
  }

  implicit def scalaDurationToTime(duration: Duration): Time = Time(duration)
}


text:
package controller

import (
	"testing"
	"time"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/kubernetes/fake"
	clientgotesting "k8s.io/client-go/testing"
	kapi "k8s.io/kubernetes/pkg/apis/core"

	"github.com/openshift/origin/pkg/security"
	"github.com/openshift/origin/pkg/security/uid"
)

type fakeRange struct {
	Err       error
	Range     *kapi.RangeAllocation
	Updated   *kapi.RangeAllocation
	UpdateErr error
}

func (r *fakeRange) Get() (*kapi.RangeAllocation, error) {
	return r.Range, r.Err
}

func (r *fakeRange) CreateOrUpdate(update *kapi.RangeAllocation) error {
	r.Updated = update
	return r.UpdateErr
}

func TestRepair(t *testing.T) {
	client := &fake.Clientset{}
	client.AddReactor("*", "*", func(a clientgotesting.Action) (bool, runtime.Object, error) {
		list := &v1.NamespaceList{
			Items: []v1.Namespace{
				{ObjectMeta: metav1.ObjectMeta{Name: "default"}},
			},
		}
		return true, list, nil
	})

	alloc := &fakeRange{
		Range: &kapi.RangeAllocation{},
	}

	uidr, _ := uid.NewRange(10, 20, 2)
	repair := NewRepair(0*time.Second, client.Core().Namespaces(), uidr, alloc)

	err := repair.RunOnce()
	if err != nil {
		t.Fatal(err)
	}
	if alloc.Updated == nil {
		t.Fatalf("did not store range: %#v", alloc)
	}
	if alloc.Updated.Range != "10-20/2" {
		t.Errorf("didn't store range properly: %#v", alloc.Updated)
	}
	if len(alloc.Updated.Data) != 0 {
		t.Errorf("data wasn't empty: %#v", alloc.Updated)
	}
}

func TestRepairIgnoresMismatch(t *testing.T) {
	client := &fake.Clientset{}
	client.AddReactor("*", "*", func(a clientgotesting.Action) (bool, runtime.Object, error) {
		list := &v1.NamespaceList{
			Items: []v1.Namespace{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:        "default",
						Annotations: map[string]string{security.UIDRangeAnnotation: "1/5"},
					},
				},
			},
		}
		return true, list, nil
	})

	alloc := &fakeRange{
		Range: &kapi.RangeAllocation{},
	}

	uidr, _ := uid.NewRange(10, 20, 2)
	repair := NewRepair(0*time.Second, client.Core().Namespaces(), uidr, alloc)

	err := repair.RunOnce()
	if err != nil {
		t.Fatal(err)
	}
	if alloc.Updated == nil {
		t.Fatalf("did not store range: %#v", alloc)
	}
	if alloc.Updated.Range != "10-20/2" {
		t.Errorf("didn't store range properly: %#v", alloc.Updated)
	}
	if len(alloc.Updated.Data) != 0 {
		t.Errorf("data wasn't empty: %#v", alloc.Updated)
	}
}

redpajama_set_name: RedPajamaGithub


text:
"""The command to install/update gcloud components."""

from googlecloudsdk.calliope import base

class Reinstall(base.SilentCommand):
  """Reinstall the Cloud SDK with the same components you have now.

  If your Cloud SDK installation becomes corrupt, this command attempts to fix
  it by downloading the latest version of the Cloud SDK and reinstalling it.
  This will replace your existing installation with a fresh one.  The command is
  the equivalent of deleting your current installation, downloading a fresh
  copy of the SDK, and installing in the same location.
  """

  @staticmethod
  def Args(parser):
    pass

  def Run(self, args):
    """Runs the list command."""
    self.group.update_manager.Reinstall()


text:
import os
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import numpy as np
import cv2
import rospy
import roslib
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image

authorizer = None
handler = None
server = None

left_cam_pub = None
right_cam_pub = None
bridge = CvBridge()

pixels_encoding = "mono8"

def publish_image_left_cam(img):
    global left_cam_pub, bridge
    try:
        left_cam_pub.publish(bridge.cv2_to_imgmsg(img, pixels_encoding))
    except CvBridgeError as e:
        rospy.loginfo(e)

def publish_image_right_cam(img):
    global right_cam_pub, bridge
    try:
        right_cam_pub.publish(bridge.cv2_to_imgmsg(img, pixels_encoding))
    except CvBridgeError as e:
        rospy.loginfo(e)

class CamerasFTPHandler(FTPHandler):
    def on_file_received(self, file):
        # print("Hey! File received. Name:")
        # print(file)
        img = cv2.imread(file, 0)
        if (img is not None):
            if("img_left" in file):
                rospy.loginfo("Left camera image")
                publish_image_left_cam(img)

            elif ("img_right" in file):
                rospy.loginfo("Right camera image")
                publish_image_right_cam(img)

    def on_incomplete_file_received(self, file):
        rospy.loginfo("Hey! Incomplete file received. Name:" + file)
        os.remove(file)

def start_FTP_server():
    global authorizer, handler, server

    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = DummyAuthorizer()

    # Define two users with full r/w permissions, one for each camera
    user_home_folder = os.getenv("HOME")
    authorizer.add_user('right_cam', 'yumiPC', user_home_folder, perm='elradfmwM')
    authorizer.add_user('left_cam', 'yumiPC', user_home_folder, perm='elradfmwM')

    # Instantiate FTP handler class
    handler = CamerasFTPHandler
    handler.authorizer = authorizer

    # Define a customized banner (string returned when client connects)
    handler.banner = "pyftpdlib based ftpd ready."
    handler.permit_privileged_ports = True

    # Instantiate FTP server class and listen on 0.0.0.0:2121
    address = ('192.168.125.50', 2121)
    server = FTPServer(address, handler)

    # set a limit for connections
    server.max_cons = 512
    server.max_cons_per_ip = 0      # 0 == no limit

    rospy.loginfo("FTP server ready, listening on Port 21")
    # start ftp server
    server.serve_forever()

def close_FTP_server():
    global server
    server.close_all()

def main():
    global left_cam_pub, right_cam_pub, server
    rospy.init_node("YumiCamerasNode", anonymous=False)
    rospy.on_shutdown(close_FTP_server)

    left_cam_pub = rospy.Publisher("/yumi/left_cam_image", Image, queue_size=1)
    right_cam_pub = rospy.Publisher("/yumi/right_cam_image", Image, queue_size=1)

    rospy.loginfo("Starting FTP server")

    start_FTP_server()

if __name__ == '__main__':
    main()


text:
import { DatabaseClient } from 'marklogic';
export interface Meta {
}
export interface Relations {
}
export interface RelatedViews {
}
export interface PrivilegeInfo {
    id: string;
    name: string;
    meta: Meta;
    relations: Relations;
    'related-views': RelatedViews;
}
export declare function getRole(client: DatabaseClient, name: string): Promise<PrivilegeInfo>;


text:
namespace ModelMatcher.Assertions.Tests.Collections
{
    using System;
    using System.Collections.Generic;
    using Shouldly;
    using Xunit;

    public partial class Collections
    {
        public class ConditionalMatching_NonDefaultsMatch
        {
            [Fact]
            public void Should_Not_Throw_If_Match_Found_And_No_Conditions()
            {
                // Given
                const string guidString = "49934b49-1cc3-443d-a89a-23496708f64b";
                var list = new List<SimpleModel>
                {
                    new SimpleModel
                    {
                        DecimalProperty = 456,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 678,
                        StringProperty = "Goodbye, World",
                        BoolProperty = false
                    },
                    new SimpleModel
                    {
                        DecimalProperty = 123,
                        GuidProperty = Guid.Parse(guidString),
                        IntProperty = 345,
                        StringProperty = "Hello, World",
                        BoolProperty = true
                    }
                };

                // When
                var expectedModel = new SimpleModel
                {
                    DecimalProperty = 123,
                    GuidProperty = Guid.Parse(guidString),
                    IntProperty = 345,
                    StringProperty = default(string),
                    BoolProperty = true
                };

                // Then
                Should.NotThrow(() => list.ShouldContainAMatchOfNonDefaultProperties(expectedModel, new List<Condition>()));
            }

            [Fact]
            public void Should_Throw_If_Match_Not_Found_And_No_Conditions()
            {
                // Given
                const string guidString = "49934b49-1cc3-443d-a89a-23496708f64b";
                var list = new List<SimpleModel>
                {
                    new SimpleModel
                    {
                        DecimalProperty = 456,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 678,
                        StringProperty = "Goodbye, World",
                        BoolProperty = false
                    },
                    new SimpleModel
                    {
                        DecimalProperty = 123,
                        GuidProperty = Guid.Parse(guidString),
                        IntProperty = 345,
                        StringProperty = "Hello, World",
                        BoolProperty = true
                    }
                };

                // When
                var expectedModel = new SimpleModel
                {
                    DecimalProperty = 123,
                    GuidProperty = Guid.Parse(guidString),
                    IntProperty = 345,
                    StringProperty = "This is a failure!",
                    BoolProperty = true
                };

                // Then
                Should.Throw<CollectionDoesNotMatch>(() => list.ShouldContainAMatchOfNonDefaultProperties(expectedModel, new List<Condition>()));
            }

            [Fact]
            public void Should_Not_Throw_If_Condition_Overrides_Default_Match_Logic()
            {
                // Given
                const string guidString = "49934b49-1cc3-443d-a89a-23496708f64b";
                var list = new List<SimpleModel>
                {
                    new SimpleModel
                    {
                        DecimalProperty = 456,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 678,
                        StringProperty = "Goodbye, World",
                        BoolProperty = false
                    },
                    new SimpleModel
                    {
                        DecimalProperty = 123,
                        GuidProperty = Guid.Parse(guidString),
                        IntProperty = 345,
                        StringProperty = "Hello, World",
                        BoolProperty = true
                    }
                };

                // When
                var expectedModel = new SimpleModel
                {
                    DecimalProperty = 123,
                    GuidProperty = Guid.NewGuid(),
                    IntProperty = 345,
                    StringProperty = default(string),
                    BoolProperty = true
                };

                // Then
                Should.NotThrow(() => list.ShouldContainAMatchOfNonDefaultProperties(expectedModel, new[]
                {
                    Ignore.This(() => expectedModel.GuidProperty)
                }));
            }

            [Fact]
            public void Should_Throw_If_Correct_Number_Of_Matches_Not_Found()
            {
                // Given
                var list = new List<SimpleModel>
                {
                    new SimpleModel
                    {
                        DecimalProperty = 456,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 678,
                        StringProperty = "Goodbye, World",
                        BoolProperty = false
                    },
                    new SimpleModel
                    {
                        DecimalProperty = 123,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 345,
                        StringProperty = "Hello, World",
                        BoolProperty = true
                    }
                };

                // When
                var expectedModel = new SimpleModel
                {
                    DecimalProperty = 123,
                    GuidProperty = default(Guid),
                    IntProperty = 345,
                    StringProperty = "This is a failure!",
                    BoolProperty = true
                };

                // Then
                Should.Throw<CollectionDoesNotMatch>(() =>
                    list.ShouldContainMatchesOfNonDefaultProperties(expectedModel, new[]
                    {
                        Ignore.This(() => expectedModel.StringProperty)
                    },
                    Matches.Two));
            }

            [Fact]
            public void Should_Not_Throw_If_Correct_Number_Of_Matches_Found_After_Conditions_Applied()
            {
                // Given
                var list = new List<SimpleModel>
                {
                    new SimpleModel
                    {
                        DecimalProperty = 456,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 678,
                        StringProperty = "Goodbye, World",
                        BoolProperty = false
                    },
                    new SimpleModel
                    {
                        DecimalProperty = 456,
                        GuidProperty = Guid.NewGuid(),
                        IntProperty = 678,
                        StringProperty = "Hello, World",
                        BoolProperty = false
                    }
                };

                // When
                var expectedModel = new SimpleModel
                {
                    DecimalProperty = 456,
                    GuidProperty = default(Guid),
                    IntProperty = 678,
                    StringProperty = "Hello, World",
                    BoolProperty = false
                };

                // Then
                Should.NotThrow(() =>
                    list.ShouldContainMatchesOfNonDefaultProperties(expectedModel, new[]
                    {
                        Ignore.This(() => expectedModel.StringProperty)
                    },
                    Matches.Two));
            }
        }

    }
}


text:
"""
서비스 관리 도구 국제화 지원 모듈.

`django-modeltranslation` 을 이용하여 다국어 지원을 하는 모듈입니다.
"""

from modeltranslation.translator import TranslationOptions, register

from .models import Category, BaseService, Service, TopBanner

@register(Category)
class CategoryTranslationOptions(TranslationOptions):
    """
    :class:`Category` 모델에 대한 국제화 지원.
    """

    fields = ('name',)

@register(BaseService)
class BaseServiceTranslationOptions(TranslationOptions):
    """
    :class:`Service` 모델에 대한 국제화 지원.
    """

    fields = ('name',)

@register(Service)
class ServiceTranslationOptions(TranslationOptions):
    """
    :class:`Service` 모델에 대한 국제화 지원.
    """

    fields = ()

@register(TopBanner)
class TopBannerTranslationOptions(TranslationOptions):
    """
    :class:`TopBanner` 모델에 대한 국제화 지원.
    """

    fields = ('text',)


text:
<title>
Antiracists confront Nazis in Ohio
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Antiracists confront Nazis in Ohio

By Jason Bechtel and Patrick Dyer | December 16, 2005 | Page 15

TOLEDO, Ohio--A massive police presence to protect a neo-Nazi rally here December 11 led to the arrest of 30 antiracists, including several who were pulled over by cops far from the actual protest.

The National Socialist Movement, a swastika-wearing Nazi organization, was run out of town October 15 by a crowd of largely African American protesters, who, when attacked by police, fought back. This time, city officials used overwhelming force--including 500 police officers, many of them on horseback--to try to intimidate demonstrators.

The real story turned out not to be the neo-Nazi rally, but the trampling of civil rights that occurred in the name of public safety. An injunction granted by a judge December 9 essentially put the city under martial law for a day.

Under the judge's order, protests were banned anywhere outside of the designated police perimeter around 1 Government Center, the site of the Nazi rally. Everyone entering the site was required to leave behind anything deemed "threatening" by police. Signs could not have sticks or poles attached. Everyone had to walk through a metal detector. Finally, everyone was required to stand in front of a video camera for documentation.

In spite of this police state atmosphere, 150 people defied police intimidation and showed up to protest the Nazis. And although everyone at the protest had passed through tight security, police methodically walked a line of horses along the barricades, forcing the protesters to back up. Anyone who did not do so quickly was arrested.

According to a legal observer, every time a protester would insult the police, officers on horseback and on foot would make an incursion into the crowd and apprehend that person. Meanwhile, horses were being maneuvered inside the crowd, often slamming into and nearly trampling protesters.

Two of the protesters arrested were Latinos from Lansing, Mich., who police claimed matched the descriptions of two individuals at the October riot. It can be proved that they were nowhere near Toledo on that day--but racial profiling became a convenient excuse for the police to arrest at will.

These tactics had both the direct effect of removing protesters from the site and the follow-up effect of intimidation, which drove many to leave early to avoid arrest. The police succeeded in decimating our forces and, in the process, succeeded in shredding our civil rights.

In the coming days, as bails are posted and charges are dropped and plead down, a class-action lawsuit against the city and the police department must materialize. If Toledo can get away with these heavy-handed tactics to protect Nazis without repercussions, then other cities will do likewise.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Riganti.Selenium.Core.Configuration;
using Riganti.Selenium.Core.Drivers;
using Riganti.Selenium.Core.Abstractions;

namespace Riganti.Selenium.Core
{
    internal class TestInstanceContextWrapper : TestContextWrapper, ITestInstanceContext
    {
        private readonly TestInstance testInstance;

        public TestInstanceContextWrapper(TestContext context, TestInstance testInstance)
        : base(context)
        {
            this.testInstance = testInstance;
        }

        public IWebBrowser CurrentWebBrowser => testInstance.CurrentWebBrowser;

        public string BaseUrl => testInstance.TestConfiguration.BaseUrl;
    }
}


text:
module Grizzly
  class Cursor
    include Enumerable
    ITEMS_PER_PAGE = 50

    def initialize(domain_object, url, options, items_per_page = ITEMS_PER_PAGE)
      @domain_object, @url, @options, @items_per_page = domain_object, url, options, items_per_page
      @current_page = 0
      @fetched_current_page = false
    end

    #Each will return the first page of results
    def each(&block)
      @current_page += 1
      fetch_current_page if !@fetched_current_page
      @items.each { |i| block.call i }
      @fetched_current_page = false
    end

    def next_page?
      total_item_count = total_items
      (@current_page * @items_per_page) < total_item_count
    end

    def total_items
      fetch_current_page if @total_items.nil?
      @total_items
    end

    def [](index)
      fetch_current_page if !@fetched_current_page
      @items[index]
    end

    private

    def page_request(url, options)
      request = Grizzly::Request.new(:get, url, options)
      request.response
    end

    def fetch_current_page
      options = @options.merge({ :page => @current_page, :count => @items_per_page })
      response = page_request(@url, options)
      @total_items = response["total_number"]

      @items = []
      response[@domain_object::API_COLLECTION_NAME].each do |domain_object|
        @items << @domain_object.new(domain_object)
      end
      @fetched_current_page = true
    end

  end
end


text:
package com.amazonaws.services.serverlessapplicationrepository.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.serverlessapplicationrepository.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ApplicationPolicyStatementMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ApplicationPolicyStatementMarshaller {

    private static final MarshallingInfo<List> ACTIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("actions").build();
    private static final MarshallingInfo<List> PRINCIPALS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("principals").build();
    private static final MarshallingInfo<String> STATEMENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("statementId").build();

    private static final ApplicationPolicyStatementMarshaller instance = new ApplicationPolicyStatementMarshaller();

    public static ApplicationPolicyStatementMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ApplicationPolicyStatement applicationPolicyStatement, ProtocolMarshaller protocolMarshaller) {

        if (applicationPolicyStatement == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(applicationPolicyStatement.getActions(), ACTIONS_BINDING);
            protocolMarshaller.marshall(applicationPolicyStatement.getPrincipals(), PRINCIPALS_BINDING);
            protocolMarshaller.marshall(applicationPolicyStatement.getStatementId(), STATEMENTID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package com.streamsets.datacollector.execution;

import com.streamsets.datacollector.config.PipelineConfiguration;
import com.streamsets.datacollector.creation.PipelineConfigBean;
import com.streamsets.datacollector.email.EmailSender;
import com.streamsets.datacollector.event.handler.remote.RemoteDataCollector;
import com.streamsets.datacollector.execution.alerts.EmailNotifier;
import com.streamsets.datacollector.execution.alerts.WebHookNotifier;
import com.streamsets.datacollector.execution.runner.common.PipelineRunnerException;
import com.streamsets.datacollector.main.RuntimeInfo;
import com.streamsets.datacollector.stagelibrary.StageLibraryTask;
import com.streamsets.datacollector.store.AclStoreTask;
import com.streamsets.datacollector.store.PipelineStoreException;
import com.streamsets.datacollector.store.PipelineStoreTask;
import com.streamsets.datacollector.util.Configuration;
import com.streamsets.datacollector.util.ContainerError;
import com.streamsets.datacollector.util.PipelineException;
import com.streamsets.datacollector.util.ValidationUtil;
import com.streamsets.datacollector.validation.PipelineConfigurationValidator;
import com.streamsets.lib.security.acl.dto.Acl;
import com.streamsets.pipeline.api.StageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public abstract  class AbstractRunner implements Runner {
  private static final Logger LOG = LoggerFactory.getLogger(AbstractRunner.class);

  @Inject protected AclStoreTask aclStoreTask;
  @Inject protected EventListenerManager eventListenerManager;
  @Inject protected PipelineStoreTask pipelineStore;
  @Inject protected StageLibraryTask stageLibrary;
  @Inject protected RuntimeInfo runtimeInfo;
  @Inject protected Configuration configuration;
  protected Map<String, Object> runtimeParameters;

  protected PipelineConfiguration getPipelineConf(String name, String rev) throws PipelineException {
    PipelineConfiguration load = pipelineStore.load(name, rev);
    PipelineConfigurationValidator validator = new PipelineConfigurationValidator(stageLibrary, name, load);
    PipelineConfiguration validate = validator.validate();
    if(validator.getIssues().hasIssues()) {
      throw new PipelineRunnerException(ContainerError.CONTAINER_0158, ValidationUtil.getFirstIssueAsString(name,
        validator.getIssues()));
    }
    return validate;
  }

  protected Acl getAcl(String name) throws PipelineException {
    return aclStoreTask.getAcl(name);
  }

  protected void registerEmailNotifierIfRequired(
      PipelineConfigBean pipelineConfigBean,
      String pipelineId,
      String pipelineTitle,
      String rev
  ) {
    //remove existing email notifier
    StateEventListener toRemove = null;
    List<StateEventListener> stateEventListenerList = eventListenerManager.getStateEventListenerList();
    for(StateEventListener s : stateEventListenerList) {
      if(s instanceof EmailNotifier &&
        ((EmailNotifier)s).getPipelineId().equals(pipelineId) &&
        ((EmailNotifier)s).getRev().equals(rev)) {
        toRemove = s;
      }
    }

    if(toRemove != null) {
      eventListenerManager.removeStateEventListener(toRemove);
    }

    //register new one if required
    if(pipelineConfigBean.notifyOnStates != null && !pipelineConfigBean.notifyOnStates.isEmpty() &&
      pipelineConfigBean.emailIDs != null && !pipelineConfigBean.emailIDs.isEmpty()) {
      Set<String> states = new HashSet<>();
      for(com.streamsets.datacollector.config.PipelineState s : pipelineConfigBean.notifyOnStates) {
        states.add(s.name());
      }
      EmailNotifier emailNotifier = new EmailNotifier(
          pipelineId,
          pipelineTitle,
          rev,
          runtimeInfo,
          new EmailSender(configuration),
          pipelineConfigBean.emailIDs,
          states
      );
      eventListenerManager.addStateEventListener(emailNotifier);
    }
  }

  protected void registerWebhookNotifierIfRequired(
      PipelineConfigBean pipelineConfigBean,
      String pipelineId,
      String pipelineTitle,
      String rev
  ) {
    //remove existing Webhook notifier
    StateEventListener toRemove = null;
    List<StateEventListener> stateEventListenerList = eventListenerManager.getStateEventListenerList();
    for(StateEventListener s : stateEventListenerList) {
      if(s instanceof WebHookNotifier &&
          ((WebHookNotifier)s).getPipelineId().equals(pipelineId) &&
          ((WebHookNotifier)s).getRev().equals(rev)) {
        toRemove = s;
      }
    }

    if(toRemove != null) {
      eventListenerManager.removeStateEventListener(toRemove);
    }

    //register new one if required
    if(pipelineConfigBean.notifyOnStates != null && !pipelineConfigBean.notifyOnStates.isEmpty() &&
        pipelineConfigBean.webhookConfigs != null && !pipelineConfigBean.webhookConfigs.isEmpty()) {
      WebHookNotifier webHookNotifier = new WebHookNotifier(
          pipelineId,
          pipelineTitle,
          rev,
          pipelineConfigBean,
          runtimeInfo,
          runtimeParameters
      );
      eventListenerManager.addStateEventListener(webHookNotifier);
    }
  }

  protected boolean isRemotePipeline() throws PipelineStoreException {
    Object isRemote = getState().getAttributes().get(RemoteDataCollector.IS_REMOTE_PIPELINE);
    // remote attribute will be null for pipelines with version earlier than 1.3
    return isRemote != null && (boolean) isRemote;
  }

  protected ScheduledFuture<Void> scheduleForRetries(
      String user,
      ScheduledExecutorService runnerExecutor
  ) throws PipelineStoreException {
    long delay = 0;
    long retryTimeStamp = getState().getNextRetryTimeStamp();
    long currentTime = System.currentTimeMillis();
    if (retryTimeStamp > currentTime) {
      delay = retryTimeStamp - currentTime;
    }
    LOG.info("Scheduling retry in '{}' milliseconds", delay);
    return runnerExecutor.schedule(() -> {
      LOG.info("Starting the runner now");
      prepareForStart(user);
      start(user, runtimeParameters);
      return null;
    }, delay, TimeUnit.MILLISECONDS);
  }

  @Override
  public void start(String user) throws PipelineException, StageException {
    start(user, null);
  }
}


text:
"""Module for testing the search network command."""

import unittest

if __name__ == "__main__":
    import utils
    utils.import_depends()

from brokertest import TestBrokerCommand

class TestSearchNetwork(TestBrokerCommand):

    def testname(self):
        command = ["search_network", "--network=%s" % self.net["tor_net_0"].name]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["tor_net_0"]), command)

    def testip0(self):
        command = ["search_network", "--ip=%s" % self.net["tor_net_0"].ip]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["tor_net_0"]), command)

    def testipcontains(self):
        command = ["search_network", "--ip=%s" % self.net["tor_net_0"].usable[0]]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["tor_net_0"]), command)

    def testtype(self):
        command = ["search_network", "--type=tor_net"]
        out = self.commandtest(command)
        for net in self.net:
            if net.nettype == "tor_net":
                self.matchoutput(out, str(net), command)
            else:
                self.matchclean(out, str(net), command)

    def testphysicalmachine(self):
        # unittest15.aqd-unittest.ms.com
        command = ["search_network", "--machine=ut8s02p1"]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["tor_net_0"]), command)

    # The test for virtual machines (with port groups) lives in
    # test_add_10gig_hardware.

    def testfailphysicalmachine(self):
        """This physical machine has no interface."""
        command = ["search_network", "--machine=ut3c1n9"]
        out = self.badrequesttest(command)
        self.matchoutput(out,
                         "Machine ut3c1n9 has no interfaces with a port group "
                         "or assigned to a network.",
                         command)

    # Failure for a virtual machine with no interface is in
    # test_add_10gig_hardware

    def testclusterpg(self):
        command = ["search_network", "--cluster=utecl5", "--pg=user-v710"]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["ut01ga2s01_v710"]), command)

    def testcluster(self):
        command = ["search_network", "--cluster=utecl1"]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["ut10_eth0"]), command)

    def testfqdn(self):
        command = ["search_network", "--fqdn=unittest15.aqd-unittest.ms.com"]
        out = self.commandtest(command)
        self.matchoutput(out, str(self.net["tor_net_0"]), command)

    def testlocation(self):
        command = ["search_network", "--building=ut"]
        out = self.commandtest(command)
        for net in self.net:
            if not net.autocreate:
                continue
            if ((net.loc_type == "building" and net.loc_name == "ut") or
                    (net.loc_type == "bunker" and net.loc_name == "bucket2.ut")):
                self.matchoutput(out, str(net), command)
            else:
                self.matchclean(out, str(net.ip), command)

    def testexactlocation(self):
        command = ["search_network", "--building=ut", "--exact_location"]
        out = self.commandtest(command)
        for net in self.net:
            if not net.autocreate:
                continue
            if net.loc_type == "building" and net.loc_name == "ut":
                self.matchoutput(out, str(net), command)
            else:
                self.matchclean(out, str(net.ip), command)

    def testfullinfo(self):
        net = self.net["tor_net_0"]
        command = ["search_network", "--ip=%s" % net.ip, "--fullinfo"]
        out = self.commandtest(command)
        self.matchoutput(out, "Network: %s" % net.name, command)
        self.matchoutput(out, "IP: %s" % net.ip, command)

    def testnoenv(self):
        # Same IP defined differently in different environments
        net = self.net["unknown0"]
        command = ["search", "network", "--ip", net.ip, "--fullinfo"]
        out = self.commandtest(command)
        self.matchoutput(out, "Network: %s" % net.name, command)
        self.matchoutput(out, "Network Environment: internal", command)
        self.matchclean(out, "Network Environment: excx", command)
        self.matchclean(out, "Network Environment: utcolo", command)
        self.matchoutput(out, "Netmask: %s" % net.netmask, command)
        self.matchclean(out, "excx-net", command)

    def testwithenv(self):
        # Same IP defined differently in different environments
        net = self.net["unknown0"]
        subnet = net.subnet()[0]
        command = ["search", "network", "--ip", net.ip,
                   "--network_environment", "excx", "--fullinfo"]
        out = self.commandtest(command)
        self.matchoutput(out, "Network: excx-net", command)
        self.matchclean(out, "Network: %s" % net.name, command)
        self.matchoutput(out, "Network Environment: excx", command)
        self.matchclean(out, "Network Environment: internal", command)
        self.matchclean(out, "Network Environment: utcolo", command)
        self.matchoutput(out, "Netmask: %s" % subnet.netmask, command)
        self.matchclean(out, "Netmask: %s" % net.netmask, command)

    def testdynrange(self):
        command = ["search", "network", "--has_dynamic_ranges"]
        out = self.commandtest(command)
        expect = [self.net["dyndhcp0"], self.net["dyndhcp1"],
                  self.net["dyndhcp3"]]
        for net in self.net:
            if not net.autocreate:
                continue
            if net in expect:
                self.matchoutput(out, str(net), command)
            else:
                self.matchclean(out, str(net), command)

    def testdynrangecsv(self):
        command = ["search_network", "--has_dynamic_ranges", "--format", "csv"]
        out = self.commandtest(command)
        expect = [self.net["dyndhcp0"], self.net["dyndhcp1"],
                  self.net["dyndhcp3"]]
        for network in self.net:
            if not network.autocreate:
                continue
            if network in expect:
                self.matchoutput(out, "%s,%s,%s,ut.ny.na,us,a,%s,\n" %
                                 (network.name, network.ip, network.netmask,
                                  network.nettype),
                                 command)
            else:
                self.matchclean(out, str(network.ip), command)

    def testside(self):
        command = ["search", "network", "--side", "b"]
        out = self.commandtest(command)
        self.matchoutput(out, "%s/26" % self.net["np06bals03_v103"].ip, command)
        self.matchoutput(out, "%s/26" % self.net["notbunkerized"].ip, command)
        self.matchclean(out, str(self.net["dyndhcp0"].ip), command)
        self.matchclean(out, str(self.net["unknown0"].ip), command)

    def testcompartment(self):
        command = ["search", "network", "--network_compartment", "perimeter.ut"]
        out = self.commandtest(command)
        for net in self.net:
            if net.name == "ut_dmz1":
                self.matchoutput(out, str(net), command)
            else:
                self.matchclean(out, str(net), command)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestSearchNetwork)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
const config = require('./config/config.json');
var express = require('express'),
    app = express(),
    sessions = require('client-sessions'),
    log4js = require('log4js'),
    load_user = require('./middleware/load_user'),
    admin_only = require('./middleware/admin_only'),
    no_guests = require('./middleware/no_guests'),
    new_user = require('./middleware/new_user'),
    formidable = require('formidable'),
    bodyParser = require('body-parser'),
    morgan = require('morgan'),
    PORT = 8080;
    var flash = require('req-flash');

    log4js.configure('./config/log4js.json');
    var logger = log4js.getLogger(config.logger);

    //app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));

    app.set('view engine', 'ejs');   //set view to ejs
    app.set('views', './templates'); //set templates directory

    //create sessions cookie
    app.use(sessions({
      cookieName: 'session',
      secret: 'somerandomstring',
      duration: 24*90*60*1000,
      activeDuration: 1000*60*5
    }));
    app.use(flash());

    //log every request to console
    app.use(morgan('dev'));

    //load user
    app.use(load_user);

    //set static directory
    app.use(express.static('public'));

    // Main middleware
    app.use(function(req, res, next){
      // if there's a flash message in the session request, make it available in the response, then delete it
      res.locals.sessionFlash = req.session.sessionFlash;
      delete req.session.sessionFlash;
      next();
    });

    //set api static directory, route, and only users allowed
    //app.use('/api', no_guests, express.static('out'));

    //use only for code review
    app.use('/api', express.static('out'));

    var api = require('./endpoints/api');
    app.get('/api', api.index); //api index

    var parseBody = bodyParser.urlencoded({ extended: true });

    var session = require('./endpoints/session');
    app.get('/', session.redirect);              //Redirects to '/login'
    app.get('/login', session.login);            //User login form
    app.post('/login', session.start);           //Create session
    app.get('/logout', no_guests, session.stop); //Deletes session

    var landing = require('./endpoints/landing');
    app.get('/index', no_guests, landing.index);
    app.post('/index/search', parseBody, landing.search);      // Search Results

    var forms = require('./endpoints/forms');
    app.get('/formAbc', no_guests, forms.abcForm);                       //Abc Form
    app.post('/formAbc', parseBody, forms.formAbcAjax);                  //Abc Form Ajax
    app.post('/formAbc/submitForm', parseBody, forms.formAbcSubmit);
    app.post('/formAbc/edit/:tag/:client', forms.editAbcForm);
    app.get('/firstForm', no_guests, forms.firstForm);                   //First Form
    app.get('/individualDonorFile', no_guests, forms.individualDonorFile); //Donor Cow Enrollment
    app.post('/individualDonorFile', parseBody, forms.individualDonorFile);
    app.post('/individualDonorFile/edit/:tag/:client', forms.editForm);
    app.get('/caneCodeLog', no_guests, forms.caneCodeLog);               //Cane Code Log
    app.get('/caneCode', no_guests, forms.caneCode);                   //Cane Code

    /* admin routes accessible only if
    a user account is an admin account */
    var admin = require('./endpoints/admin');

    //COMPLETE (At least works.)
    app.get('/admin', admin_only, admin.index);
    app.get('/admin/users', admin_only, admin.viewUsers);
    app.post('/admin/invite', admin_only, admin.inviteUser);

    //Tested
    app.post('/admin/edit/:id(\\d+)', admin_only, admin.commitEdit);
    app.get('/admin/delete/:id(\\d+)', admin_only, admin.deleteUser);

    //used to confirm new user
    var user = require('./endpoints/user');

    //COMPLETE (At least works.)
    app.get('/user/reset', user.reset);
    app.post('/user/reset', user.resetEmail);

    app.get('/user/verify/:token', user.verifyToken);
    app.post('/user/reset/:token', user.resetCommit); //working on 12/31/16
    app.get('/user/edit/:id(\\d+)', no_guests, user.edit);
    app.post('/user/edit/:id(\\d+)', user.commitEdit);

    //NOT COMPLETE YET
    app.post('/user/new/:token', user.commitNewUser);

    //handles invalid urls
    app.all('*', function(req, res) {
      res.redirect("/index");
    });

    //start express app
    app.listen(PORT, () => {
      logger.info("Listening on port " + PORT);
      console.log("Listening on port " + PORT + "\n");
    });

    module.exports = exports = app;


text:
using System;
using Binance.Net.Converters;
using Binance.Net.Enums;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;

namespace Binance.Net.Objects.Models.Spot.Lending
{
    /// <summary>
    /// Redemption record
    /// </summary>
    public class BinanceRedemptionRecord
    {
        /// <summary>
        /// Quantity purchased
        /// </summary>
        [JsonProperty("amount")]
        public decimal Quantity { get; set; }
        /// <summary>
        /// Asset name
        /// </summary>
        public string Asset { get; set; } = string.Empty;
        /// <summary>
        /// Timestamp
        /// </summary>
        [JsonConverter(typeof(DateTimeConverter))]
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// Start time
        /// </summary>
        [JsonConverter(typeof(DateTimeConverter))]
        public DateTime? StartTime { get; set; }
        /// <summary>
        /// Interest
        /// </summary>
        public decimal Interest { get; set; }
        /// <summary>
        /// Redeem type
        /// </summary>
        [JsonConverter(typeof(RedeemTypeConverter))]
        public RedeemType Type { get; set; }
        /// <summary>
        /// Id of the project
        /// </summary>
        public string ProjectId { get; set; } = string.Empty;
        /// <summary>
        /// Name of the project
        /// </summary>
        public string ProjectName { get; set; } = string.Empty;
        /// <summary>
        /// Principal
        /// </summary>
        public decimal Principal { get; set; }

        /// <summary>
        /// Purchase status
        /// </summary>
        public string Status { get; set; } = string.Empty;
    }
}


text:
import theano
import theano.tensor as T
import lasagne as nn

from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
_srng = RandomStreams()

class TiedDropoutLayer(nn.layers.Layer):
    """
    Dropout layer that broadcasts the mask across all axes beyond the first two.
    """
    def __init__(self, input_layer, p=0.5, rescale=True, **kwargs):
        super(TiedDropoutLayer, self).__init__(input_layer, **kwargs)
        self.p = p
        self.rescale = rescale

    def get_output_for(self, input, deterministic=False, *args, **kwargs):
        if deterministic or self.p == 0:
            return input
        else:
            retain_prob = 1 - self.p
            if self.rescale:
                input /= retain_prob

            mask = _srng.binomial(input.shape[:2], p=retain_prob,
                                  dtype=theano.config.floatX)
            axes = [0, 1] + (['x'] * (input.ndim - 2))
            mask = mask.dimshuffle(*axes)
            return input * mask

class BatchNormLayer(nn.layers.Layer):
    """
    lasagne.layers.BatchNormLayer(incoming, axes='auto', epsilon=1e-4,
    alpha=0.5, nonlinearity=None, mode='low_mem',
    beta=lasagne.init.Constant(0), gamma=lasagne.init.Constant(1),
    mean=lasagne.init.Constant(0), var=lasagne.init.Constant(1), **kwargs)
    Batch Normalization
    This layer implements batch normalization of its inputs, following [1]_:
    .. math::
        y = \\frac{x - \\mu}{\\sqrt{\\sigma^2 + \\epsilon}} \\gamma + \\beta
    That is, the input is normalized to zero mean and unit variance, and then
    linearly transformed.
    During training, :math:`\\mu` and :math:`\\sigma^2` are defined to be the
    mean and variance of the current input mini-batch :math:`x`, and during
    testing, they are replaced with average statistics over the training
    data. Consequently, this layer has four stored parameters: :math:`\\beta`,
    :math:`\\gamma`, and the averages :math:`\\mu` and :math:`\\sigma^2`.
    By default, this layer learns the average statistics as exponential moving
    averages computed during training, so it can be plugged into an existing
    network without any changes of the training procedure (see Notes).
    Parameters
    ----------
    incoming : a :class:`Layer` instance or a tuple
        The layer feeding into this layer, or the expected input shape
    axes : 'auto', int or tuple of int
        The axis or axes to normalize over. If ``'auto'`` (the default),
        normalize over all axes except for the second: this will normalize over
        the minibatch dimension for dense layers, and additionally over all
        spatial dimensions for convolutional layers.
    epsilon : scalar
        Small constant :math:`\\epsilon` added to the variance before taking
        the square root and dividing by it, to avoid numeric problems
    alpha : scalar
        Coefficient for the exponential moving average of batch-wise means and
        standard deviations computed during training; the closer to one, the
        more it will depend on the last batches seen
    nonlinearity : callable or None
        The nonlinearity that is applied to the layer activations. If ``None``
        is provided, the layer will be linear (this is the default).
    mode : {'low_mem', 'high_mem'}
        Specify which batch normalization implementation to use: ``'low_mem'``
        avoids storing intermediate representations and thus requires less
        memory, while ``'high_mem'`` can reuse representations for the backward
        pass and is thus 5-10% faster.
    beta : Theano shared variable, expression, numpy array, or callable
        Initial value, expression or initializer for :math:`\\beta`. Must match
        the incoming shape, skipping all axes in `axes`.
        See :func:`lasagne.utils.create_param` for more information.
    gamma : Theano shared variable, expression, numpy array, or callable
        Initial value, expression or initializer for :math:`\\gamma`. Must
        match the incoming shape, skipping all axes in `axes`.
        See :func:`lasagne.utils.create_param` for more information.
    mean : Theano shared variable, expression, numpy array, or callable
        Initial value, expression or initializer for :math:`\\mu`. Must match
        the incoming shape, skipping all axes in `axes`.
        See :func:`lasagne.utils.create_param` for more information.
    var : Theano shared variable, expression, numpy array, or callable
        Initial value, expression or initializer for :math:`\\sigma^2`. Must
        match the incoming shape, skipping all axes in `axes`.
        See :func:`lasagne.utils.create_param` for more information.
    **kwargs
        Any additional keyword arguments are passed to the :class:`Layer`
        superclass.
    Notes
    -----
    This layer should be inserted between a linear transformation (such as a
    :class:`DenseLayer`, or :class:`Conv2DLayer`) and its nonlinearity. The
    convenience function :func:`batch_norm` modifies an existing layer to
    insert batch normalization in front of its nonlinearity.
    The behavior can be controlled by passing keyword arguments to
    :func:`lasagne.layers.get_output()` when building the output expression
    of any network containing this layer.
    During training, [1]_ normalize each input mini-batch by its statistics
    and update an exponential moving average of the statistics to be used for
    validation. This can be achieved by passing ``deterministic=False``.
    For validation, [1]_ normalize each input mini-batch by the stored
    statistics. This can be achieved by passing ``deterministic=True``.
    For more fine-grained control, ``batch_norm_update_averages`` can be passed
    to update the exponential moving averages (``True``) or not (``False``),
    and ``batch_norm_use_averages`` can be passed to use the exponential moving
    averages for normalization (``True``) or normalize each mini-batch by its
    own statistics (``False``). These settings override ``deterministic``.
    Note that for testing a model after training, [1]_ replace the stored
    exponential moving average statistics by fixing all network weights and
    re-computing average statistics over the training data in a layerwise
    fashion. This is not part of the layer implementation.
    See also
    --------
    batch_norm : Convenience function to apply batch normalization to a layer
    References
    ----------
    .. [1]: Ioffe, Sergey and Szegedy, Christian (2015):
            Batch Normalization: Accelerating Deep Network Training by Reducing
            Internal Covariate Shift. http://arxiv.org/abs/1502.03167.
    """
    def __init__(self, incoming, axes='auto', epsilon=1e-4, alpha=0.1,
                 nonlinearity=None, mode='low_mem',
                 beta=nn.init.Constant(0), gamma=nn.init.Constant(1),
                 mean=nn.init.Constant(0), var=nn.init.Constant(1), **kwargs):
        super(BatchNormLayer, self).__init__(incoming, **kwargs)

        if axes == 'auto':
            # default: normalize over all but the second axis
            axes = (0,) + tuple(range(2, len(self.input_shape)))
        elif isinstance(axes, int):
            axes = (axes,)
        self.axes = axes

        self.epsilon = epsilon
        self.alpha = alpha
        if nonlinearity is None:
            nonlinearity = nn.nonlinearities.identity
        self.nonlinearity = nonlinearity
        self.mode = mode

        # create parameters, ignoring all dimensions in axes
        shape = [size for axis, size in enumerate(self.input_shape)
                 if axis not in self.axes]
        if any(size is None for size in shape):
            raise ValueError("BatchNormLayer needs specified input sizes for "
                             "all axes not normalized over.")
        self.beta = self.add_param(beta, shape, 'beta',
                                   trainable=True, regularizable=False)
        self.gamma = self.add_param(gamma, shape, 'gamma',
                                    trainable=True, regularizable=True)
        self.mean = self.add_param(mean, shape, 'mean',
                                   trainable=False, regularizable=False)
        self.var = self.add_param(var, shape, 'var',
                                  trainable=False, regularizable=False)

    def get_output_for(self, input, deterministic=False, **kwargs):
        input_mean = input.mean(self.axes)
        input_var = input.var(self.axes)

        # Decide whether to use the stored averages or mini-batch statistics
        use_averages = kwargs.get('batch_norm_use_averages',
                                  deterministic)
        if use_averages:
            mean = self.mean
            var = self.var
        else:
            mean = input_mean
            var = input_var

        # Decide whether to update the stored averages
        update_averages = kwargs.get('batch_norm_update_averages',
                                     not deterministic)
        if update_averages:
            # Trick: To update the stored statistics, we create memory-aliased
            # clones of the stored statistics:
            running_mean = theano.clone(self.mean, share_inputs=False)
            running_var = theano.clone(self.var, share_inputs=False)
            # set a default update for them:
            running_mean.default_update = ((1 - self.alpha) * running_mean +
                                           self.alpha * input_mean)
            running_var.default_update = ((1 - self.alpha) * running_var +
                                          self.alpha * input_var)
            # and make sure they end up in the graph without participating in
            # the computation (this way their default_update will be collected
            # and applied, but the computation will be optimized away):
            mean += 0 * running_mean
            var += 0 * running_var

        # prepare dimshuffle pattern inserting broadcastable axes as needed
        param_axes = iter(range(self.beta.ndim))
        pattern = ['x' if input_axis in self.axes
                   else next(param_axes)
                   for input_axis in range(input.ndim)]

        # apply dimshuffle pattern to all parameters
        beta = self.beta.dimshuffle(pattern)
        gamma = self.gamma.dimshuffle(pattern)
        mean = mean.dimshuffle(pattern)
        std = T.sqrt(var + self.epsilon)
        std = std.dimshuffle(pattern)

        # normalize
        # normalized = (input - mean) * (gamma / std) + beta
        normalized = T.nnet.batch_normalization(input, gamma=gamma, beta=beta,
                                                mean=mean, std=std,
                                                mode=self.mode)
        return self.nonlinearity(normalized)

def batch_norm(layer, **kwargs):
    """
    Apply batch normalization to an existing layer. This is a convenience
    function modifying an existing layer to include batch normalization: It
    will steal the layer's nonlinearity if there is one (effectively
    introducing the normalization right before the nonlinearity), remove
    the layer's bias if there is one (because it would be redundant), and add
    a :class:`BatchNormLayer` on top.
    Parameters
    ----------
    layer : A :class:`Layer` instance
        The layer to apply the normalization to; note that it will be
        irreversibly modified as specified above
    **kwargs
        Any additional keyword arguments are passed on to the
        :class:`BatchNormLayer` constructor. Especially note the `mode`
        argument, which controls a memory usage to performance tradeoff.
    Returns
    -------
    :class:`BatchNormLayer` instance
        A batch normalization layer stacked on the given modified `layer`.
    """
    nonlinearity = getattr(layer, 'nonlinearity', None)
    if nonlinearity is not None:
        layer.nonlinearity = nn.nonlinearities.identity
    if hasattr(layer, 'b'):
        del layer.params[layer.b]
        layer.b = None
    return BatchNormLayer(layer, nonlinearity=nonlinearity, **kwargs)

def batch_norm2(layer, **kwargs):
    nonlinearity = getattr(layer, 'nonlinearity', None)
    if nonlinearity is not None:
        layer.nonlinearity = nn.nonlinearities.identity
    if hasattr(layer, 'b') and layer.b is not None:
        del layer.params[layer.b]
        layer.b = None
    layer = BatchNormLayer(layer, **kwargs)
    if nonlinearity is not None:
        from lasagne.layers.special import NonlinearityLayer
        layer = NonlinearityLayer(layer, nonlinearity, name='%s_nl' % layer.name)
    return layer


text:
module ESA
  class BalanceChecker
    def self.check(context, options = {})
      if context.can_be_persisted? and not context.freshness.nil?
        #context.event_count = context.events.created_before(context.freshness).count
        #context.flag_count = context.flags.created_before(context.freshness).count
        context.transaction_count = context.transactions.created_before(context.freshness).count
        context.amount_count = context.amounts.created_before(context.freshness).count

        context.debits_total = context.amounts.debits.created_before(context.freshness).total
        context.credits_total = context.amounts.credits.created_before(context.freshness).total
        context.opening_balance = context.opening_context.amounts.created_before(context.freshness).balance
        context.closing_balance = context.closing_context.amounts.created_before(context.freshness).balance
      end
    end
  end
end


text:
package ru.stqa.pft.addressbook.model;

/**
 * Created by Сергей on 18.07.2017.
 */
public class ContactData {
  private final String firstname;
  private final String middlename;
  private final String lastname;
  private final String nickname;
  private final String title;
  private final String company;
  private final String address;
  private final String home;
  private final String mobile;
  private final String work;
  private final String fax;
  private final String email;
  private final String email2;
  private final String email3;
  private final String homepage;
  private final String byear;
  private final String address2;
  private final String phone2;
  private final String notes;
  private String group;

  public ContactData(String firstname,
                     String middlename,
                     String lastname,
                     String nickname,
                     String title,
                     String company,
                     String address,
                     String home,
                     String mobile,
                     String work,
                     String fax,
                     String email,
                     String email2,
                     String email3,
                     String homepage,
                     String byear,
                     String phone2,
                     String address2,
                     String notes,
                     String group)
  {
    this.firstname = firstname;
    this.middlename = middlename;
    this.lastname = lastname;
    this.nickname = nickname;
    this.title = title;
    this.company = company;
    this.address = address;
    this.home = home;
    this.mobile = mobile;
    this.work = work;
    this.fax = fax;
    this.email = email;
    this.email2 = email2;
    this.email3 = email3;
    this.homepage = homepage;
    this.byear = byear;
    this.address2 = address2;
    this.phone2 = phone2;
    this.notes = notes;
    this.group = group;
  }

  public String getFirstname() { return firstname; }
  public String getMiddlename() { return middlename; }
  public String getLastname() { return lastname; }
  public String getNickname() { return nickname; }
  public String getTitle() { return title; }
  public String getCompany() { return company; }
  public String getAddress() { return address; }
  public String getHome() { return home; }
  public String getMobile() { return mobile; }
  public String getWork() { return work; }
  public String getFax() { return fax; }
  public String getEmail() { return email; }
  public String getEmail2() { return email2; }
  public String getEmail3() { return email3; }
  public String getHomepage() { return homepage; }
  public String getByear() { return byear; }
  public String getAddress2() { return address2; }
  public String getPhone2() { return phone2; }
  public String getNotes() { return notes; }

  public String getGroup() { return group; }
}


text:
<?php
/**
 * TOP API: taobao.topats.simba.campkeywordeffect.get request
 *
 * @author auto create
 * @since 1.0, 2013-03-23 12:41:17
 */
class TopatsSimbaCampkeywordeffectGetRequest
{
	/**
	 * 查询推广计划ID
	 **/
	private $campaignId;

	/**
	 * 查询的昵称
	 **/
	private $nick;

	/**
	 * 报表类型。可选值:SEARCH(搜索)、CAT(类目出价)、 NOSEARCH(定向投放),可多选,如:SEARCH,CAT
	 **/
	private $searchType;

	/**
	 * 数据来源。可选值:1(站内)、2(站外)、SUMMARY(汇总),其中SUMMARY必须单选,其它值可多选,如:1,2
	 **/
	private $source;

	/**
	 * 时间参数(昨天:DAY、 前一周:7DAY、 前15天:15DAY、 前30天:30DAY 、前90天:90DAY)单选
	 **/
	private $timeSlot;

	private $apiParas = array();

	public function setCampaignId($campaignId)
	{
		$this->campaignId = $campaignId;
		$this->apiParas["campaign_id"] = $campaignId;
	}

	public function getCampaignId()
	{
		return $this->campaignId;
	}

	public function setNick($nick)
	{
		$this->nick = $nick;
		$this->apiParas["nick"] = $nick;
	}

	public function getNick()
	{
		return $this->nick;
	}

	public function setSearchType($searchType)
	{
		$this->searchType = $searchType;
		$this->apiParas["search_type"] = $searchType;
	}

	public function getSearchType()
	{
		return $this->searchType;
	}

	public function setSource($source)
	{
		$this->source = $source;
		$this->apiParas["source"] = $source;
	}

	public function getSource()
	{
		return $this->source;
	}

	public function setTimeSlot($timeSlot)
	{
		$this->timeSlot = $timeSlot;
		$this->apiParas["time_slot"] = $timeSlot;
	}

	public function getTimeSlot()
	{
		return $this->timeSlot;
	}

	public function getApiMethodName()
	{
		return "taobao.topats.simba.campkeywordeffect.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->campaignId,"campaignId");
		RequestCheckUtil::checkNotNull($this->searchType,"searchType");
		RequestCheckUtil::checkNotNull($this->source,"source");
		RequestCheckUtil::checkNotNull($this->timeSlot,"timeSlot");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PageOfPhotosWebsite.Models
{
    public class PageRef
    {
        public string Slug { get; set; }
        public string Name { get; set; } // UserName
        public string Description { get; set; } // User Description
        public string UserAvatarUrl { get; set; } // UserAvatarUrl
    }
}


text:
package scepserver

import (
	"crypto/subtle"
	"crypto/x509"
	"errors"

	"github.com/micromdm/scep/v2/scep"
)

// CSRSigner is a handler for CSR signing by the CA/RA
//
// SignCSR should take the CSR in the CSRReqMessage and return a
// Certificate signed by the CA.
type CSRSigner interface {
	SignCSR(*scep.CSRReqMessage) (*x509.Certificate, error)
}

// CSRSignerFunc is an adapter for CSR signing by the CA/RA
type CSRSignerFunc func(*scep.CSRReqMessage) (*x509.Certificate, error)

// SignCSR calls f(m)
func (f CSRSignerFunc) SignCSR(m *scep.CSRReqMessage) (*x509.Certificate, error) {
	return f(m)
}

// NopCSRSigner does nothing
func NopCSRSigner() CSRSignerFunc {
	return func(m *scep.CSRReqMessage) (*x509.Certificate, error) {
		return nil, nil
	}
}

// ChallengeMiddleware wraps next in a CSRSigner that validates the challenge from the CSR
func ChallengeMiddleware(challenge string, next CSRSigner) CSRSignerFunc {
	challengeBytes := []byte(challenge)
	return func(m *scep.CSRReqMessage) (*x509.Certificate, error) {
		// TODO: compare challenge only for PKCSReq?
		if subtle.ConstantTimeCompare(challengeBytes, []byte(m.ChallengePassword)) != 1 {
			return nil, errors.New("invalid challenge")
		}
		return next.SignCSR(m)
	}
}


text:
simpledo
========

Simple DigitalOcean API v2 wrapper based on Curl


text:
from fairseq import file_utils
from fairseq.data.encoders import register_bpe

@register_bpe('fastbpe')
class fastBPE(object):

    @staticmethod
    def add_args(parser):
        # fmt: off
        parser.add_argument('--bpe-codes', type=str,
                            help='path to fastBPE BPE')
        # fmt: on

    def __init__(self, args):
        if args.bpe_codes is None:
            raise ValueError('--bpe-codes is required for --bpe=fastbpe')
        codes = file_utils.cached_path(args.bpe_codes)
        try:
            import fastBPE
            self.bpe = fastBPE.fastBPE(codes)
            self.bpe_symbol = "@@ "
        except ImportError:
            raise ImportError('Please install fastBPE with: pip install fastBPE')

    def encode(self, x: str) -> str:
        return self.bpe.apply([x])[0]

    def decode(self, x: str) -> str:
        return (x + ' ').replace(self.bpe_symbol, '').rstrip()


text:
module Mailboxer
  module Models
    module Messageable
      extend ActiveSupport::Concern

      module ActiveRecord
        #Converts the model into messageable allowing it to interchange messages and
        #receive notifications
        def acts_as_messageable
          include Messageable
        end
      end

      included do
        has_many :messages, :as => :sender
        has_many :receipts, :order => 'created_at DESC', :dependent => :destroy, :as => :receiver
      end

      unless defined?(Mailboxer.name_method)
        # Returning any kind of identification you want for the model
        define_method Mailboxer.name_method do
          begin
            super
          rescue NameError
            return "You should add method :#{Mailboxer.name_method} in your Messageable model"
          end
        end
      end

      unless defined?(Mailboxer.email_method)
      #Returning the email address of the model if an email should be sent for this object (Message or Notification).
      #If no mail has to be sent, return nil.
        define_method Mailboxer.email_method do |object|
          begin
            super
          rescue NameError
            return "You should add method :#{Mailboxer.email_method} in your Messageable model"
          end
        end
      end

      #Gets the mailbox of the messageable
      def mailbox
        @mailbox = Mailbox.new(self) if @mailbox.nil?
        @mailbox.type = :all
        return @mailbox
      end

      #Sends a notification to the messageable
      def notify(subject,body,obj = nil,sanitize_text=true,notification_code=nil,send_mail=true)
        return Notification.notify_all([self],subject,body,obj,sanitize_text,notification_code,send_mail)
      end

      #Sends a messages, starting a new conversation, with the messageable
      #as originator
      def send_message(recipients, msg_body, subject, sanitize_text=true, attachment=nil, message_timestamp = Time.now)
        convo = Conversation.new({:subject => subject})
        convo.created_at = message_timestamp
        convo.updated_at = message_timestamp
        message = messages.new({:body => msg_body, :subject => subject, :attachment => attachment})
        message.created_at = message_timestamp
        message.updated_at = message_timestamp
        message.conversation = convo
        message.recipients = recipients.is_a?(Array) ? recipients : [recipients]
        message.recipients = message.recipients.uniq
        return message.deliver false,sanitize_text
      end

      #Sends an urgent message, starting a new conversation, with the messageable
      #as originator
      def send_urgent_message(recipients, msg_body, subject, sanitize_text=true, attachment=nil, message_timestamp = Time.now)
        convo = Conversation.new({:subject => subject})
        convo.created_at = message_timestamp
        convo.updated_at = message_timestamp
        message = messages.new({:body => msg_body, :subject => subject, :attachment => attachment, :urgent => true})
        message.created_at = message_timestamp
        message.updated_at = message_timestamp
        message.conversation = convo
        message.recipients = recipients.is_a?(Array) ? recipients : [recipients]
        message.recipients = message.recipients.uniq
        return message.deliver false,sanitize_text
      end

      #Basic reply method. USE NOT RECOMENDED.
      #Use reply_to_sender, reply_to_all and reply_to_conversation instead.
      def reply(conversation, recipients, reply_body, subject=nil, sanitize_text=true, attachment=nil)
        subject = subject || "RE: #{conversation.subject}"
        response = messages.new({:body => reply_body, :subject => subject, :attachment => attachment})
        response.conversation = conversation
        response.recipients = recipients.is_a?(Array) ? recipients : [recipients]
        response.recipients = response.recipients.uniq
        response.recipients.delete(self)
        return response.deliver true, sanitize_text
      end

      #Replies to the sender of the message in the conversation
      def reply_to_sender(receipt, reply_body, subject=nil, sanitize_text=true, attachment=nil)
        return reply(receipt.conversation, receipt.message.sender, reply_body, subject, sanitize_text, attachment)
      end

      #Replies to all the recipients of the message in the conversation
      def reply_to_all(receipt, reply_body, subject=nil, sanitize_text=true, attachment=nil)
        return reply(receipt.conversation, receipt.message.recipients, reply_body, subject, sanitize_text, attachment)
      end

      #Replies to all the recipients of the last message in the conversation and untrash any trashed message by messageable
      #if should_untrash is set to true (this is so by default)
      def reply_to_conversation(conversation, reply_body, subject=nil, should_untrash=true, sanitize_text=true, attachment=nil)
        #move conversation to inbox if it is currently in the trash and should_untrash parameter is true.
        if should_untrash && mailbox.is_trashed?(conversation)
          mailbox.receipts_for(conversation).untrash
        end
        return reply(conversation, conversation.last_message.recipients, reply_body, subject, sanitize_text, attachment)
      end

      #Mark the object as read for messageable.
      #
      #Object can be:
      #* A Receipt
      #* A Message
      #* A Notification
      #* A Conversation
      #* An array with any of them
      def mark_as_read(obj)
        case obj
        when Receipt
          return obj.mark_as_read if obj.receiver == self
        when Message, Notification
          obj.mark_as_read(self)
        when Conversation
          obj.mark_as_read(self)
        when Array
          obj.map{ |sub_obj| mark_as_read(sub_obj) }
        else
          return nil
        end
      end

      #Mark the object as unread for messageable.
      #
      #Object can be:
      #* A Receipt
      #* A Message
      #* A Notification
      #* A Conversation
      #* An array with any of them
      def mark_as_unread(obj)
        case obj
        when Receipt
          return obj.mark_as_unread if obj.receiver == self
        when Message, Notification
          obj.mark_as_unread(self)
        when Conversation
          obj.mark_as_unread(self)
        when Array
          obj.map{ |sub_obj| mark_as_unread(sub_obj) }
        else
        return nil
        end
      end

      #Mark the object as trashed for messageable.
      #
      #Object can be:
      #* A Receipt
      #* A Message
      #* A Notification
      #* A Conversation
      #* An array with any of them
      def trash(obj)
        case obj
        when Receipt
          return obj.move_to_trash if obj.receiver == self
        when Message, Notification
          obj.move_to_trash(self)
        when Conversation
          obj.move_to_trash(self)
        when Array
          obj.map{ |sub_obj| trash(sub_obj) }
        else
        return nil
        end
      end

      #Mark the object as not trashed for messageable.
      #
      #Object can be:
      #* A Receipt
      #* A Message
      #* A Notification
      #* A Conversation
      #* An array with any of them
      def untrash(obj)
        case obj
        when Receipt
          return obj.untrash if obj.receiver == self
        when Message, Notification
          obj.untrash(self)
        when Conversation
          obj.untrash(self)
        when Array
          obj.map{ |sub_obj| untrash(sub_obj) }
        else
        return nil
        end
      end

      def search_messages(query)
        @search = Receipt.search do
          fulltext query
          with :receiver_id, self.id
        end

        @search.results.map { |r| r.conversation }.uniq
      end
    end
  end
end