text:
            //atom built in
    var   atom_panels = require('atom-message-panel')
        , MessagePanelView = atom_panels.MessagePanelView
        , PlainMessageView = atom_panels.PlainMessageView

module.exports = {

    visible : false,

    init: function() {

        this.view = new MessagePanelView({
            title: 'lime'
        });

    },

    dispose: function() {

    },

//Public API

    show: function() {
        this.view.attach();
        this.visible = true;
    },

    hide: function() {
        this.view.close();
        this.visible = false;
    },

    toggle: function() {
        this.visible = !this.visible;
        if(this.visible) this.show();
        else this.hide();
    },

    error: function(message, clear, sticky) {
        this._msg(message, 'error', clear, sticky);
    },

    success: function(message, clear, sticky) {
        this._msg(message, 'success', clear, sticky);
    },

    debug: function(message, clear, sticky) {
        var _debug = atom.config.get('haxe.debug_logging');
        if(_debug) {
            this._msg(message, null, clear, sticky);
        }
    },

    msg: function(message, clear, sticky) {
        this._msg(message, null, clear, sticky);
    },

    info: function(message, clear, sticky) {
        this._msg(message, 'highlight', clear, sticky);
    },

//Internal

    _msg : function(message, type, clear, sticky) {

        var typename;

        if(clear) this.view.clear();
        if(type) typename = 'text-'+type;

        var msg = new PlainMessageView({
            message: message,
            className: typename
        });

        this.view.add( msg );
        this.view.body.scrollTop(1e10);
        this.show();

            clearTimeout(this.timeoutid);

        if(!sticky) {
                //:TODO: could probably config the timeout
            this.timeoutid = setTimeout(this.hide.bind(this), 5000);
        }

    } //_msg

} //module.exports


text:
<?php

namespace BlockCypher\AppCommon\App\Service\Internal;

use BlockCypher\Api\Wallet as BlockCypherWallet;
use BlockCypher\Client\WalletClient;
use BlockCypher\Exception\BlockCypherConnectionException;

/**
 * Class BlockCypherAuthenticationService
 * @package BlockCypher\AppCommon\App\Service\Internal
 */
class BlockCypherAuthenticationService
{
    const ERROR_WALLET_NOT_FOUND = 404;
    const ERROR_WALLET_ALREADY_EXISTS = 409;
    const AUTH_WALLET_COIN_SYMBOL = 'btc-testnet';
    const AUTH_WALLET_NAME = 'AUTH_WALLET';

    /**
     * @var BlockCypherApiContextFactory
     */
    private $apiContextFactory;

    /**
     * @param BlockCypherApiContextFactory $apiContextFactory
     */
    public function __construct(BlockCypherApiContextFactory $apiContextFactory)
    {
        $this->apiContextFactory = $apiContextFactory;
    }

    /**
     * @param string $token
     * @return bool
     * @throws BlockCypherConnectionException
     */
    public function authenticate($token)
    {
        $apiContext = $this->apiContextFactory->getApiContext(self::AUTH_WALLET_COIN_SYMBOL, $token);
        $walletClient = new WalletClient($apiContext);

        try {
            // Create BlockCypher wallet
            $bcWallet = new BlockCypherWallet();
            $bcWallet->setToken($token);
            $bcWallet->setName(self::AUTH_WALLET_NAME);

            $bcWallet = $walletClient->create($bcWallet);

            if ($bcWallet && $bcWallet->getName() == self::AUTH_WALLET_NAME) {
                return true;
            } else {
                return false;
            }

        } catch (BlockCypherConnectionException $e) {
            if ($e->getCode() == self::ERROR_WALLET_ALREADY_EXISTS) {
                return true;
            }
            throw $e;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Greedy implementation of the vision problem.

Written by Ooj Amit Srivastava.
"""

from typing import List

def solve(satisfactions : List[int], walkers : List[int]) -> int:
    # Find best pair go back-n-forth
    # Pair goodness = sum(pair) * U-index(pair) + sum(0->pair)

    # This is optimal because the walker would keep going
    # back-n-forth across the pair with highest satisfaction
    # as any other path would bring less total satisfaction.
    # easy and intuitive to spot if you draw any array.

    scores = {u: [] for u in walkers}
    # there is a max telescope that a walker can reach
    # which is equal to its u.
    for i in range(min(len(satisfactions), max(walkers)) - 1):
        for w in walkers:
            if i >= w:
                break
            turns = w-i
            # remaining turns would be spent going back-n-forth
            value = ((turns+1)//2)*satisfactions[i] + (turns//2)*satisfactions[i+1]
            # sum of S to reach best pair
            cost = sum(satisfactions[:i])
            scores[w].append(value+cost)

    # Since "cost" is added to each score
    # The max score is optimal path
    # and can be added to total
    total = 0
    for u in walkers:
        total += max(scores[u])

    return total

if __name__ == "__main__":
    t, w = input().split()

    # Satisfaction for ith telescope
    # S = [1, 2, 3, -1, -1, 10]
    S = [int(input()) for _ in range(int(t))]
    # Path length of jth walker
    # U = (23, 24)
    U = [int(input()) for _ in range(int(w))]

    print(solve(S, U))


text:
module Jpmobile
  VERSION = '7.0.3'.freeze
end


text:
@interface PDAddressCell : PDBaseTableViewCell

@end


text:
package org.apache.reef.runtime.local.client;

import org.apache.reef.runtime.common.client.DriverConfigurationProvider;
import org.apache.reef.runtime.common.parameters.JVMHeapSlack;
import org.apache.reef.runtime.local.client.parameters.MaxNumberOfEvaluators;
import org.apache.reef.runtime.local.client.parameters.RackNames;
import org.apache.reef.runtime.local.driver.LocalDriverConfiguration;
import org.apache.reef.runtime.local.driver.RuntimeIdentifier;
import org.apache.reef.tang.Configuration;
import org.apache.reef.tang.Configurations;
import org.apache.reef.tang.annotations.Parameter;
import org.apache.reef.tang.formats.ConfigurationModule;

import javax.inject.Inject;

import java.net.URI;
import java.util.Set;

/**
 * Helper class that assembles the driver configuration when run on the local runtime.
 */
final class LocalDriverConfigurationProviderImpl implements DriverConfigurationProvider {

  private final int maxEvaluators;
  private final double jvmHeapSlack;
  private final Set<String> rackNames;

  @Inject
  LocalDriverConfigurationProviderImpl(@Parameter(MaxNumberOfEvaluators.class) final int maxEvaluators,
                                       @Parameter(JVMHeapSlack.class) final double jvmHeapSlack,
                                       @Parameter(RackNames.class) final Set<String> rackNames) {
    this.maxEvaluators = maxEvaluators;
    this.jvmHeapSlack = jvmHeapSlack;
    this.rackNames = rackNames;
  }

  private Configuration getDriverConfiguration(final URI jobFolder,
                                               final String clientRemoteId,
                                               final String jobId) {
    ConfigurationModule configModule = LocalDriverConfiguration.CONF
        .set(LocalDriverConfiguration.MAX_NUMBER_OF_EVALUATORS, this.maxEvaluators)
        .set(LocalDriverConfiguration.ROOT_FOLDER, jobFolder.getPath())
        .set(LocalDriverConfiguration.JVM_HEAP_SLACK, this.jvmHeapSlack)
        .set(LocalDriverConfiguration.CLIENT_REMOTE_IDENTIFIER, clientRemoteId)
        .set(LocalDriverConfiguration.JOB_IDENTIFIER, jobId)
        .set(LocalDriverConfiguration.RUNTIME_NAMES, RuntimeIdentifier.RUNTIME_NAME);
    for (final String rackName : rackNames) {
      configModule = configModule.set(LocalDriverConfiguration.RACK_NAMES, rackName);
    }
    return configModule.build();
  }

  /**
   * Assembles the driver configuration.
   *
   * @param jobFolder                The folder in which the local runtime will execute this job.
   * @param clientRemoteId           the remote identifier of the client. It is used by the Driver to establish a
   *                                 connection back to the client.
   * @param jobId                    The identifier of the job.
   * @param applicationConfiguration The configuration of the application, e.g. a filled out DriverConfiguration
   * @return The Driver configuration to be used to instantiate the Driver.
   */
  public Configuration getDriverConfiguration(final URI jobFolder,
                                              final String clientRemoteId,
                                              final String jobId,
                                              final Configuration applicationConfiguration) {
    return Configurations.merge(getDriverConfiguration(jobFolder, clientRemoteId, jobId), applicationConfiguration);
  }
}


text:
AliMESpidTask *AddMESpidTask(Bool_t mc, Bool_t hm = kFALSE)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliMESpidTask *pid = new AliMESpidTask("MESpid");
  mgr->AddTask(pid);
  pid->SetPostProcess(kFALSE);
  pid->SetMCdata(mc);
  pid->SetTriggerHM(hm);
  pid->SetDebugLevel(0);

  mgr->ConnectInput(pid, 0, mgr->GetCommonInputContainer()); // connect main (ESD) container

  // get exchange containers
  AliAnalysisDataContainer *ci[AliMESbaseTask::kNcontainers] = {NULL};
  ci[0] = (AliAnalysisDataContainer*)(AliAnalysisManager::GetAnalysisManager()->GetContainers()->FindObject("MESeventInfo"));
  ci[1] = (AliAnalysisDataContainer*)(AliAnalysisManager::GetAnalysisManager()->GetContainers()->FindObject("MEStracks"));
  if(mc){
	  ci[2] = (AliAnalysisDataContainer*)(AliAnalysisManager::GetAnalysisManager()->GetContainers()->FindObject("MESMCeventInfo"));
	  ci[3] = (AliAnalysisDataContainer*)(AliAnalysisManager::GetAnalysisManager()->GetContainers()->FindObject("MESMCtracks"));
  }
  Info("AddMESpidTask", Form("Inputs : [0]=\"%s\" [1]=\"%s\" [2]=\"%s\" [3]=\"%s\"",
							 ci[0]?ci[0]->GetName():"none",
							 ci[1]?ci[1]->GetName():"none",
							 ci[2]?ci[2]->GetName():"none",
							 ci[3]?ci[3]->GetName():"none"));

  // connect containers
  mgr->ConnectInput(pid, AliMESbaseTask::kEventInfo, ci[0]); // connect event info
  mgr->ConnectInput(pid, AliMESbaseTask::kTracks, ci[1]);    // connect track info container
  if(mc){
    mgr->ConnectInput(pid, AliMESbaseTask::kMCeventInfo, ci[2]); // connect MC event info
    mgr->ConnectInput(pid, AliMESbaseTask::kMCtracks, ci[3]);    // connect MC tracks container
  }
  mgr->ConnectOutput(pid, AliMESbaseTask::kQA, mgr->CreateContainer("pidQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:MES", mgr->GetCommonFileName())));

  return pid;
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**lastUpdated** | [**LocalDate**](LocalDate.md) | last_updated string |
**observerId** | **Long** | The entity that was observing the asteroid field when it was mined.  |
**observerType** | [**ObserverTypeEnum**](#ObserverTypeEnum) | The category of the observing entity |

## Enum: ObserverTypeEnum
Name | Value
---- | -----
STRUCTURE | "structure"


text:
package uk.org.lidalia.sysoutslf4j.integration;

class SysOutUser implements ISysOutUser {
    public void useSysOut() {
        System.out.println("Logged");
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_60" class="java.beans.XMLDecoder">
 <object class="com.ti.dvt.datamodel.solution.SolutionManager$PersistState" id="SolutionManager$PersistState0">
  <void class="com.ti.dvt.datamodel.solution.SolutionManager$PersistState" method="getField">
   <string>defaultSolution</string>
   <void method="set">
    <object idref="SolutionManager$PersistState0"/>
    <string>/home/koos/ti/ccsv6/ccs_base/dvt_4.1.0.201507151655/CodeGen/solutions/CodeGenCoverage</string>
   </void>
  </void>
 </object>
<void class="com.ti.dvt.datamodel.solution.SolutionManager$PersistState" method="getField">
 <string>openedSolutions</string>
 <void id="ArrayList0" method="get">
  <object idref="SolutionManager$PersistState0"/>
  <void method="add">
   <string>/home/koos/Documents/Papers/SOURCECODE/CRFID_firmware/dvt/AnalysisSolutionsTemp/AnalysisSolution1469302192430/null</string>
  </void>
  <void method="add">
   <string>/home/koos/ti/ccsv6/ccs_base/dvt_4.1.0.201507151655/CodeGen/solutions/CodeGenCoverage</string>
  </void>
 </void>
</void>
<void idref="ArrayList0"/>
</java>


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::connection()->getSchemaBuilder()->create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('body', 255);
            $table->morphs('commentable');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::connection()->getSchemaBuilder()->dropIfExists('comments');
    }
}


text:
var app = angular.module('heatmapApp', ['services']);

// Code borrowed from stackoverflow user Anthony O. - May 15th 2014
app.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);

/*
==========================================================================================================
==========================================================================================================
==========================================================================================================
==========================================================================================================
==========================================================================================================
========================================= MAIN CONTROLLER ================================================
==========================================================================================================
==========================================================================================================
==========================================================================================================
==========================================================================================================
==========================================================================================================
*/

app.controller('heatmapCtrl', function ($scope, $http, $log, $filter, HttpServiceJsonp, $location, $timeout, $window) {
    $scope.pythonHost = python_host_global;
    console.log("REST services endpoint (Plotly_heatmapApp): " + $scope.pythonHost);
  //$scope.pythonHost = "http://localhost:8182"; // Localhost
      //$scope.pythonHost = "http://ec2-52-26-26-232.us-west-2.compute.amazonaws.com"; // PROD
  //$scope.pythonHost = "http://ec2-52-32-253-172.us-west-2.compute.amazonaws.com"; //Search Engine (Dev)
  //$scope.pythonHost = "http://ec2-52-24-205-32.us-west-2.compute.amazonaws.com:8181"; //Search Engine (Prod)

  $scope.esId = "";
  $scope.title = "";
  $scope.plotlyData = {
    "passThisDataAlong": {},
    "passThisLayoutAlong": {},
    "xValues": [],
    "yValues": [],
    "zValues": [],
    "exportRowTarget": "",
    "exportColumnTarget": "",
    "exportArray": [],
    "heatmapFullHeight": 1000,
    "heatmapFullWidth": 1000,
    "heatmapScaledHeight": 530,
    "heatmapScaledWidth": 530,
    "isFullSize": false,
    "isNewWindow": false
  }

  $scope.GetQueryStringParams = function(sParam)
  {
      var sPageURL = window.location.search.substring(1);
      var sURLVariables = sPageURL.split('&');
      for (var i = 0; i < sURLVariables.length; i++)
      {
          var sParameterName = sURLVariables[i].split('=');
          if (sParameterName[0] == sParam)
          {
              return sParameterName[1];
          }
      }
  }

  $scope.openPlotlyExternal = function(){
      var hiddenForm = $('
'+
          '<form action="https://plot.ly/external" '+
          'method="post" target="_blank">'+
          '<input type="text" '+
          'name="data" /></form>
')
          .appendTo('body');
      var graphData = JSON.stringify($scope.getPlotlyGraph());
      hiddenForm.find('input').val(graphData);
      hiddenForm.find('form').submit();
      hiddenForm.remove();
      return false;
  };

  $scope.openInNewWindow = function() {
    $window.open(window.location.href);//"http://geneli.st:8181/Prototype2/partials/Plotly_heatmap.html?geneList=OR2J3&termId=my%20title&clusterId=" + $scope.esId + "&networkTitle=my%20title&showFullSize=true");
  }

  $scope.resizeHeatMap = function() {
    //======================================
    // Flip the size toggle and take action
    //======================================
    $scope.plotlyData.isFullSize = !$scope.plotlyData.isFullSize;

    if($scope.plotlyData.isFullSize){
      var heatMapDiv = $('#heatmap').width($scope.plotlyData.heatmapFullWidth).height($scope.plotlyData.heatmapFullHeight);

      var update = {
        width: $scope.plotlyData.heatmapFullWidth,
        height: $scope.plotlyData.heatmapFullHeight
      };

      Plotly.relayout('heatmap', update);
    } else { // Scaled size
      var heatMapDiv = $('#heatmap').width($scope.plotlyData.heatmapScaledWidth).height($scope.plotlyData.heatmapScaledHeight);

      var update = {
        width: $scope.plotlyData.heatmapScaledWidth,
        height: $scope.plotlyData.heatmapScaledHeight
      };

      Plotly.relayout('heatmap', update);
    }
  }

  $scope.getPlotlyGraph = function(){
      return {
          data: $scope.plotlyData.passThisDataAlong,
          layout: $scope.passThisLayoutAlong
      };
  };

  $scope.exportData = function(){
    console.log("x: " + $scope.plotlyData.xValues.length + " y: " + $scope.plotlyData.yValues.length + " z: " + $scope.plotlyData.zValues[0].length);
    $scope.plotlyData.exportArray = Array($scope.plotlyData.yValues.length + 1);
    //=========================
    // Print the table header
    //=========================
    var tempHeader = ",";
    for (var i = 0; i < $scope.plotlyData.xValues.length; i++) {
      tempHeader += $scope.plotlyData.xValues[($scope.plotlyData.xValues.length - 1) - i] + ",";
    }
    //$scope.plotlyData.exportArray[0] = tempHeader;
    $scope.plotlyData.exportArray[0] = $scope.getXLabels();

    for (var i = 0; i < $scope.plotlyData.yValues.length; i++)
    {
      //==============================================
      // The first value in the row is the row label
      //==============================================
      var tempRowString = $scope.plotlyData.yValues[i] + ",";
      for (var j = 0; j < $scope.plotlyData.xValues.length; j++)
      {
        tempRowString += $scope.plotlyData.zValues[i][j] + ",";
      }
      $scope.plotlyData.exportArray[($scope.plotlyData.yValues.length) - i] = tempRowString;
    }

    var exportArrayString = "data:text/csv;charset=utf-8,";
    for (var k = 0; k <= $scope.plotlyData.yValues.length; k++) {
        exportArrayString += $scope.plotlyData.exportArray[k] + '\n';
    }
    console.log(exportArrayString);
    var encodedUri = encodeURI(exportArrayString);
    window.open(encodedUri);
    //console.log($scope.plotlyData.exportArray);

    //$('#heatmap').html('

' + $scope.plotlyData.zValues + '

');

  };

  $scope.exportXData = function(){
    var exportArrayString = "data:text/csv;charset=utf-8,";
    for (var i = 0; i < $scope.plotlyData.xValues.length; i++) {
        exportArrayString += $scope.plotlyData.xValues[i] + '\n';
    }

    var encodedUri = encodeURI(exportArrayString);
    window.open(encodedUri);
  };

  $scope.exportYData = function(){
    var exportArrayString = "data:text/csv;charset=utf-8,";
    for (var i = 0; i < $scope.plotlyData.yValues.length; i++) {
        exportArrayString += $scope.plotlyData.yValues[i] + '\n';
    }

    var encodedUri = encodeURI(exportArrayString);
    window.open(encodedUri);
  };

  $scope.getXLabels = function(){
    var tempHeader = ",";
    for (var i = 0; i < $scope.plotlyData.xValues.length; i++) {
      tempHeader += $scope.plotlyData.xValues[i] + ",";
    }

    return tempHeader;
  };

  $scope.getYLabels = function(){
    var tempHeader = ",";
    for (var i = 0; i < $scope.plotlyData.yValues.length; i++) {
      tempHeader += $scope.plotlyData.yValues[($scope.plotlyData.yValues.length - 1) - i] + ",";
    }

    return tempHeader;
  };

  $scope.init_page = function(){ //http://localhost:63343/Prototype2/prototype2C.html#?savedId=563a8343f6f4071f79300231
    $('#heatmapIsLoading').html('');
    var myPlot = document.getElementById('heatmap')
    var heatmap_title = "";
    $scope.esId = $scope.GetQueryStringParams("clusterId");
    $scope.title = $scope.GetQueryStringParams("termId").replace("%20", " ");
    $scope.plotlyData.isFullSize = $scope.GetQueryStringParams("showFullSize");
    if(typeof $scope.plotlyData.isFullSize === 'undefined'){
      $scope.plotlyData.isFullSize = false;
    } else {
      $scope.plotlyData.isNewWindow = true;
    }

    var url = $scope.pythonHost + "/nav/elasticsearch/getheatmap3/" + $scope.esId + "?callback=JSON_CALLBACK";
    console.log(url);
    $('#heatmap').css( "display", "none" );
    var myrequest = HttpServiceJsonp.jsonp(url)
         .success(function (result) {
           //$('#heatmapIsLoading').html('
Cluster - ' + $scope.title + '
');
           $('#heatmapIsLoading').html('');

           //===========================================
           // calculate the full size height and width
           //===========================================
           $scope.plotlyData.heatmapFullHeight = 22 * result.yValues.length + 180;
           $scope.plotlyData.heatmapFullWidth = 22 * result.xValues.length + 100;

           if($scope.plotlyData.isFullSize){
             height = $scope.plotlyData.heatmapFullHeight;
             width = $scope.plotlyData.heatmapFullWidth;
           } else {
             height = $scope.plotlyData.heatmapScaledHeight;
             width = $scope.plotlyData.heatmapScaledWidth;
           }

           $('#heatmap').width(width).height(height);

           $scope.plotlyData.xValues = result.xValues;
           $scope.plotlyData.yValues = result.yValues;
           $scope.plotlyData.zValues = result.zValues;

           var colorscaleValue = [
             [0, '#ee4035'],
             [1, '#0392cf']
           ];

           var data = [{
             x: $scope.plotlyData.xValues,
             y: $scope.plotlyData.yValues,
             z: $scope.plotlyData.zValues,
             type: 'heatmap',
             autocolorscale: false,
             //zsmooth: 'fast',
             colorscale: 'Picnic',
             zmax: 1.0,
             zmin: -1.0
           }];

           var layout = {
             title: '',
             annotations: [],
             xaxis: {
               ticks: '',
               side: 'top',
               width: 700,
               height: 700,
               autosize: true
             },
             yaxis: {
               ticks: '',
               ticksuffix: ' ',
               width: 700,
               height: 700,
               autosize: true
             }
           };

           $scope.plotlyData.passThisDataAlong = data;
           $scope.passThisLayoutAlong = layout;

           Plotly.newPlot('heatmap', data, layout, {showLink: false});
           //Plotly.addTraces('heatmap', {y: [1, 5, 7]}, 0);

/*
           $('#heatmap').on('plotly_click', function(myData){
             var plotDiv = document.getElementById('heatmap');
              console.log(plotDiv.data);
              console.log(myData.target._hoverdata[0].y);

              if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
                $scope.$apply(function(){
                  $scope.plotlyData.exportRowTarget = myData.target._hoverdata[0].y;
                  $scope.plotlyData.exportColumnTarget = myData.target._hoverdata[0].x;
                });
              }

              //alert(myData.target._hoverdata[0].y);
              //alert('Closest point clicked: ');
          });
*/
           $('#heatmap').css( "display", "block" );
         }).finally(function () {
    }).error(function (data, status, headers, config) {
                  alert(data + ' - ' + status + ' - ' + headers);
    });
  };
});


text:
from django import forms

from .models import Print, PrintImg

class PrintForm(forms.ModelForm):
    class Meta:
        model = Print
        fields = ['name', 'expires_in', 'desc']

PrintImgFormSet = forms.inlineformset_factory(
    Print, PrintImg,
    fields=['img'],
    can_order=False,
    can_delete=False,
    extra=5,
    min_num=1,
    max_num=6,
    validate_min=True,
    validate_max=True,
)


text:
package com.facebook.buck.testutil;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import java.util.regex.Pattern;

/**
 * Assertion helper for hamcrest library that checks if a given string matches a regular expression
 * or whether it contains a fragment that matches some pattern.
 */
public class RegexMatcher extends TypeSafeMatcher<CharSequence> {

  protected final Pattern pattern;

  public RegexMatcher(Pattern pattern) {
    this.pattern = pattern;
  }

  @Override
  protected boolean matchesSafely(CharSequence charSequence) {
    return pattern.matcher(charSequence).matches();
  }

  @Override
  public void describeTo(Description description) {
    description
        .appendText("a string with pattern \"")
        .appendText(pattern.toString())
        .appendText("\"");
  }

  @Override
  public void describeMismatchSafely(CharSequence charSequence, Description mismatchDescription) {
    mismatchDescription
        .appendText("was \"")
        .appendText(charSequence.toString())
        .appendText("\"");
  }

  private static class RegexFindMatcher extends RegexMatcher {

    public RegexFindMatcher(Pattern pattern) {
      super(pattern);
    }

    @Override
    protected boolean matchesSafely(CharSequence charSequence) {
      return pattern.matcher(charSequence).find();
    }

    @Override
    public void describeTo(Description description) {
      description
          .appendText("a string containing pattern \"")
          .appendText(pattern.toString())
          .appendText("\"");
    }
  }

  /**
   * Creates a matcher that checks if the examined {@link CharSequence} matches the specified
   * {@link Pattern}.
   *

   * For example:
   *
assertThat("Test-42", matchesPattern(Pattern.compile("^Test-[0-9]+$")))

   *
   * @param pattern
   *     the pattern that the returned matcher will use to match any examined {@link CharSequence}
   */
  @Factory
  public static Matcher<CharSequence> matchesPattern(Pattern pattern) {
    return new RegexMatcher(pattern);
  }

  /**
   * Creates a matcher that checks if the examined {@link CharSequence} matches the specified
   * regular expression.
   *

   * For example:
   *
assertThat("Example-43", matchesRegex("^Example-[0-9]+$"))

   *
   * @param regex
   *     the regular expression that the returned matcher will use to match any examined
   *     {@link CharSequence}
   */
  @Factory
  public static Matcher<CharSequence> matchesRegex(String regex) {
    return matchesPattern(Pattern.compile(regex));
  }

  /**
   * Creates a matcher that checks if a specified {@link Pattern} can be found in the examined
   * {@link CharSequence}
   *

   * For example:
   *
assertThat("Test-42-Test", containsPattern(Pattern.compile("[0-9]+")))

   *
   * @param pattern
   *     the pattern that the returned matcher will use to find a match in any examined
   *     {@link CharSequence}
   */
  @Factory
  public static Matcher<CharSequence> containsPattern(Pattern pattern) {
    return new RegexFindMatcher(pattern);
  }

  /**
   * Creates a matcher that checks if a specified regular expression can be found in the examined
   * {@link CharSequence}
   *

   * For example:
   *
assertThat("Test-571-Test", containsRegex("[0-9]+"))

   *
   * @param regex
   *     the regular expression that the returned matcher will use to find a match in any examined
   *     {@link CharSequence}
   */
  @Factory
  public static Matcher<CharSequence> containsRegex(String regex) {
    return containsPattern(Pattern.compile(regex));
  }

}


text:
<?php

namespace Visitor\Model\Entity;

class ProductEntity
{
    public $id;
    public $name;

    public function exchangeArray($data)
    {
        $this->id   = (!empty($data['prod_id'])) ? $data['prod_id'] : null;
        $this->name = (!empty($data['prod_name'])) ? $data['prod_name'] : null;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package nl.mantiscode.csvreader;

import com.vaadin.server.VaadinRequest;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author joey
 */
public class MyVaadinUITest {

    public MyVaadinUITest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of init method, of class MyVaadinUI.
     */
    @Test
    public void testInit() {
        System.out.println("init");
        VaadinRequest request = null;
        MyVaadinUI instance = new MyVaadinUI();
        instance.init(request);
        // TODO review the generated test code and remove the default call to fail.
        assertTrue(true);
    }

}


text:
using System;

namespace Loops
{
    class CalculateNthCatalanNumber
    {
        //In the combinatorial mathematics, the Catalan numbers are calculated by the following formula:
        //C(n)=(2n)!/[(n+1)!n!]  n>=0;
        //Write a program to calculate the Nth Catalan number by given N.

        static void Main()
        {
            //variables
            int n;
            do
            {
                Console.Write("Enter a number : ");
            }
            while (!int.TryParse(Console.ReadLine(), out n) || n <= 0);
            Console.WriteLine();
            decimal result = 1;

            //expressions
            int K = n ;
            for (int i = n + 2; i <= 2 * n; i++, K--)
            {
                result *= (decimal)i / K;
            }

            Console.WriteLine("CatalanNumber ({0}) : {1:F0}", n, result);
        }
    }
}


text:
set -x

PROFILE_ID=$(curl -s -XPOST -H "Content-Type: application/json" -d '{"username": "bob", "email": "bob1@mail.com"}' http://localhost:8080/api/profile | perl -e 'while(<>) {$_ =~ /"uid":"([^"]+)"/; print "$1\n"}')

curl -s -XGET -H "Accept: application/json" http://localhost:8080/api/profile/$PROFILE_ID
read input
curl -s -XGET -H "Accept: application/json" http://localhost:8080/api/search\?email\=bob1@mail.com
read input
curl -s -XPUT -H "Content-Type: application/json" -d '{"username": "bob", "email": "bob2@mail.com"}' http://localhost:8080/api/profile/$PROFILE_ID
read input
curl -s -XGET -H "Accept: application/json" http://localhost:8080/api/search\?email\=bob2@mail.com
read input
curl -s -XDELETE http://localhost:8080/api/profile/$PROFILE_ID
read input
curl -s -XGET -H "Accept: application/json" http://localhost:8080/api/search\?email\=bob2@mail.com


text:
namespace cast_streaming {
namespace remoting {
namespace {

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessage(
    openscreen::cast::RpcMessage_RpcProc type) {
  auto rpc = std::make_unique<openscreen::cast::RpcMessage>();
  rpc->set_proc(type);
  return rpc;
}

}  // namespace

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForError() {
  return CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONERROR);
}

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForMediaEnded() {
  return CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONENDED);
}

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForStatisticsUpdate(
    const media::PipelineStatistics& stats) {
  auto rpc =
      CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONSTATISTICSUPDATE);
  auto* message = rpc->mutable_rendererclient_onstatisticsupdate_rpc();
  message->set_audio_bytes_decoded(stats.audio_bytes_decoded);
  message->set_video_bytes_decoded(stats.video_bytes_decoded);
  message->set_video_frames_decoded(stats.video_frames_decoded);
  message->set_video_frames_dropped(stats.video_frames_dropped);
  message->set_audio_memory_usage(stats.audio_memory_usage);
  message->set_video_memory_usage(stats.video_memory_usage);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForBufferingStateChange(media::BufferingState state) {
  auto rpc = CreateMessage(
      openscreen::cast::RpcMessage::RPC_RC_ONBUFFERINGSTATECHANGE);
  auto* message = rpc->mutable_rendererclient_onbufferingstatechange_rpc();
  message->set_state(ToProtoMediaBufferingState(state).value());
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForAudioConfigChange(
    const media::AudioDecoderConfig& config) {
  auto rpc =
      CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONAUDIOCONFIGCHANGE);
  auto* message = rpc->mutable_rendererclient_onaudioconfigchange_rpc();
  openscreen::cast::AudioDecoderConfig* proto_audio_config =
      message->mutable_audio_decoder_config();
  ConvertAudioDecoderConfigToProto(config, proto_audio_config);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForVideoConfigChange(
    const media::VideoDecoderConfig& config) {
  auto rpc =
      CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONVIDEOCONFIGCHANGE);
  auto* message = rpc->mutable_rendererclient_onvideoconfigchange_rpc();
  openscreen::cast::VideoDecoderConfig* proto_video_config =
      message->mutable_video_decoder_config();
  ConvertVideoDecoderConfigToProto(config, proto_video_config);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForVideoNaturalSizeChange(const gfx::Size& size) {
  auto rpc = CreateMessage(
      openscreen::cast::RpcMessage::RPC_RC_ONVIDEONATURALSIZECHANGE);
  auto* message = rpc->mutable_rendererclient_onvideonatualsizechange_rpc();
  message->set_width(size.width());
  message->set_height(size.height());
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForVideoOpacityChange(bool opaque) {
  auto rpc =
      CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONVIDEOOPACITYCHANGE);
  rpc->set_boolean_value(opaque);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForMediaTimeUpdate(
    base::TimeDelta media_time) {
  auto rpc = CreateMessage(openscreen::cast::RpcMessage::RPC_RC_ONTIMEUPDATE);
  auto* message = rpc->mutable_rendererclient_ontimeupdate_rpc();
  message->set_time_usec(media_time.InMicroseconds());
  message->set_max_time_usec(media_time.InMicroseconds());
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForInitializationComplete(bool has_succeeded) {
  auto rpc =
      CreateMessage(openscreen::cast::RpcMessage::RPC_R_INITIALIZE_CALLBACK);
  rpc->set_boolean_value(has_succeeded);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage> CreateMessageForFlushComplete() {
  return CreateMessage(openscreen::cast::RpcMessage::RPC_R_FLUSHUNTIL_CALLBACK);
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForAcquireRendererDone(
    openscreen::cast::RpcMessenger::Handle receiver_renderer_handle) {
  auto rpc =
      CreateMessage(openscreen::cast::RpcMessage::RPC_ACQUIRE_RENDERER_DONE);
  rpc->set_integer_value(receiver_renderer_handle);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForDemuxerStreamInitialize(
    openscreen::cast::RpcMessenger::Handle local_handle) {
  DCHECK_NE(local_handle, openscreen::cast::RpcMessenger::kInvalidHandle);
  auto rpc = std::make_unique<openscreen::cast::RpcMessage>();
  rpc->set_proc(openscreen::cast::RpcMessage::RPC_DS_INITIALIZE);
  rpc->set_integer_value(local_handle);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForDemuxerStreamReadUntil(
    openscreen::cast::RpcMessenger::Handle local_handle,
    uint32_t buffers_requested) {
  DCHECK_NE(local_handle, openscreen::cast::RpcMessenger::kInvalidHandle);
  auto rpc = std::make_unique<openscreen::cast::RpcMessage>();
  rpc->set_proc(openscreen::cast::RpcMessage::RPC_DS_READUNTIL);
  auto* message = rpc->mutable_demuxerstream_readuntil_rpc();
  message->set_count(buffers_requested);
  message->set_callback_handle(local_handle);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForDemuxerStreamEnableBitstreamConverter() {
  auto rpc = std::make_unique<openscreen::cast::RpcMessage>();
  rpc->set_proc(openscreen::cast::RpcMessage::RPC_DS_ENABLEBITSTREAMCONVERTER);
  return rpc;
}

std::unique_ptr<openscreen::cast::RpcMessage>
CreateMessageForDemuxerStreamError() {
  auto rpc = std::make_unique<openscreen::cast::RpcMessage>();
  rpc->set_proc(openscreen::cast::RpcMessage::RPC_DS_ONERROR);
  return rpc;
}

}  // namespace remoting
}  // namespace cast_streaming


text:
#include "library/common/network/socket_tag_socket_option_impl.h"

#include "envoy/config/core/v3/base.pb.h"

#include "source/common/common/assert.h"
#include "source/common/common/scalar_to_byte_vector.h"

#include "library/common/jni/android_jni_utility.h"

namespace Envoy {
namespace Network {

SocketTagSocketOptionImpl::SocketTagSocketOptionImpl(uid_t uid, uint32_t traffic_stats_tag)
    : optname_(0, 0, "socket_tag"), uid_(uid), traffic_stats_tag_(traffic_stats_tag) {}

bool SocketTagSocketOptionImpl::setOption(
    Socket& socket, envoy::config::core::v3::SocketOption::SocketState state) const {
  if (state != envoy::config::core::v3::SocketOption::STATE_PREBIND) {
    return true;
  }

  // Because socket tagging happens at the socket level, not at the request level,
  // requests with different socket tags must not use the same socket. As a result
  // different socket tag socket options must end up in different socket pools.
  // This happens because different socket tag socket option generate different
  // hash keys.
  // Further, this only works for sockets which have a raw fd and will be a no-op
  // otherwise.
  int fd = socket.ioHandle().fdDoNotUse();
  tag_socket(fd, uid_, traffic_stats_tag_);
  return true;
}

void SocketTagSocketOptionImpl::hashKey(std::vector<uint8_t>& hash_key) const {
  pushScalarToByteVector(uid_, hash_key);
  pushScalarToByteVector(traffic_stats_tag_, hash_key);
}

absl::optional<Socket::Option::Details> SocketTagSocketOptionImpl::getOptionDetails(
    const Socket&, envoy::config::core::v3::SocketOption::SocketState /*state*/) const {
  if (!isSupported()) {
    return absl::nullopt;
  }

  static std::string name = "socket_tag";
  Socket::Option::Details details;
  details.name_ = optname_;
  std::vector<uint8_t> data;
  pushScalarToByteVector(uid_, data);
  pushScalarToByteVector(traffic_stats_tag_, data);
  details.value_ = std::string(reinterpret_cast<char*>(data.data()), data.size());
  return absl::make_optional(std::move(details));
}

bool SocketTagSocketOptionImpl::isSupported() const { return optname_.hasValue(); }

} // namespace Network
} // namespace Envoy


text:
package com.facebook.litho;

import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static com.facebook.litho.LithoKeyTestingUtil.getScopedComponentInfos;
import static org.assertj.core.api.Assertions.assertThat;

import android.view.View;
import com.facebook.litho.annotations.OnCreateLayout;
import com.facebook.litho.config.TempComponentsConfigurations;
import com.facebook.litho.testing.TestViewComponent;
import com.facebook.litho.testing.inlinelayoutspec.InlineLayoutSpec;
import com.facebook.litho.testing.testrunner.LithoTestRunner;
import com.facebook.litho.widget.CardClip;
import com.facebook.litho.widget.Text;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(LithoTestRunner.class)
public class LegacyStatelessComponentGlobalKeyTest {

  private ComponentContext mContext;

  @Before
  public void setup() {
    TempComponentsConfigurations.setShouldAddHostViewForRootComponent(false);
    mContext = new ComponentContext(getApplicationContext());
  }

  @Test
  public void testMultipleChildrenComponentKey() {
    final Component component = getMultipleChildrenComponent();

    int layoutSpecId = component.getTypeId();
    int nestedLayoutSpecId = layoutSpecId - 1;

    final Component column = Column.create(mContext).build();
    final int columnSpecId = column.getTypeId();

    final LithoView lithoView = getLithoView(component);
    final Map<String, List<ScopedComponentInfo>> globalKeysInfo =
        getScopedComponentInfos(lithoView);

    // Text
    final String expectedGlobalKeyText =
        ComponentKeyUtils.getKeyWithSeparatorForTest(layoutSpecId, columnSpecId, "$[Text2]");
    final ScopedComponentInfo scopedComponentInfoText = globalKeysInfo.get("Text").get(0);
    assertThat(scopedComponentInfoText.getContext().getGlobalKey())
        .isEqualTo(expectedGlobalKeyText);
    // TestViewComponent in child layout
    final String expectedGlobalKeyTestViewComponent =
        ComponentKeyUtils.getKeyWithSeparatorForTest(
            layoutSpecId, columnSpecId, nestedLayoutSpecId, columnSpecId, "$[TestViewComponent1]");
    final ScopedComponentInfo scopedComponentInfoTestViewComponent =
        globalKeysInfo.get("TestViewComponent").get(0);
    assertThat(scopedComponentInfoTestViewComponent.getContext().getGlobalKey())
        .isEqualTo(expectedGlobalKeyTestViewComponent);
    // CardClip in child
    final String expectedGlobalKeyCardClip =
        ComponentKeyUtils.getKeyWithSeparatorForTest(
            layoutSpecId,
            columnSpecId,
            nestedLayoutSpecId,
            columnSpecId,
            columnSpecId,
            "$[CardClip1]");
    final ScopedComponentInfo scopedComponentInfoCardClip = globalKeysInfo.get("CardClip").get(0);
    assertThat(scopedComponentInfoCardClip.getContext().getGlobalKey())
        .isEqualTo(expectedGlobalKeyCardClip);

    // Text in child
    final String expectedGlobalKeyTextChild =
        ComponentKeyUtils.getKeyWithSeparatorForTest(
            layoutSpecId, columnSpecId, nestedLayoutSpecId, columnSpecId, "$[Text1]");
    final ScopedComponentInfo scopedComponentInfoTextChild = globalKeysInfo.get("Text").get(1);
    assertThat(scopedComponentInfoTextChild.getContext().getGlobalKey())
        .isEqualTo(expectedGlobalKeyTextChild);

    // CardClip
    final String expectedGlobalKeyCardClip2 =
        ComponentKeyUtils.getKeyWithSeparatorForTest(
            layoutSpecId, columnSpecId, columnSpecId, "$[CardClip2]");
    final ScopedComponentInfo scopedComponentInfoCardClip2 = globalKeysInfo.get("CardClip").get(1);
    assertThat(scopedComponentInfoCardClip2.getContext().getGlobalKey())
        .isEqualTo(expectedGlobalKeyCardClip2);

    // TestViewComponent
    final String expectedGlobalKeyTestViewComponent2 =
        ComponentKeyUtils.getKeyWithSeparatorForTest(
            layoutSpecId, columnSpecId, "$[TestViewComponent2]");
    final ScopedComponentInfo scopedComponentInfoTestViewComponent2 =
        globalKeysInfo.get("TestViewComponent").get(1);
    assertThat(scopedComponentInfoTestViewComponent2.getContext().getGlobalKey())
        .isEqualTo(expectedGlobalKeyTestViewComponent2);
  }

  private LithoView getLithoView(Component component) {
    LithoView lithoView = new LithoView(mContext);
    lithoView.setComponent(component);
    lithoView.measure(
        View.MeasureSpec.makeMeasureSpec(640, View.MeasureSpec.UNSPECIFIED),
        View.MeasureSpec.makeMeasureSpec(480, View.MeasureSpec.UNSPECIFIED));
    lithoView.layout(0, 0, lithoView.getMeasuredWidth(), lithoView.getMeasuredHeight());
    return lithoView;
  }

  private static Component getMultipleChildrenComponent() {
    final int color = 0xFFFF0000;
    final Component testGlobalKeyChildComponent =
        new InlineLayoutSpec() {

          @Override
          @OnCreateLayout
          protected Component onCreateLayout(ComponentContext c) {

            return Column.create(c)
                .child(
                    TestViewComponent.create(c)
                        .widthDip(10)
                        .heightDip(10)
                        .key("[TestViewComponent1]"))
                .child(
                    Column.create(c)
                        .backgroundColor(color)
                        .child(CardClip.create(c).widthDip(10).heightDip(10).key("[CardClip1]")))
                .child(Text.create(c).text("Test").widthDip(10).heightDip(10).key("[Text1]"))
                .build();
          }
        };

    final Component testGlobalKeyChild =
        new InlineLayoutSpec() {

          @Override
          @OnCreateLayout
          protected Component onCreateLayout(ComponentContext c) {

            return Column.create(c)
                .child(Text.create(c).text("test").widthDip(10).heightDip(10).key("[Text2]"))
                .child(testGlobalKeyChildComponent)
                .child(
                    Column.create(c)
                        .backgroundColor(color)
                        .child(CardClip.create(c).widthDip(10).heightDip(10).key("[CardClip2]")))
                .child(
                    TestViewComponent.create(c)
                        .widthDip(10)
                        .heightDip(10)
                        .key("[TestViewComponent2]"))
                .build();
          }
        };

    return testGlobalKeyChild;
  }

  @After
  public void restoreConfiguration() {
    TempComponentsConfigurations.restoreShouldAddHostViewForRootComponent();
  }
}


text:
import json, logging, time
import decimal
from datetime import date, datetime
from tornado import web, gen
import tornado_cors as cors
from tornado_cors import custom_decorator

from myops2.settings import Config
import rethinkdb as r
from rethinkdb.errors import RqlRuntimeError, RqlDriverError

logger = logging.getLogger(__name__)

# handles serialization of datetime in json
#DateEncoder = lambda obj: obj.strftime("%B %d, %Y %H:%M:%S") if isinstance(obj, datetime.datetime) else None
DateEncoder = lambda obj: obj.isoformat() if isinstance(obj, datetime) else None

# support converting decimal in json
json.encoder.FLOAT_REPR = lambda o: format(o, '.2f')

# handles decimal numbers serialization in json
class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):
        if isinstance(o, decimal.Decimal):
            return (str(o) for o in [o])
        return super(DecimalEncoder, self)._iterencode(o, markers)

class Resources(cors.CorsMixin, web.RequestHandler):

    def set_default_headers(self):
        # to allow CORS
        self.set_header("Access-Control-Allow-Origin", "*")

    @gen.coroutine
    def get(self, *args):
        c = yield self.application.dbconnection

        resources = []

        cursor = yield r.table('resources').run(c)

        while (yield cursor.fetch_next()):
            item = yield cursor.next()
            resources.append(item)

        self.finish(json.dumps({"resources": resources}, cls=DecimalEncoder, default=DateEncoder))

    @web.asynchronous
    def post(self):
        pass

class Job(cors.CorsMixin, web.RequestHandler):

    def initialize(self):
        self.dbconnection = self.application.dbconnection

    def set_default_headers(self):
        # to allow CORS
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Content-Type", "application/json")

    @gen.coroutine
    def get(self, id=None):
        jobs = []
        c = yield self.dbconnection

        if id is not None:
            logger.info("GET JOB " % (id))
            ret = yield r.table('jobs').get(id).run(c)
            jobs.append(ret)
        else:
            logger.info("GET ALL JOBS")
            cursor = yield r.table('jobs').run(c)

            while (yield cursor.fetch_next()):
                item = yield cursor.next()
                jobs.append(item)

        self.finish(json.dumps({"jobs": jobs}, cls=DecimalEncoder, default=DateEncoder))

    @gen.coroutine
    def post(self, *args):
        #post body must be a list
        #jobs = []
        #jobs = tornado.escape.json_decode(self.request.body)
        c = yield self.dbconnection

        jobs = json.loads(self.request.body)

        logger.info("Received %s" % (jobs,))

        ts = time.time()
        # Adding additional info to the json
        for data in jobs:
            data["jobstatus"]       = "waiting"
            data["message"]         = "waiting to be executed"
            data["created"]         = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
            data["started"]         = ""
            data["completed"]       = ""
            data["returnstatus"]    = ""
            data["stdout"]          = ""
            data["stderr"]          = ""

            json.dumps(data)

        yield r.table('jobs').run(c)

        rows = yield r.table("jobs").insert(jobs).run(c)

        ids =[]
        # getting the generated keys from the DB
        for key in rows['generated_keys']:
            ids.append(key)

        self.finish(json.dumps({"id": ids}))


text:
namespace ArangoDB.Velocypack.Exceptions
{
    /// <author>Mark - mark at arangodb.com</author>
    public class VPackNeedAttributeTranslatorException : VPackException
    {
        private const long serialVersionUID = -676583112112943083L;
    }
}


text:
layout: null
section-type: contact
title: Contact
---
## Contact

Probably the best way of reaching me is through Twitter (iamjoona).


text:
package org.wso2.carbon.identity.data.publisher.authentication.analytics.login;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.core.util.AnonymousSessionUtil;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.data.publisher.application.authentication.AuthPublisherConstants;
import org.wso2.carbon.identity.data.publisher.application.authentication.AuthnDataPublisherUtils;
import org.wso2.carbon.identity.data.publisher.authentication.analytics.login.internal.AnalyticsLoginDataPublishDataHolder;
import org.wso2.carbon.identity.data.publisher.authentication.analytics.login.model.AuthenticationData;
import org.wso2.carbon.identity.event.IdentityEventConstants;
import org.wso2.carbon.identity.event.IdentityEventException;
import org.wso2.carbon.identity.event.event.Event;
import org.wso2.carbon.identity.event.handler.AbstractEventHandler;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;

import java.util.*;

/**
 * Publish authentication login data to analytics server.
 */
public class AnalyticsLoginDataPublishHandler extends AbstractEventHandler {

    private static final Log LOG = LogFactory.getLog(AnalyticsLoginDataPublishHandler.class);

    @Override
    public String getName() {

        return AnalyticsLoginDataPublishConstants.ANALYTICS_LOGIN_PUBLISHER_NAME;
    }

    @Override
    public void handleEvent(Event event) throws IdentityEventException {

        boolean isEnabled = isAnalyticsLoginDataPublishingEnabled(event);

        if (!isEnabled) {
            return;
        }

        if (IdentityEventConstants.EventName.AUTHENTICATION_STEP_SUCCESS.name().equals(event.getEventName()) ||
                IdentityEventConstants.EventName.AUTHENTICATION_STEP_FAILURE.name().equals(event.getEventName())) {
            AuthenticationData authenticationData = AnalyticsLoginDataPublisherUtils.buildAuthnDataForAuthnStep(event);
            publishAuthenticationData(authenticationData);
        } else if (IdentityEventConstants.EventName.AUTHENTICATION_SUCCESS.name().equals(event.getEventName()) ||
                IdentityEventConstants.EventName.AUTHENTICATION_FAILURE.name().equals(event.getEventName())) {
            AuthenticationData authenticationData = AnalyticsLoginDataPublisherUtils.
                    buildAuthnDataForAuthentication(event);
            publishAuthenticationData(authenticationData);
        } else {
            LOG.error("Event " + event.getEventName() + " cannot be handled");
        }
    }

    protected void publishAuthenticationData(AuthenticationData authenticationData) {

        try {
            Object[] payloadData = populatePayloadData(authenticationData);
            publishEvent(payloadData, authenticationData);
        } catch (IdentityRuntimeException e) {
            if (LOG.isDebugEnabled()) {
                LOG.error("Error while publishing authentication data", e);
            }
        }
    }

    protected Object[] populatePayloadData(AuthenticationData authenticationData) {

        String roleList = null;
        if (FrameworkConstants.LOCAL_IDP_NAME.equalsIgnoreCase(authenticationData.getIdentityProviderType())) {
            roleList = getCommaSeparatedUserRoles(authenticationData.getUserStoreDomain() + "/" +
                    authenticationData.getUsername(), authenticationData.getTenantDomain());
        } else if (StringUtils.isNotEmpty(authenticationData.getLocalUsername())) {
            roleList = getCommaSeparatedUserRoles(authenticationData.getUserStoreDomain() + "/" +
                    authenticationData.getLocalUsername(), authenticationData.getTenantDomain());
        }

        Object[] payloadData = new Object[23];
        payloadData[0] = authenticationData.getContextId();
        payloadData[1] = authenticationData.getEventId();
        payloadData[2] = authenticationData.getEventType();
        payloadData[3] = authenticationData.isAuthnSuccess();
        payloadData[4] = AuthnDataPublisherUtils.replaceIfNotAvailable(
                AuthPublisherConstants.CONFIG_PREFIX + AuthPublisherConstants.USERNAME,
                authenticationData.getUsername());
        payloadData[5] = AuthnDataPublisherUtils.replaceIfNotAvailable(
                AuthPublisherConstants.CONFIG_PREFIX + AuthPublisherConstants.USERNAME,
                authenticationData.getLocalUsername());
        payloadData[6] = AuthnDataPublisherUtils.replaceIfNotAvailable(
                AuthPublisherConstants.CONFIG_PREFIX + AuthPublisherConstants.USER_STORE_DOMAIN,
                authenticationData.getUserStoreDomain());
        payloadData[7] = authenticationData.getTenantDomain();
        payloadData[8] = authenticationData.getRemoteIp();
        payloadData[9] = AuthPublisherConstants.NOT_AVAILABLE;
        payloadData[10] = authenticationData.getInboundProtocol();
        payloadData[11] = AuthnDataPublisherUtils.replaceIfNotAvailable(
                AuthPublisherConstants.CONFIG_PREFIX + AuthPublisherConstants.SERVICE_PROVIDER,
                authenticationData.getServiceProvider());
        payloadData[12] = authenticationData.isRememberMe();
        payloadData[13] = authenticationData.isForcedAuthn();
        payloadData[14] = authenticationData.isPassive();
        payloadData[15] = AuthnDataPublisherUtils.replaceIfNotAvailable(
                AuthPublisherConstants.CONFIG_PREFIX + AuthPublisherConstants.ROLES, roleList);
        payloadData[16] = String.valueOf(authenticationData.getStepNo());
        payloadData[17] = AuthnDataPublisherUtils.replaceIfNotAvailable(
                AuthPublisherConstants.CONFIG_PREFIX + AuthPublisherConstants.IDENTITY_PROVIDER,
                authenticationData.getIdentityProvider());
        payloadData[18] = authenticationData.isSuccess();
        payloadData[19] = authenticationData.getAuthenticator();
        payloadData[20] = authenticationData.isInitialLogin();
        payloadData[21] = authenticationData.getIdentityProviderType();
        payloadData[22] = System.currentTimeMillis();

        if (LOG.isDebugEnabled()) {
            LOG.debug("The created payload: " + Arrays.asList(payloadData));
        }

        return payloadData;
    }

    protected void publishEvent(Object[] payloadData, AuthenticationData authenticationData) {

        String[] publishingDomains = (String[]) authenticationData
                .getParameter(AnalyticsLoginDataPublishConstants.TENANT_DOMAIN_NAMES);
        if (publishingDomains != null && publishingDomains.length > 0) {
            publishingDomains = processPublishingDomains(publishingDomains, authenticationData.getTenantDomain());

            try {
                FrameworkUtils.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
                for (String publishingDomain : publishingDomains) {
                    Object[] metadataArray = AuthnDataPublisherUtils.getMetaDataArray(publishingDomain);
                    payloadData[7] = publishingDomain;
                    payloadData[1] = UUID.randomUUID().toString();

                    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons
                            .Event(AnalyticsLoginDataPublishConstants.AUTHN_DATA_STREAM_NAME,
                            System.currentTimeMillis(), metadataArray, null, payloadData);
                    AnalyticsLoginDataPublishDataHolder.getInstance().getPublisherService().publish(event);
                    if (LOG.isDebugEnabled() && event != null) {
                        LOG.debug("Sending out to publishing domain:" + publishingDomain + " \n event : "
                                + event.toString());
                    }
                }
            } finally {
                FrameworkUtils.endTenantFlow();
            }
        }
    }

    private String getCommaSeparatedUserRoles(String userName, String tenantDomain) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("Retrieving roles for user " + userName + ", tenant domain " + tenantDomain);
        }
        if (tenantDomain == null || userName == null) {
            return StringUtils.EMPTY;
        }

        RegistryService registryService = AnalyticsLoginDataPublishDataHolder.getInstance().getRegistryService();
        RealmService realmService = AnalyticsLoginDataPublishDataHolder.getInstance().getRealmService();

        UserRealm realm = null;
        UserStoreManager userstore = null;

        try {
            realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                    realmService, tenantDomain);
            if (realm != null) {
                userstore = realm.getUserStoreManager();
                if (userstore.isExistingUser(userName)) {
                    String[] newRoles = userstore.getRoleListOfUser(userName);
                    StringBuilder sb = new StringBuilder();
                    List<String> externalRoles = AuthnDataPublisherUtils.filterRoles(newRoles);
                    for (String role : externalRoles) {
                        sb.append(",").append(role);
                    }
                    if (sb.length() > 0) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Returning roles, " + sb.substring(1));
                        }
                        return sb.substring(1); //remove the first comma
                    }
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No realm found. for tenant domain : " + tenantDomain + ". Hence no roles added");
                }
            }
        } catch (CarbonException e) {
            LOG.error("Error when getting realm for " + userName + "@" + tenantDomain, e);
        } catch (UserStoreException e) {
            LOG.error("Error when getting user store for " + userName + "@" + tenantDomain, e);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("No roles found. Returning empty string");
        }
        return StringUtils.EMPTY;
    }

    private boolean isAnalyticsLoginDataPublishingEnabled(Event event) throws IdentityEventException {

        if (this.configs.getModuleProperties() != null) {
            String handlerEnabled = this.configs.getModuleProperties()
                    .getProperty(AnalyticsLoginDataPublishConstants.ANALYTICS_LOGIN_DATA_PUBLISHER_ENABLED);
            return Boolean.parseBoolean(handlerEnabled);
        }

        return false;
    }

    private boolean isMultipleEventPublishingForSaasAppsEnabled() {

        if (this.configs.getModuleProperties() != null) {
            String multipleEventPublishingForSaasAppsEnabled = this.configs.getModuleProperties().
                    getProperty(AnalyticsLoginDataPublishConstants.
                            ANALYTICS_LOGIN_DATA_PUBLISHER_ENABLE_MULTIPLE_EVENT_PUBLISHING_FOR_SAAS_APPS);
            if (StringUtils.isNotBlank(multipleEventPublishingForSaasAppsEnabled)) {
                return Boolean.parseBoolean(multipleEventPublishingForSaasAppsEnabled);
            }
        }
        // If Multiple Event Publishing For SaaS Apps property is not defined, return true as default value.
        return true;
    }

    /**
     * Process publishing tenant domains according to config `enableMultipleEventPublishingForSaasApps`.
     * If multiple event publishing disabled for the SaaS apps, return only SP tenant domain as publishing domain.
     *
     * @param publishingDomains Publishing tenant domains array.
     * @param userTenantDomain  User tenant domain.
     * @return Processed publishing tenant domains.
     */
    private String[] processPublishingDomains(String[] publishingDomains, String userTenantDomain) {

        if (!isMultipleEventPublishingForSaasAppsEnabled() && ArrayUtils.getLength(publishingDomains) == 2 &&
                StringUtils.isNotBlank(userTenantDomain)) {
            // If we have two publishing domains one is user tenant domain and other one is sp tenant domain.
            String spTenantDomain;
            if (userTenantDomain.equalsIgnoreCase(publishingDomains[0])) {
                spTenantDomain = publishingDomains[1];
            } else {
                spTenantDomain = publishingDomains[0];
            }
            // If multiple event publishing disabled for the SaaS apps, publishing events only for the SP tenant domain.
            return new String[]{spTenantDomain};
        }
        return publishingDomains;
    }
}


text:
USING_NS_CC;

#pragma mark - Public Interface

ActionDiceSprite* ActionDiceSprite::createWithDice(Dice *dice) {
  auto sprite = new (std::nothrow) ActionDiceSprite();
  if (sprite && sprite->initWithDice(dice)) {
    sprite->autorelease();
  } else {
    CC_SAFE_DELETE(sprite);
  }

  return sprite;
}

bool ActionDiceSprite::initWithDice(Dice *dice) {
  if (!DiceSprite::initWithDice(dice)) {
    return false;
  }

  this->_setupTouchListener();

  return true;
}

void ActionDiceSprite::dockOnNode(Node* node) {
  this->retain();
  this->removeFromParent();
  node->addChild(this);
  this->setPosition(node->convertToNodeSpace(this->getPosition()));
  this->release();

  auto position = PositionUtil::centerOfNode(node);
  auto scale = ScaleTo::create(0.1, 0.58);
  auto move = MoveTo::create(0.1, position);
  this->runAction(Spawn::create(move, scale, NULL));

  this->getDice()->setDocked(true);
}

void ActionDiceSprite::undock(Layer* layer) {
  auto parent = this->getParent();

  this->retain();
  this->removeFromParent();
  layer->addChild(this);
  this->setPosition(parent->convertToWorldSpace(this->getPosition()));
  this->release();
}

void ActionDiceSprite::startDragging() {
  this->setLocalZOrder(this->getLocalZOrder() + DRAG_Z_ORDER_DELTA);
  this->getDice()->setDocked(false);
  this->runAction(ScaleTo::create(0.2, 0.58));
}

void ActionDiceSprite::restoreOriginalPosition() {
  auto move = MoveTo::create(0.2, this->getOriginalPosition());
  auto scale = ScaleTo::create(0.2, 1);

  this->runAction(Spawn::create(move, scale, NULL));
}

#pragma mark - Private Interface

void ActionDiceSprite::_setupTouchListener() {
  auto touchListener = EventListenerTouchOneByOne::create();
  touchListener->setSwallowTouches(true);
  touchListener->onTouchBegan = CC_CALLBACK_2(ActionDiceSprite::_onTouchBegan, this);
  touchListener->onTouchMoved = CC_CALLBACK_2(ActionDiceSprite::_onTouchMoved, this);
  touchListener->onTouchEnded = CC_CALLBACK_2(ActionDiceSprite::_onTouchEnded, this);

  auto dispatcher = Director::getInstance()->getEventDispatcher();
  dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
}

#pragma mark Touch Events

bool ActionDiceSprite::_onTouchBegan(Touch* touch, Event* event) {
  auto target = event->getCurrentTarget();
  auto layer = target->getParent();

  auto bounds = target->getBoundingBox();
  auto touchLocation = layer->convertTouchToNodeSpace(touch);

  auto touchedOnSprite = bounds.containsPoint(touchLocation) &&
      !(IS(this->getParent(), MagicDiceEffectLayer));

  if (touchedOnSprite &&
      IS(this->getDice()->getState(), ActionDiceStateRolled)) {
    auto data = ActionDiceDragData::create();
    data->setSprite(this);
    data->setTouch(touch);

    auto dispatcher = Director::getInstance()->getEventDispatcher();
    dispatcher->dispatchCustomEvent(EVT_ACTION_DICE_DRAG_STARTED, data);
  }

  return touchedOnSprite;
}

void ActionDiceSprite::_onTouchMoved(Touch* touch, Event* event) {
  if (IS(this->getDice()->getState(), ActionDiceStateRolled)) {
    auto data = ActionDiceDragData::create();
    data->setSprite(this);
    data->setTouch(touch);

    auto dispatcher = Director::getInstance()->getEventDispatcher();
    dispatcher->dispatchCustomEvent(EVT_ACTION_DICE_DRAG_MOVED, data);
  }
}

void ActionDiceSprite::_onTouchEnded(Touch* touch, Event* event) {
  auto target = event->getCurrentTarget();
  auto layer = target->getParent();

  auto bounds = target->getBoundingBox();
  auto touchLocation = layer->convertTouchToNodeSpace(touch);

  auto touchInSprite = bounds.containsPoint(touchLocation);

  if (touchInSprite && this->getDice()->canChangeState()) {
    this->getDice()->changeState();
  }

  if (IS(this->getDice()->getState(), ActionDiceStateRolled)) {
    auto data = ActionDiceDragData::create();
    data->setSprite(this);
    data->setTouch(touch);

    auto dispatcher = Director::getInstance()->getEventDispatcher();
    dispatcher->dispatchCustomEvent(EVT_ACTION_DICE_DRAG_ENDED, data);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">
    <TextView
        android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:gravity="center_horizontal"
    	android:textSize="18sp"
    	android:text="安徽-沃运维"/>
    <LinearLayout
        android:layout_width="fill_parent"
    	android:layout_height="wrap_content">
        <TextView
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:textSize="16sp"
    	android:text="版本号:"/>
        <TextView
            android:id="@+id/tv_version"
        android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:textSize="16sp"/>
    </LinearLayout>

        <TextView
        android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:textSize="16sp"
    	android:text="版权所有:科大国创"/>

    <LinearLayout
        android:layout_width="fill_parent"
    	android:layout_height="wrap_content">
        <TextView
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:textSize="16sp"
    	android:text="软件说明:"/>
        <TextView
        android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:textSize="16sp"
    	android:text="本软件仅适用于安徽联通人员使用,主要用于综合调度。"/>
    </LinearLayout>
</LinearLayout>


text:
#ifndef _ABSTRACT_DEMO_H_
#define _ABSTRACT_DEMO_H_

class AbstractDemo
{
public:
    virtual init() = 0;
    virtual update() = 0;
    virtual render() = 0;
    virtual shutdown() = 0;
}

#endif /* _ABSTRACT_DEMO_H_ */


text:
package beanstalk

import (
	"errors"
)

// Characters allowed in a name in the beanstalkd protocol.
const NameChars = `\-+/;.$_()0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`

// NameError indicates that a name was malformed and the specific error
// describing how.
type NameError struct {
	Name string
	Err  error
}

func (e NameError) Error() string {
	return e.Err.Error() + ": " + e.Name
}

// Name format errors. The Err field of NameError contains one of these.
var (
	ErrEmpty   = errors.New("name is empty")
	ErrBadChar = errors.New("name has bad char") // contains a character not in NameChars
	ErrTooLong = errors.New("name is too long")
)

func checkName(s string) error {
	switch {
	case len(s) == 0:
		return NameError{s, ErrEmpty}
	case len(s) >= 200:
		return NameError{s, ErrTooLong}
	case !containsOnly(s, NameChars):
		return NameError{s, ErrBadChar}
	}
	return nil
}

func containsOnly(s, chars string) bool {
outer:
	for _, c := range s {
		for _, m := range chars {
			if c == m {
				continue outer
			}
		}
		return false
	}
	return true
}