text:
import sqlalchemy as sa
from pytest import mark
from sqlalchemy import inspect

from sqlalchemy_utils import Password, PasswordType, types  # noqa
from tests import TestCase

@mark.skipif('types.password.passlib is None')
class TestPasswordType(TestCase):
    def create_models(self):
        class User(self.Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            password = sa.Column(PasswordType(
                schemes=[
                    'pbkdf2_sha512',
                    'pbkdf2_sha256',
                    'md5_crypt',
                    'hex_md5'
                ],

                deprecated=['md5_crypt', 'hex_md5']
            ))

            def __repr__(self):
                return 'User(%r)' % self.id

        self.User = User

    def test_encrypt(self):
        """Should encrypt the password on setting the attribute."""
        obj = self.User()
        obj.password = b'b'

        assert obj.password.hash != 'b'
        assert obj.password.hash.startswith(b'$pbkdf2-sha512$')

    def test_check(self):
        """
        Should be able to compare the plaintext against the
        encrypted form.
        """
        obj = self.User()
        obj.password = 'b'

        assert obj.password == 'b'
        assert obj.password != 'a'

        self.session.add(obj)
        self.session.commit()

        obj = self.session.query(self.User).get(obj.id)

        assert obj.password == b'b'
        assert obj.password != 'a'

    def test_check_and_update(self):
        """
        Should be able to compare the plaintext against a deprecated
        encrypted form and have it auto-update to the preferred version.
        """

        from passlib.hash import md5_crypt

        obj = self.User()
        obj.password = Password(md5_crypt.encrypt('b'))

        assert obj.password.hash.decode('utf8').startswith('$1$')
        assert obj.password == 'b'
        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')

    def test_auto_column_length(self):
        """Should derive the correct column length from the specified schemes.
        """

        from passlib.hash import pbkdf2_sha512

        kind = inspect(self.User).c.password.type

        # name + rounds + salt + hash + ($ * 4) of largest hash
        expected_length = len(pbkdf2_sha512.name)
        expected_length += len(str(pbkdf2_sha512.max_rounds))
        expected_length += pbkdf2_sha512.max_salt_size
        expected_length += pbkdf2_sha512.encoded_checksum_size
        expected_length += 4

        assert kind.length == expected_length

    def test_without_schemes(self):
        assert PasswordType(schemes=[]).length == 1024

    def test_compare(self):
        from passlib.hash import md5_crypt

        obj = self.User()
        obj.password = Password(md5_crypt.encrypt('b'))

        other = self.User()
        other.password = Password(md5_crypt.encrypt('b'))

        # Not sure what to assert here; the test raised an error before.
        assert obj.password != other.password

    def test_set_none(self):

        obj = self.User()
        obj.password = None

        assert obj.password is None

        self.session.add(obj)
        self.session.commit()

        obj = self.session.query(self.User).get(obj.id)

        assert obj.password is None

    def test_update_none(self):
        """
        Should be able to change a password from ``None`` to a valid
        password.
        """

        obj = self.User()
        obj.password = None

        self.session.add(obj)
        self.session.commit()

        obj = self.session.query(self.User).get(obj.id)
        obj.password = 'b'

        self.session.commit()

    def test_compare_none(self):
        """
        Should be able to compare a password of ``None``.
        """

        obj = self.User()
        obj.password = None

        assert obj.password is None
        assert obj.password == None  # noqa

        obj.password = 'b'

        assert obj.password is not None
        assert obj.password != None  # noqa

    def test_check_and_update_persist(self):
        """
        When a password is compared, the hash should update if needed to
        change the algorithm; and, commit to the database.
        """

        from passlib.hash import md5_crypt

        obj = self.User()
        obj.password = Password(md5_crypt.encrypt('b'))

        self.session.add(obj)
        self.session.commit()

        assert obj.password.hash.decode('utf8').startswith('$1$')
        assert obj.password == 'b'

        self.session.commit()

        obj = self.session.query(self.User).get(obj.id)

        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')
        assert obj.password == 'b'


text:
<!DOCTYPE html>

PASS if no crash or assertion failure.

redpajama_set_name: RedPajamaGithub


text:
sc_spintax
==========

Simple implementation of "spintax," a text generation mechanism often abused for text farms and spam

Current Library Status: *broken*
--------------------------------------------

Not ready for use

Text farms and spam?  Srsly?
----------------------------

So like, it's also got legit uses, right?  And I think it's pretty fun.  I've always loved text generation and other horseshit approaches to fighting the Turing Test using only your middle fingers.  They're great.  [The Postmodernism Generator](http://www.elsewhere.org/pomo/) is probably my favorite of these (reload it a few times,) though I also miss SMAUG (can't find an active link, sry,) [chatbots](http://en.wikipedia.org/wiki/ELIZA), and so on.

Then I saw the [spam script accidentally posted at AlexKing.org](http://alexking.org/blog/2013/12/22/spam-comment-generator-script), and I knew that I had to act. :+1:

Yeah but what the hell
----------------------

Dude this stuff is all over the 'net already; just google it.  I'm not enabling any blackhats.  I am, however, enabling new usage among people who didn't know about this stuff.

Don't you usually write useful things?
--------------------------------------

What?  Lol, no.

… but this one could be.

So for example, I kind of want to use this to do video game dialogue.

#todo example whargarbl

Other implementations and explanations
--------------------------------------

* [NPM Spintax](https://npmjs.org/package/spintax)
* [Spin Rewriter](http://www.spin-rewriter.com/)
* [YouTube Tutorial](http://www.youtube.com/watch?v=4O59LVcM4H8)

Polemic :neckbeard:
-------------------

`sc_spintax` is MIT licensed, because viral licenses and newspeak language modification are evil.  Free is ***only*** free when it's free for everyone.


text:
module ApplicationHelper
  def is_boolean? field_type
    field_type == 'boolean'
  end

  def is_admin?
    return false
    current_user.email == 'robb@teamvoice.com'
  end

  def is_camera? field_type
    field_type.downcase == 'camera'
  end

  def is_file? field_type
    field_type.downcase == 'file'
  end

  def is_numeric? field_type
    field_type.downcase == 'numeric'
  end

  def is_date? field_type
    field_type.downcase == 'datetime'
  end

  def is_class? klass
    return unless klass.present?
    class_uuids.include? klass
  end

  class CodeRayify < Redcarpet::Render::HTML
    def block_code(code, language)
      language = 'ruby' if language.blank?
      CodeRay.scan(code, language).div
    end
  end

  def markdown(text)
    return "" unless text.present?
    @coderayified ||= CodeRayify.new(:filter_html => true,
                                  :hard_wrap => true)
    options = {
      :fenced_code_blocks => true,
      :no_intra_emphasis => true,
      :autolink => true,
      :lax_html_blocks => true,
    }
    @markdown_to_html ||= Redcarpet::Markdown.new(@coderayified, options)
    @markdown_to_html.render(text).html_safe
  end

  def display_date date
    return nil unless date.present?
    I18n.l date
  end

  def current_controller?(*names)
    names.include?(params[:controller])
  end

end


text:
package org.apache.shardingsphere.encrypt.distsql.handler.update;

import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration;
import org.apache.shardingsphere.encrypt.api.config.rule.EncryptColumnRuleConfiguration;
import org.apache.shardingsphere.encrypt.api.config.rule.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.encrypt.distsql.parser.statement.DropEncryptRuleStatement;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration;
import org.apache.shardingsphere.infra.distsql.exception.rule.RequiredRuleMissedException;
import org.apache.shardingsphere.infra.distsql.exception.rule.RuleDefinitionViolationException;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;

@RunWith(MockitoJUnitRunner.class)
public final class DropEncryptRuleStatementUpdaterTest {

    @Mock
    private ShardingSphereMetaData shardingSphereMetaData;

    private final DropEncryptRuleStatementUpdater updater = new DropEncryptRuleStatementUpdater();

    @Test(expected = RequiredRuleMissedException.class)
    public void assertCheckSQLStatementWithoutCurrentRule() throws RuleDefinitionViolationException {
        updater.checkSQLStatement(shardingSphereMetaData, createSQLStatement(), null);
    }

    @Test(expected = RequiredRuleMissedException.class)
    public void assertCheckSQLStatementWithoutToBeDroppedRule() throws RuleDefinitionViolationException {
        updater.checkSQLStatement(shardingSphereMetaData, createSQLStatement(), new EncryptRuleConfiguration(Collections.emptyList(), Collections.emptyMap()));
    }

    @Test
    public void assertUpdateCurrentRuleConfiguration() {
        EncryptRuleConfiguration encryptRuleConfiguration = createCurrentRuleConfiguration();
        assertTrue(updater.updateCurrentRuleConfiguration(createSQLStatement(), encryptRuleConfiguration));
        assertTrue(encryptRuleConfiguration.getEncryptors().isEmpty());
    }

    @Test
    public void assertUpdateCurrentRuleConfigurationWithInUsedEncryptor() {
        EncryptRuleConfiguration encryptRuleConfiguration = createCurrentRuleConfigurationWithMultipleTableRules();
        assertFalse(updater.updateCurrentRuleConfiguration(createSQLStatement(), encryptRuleConfiguration));
        assertThat(encryptRuleConfiguration.getEncryptors().size(), is(1));
    }

    private DropEncryptRuleStatement createSQLStatement() {
        return new DropEncryptRuleStatement(Collections.singleton("t_encrypt"));
    }

    private EncryptRuleConfiguration createCurrentRuleConfiguration() {
        EncryptColumnRuleConfiguration columnRuleConfig = new EncryptColumnRuleConfiguration("user_id", "user_cipher", "", "user_plain", "t_encrypt_user_id_MD5");
        EncryptTableRuleConfiguration tableRuleConfig = new EncryptTableRuleConfiguration("t_encrypt", Collections.singleton(columnRuleConfig), null);
        Map<String, ShardingSphereAlgorithmConfiguration> encryptors = new HashMap<>(1, 1);
        encryptors.put("t_encrypt_user_id_MD5", new ShardingSphereAlgorithmConfiguration("TEST", new Properties()));
        return new EncryptRuleConfiguration(new LinkedList<>(Collections.singleton(tableRuleConfig)), encryptors, true);
    }

    private EncryptRuleConfiguration createCurrentRuleConfigurationWithMultipleTableRules() {
        EncryptColumnRuleConfiguration columnRuleConfig = new EncryptColumnRuleConfiguration("user_id", "user_cipher", "", "user_plain", "t_encrypt_user_id_MD5");
        EncryptTableRuleConfiguration tableRuleConfig = new EncryptTableRuleConfiguration("t_encrypt", Collections.singleton(columnRuleConfig), null);
        Map<String, ShardingSphereAlgorithmConfiguration> encryptors = new HashMap<>(1, 1);
        encryptors.put("t_encrypt_user_id_MD5", new ShardingSphereAlgorithmConfiguration("TEST", new Properties()));
        return new EncryptRuleConfiguration(new LinkedList<>(Arrays.asList(tableRuleConfig,
                new EncryptTableRuleConfiguration("t_encrypt_another", Collections.singleton(columnRuleConfig), null))), encryptors, true);
    }
}


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

  ./infer \
  --alpha 0.1    \
  --beta 0.01                                           \
  --inference_data_file ./testdata/test_data.txt \
  --inference_result_file /tmp/inference_result.txt \
  --model_file /tmp/lda_model.txt                       \
  --burn_in_iterations 10                              \
  --total_iterations 15
*/
#include <fstream>
#include <set>
#include <sstream>
#include <string>

#include "common.h"
#include "document.h"
#include "model.h"
#include "sampler.h"
#include "cmd_flags.h"

int main(int argc, char** argv) {
  using learning_lda::LDACorpus;
  using learning_lda::LDAModel;
  using learning_lda::LDAAccumulativeModel;
  using learning_lda::LDASampler;
  using learning_lda::LDADocument;
  using learning_lda::LDACmdLineFlags;
  using learning_lda::DocumentWordTopicsPB;
  using learning_lda::RandInt;
  using std::ifstream;
  using std::ofstream;
  using std::istringstream;

  LDACmdLineFlags flags;
  flags.ParseCmdFlags(argc, argv);
  if (!flags.CheckInferringValidity()) {
    return -1;
  }
  srand(time(NULL));
  map<string, int> word_index_map;
  ifstream model_fin(flags.model_file_.c_str());
  LDAModel model(model_fin, &word_index_map);
  LDASampler sampler(flags.alpha_, flags.beta_, &model, NULL);
  ifstream fin(flags.inference_data_file_.c_str());
  ofstream out(flags.inference_result_file_.c_str());
  string line;
  while (getline(fin, line)) {  // Each line is a training document.
    if (line.size() > 0 &&      // Skip empty lines.
        line[0] != '\r' &&      // Skip empty lines.
        line[0] != '\n' &&      // Skip empty lines.
        line[0] != '#') {       // Skip comment lines.
      istringstream ss(line);
      DocumentWordTopicsPB document_topics;
      string word;
      int count;
      while (ss >> word >> count) {  // Load and init a document.
        vector<int32> topics;
        for (int i = 0; i < count; ++i) {
          topics.push_back(RandInt(model.num_topics()));
        }
        map<string, int>::const_iterator iter = word_index_map.find(word);
        if (iter != word_index_map.end()) {
          document_topics.add_wordtopics(word, iter->second, topics);
        }
      }
      LDADocument document(document_topics, model.num_topics());
      TopicProbDistribution prob_dist(model.num_topics(), 0);
      for (int iter = 0; iter < flags.total_iterations_; ++iter) {
        sampler.SampleNewTopicsForDocument(&document, false);
        if (iter >= flags.burn_in_iterations_) {
          const vector<int64>& document_distribution =
              document.topic_distribution();
          for (int i = 0; i < document_distribution.size(); ++i) {
            prob_dist[i] += document_distribution[i];
          }
        }
      }
      for (int topic = 0; topic < prob_dist.size(); ++topic) {
        out << prob_dist[topic] /
              (flags.total_iterations_ - flags.burn_in_iterations_)
            << ((topic < prob_dist.size() - 1) ? " " : "\n");
      }
    }
  }
}


text:
<?php

namespace Cake\Database\Type;

use Cake\Database\Driver;
use Cake\Database\Type;

/**
 * Datetime type converter.
 *
 * Use to convert datetime instances to strings & back.
 */
class DateTimeType extends Type
{

    /**
     * The class to use for representing date objects
     *
     * @var string
     */
    public static $dateTimeClass = 'Cake\I18n\Time';

    /**
     * String format to use for DateTime parsing
     *
     * @var string
     */
    protected $_format = 'Y-m-d H:i:s';

    /**
     * Whether dates should be parsed using a locale aware parser
     * when marshalling string inputs.
     *
     * @var bool
     */
    protected $_useLocaleParser = false;

    /**
     * The date format to use for parsing incoming dates for marshalling.
     *
     * @var string|array|int
     */
    protected $_localeFormat;

    /**
     * An instance of the configured dateTimeClass, used to quickly generate
     * new instances without calling the constructor.
     *
     * @var \DateTime
     */
    protected $_datetimeInstance;

    /**
     * {@inheritDoc}
     */
    public function __construct($name = null)
    {
        parent::__construct($name);

        if (!class_exists(static::$dateTimeClass)) {
            static::$dateTimeClass = 'DateTime';
        }

        $this->_datetimeInstance = new static::$dateTimeClass;
    }

    /**
     * Convert DateTime instance into strings.
     *
     * @param string|int|\DateTime $value The value to convert.
     * @param Driver $driver The driver instance to convert with.
     * @return string
     */
    public function toDatabase($value, Driver $driver)
    {
        if ($value === null || is_string($value)) {
            return $value;
        }
        if (is_int($value)) {
            $value = new static::$dateTimeClass('@' . $value);
        }
        return $value->format($this->_format);
    }

    /**
     * Convert strings into DateTime instances.
     *
     * @param string $value The value to convert.
     * @param Driver $driver The driver instance to convert with.
     * @return \Cake\I18n\Time|DateTime
     */
    public function toPHP($value, Driver $driver)
    {
        if ($value === null || strpos($value, '0000-00-00') === 0) {
            return null;
        }

        if (strpos($value, '.') !== false) {
            list($value) = explode('.', $value);
        }

        $instance = clone $this->_datetimeInstance;
        return $instance->modify($value);
    }

    /**
     * Convert request data into a datetime object.
     *
     * @param mixed $value Request data
     * @return \Cake\I18n\Time|DateTime
     */
    public function marshal($value)
    {
        if ($value instanceof \DateTime) {
            return $value;
        }

        $class = static::$dateTimeClass;
        try {
            $compare = $date = false;
            if ($value === '' || $value === null || $value === false || $value === true) {
                return null;
            } elseif (is_numeric($value)) {
                $date = new $class('@' . $value);
            } elseif (is_string($value) && $this->_useLocaleParser) {
                return $this->_parseValue($value);
            } elseif (is_string($value)) {
                $date = new $class($value);
                $compare = true;
            }
            if ($compare && $date && $date->format($this->_format) !== $value) {
                return $value;
            }
            if ($date) {
                return $date;
            }
        } catch (\Exception $e) {
            return $value;
        }

        if (is_array($value) && implode('', $value) === '') {
            return null;
        }
        $value += ['hour' => 0, 'minute' => 0, 'second' => 0];

        $format = '';
        if (isset($value['year'], $value['month'], $value['day']) &&
            (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
        ) {
            $format .= sprintf('%d-%02d-%02d', $value['year'], $value['month'], $value['day']);
        }

        if (isset($value['meridian'])) {
            $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
        }
        $format .= sprintf(
            '%s%02d:%02d:%02d',
            empty($format) ? '' : ' ',
            $value['hour'],
            $value['minute'],
            $value['second']
        );
        $tz = isset($value['timezone']) ? $value['timezone'] : null;

        return new $class($format, $tz);
    }

    /**
     * Sets whether or not to parse dates passed to the marshal() function
     * by using a locale aware parser.
     *
     * @param bool $enable Whether or not to enable
     * @return $this
     */
    public function useLocaleParser($enable = true)
    {
        if ($enable === false) {
            $this->_useLocaleParser = $enable;
            return $this;
        }
        if (static::$dateTimeClass === 'Cake\I18n\Time' ||
            is_subclass_of(static::$dateTimeClass, 'Cake\I18n\Time')
        ) {
            $this->_useLocaleParser = $enable;
            return $this;
        }
        throw new \RuntimeException(
            sprintf('Cannot use locale parsing with the %s class', static::$dateTimeClass)
        );
    }

    /**
     * Sets the format string to use for parsing dates in this class. The formats
     * that are accepted are documented in the `Cake\I18n\Time::parseDateTime()`
     * function.
     *
     * @param string|array $format The format in which the string are passed.
     * @see \Cake\I18n\Time::parseDateTime()
     * @return $this
     */
    public function setLocaleFormat($format)
    {
        $this->_localeFormat = $format;
        return $this;
    }

    /**
     * Converts a string into a DateTime object after parseing it using the locale
     * aware parser with the specified format.
     *
     * @param string $value The value to parse and convert to an object.
     * @return \Cake\I18n\Time|null
     */
    protected function _parseValue($value)
    {
        $class = static::$dateTimeClass;
        return $class::parseDateTime($value, $this->_localeFormat);
    }
}


text:
import * as html from '../ml_parser/ast';
import { InterpolationConfig } from '../ml_parser/interpolation_config';
import * as i18n from './i18n_ast';
/**
 * Returns a function converting html nodes to an i18n Message given an interpolationConfig
 */
export declare function createI18nMessageFactory(interpolationConfig: InterpolationConfig): (nodes: html.Node[], meaning: string, description: string, id: string) => i18n.Message;


text:
package kafka.controller

import collection._
import collection.JavaConversions._
import java.util.concurrent.atomic.AtomicBoolean
import kafka.common.{TopicAndPartition, StateChangeFailedException}
import kafka.utils.{ZkUtils, Logging}
import org.I0Itec.zkclient.IZkChildListener
import org.apache.log4j.Logger

/**
 * This class represents the state machine for replicas. It defines the states that a replica can be in, and
 * transitions to move the replica to another legal state. The different states that a replica can be in are -
 * 1. NewReplica        : The controller can create new replicas during partition reassignment. In this state, a
 *                        replica can only get become follower state change request.  Valid previous
 *                        state is NonExistentReplica
 * 2. OnlineReplica     : Once a replica is started and part of the assigned replicas for its partition, it is in this
 *                        state. In this state, it can get either become leader or become follower state change requests.
 *                        Valid previous state are NewReplica, OnlineReplica or OfflineReplica
 * 3. OfflineReplica    : If a replica dies, it moves to this state. This happens when the broker hosting the replica
 *                        is down. Valid previous state are NewReplica, OnlineReplica
 * 4. NonExistentReplica: If a replica is deleted, it is moved to this state. Valid previous state is OfflineReplica
 */
class ReplicaStateMachine(controller: KafkaController) extends Logging {
  private val controllerContext = controller.controllerContext
  private val controllerId = controller.config.brokerId
  private val zkClient = controllerContext.zkClient
  var replicaState: mutable.Map[(String, Int, Int), ReplicaState] = mutable.Map.empty
  val brokerRequestBatch = new ControllerBrokerRequestBatch(controller.controllerContext, controller.sendRequest,
    controllerId, controller.clientId)
  private val hasStarted = new AtomicBoolean(false)
  this.logIdent = "[Replica state machine on controller " + controller.config.brokerId + "]: "
  private val stateChangeLogger = Logger.getLogger(KafkaController.stateChangeLogger)

  /**
   * Invoked on successful controller election. First registers a broker change listener since that triggers all
   * state transitions for replicas. Initializes the state of replicas for all partitions by reading from zookeeper.
   * Then triggers the OnlineReplica state change for all replicas.
   */
  def startup() {
    // initialize replica state
    initializeReplicaState()
    hasStarted.set(true)
    // move all Online replicas to Online
    handleStateChanges(getAllReplicasOnBroker(controllerContext.allTopics.toSeq,
      controllerContext.liveBrokerIds.toSeq), OnlineReplica)
    info("Started replica state machine with initial state -> " + replicaState.toString())
  }

  // register broker change listener
  def registerListeners() {
    registerBrokerChangeListener()
  }

  /**
   * Invoked on controller shutdown.
   */
  def shutdown() {
    hasStarted.set(false)
    replicaState.clear()
  }

  /**
   * This API is invoked by the broker change controller callbacks and the startup API of the state machine
   * @param replicas     The list of replicas (brokers) that need to be transitioned to the target state
   * @param targetState  The state that the replicas should be moved to
   * The controller's allLeaders cache should have been updated before this
   */
  def handleStateChanges(replicas: Set[PartitionAndReplica], targetState: ReplicaState) {
    info("Invoking state change to %s for replicas %s".format(targetState, replicas.mkString(",")))
    try {
      brokerRequestBatch.newBatch()
      replicas.foreach(r => handleStateChange(r.topic, r.partition, r.replica, targetState))
      brokerRequestBatch.sendRequestsToBrokers(controller.epoch, controllerContext.correlationId.getAndIncrement)
    }catch {
      case e: Throwable => error("Error while moving some replicas to %s state".format(targetState), e)
    }
  }

  /**
   * This API exercises the replica's state machine. It ensures that every state transition happens from a legal
   * previous state to the target state.
   * @param topic       The topic of the replica for which the state transition is invoked
   * @param partition   The partition of the replica for which the state transition is invoked
   * @param replicaId   The replica for which the state transition is invoked
   * @param targetState The end state that the replica should be moved to
   */
  def handleStateChange(topic: String, partition: Int, replicaId: Int, targetState: ReplicaState) {
    val topicAndPartition = TopicAndPartition(topic, partition)
    if (!hasStarted.get)
      throw new StateChangeFailedException(("Controller %d epoch %d initiated state change of replica %d for partition %s " +
                                            "to %s failed because replica state machine has not started")
                                              .format(controllerId, controller.epoch, replicaId, topicAndPartition, targetState))
    try {
      replicaState.getOrElseUpdate((topic, partition, replicaId), NonExistentReplica)
      val replicaAssignment = controllerContext.partitionReplicaAssignment(topicAndPartition)
      targetState match {
        case NewReplica =>
          assertValidPreviousStates(topic, partition, replicaId, List(NonExistentReplica), targetState)
          // start replica as a follower to the current leader for its partition
          val leaderIsrAndControllerEpochOpt = ZkUtils.getLeaderIsrAndEpochForPartition(zkClient, topic, partition)
          leaderIsrAndControllerEpochOpt match {
            case Some(leaderIsrAndControllerEpoch) =>
              if(leaderIsrAndControllerEpoch.leaderAndIsr.leader == replicaId)
                throw new StateChangeFailedException("Replica %d for partition %s cannot be moved to NewReplica"
                  .format(replicaId, topicAndPartition) + "state as it is being requested to become leader")
              brokerRequestBatch.addLeaderAndIsrRequestForBrokers(List(replicaId),
                                                                  topic, partition, leaderIsrAndControllerEpoch,
                                                                  replicaAssignment)
            case None => // new leader request will be sent to this replica when one gets elected
          }
          replicaState.put((topic, partition, replicaId), NewReplica)
          stateChangeLogger.trace("Controller %d epoch %d changed state of replica %d for partition %s to NewReplica"
                                    .format(controllerId, controller.epoch, replicaId, topicAndPartition))
        case NonExistentReplica =>
          assertValidPreviousStates(topic, partition, replicaId, List(OfflineReplica), targetState)
          // send stop replica command
          brokerRequestBatch.addStopReplicaRequestForBrokers(List(replicaId), topic, partition, deletePartition = true)
          // remove this replica from the assigned replicas list for its partition
          val currentAssignedReplicas = controllerContext.partitionReplicaAssignment(topicAndPartition)
          controllerContext.partitionReplicaAssignment.put(topicAndPartition, currentAssignedReplicas.filterNot(_ == replicaId))
          replicaState.remove((topic, partition, replicaId))
          stateChangeLogger.trace("Controller %d epoch %d changed state of replica %d for partition %s to NonExistentReplica"
                                    .format(controllerId, controller.epoch, replicaId, topicAndPartition))
        case OnlineReplica =>
          assertValidPreviousStates(topic, partition, replicaId, List(NewReplica, OnlineReplica, OfflineReplica), targetState)
          replicaState((topic, partition, replicaId)) match {
            case NewReplica =>
              // add this replica to the assigned replicas list for its partition
              val currentAssignedReplicas = controllerContext.partitionReplicaAssignment(topicAndPartition)
              if(!currentAssignedReplicas.contains(replicaId))
                controllerContext.partitionReplicaAssignment.put(topicAndPartition, currentAssignedReplicas :+ replicaId)
              stateChangeLogger.trace("Controller %d epoch %d changed state of replica %d for partition %s to OnlineReplica"
                                        .format(controllerId, controller.epoch, replicaId, topicAndPartition))
            case _ =>
              // check if the leader for this partition ever existed
              controllerContext.partitionLeadershipInfo.get(topicAndPartition) match {
                case Some(leaderIsrAndControllerEpoch) =>
                  brokerRequestBatch.addLeaderAndIsrRequestForBrokers(List(replicaId), topic, partition, leaderIsrAndControllerEpoch,
                    replicaAssignment)
                  replicaState.put((topic, partition, replicaId), OnlineReplica)
                  stateChangeLogger.trace("Controller %d epoch %d changed state of replica %d for partition %s to OnlineReplica"
                    .format(controllerId, controller.epoch, replicaId, topicAndPartition))
                case None => // that means the partition was never in OnlinePartition state, this means the broker never
                  // started a log for that partition and does not have a high watermark value for this partition
              }

          }
          replicaState.put((topic, partition, replicaId), OnlineReplica)
        case OfflineReplica =>
          assertValidPreviousStates(topic, partition, replicaId, List(NewReplica, OnlineReplica), targetState)
          // As an optimization, the controller removes dead replicas from the ISR
          val leaderAndIsrIsEmpty: Boolean =
            controllerContext.partitionLeadershipInfo.get(topicAndPartition) match {
              case Some(currLeaderIsrAndControllerEpoch) =>
                if (currLeaderIsrAndControllerEpoch.leaderAndIsr.isr.contains(replicaId))
                  controller.removeReplicaFromIsr(topic, partition, replicaId) match {
                    case Some(updatedLeaderIsrAndControllerEpoch) =>
                      // send the shrunk ISR state change request only to the leader
                      brokerRequestBatch.addLeaderAndIsrRequestForBrokers(List(updatedLeaderIsrAndControllerEpoch.leaderAndIsr.leader),
                        topic, partition, updatedLeaderIsrAndControllerEpoch, replicaAssignment)
                      replicaState.put((topic, partition, replicaId), OfflineReplica)
                      stateChangeLogger.trace("Controller %d epoch %d changed state of replica %d for partition %s to OfflineReplica"
                                                .format(controllerId, controller.epoch, replicaId, topicAndPartition))
                      false
                    case None =>
                      true
                  }
                else {
                  replicaState.put((topic, partition, replicaId), OfflineReplica)
                  stateChangeLogger.trace("Controller %d epoch %d changed state of replica %d for partition %s to OfflineReplica"
                    .format(controllerId, controller.epoch, replicaId, topicAndPartition))
                  false
                }
              case None =>
                true
            }
          if (leaderAndIsrIsEmpty)
            throw new StateChangeFailedException(
              "Failed to change state of replica %d for partition %s since the leader and isr path in zookeeper is empty"
              .format(replicaId, topicAndPartition))
      }
    }
    catch {
      case t: Throwable =>
        stateChangeLogger.error("Controller %d epoch %d initiated state change of replica %d for partition [%s,%d] to %s failed"
                                  .format(controllerId, controller.epoch, replicaId, topic, partition, targetState), t)
    }
  }

  private def assertValidPreviousStates(topic: String, partition: Int, replicaId: Int, fromStates: Seq[ReplicaState],
                                        targetState: ReplicaState) {
    assert(fromStates.contains(replicaState((topic, partition, replicaId))),
      "Replica %s for partition [%s,%d] should be in the %s states before moving to %s state"
        .format(replicaId, topic, partition, fromStates.mkString(","), targetState) +
        ". Instead it is in %s state".format(replicaState((topic, partition, replicaId))))
  }

  private def registerBrokerChangeListener() = {
    zkClient.subscribeChildChanges(ZkUtils.BrokerIdsPath, new BrokerChangeListener())
  }

  /**
   * Invoked on startup of the replica's state machine to set the initial state for replicas of all existing partitions
   * in zookeeper
   */
  private def initializeReplicaState() {
    for((topicPartition, assignedReplicas) <- controllerContext.partitionReplicaAssignment) {
      val topic = topicPartition.topic
      val partition = topicPartition.partition
      assignedReplicas.foreach { replicaId =>
        controllerContext.liveBrokerIds.contains(replicaId) match {
          case true => replicaState.put((topic, partition, replicaId), OnlineReplica)
          case false => replicaState.put((topic, partition, replicaId), OfflineReplica)
        }
      }
    }
  }

  private def getAllReplicasOnBroker(topics: Seq[String], brokerIds: Seq[Int]): Set[PartitionAndReplica] = {
    brokerIds.map { brokerId =>
      val partitionsAssignedToThisBroker =
        controllerContext.partitionReplicaAssignment.filter(p => topics.contains(p._1.topic) && p._2.contains(brokerId))
      if(partitionsAssignedToThisBroker.size == 0)
        info("No state transitions triggered since no partitions are assigned to brokers %s".format(brokerIds.mkString(",")))
      partitionsAssignedToThisBroker.map(p => new PartitionAndReplica(p._1.topic, p._1.partition, brokerId))
    }.flatten.toSet
  }

  def getPartitionsAssignedToBroker(topics: Seq[String], brokerId: Int):Seq[TopicAndPartition] = {
    controllerContext.partitionReplicaAssignment.filter(_._2.contains(brokerId)).keySet.toSeq
  }

  /**
   * This is the zookeeper listener that triggers all the state transitions for a replica
   */
  class BrokerChangeListener() extends IZkChildListener with Logging {
    this.logIdent = "[BrokerChangeListener on Controller " + controller.config.brokerId + "]: "
    def handleChildChange(parentPath : String, currentBrokerList : java.util.List[String]) {
      info("Broker change listener fired for path %s with children %s".format(parentPath, currentBrokerList.mkString(",")))
      controllerContext.controllerLock synchronized {
        if (hasStarted.get) {
          ControllerStats.leaderElectionTimer.time {
            try {
              val curBrokerIds = currentBrokerList.map(_.toInt).toSet
              val newBrokerIds = curBrokerIds -- controllerContext.liveOrShuttingDownBrokerIds
              val newBrokerInfo = newBrokerIds.map(ZkUtils.getBrokerInfo(zkClient, _))
              val newBrokers = newBrokerInfo.filter(_.isDefined).map(_.get)
              val deadBrokerIds = controllerContext.liveOrShuttingDownBrokerIds -- curBrokerIds
              controllerContext.liveBrokers = curBrokerIds.map(ZkUtils.getBrokerInfo(zkClient, _)).filter(_.isDefined).map(_.get)
              info("Newly added brokers: %s, deleted brokers: %s, all live brokers: %s"
                .format(newBrokerIds.mkString(","), deadBrokerIds.mkString(","), controllerContext.liveBrokerIds.mkString(",")))
              newBrokers.foreach(controllerContext.controllerChannelManager.addBroker(_))
              deadBrokerIds.foreach(controllerContext.controllerChannelManager.removeBroker(_))
              if(newBrokerIds.size > 0)
                controller.onBrokerStartup(newBrokerIds.toSeq)
              if(deadBrokerIds.size > 0)
                controller.onBrokerFailure(deadBrokerIds.toSeq)
            } catch {
              case e: Throwable => error("Error while handling broker changes", e)
            }
          }
        }
      }
    }
  }
}

sealed trait ReplicaState { def state: Byte }
case object NewReplica extends ReplicaState { val state: Byte = 1 }
case object OnlineReplica extends ReplicaState { val state: Byte = 2 }
case object OfflineReplica extends ReplicaState { val state: Byte = 3 }
case object NonExistentReplica extends ReplicaState { val state: Byte = 4 }


text:
using System.Web.Mvc;
using SFA.DAS.Authorization.Mvc.Attributes;
using SFA.DAS.EAS.Web.Extensions;

namespace SFA.DAS.EAS.Web.Controllers
{
    [DasAuthorize]
    [RoutePrefix("accounts/{HashedAccountId}/teams")]
    public class EmployerTeamController : Controller
    {
        [HttpGet]
        [Route]
        public ActionResult Index(string hashedAccountId)
        {
            return Redirect(Url.EmployerAccountsAction($"teams?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("view")]
        public ActionResult ViewTeam(string hashedAccountId)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/view?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("invite")]
        public ActionResult Invite(string hashedAccountId)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/invite?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("invite/next")]
        public ActionResult NextSteps(string hashedAccountId)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/invite/next?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("{invitationId}/cancel")]
        public ActionResult Cancel(string email, string invitationId, string hashedAccountId)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/{invitationId}/cancel?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("{email}/remove")]
        public ActionResult Remove(string hashedAccountId, string email)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/{email}/remove?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("{email}/role/change")]
        public ActionResult ChangeRole(string hashedAccountId, string email)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/{email}/role/change?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("{email}/review")]
        public ActionResult Review(string hashedAccountId, string email)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/{email}/review?{Request.QueryString}"));
        }

        [HttpGet]
        [Route("hideWizard")]
        public ActionResult HideWizard(string hashedAccountId)
        {
            return Redirect(Url.EmployerAccountsAction($"teams/hideWizard?{Request.QueryString}"));
        }
    }
}


text:
//
// Copyright (c) 2014-2016 Oliver Lehmann <lehmann@ans-netz.de>
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
//
package org.laladev.moneyjinn.hbci.core;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Observer;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.kapott.hbci.manager.HBCIHandler;
import org.kapott.hbci.manager.HBCIUtils;
import org.kapott.hbci.manager.HBCIUtilsInternal;
import org.kapott.hbci.passport.AbstractHBCIPassport;
import org.kapott.hbci.passport.HBCIPassport;
import org.kapott.hbci.structures.Konto;
import org.laladev.moneyjinn.hbci.core.collector.AccountMovementCollector;
import org.laladev.moneyjinn.hbci.core.collector.BalanceDailyCollector;
import org.laladev.moneyjinn.hbci.core.entity.AbstractAccountEntitiy;
import org.laladev.moneyjinn.hbci.core.entity.AccountMovement;
import org.laladev.moneyjinn.hbci.core.entity.BalanceDaily;
import org.laladev.moneyjinn.hbci.core.handler.AbstractHandler;
import org.laladev.moneyjinn.hbci.core.handler.AccountMovementHandler;
import org.laladev.moneyjinn.hbci.core.handler.BalanceDailyHandler;
import org.laladev.moneyjinn.hbci.core.handler.BalanceMonthlyHandler;

public final class LalaHBCI {
	private final Properties properties;

	public LalaHBCI(final Properties properties) {
		this.properties = properties;
	}

	public void main(final List<String> passports, final List<Observer> observerList) throws Exception {

		HBCIUtils.init(this.getHbciProperties(), new LalaHBCICallback());

		final SessionFactory sf = this.getSessionFactory();
		final EntityManager entityManager = sf.createEntityManager();
		try {
			for (final String passport : passports) {
				this.process(passport, entityManager, observerList);
			}
		} finally {
			entityManager.close();
			sf.close();
			HBCIUtils.done();
		}
	}

	/**
	 * executes all implemented handlers for all given passports
	 *
	 * @param passport
	 * @param session
	 * @param observerList
	 * @throws IOException
	 */
	private void process(final String passport, final EntityManager entityManager, final List<Observer> observerList)
			throws IOException {

		((LalaHBCICallback) HBCIUtilsInternal.getCallback()).setPassportPassword(this.getPassword(passport));

		final String type = this.getType(passport);

		if (type.equals("RDHNew")) {
			HBCIUtils.setParam("client.passport.RDHNew.filename", passport);
		} else if (type.equals("PinTan")) {
			HBCIUtils.setParam("client.passport.PinTan.filename", passport);
			((LalaHBCICallback) HBCIUtilsInternal.getCallback()).setPin(this.getPin(passport));
		} else {
			throw new RuntimeException("type " + type + " for passport " + passport
					+ " not supported (only PinTan and RDHNew supported)!");
		}

		final EntityTransaction tx = entityManager.getTransaction();
		tx.begin();
		final HBCIPassport hbciPassport = AbstractHBCIPassport.getInstance(type);

		HBCIHandler hbciHandler = null;
		try {
			hbciHandler = new HBCIHandler(null, hbciPassport);
			final Konto[] accounts = hbciPassport.getAccounts();

			for (final Konto account : accounts) {
				final AccountMovementCollector accountMovementCollector = new AccountMovementCollector();
				final BalanceDailyCollector balanceDailyCollector = new BalanceDailyCollector();

				final List<AccountMovement> accountMovements = accountMovementCollector.collect(hbciHandler, account);
				final BalanceDaily balanceDaily = balanceDailyCollector.collect(hbciHandler, account);

				if (accountMovements != null && !accountMovements.isEmpty()) {
					for (final AccountMovement accountMovement : accountMovements) {
						this.addIbanBic(accountMovement);
					}
				}

				if (balanceDaily != null) {
					this.addIbanBic(balanceDaily);
				}

				this.executeHandler(new AccountMovementHandler(entityManager, accountMovements), observerList);
				this.executeHandler(new BalanceDailyHandler(entityManager, balanceDaily), observerList);
				this.executeHandler(new BalanceMonthlyHandler(entityManager, balanceDaily, accountMovements),
						observerList);
			}

		} finally {
			if (hbciHandler != null) {
				hbciHandler.close();
			} else if (hbciPassport != null) {
				hbciPassport.close();
			}
		}

		tx.commit();

	}

	private void addIbanBic(final AbstractAccountEntitiy accountEntity) {
		if (accountEntity.getMyIban() == null && accountEntity.getMyAccountnumber() != null
				&& accountEntity.getMyBankcode() != null) {
			accountEntity.setMyIban(this.getProperty("hbci.mapping.iban."
					+ accountEntity.getMyAccountnumber().toString() + "." + accountEntity.getMyBankcode().toString()));
			accountEntity.setMyBic(this.getProperty("hbci.mapping.bic." + accountEntity.getMyAccountnumber().toString()
					+ "." + accountEntity.getMyBankcode().toString()));
		}
	}

	/**
	 * executes a given handler for all specified accounts
	 *
	 * @param handler
	 * @param hbciHandler
	 * @param observerList
	 * @param accounts
	 */
	private void executeHandler(final AbstractHandler handler, final List<Observer> observerList) {

		for (final Observer observer : observerList) {
			handler.addObserver(observer);
		}
		handler.handle();

	}

	/**
	 * returns the configured type for the given {@link HBCIPassport} filename
	 *
	 * @param passport
	 * @return online banking PIN
	 */
	private String getType(final String passport) {
		final File passportFile = new File(passport);
		final String type = this.getProperty("hbci." + passportFile.getName() + ".type");
		if (type == null) {
			throw new RuntimeException("type for passport " + passport + " not defined as property (hbci."
					+ passportFile.getName() + ".type)");
		}
		return type;

	}

	/**
	 * returns the configured password for the given {@link HBCIPassport} filename
	 *
	 * @param passport
	 * @return online banking PIN
	 */
	private String getPassword(final String passport) {
		final File passportFile = new File(passport);
		final String password = this.getProperty("hbci." + passportFile.getName() + ".password");
		if (password == null) {
			throw new RuntimeException("password for passport " + passport + " not defined as property (hbci."
					+ passportFile.getName() + ".password)");
		}
		return password;

	}

	/**
	 * returns the configured online banking PIN for the given {@link HBCIPassport} filename
	 *
	 * @param passport
	 * @return online banking PIN
	 */
	private String getPin(final String passport) {
		final File passportFile = new File(passport);
		final String pin = this.getProperty("hbci." + passportFile.getName() + ".pin");
		if (pin == null) {
			throw new RuntimeException("pin for passport " + passport + " not defined as property (hbci."
					+ passportFile.getName() + ".pin)");
		}
		return pin;

	}

	/**
	 * gets a property
	 *
	 * @param property
	 * @return property value
	 */
	private String getProperty(final String property) {
		return this.properties.getProperty(property);
	}

	/**
	 * creates the default hbci4java Properties valid for all of lalaHBCIs requests
	 *
	 * @return hbci4java {@link Properties}
	 */
	private Properties getHbciProperties() {
		final Properties hbciProperties = new Properties();
		hbciProperties.setProperty("client.product.name", "HBCI4Java");
		hbciProperties.setProperty("client.product.version", "2.5");
		hbciProperties.setProperty("client.passport.PinTan.checkcert", "1");
		hbciProperties.setProperty("client.passport.PinTan.init", "1");
		// hbciProperties.setProperty("client.passport.default", "PinTan");
		hbciProperties.setProperty("log.loglevel.default", "0");
		hbciProperties.setProperty("log.filter", "3");
		return hbciProperties;
	}

	/**
	 * creates and returns the Hibernate {@link SessionFactory} lalaHBCI works with
	 *
	 * @return {@link SessionFactory}
	 */
	private SessionFactory getSessionFactory() {
		return new Configuration().configure().buildSessionFactory();
	}
}


text:
package at.outdated.bitcoin.exchange.bitstamp;

import at.outdated.bitcoin.exchange.api.market.OrderType;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * Created by ebirn on 09.02.14.
 */
public class BitstampOrderTypeAdapter extends XmlAdapter<Integer,OrderType> {

    @Override
    public OrderType unmarshal(Integer v) throws Exception {

        switch(v) {
            case 0:
                return OrderType.BID;

            case 1:
                return OrderType.ASK;
        }

        return OrderType.UNDEF;
    }

    @Override
    public Integer marshal(OrderType v) throws Exception {

        switch(v) {
            case BID:
                return 0;

            case ASK:
                return 1;
        }
        return -1;
    }
}


text:
ROOT = ../../../..

include $(ROOT)/mak/config.mak

DIR = Providers/sample/SNMPIndicationProvider

LIBRARY = nsatrap

LIBRARIES = \
    pegprovider \
    pegclient \
    pegcommon

SOURCES = \
	SNMPIndicationProviderMain.cpp \
	SNMPIndicationProvider.cpp

include $(ROOT)/mak/dynamic-library.mak


text:
export declare abstract class OnAfterSave {
    abstract onAfterSave(): void;
}


text:
/* jshint asi:true */

'use strict'

var lib = require('../index')
var minimist = require('minimist')

var cli = lib.expand(minimist, {
  alias: {
    s: 'set'
  }
})

// run:
// node examples/expand-standalone.js --set=a:b
// node examples/expand-standalone.js -s=foo:bar
// node examples/expand-standalone.js --get=c:d
cli(process.argv.slice(2), {
  alias: {
    g: 'get'
  }
})

console.log('options', cli.options)
console.log('argv', cli.argv)


text:
package com.amazonaws.services.s3.model;

import com.amazonaws.services.s3.AmazonS3;

/**
 * Request object for the parameters to delete a bucket's cross origin configuration.
 *
 * @see AmazonS3#deleteBucketCrossOriginConfiguration(DeleteBucketCrossOriginConfigurationRequest)
 */
public class DeleteBucketCrossOriginConfigurationRequest extends GenericBucketRequest {

    /**
     * Creates a new request object, ready to be executed to delete the cross origin
     * configuration for the specified bucket.
     *
     * @param bucketName
     *            The name of the bucket whose cross origin configuration is being
     *            deleted.
     */
    public DeleteBucketCrossOriginConfigurationRequest(String bucketName) {
        super(bucketName);
    }
}


text:
JBrowse in Galaxy
=================

    JBrowse is a fast, embeddable genome browser built completely with
    JavaScript and HTML5

Thus, it makes an ideal fit with Galaxy, especially for use as a
workflow summary. E.g. annotate a genome, then visualise all of the
associated datasets as an interactive HTML page. This tool MUST be whitelisted
(or ``sanitize_all_html=False``) to function correctly.

Installation
============

It is recommended to install this wrapper via the Galaxy Tool Shed.

Running Locally
===============

The Galaxy tool interface writes out a yaml file which is then used to generate
the visualizations. An example used during development/testing can be seen in
`test-data/*/test.xml`. The format is in no way rigorously defined and is
likely to change at any time! Beware. ;)

History
=======

-  0.5.2 Support for CanvasFeatures options.
-  0.5.1 Support for contextual menus. Conda tests.
-  0.5 Update existing instances on disk. Index names. Support HTML tracks
   instead of Canvas. Support default tracks. General JBrowse optinos
-  0.4 Support for dataset collections and customisation of tracks including
   labelling, colours, styling. Added support for genetic code selection.
   Fixed package installation recipe issues.
-  0.3 Added support for BigWig, etc.
-  0.2 Added support for BAM, Blast, VCF.
-  0.1 Initial public release.

Wrapper License (MIT/BSD Style)
===============================

Permission to use, copy, modify, and distribute this software and its
documentation with or without modifications and for any purpose and
without fee is hereby granted, provided that any copyright notices
appear in all copies and that both those copyright notices and this
permission notice appear in supporting documentation, and that the names
of the contributors or copyright holders not be used in advertising or
publicity pertaining to distribution of the software without specific
prior permission.

THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.


text:
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Oxagile.Demos.Api.Dtos;
using Oxagile.Demos.Data;
using Oxagile.Demos.Data.Entities;
using Oxagile.Demos.Data.Repositories;

namespace Oxagile.Demos.Api.Controllers
{
    [Route("api/companies/{id:int}")]
    public class CompanyController : ControllerBase
    {
        private readonly IUnitOfWork uow;
        private readonly IMapper mapper;

        public CompanyController(
            IUnitOfWork uow,
            IMapper mapper)
        {
            this.uow = uow;
            this.mapper = mapper;
        }

        [HttpGet]
        [ProducesResponseType(typeof(GetCompanyDto), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Get(int id)
        {
            var company = await uow.Company.Get(id);
            if (company == null)
            {
                return NotFound(new { respose = "error", message = $"company id = {id} does not exist"});
            }

            return Ok(mapper.Map<GetCompanyDto>(company));
        }

        [HttpGet("users")]
        [ProducesResponseType(typeof(IEnumerable<GetCompanyUserDto>), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetUsers(int id)
        {
            var company = await uow.Company.Get(id);
            if (company == null)
            {
                return NotFound(new { respose = "error", message = $"company id = {id} does not exist"});
            }

            return Ok(mapper.Map<IEnumerable<GetCompanyUserDto>>(company.Users));
        }

        [HttpPut]
        [ProducesResponseType(typeof(GetCompanyDto), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> Edit(int id, [FromBody]EditCompanyDto company)
        {
            if (ModelState.IsValid)
            {
                var existing = await uow.Company.Get(id);
                if (existing == null)
                {
                    return NotFound(new { respose = "error", message = $"company id = {id} does not exist"});
                }

                existing.Name = company.Name;

                var updated = uow.Company.Update(existing);
                await uow.CommitAsync();
                return Ok(mapper.Map<GetCompanyDto>(updated));
            }

            return BadRequest(ModelState);
        }

        [HttpDelete]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Delete(int id)
        {
            var existing = await uow.Company.Get(id);
            if (existing == null)
            {
                return NotFound(new { respose = "error", message = $"company id = {id} does not exist"});
            }

            uow.Company.Delete(existing);
            await uow.CommitAsync();
            return Ok();
        }
    }
}


text:
package org.gradoop.common.model.impl.properties.strategies;

import org.apache.flink.core.memory.DataInputView;
import org.gradoop.common.model.impl.properties.bytes.Bytes;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.common.model.impl.properties.Type;

import java.io.IOException;

/**
 * Strategy class for handling {@code PropertyValue} operations with a value of the type
 * {@code Integer}.
 */
public class IntegerStrategy extends AbstractFixSizedPropertyValueStrategy<Integer> {

  @Override
  public Integer read(DataInputView inputView, byte typeByte) throws IOException {
    int length = Bytes.SIZEOF_INT;
    byte[] rawBytes = new byte[length];

    for (int i  = 0; i < rawBytes.length; i++) {
      rawBytes[i] = inputView.readByte();
    }

    return Bytes.toInt(rawBytes);
  }

  @Override
  public int compare(Integer value, Object other) {
    return PropertyValueStrategyUtils.compareNumerical(value, other);
  }

  @Override
  public boolean is(Object value) {
    return value instanceof Integer;
  }

  @Override
  public Class<Integer> getType() {
    return Integer.class;
  }

  @Override
  public Integer get(byte[] bytes) {
    return Bytes.toInt(bytes, PropertyValue.OFFSET);
  }

  @Override
  public byte getRawType() {
    return Type.INTEGER.getTypeByte();
  }

  @Override
  public byte[] getRawBytes(Integer value) {
    byte[] rawBytes = new byte[PropertyValue.OFFSET + Bytes.SIZEOF_INT];
    rawBytes[0] = getRawType();
    Bytes.putInt(rawBytes, PropertyValue.OFFSET, value);
    return rawBytes;
  }
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.test.util;

import android.annotation.TargetApi;
import android.os.Build;

import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.ntp.IncognitoNewTabPage;
import org.chromium.chrome.browser.ntp.NewTabPage;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;

/**
 * Utilities for testing the NTP.
 */
public class NewTabPageTestUtils {

    /**
     * Waits for the NTP owned by the passed in tab to be fully loaded.
     *
     * @param tab The tab to be monitored for NTP loading.
     * @return Whether the NTP has fully loaded.
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static boolean waitForNtpLoaded(final Tab tab) throws InterruptedException {
        return CriteriaHelper.pollForUIThreadCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                if (!tab.isIncognito()) {
                    // TODO(tedchoc): Make MostVisitedPage also have a isLoaded() concept.
                    if (FeatureUtilities.isDocumentMode(
                            tab.getWindowAndroid().getApplicationContext())) {
                        return tab.getView().isAttachedToWindow();
                    }
                    if (!(tab.getNativePage() instanceof NewTabPage)) {
                        return false;
                    }
                    return ((NewTabPage) tab.getNativePage()).isLoadedForTests();
                } else {
                    if (!(tab.getNativePage() instanceof IncognitoNewTabPage)) {
                        return false;
                    }
                    return ((IncognitoNewTabPage) tab.getNativePage()).isLoadedForTests();
                }
            }
        });
    }

}


text:
import sys
import os
import pynja
from .root_dir import finder

pynja.set_root_dir(finder.get_root_dir())
pynja.rootDir = pynja.root_paths.rootDir

def init():
    # qt helper projects
    pynja.import_file('build/repo/qt/qt_core.py')
    pynja.import_file('build/repo/qt/qt_xml.py')
    # boost helper projects
    pynja.import_file('build/repo/boost/boost_build.py')

    # output paths
    pynja.rootPaths.out = os.path.join(pynja.rootDir, "_out")
    pynja.rootPaths.built = os.path.join(pynja.rootPaths.out, "built")
    pynja.rootPaths.codeBrowsing = os.path.join(pynja.rootPaths.out, "cb")
    pynja.rootPaths.bin = os.path.join(pynja.rootPaths.out, "bin")

    # tool paths
    pynja.rootPaths.protobuf = os.path.join(pynja.rootDir, "imports/protobuf-2.4.1")

    if (os.name == 'nt'):
        # you can customize these paths to point at a location in source control
        if pynja.io.is_64bit_os():
            pynja.rootPaths.msvc9 = r"C:\Program Files (x86)\Microsoft Visual Studio 9.0"
            pynja.rootPaths.msvc10 = r"C:\Program Files (x86)\Microsoft Visual Studio 10.0"
            pynja.rootPaths.msvc11 = r"C:\Program Files (x86)\Microsoft Visual Studio 11.0"
            pynja.rootPaths.msvc12 = r"C:\Program Files (x86)\Microsoft Visual Studio 12.0"
            pynja.rootPaths.msvc14 = r"C:\Program Files (x86)\Microsoft Visual Studio 14.0"
            pynja.rootPaths.llvmDir = r"C:\Program Files (x86)\LLVM"
        else:
            raise Exception("32-bit OS, seriously?")

        pynja.rootPaths.winsdk71 = r'C:\Program Files\Microsoft SDKs\Windows\v7.1'
        pynja.rootPaths.winsdk80 = r'C:\Program Files (x86)\Windows Kits\8.0'
        pynja.rootPaths.winsdk81 = r'C:\Program Files (x86)\Windows Kits\8.1'
        pynja.rootPaths.ucrt100 = r'C:\Program Files (x86)\Windows Kits\10'
        pynja.rootPaths.ucrt100Ver = "10.0.10150.0"

        pynja.rootPaths.mingw = r"C:\MinGW"
        pynja.rootPaths.mingw64 = r"C:\MinGW64"

        pynja.rootPaths.cuda50 = r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0"

        pynja.rootPaths.android_ndk_r8d = r"C:\Software\Android\android-ndk-r8d"

        pynja.rootPaths.jdk15 = r"C:\Program Files\Java\jdk1.7.0_15"

        pynja.rootPaths.qt5vc11BinDir = r"C:\Qt\Qt5.0.2\5.0.2\msvc2012_64\bin"
        pynja.rootPaths.boost150 = r"D:\work\code\boost\boost_1_50_0"
        pynja.rootPaths.re2c = os.path.join(pynja.rootDir, r"prebuilt\windows\re2c\re2c-0.13.5-bin\re2c.exe")


text:
<?php

namespace Com\Tecnick\Pdf;

use \Com\Tecnick\Pdf\Exception as PdfException;
use \Com\Tecnick\Color\Pdf as ObjColor;
use \Com\Tecnick\Barcode\Barcode as ObjBarcode;
use \Com\Tecnick\File\File as ObjFile;
use \Com\Tecnick\Unicode\Convert as ObjUniConvert;
use \Com\Tecnick\Pdf\Encrypt\Encrypt as ObjEncrypt;
use \Com\Tecnick\Pdf\Page\Page as ObjPage;
use \Com\Tecnick\Pdf\Graph\Draw as ObjGraph;
use \Com\Tecnick\Pdf\Font\Stack as ObjFont;
use \Com\Tecnick\Pdf\Image\Import as ObjImage;

/**
 * Com\Tecnick\Pdf\ClassObjects
 *
 * External class objects PDF class
 *
 * @since       2002-08-03
 * @category    Library
 * @package     Pdf
 * @author      Nicola Asuni <info@tecnick.com>
 * @copyright   2002-2017 Nicola Asuni - Tecnick.com LTD
 * @license     http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
 * @link        https://github.com/tecnickcom/tc-lib-pdf
 */
abstract class ClassObjects extends \Com\Tecnick\Pdf\MetaInfo
{
    /**
     * Encrypt object
     *
     * @var \Com\Tecnick\Pdf\Encrypt\Encrypt
     */
    public $encrypt;

    /**
     * Color object
     *
     * @var \Com\Tecnick\Color\Pdf
     */
    public $color;

    /**
     * Barcode object
     *
     * @var \Com\Tecnick\Barcode\Barcode
     */
    public $barcode;

    /**
     * File object
     *
     * @var \Com\Tecnick\File\File
     */
    public $file;

    /**
     * Unicode Convert object
     *
     * @var \Com\Tecnick\Unicode\Convert
     */
    public $uniconv;

    /**
     * Page object
     *
     * @var \Com\Tecnick\Pdf\Page\Page
     */
    public $page;

    /**
     * Graph object
     *
     * @var \Com\Tecnick\Pdf\Graph\Draw
     */
    public $graph;

    /**
     * Font object
     *
     * @var \Com\Tecnick\Pdf\Font\Stack
     */
    public $font;

    /**
     * Image Import object
     *
     * @var \Com\Tecnick\Pdf\Image\Import
     */
    public $image;

    /**
     * Initialize class objects
     */
    protected function initClassObjects()
    {
        $this->color = new ObjColor;
        $this->barcode = new ObjBarcode;
        $this->file = new ObjFile;
        $this->uniconv = new ObjUniConvert;

        if ($this->encrypt === null) {
            $this->encrypt = new ObjEncrypt();
        }

        $this->page = new ObjPage(
            $this->unit,
            $this->color,
            $this->encrypt,
            $this->pdfa,
            $this->sigapp
        );
        $this->kunit = $this->page->getKUnit();

        $this->graph = new ObjGraph(
            $this->kunit,
            0, // $this->graph->setPageWidth($pagew)
            0, // $this->graph->setPageHeight($pageh)
            $this->color,
            $this->encrypt,
            $this->pdfa
        );

        $this->font = new ObjFont(
            $this->kunit,
            $this->subsetfont,
            $this->isunicode,
            $this->pdfa
        );

        $this->image = new ObjImage(
            $this->kunit,
            $this->encrypt,
            $this->pdfa
        );
    }

    /**
     * Enable or disable the the Signature Approval
     *
     * @param boolean $enabled It true enable the Signature Approval
     */
    protected function enableSignatureApproval($enabled = true)
    {
        $this->sigapp = (bool) $enabled;
        $this->page->enableSignatureApproval($this->sigapp);
        return $this;
    }
}


text:
package com.github.ruediste.rise.core.persistence.time;

import java.time.ZoneId;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import com.github.ruediste.rise.nonReloadable.persistence.AnyUnit;

@Converter(autoApply = true)
@AnyUnit
public class ZoneIdConverter implements AttributeConverter<ZoneId, String> {

    @Override
    public String convertToDatabaseColumn(ZoneId arg) {
        if (arg == null)
            return null;
        return arg.getId();
    }

    @Override
    public ZoneId convertToEntityAttribute(String arg) {
        if (arg == null)
            return null;
        return ZoneId.of(arg);
    }

}


text:
package org.elasticsearch.search.aggregations.pipeline.seriesarithmetic;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.Script.ScriptField;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilder;

import java.io.IOException;
import java.util.Map;

public class SeriesArithmeticBuilder extends PipelineAggregatorBuilder<SeriesArithmeticBuilder> {

    private String format;
    private GapPolicy gapPolicy;
    private Script script;
    private Map<String, String> bucketsPathsMap;

    public SeriesArithmeticBuilder(String name) {
        super(name, SeriesArithmeticPipelineAggregator.TYPE.name());
    }

    public SeriesArithmeticBuilder script(Script script) {
        this.script = script;
        return this;
    }

    public SeriesArithmeticBuilder format(String format) {
        this.format = format;
        return this;
    }

    public SeriesArithmeticBuilder gapPolicy(GapPolicy gapPolicy) {
        this.gapPolicy = gapPolicy;
        return this;
    }

    /**
     * Sets the paths to the buckets to use for this pipeline aggregator
     */
    public SeriesArithmeticBuilder setBucketsPathsMap(Map<String, String> bucketsPathsMap) {
        this.bucketsPathsMap = bucketsPathsMap;
        return this;
    }

    @Override
    protected XContentBuilder internalXContent(XContentBuilder builder, Params builderParams) throws IOException {
        if (script != null) {
            builder.field(ScriptField.SCRIPT.getPreferredName(), script);
        }
        if (format != null) {
            builder.field(SeriesArithmeticParser.FORMAT.getPreferredName(), format);
        }
        if (gapPolicy != null) {
            builder.field(SeriesArithmeticParser.GAP_POLICY.getPreferredName(), gapPolicy.getName());
        }
        if (bucketsPathsMap != null) {
            builder.field(PipelineAggregator.Parser.BUCKETS_PATH.getPreferredName(), bucketsPathsMap);
        }
        return builder;
    }

}


text:
LOGGED IN AS: {{home.userEmail}}

    ID
    DESCRIPTION
    PRIORITY
    STATUS
    ACTIONS

  <input class="inputEdit" ng-model="home.editField" ng-show="home.editingTask">
  <button class="saveButton" ng-click="home.updateFirebaseDescription(home.editField, home.indexEdit)" ng-show="home.editingTask">Save</button>
  <button class="saveButton" ng-click="home.editingTask = false" ng-show="home.editingTask">cancel</button>

    {{list.id}}

{{list.description}}

      <button class="editButton" ng-click="home.editingTask = true; home.indexEdit = $index; home.editField = list.description">Edit</button>

    {{list.priority}}
      <select ng-model="home.changePriority[$index]" ng-change="home.updateFirebasePriority(home.changePriority[$index], $index); home.changeFirebasePriorityColor($index)">
        <option value="high">HIGH</option>
        <option value="medium">MEDIUM</option>
        <option value="low">LOW</option>
      </select>

    {{list.status}}
      <select ng-model="home.changeStatus[$index]" ng-change="home.updateFirebaseStatus(home.changeStatus[$index], $index)">
        <option value="incomplete">INCOMPLETE</option>
        <option value="complete">COMPLETE</option>
      </select>

    <button ng-click="home.removeFirebaseItem($index)">REMOVE ITEM</button>

<input ng-model="home.newToDoItem" type="text">
<button ng-click="home.addRecordToFirebase(home.newToDoItem)">ADD ITEM</button>
<button ng-click="home.removeAll()">Remove All</button>


text:
DB2/Informix DBMS
===================

Include scripts or SQL statements specific to DB2 or Informix DBMS'

----------


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.25 at 05:48:09 PM CEST
//

package es.rickyepoderi.wbxml.bind.wvcsp;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "groupID",
    "groupProperties",
    "ownProperties"
})
@XmlRootElement(name = "SetGroupProps-Request")
public class SetGroupPropsRequest {

    @XmlElement(name = "GroupID", required = true)
    protected GroupID groupID;
    @XmlElement(name = "GroupProperties")
    protected GroupProperties groupProperties;
    @XmlElement(name = "OwnProperties")
    protected OwnProperties ownProperties;

    /**
     * Gets the value of the groupID property.
     *
     * @return
     *     possible object is
     *     {@link GroupID }
     *
     */
    public GroupID getGroupID() {
        return groupID;
    }

    /**
     * Sets the value of the groupID property.
     *
     * @param value
     *     allowed object is
     *     {@link GroupID }
     *
     */
    public void setGroupID(GroupID value) {
        this.groupID = value;
    }

    /**
     * Gets the value of the groupProperties property.
     *
     * @return
     *     possible object is
     *     {@link GroupProperties }
     *
     */
    public GroupProperties getGroupProperties() {
        return groupProperties;
    }

    /**
     * Sets the value of the groupProperties property.
     *
     * @param value
     *     allowed object is
     *     {@link GroupProperties }
     *
     */
    public void setGroupProperties(GroupProperties value) {
        this.groupProperties = value;
    }

    /**
     * Gets the value of the ownProperties property.
     *
     * @return
     *     possible object is
     *     {@link OwnProperties }
     *
     */
    public OwnProperties getOwnProperties() {
        return ownProperties;
    }

    /**
     * Sets the value of the ownProperties property.
     *
     * @param value
     *     allowed object is
     *     {@link OwnProperties }
     *
     */
    public void setOwnProperties(OwnProperties value) {
        this.ownProperties = value;
    }

}


text:
using System;

namespace Google.Apis.Logging
{
    /// <summary>
    /// Describes a logging interface used for outputing errors/messages/debug info.
    /// </summary>
    public interface ILogger
    {
        /// <summary>
        /// Defines whether debug output is logged or not.
        /// </summary>
        bool IsDebugEnabled { get; }

        /// <summary>
        /// Returns a logger which will be associated with the specified type.
        /// </summary>
        /// <param name="type">Type to which this logger belongs.</param>
        /// <returns>A type-associated logger.</returns>
        ILogger ForType(Type type);

        /// <summary>
        /// Returns a logger which will be associated with the specified type.
        /// </summary>
        /// <returns>A type-associated logger.</returns>
        ILogger ForType<T>();

        /// <summary>
        /// Logs an info message.
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="formatArgs">String.Format arguments (if applicable).</param>
        void Info(string message, params object[] formatArgs);

        /// <summary>
        /// Logs a warning.
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="formatArgs">String.Format arguments (if applicable).</param>
        void Warning(string message, params object[] formatArgs);

        /// <summary>
        /// Logs a debug message.
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="formatArgs">String.Format arguments (if applicable).</param>
        void Debug(string message, params object[] formatArgs);

        /// <summary>
        /// Logs an error message resulting from an exception.
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="message">The message to log.</param>
        /// <param name="formatArgs">String.Format arguments (if applicable).</param>
        void Error(Exception exception, string message, params object[] formatArgs);

        /// <summary>
        /// Logs an error message
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="formatArgs">String.Format arguments (if applicable).</param>
        void Error(string message, params object[] formatArgs);
    }
}


text:
#ifdef WIN32
#include "pch.hpp"
#else
#include <core/pch.hpp>
#endif

#include <core/Query/PlaylistLoad.h>
#include <core/Library/Base.h>

using namespace musik::core;

//////////////////////////////////////////
///\brief
///Constructor
//////////////////////////////////////////
Query::PlaylistLoad::PlaylistLoad(void){
}

//////////////////////////////////////////
///\brief
///Destructor
//////////////////////////////////////////
Query::PlaylistLoad::~PlaylistLoad(void){
}

void Query::PlaylistLoad::LoadPlaylist(int playlistId){
    this->playlistId    = playlistId;
}

bool Query::PlaylistLoad::ParseQuery(Library::Base *library,db::Connection &db){

    db::Statement selectTracks("SELECT track_id FROM playlist_tracks WHERE playlist_id=? ORDER BY sort_order",db);
    selectTracks.BindInt(0,this->playlistId);

    while(selectTracks.Step()==db::Row){
        boost::mutex::scoped_lock lock(library->resultMutex);
        this->trackResults.push_back(TrackPtr(new LibraryTrack(selectTracks.ColumnInt(0),library->Id())));
    }
    return true;
}

//////////////////////////////////////////
///\brief
///Copy a query
///
///\returns
///A shared_ptr to the Query::Base
//////////////////////////////////////////
Query::Ptr Query::PlaylistLoad::copy() const{
    return Query::Ptr(new Query::PlaylistLoad(*this));
}


text:
from __future__ import absolute_import
from __future__ import print_function

import json
import os
from PIL import Image
import shutil
import subprocess
import tempfile
import unittest
import uuid

import tensorflow as tf
from tensorflow.python.lib.io import file_io

import google.datalab as dl
import google.datalab.bigquery as bq

CODE_PATH = os.path.abspath(os.path.join(
    os.path.dirname(__file__), '..', 'mltoolbox', 'code_free_ml'))

class TestTransformRawData(unittest.TestCase):
  """Tests for applying a saved model"""

  @classmethod
  def setUpClass(cls):

    # Set up dirs.
    cls.working_dir = tempfile.mkdtemp()
    cls.source_dir = os.path.join(cls.working_dir, 'source')
    cls.analysis_dir = os.path.join(cls.working_dir, 'analysis')
    cls.output_dir = os.path.join(cls.working_dir, 'output')
    file_io.create_dir(cls.source_dir)

    # Make test image files.
    img1_file = os.path.join(cls.source_dir, 'img1.jpg')
    image1 = Image.new('RGBA', size=(300, 300), color=(155, 0, 0))
    image1.save(img1_file)
    img2_file = os.path.join(cls.source_dir, 'img2.jpg')
    image2 = Image.new('RGBA', size=(50, 50), color=(125, 240, 0))
    image2.save(img2_file)
    img3_file = os.path.join(cls.source_dir, 'img3.jpg')
    image3 = Image.new('RGBA', size=(800, 600), color=(33, 55, 77))
    image3.save(img3_file)

    # Make csv input file
    cls.csv_input_filepath = os.path.join(cls.source_dir, 'input.csv')
    file_io.write_string_to_file(
        cls.csv_input_filepath,
        '1,1,Monday,23.0,%s\n' % img1_file +
        '2,0,Friday,18.0,%s\n' % img2_file +
        '3,0,Sunday,12.0,%s\n' % img3_file)

    # Call analyze.py to create analysis results.
    schema = [{'name': 'key_col', 'type': 'INTEGER'},
              {'name': 'target_col', 'type': 'FLOAT'},
              {'name': 'cat_col', 'type': 'STRING'},
              {'name': 'num_col', 'type': 'FLOAT'},
              {'name': 'img_col', 'type': 'STRING'}]
    schema_file = os.path.join(cls.source_dir, 'schema.json')
    file_io.write_string_to_file(schema_file, json.dumps(schema))
    features = {'key_col': {'transform': 'key'},
                'target_col': {'transform': 'target'},
                'cat_col': {'transform': 'one_hot'},
                'num_col': {'transform': 'identity'},
                'img_col': {'transform': 'image_to_vec'}}
    features_file = os.path.join(cls.source_dir, 'features.json')
    file_io.write_string_to_file(features_file, json.dumps(features))
    cmd = ['python ' + os.path.join(CODE_PATH, 'analyze.py'),
           '--output=' + cls.analysis_dir,
           '--csv=' + cls.csv_input_filepath,
           '--schema=' + schema_file,
           '--features=' + features_file]
    subprocess.check_call(' '.join(cmd), shell=True)

    # Setup a temp GCS bucket.
    cls.bucket_root = 'gs://temp_mltoolbox_test_%s' % uuid.uuid4().hex
    subprocess.check_call('gsutil mb %s' % cls.bucket_root, shell=True)

  @classmethod
  def tearDownClass(cls):
    shutil.rmtree(cls.working_dir)
    subprocess.check_call('gsutil -m rm -r %s' % cls.bucket_root, shell=True)

  def test_local_csv_transform(self):
    """Test transfrom from local csv files."""

    cmd = ['python ' + os.path.join(CODE_PATH, 'transform.py'),
           '--csv=' + self.csv_input_filepath,
           '--analysis=' + self.analysis_dir,
           '--prefix=features',
           '--output=' + self.output_dir]
    print('cmd ', ' '.join(cmd))
    subprocess.check_call(' '.join(cmd), shell=True)

    # Read the tf record file. There should only be one file.
    record_filepath = os.path.join(self.output_dir,
                                   'features-00000-of-00001.tfrecord.gz')
    options = tf.python_io.TFRecordOptions(
        compression_type=tf.python_io.TFRecordCompressionType.GZIP)
    serialized_examples = list(tf.python_io.tf_record_iterator(record_filepath, options=options))
    self.assertEqual(len(serialized_examples), 3)

    example = tf.train.Example()
    example.ParseFromString(serialized_examples[0])

    transformed_number = example.features.feature['num_col'].float_list.value[0]
    self.assertAlmostEqual(transformed_number, 23.0)
    transformed_category = example.features.feature['cat_col'].int64_list.value[0]
    self.assertEqual(transformed_category, 2)
    image_bytes = example.features.feature['img_col'].float_list.value
    self.assertEqual(len(image_bytes), 2048)
    self.assertTrue(any(x != 0.0 for x in image_bytes))

  def test_local_bigquery_transform(self):
    """Test transfrom locally, but the data comes from bigquery."""

    # Make a BQ table, and insert 1 row.
    try:
      project_id = dl.Context.default().project_id
      dataset_name = 'test_transform_raw_data_%s' % uuid.uuid4().hex
      table_name = 'tmp_table'

      dataset = bq.Dataset((project_id, dataset_name)).create()
      table = bq.Table((project_id, dataset_name, table_name))
      table.create([{'name': 'key_col', 'type': 'INTEGER'},
                    {'name': 'target_col', 'type': 'FLOAT'},
                    {'name': 'cat_col', 'type': 'STRING'},
                    {'name': 'num_col', 'type': 'FLOAT'},
                    {'name': 'img_col', 'type': 'STRING'}])

      img1_file = os.path.join(self.source_dir, 'img1.jpg')
      dest_file = os.path.join(self.bucket_root, 'img1.jpg')
      subprocess.check_call('gsutil cp %s %s' % (img1_file, dest_file), shell=True)

      data = [
          {
           'key_col': 1,
           'target_col': 1.0,
           'cat_col': 'Monday',
           'num_col': 23.0,
           'img_col': dest_file,
          },
      ]
      table.insert(data=data)

      cmd = ['python ' + os.path.join(CODE_PATH, 'transform.py'),
             '--bigquery=%s.%s.%s' % (project_id, dataset_name, table_name),
             '--analysis=' + self.analysis_dir,
             '--prefix=features',
             '--project-id=' + project_id,
             '--output=' + self.output_dir]
      print('cmd ', ' '.join(cmd))
      subprocess.check_call(' '.join(cmd), shell=True)

      # Read the tf record file. There should only be one file.
      record_filepath = os.path.join(self.output_dir,
                                     'features-00000-of-00001.tfrecord.gz')
      options = tf.python_io.TFRecordOptions(
          compression_type=tf.python_io.TFRecordCompressionType.GZIP)
      serialized_examples = list(tf.python_io.tf_record_iterator(record_filepath, options=options))
      self.assertEqual(len(serialized_examples), 1)

      example = tf.train.Example()
      example.ParseFromString(serialized_examples[0])

      transformed_number = example.features.feature['num_col'].float_list.value[0]
      self.assertAlmostEqual(transformed_number, 23.0)
      transformed_category = example.features.feature['cat_col'].int64_list.value[0]
      self.assertEqual(transformed_category, 2)
      image_bytes = example.features.feature['img_col'].float_list.value
      self.assertEqual(len(image_bytes), 2048)
      self.assertTrue(any(x != 0.0 for x in image_bytes))
    finally:
      dataset.delete(delete_contents=True)

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


text:
STRIP ?= strip

all : ../out/wslbridge-backend

../out/wslbridge-backend : wslbridge-backend.cc ../common/SocketIo.cc ../common/SocketIo.h ../VERSION.txt Makefile
	mkdir -p ../out
	$(CXX) -std=c++11 -fno-exceptions \
		-static-libgcc -static-libstdc++ \
		-D_GNU_SOURCE \
		-DWSLBRIDGE_VERSION=$(shell cat ../VERSION.txt) \
		-Wall -O2 $< ../common/SocketIo.cc -o $@ -lutil -pthread
	$(STRIP) $@

clean:
	rm -f ../out/wslbridge-backend


text:
current_dir = File.dirname(__FILE__)
# https://github.com/chef/chef/issues/2449
chef_repo_path File.join(current_dir, '..', 'zero-repo')

# We'll use policyfiles with local mode.
use_policyfile true
policy_group 'local'
policy_name 'pantry'
versioned_cookbooks true
policy_document_native_api true


text:
#include <soc.h>
#include <arch/arm/cortex_m/mpu/nxp_mpu.h>

#define FLEXBUS_BASE_ADDRESS 0x08000000
#define SRAM_L_BASE_ADDRESS 0x1FFF0000
#define DEVICE_S_BASE_ADDRESS 0x20030000

static struct nxp_mpu_region mpu_regions[] = {
	/* Region 0 */
	MPU_REGION_ENTRY("FLASH_0",
			 CONFIG_FLASH_BASE_ADDRESS,
			 0x07FFFFFF,
			 REGION_FLASH_ATTR),
	/* Region 1 */
	/*
	 * This region (Flexbus + FlexNVM) is bigger than the FLEXBUS one in
	 * order to save 1 region allocation in the MPU.
	 */
	MPU_REGION_ENTRY("FLEXBUS_0",
			 FLEXBUS_BASE_ADDRESS,
			 0x1BFFFFFF,
			 REGION_IO_ATTR),
	/* Region 2 */
	MPU_REGION_ENTRY("RAM_L_0",
			 SRAM_L_BASE_ADDRESS,
			 0x1FFFFFFF,
			 REGION_RAM_ATTR),
	/* Region 3 */
	MPU_REGION_ENTRY("RAM_U_0",
			 CONFIG_SRAM_BASE_ADDRESS,
			 (CONFIG_SRAM_BASE_ADDRESS +
				 (CONFIG_SRAM_SIZE * 1024) - 1),
			 REGION_RAM_ATTR),
	/* Region 4 */
	MPU_REGION_ENTRY("DEVICE_0",
			 DEVICE_S_BASE_ADDRESS,
			 0xFFFFFFFF,
			 REGION_IO_ATTR),
};

struct nxp_mpu_config mpu_config = {
	.num_regions = ARRAY_SIZE(mpu_regions),
	.mpu_regions = mpu_regions,
	.sram_region = 3,
};


text:
Kubernetes worker is the driver to integrated with ArchCI and kubernetes.

With kubernetes worker, we can deploy CI tasks in kubernetes cluster without any effort. Notice that this worker is under development, we will update the repo if we make some progress.

## Usage

It's written in go so you can run it at most platforms.

```
cd ArchCI/kubernetes-workers
go run worker.go
```

Or simply download the binary.

```
go get github.com/ArchCI/kubernetes-workers
```

The worker will pull tasks from [archci](https://github.com/ArchCI/archci), please make sure it's running at first.


text:
package flags

import (
	"fmt"
	"path"
	"runtime"
	"testing"
)

func assertCallerInfo() (string, int) {
	ptr := make([]uintptr, 15)
	n := runtime.Callers(1, ptr)

	if n == 0 {
		return "", 0
	}

	mef := runtime.FuncForPC(ptr[0])
	mefile, meline := mef.FileLine(ptr[0])

	for i := 2; i < n; i++ {
		f := runtime.FuncForPC(ptr[i])
		file, line := f.FileLine(ptr[i])

		if file != mefile {
			return file, line
		}
	}

	return mefile, meline
}

func assertErrorf(t *testing.T, format string, args ...interface{}) {
	msg := fmt.Sprintf(format, args...)

	file, line := assertCallerInfo()

	t.Errorf("%s:%d: %s", path.Base(file), line, msg)
}

func assertFatalf(t *testing.T, format string, args ...interface{}) {
	msg := fmt.Sprintf(format, args...)

	file, line := assertCallerInfo()

	t.Fatalf("%s:%d: %s", path.Base(file), line, msg)
}

func assertString(t *testing.T, a string, b string) {
	if a != b {
		assertErrorf(t, "Expected %#v, but got %#v", b, a)
	}
}

func assertStringArray(t *testing.T, a []string, b []string) {
	if len(a) != len(b) {
		assertErrorf(t, "Expected %#v, but got %#v", b, a)
		return
	}

	for i, v := range a {
		if b[i] != v {
			assertErrorf(t, "Expected %#v, but got %#v", b, a)
			return
		}
	}
}

func assertBoolArray(t *testing.T, a []bool, b []bool) {
	if len(a) != len(b) {
		assertErrorf(t, "Expected %#v, but got %#v", b, a)
		return
	}

	for i, v := range a {
		if b[i] != v {
			assertErrorf(t, "Expected %#v, but got %#v", b, a)
			return
		}
	}
}

func assertParserSuccess(t *testing.T, data interface{}, args ...string) (*Parser, []string) {
	parser := NewParser(data, Default&^PrintErrors)
	ret, err := parser.ParseArgs(args)

	if err != nil {
		t.Fatalf("Unexpected parse error: %s", err)
		return nil, nil
	}

	return parser, ret
}

func assertParseSuccess(t *testing.T, data interface{}, args ...string) []string {
	_, ret := assertParserSuccess(t, data, args...)
	return ret
}

func assertError(t *testing.T, err error, typ ErrorType, msg string) {
	if err == nil {
		assertFatalf(t, "Expected error: %s", msg)
		return
	}

	if e, ok := err.(*Error); !ok {
		assertFatalf(t, "Expected Error type, but got %#v", err)
	} else {
		if e.Type != typ {
			assertErrorf(t, "Expected error type {%s}, but got {%s}", typ, e.Type)
		}

		if e.Message != msg {
			assertErrorf(t, "Expected error message %#v, but got %#v", msg, e.Message)
		}
	}
}

func assertParseFail(t *testing.T, typ ErrorType, msg string, data interface{}, args ...string) []string {
	parser := NewParser(data, Default&^PrintErrors)
	ret, err := parser.ParseArgs(args)

	assertError(t, err, typ, msg)
	return ret
}


text:
cask :v1 => 'trash-it' do
  if MacOS.release <= :leopard
    version '4.1'
    sha256 'a30ed22452d4c2fcefdbf2d892394524a3744ebd50fdcee2203ff705e648240e'
    url "http://nonamescriptware.com/wp-content/uploads/TrashIt#{version.gsub('.','')}.zip"
    app "TrashIt #{version}/Drag content to Desktop/Trash It!.app"
  else
    version '6.0.1'
    sha256 'c3a45b6f97a210502bc6adbb4f09329de2622ca9cdb999c40bddd55ed6c8f4db'
    url 'http://nonamescriptware.com/wp-content/uploads/Trashit.zip'
    app "Trash It! #{version}/Drag content to Desktop/Trash It!.app"
  end

  homepage 'http://nonamescriptware.com/'
  license :unknown    # todo: improve this machine-generated value
end


text:
package ie.cit.caf.rowmapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import ie.cit.caf.domain.Participant;

public class ParticipantRowMapper implements RowMapper<Participant>{

@Override
	public Participant mapRow(ResultSet rs, int index) throws SQLException {
		Participant part = new Participant();

		part.setParticipant_id(rs.getInt("participant_id"));
		part.setPerson_id(rs.getString("person_id"));
		part.setPerson_name(rs.getString("person_name"));
		part.setPerson_date(rs.getString("person_date"));
		part.setPerson_url(rs.getString("person_url"));

		return part;
	}
}