text:
from __future__ import division

from BitTorrent.platform import install_translation
install_translation()

import sys
import os
import threading

from time import time, strftime, sleep
from cStringIO import StringIO

from Axon.ThreadedComponent import threadedcomponent
from Axon.Component import component

from BitTorrent.download import Feedback, Multitorrent
from BitTorrent.defaultargs import get_defaults
from BitTorrent.parseargs import printHelp
from BitTorrent.zurllib import urlopen
from BitTorrent.bencode import bdecode
from BitTorrent.ConvertedMetainfo import ConvertedMetainfo
from BitTorrent.prefs import Preferences
from BitTorrent import configfile
from BitTorrent import BTFailure
from BitTorrent import version
from BitTorrent import GetTorrent

class Lagger(component):
	def main(self):
		while 1:
			yield 1
			sleep(0.05)

class TorrentClient(threadedcomponent):
    """Using threadedcomponent so we don't have to worry about blocking IO or making
    mainline yield periodically"""

    Inboxes  = { "inbox"   : "Commands, e.g. shutdown",
                "control" : "NOT USED",
              }
    Outboxes = { "outbox" : "State change information, e.g. finished",
                "signal" : "NOT USED",
              }

    def __init__(self, torrentfilename):
        super(TorrentClient, self).__init__()
        self.torrentfilename = torrentfilename
        self.done = False

    def main(self):
        print "TorrentClient.run"
        """Main loop"""
        uiname = 'bittorrent-console'
        defaults = get_defaults(uiname)
        defaults.append(('twisted', 0,
     _("Use Twisted network libraries for network connections. 1 means use twisted, 0 means do not use twisted, -1 means autodetect, and prefer twisted")))

        metainfo = None
        config, args = configfile.parse_configuration_and_args(defaults, uiname)

        try:
            metainfo, errors = GetTorrent.get( self.torrentfilename )
            if errors:
                raise BTFailure(_("Error reading .torrent file: ") + '\n'.join(errors))
            else:
                self.dl = DLKamaelia(metainfo, config, self)
                self.dl.run()
        except BTFailure, e:
            print str(e)
            sys.exit(1)
        self.outqueues["outbox"].put("exited")

    def checkInboxes(self):
        while not self.inqueues["inbox"].empty():
            command = self.inqueues["inbox"].get()
            if command == "shutdown":
                self.dl.multitorrent.rawserver.doneflag.set()

    def finished(self):
        """Called by DL class when the download has completed successfully"""
        self.done = True
        self.send("complete", "outbox")
        print "BitTorrent debug: finished"

    def error(self, errormsg):
        """Called by DL if an error occurs"""
        print strftime('[%H:%M:%S] ') + errormsg
        self.send("failed", "outbox")

    def display(self, statistics):
        """Called by DL to display status updates"""
        # Forward on to next component
        self.send(statistics, "outbox")

    def set_torrent_values(self, name, path, size, numpieces):
        self.file = name
        self.downloadTo = path
        self.fileSize = size
        self.numpieces = numpieces

class DLKamaelia(Feedback):
    """This class accepts feedback from the multitorrent downloader class
    which it can then pass back to the inboxes of TorrentClient"""
    def __init__(self, metainfo, config, interface):
        self.doneflag = threading.Event()
        self.metainfo = metainfo
        self.config = Preferences().initWithDict(config)
        self.d = interface

    def run(self):
        try:
            self.multitorrent = Multitorrent(self.config, self.doneflag,
                                             self.global_error)
            # raises BTFailure if bad
            metainfo = ConvertedMetainfo(bdecode(self.metainfo))
            torrent_name = metainfo.name_fs
            if self.config['save_as']:
                if self.config['save_in']:
                    raise BTFailure(_("You cannot specify both --save_as and "
                                      "--save_in"))
                saveas = self.config['save_as']
            elif self.config['save_in']:
                saveas = os.path.join(self.config['save_in'], torrent_name)
            else:
                saveas = torrent_name

            self.d.set_torrent_values(metainfo.name, os.path.abspath(saveas),
                                metainfo.total_bytes, len(metainfo.hashes))
            self.torrent = self.multitorrent.start_torrent(metainfo,
                                Preferences(self.config), self, saveas)
        except BTFailure, e:
            print str(e)
            return
        self.get_status()
        #self.multitorrent.rawserver.install_sigint_handler() - can only be done on the main thread so does not work with Kamaelia
        self.multitorrent.rawserver.listen_forever( self.d )
        self.d.display({'activity':_("shutting down"), 'fractionDone':0})
        self.torrent.shutdown()
        print "BitTorrent Debug: shutting down"

    def reread_config(self):
        try:
            newvalues = configfile.get_config(self.config, 'bittorrent-console')
        except Exception, e:
            self.d.error(_("Error reading config: ") + str(e))
            return
        self.config.update(newvalues)
        # The set_option call can potentially trigger something that kills
        # the torrent (when writing this the only possibility is a change in
        # max_files_open causing an IOError while closing files), and so
        # the self.failed() callback can run during this loop.
        for option, value in newvalues.iteritems():
            self.multitorrent.set_option(option, value)
        for option, value in newvalues.iteritems():
            self.torrent.set_option(option, value)

    def get_status(self):
        self.multitorrent.rawserver.add_task(self.get_status,
                                             self.config['display_interval'])
        status = self.torrent.get_status(self.config['spew'])
        self.d.display(status)

    def global_error(self, level, text):
        self.d.error(text)

    def error(self, torrent, level, text):
        self.d.error(text)

    def failed(self, torrent, is_external):
        self.doneflag.set()

    def finished(self, torrent):
        self.d.finished()

if __name__ == '__main__':
    from Kamaelia.Util.PipelineComponent import pipeline
    from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer

    # download a linux distro
    pipeline(
        ConsoleReader(">>> ", ""),
        TorrentClient("http://www.tlm-project.org/public/distributions/damnsmall/current/dsl-2.4.iso.torrent"),
        ConsoleEchoer(),
    ).run()


text:
require 'spec_helper'

describe GrooveHQ::Client::Customers, integration: true do

  let(:client) { GrooveHQ::Client.new }
  let(:customer_email) { "customer@example.com" }

  describe "#update_customer" do

    it "updates customer info" do
      customer = client.customer(customer_email)
      new_about_text = "Some new about text"
      response = client.update_customer(customer_email, about: new_about_text)
      expect(customer.about).to eq new_about_text
      expect(response.rels[:tickets].href).to eq "http://api.groovehq.com/v1/tickets?customer=#{customer.id}"
    end

  end

  describe "#customer" do

    let(:response) { client.customer(customer_email) }

    it "successfully gets customer" do
      expect(response.data).to have_attributes(id: String, email: String)
    end

    it "gets the right customer info" do
      expect(response.data).to have_attributes(email: customer_email, name: "Testcustomer")
    end

  end

  describe "#customers" do

    let(:response) { client.customers }

    it "successfully gets customers" do
      expect(response).to be_instance_of GrooveHQ::ResourceCollection
    end

    it "gets the right customers info" do
      expect(response.any? { |customer| customer.email == customer_email }).to be true
    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
var chai = require('chai');
var should = chai.should();
var location = require('../../../../lib/model/response/vehicle/location');

describe('location model test', function () {

  it('should create model', function (done) {

    var locationModel = new location.Location('wielkopolskie', 'PL');
    should.exist(locationModel);
    locationModel.state.should.be.equal('wielkopolskie');
    locationModel.country.should.be.equal('PL');

    done();
  });

  it('should create model by builder', function (done) {

    var locationModel = new location.LocationBuilder()
      .withState('wielkopolskie')
      .withCountry('PL')
      .build();

    should.exist(locationModel);
    locationModel.state.should.be.equal('wielkopolskie');
    locationModel.country.should.be.equal('PL');

    done();
  });

});


text:
package cn.fmachine.lintcode.easy;

import cn.fmachine.lintcode.util.TreeNode;

import java.util.ArrayList;

/**
 * Given a binary tree, return the postorder traversal of its nodes' values.
 *

 * Have you met this question in a real interview? Yes
 * Example
 * Given binary tree {1,#,2,3},
 *

 * 1
 * \
 * 2
 * /
 * 3
 *

 *

 * return [3,2,1].
 *

 * Challenge
 * Can you do it without recursion?
 *

 * Tags
 * Recursion Binary Tree Binary Tree Traversal
 * Related Problems
 * Easy Binary Tree Preorder Traversal
 * algorithm
 * Author: XIN MING
 * Date: 10/19/16
 */
public class BinaryTreePostorderTraversal {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<>();
        if (root == null) return result;

        //divide
        ArrayList<Integer> left = postorderTraversal(root.left);
        ArrayList<Integer> right = postorderTraversal(root.right);
        //conquer
        result.addAll(left);
        result.addAll(right);
        result.add(root.val);
        return result;
    }

}


text:
package org.openengsb.issues.github;

import org.openengsb.core.OpenEngSBComponent;

/**
 * @org.apache.xbean.XBean element="githubComponent"
 *                         description="Github Issue Tracker Component"
 */
public class GithubComponent extends OpenEngSBComponent {
    @Override
    protected Class<?>[] getEndpointClasses() {
        return new Class[] { GithubEndpoint.class };
    }

}


text:
css-tinter
=========

Pure-CSS tinter


text:
namespace mesos {
namespace internal {
namespace master {
namespace maintenance {

using namespace mesos::maintenance;

using google::protobuf::RepeatedPtrField;

UpdateSchedule::UpdateSchedule(
    const maintenance::Schedule& _schedule)
  : schedule(_schedule) {}

Try<bool> UpdateSchedule::perform(
    Registry* registry,
    hashset<SlaveID>* slaveIDs,
    bool strict)
{
  // Put the machines in the existing schedule into a set.
  hashset<MachineID> existing;
  foreach (const maintenance::Schedule& agenda, registry->schedules()) {
    foreach (const maintenance::Window& window, agenda.windows()) {
      foreach (const MachineID& id, window.machine_ids()) {
        existing.insert(id);
      }
    }
  }

  // Put the machines in the updated schedule into a set.
  // Keep the relevant unavailability to help update existing machines.
  hashmap<MachineID, Unavailability> updated;
  foreach (const maintenance::Window& window, schedule.windows()) {
    foreach (const MachineID& id, window.machine_ids()) {
      updated[id] = window.unavailability();
    }
  }

  // This operation overwrites the existing schedules with a new one.
  // At the same time, every machine in the schedule is saved as a
  // `MachineInfo` in the registry.

  // TODO(josephw): allow more than one schedule.

  // Loop through and modify the existing `MachineInfo` entries.
  for (int i = registry->machines().machines().size() - 1; i >= 0; i--) {
    const MachineID& id = registry->machines().machines(i).info().id();

    // Update the `MachineInfo` entry for all machines in the schedule.
    if (updated.contains(id)) {
      registry->mutable_machines()->mutable_machines(i)->mutable_info()
        ->mutable_unavailability()->CopyFrom(updated[id]);

      continue;
    }

    // Delete the `MachineInfo` entry for each removed machine.
    registry->mutable_machines()->mutable_machines()->DeleteSubrange(i, 1);
  }

  // Create new `MachineInfo` entries for each new machine.
  foreach (const maintenance::Window& window, schedule.windows()) {
    foreach (const MachineID& id, window.machine_ids()) {
      if (existing.contains(id)) {
        continue;
      }

      // Each newly scheduled machine starts in `DRAINING` mode.
      Registry::Machine* machine = registry->mutable_machines()->add_machines();
      MachineInfo* info = machine->mutable_info();
      info->mutable_id()->CopyFrom(id);
      info->set_mode(MachineInfo::DRAINING);
      info->mutable_unavailability()->CopyFrom(window.unavailability());
    }
  }

  // Replace the old schedule with the new schedule.
  registry->clear_schedules();
  registry->add_schedules()->CopyFrom(schedule);

  return true; // Mutation.
}

StartMaintenance::StartMaintenance(
    const RepeatedPtrField<MachineID>& _ids)
{
  foreach (const MachineID& id, _ids) {
    ids.insert(id);
  }
}

Try<bool> StartMaintenance::perform(
    Registry* registry,
    hashset<SlaveID>* slaveIDs,
    bool strict)
{
  // Flip the mode of all targeted machines.
  bool changed = false;
  for (int i = 0; i < registry->machines().machines().size(); i++) {
    if (ids.contains(registry->machines().machines(i).info().id())) {
      // Flip the mode.
      registry->mutable_machines()->mutable_machines(i)
        ->mutable_info()->set_mode(MachineInfo::DOWN);

      changed = true; // Mutation.
    }
  }

  return changed;
}

StopMaintenance::StopMaintenance(
    const RepeatedPtrField<MachineID>& _ids)
{
  foreach (const MachineID& id, _ids) {
    ids.insert(id);
  }
}

Try<bool> StopMaintenance::perform(
    Registry* registry,
    hashset<SlaveID>* slaveIDs,
    bool strict)
{
  // Delete the machine info entry of all targeted machines.
  // i.e. Transition them into `UP` mode.
  bool changed = false;
  for (int i = registry->machines().machines().size() - 1; i >= 0; i--) {
    if (ids.contains(registry->machines().machines(i).info().id())) {
      registry->mutable_machines()->mutable_machines()->DeleteSubrange(i, 1);

      changed = true; // Mutation.
    }
  }

  // Delete the machines from the schedule.
  for (int i = registry->schedules().size() - 1; i >= 0; i--) {
    maintenance::Schedule* schedule = registry->mutable_schedules(i);

    for (int j = schedule->windows().size() - 1; j >= 0; j--) {
      maintenance::Window* window = schedule->mutable_windows(j);

      // Delete individual machines.
      for (int k = window->machine_ids().size() - 1; k >= 0; k--) {
        if (ids.contains(window->machine_ids(k))) {
          window->mutable_machine_ids()->DeleteSubrange(k, 1);
        }
      }

      // If the resulting window is empty, delete it.
      if (window->machine_ids().size() == 0) {
        schedule->mutable_windows()->DeleteSubrange(j, 1);
      }
    }

    // If the resulting schedule is empty, delete it.
    if (schedule->windows().size() == 0) {
      registry->mutable_schedules()->DeleteSubrange(i, 1);
    }
  }

  return changed;
}

namespace validation {

Try<Nothing> schedule(
    const maintenance::Schedule& schedule,
    const hashmap<MachineID, Machine>& machines)
{
  hashset<MachineID> updated;
  foreach (const maintenance::Window& window, schedule.windows()) {
    // Check that each window has at least one machine.
    if (window.machine_ids().size() == 0) {
      return Error("List of machines in the maintenance window is empty");
    }

    // Check the time specified by the unavailability.
    Try<Nothing> unavailability =
      maintenance::validation::unavailability(window.unavailability());

    if (unavailability.isError()) {
      return Error(unavailability.error());
    }

    // Collect machines from the updated schedule into a set.
    foreach (const MachineID& id, window.machine_ids()) {
      // Validate the single machine.
      Try<Nothing> validId = validation::machine(id);
      if (validId.isError()) {
        return Error(validId.error());
      }

      // Check that the machine is unique.
      if (updated.contains(id)) {
        return Error(
            "Machine '" + stringify(JSON::protobuf(id)) +
              "' appears more than once in the schedule");
      }

      updated.insert(id);
    }
  }

  // Ensure that no `DOWN` machine is removed from the schedule.
  foreachpair (const MachineID& id, const Machine& machine, machines) {
    if (machine.info.mode() == MachineInfo::DOWN && !updated.contains(id)) {
      return Error(
          "Machine '" + stringify(JSON::protobuf(id)) +
            "' is deactivated and cannot be removed from the schedule");
    }
  }

  return Nothing();
}

Try<Nothing> unavailability(const Unavailability& unavailability)
{
  const Duration duration =
    Nanoseconds(unavailability.duration().nanoseconds());

  // Check the bounds of the unavailability.
  if (duration < Duration::zero()) {
    return Error("Unavailability 'duration' is negative");
  }

  return Nothing();
}

Try<Nothing> machines(const RepeatedPtrField<MachineID>& ids)
{
  if (ids.size() <= 0) {
    return Error("List of machines is empty");
  }

  // Verify that the machine has at least one non-empty field value.
  hashset<MachineID> uniques;
  foreach (const MachineID& id, ids) {
    // Validate the single machine.
    Try<Nothing> validId = validation::machine(id);
    if (validId.isError()) {
      return Error(validId.error());
    }

    // Check machine uniqueness.
    if (uniques.contains(id)) {
      return Error(
          "Machine '" + stringify(JSON::protobuf(id)) +
            "' appears more than once in the schedule");
    }

    uniques.insert(id);
  }

  return Nothing();
}

Try<Nothing> machine(const MachineID& id)
{
  // Verify that the machine has at least one non-empty field value.
  if (id.hostname().empty() && id.ip().empty()) {
    return Error("Both 'hostname' and 'ip' for a machine are empty");
  }

  // Validate the IP field.
  if (!id.ip().empty()) {
    Try<net::IP> ip = net::IP::parse(id.ip(), AF_INET);
    if (ip.isError()) {
      return Error(ip.error());
    }
  }

  return Nothing();
}

} // namespace validation {
} // namespace maintenance {
} // namespace master {
} // namespace internal {
} // namespace mesos {


text:
package vidada.viewsFX.player;

import archimedes.core.events.EventArgs;
import archimedes.core.events.IEvent;

public interface IMediaPlayerService {

	/**
	 * Abstract representation of a media player
	 * @author IsNull
	 *
	 */
	static interface IMediaPlayerComponent {
		/**
		 * Raised when this shared MediaPlayer component should be released by its current user
		 * @return
		 */
		IEvent<EventArgs> getRequestReleaseEvent();

		/**
		 * Represents an shared media player visual Node
		 */
		MediaPlayerFx getSharedPlayer();

	}

	/**
	 * Gets a (shared) media player
	 * @return
	 */
	IMediaPlayerComponent resolveMediaPlayer();

	/**
	 * Is a media player available?
	 * @return
	 */
	boolean isMediaPlayerAvaiable();

}


text:
package droidack;

public interface IFragmentHostState<E extends Enum<E>>
	     extends IViewState<E> {

	/**
	 * Call from child.onCreate(parent) if hosting a Fragment (the
	 * normal case);  otherwise just call super.onCreate(parent) directly
	 *
	 * @param parent - the AFragmentHostModule parent
	 * @param fragmentName - class name for the hosted Fragment;
	 * @param layoutId - resource ID for hosted fragment layout
	 */
	void onCreate(IControlModule<IControl> parent, String fragmentName,
			int layoutId);
}


text:
namespace SceneEngine
{
    class PerlinNoiseResources
    {
    public:
        class Desc {};

        PerlinNoiseResources(const Desc& desc);
        ~PerlinNoiseResources();

        using SRV = RenderCore::Metal::ShaderResourceView;
        SRV _gradShaderResource;
        SRV _permShaderResource;
    };
}


text:
extern "C" bool LoaderLockDetected();

namespace crashpad {
namespace test {
namespace {

TEST(LoaderLock, Detected) {
  EXPECT_FALSE(IsThreadInLoaderLock());
  auto* loader_lock_detected = GET_FUNCTION_REQUIRED(
      L"crashpad_util_test_loader_lock_test.dll", LoaderLockDetected);
  EXPECT_TRUE(loader_lock_detected());
  EXPECT_FALSE(IsThreadInLoaderLock());
}

}  // namespace
}  // namespace test
}  // namespace crashpad


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>LevelMap Members</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

LevelMap Members

        LevelMap overview

Public Instance Constructors

              LevelMap Constructor

             Construct the level map

Public Instance Properties

AllLevels	 Return all possible levels as a list of Level objects.

Item	 Lookup a Level by name

Public Instance Methods

Add	Overloaded.  Create a new Level and add it to the map

Clear	 Clear the internal maps of all levels

Equals (inherited from Object)

GetHashCode (inherited from Object)

GetType (inherited from Object)

LookupWithDefault	 Lookup a named level from the map

ToString (inherited from Object)

See Also

        LevelMap Class | log4net.Core Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="LevelMap class">
        </param>
        <param name="Keyword" value="log4net.Core.LevelMap class">
        </param>
        <param name="Keyword" value="LevelMap class, all members">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
<?xml version="1.0" ?>
<TestSuite>
        <Details>
                <Name>ts_runmode_ruf_at_ts_local_level</Name>
                <Title>test suite to run runmode(RMT) at testsuite file local section</Title>
                <Engineer>Warrior_user</Engineer>
                <random_tc_Execution>true</random_tc_Execution>
                <Date>07-18-2018</Date>
                <Time>11:37:26</Time>
                <default_onError action="next"/>
                <Resultsdir/>
        </Details>
        <Requirements>
                <Requirement>Requirement-001</Requirement>
                <Requirement>Requirement-002</Requirement>
        </Requirements>
        <Testcases>
            <Testcase>
                        <path>../../../testcases/framework_tests/runmode_tests/tc_runmode_ruf_at_ts_local_level.xml</path>
                        <context>positive</context>
                        <runtype>sequential_keywords</runtype>
                        <onError action="next"/>
			            <runmode type="RUF" value="7"/>
                        <impact>noimpact</impact>
            </Testcase>
            <Testcase>
                        <path>../../../testcases/framework_tests/runmode_tests/tc_runmode_ruf_at_ts_local_level_with_last_instance.xml</path>
                        <context>positive</context>
                        <runtype>sequential_keywords</runtype>
                        <onError action="next"/>
			            <runmode type="RUF" value="4" status="last_instance"/>
                        <impact>noimpact</impact>
            </Testcase>
            <Testcase>
                        <path>../../../testcases/framework_tests/runmode_tests/tc_runmode_ruf_at_ts_local_level_with_expected.xml</path>
                        <context>positive</context>
                        <runtype>sequential_keywords</runtype>
                        <onError action="next"/>
			            <runmode type="RUF" value="4" status="expected"/>
                        <impact>impact</impact>
            </Testcase>
        </Testcases>
</TestSuite>


text:
function g = modelGradient(params, model, varargin)

% MODELGRADIENT Gradient of error function to minimise for given model.
% FORMAT
% DESC gives the gradient of the objective function for a model. By
% default the objective function is a negative log likelihood.
% ARG params : parameter vector to evaluate at.
% ARG model : model structure to optimise.
% ARG P1, P2, P3 ... : optional additional arguments.
% RETURN g : the gradient of the error function to be minimised.
%
% SEEALSO : modelLogLikeGradient, modelObjective, modelOptimise
%
% COPYRIGHT : Neil D. Lawrence, 2006

% MLTOOLS

fhandle = [model.type 'Gradient'];
if exist(fhandle) == 2
  fhandle = str2func(fhandle);
  g = fhandle(params, model, varargin{:});
else
  fhandle = str2func([model.type 'ExpandParam']);
  model = fhandle(model, params);
  fhandle = str2func([model.type 'LogLikeGradients']);
  g = - fhandle(model, varargin{:});
end


text:
// #docplaster
// #docregion
import { TestBed, async } from '@angular/core/testing';
// #enddocregion
import { AppComponent } from './app-initial.component';
/*
// #docregion
import { AppComponent } from './app.component';

describe('AppComponent', () => {
// #enddocregion
*/
describe('AppComponent (initial CLI version)', () => {
  // #docregion
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'app'`, async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app');
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
  }));
});
// #enddocregion

/// As it should be
import { DebugElement } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';

describe('AppComponent (initial CLI version - as it should be)', () => {

  let app: AppComponent;
  let de: DebugElement;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    });

    fixture = TestBed.createComponent(AppComponent);
    app = fixture.componentInstance;
    de = fixture.debugElement;
  });

  it('should create the app', () => {
    expect(app).toBeDefined();
  });

  it(`should have as title 'app'`, () => {
    expect(app.title).toEqual('app');
  });

  it('should render title in an h1 tag', () => {
    fixture.detectChanges();
    expect(de.nativeElement.querySelector('h1').textContent)
      .toContain('Welcome to app!');
  });
});


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Categoria extends CI_Controller {

	public function __construct(){
		parent::__construct();
		if(!$this->session->userdata('logado')){
			redirect(base_url('admin/login'));
		}
		$this->load->model('categorias_model','modelcategorias');
		$this->categorias = $this->modelcategorias->listar_categorias();
		$this->load->model('usuarios_model','modelusuarios');
	}

	public function index($publicado = null)
	{
		$this->load->library('table');
		$dados['categorias'] = $this->categorias;
		//dados para o cabeçalho
		$dados['titulo'] ='Painel de Controle';
		$dados['subtitulo'] ='Categoria';
		$dados['publicado']= $publicado;

		$this->load->view('backend/template/html-header',$dados);
		$this->load->view('backend/template/template');
		$this->load->view('backend/categoria');
		$this->load->view('backend/template/html-footer');
	}
	public function inserir(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('txt-categoria','Nome da Categoria',
			'required|min_length[3]|is_unique[categoria.titulo]'); //valida tres coisas do form: required>preenchido? is_unique>existe outro titulo igual no banco?
		if($this->form_validation->run() == false){
			$this->index();
		}else{
			$titulo=$this->input->post('txt-categoria');  //envia por post o txt-categoria
			if($this->modelcategorias->adicionar($titulo)){ //se conseguiu adicionar
				redirect(base_url('admin/categoria/1'));
			}else{
				echo "Houve um erro no sistema!";
			}
		}
	}

	public function excluir($id){
		if($this->modelcategorias->excluir($id)){ //se conseguiu adicionar
			redirect(base_url('admin/categoria'));
		}else{
			echo "Houve um erro no sistema!";
		}
	}

	public function alterar($id){
		$this->load->library('table');
		$dados['categorias'] = $this->modelcategorias->listar_categoria($id);
		//dados para o cabeçalho
		$dados['titulo'] ='Painel de Controle';
		$dados['subtitulo'] ='Categoria';

		$this->load->view('backend/template/html-header',$dados);
		$this->load->view('backend/template/template');
		$this->load->view('backend/alterar-categoria');
		$this->load->view('backend/template/html-footer');
	}

	public function salvaralteracoes($idCrip){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('txt-categoria','Nome da Categoria',
			'required|min_length[3]|is_unique[categoria.titulo]'); //valida tres coisas do form: required>preenchido? is_unique>existe outro titulo igual no banco?
		if($this->form_validation->run() == false){
			$this->alterar($idCrip);
		}else{
			$titulo=$this->input->post('txt-categoria');  //envia por post o txt-categoria
			$id = $this->input->post('txt-id');
			if($this->modelcategorias->alterar($titulo,$id)){ //se conseguiu adicionar
				redirect(base_url('admin/categoria'));
			}else{
				echo "Houve um erro no sistema!";
			}
		}
	}
}


text:
# Dizi
## API in a Nutshell
### Version: 1.0.0

#### Methods:
##### Http & Templating
* `.render()` Reading & Rendering a template using object dataset. Parameters:
    * document (String: file adress/text)
    * dataset (object {tagX: replacementY}) _optional
    * encoding (default:'utf8') _optional

*.render() method, also looks for 'same_file_name.json' in same path for localisation and templating. That json file may be like this:*
```
// same/path/same_file_name.json :
{
    'localisation':{
        'en':{
            'dinner': 'dizi'
        },
        'fa':{
            'dinner': 'دیزی'
        }
    },
    'tag': 'Replaced tag',
    'another tag': 'another Replacement'
}
```

* `.parse(nodejs_request, req_body_buffer)`
Parses request body etc >> server_handler function

* `.createServer(handler<function>, port<number>)`
Creates and returns instance of http server.
    * handler_function (Integrated_parsed_request [obj], nodejs_req, nodejs_res) {
        * Integrated_parsed_request (ipr) object includes:
            1. headers: object {host, 'content-type', remote, method, etc...}
            2. post: object (Multipart/Form-data) { files[{name, filename, value, length, etc...}, ...], fields{name:{value}, name:[val1,val2]...}}
            3. post: buffer / json / etc
            4. url:  String '/home/page/search?q=value'
            5. path: array of path steps ['home','page']
            6. target: string 'search'
            7. query: object {'q':'value'}
            8. session: object {id, token, data(user defined), last-attempt, etc...}
            9. cookie: object {'cook':'value',...}
        * /* you can response, NodeJs like: */ nodejs_res.writeHead(xx)
        * /* or simply: */ return
            1. boolean (false: e404 / true: app.document)
            2. String  (Looking for html tags, then: text/plain | text/html)
            3. Object  (application/json)
            4. Buffer / File

    };
* `.route('from','to')`

* `<ipr.post.file[i]>.save()`
Returns Absolute Path of Saved File.
Optional Parameters:
    * filename
    * path
    * options {encoding, mode, flag} / 'utf8'
    * callback

*Note: `.save(true)` saves file with its name to default media `.folder` path and `.save(null)` creates a unique file name using current times stamp.*

##### Sessioning
* dizi`.sessioning`
    * [max-age] (seconds)
    * .decay (seconds)
    * .check-interval (seconds)
* ipr`.session`
    * `.sign(id<string>, data<userdefined|null>, Decay<seconds|7*60>)`
    * `.set(id<Default this.id>, data<userdefined>)`
    * `.get(id)` // returns session by id default current session
    * `.update(id<Default this.id>)` // updates Last-attempt to current time
    * `.isActive(id<Default this.id>)` // boolean
    * `.check(id<Default this.id>)` // status number (-1,0,1 : fired, decayed, active) + used in automatic expire Check

##### Cookie
* ipr`.cookie`
    * `.set('name','value',{'Duration':<secounds>, HttpOnly:<boolean>, Secure:<boolean>, 'Max-Age':<secounds>, Path:<null/string>, Domain:<null/string>});`
    * `.set('name','value',60)` // expires after 60 seconds
    * `.set('name','value','flags like: HttpOnly;')`

##### Jodo (JavaScript Object Database Operation)
Creating a Jodo database object:
* dizi`.jodo('path/to/file.json')`
* dizi`.jodo(object)`
each returns jodo-object, with these properties:

    * jodo-object`.path` String (path of flat json file)

    * jodo-object`.save()` saves current state of object to json file.
    * jodo-object`.save('Optional_Path/to/file.json')` saves current state of object to new json file.

    * jodo-object`.any()` // Search Function. parameters:
        * field (string) where to search
        * condition (optional - string: !=|>=|... Default: '==')
        * value (string) what to search
        * Case insensetive (boolean - Default:true)
        * Manipulator_function (value, entry) // call on each found value and entry
    * nested-jodo-object|subfields`.any()` // to the deeper levels
    Exmple: db.any()  db.users.any()  db.users.persians.any()

#### Events
Dizi Apps are Naturally Event Emitters:
* `render` : Rendering is done and app.document is ready.
* `render_callback` : Callback of render function is invoked.
* `request_ready` : Request & its body are completely received.
* `limit` : Payload Too Large >> Request is truncated to limit (dizi.limit).
* `session_created`
* `session_exited`
* `session_fired`

#### Properties
Any Instance of Dizi has this Properties:
* `.index` String (html file/Adress)
* `.folder` String -- Path to Media Folder (Default: 'root/saved_files');
* `.tagMarker` String (like '#' for #tags) / Array (like ['%','%'] for %tags%)
* `.callback` Function (Will be called, if there is not any callback for .render method -- Default: undefined)
* `.e404` Object (Default 404 Page. like: {data:'Not Found', 'content-type':'text/plain'})
* `.document` String (Stored recent result of .render method)
* `.server` Http Server (Made by .createServer method)
* `.timeout` Milliseconds (Server timeout - Default: 120000)
* `.limit` Bytes (Payload of request body - Default: 1000000 (1MB) )
* `.root` String (Default process.cwd())
* `.public` Array ['path/to/public/folder1', '/statics', ...]
* ` .localisation` Array ['en','fa']; // Available localisations (1st one is Default) // null = en
* `.renderables` Array ['html','htm','txt','xml','md','csv','text','xhtml']


text:
Chrome extension games to play in your browser
Check out the website at: https://johnmryan.github.io/chrome-games/index.html

How to install:
- enable developer mode in chrome
- load unpacked extension
- choose:  /chrome-games/src/extension/

How to add a game:
- edit the popup.html file to add the game name and play/stop buttons
- edit the popup.js file to apply your .js once your game button is clicked
- within /gameJS add your js file(s)

How to play Cannon game:
  - left right arrows to aim
  - 's' to shoot


text:
<!DOCTYPE html>

        <link rel="stylesheet" href="styles/main.css">


text:
package org.apache.synapse.util.xpath;

import junit.framework.TestCase;
import org.jaxen.Context;
import org.jaxen.ContextSupport;

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

public class Base64DecodeFunctionTest extends TestCase {

    public void testBase64DecodeFunctionWithCharset() throws Exception {
        String encodedString = "U3luYXBzZQ==";
        Base64DecodeFunction base64DecodeFunction = new Base64DecodeFunction();
        List<String> params = new ArrayList<String>();
        params.add(encodedString);
        params.add("UTF-8");
        Context context = new Context(null);
        context.setContextSupport(new ContextSupport());
        String decodedString = (String) base64DecodeFunction.call(context, params);
        assertEquals("Wrong decoded value found", "Synapse", decodedString);

    }

    public void testBase64DecodeFunctionWithoutCharset() throws Exception {
        String encodedString = "U3luYXBzZQ==";
        Base64DecodeFunction base64DecodeFunction = new Base64DecodeFunction();
        List<String> params = new ArrayList<String>();
        params.add(encodedString);
        Context context = new Context(null);
        context.setContextSupport(new ContextSupport());
        String decodedString = (String) base64DecodeFunction.call(context, params);
        assertEquals("Wrong decoded value found", "Synapse", decodedString);
    }

    public void testBase64DecodeFunctionWithoutParameters() throws Exception {
        Base64DecodeFunction base64DecodeFunction = new Base64DecodeFunction();
        List<String> params = new ArrayList<String>();
        Context context = new Context(null);
        context.setContextSupport(new ContextSupport());
        String decodedString = (String) base64DecodeFunction.call(context, params);
        assertEquals("Wrong decoded value found", "", decodedString);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>qutip.simdiag — QuTiP 4.1 Documentation</title>

    <link rel="shortcut icon" href="../../_static/favicon.ico"/>

    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />

        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="QuTiP 4.1 Documentation" href="../../index.html"/>
        <link rel="up" title="Module code" href="../index.html"/>

             QuTiP: Quantum Toolbox in Python

                4.1

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Frontmatter

Installation

Users Guide

API documentation

Change Log

Developers

Bibliography

          QuTiP: Quantum Toolbox in Python

Docs »

Module code »

qutip.simdiag

Source code for qutip.simdiag

# This file is part of QuTiP: Quantum Toolbox in Python.
#
#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
#    All rights reserved.
#
#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions are
#    met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
#       of its contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################

__all__ = ['simdiag']

import numpy as np
import scipy.linalg as la
from qutip.qobj import Qobj

[docs]def simdiag(ops, evals=True):
    """Simulateous diagonalization of communting Hermitian matrices..

    Parameters
    ----------
    ops : list/array
        ``list`` or ``array`` of qobjs representing commuting Hermitian
        operators.

    Returns
    --------
    eigs : tuple
        Tuple of arrays representing eigvecs and eigvals of quantum objects
        corresponding to simultaneous eigenvectors and eigenvalues for each
        operator.

    """
    tol = 1e-14
    start_flag = 0
    if not any(ops):
        raise ValueError('Need at least one input operator.')
    if not isinstance(ops, (list, np.ndarray)):
        ops = np.array([ops])
    num_ops = len(ops)
    for jj in range(num_ops):
        A = ops[jj]
        shape = A.shape
        if shape[0] != shape[1]:
            raise TypeError('Matricies must be square.')
        if start_flag == 0:
            s = shape[0]
        if s != shape[0]:
            raise TypeError('All matrices. must be the same shape')
        if not A.isherm:
            raise TypeError('Matricies must be Hermitian')
        for kk in range(jj):
            B = ops[kk]
            if (A * B - B * A).norm() / (A * B).norm() > tol:
                raise TypeError('Matricies must commute.')

    A = ops[0]
    eigvals, eigvecs = la.eig(A.full())
    zipped = zip(-eigvals, range(len(eigvals)))
    zipped.sort()
    ds, perm = zip(*zipped)
    ds = -np.real(np.array(ds))
    perm = np.array(perm)
    eigvecs_array = np.array(
        [np.zeros((A.shape[0], 1), dtype=complex) for k in range(A.shape[0])])

    for kk in range(len(perm)):  # matrix with sorted eigvecs in columns
        eigvecs_array[kk][:, 0] = eigvecs[:, perm[kk]]
    k = 0
    rng = np.arange(len(eigvals))
    while k < len(ds):
        # find degenerate eigenvalues, get indicies of degenerate eigvals
        inds = np.array(abs(ds - ds[k]) < max(tol, tol * abs(ds[k])))
        inds = rng[inds]
        if len(inds) > 1:  # if at least 2 eigvals are degenerate
            eigvecs_array[inds] = degen(
                tol, eigvecs_array[inds],
                np.array([ops[kk] for kk in range(1, num_ops)]))
        k = max(inds) + 1
    eigvals_out = np.zeros((num_ops, len(ds)), dtype=float)
    kets_out = np.array([Qobj(eigvecs_array[j] / la.norm(eigvecs_array[j]),
                              dims=[ops[0].dims[0], [1]],
                              shape=[ops[0].shape[0], 1])
                         for j in range(len(ds))])
    if not evals:
        return kets_out
    else:
        for kk in range(num_ops):
            for j in range(len(ds)):
                eigvals_out[kk, j] = np.real(np.dot(
                    eigvecs_array[j].conj().T,
                    ops[kk].data * eigvecs_array[j]))
        return eigvals_out, kets_out

def degen(tol, in_vecs, ops):
    """
    Private function that finds eigen vals and vecs for degenerate matrices..
    """
    n = len(ops)
    if n == 0:
        return in_vecs
    A = ops[0]
    vecs = np.column_stack(in_vecs)
    eigvals, eigvecs = la.eig(np.dot(vecs.conj().T, A.data.dot(vecs)))
    zipped = zip(-eigvals, range(len(eigvals)))
    zipped.sort()
    ds, perm = zip(*zipped)
    ds = -np.real(np.array(ds))
    perm = np.array(perm)
    vecsperm = np.zeros(eigvecs.shape, dtype=complex)
    for kk in range(len(perm)):  # matrix with sorted eigvecs in columns
        vecsperm[:, kk] = eigvecs[:, perm[kk]]
    vecs_new = np.dot(vecs, vecsperm)
    vecs_out = np.array(
        [np.zeros((A.shape[0], 1), dtype=complex) for k in range(len(ds))])
    for kk in range(len(perm)):  # matrix with sorted eigvecs in columns
        vecs_out[kk][:, 0] = vecs_new[:, kk]
    k = 0
    rng = np.arange(len(ds))
    while k < len(ds):
        inds = np.array(abs(ds - ds[k]) < max(
            tol, tol * abs(ds[k])))  # get indicies of degenerate eigvals
        inds = rng[inds]
        if len(inds) > 1:  # if at least 2 eigvals are degenerate
            vecs_out[inds] = degen(tol, vecs_out[inds],
                                   np.array([ops[jj] for jj in range(1, n)]))
        k = max(inds) + 1
    return vecs_out

        © Copyright 2011 and later, P.D. Nation, J.R. Johansson, A.J.G. Pitchford, C. Granade, and A.L. Grimsmo.
      Last updated on Jul 14, 2017.

  Built with Sphinx using a theme provided by Read the Docs.


text:
<?php

namespace Teampass\Api\Repository;

class RepositoryContainer
{
    /**
     * @var \Pimple
     */
    private $container;

    /**
     * @var array
     */
    private $repositoryMap;

    public function __construct(\Pimple $container, array $repositoryMap)
    {
        $this->container = $container;
        $this->repositoryMap = $repositoryMap;
    }

    /**
     * @param $key
     *
     * @return AbstractRepository
     *
     * @throws \Exception
     */
    public function get($key)
    {
        if (!isset($this->repositoryMap[$key])) {
            throw new \Exception(sprintf('Unknown repository name %s', $key));
        }
        $service = $this->repositoryMap[$key];

        return $this->container[$service];
    }
}


text:
import * as assert from 'assert';
import * as Supertest from "supertest";
import * as Mocha from "mocha";
import backend = require("../source/backend");

module Chassis.Tests {

    describe('Server', () => {
        var server;

        before(done => {
            backend.onReady(serverInstance => {
                server = serverInstance;
                assert.ok(!!server, "Server ready.");
                done();
            })
        });
        after(() => {
            server.close();
        });

        describe('Metadata', () => {
            it('should return all', done => {
                Supertest(server).get("/metadata").expect(200).
                end((err, res) => {
                    // HTTP status should be 200
                    assert.equal(res.status, 200);
                    assert.equal(res.body.error, undefined, "No error");

                    var metadata: Array<any> = res.body;
                    assert.equal(metadata.length, 5, "Basic metadata");
                    done();
                });
            });
        });

        describe('Data', () => {
            it('should return object descriptors', done => {
                Supertest(server).get("/data/ObjectDescriptor").expect(200).
                end((err, res) => {
                    // HTTP status should be 200
                    assert.equal(res.status, 200);
                    assert.equal(res.body.error, undefined, "No error");

                    var data: Array<any> = res.body;
                    assert.deepEqual(data, []);
                    done();
                });
            });

            it('should be able to create object descriptor', done => {
                Supertest(server)
                // .put("/data/ObjectDescriptor").send({ name: "Test" }).expect(200)
                // .end((err, res) => {
                //     // HTTP status should be 200
                //     assert.equal(res.status, 200);
                //     assert.equal(res.body.error, undefined, "No error");
                //
                //     var data = res.body;
                //     assert.ok(!!data.id);
                //     assert.equal(data.name, "Test");
                //     done();
                // });
                done();
            });

            it('should be able to delete object', done => {
                Supertest(server)
                // .delete("/data/Application/1").expect(200)
                // .end((err, res) => {
                //     // HTTP status should be 200
                //     assert.equal(res.status, 200);
                //     assert.equal(res.body.error, undefined, "No error");
                //
                //     var data = res.body;
                //     assert.ok(!!data.deleted);
                //     done();
                // });
                done();
            });
        });
    });

}

export = Chassis.Tests


text:
package com.google.copybara.git.github.api;

import com.google.api.client.util.Key;
import com.google.api.client.util.NullValue;
import com.google.api.client.util.Value;
import com.google.common.base.MoreObjects;
import javax.annotation.Nullable;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.StarlarkValue;

/**
 * Represents a GitHub App's checkRun detail.
 * https://developer.github.com/v3/checks/runs/#create-a-check-run
 * https://developer.github.com/v3/checks/runs/#response
 */
@StarlarkBuiltin(
    name = "github_check_run_obj",
    doc =
        "Detail about a check run as defined in "
            + "https://developer.github.com/v3/checks/runs/#create-a-check-run")
public class CheckRun implements StarlarkValue {

  @Key("details_url")
  @Nullable
  private String detailUrl;

  @Key("status")
  private Status status;

  @Key
  @Nullable
  private Conclusion conclusion;

  @Key("head_sha")
  private String sha;

  @Key("name")
  private String name;

  @Key private GitHubApp app;

  @Key private Output output;

  @StarlarkMethod(
      name = "detail_url",
      doc = "The URL of the integrator's site that has the full details of the check.",
      structField = true,
      allowReturnNones = true
  )
  @Nullable
  public String getDetailUrl() {
    return detailUrl;
  }

  @StarlarkMethod(
      name = "status",
      doc = "The current status of the check run. Can be one of queued, in_progress, or completed.",
      structField = true
  )
  public String getStatus() {
    return status.toString().toLowerCase();
  }

  @StarlarkMethod(
      name = "conclusion",
      doc = "The final conclusion of the check. Can be one of success, failure, neutral, "
          + "cancelled, timed_out, or action_required.",
      structField = true,
      allowReturnNones = true
  )
  @Nullable
  public String getConclusion() {
    return conclusion == null ? null : conclusion.toString().toLowerCase();
  }

  @StarlarkMethod(
      name = "sha",
      doc = "The SHA-1 the check run is based on",
      structField = true
  )
  public String getSha() {
    return sha;
  }

  @StarlarkMethod(
      name = "name",
      doc = "The name of the check",
      structField = true
  )
  public String getName() {
    return name;
  }

  @StarlarkMethod(
      name = "app",
      doc = "The detail of a GitHub App, such as id, slug, and name",
      structField = true
  )
  public GitHubApp getApp() {
    return app;
  }

  @StarlarkMethod(
      name = "output",
      doc = "The description of a GitHub App's run, including title, summary, text.",
      structField = true
  )
  public Output getOutput() {
    return output;
  }

  /**
   * Status of a check run
   */
  public enum Status {
    @Value("queued") QUEUED,
    @Value("in_progress") IN_PROGRESS,
    @Value("completed") COMPLETED;
  }

  /**
   * Conclusion of a check run status
   */
  public enum Conclusion {
    @NullValue NONE,
    @Value("success") SUCCESS,
    @Value("failure") FAILURE,
    @Value("neutral") NEUTRAL,
    @Value("timed_out") TIMEDOUT,
    @Value("cancelled") CANCELLED,
    @Value("action_required") ACTIONREQUIRED,
    @Value("skipped") SKIPPED;
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("details_url", detailUrl)
        .add("status", status)
        .add("conclusion", conclusion)
        .add("sha", sha)
        .add("name", name)
        .add("app", app)
        .add("output", output)
        .toString();
  }
}


text:
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE GADTs                 #-}
{-# LANGUAGE MonadComprehensions   #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RebindableSyntax      #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE UndecidableInstances  #-}
{-# LANGUAGE ViewPatterns          #-}

-- | Queries over the stock trading schema from the AQuery paper by Lerner and
-- Shasha (VLDB 2003).
module Queries.AQuery.Trades
    ( bestProfit
    , last10
    ) where

import           Database.DSH
import           Prelude       ()

import           Schema.AQuery

--------------------------------------------------------------------------------
-- For a given date and stock, compute the best profit obtained by
-- buying the stock and selling it later.
--
-- The SQL query shown in the original paper:
--
-- select max(running_diff)
-- from (select t_tid, t_tradedate,
--              t_price - min(t_price) over
--                (partition by t_tid, t_tradedate
-- 	        order by t_timestamp
--                 rows unbounded preceding)
--                as running_diff
--       from trades) as t1
-- where t_tid = 94 and t_tradedate = 15;S
--
-- The same query with the predicate pushed down:
--
-- select max(running_diff)
-- from (select t_price - min(t_price) over
--                (order by t_timestamp
--                 rows unbounded preceding)
--                as running_diff
--       from trades
--       where t_tid = 94 and t_tradedate = 15) as t1;

-- | Running minimum: For each list element, compute the minimum of its
-- predecessors.
mins :: (QA a, TA a, Ord a) => Q [a] -> Q [a]
mins xs = [ minimum [ y | (view -> (y, j)) <- number xs, j <= i ]
          | (view -> (_, i)) <- number xs
          ]

margins :: (Ord a, Num (Q a), QA a, TA a) => Q [a] -> Q [a]
margins xs = [ x - y | (view -> (x,y)) <- zip xs (mins xs) ]

-- | Our profit is the maximum margin obtainable
profit :: (Ord a, Num (Q a), QA a, TA a) => Q [a] -> Q a
profit xs = maximum (margins xs)

-- | Pest profit obtainable for stock on given date
bestProfit :: Integer -> Day -> Q Double
bestProfit stock date =
    profit [ t_priceQ t
           | t <- sortWith t_timestampQ trades
           , t_tidQ t == toQ stock
           , t_tradeDateQ t == toQ date
           ]

--------------------------------------------------------------------------------
-- Compute the ten last stocks for each quote in a portfolio.

lastn :: QA a => Integer -> Q [a] -> Q [a]
lastn n xs = drop (length xs - toQ n) xs

last10 :: Integer -> Q [(Integer, [Double])]
last10 portfolioId =
    map (\(view -> (tid, g)) -> pair tid (map snd $ lastn 10 g))
    $ groupWithKey fst
    [ pair (t_tidQ t) (t_priceQ t)
    | t <- trades
    , p <- portfolios
    , t_tidQ t == po_tidQ p
    , po_pidQ p == toQ portfolioId
    ]


text:
<?php

namespace FDevs\CoreBundle\DataFixtures\MongoDB;

class LoadBlockData extends \FDevs\CoreBundle\DataFixtures\LoadBlockData
{

}


text:
"""
Implements standard code for problems that
require the Concave-Convex Procedure (CCCP),
or similar iteration.
"""
from __future__ import print_function, division
from sys import stderr

class CCCP(object):
    """
    Encapsulates the CCCP
    """
    TOLERANCE = 1e-6

    def __init__(self, verbose=True, max_iters=50, **kwargs):
        self.verbose = verbose
        self.max_iters = (max_iters + 1)
        self.kwargs = kwargs

    def mention(self, message):
        if self.verbose:
            print(message)

    def solve(self):
        """
        Called to solve the CCCP problem
        """
        for i in range(1, self.max_iters):
            self.mention('\nIteration %d...' % i)
            try:
                self.kwargs, solution = self.iterate(**self.kwargs)
            except Exception as e:
                if self.verbose:
                    print('Warning: Bailing due to error: %s' % e, file=stderr)
                return self.bailout(**self.kwargs)
            if solution is not None:
                return solution

        if self.verbose:
            print('Warning: Max iterations exceeded', file=stderr)
        return self.bailout(**self.kwargs)

    def iterate(self, **kwargs):
        """
        Should perform an iteration of the CCCP,
        using values in kwargs, and returning the
        kwargs for the next iteration.

        If the CCCP should terminate, also return the
        solution; otherwise, return 'None'
        """
        pass

    def bailout(self, **kwargs):
        """
        Return a solution in the case that the
        maximum allowed iterations was exceeded.
        """
        pass

    def check_tolerance(self, last_obj, new_obj=0.0):
        """
        Compares objective values, or takes the first
        value as delta if no second argument is given.
        """
        if last_obj is not None:
            delta_obj = abs(float(new_obj) - float(last_obj))
            self.mention('delta obj ratio: %.2e' % (delta_obj / self.TOLERANCE))
            return delta_obj < self.TOLERANCE
        return False


text:
/**
 * Loads a grid for managing languages.
 *
 * @class MODx.grid.Language
 * @extends MODx.grid.Grid
 * @param {Object} config An object of configuration properties
 * @xtype modx-grid-language
 */
MODx.grid.Language = function(config) {
    config = config || {};
    Ext.applyIf(config,{
        title: _('languages')
        ,id: 'modx-grid-language'
        ,url: MODx.config.connectors_url+'system/language.php'
        ,fields: ['id','name','menu']
        ,width: '97%'
        ,paging: true
        ,autosave: true
        ,primaryKey: 'name'
        ,columns: [{
            header: _('name')
            ,dataIndex: 'name'
            ,width: 200
            ,sortable: true
        }]
        ,tbar: [{
            text: _('language_create')
            ,handler: {
                xtype: 'modx-window-language-create'
                ,listeners: {
                    'success':{fn:function(o) {
                        var r = o.a.result.object;
                        this.refresh();

                        var g = Ext.getCmp('modx-grid-lexicon');
                        if (g) {
                            g.setFilterParams(null,null,r.name);
                        }
                    },scope:this}
                }
            }
            ,scope: this
        }]
    });
    MODx.grid.Language.superclass.constructor.call(this,config);
};
Ext.extend(MODx.grid.Language,MODx.grid.Grid,{
    duplicateLanguage: function(btn,e) {
        var df = Ext.Ajax.timeout;
        Ext.Ajax.timeout = 0;
        this.menu.record.new_name = _('duplicate_of')+this.menu.record.name;
        this.loadWindow(btn,e,{
            xtype: 'modx-window-language-duplicate'
            ,record: this.menu.record
            ,listeners: {
                'success': {fn:function(r) {
                    Ext.Ajax.timeout = df;
                    this.refresh();
                    var g = Ext.getCmp('modx-grid-lexicon');
                    if (g) {
                        g.setFilterParams(null,null,r.name);
                    }
                },scope:this}
            }
        });
    }
});
Ext.reg('modx-grid-language',MODx.grid.Language);

/**
 * Generates the create language window.
 *
 * @class MODx.window.CreateLanguage
 * @extends MODx.Window
 * @param {Object} config An object of options.
 * @xtype modx-window-language-create
 */
MODx.window.CreateLanguage = function(config) {
    config = config || {};
    var r = config.record;
    Ext.applyIf(config,{
        title: _('language_create')
        ,url: MODx.config.connectors_url+'system/language.php'
        ,action: 'create'
        ,fields: [{
            xtype: 'textfield'
            ,fieldLabel: _('name')
            ,name: 'name'
            ,itemId: 'name'
            ,anchor: '95%'
            ,maxLength: 100
            ,allowBlank: false
        }]
    });
    MODx.window.CreateLanguage.superclass.constructor.call(this,config);
};
Ext.extend(MODx.window.CreateLanguage,MODx.Window);
Ext.reg('modx-window-language-create',MODx.window.CreateLanguage);

MODx.window.DuplicateLanguage = function(config) {
    config = config || {};
    var r = config.record;
    Ext.applyIf(config,{
        title: _('language_duplicate')
        ,url: MODx.config.connectors_url+'system/language.php'
        ,action: 'duplicate'
        ,fields: [{
            xtype: 'statictextfield'
            ,fieldLabel: _('duplicate')
            ,name: 'name'
            ,itemId: 'name'
            ,anchor: '100%'
            ,maxLength: 100
            ,allowBlank: false
            ,submitValue: true
        },{
            xtype: 'textfield'
            ,fieldLabel: _('language_new_name')
            ,description: _('language_new_name_desc')
            ,name: 'new_name'
            ,itemId: 'new_name'
            ,anchor: '100%'
            ,allowBlank: false
        },{
            xtype: 'xcheckbox'
            ,boxLabel: _('language_recursive')
            ,description: _('language_recursive_desc')
            ,name: 'recursive'
            ,itemId: 'recursive'
            ,inputValue: 1
            ,checked: true
        }]
    });
    MODx.window.DuplicateLanguage.superclass.constructor.call(this,config);
};
Ext.extend(MODx.window.DuplicateLanguage,MODx.Window);
Ext.reg('modx-window-language-duplicate',MODx.window.DuplicateLanguage);


text:
package com.DroneSimulator;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.*;

/**
 * Represents the visual aspect of the simulation.
 *
 * @author Lars Bokkers, Joost Coenen, Jouke Geerts, Robert Jansen
 *
 */
public class Screen extends JPanel {

	private static final int DRONE_SIZE = 10;
	private static final int TIMER_DELAY = 15;
	// The frame that contains the display.
	private JFrame frame;
	private JProgressBar progressBar = null;

	// The dimensions of the whole desktop.
	private Dimension dim = null;

	// The parameters for the current trial.
	private TrialParameters currentTrial = null;

	// The Simulation which the screen is running.
	// private Simulation simulation = null;

	// The location of the cursor.
	private int cursorX, cursorY;
	public static final int STEPSIZE = 100;

	private States state = Screen.States.TRIAL_EMPTY;

	// The timer for the progressbar
	private Timer timer;

	// States
	public static enum States {
		TRIAL_BUSY, TRIAL_BREAK, TRIAL_EMPTY, TRIAL_END, TRIAL_CLASSIFYING
	}

	//save drone positions for later use
	private ArrayList<Integer> dronePositionsY= new  ArrayList<Integer>();
	private ArrayList<Integer> dronePositionsX= new  ArrayList<Integer>();

	private ArrayList<TrialResults> results = new ArrayList<TrialResults>();
	// private JLabel countdownLabel = new JLabel();
	private int breakTimeLeft;

	/**
	 * Initializes the screen with the given simulation.
	 *
	 * @param sim
	 *            The simulation to run in the screen.
	 */
	public Screen() {

		// Initialize display frame.
		frame = new JFrame();
		frame.setTitle("UAV BCI Software");
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// this.setLayout(new GridBagLayout());
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.setBackground(Color.WHITE);
		frame.add(this);
		frame.setVisible(true);
		dim = Toolkit.getDefaultToolkit().getScreenSize();

		// Initialize progress bar.
		progressBar = new JProgressBar(0, Simulation.TRIAL_LENGTH);
		progressBar.setValue(0);
		// progressBar.setSize(100, 100);
		progressBar.setPreferredSize(new Dimension(50, 150));
		// progressBar.setValue(1);
		// progressBar.setStringPainted(true);
		progressBar.setVisible(true);
		progressBar.setBackground(Color.BLACK);
		this.add(progressBar);

		// Initialize timer for progress bar

		timer = new Timer(TIMER_DELAY, new ActionListener() {
			long starttime = System.currentTimeMillis();

			@Override
			public void actionPerformed(ActionEvent e) {
				long value;
				if (progressBar.getValue() == 0) {
					starttime = System.currentTimeMillis();
					value = 1;
				} else {
					value = (System.currentTimeMillis() - starttime);
				}

				// int value = progressBar.getValue() + TIMER_DELAY;

				//System.out.println(value);
				if (value >= progressBar.getMaximum()) {
					System.out.println("Time elapsed since start of trial: "
							+ (System.currentTimeMillis() - starttime));

					value = progressBar.getMaximum();
					timer.stop();

					// submitResult();
					// reset();

				}

				progressBar.setValue((int) value);
				// System.out.println(value);
				repaint();

			}

		});

		// Initialise Maps for Keybindings.
		InputMap im = this.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
		ActionMap am = this.getActionMap();

		// Keybindings
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Escape");
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "Right");
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
		im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "Space");

		am.put("Escape", new KeyAction("Escape", this));
		am.put("Enter", new KeyAction("Enter", this));
		am.put("Up", new KeyAction("Up", this));
		am.put("Down", new KeyAction("Down", this));
		am.put("Right", new KeyAction("Right", this));
		am.put("Left", new KeyAction("Left", this));
		am.put("Space", new KeyAction("Space", this));

		// Joystick stuff

	}

	public void setCurrentTrial(TrialParameters currentTrial) {
		this.currentTrial = currentTrial;
	}

	public TrialParameters getCurrentTrial() {
		return currentTrial;
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);

		if (state == Screen.States.TRIAL_BUSY || state == Screen.States.TRIAL_CLASSIFYING) {
			int height = (int) currentTrial.getTargetHeight();
			int width = (int) currentTrial.getTargetWidth();

			if (state == Screen.States.TRIAL_BUSY)
				g.setColor(Color.RED);
			else if (state == Screen.States.TRIAL_CLASSIFYING)
				g.setColor(Color.GREEN);

			g.fillRect(dim.width / 2 - width / 2, dim.height / 2 - height / 2,
					width, height);
			g.setColor(Color.BLACK);
			g.fillOval(cursorX, cursorY, DRONE_SIZE, DRONE_SIZE);
		} else if (state == Screen.States.TRIAL_BREAK) {
			drawCountdown(g);
		} else if (state == Screen.States.TRIAL_END) {
			drawEnd(g);
		}

	}

	private void drawEnd(Graphics g) {
		Graphics2D graphics2D = (Graphics2D) g;
		graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
				RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		Font font = new Font(null, Font.PLAIN, 100);
		graphics2D.setFont(font);
		String tekst = "That's all folks!";
		int stringWidth = (int) graphics2D.getFontMetrics(font)
				.getStringBounds(tekst, g).getWidth();
		graphics2D.drawString(tekst, dim.width / 2 - stringWidth / 2,
				dim.height / 2);

	}

	private void drawCountdown(Graphics g) {
		// countdownLabel.setText(Integer.toString(breakTimeLeft));
		Graphics2D graphics2D = (Graphics2D) g;
		graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
				RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		Font font = new Font(null, Font.PLAIN, 100);
		graphics2D.setFont(font);

		int stringWidth = (int) graphics2D.getFontMetrics(font)
				.getStringBounds(Integer.toString(breakTimeLeft), g).getWidth();
		graphics2D.drawString(Integer.toString(breakTimeLeft), dim.width / 2
				- stringWidth / 2, dim.height / 2);

	}

	public void startCountdown(int length) {
		breakTimeLeft = length;
		// showCountdown();
		while (breakTimeLeft > 0) {

			System.out.println("Timeleft: " + breakTimeLeft);
			setBreakTimeLeft(breakTimeLeft);

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			repaint();
			breakTimeLeft--;
		}
		// hideCountdown();
	}

	private void setBreakTimeLeft(int btl) {
		this.breakTimeLeft = btl;

	}

	/**
	 * Submits the simulation results to the Simulation.
	 */
	/*
	 * private void submitResult() { TrialResults result = new TrialResults();
	 * result.setHit(isHit()); //result.setTimeRequired(1337); // TODO: change
	 * result.setSimulationDetails(currentTrial); // TODO put in loop:
	 * simulation.reportSimulationResults(result); }
	 */
	/**
	 * Handles enter key presses
	 */
	public void enterKey() {
		reset();
		this.repaint();
	}

	/**
	 * Handles escape key presses
	 */
	public void escapeKey() {
		this.frame.dispatchEvent(new WindowEvent(frame,
				WindowEvent.WINDOW_CLOSING));
	}

	/**
	 * Handles up key presses
	 */
	public void upKey() {
		cursorY -= STEPSIZE;
		cursorY = (cursorY < 0) ? 0 : cursorY;
		dronePositionsY.add(cursorY);
		this.repaint();
	}

	/**
	 * Handles down key presses
	 */
	public void downKey() {
		cursorY += STEPSIZE;
		cursorY = (int) ((cursorY > (dim.getHeight() - 70)) ? (dim.getHeight() - 70)
				: cursorY);
		dronePositionsY.add(cursorY);
		this.repaint();
	}

	/**
	 * Handles right key presses
	 */
	public void rightKey() {
		cursorX += STEPSIZE;
		cursorX = (int) ((cursorX > (dim.getWidth() - 10)) ? (dim.getWidth() - 10)
				: cursorX);
		this.repaint();
		dronePositionsX.add(cursorX);
	}

	/**
	 * Handles left key presses
	 */
	public void leftKey() {
		cursorX -= STEPSIZE;
		cursorX = (cursorX < 0) ? 0 : cursorX;
		this.repaint();
		dronePositionsX.add(cursorX);
	}

	public void setState(States state) {
		this.state = state;
	}

	public States getState() {
		return state;
	}

	/**
	 * Checks if the cursor hit the target
	 *
	 * @return true if hit, otherwise false.
	 */
	public boolean isHit() {
		return (cursorY + (DRONE_SIZE / 2)) <= (dim.getHeight() / 2 + currentTrial
				.getTargetHeight() / 2)
				&& (cursorY + (DRONE_SIZE / 2)) >= (dim.getHeight() / 2 - currentTrial
						.getTargetHeight() / 2)
				&& (cursorX + (DRONE_SIZE / 2)) <= (dim.getWidth() / 2 + currentTrial
						.getTargetWidth() / 2)
				&& (cursorX + (DRONE_SIZE / 2)) >= (dim.getWidth() / 2 - currentTrial
						.getTargetWidth() / 2);
	}

	// TODO put in loop:
	public void reset() {
		cursorX = (int) currentTrial.getStartX(); // Adjust Coordinates
		cursorY = (int) currentTrial.getStartY(); //
		// timer.stop();
		progressBar.setValue(0);
		timer.start();
	}

	public void startTimer() {
		// timer.st
	}

	public void showProgressBar() {
		progressBar.setVisible(true);

	}

	public void spaceKey() {
		if (state == Screen.States.TRIAL_BREAK) {
			breakTimeLeft = 2;
			System.out.println("Space pressed");
		}
	}

	public void resetDronePos() {
		// TODO Auto-generated method stub
		dronePositionsY = new ArrayList<Integer>();
		dronePositionsX = new ArrayList<Integer>();

	}

	public ArrayList<Integer> getDronePositionsY() {
		return dronePositionsY;
	}

	public ArrayList<Integer> getDronePositionsX() {
		// TODO Auto-generated method stub
		return dronePositionsX;
	}

	public int getCursorX()
	{
		return cursorX;
	}

	public int getCursorY()
	{
		return cursorY;
	}

	public int getSimulationHeight()
	{
		return dim.height;
	}

	// public void showCountdown() {
	// countdownLabel.setVisible(true);
	// }
	//
	// public void hideCountdown() {
	// countdownLabel.setVisible(false);
	// }

}


text:
package org.gradle.tooling.internal.connection;

import com.google.common.collect.Sets;
import org.gradle.api.Transformer;
import org.gradle.internal.composite.DefaultGradleParticipantBuild;
import org.gradle.internal.composite.GradleParticipantBuild;
import org.gradle.tooling.GradleConnectionException;
import org.gradle.tooling.connection.GradleConnection;
import org.gradle.tooling.connection.GradleConnectionBuilder;
import org.gradle.tooling.internal.consumer.DefaultCompositeConnectionParameters;
import org.gradle.tooling.internal.consumer.Distribution;
import org.gradle.tooling.internal.consumer.DistributionFactory;
import org.gradle.util.CollectionUtils;
import org.gradle.util.GradleVersion;

import java.io.File;
import java.net.URI;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class DefaultGradleConnectionBuilder implements GradleConnectionBuilderInternal {
    private final Set<DefaultGradleConnectionParticipantBuilder> participantBuilders = Sets.newLinkedHashSet();
    private final GradleConnectionFactory gradleConnectionFactory;
    private final DistributionFactory distributionFactory;
    private File gradleUserHomeDir;
    private Integer daemonMaxIdleTimeValue;
    private TimeUnit daemonMaxIdleTimeUnits;
    private File daemonBaseDir;

    public DefaultGradleConnectionBuilder(GradleConnectionFactory gradleConnectionFactory, DistributionFactory distributionFactory) {
        this.gradleConnectionFactory = gradleConnectionFactory;
        this.distributionFactory = distributionFactory;
    }

    @Override
    public GradleConnectionBuilder useGradleUserHomeDir(File gradleUserHomeDir) {
        this.gradleUserHomeDir = gradleUserHomeDir;
        return this;
    }

    @Override
    public ParticipantBuilder addParticipant(File projectDirectory) {
        DefaultGradleConnectionParticipantBuilder participantBuilder = new DefaultGradleConnectionParticipantBuilder(projectDirectory);
        participantBuilders.add(participantBuilder);
        return participantBuilder;
    }

    @Override
    public GradleConnection build() throws GradleConnectionException {
        if (participantBuilders.isEmpty()) {
            throw new IllegalStateException("At least one participant must be specified before creating a connection.");
        }
        return createGradleConnection();
    }

    private GradleConnection createGradleConnection() {
        Set<GradleParticipantBuild> participants = CollectionUtils.collect(participantBuilders, new Transformer<GradleParticipantBuild, DefaultGradleConnectionParticipantBuilder>() {
            @Override
            public GradleParticipantBuild transform(DefaultGradleConnectionParticipantBuilder participantBuilder) {
                return participantBuilder.build();
            }
        });
        DefaultCompositeConnectionParameters.Builder compositeConnectionParametersBuilder = DefaultCompositeConnectionParameters.builder();
        compositeConnectionParametersBuilder.setBuilds(participants);
        compositeConnectionParametersBuilder.setGradleUserHomeDir(gradleUserHomeDir);
        compositeConnectionParametersBuilder.setDaemonMaxIdleTimeValue(daemonMaxIdleTimeValue);
        compositeConnectionParametersBuilder.setDaemonMaxIdleTimeUnits(daemonMaxIdleTimeUnits);
        compositeConnectionParametersBuilder.setDaemonBaseDir(daemonBaseDir);

        DefaultCompositeConnectionParameters connectionParameters = compositeConnectionParametersBuilder.build();

        Distribution distribution = distributionFactory.getDistribution(GradleVersion.current().getVersion());
        return gradleConnectionFactory.create(distribution, connectionParameters, false);
    }

    @Override
    public GradleConnectionBuilderInternal daemonMaxIdleTime(int timeoutValue, TimeUnit timeoutUnits) {
        this.daemonMaxIdleTimeValue = timeoutValue;
        this.daemonMaxIdleTimeUnits = timeoutUnits;
        return this;
    }

    @Override
    public GradleConnectionBuilderInternal daemonBaseDir(File daemonBaseDir) {
        this.daemonBaseDir = daemonBaseDir;
        return this;
    }

    private class DefaultGradleConnectionParticipantBuilder implements ParticipantBuilder {
        private final File projectDir;
        private File gradleHome;
        private URI gradleDistribution;
        private String gradleVersion;

        public DefaultGradleConnectionParticipantBuilder(File projectDir) {
            if (projectDir == null) {
                throw new IllegalArgumentException("Project directory cannot be null.");
            }
            this.projectDir = projectDir;
        }

        @Override
        public ParticipantBuilder useBuildDistribution() {
            resetDistribution();
            return this;
        }

        @Override
        public ParticipantBuilder useInstallation(File gradleHome) {
            resetDistribution();
            this.gradleHome = gradleHome;
            return this;
        }

        @Override
        public ParticipantBuilder useGradleVersion(String gradleVersion) {
            resetDistribution();
            this.gradleVersion = gradleVersion;
            return this;
        }

        @Override
        public ParticipantBuilder useDistribution(URI gradleDistribution) {
            resetDistribution();
            this.gradleDistribution = gradleDistribution;
            return this;
        }

        public GradleParticipantBuild build() {
            return new DefaultGradleParticipantBuild(projectDir, gradleHome, gradleDistribution, gradleVersion);
        }

        private void resetDistribution() {
            this.gradleHome = null;
            this.gradleDistribution = null;
            this.gradleVersion = null;
        }
    }

}


text:
<?php

defined('_JEXEC') or die;

JHtml::addIncludePath(JPATH_COMPONENT . '/helpers');
?>

	<div class="category-list<?php echo $this->pageclass_sfx; ?>">

		<?php
		$this->subtemplatename = 'items';
		echo JLayoutHelper::render('joomla.content.category_default', $this);
		?>

	</div>

<?php if ($this->params->get('show_footer'))
{
	echo projectlogHTML::buildThinkeryFooter();
}


text:
import fnmatch
import os
import csv
import subprocess

def write_file(filename, contents):
    """Write the given contents to a text file.

    ARGUMENTS
    filename (string) - name of the file to write to, creating if it doesn't exist
    contents (string) - contents of the file to be written
    """

    # Open the file for writing
    file = open(filename, 'w')

    # Write the file contents
    file.write(contents)

    # Close the file
    file.close()

    return

def qsub_submit(command_filename, hold_jobid = None, fname = None):
    """Submit the given command filename to the queue.

    ARGUMENTS
    command_filename (string) - the name of the command file to submit

    OPTIONAL ARGUMENTS
    hold_jobid (int) - job id to hold on as a prerequisite for execution

    RETURNS
    jobid (integer) - the jobid
    """

    # Form command
    command = 'qsub'
    if fname: command += ' -N %s' % fname
    if hold_jobid: command += ' -hold_jid %d' % hold_jobid
    command += ' %s' % command_filename

    # Submit the job and capture output.
    import subprocess
    print "> " + command
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    out, err = process.communicate()
    print(out)

    # Match job id
    jobid = out.split(' ')[2]

    return int(jobid)

trim_file_name = 'pengt_2nd'

path = os.path.join('/netapp/home/idriver', trim_file_name)

file_out= '${TMPDIR}'

for root, dirnames, filenames in os.walk(path):
    if dirnames == []:
        fastq_files = [files for files in filenames if '.fastq.gz' in files]

        name = os.path.basename(root)

        #subprocess.call('mkdir -p '+path+'/%s' % name, shell=True)
        if len(fastq_files) > 2:
            r1_files = [r1 for r1 in fastq_files if r1.strip('.fastq.gz').split('_')[-2] == 'R1']
            r1_files.sort()
            r2_files = [r2 for r2 in fastq_files if r2.strip('.fastq.gz').split('_')[-2] == 'R2']
            r2_files.sort()
            r1_cat_cmd = 'cat '
            r2_cat_cmd = 'cat '
            for r1,r2 in zip(r1_files,r2_files):
                r1_cat_cmd+= os.path.join(root,r1)+' '
                r2_cat_cmd+= os.path.join(root,r2)+' '
            r1_cat_cmd+= '> '+os.path.join(root,r1_files[0].strip('.fastq.gz')+'_new'+'.fastq.gz')
            r2_cat_cmd+= '> '+os.path.join(root,r2_files[0].strip('.fastq.gz')+'_new'+'.fastq.gz')
            print(r1_cat_cmd)
            if os.path.isfile(os.path.join(root,r1_files[0].strip('.fastq.gz')+'_new'+'.fastq.gz')):
                print(os.path.join(root,r1_files[0].strip('.fastq.gz')+'_new'+'.fastq.gz')+' exists.')
                pass
            else:
                process = subprocess.Popen(r1_cat_cmd, stdout=subprocess.PIPE, shell=True)
                out1, err1 = process.communicate()
                print(out1)
                print(r2_cat_cmd)
                process = subprocess.Popen(r2_cat_cmd, stdout=subprocess.PIPE, shell=True)
                out2, err2 = process.communicate()
                print(out2)
            pair_1 = os.path.join(root,r1_files[0].strip('.fastq.gz')+'_new'+'.fastq.gz')
            pair_2 = os.path.join(root,r2_files[0].strip('.fastq.gz')+'_new'+'.fastq.gz')
        if len(fastq_files) == 2:
            for files in fastq_files:
                num = files.strip('.fastq.gz').split('_')[-2]
                if num == 'R1':
                    pair_1 = os.path.join(root,files)
                if num == 'R2':
                    pair_2 = os.path.join(root,files)
        if len(fastq_files) == 1:
            trim_fasta_path = '/netapp/home/idriver/Trimmomatic-0.36/adapters/TruSeq3-SE.fa'
            output_text = ' '+file_out+'/'+name+'_trimed_fastq.gz '
            input_file = os.path.join(root,fastq_files[0])
            trim_cmd = 'java -jar /netapp/home/idriver/Trimmomatic-0.36/trimmomatic-0.36.jar SE -phred33 '+input_file+output_text+'ILLUMINACLIP:${TMPDIR}/TruSeq3-SE.fa:2:30:10 LEADING:3 TRAILING:3 SLIDINGWINDOW:4:15 MINLEN:75'
        else:
            trim_fasta_path = '/netapp/home/idriver/Trimmomatic-0.36/adapters/NexteraPE-PE.fa'
            file_name_end_list = ['_forward_paired.fq.gz','_forward_unpaired.fq.gz','_reverse_paired.fq.gz','_reverse_unpaired.fq.gz']
            output_text = ' '
            for extension in file_name_end_list:
                output_text = output_text+file_out+'/'+name+extension+' '
            trim_cmd = 'java -jar /netapp/home/idriver/Trimmomatic-0.36/trimmomatic-0.36.jar PE -phred33 '+pair_1+' '+pair_2+output_text+'ILLUMINACLIP:${TMPDIR}/NexteraPE-PE.fa:2:30:10 LEADING:3 TRAILING:3 SLIDINGWINDOW:4:15 MINLEN:70'

        command = """\
#!/bin/sh
#!/bin/sh
#$ -l arch=linux-x64
#$ -S /bin/bash
#$ -o %(path)s
#$ -e /netapp/home/idriver/error_spc
#$ -cwd
#$ -r y
#$ -j y
#$ -l netapp=5G,scratch=8G,mem_total=10G
#$ -pe smp 4
#$ -R yes
#$ -l h_rt=1:00:00
set echo on
date
hostname
pwd
export PATH=$PATH:${HOME}/bin
PATH=$PATH:/netapp/home/idriver/bin/cufflinks-2.2.1.Linux_x86_64
PATH=$PATH:/netapp/home/idriver/bin/bowtie2-2.2.8
PATH=$PATH:/netapp/home/idriver/bin/samtools-1.3
PATH=$PATH:/netapp/home/idriver/bin/tophat-2.1.0.Linux_x86_64
PATH=$PATH:/usr/bin/gunzip
export PATH
export TMPDIR=/scratch
echo $TMPDIR
cd $TMPDIR
cp %(trim_fasta_path)s .
%(trim_cmd)s
# Copy the results back to the project directory:
cd $TMPDIR
cp -r %(name)s_* %(path)s/%(name)s/
""" % vars()
        if name != '': #['BU3_C36_F9','BU3_C76_E12','ips17_C13_C3','ips17_C26_E2','ips17_C27_E3','ips17_C25_E1']:
            print(trim_cmd)
            filename = 'trim_'+name+'.sh'
            write_file(filename, command)
            jobid = qsub_submit(filename, fname=name)
            print "Submitted. jobid = %d" % jobid
            # Write jobid to a file.
            import subprocess
            process = subprocess.Popen('echo %d > jobids' % jobid, stdout=subprocess.PIPE, shell = True)
            out, err = process.communicate()
            print(out)


text:
title: The Closeness of the Internet
published: False
---


text:
package com.bstek.ureport.parser.impl;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;

import com.bstek.ureport.definition.HeaderFooterDefinition;
import com.bstek.ureport.expression.ExpressionUtils;
import com.bstek.ureport.expression.model.Expression;
import com.bstek.ureport.parser.Parser;

/**
 * @author Jacky.gao
 * @since 2017年4月14日
 */
public class HeaderFooterParser implements Parser<HeaderFooterDefinition> {
	@Override
	public HeaderFooterDefinition parse(Element element) {
		HeaderFooterDefinition hf=new HeaderFooterDefinition();
		String margin=element.attributeValue("margin");
		if(StringUtils.isNotBlank(margin)){
			hf.setMargin(Integer.valueOf(margin));
		}
		String bold=element.attributeValue("bold");
		if(StringUtils.isNotBlank(bold)){
			hf.setBold(Boolean.valueOf(bold));
		}
		String italic=element.attributeValue("italic");
		if(StringUtils.isNotBlank(italic)){
			hf.setItalic(Boolean.valueOf(italic));
		}
		String underline=element.attributeValue("underline");
		if(StringUtils.isNotBlank(underline)){
			hf.setUnderline(Boolean.valueOf(underline));
		}
		String fontFamily=element.attributeValue("font-family");
		if(StringUtils.isNotBlank(fontFamily)){
			hf.setFontFamily(fontFamily);
		}
		String forecolor=element.attributeValue("forecolor");
		if(StringUtils.isNotBlank(forecolor)){
			hf.setForecolor(forecolor);
		}
		String fontSize=element.attributeValue("font-size");
		if(StringUtils.isNotBlank(fontSize)){
			hf.setFontSize(Integer.valueOf(fontSize));
		}
		for(Object obj:element.elements()){
			if(obj==null || !(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			String name=ele.getName();
			if(name.equals("left")){
				hf.setLeft(ele.getText());
				if(StringUtils.isNotBlank(hf.getLeft())){
					Expression expr=ExpressionUtils.parseExpression(hf.getLeft());
					hf.setLeftExpression(expr);
				}
			}else if(name.equals("center")){
				hf.setCenter(ele.getText());
				if(StringUtils.isNotBlank(hf.getCenter())){
					Expression expr=ExpressionUtils.parseExpression(hf.getCenter());
					hf.setCenterExpression(expr);
				}
			}else if(name.equals("right")){
				hf.setRight(ele.getText());
				if(StringUtils.isNotBlank(hf.getRight())){
					Expression expr=ExpressionUtils.parseExpression(hf.getRight());
					hf.setRightExpression(expr);
				}
			}
		}
		return hf;
	}
}


text:
describe CustomButtonEvent do
  let(:custom_button) { FactoryBot.create(:custom_button, :applies_to_class => "Vm", :name => "Test Button") }
  let(:ae_entry_point) { "/SYSTEM/PROCESS/Request" }
  let(:cb_event) do
    FactoryBot.create(:custom_button_event,
                       :full_data => {
                         :automate_entry_point => ae_entry_point,
                         :button_id            => custom_button.id,
                         :button_name          => custom_button.name
                       })
  end

  context '#automate_entry_point' do
    it 'returns a string' do
      expect(cb_event.automate_entry_point).to eq(ae_entry_point)
    end

    it 'returns an empty string' do
      cb_event.full_data.delete(:automate_entry_point)
      cb_event.save!

      expect(cb_event.automate_entry_point).to eq("")
    end
  end

  context '#button_name' do
    it "returns button's current name" do
      expect(cb_event.button_name).to eq("Test Button")

      custom_button.update_attributes(:name => "New Button Name")
      expect(cb_event.button_name).to eq("New Button Name")
    end

    it 'returns button name from event data' do
      cb_event.full_data[:button_id] = custom_button.id - 1
      cb_event.save!
      custom_button.update_attributes(:name => "New Button Name")

      expect(cb_event.button_name).to eq("Test Button")
    end
  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: Leonardo Shinagawa
 * Date: 13/02/14
 * Time: 11:04
 */

namespace shina\controlmybudget\controller;

use shina\controlmybudget\BudgetControlService;
use shina\controlmybudget\MonthlyGoalService;

class DailyBudgetController extends AbstractOAuthController
{

    public function myDailyBudgetAction($monthly_goal_id, $spent_simulation = null)
    {
        /** @var BudgetControlService $budget_control_service */
        $budget_control_service = $this->app->container->get('budget_control_service');
        /** @var MonthlyGoalService $monthly_goal_service */
        $monthly_goal_service = $this->app->container->get('monthly_goal_service');

        $monthly_goal = $monthly_goal_service->getMonthlyGoalById($monthly_goal_id);
        $daily_budget = $budget_control_service->getDailyMonthlyBudget($monthly_goal, $this->user, $spent_simulation);

        $this->app->response->setBody($daily_budget);
    }

}


text:
package io.github.xiaolei.transaction.event;

/**
 * TODO: add comment
 */
public class ActionMenuItemClickEvent {
    public static final int ACTION_ITEM_NEW_PRODUCT = 1;

    private int clickMenuItemId;

    public int getClickMenuItemId(){
        return clickMenuItemId;
    }

    public ActionMenuItemClickEvent(int clickMenuItemId) {
        this.clickMenuItemId = clickMenuItemId;
    }
}


text:
XXXXXXXXX XXX XXXXXXXXXX XXXXXXXX X XXXXXXXXX XXXXXXXX XXX XXXXXX XXXXXXXXX
XXX XXXXXXXXXX XXX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX

XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XX XXXXXXXX XXX
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XX XXXXXXXX XX
XXXXX      XXXXXX XX XXXXXXXX XX
XXXXX      XXXXXX XX XXXXXXXX XX
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XX XXXXXXXX XX
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XXX XXXXXXXX X
XXXXX      XXXXXX XX XXXXXXXX XX
XXXXXXXX   XXXXXX XXX XXXXXXXX X


text:
export const environment = {
    production: false,
    nonauth: true,
    appUrl: "http://localhost:4200",
    stsURL: "https://localhost:44300",
    apiUrl: "https://api-bdps.gear.host/api/",
    v1AppUrl: "https://localhost:44309"
};


text:
"""Admin helper utilities."""
from league.admin.models import SiteSettings, User
from league.slack_messenger import DEFAULT_CONFIG, SLACK_ENABLED

def create_root_user(app):
    """Create root user."""
    if User.get_by_username('root') is None:
        root_user = User(username='root', email='root@localhost',
                         password=app.config['LEAGUE_ROOT_PASS'],
                         active=True,
                         is_admin=True)
        root_user.save()

def load_messenger_config(app):
    """Load Slack messenger configuration."""
    if SiteSettings.get_by_key(SLACK_ENABLED) is None:
        for k, v in DEFAULT_CONFIG.items():
            config_item = SiteSettings(key='slack_{}'.format(k), value=v)
            config_item.save()
    else:
        new_config = {k: SiteSettings.get_by_key('slack_{}'.format(k)).value
                      for k in DEFAULT_CONFIG.keys()}
        app.extensions['messenger'].update_configuration(config=new_config)

def update_messenger_config(app, **kwargs):
    """Update Slack messenger configuration."""
    for key, value in kwargs.items():
        if type(value) == bool:
            value = 'True' if value else 'False'
        config_item = SiteSettings.get_by_key(key='slack_{}'.format(key))
        config_item.value = value
        config_item.update()
    app.extensions['messenger'].update_configuration(config=kwargs)

def load_site_config(app):
    """Load site settings from the database."""
    config = app.config['SITE_SETTINGS']
    new_config = dict()
    for key in config:
        config_item = SiteSettings.get_by_key(
            key='site_settings_{}'.format(key))
        if config_item is not None:
            new_config[key] = config_item.value
    config.update(new_config)
    app.config.update(SITE_SETTINGS=config)

def update_site_settings(app, **kwargs):
    """Update site settings."""
    config = app.config['SITE_SETTINGS']
    for key, value in kwargs.items():
        if type(value) == bool:
            value = 'True' if value else 'False'
        config_item = SiteSettings.get_by_key(
            key='site_settings_{key}'.format(key=key))
        if config_item is not None:
            config_item.value = value
            config_item.update()
        else:
            config_item = SiteSettings(
                key='site_settings_{}'.format(key), value=value)
            config_item.save()
    config.update(**kwargs)
    app.config.update(SITE_SETTINGS=config)