text:
module.exports = {
    toObject        : toObject,
    toArray         : toArray,
    toColumnArray   : toColumnArray,
    toSchemaObject  : toSchemaObject,
    toCSV           : toCSV
}

function toColumnArray(data, opts){

    opts = opts || { };

    var delimiter   = (opts.delimiter || ',');
    var quote       = _getQuote(opts.quote);
    var content     = data;
    var headers     = null;

    if(typeof(content) !== "string"){
        throw new Error("Invalid input, input data should be a string");
    }

    content     = content.split(/[\n\r]+/ig);

    if(typeof(opts.headers) === "string"){
        headers = opts.headers.split(/[\n\r]+/ig);
        headers = quote ?
                _convertArray(headers.shift(), delimiter, quote) :
                headers.shift().split(delimiter);
    }else{
        headers = quote ?
                _convertArray(content.shift(), delimiter, quote) :
                content.shift().split(delimiter);
    }

    var hashData    = { };

    headers.forEach(function(item){
        hashData[item] = [];
    });

    content.forEach(function(item){
        if(item){
            item = quote ?
                  _convertArray(item, delimiter, quote) :
                  item.split(delimiter);
            item.forEach(function(val, index){
                hashData[headers[index]].push(_trimQuote(val));
            });
        }
    });

    return hashData;
}

function toObject(data, opts){

    opts = opts || { };

    var delimiter   = (opts.delimiter || ',');
    var quote       = _getQuote(opts.quote);
    var content     = data;
    var headers     = null;

    if(typeof(content) !== "string"){
        throw new Error("Invalid input, input data should be a string");
    }

    content = content.split(/[\n\r]+/ig);

    if(typeof(opts.headers) === "string"){
        headers = opts.headers.split(/[\n\r]+/ig);
        headers = quote ?
                _convertArray(headers.shift(), delimiter, quote) :
                headers.shift().split(delimiter);
    }else{
        headers = quote ?
                _convertArray(content.shift(), delimiter, quote) :
                content.shift().split(delimiter);
    }

    var hashData = [ ];
    content.forEach(function(item){
        if(item){
          item = quote ?
                _convertArray(item, delimiter, quote) :
                item.split(delimiter);
          var hashItem = { };
          headers.forEach(function(headerItem, index){
              hashItem[headerItem] = _trimQuote(item[index]);
          });
          hashData.push(hashItem);
        }
    });
    return hashData;
}

function toSchemaObject(data, opts){

    opts = opts || { };

    var delimiter   = (opts.delimiter || ',');
    var quote       = _getQuote(opts.quote);
    var content     = data;
    var headers     = null;
    if(typeof(content) !== "string"){
        throw new Error("Invalid input, input should be a string");
    }

    content         = content.split(/[\n\r]+/ig);

    if(typeof(opts.headers) === "string"){
        headers = opts.headers.split(/[\n\r]+/ig);
        headers = quote ?
                _convertArray(headers.shift(), delimiter, quote) :
                headers.shift().split(delimiter);
    }else{
        headers = quote ?
                _convertArray(content.shift(), delimiter, quote) :
                content.shift().split(delimiter);
    }

    var hashData    = [ ];

    content.forEach(function(item){
        if(item){
          item = quote ?
                _convertArray(item, delimiter, quote) :
                item.split(delimiter);
            var schemaObject = {};
            item.forEach(function(val, index){
                _putDataInSchema(headers[index], val, schemaObject , delimiter, quote);
            });
            hashData.push(schemaObject);
        }
    });

    return hashData;
}

function toArray(data, opts){

    opts = opts || { };

    var delimiter   = (opts.delimiter || ',');
    var quote       = _getQuote(opts.quote);
    var content     = data;

    if(typeof(content) !== "string"){
        throw new Error("Invalid input, input data should be a string");
    }

    content = content.split(/[\n\r]+/ig);
    var arrayData = [ ];
    content.forEach(function(item){
        if(item){
            item = quote ?
                _convertArray(item, delimiter, quote) :
                item.split(delimiter);

            item = item.map(function(cItem){
                return _trimQuote(cItem);
            });
            arrayData.push(item);
        }
    });
    return arrayData;
}

function _getQuote(q){
  if(typeof(q) === "string"){
    return q;
  }else if(q === true){
    return '"';
  }
  return null;
}

function _dataType(arg) {
    if (arg === null) {
        return 'null';
    }
    else if (arg && (arg.nodeType === 1 || arg.nodeType === 9)) {
        return 'element';
    }
    var type = (Object.prototype.toString.call(arg)).match(/\[object (.*?)\]/)[1].toLowerCase();
    if (type === 'number') {
        if (isNaN(arg)) {
            return 'nan';
        }
        if (!isFinite(arg)) {
            return 'infinity';
        }
    }
    return type;
}

function toCSV(data, opts){

    opts                = (opts || { });
    opts.delimiter      = (opts.delimiter || ',');
    opts.wrap           = (opts.wrap || '');
    opts.arrayDenote    = (opts.arrayDenote && String(opts.arrayDenote).trim() ? opts.arrayDenote : '[]');
    opts.objectDenote   = (opts.objectDenote && String(opts.objectDenote).trim() ? opts.objectDenote : '.');
    opts.detailedOutput = (typeof(opts.detailedOutput) !== "boolean" ? true : opts.detailedOutput);
    opts.headers        = String(opts.headers).toLowerCase();
    var csvJSON         = { };
    var csvData         = "";

    if(!opts.headers.match(/none|full|relative|key/)){
      opts.headers = 'full';
    }else{
      opts.headers = opts.headers.match(/none|full|relative|key/)[0];
    }

    if(opts.wrap === true){
        opts.wrap = '"';
    }

    if(typeof(data) === "string"){
        data = JSON.parse(data);
    }

    _toCsv(data, csvJSON, "", 0, opts);

    var headers = _getHeaders(opts.headers, csvJSON, opts);

    if(headers){
      if(opts.wrap){
        headers = headers.map(function(item){
          return opts.wrap + item + opts.wrap;
        });
      }
      csvData = headers.join(opts.delimiter);
    }

    var bigArrayLen = _getBigArrayLength(csvJSON);
    var keys        = Object.keys(csvJSON);
    var row         = [ ];

    var replaceNewLinePattern = /\n|\r/g;
    if(!opts.wrap){
        replaceNewLinePattern = new RegExp('\n|\r|' + opts.delimiter, 'g');
    }

    for(var i = 0; i < bigArrayLen; i++){
        row = [ ];
        for(var j = 0; j < keys.length; j++){
            if(csvJSON[keys[j]][i]){
                csvJSON[keys[j]][i] = csvJSON[keys[j]][i].replace(replaceNewLinePattern, '\t');
                if(opts.wrap){
                    csvJSON[keys[j]][i] = opts.wrap + csvJSON[keys[j]][i] + opts.wrap;
                }
                row[row.length] = csvJSON[keys[j]][i];
            }else{
                row[row.length] = "";
            }
        }
      csvData += '\n' + row.join(opts.delimiter);
    }
    return csvData;
}

function _toCsv(data, table, parent, row, opt){
    if(_dataType(data) === 'undefined'){
        return _putData('', table, parent, row, opt);
    }else if(_dataType(data) === 'null'){
        return _putData('null', table, parent, row, opt);
    }else if(Array.isArray(data)){
        return _arrayToCsv(data, table, parent, row, opt);
    }else if(typeof(data) === "object"){
        return _objectToCsv(data, table, parent, row, opt);
    }else{
        return _putData(String(data), table, parent, row, opt);
    }
}

function _putData(data, table, parent, row, opt){
  if(!table || !table[parent]){
      table[parent] = [ ];
  }
  if(row < table[parent].length){
    row = table[parent].length;
  }
  table[parent][row] = data;
  return table;
}

function _arrayToCsv(data, table, parent, row, opt){
    if(_doesNotContainsObjectAndArray(data)){
      return _putData(data.join(';'), table, parent + opt.arrayDenote, row, opt);
    }
    data.forEach(function(item, index){
        return _toCsv(item, table, parent + opt.arrayDenote, index, opt);
    });
}

function _doesNotContainsObjectAndArray(array){
  return array.every(function(item){
        var datatype = _dataType(item);
        if(!datatype.match(/array|object/)){
          return true;
        }
        return false;
  });
}

function _objectToCsv(data, table, parent, row, opt){
  Object.keys(data).forEach(function(item){
      return _toCsv(data[item], table, parent + opt.objectDenote + item, row, opt);
  });
}

function _getHeaders(headerType, table, opt){
  var keyMatchPattern       = /([^\[\]\.]+)$/;
  var relativeMatchPattern  = /\[\]\.?([^\[\]]+)$/;
  switch(headerType){
    case "none":
      return null;
    case "full":
      return Object.keys(table);
    case "key":
      return Object.keys(table).map(function(header){
        var head = header.match(keyMatchPattern);
        if(head && head.length === 2){
          return head[1];
        }
        return header;
      });
    case "relative":
      return Object.keys(table).map(function(header){
        var head = header.match(relativeMatchPattern);
        if(head && head.length === 2){
          return head[1];
        }
        return header;
      });
  }
}

function _getBigArrayLength(table){
  var len = 0;
  Object.keys(table).forEach(function(item){
      if(Array.isArray(table[item]) && table[item].length > len){
        len = table[item].length;
      }
  });
  return len;
}

function _putDataInSchema(header, item, schema, delimiter, quote){
    var match = header.match(/\[*[\d]\]\.(\w+)|\.|\[\]|\[(.)\]|-|\+/ig);
    var headerName, currentPoint;
    if(match){
        var testMatch = match[0];
        if(match.indexOf('-') !== -1){
            return true;
        }else if(match.indexOf('.') !== -1){
            var headParts = header.split('.');
            currentPoint = headParts.shift();
            schema[currentPoint] = schema[currentPoint] || {};
            _putDataInSchema(headParts.join('.'), item, schema[currentPoint], delimiter, quote);
        }else if(match.indexOf('[]') !== -1){
            headerName = header.replace(/\[\]/ig,'');
            if(!schema[headerName]){
            schema[headerName] = [];
            }
            schema[headerName].push(item);
        }else if(/\[*[\d]\]\.(\w+)/.test(testMatch)){
            headerName = header.split('[').shift();
            var index = parseInt(testMatch.match(/\[(.)\]/).pop(),10);
            currentPoint = header.split('.').pop();
            schema[headerName] = schema[headerName] || [];
            schema[headerName][index] = schema[headerName][index] || {};
            schema[headerName][index][currentPoint] = item;
        }else if(/\[(.)\]/.test(testMatch)){
            var delimiter = testMatch.match(/\[(.)\]/).pop();
            headerName = header.replace(/\[(.)\]/ig,'');
            schema[headerName] = _convertArray(item, delimiter, quote);
        }else if(match.indexOf('+') !== -1){
            headerName = header.replace(/\+/ig,"");
            schema[headerName] = Number(item);
        }
    }else{
        schema[header] = _trimQuote(item);
    }
    return schema ;
}

function _trimQuote(str){
    if(str){
        return String(str).trim().replace(/^["|'](.*)["|']$/, '$1');
    }
    return "";
}

function _convertArray(str, delimiter, quote) {
    if(quote && str.indexOf(quote) !== -1){
      return _csvToArray(str, delimiter, quote);
    }
    var output = [];
    var arr = str.split(delimiter);
    arr.forEach(function(val) {
        var trimmed = val.trim();
        output.push(trimmed);
    });
    return output;
}

function _csvToArray(text, delimit, quote) {

    delimit = delimit || ",";
    quote   = quote || '"';

    var value = new RegExp("(?!\\s*$)\\s*(?:" +  quote + "([^" +  quote + "\\\\]*(?:\\\\[\\S\\s][^" +  quote + "\\\\]*)*)" +  quote + "|([^" +  delimit  +  quote + "\\s\\\\]*(?:\\s+[^" +  delimit  +  quote + "\\s\\\\]+)*))\\s*(?:" +  delimit + "|$)", "g");

    var a = [ ];

    text.replace(value,
        function(m0, m1, m2) {
            if(m1 !== undefined){
                a.push(m1.replace(/\\'/g, "'"));
            }else if(m2 !== undefined){
                a.push(m2);
            }
            return '';
        }
    );

    if (/,\s*$/.test(text)){
        a.push('');
    }
    return a;
}


text:
package com.mtramin.rxfingerprint;

/**
 * Logger for RxFingerprint to support custom logging behavior
 */
public interface RxFingerprintLogger {

	/**
	 * Log a warning message
	 *
	 * @param message
	 */
	void warn(String message);

	/**
	 * Log an error message
	 *
	 * @param message
	 */
	void error(String message, Throwable throwable);
}

redpajama_set_name: RedPajamaGithub


text:
package com.exemplo.luciana.catalogofilmes;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.exemplo.luciana.catalogofilmes.model.Filme;
import com.exemplo.luciana.catalogofilmes.services.ImageService;

/**
 * Created by Luciana on 27/09/2015.
 */
public class DetailsActivity extends Activity {

    private TextView TextNomeFilme;
    private TextView TextDiretorFilme;
    private TextView TextLancamentoFilme;
    private TextView TextAtoresFilme;
    private TextView TextGeneroFilme;
    private TextView TextNacionalidadeFilme;
    private ImageView ImgFilme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.details_activity);
        Intent intent = getIntent();

        Filme filme = (Filme) intent.getSerializableExtra("filme");

        TextNomeFilme = (TextView) findViewById(R.id.nome_filme);
        TextDiretorFilme = (TextView) findViewById(R.id.diretor_filme);
        TextLancamentoFilme = (TextView) findViewById(R.id.lancamento_filme);
        TextAtoresFilme = (TextView) findViewById(R.id.atores_filme);
        TextGeneroFilme = (TextView) findViewById(R.id.genero_filme);
        TextNacionalidadeFilme = (TextView) findViewById(R.id.nacionalidade_filme);

        ImgFilme = (ImageView)findViewById(R.id.img_filme);

        TextNomeFilme.setText(filme.getNome());
        TextDiretorFilme.setText(filme.getDiretor());
        TextLancamentoFilme.setText(filme.getLancamento());
        TextAtoresFilme.setText(filme.getAtores());
        TextGeneroFilme.setText(filme.getGenero());
        TextNacionalidadeFilme.setText(filme.getNacionalidade());
        new ImageService(ImgFilme,this).execute(filme.getImage());
    }

    public void locateCines(View v){
        Intent intent = new Intent(this, CinemasOnMapsActivity.class);
        startActivity(intent);
    }
}


text:
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System;

public class Goal : MonoBehaviour {

    public int team;
    public bool fireConfetti;
    private ParticleSystem[] particleSystems;

    void Start()
    {
        particleSystems = GetComponentsInChildren<ParticleSystem>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Ball"))
        {
            Game.instance.Goal(team);
            if (fireConfetti)
                FireConfetti();
        }
    }

    void FireConfetti()
    {
        foreach (var ps in particleSystems)
        {
            ps.Play();
        }
    }

}


text:
                        类型

                            <button class="btn btn-default" ng-click="me.add()">
                                 添加
                            </button>

                        <colgroup>

                            <col />
                            <col width="64px" />
                        </colgroup>

                            {{row.rmtypename}}

                                    <button class="btn btn-default" ng-click="me.edit(row.rmtypeid)">

                                    </button>
                                    <button class="btn btn-danger" ng-click="me.drop(row.rmtypeid)">

                                    </button>

                        明细

                            房类信息

                                编号:

                                    {{me.current.rmtypeid}}

                                名称:

                                    {{me.current.rmtypename}}

                            电源信号


text:
import React from "react";
import { shallow } from "enzyme";
import DataDisplay from "./DataDisplay";

describe("DataDisplay", () => {
  it("matches snapshot when table is false", () => {
    const aDataDisplay = shallow(<DataDisplay table={false} />);
    expect(aDataDisplay).toMatchSnapshot();
  });
  it("matches snapshot when table is true", () => {
    const aDataDisplay = shallow(<DataDisplay table={true} />);
    expect(aDataDisplay).toMatchSnapshot();
  });
});


text:
/**
 * @fileoverview Functions for injecting Blockly into a web page.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.inject');

goog.require('Blockly.Css');
goog.require('Blockly.WorkspaceSvg');
goog.require('goog.dom');
goog.require('goog.ui.Component');
goog.require('goog.userAgent');

/**
 * Inject a Blockly editor into the specified container element (usually a div).
 * @param {!Element|string} container Containing element or its ID.
 * @param {Object} opt_options Optional dictionary of options.
 * @return {!Blockly.Workspace} Newly created main workspace.
 */
Blockly.inject = function(container, opt_options) {
  if (goog.isString(container)) {
    container = document.getElementById(container);
  }
  // Verify that the container is in document.
  if (!goog.dom.contains(document, container)) {
    throw 'Error: container is not in current document.';
  }
  var options = Blockly.parseOptions_(opt_options || {});
  var workspace;
  var startUi = function() {
    var svg = Blockly.createDom_(container, options);
    workspace = Blockly.createMainWorkspace_(svg, options);
    Blockly.init_(workspace);
    workspace.markFocused();
    Blockly.bindEvent_(svg, 'focus', workspace, workspace.markFocused);
  };
  if (options.enableRealtime) {
    var realtimeElement = document.getElementById('realtime');
    if (realtimeElement) {
      realtimeElement.style.display = 'block';
    }
    Blockly.Realtime.startRealtime(startUi, container, options.realtimeOptions);
  } else {
    startUi();
  }
  return workspace;
};

/**
 * Parse the provided toolbox tree into a consistent DOM format.
 * @param {Node|string} tree DOM tree of blocks, or text representation of same.
 * @return {Node} DOM tree of blocks or null.
 * @private
 */
Blockly.parseToolboxTree_ = function(tree) {
  if (tree) {
    if (typeof tree != 'string' && typeof XSLTProcessor == 'undefined') {
      // In this case the tree will not have been properly built by the
      // browser. The HTML will be contained in the element, but it will
      // not have the proper DOM structure since the browser doesn't support
      // XSLTProcessor (XML -> HTML). This is the case in IE 9+.
      tree = tree.outerHTML;
    }
    if (typeof tree == 'string') {
      tree = Blockly.Xml.textToDom(tree);
    }
  } else {
    tree = null;
  }
  return tree;
};

/**
 * Configure Blockly to behave according to a set of options.
 * @param {!Object} options Dictionary of options.  Specification:
 *   https://developers.google.com/blockly/installation/overview#configuration
 * @return {!Object} Dictionary of normalized options.
 * @private
 */
Blockly.parseOptions_ = function(options) {
  var readOnly = !!options['readOnly'];
  if (readOnly) {
    var languageTree = null;
    var hasCategories = false;
    var hasTrashcan = false;
    var hasCollapse = false;
    var hasComments = false;
    var hasDisable = false;
    var hasSounds = false;
  } else {
    var languageTree = Blockly.parseToolboxTree_(options['toolbox']);
    var hasCategories = Boolean(languageTree &&
        languageTree.getElementsByTagName('category').length);
    var hasTrashcan = options['trashcan'];
    if (hasTrashcan === undefined) {
      hasTrashcan = hasCategories;
    }
    var hasCollapse = options['collapse'];
    if (hasCollapse === undefined) {
      hasCollapse = hasCategories;
    }
    var hasComments = options['comments'];
    if (hasComments === undefined) {
      hasComments = hasCategories;
    }
    var hasDisable = options['disable'];
    if (hasDisable === undefined) {
      hasDisable = hasCategories;
    }
    var hasSounds = options['sounds'];
    if (hasSounds === undefined) {
      hasSounds = true;
    }
  }
  var hasScrollbars = options['scrollbars'];
  if (hasScrollbars === undefined) {
    hasScrollbars = hasCategories;
  }
  var hasCss = options['css'];
  if (hasCss === undefined) {
    hasCss = true;
  }
  var grid = options['grid'] || {};
  if (!grid['spacing']) {
    grid['spacing'] = 0;
  } else {
    grid['spacing'] = parseFloat(grid['spacing']);
  }
  if (!grid['colour']) {
    grid['colour'] = '#888';
  }
  if (!grid['length']) {
    grid['length'] = 1;
  } else {
    grid['length'] = parseFloat(grid['length']);
  }
  grid['snap'] = grid['spacing'] > 0 && !!grid['snap'];
  //var pathToMedia = 'https://blockly-demo.appspot.com/static/media/';
  var pathToMedia = '../blockly/media/';
  if (options['media']) {
    pathToMedia = options['media'];
  } else if (options['path']) {
    // 'path' is a deprecated option which has been replaced by 'media'.
    pathToMedia = options['path'] + 'media/';
  }
  var enableRealtime = !!options['realtime'];
  var realtimeOptions = enableRealtime ? options['realtimeOptions'] : undefined;

  return {
    RTL: !!options['rtl'],
    collapse: hasCollapse,
    comments: hasComments,
    disable: hasDisable,
    readOnly: readOnly,
    maxBlocks: options['maxBlocks'] || Infinity,
    pathToMedia: pathToMedia,
    hasCategories: hasCategories,
    hasScrollbars: hasScrollbars,
    hasTrashcan: hasTrashcan,
    hasSounds: hasSounds,
    hasCss: hasCss,
    languageTree: languageTree,
    gridOptions: grid,
    enableRealtime: enableRealtime,
    realtimeOptions: realtimeOptions
  };
};

/**
 * Create the SVG image.
 * @param {!Element} container Containing element.
 * @param {Object} options Dictionary of options.
 * @return {!Element} Newly created SVG image.
 * @private
 */
Blockly.createDom_ = function(container, options) {
  // Sadly browsers (Chrome vs Firefox) are currently inconsistent in laying
  // out content in RTL mode.  Therefore Blockly forces the use of LTR,
  // then manually positions content in RTL as needed.
  container.setAttribute('dir', 'LTR');
  // Closure can be trusted to create HTML widgets with the proper direction.
  goog.ui.Component.setDefaultRightToLeft(options.RTL);

  // Load CSS.
  Blockly.Css.inject(options.hasCss, options.pathToMedia);

  // Build the SVG DOM.
  /*
  <svg
    xmlns="http://www.w3.org/2000/svg"
    xmlns:html="http://www.w3.org/1999/xhtml"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    version="1.1"
    class="blocklySvg">
    ...
  </svg>
  */
  var svg = Blockly.createSvgElement('svg', {
    'xmlns': 'http://www.w3.org/2000/svg',
    'xmlns:html': 'http://www.w3.org/1999/xhtml',
    'xmlns:xlink': 'http://www.w3.org/1999/xlink',
    'version': '1.1',
    'class': 'blocklySvg'
  }, container);
  /*
  <defs>
    ... filters go here ...
  </defs>
  */
  var defs = Blockly.createSvgElement('defs', {}, svg);
  var filter, feSpecularLighting, feMerge;
  /*
    <filter id="blocklyEmboss">
      <feGaussianBlur in="SourceAlpha" stdDeviation="1" result="blur"/>
      <feSpecularLighting in="blur" surfaceScale="1" specularConstant="0.5"
                          specularExponent="10" lighting-color="white"
                          result="specOut">
        <fePointLight x="-5000" y="-10000" z="20000"/>
      </feSpecularLighting>
      <feComposite in="specOut" in2="SourceAlpha" operator="in"
                   result="specOut"/>
      <feComposite in="SourceGraphic" in2="specOut" operator="arithmetic"
                   k1="0" k2="1" k3="1" k4="0"/>
    </filter>
  */
  filter = Blockly.createSvgElement('filter', {'id': 'blocklyEmboss'}, defs);
  Blockly.createSvgElement('feGaussianBlur',
      {'in': 'SourceAlpha', 'stdDeviation': 1, 'result': 'blur'}, filter);
  feSpecularLighting = Blockly.createSvgElement('feSpecularLighting',
      {'in': 'blur', 'surfaceScale': 1, 'specularConstant': 0.5,
       'specularExponent': 10, 'lighting-color': 'white', 'result': 'specOut'},
      filter);
  Blockly.createSvgElement('fePointLight',
      {'x': -5000, 'y': -10000, 'z': 20000}, feSpecularLighting);
  Blockly.createSvgElement('feComposite',
      {'in': 'specOut', 'in2': 'SourceAlpha', 'operator': 'in',
       'result': 'specOut'}, filter);
  Blockly.createSvgElement('feComposite',
      {'in': 'SourceGraphic', 'in2': 'specOut', 'operator': 'arithmetic',
       'k1': 0, 'k2': 1, 'k3': 1, 'k4': 0}, filter);
  /*
    <filter id="blocklyShadowFilter">
      <feGaussianBlur stdDeviation="2"/>
    </filter>
  */
  filter = Blockly.createSvgElement('filter',
      {'id': 'blocklyShadowFilter'}, defs);
  Blockly.createSvgElement('feGaussianBlur', {'stdDeviation': 2}, filter);
  /*
    <pattern id="blocklyDisabledPattern" patternUnits="userSpaceOnUse"
             width="10" height="10">
      <rect width="10" height="10" fill="#aaa" />
      <path d="M 0 0 L 10 10 M 10 0 L 0 10" stroke="#cc0" />
    </pattern>
  */
  var disabledPattern = Blockly.createSvgElement('pattern',
      {'id': 'blocklyDisabledPattern', 'patternUnits': 'userSpaceOnUse',
       'width': 10, 'height': 10}, defs);
  Blockly.createSvgElement('rect',
      {'width': 10, 'height': 10, 'fill': '#aaa'}, disabledPattern);
  Blockly.createSvgElement('path',
      {'d': 'M 0 0 L 10 10 M 10 0 L 0 10', 'stroke': '#cc0'}, disabledPattern);
  /*
    <pattern id="blocklyGridPattern837493" patternUnits="userSpaceOnUse"
             width="10" height="10">
      <rect width="1" height="1" stroke="#888" />
      <rect width="1" height="1" stroke="#888" />
    </pattern>
  */
  // MSIE freaks if it sees a 0x0 pattern, so set empty patterns to 100x100.
  var safeSpacing = options.gridOptions['spacing'] || 100;
  var gridPattern = Blockly.createSvgElement('pattern',
      {'id': 'blocklyGridPattern' + String(Math.random()).substring(2),
       'patternUnits': 'userSpaceOnUse',
       'width': safeSpacing,
       'height': safeSpacing}, defs);
  if (options.gridOptions['length'] > 0 && options.gridOptions['spacing'] > 0) {
    var half = Math.floor(options.gridOptions['spacing'] / 2) + .5;
    var start = half - options.gridOptions['length'] / 2;
    var end = half + options.gridOptions['length'] / 2;
    Blockly.createSvgElement('line',
        {'x1': start,
         'y1': half,
         'x2': end,
         'y2': half,
         'stroke': options.gridOptions['colour']},
        gridPattern);
    if (options.gridOptions['length'] > 1) {
      Blockly.createSvgElement('line',
          {'x1': half,
           'y1': start,
           'x2': half,
           'y2': end,
           'stroke': options.gridOptions['colour']},
          gridPattern);
    }
  }
  options.gridPattern = gridPattern;
  options.svg = svg;
  return svg;
};

/**
 * Create a main workspace and add it to the SVG.
 * @param {!Element} svg SVG element with pattern defined.
 * @param {Object} options Dictionary of options.
 * @return {!Blockly.Workspace} Newly created main workspace.
 * @private
 */
Blockly.createMainWorkspace_ = function(svg, options) {
  options.parentWorkspace = null;
  options.getMetrics = Blockly.getMainWorkspaceMetrics_;
  options.setMetrics = Blockly.setMainWorkspaceMetrics_;
  var mainWorkspace = new Blockly.WorkspaceSvg(options);
  svg.appendChild(mainWorkspace.createDom('blocklyMainBackground'));
  mainWorkspace.markFocused();

  if (!options.readOnly && !options.hasScrollbars) {
    var workspaceChanged = function() {
      if (Blockly.dragMode_ == 0) {
        var metrics = mainWorkspace.getMetrics();
        var edgeLeft = metrics.viewLeft + metrics.absoluteLeft;
        var edgeTop = metrics.viewTop + metrics.absoluteTop;
        if (metrics.contentTop < edgeTop ||
            metrics.contentTop + metrics.contentHeight >
            metrics.viewHeight + edgeTop ||
            metrics.contentLeft <
                (options.RTL ? metrics.viewLeft : edgeLeft) ||
            metrics.contentLeft + metrics.contentWidth > (options.RTL ?
                metrics.viewWidth : metrics.viewWidth + edgeLeft)) {
          // One or more blocks may be out of bounds.  Bump them back in.
          var MARGIN = 25;
          var blocks = mainWorkspace.getTopBlocks(false);
          for (var b = 0, block; block = blocks[b]; b++) {
            var blockXY = block.getRelativeToSurfaceXY();
            var blockHW = block.getHeightWidth();
            // Bump any block that's above the top back inside.
            var overflow = edgeTop + MARGIN - blockHW.height - blockXY.y;
            if (overflow > 0) {
              block.moveBy(0, overflow);
            }
            // Bump any block that's below the bottom back inside.
            var overflow = edgeTop + metrics.viewHeight - MARGIN - blockXY.y;
            if (overflow < 0) {
              block.moveBy(0, overflow);
            }
            // Bump any block that's off the left back inside.
            var overflow = MARGIN + edgeLeft -
                blockXY.x - (options.RTL ? 0 : blockHW.width);
            if (overflow > 0) {
              block.moveBy(overflow, 0);
            }
            // Bump any block that's off the right back inside.
            var overflow = edgeLeft + metrics.viewWidth - MARGIN -
                blockXY.x + (options.RTL ? blockHW.width : 0);
            if (overflow < 0) {
              block.moveBy(overflow, 0);
            }
          }
        }
      }
    };
    mainWorkspace.addChangeListener(workspaceChanged);
  }
  // The SVG is now fully assembled.
  Blockly.svgResize(mainWorkspace);
  Blockly.WidgetDiv.createDom();
  Blockly.Tooltip.createDom()
  return mainWorkspace;
};

/**
 * Initialize Blockly with various handlers.
 * @param {!Blockly.Workspace} mainWorkspace Newly created main workspace.
 * @private
 */
Blockly.init_ = function(mainWorkspace) {
  var options = mainWorkspace.options;
  var svg = mainWorkspace.options.svg;
  // Supress the browser's context menu.
  Blockly.bindEvent_(svg, 'contextmenu', null,
      function(e) {
        if (!Blockly.isTargetInput_(e)) {
          e.preventDefault();
        }
      });
  // Bind events for scrolling the workspace.
  // Most of these events should be bound to the SVG's surface.
  // However, 'mouseup' has to be on the whole document so that a block dragged
  // out of bounds and released will know that it has been released.
  // Also, 'keydown' has to be on the whole document since the browser doesn't
  // understand a concept of focus on the SVG image.

  Blockly.bindEvent_(svg, 'touchstart', null,
                     function(e) {Blockly.longStart_(e, null);});
  Blockly.bindEvent_(window, 'resize', null,
                     function() {Blockly.svgResize(mainWorkspace);});

  if (!Blockly.documentEventsBound_) {
    // Only bind the window/document events once.
    // Destroying and reinjecting Blockly should not bind again.
    Blockly.bindEvent_(document, 'keydown', null, Blockly.onKeyDown_);
    Blockly.bindEvent_(document, 'touchend', null, Blockly.longStop_);
    Blockly.bindEvent_(document, 'touchcancel', null, Blockly.longStop_);
    // Don't use bindEvent_ for document's mouseup since that would create a
    // corresponding touch handler that would squeltch the ability to interact
    // with non-Blockly elements.
    document.addEventListener('mouseup', Blockly.onMouseUp_, false);
    // Some iPad versions don't fire resize after portrait to landscape change.
    if (goog.userAgent.IPAD) {
      Blockly.bindEvent_(window, 'orientationchange', document, function() {
        Blockly.fireUiEvent(window, 'resize');
      });
    }
    Blockly.documentEventsBound_ = true;
  }

  if (options.languageTree) {
    if (mainWorkspace.toolbox_) {
      mainWorkspace.toolbox_.init(mainWorkspace);
    } else if (mainWorkspace.flyout_) {
      // Build a fixed flyout with the root blocks.
      mainWorkspace.flyout_.init(mainWorkspace);
      mainWorkspace.flyout_.show(options.languageTree.childNodes);
      // Translate the workspace sideways to avoid the fixed flyout.
      mainWorkspace.scrollX = mainWorkspace.flyout_.width_;
      if (options.RTL) {
        mainWorkspace.scrollX *= -1;
      }
      var translation = 'translate(' + mainWorkspace.scrollX + ', 0)';
      mainWorkspace.getCanvas().setAttribute('transform', translation);
      mainWorkspace.getBubbleCanvas().setAttribute('transform', translation);
    }
  }
  if (options.hasScrollbars) {
    mainWorkspace.scrollbar = new Blockly.ScrollbarPair(mainWorkspace);
    mainWorkspace.scrollbar.resize();
  }

  // Load the sounds.
  if (options.hasSounds) {
    mainWorkspace.loadAudio_(
        [options.pathToMedia + 'click.mp3',
         options.pathToMedia + 'click.wav',
         options.pathToMedia + 'click.ogg'], 'click');
    mainWorkspace.loadAudio_(
        [options.pathToMedia + 'delete.mp3',
         options.pathToMedia + 'delete.ogg',
         options.pathToMedia + 'delete.wav'], 'delete');

    // Bind temporary hooks that preload the sounds.
    var soundBinds = [];
    var unbindSounds = function() {
      while (soundBinds.length) {
        Blockly.unbindEvent_(soundBinds.pop());
      }
      mainWorkspace.preloadAudio_();
    };
    // Android ignores any sound not loaded as a result of a user action.
    soundBinds.push(
        Blockly.bindEvent_(document, 'mousemove', null, unbindSounds));
    soundBinds.push(
        Blockly.bindEvent_(document, 'touchstart', null, unbindSounds));
  }
};

/**
 * Modify the block tree on the existing toolbox.
 * @param {Node|string} tree DOM tree of blocks, or text representation of same.
 */
Blockly.updateToolbox = function(tree, workspace) {
  console.warn('Deprecated call to Blockly.updateToolbox, ' +
               'use workspace.updateToolbox instead.');
  Blockly.getMainWorkspace().updateToolbox(tree);
};


text:
文件集接口
==============

.. module:: teambition.api.collections

.. autoclass:: Collections
   :members:


text:
module SimpleApi
  module Sitemap
    class Root < Sequel::Model
      set_dataset :roots
      def breadcrumbs
        [
          {
            label: sphere,
            url: "/en/#{sphere}/index/#{param || 'group'}" #change when param added to self
          }
        ]
      end

      def clean_index
        SimpleApi::Sitemap::ObjectData.where(root_id: pk).delete
        ruls = SimpleApi::Rule.where(sphere: sphere).all.map(&:pk)
        SimpleApi::Sitemap::Reference.where(rule_id: ruls, sitemap_session_id: sitemap_session_id).delete
        SimpleApi::Sitemap::Index.where(root_id: pk).delete
        SimpleApi::Sitemap::Production.where(root_id: pk).update(root_id: nil)
        delete
      end
    end
  end
end


text:
""" {{cookiecutter.modelname}} model configuration """

from ...configuration_utils import PretrainedConfig
from ...utils import logging

logger = logging.get_logger(__name__)

{{cookiecutter.uppercase_modelname}}_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "{{cookiecutter.checkpoint_identifier}}": "https://huggingface.co/{{cookiecutter.checkpoint_identifier}}/resolve/main/config.json",
    # See all {{cookiecutter.modelname}} models at https://huggingface.co/models?filter={{cookiecutter.lowercase_modelname}}
}

class {{cookiecutter.camelcase_modelname}}Config(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a :class:`~transformers.{{cookiecutter.camelcase_modelname}}Model`.
    It is used to instantiate an {{cookiecutter.modelname}} model according to the specified arguments, defining the model
    architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
    the {{cookiecutter.modelname}} `{{cookiecutter.checkpoint_identifier}} <https://huggingface.co/{{cookiecutter.checkpoint_identifier}}>`__ architecture.

    Configuration objects inherit from  :class:`~transformers.PretrainedConfig` and can be used
    to control the model outputs. Read the documentation from  :class:`~transformers.PretrainedConfig`
    for more information.

    Args:
        {% if cookiecutter.is_encoder_decoder_model == "False" -%}
        vocab_size (:obj:`int`, `optional`, defaults to 30522):
            Vocabulary size of the {{cookiecutter.modelname}} model. Defines the number of different tokens that can be represented by the
            :obj:`inputs_ids` passed when calling :class:`~transformers.{{cookiecutter.camelcase_modelname}}Model` or
            :class:`~transformers.TF{{cookiecutter.camelcase_modelname}}Model`.
        hidden_size (:obj:`int`, `optional`, defaults to 768):
            Dimension of the encoder layers and the pooler layer.
        num_hidden_layers (:obj:`int`, `optional`, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (:obj:`int`, `optional`, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (:obj:`int`, `optional`, defaults to 3072):
            Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        hidden_act (:obj:`str` or :obj:`function`, `optional`, defaults to :obj:`"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler.
            If string, :obj:`"gelu"`, :obj:`"relu"`, :obj:`"selu"` and :obj:`"gelu_new"` are supported.
        hidden_dropout_prob (:obj:`float`, `optional`, defaults to 0.1):
            The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (:obj:`float`, `optional`, defaults to 0.1):
            The dropout ratio for the attention probabilities.
        max_position_embeddings (:obj:`int`, `optional`, defaults to 512):
            The maximum sequence length that this model might ever be used with.
            Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
        type_vocab_size (:obj:`int`, `optional`, defaults to 2):
            The vocabulary size of the :obj:`token_type_ids` passed when calling :class:`~transformers.{{cookiecutter.camelcase_modelname}}Model` or
            :class:`~transformers.TF{{cookiecutter.camelcase_modelname}}Model`.
        initializer_range (:obj:`float`, `optional`, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (:obj:`float`, `optional`, defaults to 1e-12):
            The epsilon used by the layer normalization layers.
        use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if ``config.is_decoder=True``.
        gradient_checkpointing (:obj:`bool`, `optional`, defaults to :obj:`False`):
            If :obj:`True`, use gradient checkpointing to save memory at the expense of slower backward pass.
        {% else -%}
        vocab_size (:obj:`int`, `optional`, defaults to 50265):
            Vocabulary size of the {{cookiecutter.modelname}} model. Defines the number of different tokens that can be represented by the
            :obj:`inputs_ids` passed when calling :class:`~transformers.{{cookiecutter.camelcase_modelname}}Model` or
            :class:`~transformers.TF{{cookiecutter.camelcase_modelname}}Model`.
        d_model (:obj:`int`, `optional`, defaults to 1024):
            Dimension of the layers and the pooler layer.
        encoder_layers (:obj:`int`, `optional`, defaults to 12):
            Number of encoder layers.
        decoder_layers (:obj:`int`, `optional`, defaults to 12):
            Number of decoder layers.
        encoder_attention_heads (:obj:`int`, `optional`, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        decoder_attention_heads (:obj:`int`, `optional`, defaults to 16):
            Number of attention heads for each attention layer in the Transformer decoder.
        decoder_ffn_dim (:obj:`int`, `optional`, defaults to 4096):
            Dimension of the "intermediate" (often named feed-forward) layer in decoder.
        encoder_ffn_dim (:obj:`int`, `optional`, defaults to 4096):
            Dimension of the "intermediate" (often named feed-forward) layer in decoder.
        activation_function (:obj:`str` or :obj:`function`, `optional`, defaults to :obj:`"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string,
            :obj:`"gelu"`, :obj:`"relu"`, :obj:`"silu"` and :obj:`"gelu_new"` are supported.
        dropout (:obj:`float`, `optional`, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_dropout (:obj:`float`, `optional`, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        activation_dropout (:obj:`float`, `optional`, defaults to 0.0):
            The dropout ratio for activations inside the fully connected layer.
        classifier_dropout (:obj:`float`, `optional`, defaults to 0.0):
            The dropout ratio for classifier.
        max_position_embeddings (:obj:`int`, `optional`, defaults to 1024):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        init_std (:obj:`float`, `optional`, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        encoder_layerdrop: (:obj:`float`, `optional`, defaults to 0.0):
            The LayerDrop probability for the encoder. See the `LayerDrop paper <see
            https://arxiv.org/abs/1909.11556>`__ for more details.
        decoder_layerdrop: (:obj:`float`, `optional`, defaults to 0.0):
            The LayerDrop probability for the decoder. See the `LayerDrop paper <see
            https://arxiv.org/abs/1909.11556>`__ for more details.
        use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether or not the model should return the last key/values attentions (not used by all models).
        {% endif -%}

    Example::

        >>> from transformers import {{cookiecutter.camelcase_modelname}}Model, {{cookiecutter.camelcase_modelname}}Config

        >>> # Initializing a {{cookiecutter.modelname}} {{cookiecutter.checkpoint_identifier}} style configuration
        >>> configuration = {{cookiecutter.camelcase_modelname}}Config()

        >>> # Initializing a model from the {{cookiecutter.checkpoint_identifier}} style configuration
        >>> model = {{cookiecutter.camelcase_modelname}}Model(configuration)

        >>> # Accessing the model configuration
        >>> configuration = model.config
    """
    model_type = "{{cookiecutter.lowercase_modelname}}"
    {% if cookiecutter.is_encoder_decoder_model == "False" -%}
    {% else -%}
    keys_to_ignore_at_inference = ["past_key_values"]
    {% endif -%}

    def __init__(
        self,
        {% if cookiecutter.is_encoder_decoder_model == "False" -%}
        vocab_size=30522,
        hidden_size=768,
        num_hidden_layers=12,
        num_attention_heads=12,
        intermediate_size=3072,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=2,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        use_cache=True,
        is_encoder_decoder=False,
        {% else -%}
        vocab_size=50265,
        max_position_embeddings=1024,
        encoder_layers=12,
        encoder_ffn_dim=4096,
        encoder_attention_heads=16,
        decoder_layers=12,
        decoder_ffn_dim=4096,
        decoder_attention_heads=16,
        encoder_layerdrop=0.0,
        decoder_layerdrop=0.0,
        use_cache=True,
        is_encoder_decoder=True,
        activation_function="gelu",
        d_model=1024,
        dropout=0.1,
        attention_dropout=0.0,
        activation_dropout=0.0,
        init_std=0.02,
        decoder_start_token_id=2,
        classifier_dropout=0.0,
        scale_embedding=False,
        gradient_checkpointing=False,
        {% endif -%}
        pad_token_id=1,
        bos_token_id=0,
        eos_token_id=2,
        **kwargs
    ):
        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            {% if cookiecutter.is_encoder_decoder_model == "False" -%}
            {% else -%}
            is_encoder_decoder=is_encoder_decoder,
            decoder_start_token_id=decoder_start_token_id,
            {% endif -%}
            **kwargs
        )

        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        {% if cookiecutter.is_encoder_decoder_model == "False" -%}
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.initializer_range = initializer_range
        self.type_vocab_size = type_vocab_size
        self.layer_norm_eps = layer_norm_eps
        self.use_cache = use_cache
        {% else -%}
        self.d_model = d_model
        self.encoder_ffn_dim = encoder_ffn_dim
        self.encoder_layers = encoder_layers
        self.encoder_attention_heads = encoder_attention_heads
        self.decoder_ffn_dim = decoder_ffn_dim
        self.decoder_layers = decoder_layers
        self.decoder_attention_heads = decoder_attention_heads
        self.dropout = dropout
        self.attention_dropout = attention_dropout
        self.activation_dropout = activation_dropout
        self.activation_function = activation_function
        self.init_std = init_std
        self.encoder_layerdrop = encoder_layerdrop
        self.decoder_layerdrop = decoder_layerdrop
        self.classifier_dropout = classifier_dropout
        self.use_cache = use_cache
        self.num_hidden_layers = encoder_layers
        self.gradient_checkpointing = gradient_checkpointing
        self.scale_embedding = scale_embedding  # scale factor will be sqrt(d_model) if True

        {% endif -%}

    {% if cookiecutter.is_encoder_decoder_model == "False" %}
    {%- else %}
    @property
    def num_attention_heads(self) -> int:
        return self.encoder_attention_heads

    @property
    def hidden_size(self) -> int:
        return self.d_model
    {%- endif %}


text:
from twython import Twython, TwythonRateLimitError
import sexmachine.detector as gender
import tweepy
from tweepy import OAuthHandler
from analyze import declared_gender, split, rm_punctuation
import argparse
from unidecode import unidecode
import json

consumer_key = 'RGRcS3VbTYYTCg5InwpHn7wuv'
consumer_secret = 'qKGjYAfextYSL6cBMTIZ4P3MVKwfL4jzAQjzYiuntiwenWY7L6'
access_token = '860191918776619008-EvW5GuJQas6iNmfMMhLQFSA0qYswxKc'
access_token_secret = 'dmMEoGKq1DuzfXVE7iSTymaU0lYq8eZ4WCcvqgwjXMLJO'

twitter = Twython(consumer_key, consumer_secret, oauth_version=1)

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

detector = gender.Detector(case_sensitive=False)

def defineOptions():
    parser = argparse.ArgumentParser( description='Gender Analyze Twitter Tool' )
    parser.add_argument('screen_name', type=str, help="Twitter account name to be analyzed")
    args = parser.parse_args()
    return (args, parser)

def guessGender( name, description=None, country=None ):
    g = "undetermined"
    g = declared_gender( description )
    if g == 'andy':
        for name, country in [
            (split(name), None),
            (name, None),
            (unidecode(name), None),
            (split(unidecode(name)), None),
        ]:
            g = detector.get_gender(name, country)
            if g != 'andy':
                # Not androgynous.
                break
            g = detector.get_gender(rm_punctuation(name), country)
            if g != 'andy':
                # Not androgynous.
                break
    if g != 'andy':
        return g
    else:
        return "undetermined"

def getUserInfo( name ):
    return api.get_user( name )

def getFollowers( name ):
    return twitter.get_followers_list(screen_name=name, count=200,cursor=-1)

def getFriends( name ):
    return twitter.get_friends_list(screen_name=name, count=200, cursor=-1)

def usersInfo( userList ):
    userDict = {}
    for user in userList:
        userDict[ user["screen_name"] ] = {}
        userDict[ user["screen_name"] ]["name"]             = user["name"]
        userDict[ user["screen_name"] ]["id"]               = user["id"]
        userDict[ user["screen_name"] ]["lang"]             = user["lang"]
        userDict[ user["screen_name"] ]["location"]         = user["location"]
        userDict[ user["screen_name"] ]["friends_count"]    = user["friends_count"]
        userDict[ user["screen_name"] ]["followers_count"]  = user["followers_count"]
        userDict[ user["screen_name"] ]["favourites_count"] = user["favourites_count"]
        userDict[ user["screen_name"] ]["statuses_count"]   = user["statuses_count"]
        g = guessGender(  user["name"], user["description"], user["location"] )
        userDict[ user["screen_name"] ]["gender"]           = g

    return userDict

def getDiversityOfIntersect( dict1, dict2 ):
    interDict = {}
    # Calc intersect
    for name_key in dict1.keys():
        if not interDict.has_key(name_key):
            interDict[name_key] = dict1[name_key]["gender"]
    for name_key in dict2.keys():
        if not interDict.has_key(name_key):
            interDict[name_key] = dict2[name_key]["gender"]

    # Get diversity info
    female_count = 0
    male_count = 0
    nonbinary_count = 0
    undefined_count = 0
    total_count = 0

    for key in interDict.keys():
        if interDict[key] == "female":
            female_count += 1
        elif interDict[key] == "male":
            male_count += 1
        elif interDict[key] == "nonbinary":
            nonbinary_count += 1
        elif interDict[key] == "undetermined":
            undefined_count += 1

        total_count += 1

    if total_count > 0:
        female_rate   = str((female_count * 100) / total_count)+"%"
        male_rate     = str((male_count * 100) / total_count)+"%"
        nonbinary_rate= str((nonbinary_count * 100) / total_count)+"%"
        undefined_rate= str((undefined_count * 100) / total_count)+"%"

    return (female_count,male_count,nonbinary_count,undefined_count,female_rate,male_rate,nonbinary_rate,undefined_rate,total_count)

if __name__ == "__main__":
    global args
    (args, parser) = defineOptions()

    followers = getFollowers( args.screen_name )
    followersInfo = usersInfo( followers["users"] )

    friends   = getFriends( args.screen_name )
    friendsInfo = usersInfo( friends["users"] )

    userInfo = getUserInfo( args.screen_name )
    uDict = {}
    uDict[args.screen_name] = {}

    uDict[args.screen_name]['name']             = userInfo.name
    uDict[args.screen_name]['id']               = userInfo.id
    uDict[args.screen_name]['lang']             = userInfo.lang
    uDict[args.screen_name]['location']         = userInfo.location
    uDict[args.screen_name]['friends_count']    = userInfo.friends_count
    uDict[args.screen_name]['followers_count']  = userInfo.followers_count
    uDict[args.screen_name]['favourites_count'] = userInfo.favourites_count
    uDict[args.screen_name]['statuses_count']   = userInfo.statuses_count
    uDict[args.screen_name]['gender']           = guessGender( userInfo.name, userInfo.description, userInfo.location )

    ( female_c, male_c, nonbinary_c, undefined_c, female_r, male_r, nonbinary_r, undefined_r, total_c ) = getDiversityOfIntersect( followersInfo, friendsInfo )

    uDict[args.screen_name]['total_count']     = total_c

    uDict[args.screen_name]['female_count']    = female_c
    uDict[args.screen_name]['male_count']      = male_c
    uDict[args.screen_name]['nonbinary_count'] = nonbinary_c
    uDict[args.screen_name]['undefined_count'] = undefined_c

    uDict[args.screen_name]['female_rate']     = female_r
    uDict[args.screen_name]['male_rate']       = male_r
    uDict[args.screen_name]['nonbinary_rate']  = nonbinary_r
    uDict[args.screen_name]['undefined_rate']  = undefined_r

    uDict[args.screen_name]['followers_list']   = followersInfo
    uDict[args.screen_name]['friends_list']     = friendsInfo

    f = open( '../out/'+args.screen_name+'.json' , 'w')
    f.write( json.dumps(uDict) )
    f.close()


text:
namespace markdown
{

NormalizeWhitespace::~NormalizeWhitespace(void)
{}

QStringList NormalizeWhitespace::run(const QStringList &lines)
{
    std::shared_ptr<Markdown> markdown = this->markdown.lock();

    QString source = lines.join("\n");
    source = source.replace(util::STX, QString());
    source = source.replace(util::ETX, QString());
    source = source.replace("\r\n", "\n");
    source = source.replace("\r", "\n");
    source += "\n\n";
    source = pypp::expandtabs(source, markdown->tab_length());
    source = source.replace(QRegularExpression("(?<=\n) +\n"), "\n");
    return source.split("\n");
}

} // namespace markdown


text:
#import <Foundation/Foundation.h>

@interface REVertexArrayObject : NSObject {
    GLuint vertexArrayObject;
}

- (void)bind;
+ (void)unbind;

@end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.

package com.microsoft.alm.plugin.idea.ui.checkout;

import com.microsoft.alm.plugin.idea.IdeaAbstractTest;
import com.microsoft.alm.plugin.idea.ui.checkout.mocks.MockCheckoutPage;
import com.microsoft.alm.plugin.idea.ui.checkout.mocks.MockCheckoutPageModel;
import com.microsoft.alm.plugin.idea.ui.common.ServerContextTableModel;
import com.microsoft.alm.plugin.idea.ui.common.forms.LoginForm;
import com.microsoft.alm.plugin.idea.ui.controls.UserAccountPanel;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import java.awt.event.ActionEvent;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class CheckoutPageControllerTest extends IdeaAbstractTest {
    /**
     * This test was added to cover the bit of the tfs controller that wasn't already covered
     */
    @Test
    public void testActionPerformed() {
        MockCheckoutPageModel tfsModel = new MockCheckoutPageModel(null, ServerContextTableModel.VSO_REPO_COLUMNS);
        MockCheckoutPage tfsPage = new MockCheckoutPage();
        CheckoutPageController tcc = new CheckoutPageController(tfsModel, tfsPage);

        // Trigger the controller to do connect
        tcc.actionPerformed(new ActionEvent(this, 1, LoginForm.CMD_SIGN_IN));
        assertEquals(true, tfsModel.isLoadRepositoriesCalled());
        tfsModel.clearInternals();

        // Trigger the controller to do sign out
        assertEquals(true, tfsModel.isConnected());
        tcc.actionPerformed(new ActionEvent(this, 1, UserAccountPanel.CMD_SIGN_OUT));
        assertEquals(false, tfsModel.isConnected());
        tfsModel.clearInternals();

        // Trigger the controller to do filter changed
        assertTrue(StringUtils.isEmpty(tfsModel.getRepositoryFilter()));
        tfsPage.setRepositoryFilter("filter");
        tcc.actionPerformed(new ActionEvent(this, 1, CheckoutForm.CMD_REPO_FILTER_CHANGED));
        assertEquals("filter", tfsModel.getRepositoryFilter());
        tfsModel.clearInternals();
    }

}


text:
<?php

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property string $DisputeID
 */
class GetDisputeRequestType extends \DTS\eBaySDK\Trading\Types\AbstractRequestType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = array(
        'DisputeID' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'DisputeID'
        )
    );

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = array())
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents';
        }

        if (!array_key_exists(__CLASS__, self::$requestXmlRootElementNames)) {
            self::$requestXmlRootElementNames[__CLASS__] = 'GetDisputeRequest';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
package i6502

const (
	aciaData = iota
	aciaStatus
	aciaCommand
	aciaControl
)

/*
ACIA 6551 Serial IO

This Asynchronous Communications Interface Adapater can be
directly attached to the 6502's address and data busses.

It provides serial IO.

The supplied Rx and Tx channels can be used to read and wirte
data to the ACIA 6551.
*/
type Acia6551 struct {
	rx byte
	tx byte

	commandData byte
	controlData byte

	rxFull  bool
	txEmpty bool

	rxIrqEnabled bool
	txIrqEnabled bool

	overrun bool

	output chan []byte
}

func NewAcia6551(output chan []byte) (*Acia6551, error) {
	acia := &Acia6551{output: output}
	acia.Reset()

	return acia, nil
}

func (a *Acia6551) Size() uint16 {
	// We have a only 4 addresses, Data, Status, Command and Control
	return 0x04
}

// Emulates a hardware reset
func (a *Acia6551) Reset() {
	a.rx = 0
	a.rxFull = false

	a.tx = 0
	a.txEmpty = true

	a.rxIrqEnabled = false
	a.txIrqEnabled = false

	a.overrun = false

	a.setControl(0)
	a.setCommand(0)
}

func (a *Acia6551) setControl(data byte) {
	a.controlData = data
}

func (a *Acia6551) setCommand(data byte) {
	a.commandData = data

	a.rxIrqEnabled = (data & 0x02) != 0
	a.txIrqEnabled = ((data & 0x04) != 0) && ((data & 0x08) != 1)
}

func (a *Acia6551) statusRegister() byte {
	status := byte(0)

	if a.rxFull {
		status |= 0x08
	}

	if a.txEmpty {
		status |= 0x10
	}

	if a.overrun {
		status |= 0x04
	}

	return status
}

// Implements io.Reader, for external programs to read TX'ed data from
// the serial output.
func (a *Acia6551) Read(p []byte) (n int, err error) {
	if len(p) == 0 {
		return 0, nil
	}

	if a.txEmpty {
		return 0, nil
	} else {
		a.txEmpty = true
		copy(p, []byte{a.tx})
		// TODO: Handle txInterrupt
		return 1, nil
	}
}

// Implements io.Writer, for external programs to write to the
// ACIA's RX
func (a *Acia6551) Write(p []byte) (n int, err error) {
	for _, b := range p {
		a.rxWrite(b)
	}

	return len(p), nil
}

// Used by the AddressBus to read data from the ACIA 6551
func (a *Acia6551) ReadByte(address uint16) byte {
	switch address {
	case aciaData:
		return a.rxRead()
	case aciaStatus:
		return a.statusRegister()
	case aciaCommand:
		return a.commandData
	case aciaControl:
		return a.controlData
	}

	return 0x00
}

// Used by the AddressBus to write data to the ACIA 6551
func (a *Acia6551) WriteByte(address uint16, data byte) {
	switch address {
	case aciaData:
		a.txWrite(data)
	case aciaStatus:
		a.Reset()
	case aciaCommand:
		a.setCommand(data)
	case aciaControl:
		a.setControl(data)
	}
}

func (a *Acia6551) rxRead() byte {
	a.overrun = false
	a.rxFull = false
	return a.rx
}

func (a *Acia6551) rxWrite(data byte) {
	// Oh no, overrun. Set the appropriate status
	if a.rxFull {
		a.overrun = true
	}

	a.rx = data
	a.rxFull = true

	// TODO: Interrupts
}

func (a *Acia6551) txWrite(data byte) {
	a.output <- []byte{data}
	a.tx = data
	// a.txEmpty = false
}


text:
package com.xdd;

import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;

import static java.lang.String.format;

public class SpecRunner extends Runner {

    private final Spec spec;
    private final Description specDescription;

    public SpecRunner(Class testClass) {
        this.spec = validatedSpecFromThe(testClass);
        this.specDescription = Description.createSuiteDescription(spec.getClass());
    }

    private Spec validatedSpecFromThe(Class testClass) {
        try {
            return (Spec) testClass.newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassCastException e) {
            throw new SpecificationException(format("%s is not in proper Spec format!", testClass.getName()));
        }
    }

    @Override
    public Description getDescription() {
        addSpecificationDetailsToSpecDescription();
        return specDescription;
    }

    private void addSpecificationDetailsToSpecDescription() {
        for (SpecificationDetails specificationDetails : spec.getSpecificationDetails()) {
            specDescription.addChild(Description.createSuiteDescription(specificationDetails.getDescription()));
        }
    }

    @Override
    public void run(RunNotifier notifier) {
        for(SpecificationDetails specificationDetails : spec.getSpecificationDetails()) {
            specificationDetails.runTestWith(spec,notifier);
        }
    }
}


text:
package federation

import (
	"context"
	"encoding/json"
	"io"
	"io/ioutil"
	"os"
	"testing"
	"time"

	"github.com/samsarahq/go/oops"
	"github.com/samsarahq/thunder/graphql/introspection"
	"github.com/samsarahq/thunder/graphql/schemabuilder"
	"github.com/stretchr/testify/require"
)

type FileSchemaSyncer struct {
	services        []string
	add             chan string // new URL channel
	currentSchema   []byte
	serviceSelector ServiceSelector
}

func newFileSchemaSyncer(ctx context.Context, services []string) *FileSchemaSyncer {
	ss := &FileSchemaSyncer{
		services: services,
		add:      make(chan string),
	}
	return ss
}

func (s *FileSchemaSyncer) FetchPlanner(ctx context.Context) (*Planner, error) {
	schemas := make(map[string]*IntrospectionQueryResult)
	for _, server := range s.services {
		schema, err := readFile(server)
		if err != nil {
			return nil, oops.Wrapf(err, "error reading file for server %s", server)
		}
		var iq IntrospectionQueryResult
		if err := json.Unmarshal(schema, &iq); err != nil {
			return nil, oops.Wrapf(err, "unmarshaling schema %s", server)
		}
		schemas[server] = &iq
	}

	types, err := convertSchema(schemas)
	if err != nil {
		return nil, oops.Wrapf(err, "converting schemas error")
	}

	introspectionSchema := introspection.BareIntrospectionSchema(types.Schema)
	schema, err := introspection.RunIntrospectionQuery(introspection.BareIntrospectionSchema(introspectionSchema))
	if err != nil || schema == nil {
		return nil, oops.Wrapf(err, "error running introspection query")
	}

	var iq IntrospectionQueryResult
	if err := json.Unmarshal(schema, &iq); err != nil {
		return nil, oops.Wrapf(err, "unmarshaling introspection schema")
	}

	schemas["introspection"] = &iq
	types, err = convertSchema(schemas)
	if err != nil {
		return nil, oops.Wrapf(err, "converting schemas error")
	}

	return NewPlanner(types, s.serviceSelector)
}

// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func WriteToFile(filename string, data string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.WriteString(file, data)
	if err != nil {
		return err
	}
	return file.Sync()
}

func writeSchemaToFile(name string, data []byte) error {
	if _, err := os.Stat("testdata/temp/"); os.IsNotExist(err) {
		os.Mkdir("testdata/temp/", 0755)
	}
	fileName := "./testdata/temp/fileschemasyncer-" + name
	file, err := os.Create(fileName)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.WriteString(file, string(data))
	if err != nil {
		return err
	}
	return file.Sync()
}

func readFile(name string) ([]byte, error) {
	if _, err := os.Stat("testdata/temp/"); os.IsNotExist(err) {
		os.Mkdir("testdata/temp/", 0755)
	}
	fileName := "./testdata/temp/fileschemasyncer-" + name
	return ioutil.ReadFile(fileName)
}

func TestExecutorQueriesWithCustomSchemaSyncer(t *testing.T) {
	s1 := buildTestSchema1()
	s2 := buildTestSchema2()

	ctx := context.Background()
	execs, err := makeExecutors(map[string]*schemabuilder.Schema{
		"s1": s1,
		"s2": s2,
	})
	require.NoError(t, err)

	// Write the schemas to a file
	services := []string{"s1", "s2"}
	for _, service := range services {
		schema, err := fetchSchema(ctx, execs[service], nil)
		require.NoError(t, err)
		err = writeSchemaToFile(service, schema.Result)
		require.NoError(t, err)
	}

	// Creata file schema syncer that reads the schemas from the
	// written files and listens to updates if those change
	schemaSyncer := newFileSchemaSyncer(ctx, services)
	e, err := NewExecutor(ctx, execs, &SchemaSyncerConfig{
		SchemaSyncer:              schemaSyncer,
		SchemaSyncIntervalSeconds: func(ctx context.Context) int64 { return 1 },
	})
	require.NoError(t, err)

	// Test Case 1.
	query := `query Foo {
					s2root
					s1fff {
						s1hmm
					}
				}`
	expectedOutput := `{
					"s2root": "hello",
					"s1fff":[
						{
							"s1hmm":"jimbo!!!"
						},
						{
							"s1hmm":"bob!!!"
						}
					]
				}`

	// Run a federated query and ensure that it works
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
	time.Sleep(2 * time.Second)

	// Test Case 2.
	// Add a new field to schema2
	s2.Query().FieldFunc("syncerTest", func() string {
		return "hello"
	})

	newExecs, err := makeExecutors(map[string]*schemabuilder.Schema{
		"s1": s1,
		"s2": s2,
	})
	require.NoError(t, err)

	// We need to do this to udpate the executor in our test
	// But when run locally it should already know about the new
	// field when the new service starts
	e.Executors = newExecs

	query2 := `query Foo {
		syncerTest
	}`
	expectedOutput2 := `{
		"syncerTest":"hello"
	}`

	// Since we havent written the new schema to the file, the merged schema and planner
	// dont know about the new field. We should see an error
	runAndValidateQueryError(t, ctx, e, query2, expectedOutput2, "unknown field syncerTest on typ Query")

	// Test case 3.
	// Writes the new schemas to the file
	for _, service := range services {
		schema, err := fetchSchema(ctx, newExecs[service], nil)
		require.NoError(t, err)
		err = writeSchemaToFile(service, schema.Result)
		require.NoError(t, err)
	}

	// Sleep for 3 seconds to wait for the schema syncer to get the update
	time.Sleep(3 * time.Second)

	// 	Run the same query and validate that it works
	runAndValidateQueryResults(t, ctx, e, query2, expectedOutput2)

	// Test case 4.
	// Add the same fieldfunc to s1.
	s1.Query().FieldFunc("syncerTest", func() string {
		return "hello from s1"
	})
	newExecs, err = makeExecutors(map[string]*schemabuilder.Schema{
		"s1": s1,
		"s2": s2,
	})
	require.NoError(t, err)
	// We need to do this to udpate the executor in our test
	// But when run locally it should already know about the new
	// field when the new service starts
	e.Executors = newExecs
	// Writes the new schemas to the file
	for _, service := range services {
		schema, err := fetchSchema(ctx, newExecs[service], nil)
		require.NoError(t, err)
		err = writeSchemaToFile(service, schema.Result)
		require.NoError(t, err)
	}
	// Sleep for 3 seconds to wait for the schema syncer to get the update
	time.Sleep(3 * time.Second)

	// Update the serviceSelector, syncerTestFunc to be resolved by service 1.
	schemaSyncer.serviceSelector = func(typeName string, fieldName string) string {
		if typeName == "Query" && fieldName == "syncerTest" {
			return "s1"
		}
		return ""
	}
	expectedOutput2 = `{
		"syncerTest":"hello from s1"
	}`
	// Sleep for 2 seconds to wait for the schema syncer to get the update
	time.Sleep(2 * time.Second)
	// Run the same query and validate that it works
	runAndValidateQueryResults(t, ctx, e, query2, expectedOutput2)
}

func TestOnlyShadowServiceKnowsAboutNewField(t *testing.T) {
	type User struct {
		Id          int64
		OrgId       int64
		Name        string
		Email       string
		PhoneNumber string
	}
	type UserKeys struct {
		Id    int64
		OrgId int64
	}

	s1 := schemabuilder.NewSchemaWithName("schema1")
	user := s1.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKeys }) []*User {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "testUser", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "testUser2", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		return users
	}))
	user.Key("id")
	s1.Query().FieldFunc("users", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "testUser", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "testUser2", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		return users, nil
	})

	s2 := schemabuilder.NewSchemaWithName("schema2")
	userWithContactInfo := s2.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKeys }) []*User {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "testUser", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "testUser2", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		return users
	}))
	userWithContactInfo.FieldFunc("isCool", func(ctx context.Context) (bool, error) { return true, nil })

	ctx := context.Background()
	execs, err := makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2,
	})
	require.NoError(t, err)

	// Write the schemas to a file
	services := []string{"schema1", "schema2"}
	for _, service := range services {
		schema, err := fetchSchema(ctx, execs[service], nil)
		require.NoError(t, err)
		err = writeSchemaToFile(service, schema.Result)
		require.NoError(t, err)
	}

	// Creata file schema syncer that reads the schemas from the
	// written files and listens to updates if those change
	schemaSyncer := newFileSchemaSyncer(ctx, services)
	e, err := NewExecutor(ctx, execs, &SchemaSyncerConfig{
		SchemaSyncer:              schemaSyncer,
		SchemaSyncIntervalSeconds: func(ctx context.Context) int64 { return 100 },
	})
	require.NoError(t, err)

	query := `query Foo {
					users {
						isCool
					}
				}`
	expectedOutput := `{
					"users":[
						{
							"__key":1,
							"isCool":true
						},
						{
							"__key":2,
							"isCool":true
						}
					]
				}`

	// Run a federated query and ensure that it works
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	type UserKeysNew struct {
		Id    int64
		OrgId int64
		Name  string `graphql:",optional"`
	}

	s2new := schemabuilder.NewSchemaWithName("schema2")
	userWithContactInfoNew := s2new.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKeysNew }) []*User {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "testUser", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "testUser2", Email: "email@gmail.com", PhoneNumber: "555-5555"})
		return users
	}))
	userWithContactInfoNew.FieldFunc("isCool", func(ctx context.Context) (bool, error) { return true, nil })

	newExecs, err := makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2new,
	})
	require.NoError(t, err)

	// The executor is updated. This mocsk the case where the federated executor
	// knows about a new field, but the gateway doesnt know about it yet
	// We want to fill it with a blank value until the gateway can correctly send the information
	e.Executors = newExecs

	// Run a federated query and ensure that it works
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

}

func updateSchemaFiles(t *testing.T, executors map[string]*schemabuilder.Schema) *Executor {
	ctx := context.Background()
	newExecs, err := makeExecutors(executors)
	services := []string{"schema1", "schema2"}
	for _, service := range services {
		schema, err := fetchSchema(ctx, newExecs[service], nil)
		require.NoError(t, err)
		err = writeSchemaToFile(service, schema.Result)
		require.NoError(t, err)
	}
	schemaSyncer := newFileSchemaSyncer(ctx, services)
	e, err := NewExecutor(ctx, newExecs, &SchemaSyncerConfig{
		SchemaSyncer:              schemaSyncer,
		SchemaSyncIntervalSeconds: func(ctx context.Context) int64 { return 100 },
	})
	require.NoError(t, err)
	return e
}

func createSchemasWithFederatedUser(t *testing.T) (*schemabuilder.Schema, *schemabuilder.Schema, *Executor) {
	type User struct {
		Id    int64
		OrgId int64
		Name  string
	}
	type UserKey struct {
		Id    int64
		OrgId int64
	}
	s1 := schemabuilder.NewSchemaWithName("schema1")
	user := s1.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKey }) []*User {
		users := make([]*User, 0, len(args.Keys))
		for _, key := range args.Keys {
			users = append(users, &User{Id: key.Id, OrgId: key.OrgId, Name: "Bob"})
		}
		return users
	}))
	user.Key("id")
	user.FieldFunc("isCool2", func(ctx context.Context, user *User) (bool, error) { return true, nil })
	s1.Query().FieldFunc("users", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "bob"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "bob"})
		return users, nil
	})

	s2 := schemabuilder.NewSchemaWithName("schema2")
	user2 := s2.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKey }) []*User {
		users := make([]*User, 0, len(args.Keys))
		for _, key := range args.Keys {
			users = append(users, &User{Id: key.Id, OrgId: key.OrgId, Name: "Bob"})
		}
		return users
	}))
	user2.Key("id")
	user2.FieldFunc("isCool", func(ctx context.Context, user *User) (bool, error) { return true, nil })
	s2.Query().FieldFunc("users2", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "bob"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "bob"})
		return users, nil
	})
	e := updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2,
	})
	return s1, s2, e
}

func TestDeletingFederatedKey(t *testing.T) {
	ctx := context.Background()
	s1, s2, e := createSchemasWithFederatedUser(t)
	query := `query Foo {
					users {
						isCool
					}
					users2 {
						isCool2
					}
				}`
	expectedOutput := `{
					"users":[
						{
							"__key":1,
							"isCool":true
						},
						{
							"__key":2,
							"isCool":true
						}
					],
					"users2":[
						{
							"__key":1,
							"isCool2":true
						},
						{
							"__key":2,
							"isCool2":true
						}
					]
				}`

	// Run a federated query and ensure that it works
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 1: s2 no longer requests "orgId" as a key, gateway doesnt know
	type User struct {
		Id    int64
		OrgId int64
		Name  string
	}
	type UserKey2 struct {
		Id int64
	}
	s2New := schemabuilder.NewSchemaWithName("schema2")
	user2New := s2New.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKey2 }) []*User {
		users := make([]*User, 0, len(args.Keys))
		for _, key := range args.Keys {
			users = append(users, &User{Id: key.Id, OrgId: key.Id, Name: "Bob"})
		}
		return users
	}))
	user2New.Key("id")
	user2New.FieldFunc("isCool", func(ctx context.Context, user *User) (bool, error) { return true, nil })
	s2New.Query().FieldFunc("users2", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1)})
		users = append(users, &User{Id: int64(2), OrgId: int64(2)})
		return users, nil
	})
	newExecs, err := makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2New,
	})
	require.NoError(t, err)
	e.Executors = newExecs
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 2: The s2 user schema no longer requests the field "orgId", gateway knows about the schema update
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2New,
	})
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2,
	})

	// Test 3: s1 user schema no longer reqyests the field "orgId", gateway doesnt know about the schema update
	s1New := schemabuilder.NewSchemaWithName("schema1")
	user2 := s1New.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKey2 }) []*User {
		users := make([]*User, 0, len(args.Keys))
		for _, key := range args.Keys {
			users = append(users, &User{Id: key.Id, OrgId: key.Id, Name: "Bob"})
		}
		return users
	}))
	user2.Key("id")
	user2.FieldFunc("isCool2", func(ctx context.Context, user *User) (bool, error) { return true, nil })
	s1New.Query().FieldFunc("users", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1)})
		users = append(users, &User{Id: int64(2), OrgId: int64(2)})
		return users, nil
	})
	newExecs, err = makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2,
	})
	require.NoError(t, err)
	e.Executors = newExecs
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 4: The s1 user schema no longer requests the field "orgId", gateway knows about the schema update
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2,
	})
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2,
	})

	// Test 5: The s1 and s2 schema both no longer request "orgId", gateway doesnt know about it
	newExecs, err = makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2New,
	})
	require.NoError(t, err)
	e.Executors = newExecs
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 6: The s1 and s2 schema both no longer request "orgId", gateway knows about it
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2New,
	})
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
}

func TestAddingFederatedKey(t *testing.T) {
	ctx := context.Background()
	s1, s2, e := createSchemasWithFederatedUser(t)
	query := `query Foo {
					users {
						isCool
					}
					users2 {
						isCool2
					}
				}`
	expectedOutput := `{
					"users":[
						{
							"__key":1,
							"isCool":true
						},
						{
							"__key":2,
							"isCool":true
						}
					],
					"users2":[
						{
							"__key":1,
							"isCool2":true
						},
						{
							"__key":2,
							"isCool2":true
						}
					]
				}`

	// Run a federated query and ensure that it works
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 1: s2 requests new optional field "name" as a key, gateway doesnt know about the schema update
	type User struct {
		Id    int64
		OrgId int64
		Name  string
	}
	type UserKey2 struct {
		Id    int64
		OrgId int64
		Name  string `graphql:",optional"`
	}
	s2New := schemabuilder.NewSchemaWithName("schema2")
	user2New := s2New.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKey2 }) []*User {
		users := make([]*User, 0, len(args.Keys))
		for _, key := range args.Keys {
			users = append(users, &User{Id: key.Id, OrgId: key.OrgId, Name: key.Name})
		}
		return users
	}))
	user2New.Key("id")
	user2New.FieldFunc("isCool", func(ctx context.Context, user *User) (bool, error) { return true, nil })
	s2New.Query().FieldFunc("users2", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "bob"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "bob"})
		return users, nil
	})
	newExecs, err := makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2New,
	})
	require.NoError(t, err)
	e.Executors = newExecs
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 2: s2 requests new optional field "name" as a key, gateway knows about the schema update
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2New,
	})
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2,
	})

	// Test 3: s1 requests new optional field "name" as a key, gateway doesnt know about the schema update
	s1New := schemabuilder.NewSchemaWithName("schema1")
	user2 := s1New.Object("User", User{}, schemabuilder.FetchObjectFromKeys(func(args struct{ Keys []*UserKey2 }) []*User {
		users := make([]*User, 0, len(args.Keys))
		for _, key := range args.Keys {
			users = append(users, &User{Id: key.Id, OrgId: key.Id, Name: "Bob"})
		}
		return users
	}))
	user2.Key("id")
	user2.FieldFunc("isCool2", func(ctx context.Context, user *User) (bool, error) { return true, nil })
	s1New.Query().FieldFunc("users", func(ctx context.Context) ([]*User, error) {
		users := make([]*User, 0, 1)
		users = append(users, &User{Id: int64(1), OrgId: int64(1), Name: "bob"})
		users = append(users, &User{Id: int64(2), OrgId: int64(2), Name: "bob"})
		return users, nil
	})
	newExecs, err = makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2,
	})
	require.NoError(t, err)
	e.Executors = newExecs
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 4: The s1 user schema requests the new field "name", gateway knows about the schema update
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2,
	})
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1,
		"schema2": s2,
	})

	// Test 5: The s1 and s2 schema both request "name", gateway doesnt know about it
	newExecs, err = makeExecutors(map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2New,
	})
	require.NoError(t, err)
	e.Executors = newExecs
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)

	// Test 6: The s1 and s2 schema both request "name", gateway knows about it
	updateSchemaFiles(t, map[string]*schemabuilder.Schema{
		"schema1": s1New,
		"schema2": s2New,
	})
	runAndValidateQueryResults(t, ctx, e, query, expectedOutput)
}


text:
<?php declare(strict_types=1);

namespace Star\BacklogVelocity\Agile\Infrastructure\Persistence\InMemory;

use Star\BacklogVelocity\Agile\BacklogPlugin;
use Star\BacklogVelocity\Agile\RepositoryManager;
use Star\BacklogVelocity\Cli\BacklogApplication;

final class InMemoryPlugin implements BacklogPlugin
{
    /**
     * Returns the repository manager.
     *
     * @return RepositoryManager
     */
    public function getRepositoryManager()
    {
        return new CollectionManager();
    }

    /**
     * Hook to inject custom application changes.
     *
     * @param BacklogApplication $application
     */
    public function build(BacklogApplication $application)
    {
        throw new \RuntimeException('Method ' . __METHOD__ . ' not implemented yet.');
    }
}


text:
package br.com.gabrielmalakias.mqtt;

import br.com.gabrielmalakias.converter.StringToOutputMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class Publisher {
    private final Client client;

    @Autowired
    public Publisher(Client client) {
        this.client = client;
    }

    public boolean send(String message) {
        return Optional.ofNullable(message)
                .map(this::toOutputMessage)
                .map(this::publish)
                .get();
    }

    private OutputMessage toOutputMessage(String message) {
        return new StringToOutputMessage().convert(message);
    }

    private boolean publish(OutputMessage outputMessage) {
        String topic = outputMessage.getType() + "/" + outputMessage.getIdentifier();
        return client.publish(topic, outputMessage.getValue());
    }
}


text:
<?php

namespace Escher;

class Provider
{
    private $credentialScope;
    private $escherKey;
    private $escherSecret;
    private $keyDB;

    public function __construct($credentialScope, $escherKey, $escherSecret, $keyDB)
    {
        $this->credentialScope = $credentialScope;
        $this->escherKey = $escherKey;
        $this->escherSecret = $escherSecret;
        $this->keyDB = $keyDB;
    }

    /**
     * @return Escher
     */
    public function createEscher()
    {
        return Escher::create($this->credentialScope)
            ->setAlgoPrefix('EMS')
            ->setVendorKey('EMS')
            ->setAuthHeaderKey('X-Ems-Auth')
            ->setDateHeaderKey('X-Ems-Date');
    }

    /**
     * @return string
     */
    public function getEscherKey()
    {
        return $this->escherKey;
    }

    /**
     * @return string
     */
    public function getEscherSecret()
    {
        return $this->escherSecret;
    }

    /**
     * @return \ArrayAccess|array
     */
    public function getKeyDB()
    {
        return $this->keyDB;
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

module LimitedHashMapSpec where

import           Control.Arrow           ((&&&))
import           Control.Concurrent.MVar (MVar, newMVar, readMVar, swapMVar)
import           Control.Monad           (liftM, when)
import           Data.Maybe              (isJust, isNothing)

import           Control.Lens            (view, (^.))
import           Data.ByteString         (ByteString)
import qualified Data.HashMap.Lazy       as HML
import           Data.Time.Clock.POSIX   (getPOSIXTime)
import           Test.Hspec
import           Test.HUnit.Base         (assertFailure)

import           LimitedHashMap

-- | Point a fresh LHM before every test case
resetLHM :: MVar LimitedHashMap -> IO ()
resetLHM mv = do
  swapMVar mv $ initialLHM 2
  return ()

-- | Get the easily predictable parts of a value
testValue :: Maybe Value -> Maybe (ByteString, Int)
testValue = liftM (view value &&& view flags)

spec :: Spec
spec = do
  mlhm <- runIO . newMVar $ initialLHM 2
  before_ (resetLHM mlhm) $ do

    it "initializes to the proper state" $ do
      lhm <- readMVar mlhm
      lhm^.maxSize `shouldBe` 2
      lhm^.mru `shouldBe` []

    it "can set and get multiple key-value-pairs" $ do
      set mlhm "1" 0 10 "one"
      set mlhm "2" 7 10 "two"
      liftM testValue (get mlhm "1") `shouldReturn` Just ("one", 0)
      liftM testValue (get mlhm "2") `shouldReturn` Just ("two", 7)

    it "sets the proper time-to-live" $ do
      now <- getPOSIXTime
      set mlhm "1" 0 60 "one"
      set mlhm "2" 0 (now + 10) "two" -- Large values are considered unix time
      lhm <- readMVar mlhm
      case get' lhm "1" of
        Nothing  -> assertFailure "Did not find deposited value"
        Just val -> val^.ttl - now `shouldSatisfy` (\t -> t > 59 && t < 61)
      case get' lhm "2" of
        Nothing  -> assertFailure "Did not find deposited value"
        Just val -> val^.ttl - now `shouldSatisfy` (\t -> t > 9 && t < 11)

    it "can append and prepend values to existing values" $ do
      set mlhm "1" 0 60 "one"
      append mlhm "1" "toe"
      prepend mlhm "1" "ice"
      liftM testValue (get mlhm "1") `shouldReturn` Just ("iceonetoe", 0)

    it "can touch values" $ do
      set mlhm "1" 0 60 "one"
      now <- getPOSIXTime
      lhm <- readMVar mlhm
      case get' lhm "1" of
        Nothing  -> assertFailure "Did not find deposited value"
        Just val -> val^.ttl - now `shouldSatisfy` (\t -> t > 59 && t < 61)
      touch mlhm "1" 10
      lhm <- readMVar mlhm
      case get' lhm "1" of
        Nothing  -> assertFailure "Did not find deposited value"
        Just val -> val^.ttl - now `shouldSatisfy` (\t -> t > 9 && t < 11)

    it "recognizes non-existent keys" $
      liftM testValue (get mlhm "1") `shouldReturn` Nothing

    it "deletes the least recently set key when full" $ do
      set mlhm "1" 0 10 "one"
      set mlhm "2" 0 10 "two"
      set mlhm "3" 0 10 "thr"
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 2
      length (lhm^.mru) `shouldBe` 2
      liftM testValue (get mlhm "1") `shouldReturn` Nothing
      liftM testValue (get mlhm "2") `shouldReturn` Just ("two", 0)
      liftM testValue (get mlhm "3") `shouldReturn` Just ("thr", 0)

    it "deletes the least recently gotten key when full" $ do
      set mlhm "1" 0 10 "one"
      set mlhm "2" 0 10 "two"
      get mlhm "1"
      set mlhm "3" 0 10 "thr"
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 2
      length (lhm^.mru) `shouldBe` 2
      liftM testValue (get mlhm "1") `shouldReturn` Just ("one", 0)
      liftM testValue (get mlhm "2") `shouldReturn` Nothing
      liftM testValue (get mlhm "3") `shouldReturn` Just ("thr", 0)

    it "does not delete keys when updating existing ones" $ do
      set mlhm "1" 0 10 "one"
      set mlhm "2" 0 10 "two"
      set mlhm "1" 0 10 "uno"
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 2
      length (lhm^.mru) `shouldBe` 2
      liftM testValue (get mlhm "1") `shouldReturn` Just ("uno", 0)
      liftM testValue (get mlhm "2") `shouldReturn` Just ("two", 0)

    it "updates the most recently used list to reflect queries" $ do
      set mlhm "1" 0 10 "one"
      set mlhm "2" 0 10 "two"
      set mlhm "1" 0 10 "uno"
      lhm <- readMVar mlhm
      lhm^.mru `shouldBe` ["2","1"]

    it "does not return expired KVPs" $ do
      set mlhm "1" 0 (-1) "one"
      liftM testValue (get mlhm "1") `shouldReturn` Nothing

    it "can delete a KVP from both the hashmap and the mru" $ do
      set mlhm "1" 0 10 "one"
      delete mlhm "1"
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 0
      length (lhm^.mru) `shouldBe` 0
      liftM testValue (get mlhm "1") `shouldReturn` Nothing

    it "does not delete any KVP if the desired one does not exist" $ do
      set mlhm "1" 0 10 "one"
      delete mlhm "2"
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 1
      length (lhm^.mru) `shouldBe` 1
      liftM testValue (get mlhm "1") `shouldReturn` Just ("one", 0)

    it "deletes expired KVPs when encountered" $ do
      set mlhm "1" 0 (-1) "one"
      liftM testValue (get mlhm "1") `shouldReturn` Nothing
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 0
      length (lhm^.mru) `shouldBe` 0

    it "cleans up expired KVPs when ordered to" $ do
      set mlhm "1" 0 (-1) "one"
      set mlhm "2" 0 10 "two"
      cleanup mlhm
      liftM testValue (get mlhm "2") `shouldReturn` Just ("two", 0)
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 1
      length (lhm^.mru) `shouldBe` 1

    it "flushes when ordered to" $ do
      set mlhm "2" 0 10 "two"
      flush mlhm 0
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 0
      length (lhm^.mru) `shouldBe` 0

    it "flushed only KVPs that are valid long enough" $ do
      set mlhm "1" 0 8 "one"
      set mlhm "2" 0 12 "two"
      flush mlhm 10
      isMember mlhm "1" `shouldReturn` True
      lhm <- readMVar mlhm
      HML.size (lhm^.hashMap) `shouldBe` 1
      length (lhm^.mru) `shouldBe` 1

    it "increases the global counter when using a unique number" $ do
      old <- getUnique mlhm
      new <- getUnique mlhm
      new - old `shouldBe` 1

    it "increases the unique number when performing modifying opearations" $ do
      set mlhm "1" 0 8 "one"
      value <- get mlhm "1"
      lhm <- readMVar mlhm
      let value = get' lhm "1"
      case value of
        Nothing  -> assertFailure "Nothing returned"
        Just val -> do
          let old = val^.uniq
          updateUnique mlhm "1"
          lhm <- readMVar mlhm
          let value = get' lhm "1"
          case value of
            Nothing  -> assertFailure "Nothing returned"
            Just val -> val^.uniq - old `shouldBe` 1

    context "when incrementing values" $ do
      it "updates the mru" $ do
        set mlhm "one" 0 8 "1"
        set mlhm "two" 0 8 "2"
        view mru <$> readMVar mlhm `shouldReturn` ["one","two"]
        incr mlhm "one" 2 `shouldReturn` "3"
        view mru <$> readMVar mlhm `shouldReturn` ["two","one"]

      it "increments values properly" $
        doIncr 2 (Value "8" 0 0 0) `shouldBe` Value "10" 0 0 0

      it "wraps at the 64-bit mark" $
        doIncr 3 (Value "18446744073709551615" 0 0 0) `shouldBe` Value "2" 0 0 0

    context "when decrementing values" $ do
      it "updates the mru" $ do
        set mlhm "one" 0 8 "5"
        set mlhm "two" 0 8 "2"
        view mru <$> readMVar mlhm `shouldReturn` ["one","two"]
        decr mlhm "one" 2 `shouldReturn` "3"
        view mru <$> readMVar mlhm `shouldReturn` ["two","one"]

      it "decrements values properly" $
        doDecr 3 (Value "12" 0 0 0) `shouldBe` Value "9" 0 0 0

      it "does not decrement further than zero" $
        doDecr 5 (Value "3" 0 0 0) `shouldBe` Value "0" 0 0 0

      it "does not decrement values that are already zero" $
        doDecr 5 (Value "0" 0 0 0) `shouldBe` Value "0" 0 0 0

{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}


text:
OS = LINUX
#OS = MACOSX
#OS = WINDOWS

ifeq ($(OS), LINUX)
CC = gcc
CFLAGS = -Wall -O2 -DLINUX
TARGET = receive_test_mod

else ifeq ($(OS), MACOSX)
CC = gcc
CFLAGS = -Wall -O2 -DMACOSX
TARGET = receive_test_mod

else ifeq ($(OS), WINDOWS)
CC = i586-mingw32msvc-gcc
CFLAGS = -Wall -O2 -DWINDOWS
TARGET = receive_test_mod.exe
endif

all: $(TARGET)

$(TARGET): receive_test_mod.c ModMakefile
	$(CC) $(CFLAGS) -o $(TARGET) receive_test_mod.c

clean:
	rm -f receive_test_mod receive_test_mod.exe


text:
<?php

namespace Pathetic\TgBot\Tests\Types;

use Pathetic\TgBot\Types\Video;
use Pathetic\TgBot\Types\PhotoSize;

class VideoTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Pathetic\TgBot\Types\Video
     */
    protected $video;

    public function setUp()
    {
        $this->video = new Video([
            'file_id' => 'BQADAgADAwAD3xCtBYugqH4D2MqwAg',
            'width' => 960,
            'height' => 720,
            'duration' => 1,
            'thumb' => [],
            'mime_type' => 'video/mp4',
            'file_size' => 38
        ]);
    }

    public function testFileId()
    {
        $this->assertAttributeEquals('BQADAgADAwAD3xCtBYugqH4D2MqwAg', 'file_id', $this->video);
    }

    public function testWidth()
    {
        $this->assertAttributeEquals(960, 'width', $this->video);
    }

    public function testHeight()
    {
        $this->assertAttributeEquals(720, 'height', $this->video);
    }

    public function testDuration()
    {
        $this->assertAttributeEquals(1, 'duration', $this->video);
    }

    public function testThumb()
    {
        $this->assertAttributeInstanceOf(PhotoSize::class, 'thumb', $this->video);
    }

    public function testMimeType()
    {
        $this->assertAttributeEquals('video/mp4', 'mime_type', $this->video);
    }

    public function testFileSize()
    {
        $this->assertAttributeEquals(38, 'file_size', $this->video);
    }
}


text:
// Copyright 2015-2018 Sound Metrics Corp. All Rights Reserved.

using System.Diagnostics;
using System.Text;

namespace SoundMetrics.Aris.Files
{
    /// <summary>
    /// Provides a means of return error information to a caller.
    /// The text assigned may be appened. This is an immutable struct.
    /// </summary>
    public struct ErrorInfo
    {
        /// <summary>
        /// Text describing the error condition.
        /// </summary>
        public string Text { get { return _builder.ToString(); } }

        private ErrorInfo(StringBuilder builder) => _builder = builder;

        private readonly StringBuilder _builder;

        /// <summary>
        /// Creates a new instance.
        /// </summary>
        /// <param name="text">Text describing the error condition.</param>
        /// <returns>A new instance.</returns>
        public static ErrorInfo Create(string text)
        {
            var sb = new StringBuilder(text);
            return new ErrorInfo(sb);
        }

        /// <summary>
        /// Appends additional text describing the error condition.
        /// </summary>
        /// <param name="text">Text describing the error condition.</param>
        /// <returns>A new instance.</returns>
        public ErrorInfo Append(string text)
        {
            var sb = this._builder;
            sb.AppendLine();
            sb.Append(text);
            return new ErrorInfo(sb);
        }
    }
}


text:
package info.xiaomo.core.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import info.xiaomo.core.untils.TimeUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author : xiaomo
 */
public class CustomDateSerializerFilter extends JsonSerializer<Date> {

    @Override
    public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat(TimeUtil.DEFAULT_FORMAT2);
        jsonGenerator.writeString(sdf.format(value));
    }
}


text:
package registry.annotation;

import java.lang.annotation.*;

/**
 * Created by anzhen on 2016/5/1.
 */
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface NotEmpty {

    String message() default "";
}