text:
const Backbone = require('backbone');
const _ = require('underscore');
const LikeModel = require('dashboard/data/like-model');
const UserModel = require('dashboard/data/user-model');
const PermissionModel = require('dashboard/data/permission-model');
const MapModel = require('dashboard/data/map-model');
const VisualizationOrderModel = require('dashboard/data/visualization-order-model');
const SlideTransition = require('dashboard/data/slide-transition-model');
const MapUrlModel = require('dashboard/data/map-url-model');
const DatasetUrlModel = require('dashboard/data/dataset-url-model');
const UrlModel = require('dashboard/data/url-model');
const CartoTableMetadata = require('dashboard/views/public-dataset/carto-table-metadata');
const checkAndBuildOpts = require('builder/helpers/required-opts');

const REQUIRED_OPTS = [
  'configModel'
];

const PRIVACY_OPTIONS = {
  default: {
    public: 'PUBLIC',
    link: 'LINK',
    private: 'PRIVATE',
    password: 'PASSWORD'
  },
  kuviz: {
    public: 'PUBLIC',
    password: 'PASSWORD'
  }
};

const VISUALIZATON_TYPES = [
  'derived',
  'kuviz',
  'slide'
];

const VisualizationModel = Backbone.Model.extend({

  defaults: {
    bindMap: true
  },

  INHERIT_TABLE_ATTRIBUTES: [
    'name', 'description', 'privacy'
  ],

  initialize: function (attrs, opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this.type = this.get('type');
    if (this.type !== 'kuviz') {
      this.map = new MapModel({ configModel: this._configModel });
      if (this.get('bindMap')) this._bindMap();
    }

    this._privacyOptions = (this.type === 'kuviz') ? PRIVACY_OPTIONS[this.type] : PRIVACY_OPTIONS['default'];
    this.permission = new PermissionModel(this.get('permission'), { configModel: this._configModel });
    this.order = new VisualizationOrderModel({ visualization: this });
    this.transition = new SlideTransition(this.get('transition_options'), { parse: true });

    this.like = LikeModel.newByVisData({
      vis_id: this.id,
      liked: this.get('liked'),
      likes: this.get('likes'),
      config: this._configModel
    });

    this._initBinds();
  },

  _initBinds: function () {
    this.permission.acl.bind('reset', function () {
      // Sync the local permission object w/ the raw data, so vis.save don't accidentally overwrites permissions changes
      this.set('permission', this.permission.attributes, { silent: true });
      this.trigger('change:permission', this);
    }, this);

    // Keep permission model in sync, e.g. on vis.save
    this.bind('change:permission', function () {
      this.permission.set(this.get('permission'));
    }, this);
  },

  _bindMap: function () {
    this.on('change:map_id', this._fetchMap, this);

    this.map.bind('change:id', function () {
      this.set('map_id', this.map.id);
    }, this);

    this.map.set('id', this.get('map_id'));
  },

  url: function (method) {
    var version = this._configModel.urlVersion('visualization', method);
    var base = '/api/' + version + '/viz';
    if (this.isNew()) {
      return base;
    }
    return base + '/' + this.id;
  },

  parse: function (data) {
    if (this.transition && data.transition_options) {
      this.transition.set(this.transition.parse(data.transition_options));
    }

    if (this.like) {
      this.like.set({
        vis_id: this.id,
        likes: this.get('likes'),
        liked: this.get('liked')
      });
    }

    if (this.owner) {
      this.owner = new UserModel(this.owner);
    }

    return data;
  },

  toJSON: function () {
    var attr = _.clone(this.attributes);

    delete attr.bindMap;
    delete attr.stats;
    delete attr.related_tables;
    delete attr.children;

    attr.transition_options = this.transition.toJSON();

    return attr;
  },

  getLikesModel: function () {
    return this.like;
  },

  /**
   *  Create a copy of the visualization model
   */
  copy: function (attrs, options) {
    attrs = attrs || {};
    options = options || {};
    var vis = new VisualizationModel(
      _.extend({
        source_visualization_id: this.id
      },
      attrs
      ),
      { configModel: this._configModel }
    );
    vis.save(null, options);
    return vis;
  },

  /**
   *  Fetch map information
   */
  _fetchMap: function () {
    this.map
      .set('id', this.get('map_id'))
      .fetch();
  },

  /**
   * Get the URL for current instance.
   * @param {Object} currentUser (Optional) Get the URL from the perspective of the current user, necessary to
   *   correctly setup URLs to tables.
   * @return {Object} instance of cdb.common.Url
   */
  viewUrl: function (currentUser) {
    const owner = this.permission.owner;
    let userUrl = this.permission.owner.viewUrl();

    // the undefined check is required for backward compability, in some cases (e.g. dependant visualizations) the type
    // is not available on the attrs, if so assume the old behavior (e.g. it's a visualization/derived/map).
    if (this.isVisualization() || _.isUndefined(this.get('type'))) {
      let id = this.get('id');

      if (this.get('type') === 'kuviz') {
        return new UrlModel({
          base_url: userUrl.urlToPath('kuviz', id)
        });
      }

      if (currentUser && currentUser.id !== owner.id && this.permission.hasAccess(currentUser)) {
        userUrl = currentUser.viewUrl();
        id = owner.get('username') + '.' + id;
      }

      return new MapUrlModel({
        base_url: userUrl.urlToPath('viz', id)
      });
    } else {
      if (currentUser && this.permission.hasAccess(currentUser)) {
        userUrl = currentUser.viewUrl();
      }
      return new DatasetUrlModel({
        base_url: userUrl.urlToPath('tables', this.tableMetadata().getUnquotedName())
      });
    }
  },

  // return: Array of entities (user or organizations) this vis is shared with
  sharedWithEntities: function () {
    return _.map((this.permission.acl.toArray() || []), function (aclItem) {
      return aclItem.get('entity');
    });
  },

  /**
   *  Is this model a true visualization?
   */
  isVisualization: function () {
    const type = this.get('type');
    return VISUALIZATON_TYPES.indexOf(type) > -1;
  },

  /**
   * Get table metadata related to this vis.
   * Note that you might need to do a {metadata.fetch()} to get full data.
   *
   * @returns {CartoTableMetadata} if this vis represents a table
   * TODO: when and when isn't it required to do a fetch really?
   */
  tableMetadata: function () {
    if (!this._metadata) {
      this._metadata = new CartoTableMetadata(this.get('table'), { configModel: this._configModel });
    }
    return this._metadata;
  },

  getTableModel: function () {
    if (!this._metadata) {
      this._metadata = new CartoTableMetadata(this.get('table'), { configModel: this._configModel });
    }
    return this._metadata;
  },

  privacyOptions: function () {
    const privacyOptionsValues = _.values(this._privacyOptions);

    if (this.isVisualization()) {
      return privacyOptionsValues;
    } else {
      return _.filter(privacyOptionsValues, option => option !== 'PASSWORD');
    }
  },

  isRaster: function () {
    return this.get('kind') === 'raster';
  },

  getPermissionModel: function () {
    return this.permission;
  },

  getSynchronizationModel: function () {
    return this._synchronizationModel;
  },

  mapcapsURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v3/viz/' + this.id + '/mapcaps';
  }
}, {
  isPubliclyAvailable: function (privacyStatus) {
    return privacyStatus === PRIVACY_OPTIONS['default'].password ||
           privacyStatus === PRIVACY_OPTIONS['default'].link ||
           privacyStatus === PRIVACY_OPTIONS['default'].public;
  }
});

module.exports = VisualizationModel;


text:
using System;
using System.IO;
using System.Reflection;
using Entitas.CodeGenerator;

class GenerateTestComponents {
    public static void Main(string[] args) {
        generate();
    }

    static void generate() {
        var assembly = Assembly.GetAssembly(typeof(SomeComponent));
        var generatedFolder = getEntitasProjectDir() + "/Tests/Tests/Entitas/CodeGenerator/Fixtures/Generated/";

        var codeGenerators = new ICodeGenerator[] {
            new ComponentExtensionsGenerator(),
            new ComponentIndicesGenerator(),
            new PoolAttributesGenerator(),
            new PoolsGenerator()
        };

        var provider = new TypeReflectionProvider(assembly.GetTypes(), new string[0], new string[0]);
        var files = CodeGenerator.Generate(provider, generatedFolder, codeGenerators);

        foreach (var file in files) {
            Console.WriteLine("Generated: " + file.fileName);
        }

        Console.WriteLine("Done. Press any key...");
        Console.Read();
    }

    static string getEntitasProjectDir() {
        var dirInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
        const string projectName = "Tests";
        while (dirInfo.Name != projectName) {
            dirInfo = dirInfo.Parent;
        }

        return dirInfo.Parent.FullName;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Client\V1\Rest\Client;

class ClientResourceFactory
{
    public function __invoke($services)
    {
        return new ClientResource();
    }
}


text:
/*
 * Created by Yuriy Stul 17 May 2018
 */
package com.stulsoft.poc.prometheus.manager;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.hotspot.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Objects;

/**
 * Prometheus metrics manager.
 *

 * Example 1 (without default metrics):
 *
 *

 * {@code
 * // Add new counter
 * MetricsManager.getInstance().addCounter(SERVICE_NAME, COUNTER_NAME_GETS, "Counts all gets");
 * ...
 * // Increment counter
 * MetricsManager.getInstance().getCounter(SERVICE_NAME, COUNTER_NAME_GETS).inc();
 * }
 *

 *

 * Example 2 (with default metrics):
 *
 *

 * {@code
 * ...
 * // Initialize default metrics
 * MetricsManager.getInstance().initDefaultMetrics();
 * ...
 * // Add new counter
 * MetricsManager.getInstance().addCounter(SERVICE_NAME, COUNTER_NAME_GETS, "Counts all gets");
 * ...
 * // Increment counter
 * MetricsManager.getInstance().getCounter(SERVICE_NAME, COUNTER_NAME_GETS).inc();
 * }
 *

 *

 * Activating "/metrics" handler:
 *
 *

 * {@code
 * ...
 * Router router = Router.router(vertx);
 * router.get("/metrics").handler(MetricsManager.getInstance().getMetricsHandler());
 * }
 *

 *
 * @author Yuriy Stul
 */
public class MetricsManager {
	private static final Logger logger = LoggerFactory.getLogger(MetricsManager.class);
	private static boolean defaultMetricsInitialized = false;
	private static final Object lock = new Object();
	private static MetricsManager instance = null;

	public static final String METRICS_NAME_PREFIX = "webpals";

	private final CollectorRegistry registry;
	private final HashMap<String, Counter> counters;
	private final HashMap<String, Gauge> gauges;
	private final MetricsHandler metricsHandler;

	/**
	 * Initializes a new instance of the MetricsManager class.
	 */
	private MetricsManager() {
		registry = new CollectorRegistry();
		counters = new HashMap<>();
		gauges = new HashMap<>();
		metricsHandler = new MetricsHandler(registry);
	}

	/**
	 * Returns full metrics name in the format PREFIX_SERVICENAME_METRICSNAME
	 *
	 * @param serviceName
	 *            the service name
	 * @param metricsName
	 *            the metrics name
	 * @return full metrics name in the format PREFIX_SERVICENAME_METRICSNAME
	 */
	private String buildMetricsName(final String serviceName, final String metricsName) {
		return Counter.sanitizeMetricName(String.format("%s_%s_%s", METRICS_NAME_PREFIX, serviceName, metricsName));
	}

	/**
	 * Initializes a default JVM metrics.
	 */
	public void initDefaultMetrics() {
		if (!defaultMetricsInitialized) {
			synchronized (lock) {
				if (!defaultMetricsInitialized) {
					logger.info("Initializing default exports...");
					new StandardExports().register(registry);
					new MemoryPoolsExports().register(registry);
					new BufferPoolsExports().register(registry);
					new GarbageCollectorExports().register(registry);
					new ThreadExports().register(registry);
					new ClassLoadingExports().register(registry);
					new VersionInfoExports().register(registry);
					defaultMetricsInitialized = true;
					logger.info("Initialized default exports.");
				}
			}
		}
	}

	/**
	 * Returns an instance of the MetricsManager class.
	 *
	 * @return the instance of the MetricsManager class.
	 */
	public static MetricsManager getInstance() {
		if (instance == null) {
			synchronized (lock) {
				if (instance == null) {
					instance = new MetricsManager();
				}
			}
		}
		return instance;
	}

	public MetricsHandler getMetricsHandler() {
		return metricsHandler;
	}

	/**
	 * Adds a new Counter.
	 *
	 *

	 * If a counter with same service and counter names already exists then the
	 * method returns existing counter. Otherwise the method creates new counter and
	 * returns created counter.
	 *

	 *
	 * @param serviceName
	 *            specifies the service name
	 * @param counterName
	 *            specifies the counter name
	 * @param description
	 *            specifies the description
	 * @param labelNames
	 *            optional, specifies labels
	 * @return the Counter
	 */
	public Counter addCounter(final String serviceName, final String counterName, final String description,
			final String... labelNames) {
		Objects.requireNonNull(serviceName, "serviceName should be defined");
		Objects.requireNonNull(counterName, "counterName should be defined");
		Objects.requireNonNull(description, "description should be defined");
		final String fullMetricsName = buildMetricsName(serviceName, counterName);
		Counter counter = counters.get(fullMetricsName);
		if (counter == null) {
			synchronized (lock) {
				if (counter == null) {
					Counter.Builder builder = Counter
							.build(fullMetricsName, description);
					if (labelNames != null && labelNames.length > 0) {
						builder.labelNames(labelNames);
					}

					counter = builder.register(registry);
					counters.put(fullMetricsName, counter);
				}
			}
		}
		return counter;
	}

	/**
	 * Returns a Counter for specified service and counter names.
	 *
	 * @param serviceName
	 *            specifies service
	 * @param counterName
	 *            specifies counter
	 * @return the Counter for specified service and counter names.
	 * @throws RuntimeException
	 *             if no counter exists
	 */
	public Counter getCounter(final String serviceName, final String counterName) {
		final String fullMetricsName = buildMetricsName(serviceName, counterName);
		Counter counter = counters.get(fullMetricsName);
		if (counter == null) {
			final String message = String.format("Counter with service name %s and counter name %s doesn't exist.",
					serviceName, counterName);
			logger.error(message);
			throw new RuntimeException(message);
		}
		return counter;
	}

	/**
	 * Adds a new Gauge.
	 *
	 *

	 * If a gauge with same service and counter names already exists then the method
	 * returns existing gauge. Otherwise the method creates new gauge and returns
	 * created gauge.
	 *

	 *
	 * @param serviceName
	 *            specifies the service name
	 * @param counterName
	 *            specifies the counter name
	 * @param description
	 *            specifies the description
	 * @param labelNames
	 *            optional, specifies labels
	 * @return the Gauge
	 */
	public Gauge addGauge(final String serviceName, final String counterName, final String description,
			final String... labelNames) {
		Objects.requireNonNull(serviceName, "serviceName should be defined");
		Objects.requireNonNull(counterName, "counterName should be defined");
		Objects.requireNonNull(description, "description should be defined");
		final String fullMetricsName = buildMetricsName(serviceName, counterName);
		Gauge gauge = gauges.get(fullMetricsName);
		if (gauge == null) {
			synchronized (lock) {
				if (gauge == null) {
					Gauge.Builder builder = Gauge
							.build(fullMetricsName, description);
					if (labelNames != null && labelNames.length > 0) {
						builder.labelNames(labelNames);
					}

					gauge = builder.register(registry);
					gauges.put(fullMetricsName, gauge);
				}
			}
		}
		return gauge;
	}

	/**
	 * Returns a Gauge for specified service and counter names.
	 *
	 * @param serviceName
	 *            specifies service
	 * @param gaugeName
	 *            specifies gauge
	 * @return the Gauge for specified service and gauge names.
	 * @throws RuntimeException
	 *             if no gauge exists
	 */
	public Gauge getGauge(final String serviceName, final String gaugeName) {
		final String fullMetricsName = buildMetricsName(serviceName, gaugeName);
		Gauge gauge = gauges.get(fullMetricsName);
		if (gauge == null) {
			final String message = String.format("Gauge with service name %s and gauge name %s doesn't exist.",
					serviceName, gaugeName);
			logger.error(message);
			throw new RuntimeException(message);
		}
		return gauge;
	}
}


text:
import { browser, by, element, $ } from 'protractor';

export class LoginPage {
  id = $('input[name="id"]'); // $ is an alias for element(by.css())
  pwd = $('input[name="pwd"]');
  submit = element(by.buttonText('Login'));
  errMessage = element(by.id('errMessage'));

  login(id: string, password: string): void {
    this.id.sendKeys(id);
    this.pwd.sendKeys(password);
    this.submit.click();
  }
  navigateToLogin() {
    return browser.get('/login');
  }

  getErrorMessage() {
    return this.errMessage;
  }
}


text:
<title>
On the picket line
</title>

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

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

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

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

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

On the picket line

August 17, 2007 | Page 11

Police attack labor rights protest

By Brian Chidester

NORTH PROVIDENCE, R.I.--Police attacked a peaceful demonstration for labor rights August 11, pepper-spraying several protesters, arresting two and seriously injuring one of those arrested.

The protest of 40 people was called by the Providence chapter of the Industrial Workers of the World and included members of Students for a Democratic Society from Providence and Boston. The demonstrators were targeting Jacky's Galaxie restaurant, a pan-Asian restaurant that is supplied by HWH/Dragon Land Trading, a sweatshop operation based in New York.

Protesters were marching up Mineral Spring Avenue when police ordered them onto the side of the road or the sidewalk. Though the group complied, the police attacked some of the marchers without warning.

One, 22-year-old Alex Svoboda "was pinned down by the police during her arrest and suffered a broken and dislocated leg, and ruptured blood vessel in the knee. These injuries will require at least two surgeries and extensive rehab, and even then, may not completely repair the damage," wrote SDS activist Michael da Cruz in an e-mail.

As Green Party member Steve Lamarre described the scene, "Police say she was resisting, but aside from wanting to avoid broken glass, the only other 'resistance' I could discern was they were putting extreme pressure on her left leg, which snapped at the knee after two officers put enough of their weight on it."

North Providence police used an exaggerated estimate of 100 protesters to claim that they were outnumbered. They charged Svoboda with three counts of assaulting a police officer, and arrested her roommate Jason Friedmutter, charging him with obstruction of a police officer.

Activists plan to continue pickets at the North Providence restaurant and other locations. In addition, they are organizing a protest march in response to the violence of the police.

Messages of support and donations for Alex's medical and legal costs can be sent to: IWW Providence General Membership Branch, P.O. Box 5795, Providence, RI 02903. Pictures of the protest can be viewed online at jonathanmcintosh.smugmug.com/gallery/3293537.

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

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


text:
#include "saveable.h"

const Saveable::SAVE_FORMAT Saveable::DEFAULT_SAVE_FORMAT;

std::string Saveable::full_path() const
{
    return m_full_path;
}

Saveable::Saveable(){

}
/**
 * @brief Saveable::~Saveable
 * virtual destructor
 */
Saveable::~Saveable(){

}

/**
 * @brief FileHandler::save_saveable
 * @param savable
 * @param dir_path
 * @param save_format
 * @return Saves a Json file to provided directory with file_name and save_format
 */
bool Saveable::save_saveable(const std::string& file_name,
                             const std::string& dir_path, const SAVE_FORMAT& save_format){
    QDir dir;
    dir.mkpath(QString::fromStdString(dir_path)); // Make required directory path
    return save_saveable(dir_path + file_name, save_format); // Call with full path dir + "/file_name"
}

/**
 * @brief Saveable::save_saveable
 * @param full_path
 * @param save_format
 * @return true if successfull, false else
 */
bool Saveable::save_saveable(const std::string &full_path, const Saveable::SAVE_FORMAT &save_format) {
    m_full_path = full_path;
    QFile save_file(QString::fromStdString(full_path));
    if(!save_file.open(QIODevice::WriteOnly)){  // Attempt to open full_path
        qDebug() << "Couldn't open save file", save_file.fileName().toStdString().c_str();   // Send warning if unsuccessful
        return false;
    }
    QJsonObject json_saveable;                  // Data to be saved
    this->write(json_saveable);                 // Write data to be saved, OBS! Implement this when inheriting
    QJsonDocument save_doc(json_saveable);      // File to write to
    save_file.write(save_format == JSON         // Choose written format
            ? save_doc.toJson()
            : save_doc.toBinaryData());

    return true;
}

/**
 * @brief Saveable::delete_saveable
 * @return
 * Delete previously set path m_full_path
 * m_full_path is set by both save_saveable and load saveable
 */
bool Saveable::delete_saveable()
{
    QFile file(QString::fromStdString(m_full_path));
    if(file.exists()) return file.remove();
    qDebug() << "Couldn't delete file: " + QString::fromStdString(m_full_path);
    return false;
}

/**
 * @brief Saveable::load_savable
 * @param full savable path
 * @param save_format
 * @return loaded Savable
 * Loads saveable from binary or json file.
 */
bool Saveable::load_saveable(const std::string& full_path, const SAVE_FORMAT& save_format){
    m_full_path = full_path;
    QFile load_file(QString::fromStdString(full_path));
    if (!load_file.open(QIODevice::ReadOnly)) {     // Attempt to open file
        qWarning("Couldn't open load file %s ",
                 load_file.fileName().toStdString().c_str()); // Could not open file
        // Ur code handling failure
        return false;
    }
    QByteArray save_data = load_file.readAll();         // Read file to be loaded
    QJsonDocument load_doc(save_format == JSON          // Decide format to decode to
        ? QJsonDocument::fromJson(save_data)
        : QJsonDocument::fromBinaryData(save_data));
    this->read(load_doc.object());                      // Read data to be loaded, OBS! Implement this when inheriting

    return true;
}


text:
require 'spec_helper'

describe command('docker pull node:10.16.3-slim') do
  its(:exit_status) { should eq 0 }
end

describe command('docker run -t --rm node:10.16.3-slim node --version') do
  its(:stdout) { should match /v10.16.3/ }
#  its(:stderr) { should match /^$/ }
  its(:exit_status) { should eq 0 }
end


text:
"""Main entry point for toolchain_build buildbots.

Passes its arguments to toolchain_build.py.
"""

import optparse
import os
import subprocess
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import pynacl.platform

import packages

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
NACL_DIR = os.path.dirname(SCRIPT_DIR)
BUILD_DIR = os.path.join(NACL_DIR, 'build')
TOOLCHAIN_BUILD_DIR = os.path.join(NACL_DIR, 'toolchain_build')
TOOLCHAIN_BUILD_OUT_DIR = os.path.join(TOOLCHAIN_BUILD_DIR, 'out')
TOOLCHAIN_BUILD_PACKAGES = os.path.join(TOOLCHAIN_BUILD_OUT_DIR, 'packages')

PKG_VER = os.path.join(BUILD_DIR, 'package_version', 'package_version.py')
BUILDBOT_STANDARD = os.path.join(SCRIPT_DIR, 'buildbot_standard.py')

TEMP_TOOLCHAIN_DIR = os.path.join(TOOLCHAIN_BUILD_PACKAGES, 'output')
TEMP_PACKAGES_FILE = os.path.join(TOOLCHAIN_BUILD_OUT_DIR, 'packages.txt')

TOOLCHAIN_TESTS = {
#   TOOLCHAIN_NAME:    [(MODE,  ARCH,  CLIB)]
    'nacl_arm_glibc': [('opt', 'arm', 'glibc')],
    'nacl_arm_glibc_raw': [('opt', 'arm', 'glibc')],
    }

def main(args):
  parser = optparse.OptionParser(
    usage='USAGE: %prog [options] <build_name>')
  parser.add_option(
    '--buildbot',
    default=False, action='store_true',
    help='Run as a buildbot.')
  parser.add_option(
    '--trybot',
    default=False, action='store_true',
    help='Run as a trybot.')
  parser.add_option(
    '--test_toolchain', dest='test_toolchains',
    default=[], action='append',
    help='Append toolchain to test.')
  parser.add_option(
    '--skip-toolchain-build', dest='skip_toolchain_build',
    default=False, action='store_true',
    help='Skip Toolchain Build.')

  options, arguments = parser.parse_args(args)
  if len(arguments) != 1:
    print 'Error - expected build_name arguments'
    return 1

  build_name, = arguments

  build_script = os.path.join(NACL_DIR, 'toolchain_build', build_name + '.py')
  if not os.path.isfile(build_script):
    print 'Error - Unknown build script: %s' % build_script
    return 1

  if sys.platform == 'win32':
    print '@@@BUILD_STEP install mingw@@@'
    sys.stdout.flush()
    subprocess.check_call([os.path.join(NACL_DIR, 'buildbot', 'mingw_env.bat')])

  print '@@@BUILD_STEP run_pynacl_tests.py@@@'
  sys.stdout.flush()
  subprocess.check_call([
      sys.executable, os.path.join(NACL_DIR, 'pynacl', 'run_pynacl_tests.py')])

  bot_arg = ['--bot']
  if options.buildbot:
    bot_arg.append('--buildbot')
  elif options.trybot:
    bot_arg.append('--trybot')

  # Toolchain build emits its own annotator stages.
  sys.stdout.flush()
  if not options.skip_toolchain_build:
    subprocess.check_call([sys.executable,
                           build_script] +
                           bot_arg +
                           ['--packages-file', TEMP_PACKAGES_FILE])

  if options.buildbot or options.trybot:
    packages.UploadPackages(TEMP_PACKAGES_FILE, options.trybot)

  # Run toolchain tests for built toolchains
  for toolchain_name in options.test_toolchains:
    print '@@@BUILD_STEP test toolchains (%s)@@@' % toolchain_name
    sys.stdout.flush()
    test_options = TOOLCHAIN_TESTS.get(toolchain_name, None)
    if test_options is None:
      print 'Error - unknown toolchain to test with: %s' % toolchain_name
      return 1

    # Extract the toolchain into a temporary directory.
    subprocess.check_call([sys.executable,
                           PKG_VER,
                           '--packages', toolchain_name,
                           '--tar-dir', TOOLCHAIN_BUILD_PACKAGES,
                           '--dest-dir', TEMP_TOOLCHAIN_DIR,
                           'extract',
                           '--skip-missing'])

    toolchain_dir = os.path.join(TEMP_TOOLCHAIN_DIR,
                                 '%s_%s' % (pynacl.platform.GetOS(),
                                            pynacl.platform.GetArch()),
                                 toolchain_name)

    # Use buildbot_standard to run all the scons tests for each test option.
    for mode, arch, clib in test_options:
      if toolchain_name.startswith('nacl_'):
        scons_toolchain_arg = 'nacl_%s_dir' % clib
      elif toolchain_name.startswith('pnacl_'):
        scons_toolchain_arg = 'pnacl_%s_dir' % clib
      else:
        print 'Error - Could not figure out toolchain type: %s' % toolchain_name
        return 1

      subprocess.check_call([sys.executable,
                             BUILDBOT_STANDARD,
                             '--step-suffix= [%s %s]' % (toolchain_name, mode),
                             '--scons-args', '%s=%s' % (scons_toolchain_arg,
                                                        toolchain_dir),
                             mode, arch, clib])

  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))


text:
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Internal.Runtime.Augments;

namespace System
{
    public static partial class Environment
    {
        private static string CurrentDirectoryCore
        {
            get
            {
                StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH + 1);
                if (Interop.Kernel32.GetCurrentDirectory(sb.Capacity, sb) == 0)
                {
                    StringBuilderCache.Release(sb);
                    throw Win32Marshal.GetExceptionForLastWin32Error();
                }
                string currentDirectory = sb.ToString();

                // Note that if we have somehow put our command prompt into short
                // file name mode (i.e. by running edlin or a DOS grep, etc), then
                // this will return a short file name.
                if (currentDirectory.IndexOf('~') >= 0)
                {
                    int r = Interop.Kernel32.GetLongPathName(currentDirectory, sb, sb.Capacity);
                    if (r == 0 || r >= Interop.Kernel32.MAX_PATH)
                    {
                        int errorCode = r >= Interop.Kernel32.MAX_PATH ?
                            Interop.Errors.ERROR_FILENAME_EXCED_RANGE :
                            Marshal.GetLastWin32Error();

                        if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND &&
                            errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND &&
                            errorCode != Interop.Errors.ERROR_INVALID_FUNCTION &&
                            errorCode != Interop.Errors.ERROR_ACCESS_DENIED)
                        {
                            StringBuilderCache.Release(sb);
                            throw Win32Marshal.GetExceptionForWin32Error(errorCode);
                        }
                    }

                    currentDirectory = sb.ToString();
                }

                StringBuilderCache.Release(sb);
                return currentDirectory;
            }
            set
            {
                if (!Interop.Kernel32.SetCurrentDirectory(value))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw Win32Marshal.GetExceptionForWin32Error(
                        errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND ? Interop.Errors.ERROR_PATH_NOT_FOUND : errorCode,
                        value);
                }
            }
        }

        public static string[] GetLogicalDrives() => DriveInfoInternal.GetLogicalDrives();

        public static string NewLine => "\r\n";

        private static int ProcessorCountFromSystemInfo
        {
            get
            {
                var info = default(Interop.Kernel32.SYSTEM_INFO);
                Interop.Kernel32.GetSystemInfo(out info);
                return info.dwNumberOfProcessors;
            }
        }

        public static int SystemPageSize
        {
            get
            {
                var info = default(Interop.Kernel32.SYSTEM_INFO);
                Interop.Kernel32.GetSystemInfo(out info);
                return info.dwPageSize;
            }
        }

        public static int ExitCode { get { return EnvironmentAugments.ExitCode; } set { EnvironmentAugments.ExitCode = value; } }

        private static string ExpandEnvironmentVariablesCore(string name)
        {
            int currentSize = 100;
            StringBuilder result = StringBuilderCache.Acquire(currentSize); // A somewhat reasonable default size

            result.Length = 0;
            int size = Interop.Kernel32.ExpandEnvironmentStringsW(name, result, currentSize);
            if (size == 0)
            {
                StringBuilderCache.Release(result);
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            while (size > currentSize)
            {
                currentSize = size;
                result.Length = 0;
                result.Capacity = currentSize;

                size = Interop.Kernel32.ExpandEnvironmentStringsW(name, result, currentSize);
                if (size == 0)
                {
                    StringBuilderCache.Release(result);
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }

            return StringBuilderCache.GetStringAndRelease(result);
        }

        private static bool Is64BitOperatingSystemWhen32BitProcess
        {
            get
            {
                bool isWow64;
                return Interop.Kernel32.IsWow64Process(Interop.Kernel32.GetCurrentProcess(), out isWow64) && isWow64;
            }
        }

        public static string MachineName
        {
            get
            {
                string name = Interop.Kernel32.GetComputerName();
                if (name == null)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_ComputerName);
                }
                return name;
            }
        }

        private static unsafe Lazy<OperatingSystem> s_osVersion = new Lazy<OperatingSystem>(() =>
        {
            var version = new Interop.Kernel32.OSVERSIONINFOEX { dwOSVersionInfoSize = sizeof(Interop.Kernel32.OSVERSIONINFOEX) };
            if (!Interop.Kernel32.GetVersionExW(ref version))
            {
                throw new InvalidOperationException(SR.InvalidOperation_GetVersion);
            }

            return new OperatingSystem(
                PlatformID.Win32NT,
                new Version(version.dwMajorVersion, version.dwMinorVersion, version.dwBuildNumber, (version.wServicePackMajor << 16) | version.wServicePackMinor),
                Marshal.PtrToStringUni((IntPtr)version.szCSDVersion));
        });

        public static int ProcessorCount
        {
            get
            {
                // First try GetLogicalProcessorInformationEx, caching the result as desktop/coreclr does.
                // If that fails for some reason, fall back to a non-cached result from GetSystemInfo.
                // (See SystemNative::GetProcessorCount in coreclr for a comparison.)
                int pc = s_processorCountFromGetLogicalProcessorInformationEx.Value;
                return pc != 0 ? pc : ProcessorCountFromSystemInfo;
            }
        }

        private static readonly unsafe Lazy<int> s_processorCountFromGetLogicalProcessorInformationEx = new Lazy<int>(() =>
        {
            // Determine how much size we need for a call to GetLogicalProcessorInformationEx
            uint len = 0;
            if (!Interop.Kernel32.GetLogicalProcessorInformationEx(Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup, IntPtr.Zero, ref len) &&
                Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
            {
                // Allocate that much space
                Debug.Assert(len > 0);
                var buffer = new byte[len];
                fixed (byte* bufferPtr = buffer)
                {
                    // Call GetLogicalProcessorInformationEx with the allocated buffer
                    if (Interop.Kernel32.GetLogicalProcessorInformationEx(Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup, (IntPtr)bufferPtr, ref len))
                    {
                        // Walk each SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX in the buffer, where the Size of each dictates how
                        // much space it's consuming.  For each group relation, count the number of active processors in each of its group infos.
                        int processorCount = 0;
                        byte* ptr = bufferPtr, endPtr = bufferPtr + len;
                        while (ptr < endPtr)
                        {
                            var current = (Interop.Kernel32.SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)ptr;
                            if (current->Relationship == Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup)
                            {
                                Interop.Kernel32.PROCESSOR_GROUP_INFO* groupInfo = &current->Group.GroupInfo;
                                int groupCount = current->Group.ActiveGroupCount;
                                for (int i = 0; i < groupCount; i++)
                                {
                                    processorCount += (groupInfo + i)->ActiveProcessorCount;
                                }
                            }
                            ptr += current->Size;
                        }
                        return processorCount;
                    }
                }
            }

            return 0;
        });

        public static string SystemDirectory
        {
            get
            {
                StringBuilder sb = StringBuilderCache.Acquire(PathInternal.MaxShortPath);
                if (Interop.Kernel32.GetSystemDirectoryW(sb, PathInternal.MaxShortPath) == 0)
                {
                    StringBuilderCache.Release(sb);
                    throw Win32Marshal.GetExceptionForLastWin32Error();
                }
                return StringBuilderCache.GetStringAndRelease(sb);
            }
        }

        public static string UserName
        {
            get
            {
                string username = "Windows User";
                GetUserName(ref username);
                return username;
            }
        }

        static partial void GetUserName(ref string username);

        public static string UserDomainName
        {
            get
            {
                string userDomainName = "Windows Domain";
                GetDomainName(ref userDomainName);
                return userDomainName;
            }
        }

        static partial void GetDomainName(ref string userDomainName);
    }
}


text:
require 'attrocity/coercers/string'

module Attrocity
  RSpec.describe Coercers::String do
    describe '#coerce' do
      it 'coerces to a string' do
        coercer = Coercers::String.new
        expect(coercer.coerce(1)).to eq('1')
      end
    end
  end
end


text:
/*
Title: Joomla From Validation
Date: 20130225
Tags: joomla,web design

*/

# Joomla! Form Validation

Do you need to add some JavaScript form validation to your [Joomla!](http://www.spacecadet9.com/category/joomla/) module or component?

Of course you do!

Add this to your [php](http://www.spacecadet9.com/category/php/)  page:

`
JHTML::_('behavior.mootools');
JHTML::_('behavior.formvalidation');
`

Then add this to the form:

`
class="form-validate" onSubmit="return myValidate(this);"
`

Then add these classes to the form inputs:

`
class="required"
`

or

`
class="required validate-email"
`

Bob's you're auntie..!


text:
import {provide, ComponentRef} from 'angular2/core';
import {bootstrap, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';

import {provideStore} from '@ngrx/store';
import {UserService} from './app/model/UserService';
import {AuthService} from './app/model/AuthService';
import {users} from './app/reducers/users';
import {auth} from './app/reducers/auth';
import {API_PROVIDERS} from './app/api/api';

// hack from https://github.com/brandonroberts/angular2-router-example
import {appInjector} from './app/helpers/helpers';

/*
 * App Component
 * our top level component that holds all of our components
 */
import {App} from './app/app';

/*
 * Bootstrap our Angular app with a top level component `App` and inject
 * our Services and Providers into Angular's dependency injection
 */
document.addEventListener('DOMContentLoaded', function main() {
  bootstrap(App, [
    ('production' === process.env.ENV ? [] : ELEMENT_PROBE_PROVIDERS),
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    //provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provideStore({ users, auth }),
    UserService,
    AuthService,
    API_PROVIDERS
  ])
  // hack from https://github.com/brandonroberts/angular2-router-example
  .then((appRef: ComponentRef) => {
    appInjector(appRef.injector);
  })
  .catch(err => console.error(err));
});


text:
import { FETCH_HERO } from '../actions'

const INITIAL_STATE = {
};

export default function(state = INITIAL_STATE, action) {
  switch(action.type) {
    case FETCH_HERO:
      return action.hero
    default:
      return state;
  }
}


text:
title: Either.isLeft - Kotlin utilities
---

[Kotlin utilities](../../index.html) / [it.czerwinski.kotlin.util](../index.html) / [Either](index.html) / [isLeft](./is-left.html)

# isLeft

`abstract val isLeft: `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)

Returns `true` if this is a [Left](../-left/index.html) or `false` if this is [Right](../-right/index.html).

**Return**
`true` if this is a [Left](../-left/index.html) or `false` if this is [Right](../-right/index.html).


text:
<?php
/**
 * Image effect for round image corners.
 *
 * $Horde: framework/Image/Image/Effect/gd/round_corners.php,v 1.6.2.1 2007/12/20 13:49:11 jan Exp $
 *
 * This algorithm is from the phpThumb project available at
 * http://phpthumb.sourceforge.net and all credit for this script should go to
 * James Heinrich <info@silisoftware.com>.  Modifications made to the code
 * to fit it within the Horde framework and to adjust for our coding standards.
 *
 * @author  Michael J. Rubinsky <mrubinsk@horde.org>
 * @since   Horde 3.2
 * @package Horde_Image
 */
class Horde_Image_Effect_gd_round_corners extends Horde_Image_Effect {

    /**
     * Valid parameters:
     *
     * radius - Radius of rounded corners.
     *
     * @var array
     */
    var $_params = array('radius' => 10);

    /**
     * Apply the round_corners effect.
     *
     * @return mixed true | PEAR_Error
     */
    function apply()
    {
        // Original comments from phpThumb projet:
        // generate mask at twice desired resolution and downsample afterwards
        // for easy antialiasing mask is generated as a white double-size
        // elipse on a triple-size black background and copy-paste-resampled
        // onto a correct-size mask image as 4 corners due to errors when the
        // entire mask is resampled at once (gray edges)
        $radius_x = $radius_y = $this->_params['radius'];
        $gdimg = $this->_image->_im;
        $imgX = round($this->_image->_call('imageSX', array($gdimg)));
        $imgY = round($this->_image->_call('imageSY', array($gdimg)));

        $gdimg_cornermask_triple = $this->_image->_create(round($radius_x * 6),
                                                          round($radius_y * 6));
        if (!is_a($gdimg_cornermask_triple, 'PEAR_Error')) {

            $gdimg_cornermask = $this->_image->_create($imgX, $imgY);
            if (!is_a($gdimg_cornermask, 'PEAR_Error')) {
                $color_transparent = $this->_image->_call('imageColorAllocate',
                                                          array($gdimg_cornermask_triple,
                                                                255,
                                                                255,
                                                                255));

                $this->_image->_call('imageFilledEllipse',
                                     array($gdimg_cornermask_triple,
                                           $radius_x * 3,
                                           $radius_y * 3,
                                           $radius_x * 4,
                                           $radius_y * 4,
                                           $color_transparent));

                $this->_image->_call('imageFilledRectangle',
                                     array($gdimg_cornermask,
                                           0,
                                           0,
                                           $imgX,
                                           $imgY,
                                           $color_transparent));

                $this->_image->_call('imageCopyResampled',
                                     array($gdimg_cornermask,
                                           $gdimg_cornermask_triple,
                                           0,
                                           0,
                                           $radius_x,
                                           $radius_y,
                                           $radius_x,
                                           $radius_y,
                                           $radius_x * 2,
                                           $radius_y * 2));

                $this->_image->_call('imageCopyResampled',
                                     array($gdimg_cornermask,
                                           $gdimg_cornermask_triple,
                                           0,
                                           $imgY - $radius_y,
                                           $radius_x,
                                           $radius_y * 3,
                                           $radius_x,
                                           $radius_y,
                                           $radius_x * 2,
                                           $radius_y * 2));

                $this->_image->_call('imageCopyResampled',
                                     array($gdimg_cornermask,
                                           $gdimg_cornermask_triple,
                                           $imgX - $radius_x,
                                           $imgY - $radius_y,
                                           $radius_x * 3,
                                           $radius_y * 3,
                                           $radius_x,
                                           $radius_y,
                                           $radius_x * 2,
                                           $radius_y * 2));

                $this->_image->_call('imageCopyResampled',
                                     array($gdimg_cornermask,
                                           $gdimg_cornermask_triple,
                                           $imgX - $radius_x,
                                           0,
                                           $radius_x * 3,
                                           $radius_y,
                                           $radius_x,
                                           $radius_y,
                                           $radius_x * 2,
                                           $radius_y * 2));

                $result = $this->_image->_applyMask($gdimg_cornermask);
                if (is_a($result, 'PEAR_Error')) {
                    return $result;
                }
                $this->_image->_call('imageDestroy', array($gdimg_cornermask));
                return true;
            } else {
                return $gdimg_cornermas; // PEAR_Error
            }
            $this->_image->_call('imageDestroy',
                                 array($gdimg_cornermask_triple));
        } else {
            return $gdimg_cornermas_triple; // PEAR_Error
        }
    }

}


text:
<?php
namespace User\Controller;

use Application\Entity\User;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use User\Form\RegisterForm;

class RegisterController extends AbstractActionController
{

    /**
     * get the registration form
     *
     * @return ViewModel
     */
    public function indexAction()
    {
        $form = new RegisterForm();
        return new ViewModel(array("registerForm" => $form));
    }

    /**
     * validate data and register user in DB
     *
     * @return ViewModel
     */
    public function processAction()
    {

        if ($this->request->isPost()) {
            $form = new RegisterForm();
            $data = $this->params()->fromPost();

            $viewModel = new ViewModel();
            $viewModel->setTemplate('user/register/index');
            $viewModel->setVariable("registerForm", $form);

            $form->setData($data);

            if ($form->isValid()) {

                if ($data["password"] == $data["confirm_password"]) {

                    $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
                    $userRepo = $em->getRepository('Application\Entity\User');
                    $user = $userRepo->findByEmail($data['email']);

                    if($user){
                        $viewModel->setVariable('accountExistError', true);
                        return $viewModel;
                    }

                    $user = new User();
                    $user->setFirstname($data['firstname']);
                    $user->setLastname($data['lastname']);
                    $user->setEmail($data['email']);
                    $user->setPhone($data['phone']);
                    $user->setPassword($data['password']);

                    $user->setBlocked(0);
                    $user->setEmailVerified(0);
                    $user->setPhoneVerified(0);
                    $user->setRole('u');
                    $user->setRegistredDate(time());

                    $em->persist($user);
                    $em->flush();

                    $params = [
                        "email" => $user->getEmail(),
                    ];

                    //$eventManager = $this->getEventManager()->trigger('sendMail', null, );
                    //TODO continue and send mail by Listener class
                    $this->redirect()->toRoute('user', array('controller'=>'register', 'action'=>'success'));

                } else {
                    $viewModel->setVariable('passwordError', true);
                    return $viewModel;
                }
            } else {
                $viewModel->setVariable('formError', true);
                return $viewModel;
            }
        } else {
            $this->redirect()->toRoute('user', array('controller' => "register", "action" => "index"));
        }

    }

    /**
     * display success page
     *
     * @return ViewModel
     */
    public function successAction()
    {
        return new ViewModel();
    }
}


text:
package test.methodinterceptors.issue1726;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Priority {
  int value() default 0;
}


text:
#include "GlobalDef.h"
#include "J1850.h"

//#define Toyota_GetTXCTState()	J1850_GetState()

#define DataHigh 	1
#define DataLow 	2

#define Receiving	1
#define Sending		2

#ifdef HW_TB
#define ToyotaOld_TXCTInput_Init()		BitClear(DDRD,DDD4)
#endif

#ifdef HW_ALCA
#define ToyotaOld_TXCTInput_Init()		BitClear(DDRC,DDC5)
#endif

#ifdef HW_BLADE
#define ToyotaOld_TXCTInput_Init()		BitClear(DDRG,DDG0)
#endif

Uint8 ToyotaOld_GetTXCT(void);

/*******************************************************************************************/
/* Uint8 LearnOld_Toyota()                                                                 */
/*                                                                                */
/* Parameter    : None                                                                     */
/* Return value : SUCCESS or FAIL						         		                   */
/*                                                                                */
/* This function learn start mode and save the pattern in EEPROM. This function is for Old */
/* Toyota vehicle.											                               */
/*******************************************************************************************/
Uint8 ToyotaOld_Learn(void);

/*******************************************************************************************/
/* Uint8 ToyotaOld_ReceiveTXCT();                                                          */
/*                                                                                */
/* Parameter    : Uint8 nByte = How many byte are we waiting ??                            */
/* Return value : Uint8 Error code                                                         */
/*                                                                                */
/* This function receive a Challenge on TXCT bus and return the data. If no byte are       */
/* received after 100msec, the function quit and return FAIL error.  If a bit is missing   */
/* or not correct, the function quit and return FAIL. Else, the function successfully      */
/* received all byte and return SUCCESS.                                                   */
/*******************************************************************************************/
//Uint8 ToyotaOld_ReceiveTXCT();
Uint8 ToyotaOld_ReceiveTXCT(Uint8 Type);

/*******************************************************************************************/
/* Uint8 ToyotaOld_ReceiveBit();                                                           */
/*                                                                                */
/* Parameter    : Uint8 *Data = Data to receive from TXCT bus                              */
/* Return value : Uint8 Error code                                                         */
/*                                                                                */
/* This function receive a Byte on TXCT bus and return the data. If no byte are received   */
/* after 100msec, the function quit and return TIMEOUT error.  If a bit is missing or not  */
/* correct, the function quit and return ERROR. Else, the function successfully received   */
/* all byte and return OK.                                                                 */
/*******************************************************************************************/
Uint8 ToyotaOld_ReceiveBit(void);

/*******************************************************************************************/
/* Uint8 TIRFID_ReceiveByteTXCT(Uint8 *Data)                                               */
/*                                                                                */
/* Parameter    : Uint8 *Data = Data to receive from TXCT bus                              */
/* Return value : Uint8 Error code                                                         */
/*                                                                                */
/* This function receive a Byte on TXCT bus and return the data. If no byte are received   */
/* after 100msec, the function quit and return TIMEOUT error.  If a bit is missing or not  */
/* correct, the function quit and return ERROR. Else, the function successfully received   */
/* all byte and return OK.                                                                 */
/*******************************************************************************************/
Uint8 ToyotaOld_ReceiveFrame(void);

/*******************************************************************************************/
/* Uint8 ToyotaOld_SendFrame()                                          				   */
/*                                                                                */
/* Parameter    : Uint8 *Data = Data to receive from TXCT bus                              */
/* Return value : Uint8 Error code                                                         */
/*                                                                                */
/* This function receive a Byte on TXCT bus and return the data. If no byte are received   */
/* after 100msec, the function quit and return TIMEOUT error.  If a bit is missing or not  */
/* correct, the function quit and return ERROR. Else, the function successfully received   */
/* all byte and return OK.                                                                 */
/*******************************************************************************************/
Uint8 ToyotaOld_SendFrame(void);

/*******************************************************************************************/
/* Uint16 TIRFID_ComputeBCC(Uint8 *Data,Uint8 nByte,Uint16 BCCReg)                         */
/*                                                                                */
/* Parameter    : Uint8 *Data = Array of data to compute BCC value                         */
/*                Uint8 nByte = How many byte is in the data array ??                      */
/*                Uint16 BCCReg = Start value (SEED) of the BCCReg                         */
/*                                                                                */
/* Note         : Seed=0x3791 for FrameBCC in DST transponder application                  */
/*                Seed=0x0000 for FrameBCC in all transponder application                  */
/*                                                                                */
/* Return value : Uint16 compute BCC                                                       */
/*                                                                                */
/* This function compute a frame BCC value for the data array passed in parameter.  The    */
/* CRC Generator includes a 16-bits shift register with its Serial Data Output (LSB),      */
/* which is connected to an Exclusive-OR gate. Its output feeds back to other Exclusive-   */
/* OR gates, which are located in between the sections of the shift register. Placement    */
/* and quantity of Exclusive-OR gates define the so called CRC-CCITT generator             */
/* polynomial P(X)=X16+X12+X5+1.                                                           */
/*                                                                                */
/* Ex : SN=0x0000000007C0C6F7                                                              */
/*                                                                                */
/*      unsigned char SN[8]={0,0,0,0,0x07,0xC0,0xC6,0xF7};                                 */
/*      TIRFID_ComputeBCC(SN,8,0);  --> bad result BCC = 0x40F1                            */
/*                                                                                */
/*      unsigned char SN[8]={0xF7,0xC6,0xC0,0x07,0,0,0,0};                                 */
/*      TIRFID_ComputeBCC(SN,8,0);  --> good result BCC = 0xF1EC                           */
/*                                                                                */
/*******************************************************************************************/
Uint16 ToyotaOld_ComputeBCC(Uint8 *Data,Uint8 nByte,Uint16 BCCReg);

/*******************************************************************************************/
/* void ToyotaOld_SaveFrmae(Uint8 FrameSize)                                               */
/*                                                                                */
/* Parameter    : FrameSize                                                                */
/* Return value : None                                                                     */
/*                                                                                */
/* This function save the Frame learned in EEPROM                                          */
/*******************************************************************************************/
void ToyotaOld_SaveFrame(Uint8 FrameSize);

/*******************************************************************************************/
/* void ToyotaOld_GetFrame()                            			   					   */
/*                                                                                */
/* Parameter    : Frame Size                                                               */
/* Return value : return TXFrame                                         				   */
/*                                                                                */
/* This function is for Getting  frame from EEPROM and return it to TX_Frame.              */
/*******************************************************************************************/
void ToyotaOld_GetFrame(void);


text:
package org.asciidoctor.integrationguide.extension;

//tag::include[]

import org.asciidoctor.ast.ContentNode;
import org.asciidoctor.extension.InlineMacroProcessor;
import org.asciidoctor.extension.Name;

import java.util.HashMap;
import java.util.Map;

@Name("issue")                                                           // <1>
public class IssueInlineMacroProcessor extends InlineMacroProcessor {    // <2>

    @Override
    public Object process(                                               // <3>
            ContentNode parent, String target, Map<String, Object> attributes) {

        String href =
                new StringBuilder()
                    .append("https://github.com/")
                    .append(attributes.containsKey("repo") ?
                            attributes.get("repo") :
                            parent.getDocument().getAttribute("repo"))
                    .append("/issues/")
                    .append(target).toString();

        Map<String, Object> options = new HashMap<>();
        options.put("type", ":link");
        options.put("target", href);
        return createPhraseNode(parent, "anchor", target, attributes, options); // <4>
    }

}
//end::include[]


text:
@implementation Jdb

@end


text:
package learn.you.a.data.structure.list.array;

import learn.you.a.data.structure.Iterator;

public class ArrayListIterator <T> implements Iterator<T> {
	@Override
	public boolean hasNext() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public T next() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
import os
import shutil
import sys
import zipfile

def main(argv):
    indir = argv[1]
    outdir = argv[2]
    for root, dirs, files in os.walk(indir):
        outroot = os.path.join(outdir, os.path.relpath(root, indir))
        for d in dirs:
            os.mkdir(os.path.join(outroot, d))
        for f in files:
            infile = os.path.join(root, f)
            outfile = os.path.join(outroot, f)
            if not f.endswith(".jar"):
                shutil.copyfile(infile, outfile)
            else:
                inzip = zipfile.ZipFile(infile, "r")
                outzip = zipfile.ZipFile(outfile, "w")
                for zinfo in inzip.infolist():
                    raw_content = inzip.read(zinfo.filename)
                    transformed = raw_content.replace(
                        b"__FIND_ME_HERE__content=1__GOODBYE__",
                        b"__FIND_ME_HERE__content=2__GOODBYE__",
                    )
                    outzip.writestr(zinfo, transformed)
                outzip.close()
                inzip.close()

if __name__ == "__main__":
    sys.exit(main(sys.argv))


text:
<?php

namespace opensrs\OMA;

use opensrs\OMA;
use opensrs\Exception;

// command: stats_snapshot
// Generate a URL that a stats snapshot can be downloaded from. Note URLs are only valid for 15 minutes after generation.

class StatsSnapshot
{
    public static function call($data)
    {
        if (self::validate($data)) {
            return OMA::send_cmd('stats_snapshot', $data);
        }
    }

    // Valdation rule here
    public static function validate($data)
    {
        if (empty($data['type']) || empty($data['object']) || empty($data['date'])) {
            throw new Exception('oSRS Error - Company required');
        } else {
            return true;
        }
    }
}


text:
from setuptools import setup, find_packages

requires = [
    'gurobipy',
    'celery==4.1.0',
    'marshmallow==2.13.4',
]

setup(
    name='puzzle_engine',
    version='0.0.1-dev',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=requires,
    entry_points="""\
    [console_scripts]
    puzzle_engine = puzzle_engine.cli:cli
    """
)


text:
layout: video
show_meta: true
title: "iPhone 6S vs Note 7 Speed Test"
subheadline: ""
teaser: "Samsung's best effort from this year is still not enough to beat Apple's from last year."
categories:
    - videos
author: Morgan
iframe: ""
video:
    embedURL: "https://www.youtube.com/embed/3-61FFoJFy0"
    contentURL: "https://www.youtube.com/watch?v=3-61FFoJFy0"
    thumbnailUrl: "http://img.youtube.com/vi/3-61FFoJFy0/maxresdefault.jpg"
breadcrumb: true
---

Samsung's best effort from _this_ year is still not enough to beat Apple's from _last_ year. Why do people buy Samsung products again?

---

Typed on ErgoDox Test Board


text:
package com.mongodb.dibs.email;

import com.mongodb.dibs.model.Order;
import com.mongodb.dibs.model.SeamlessConfirmation;
import com.sun.mail.imap.IMAPMessage;
import org.apache.commons.mail.util.MimeMessageParser;
import org.apache.commons.mail.util.MimeMessageUtils;
import org.mongodb.morphia.Datastore;

import javax.mail.Address;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SeamlessConfirmationEmailListener {
    public final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("h:m a M/d/yy");
    private static final String CONFIRMED = "Confirmed";

    private final EmailParser emailParser = new EmailParser();
    private final Session session;
    private final Datastore ds;
    public static final String ESTIMATED_DELIVERY = "Estimated Delivery: ";
    private ScheduledExecutorService executorService;

    public SeamlessConfirmationEmailListener(Datastore ds) {
        this.ds = ds;
        session = Session.getInstance(new Properties());
        executorService = Executors.newScheduledThreadPool(2);
    }

    public void start() throws MessagingException {
        executorService.scheduleAtFixedRate(new NotificationsWatcher(this), 0, 1, TimeUnit.MINUTES);
        executorService.scheduleAtFixedRate(new UpForGrabsWatcher(this), 0, 1, TimeUnit.MINUTES);
    }

    public void deliver(final Message message, final boolean upForGrabs) throws MessagingException {
        final SeamlessConfirmation seamlessConfirmation = parseMessage(message);
//        ds.save(seamlessConfirmation);

        Order order = emailParser.parse(seamlessConfirmation);
        order.setUpForGrabs(upForGrabs);

        ds.save(order);
    }

    public SeamlessConfirmation parseMessage(final Message message) throws MessagingException {
        MimeMessage content;
        final MimeMessageParser parser;
        final String from;
        final Address to;
        String subject = null;
        String vendor;
        Date expectedAt;
        try {
            content = MimeMessageUtils.createMimeMessage(null, String.valueOf(message.getContent()));
            parser = new MimeMessageParser(content).parse();
            to = parser.getTo().get(0);
            from = parser.getFrom();
            subject = parser.getSubject();

            vendor = subject.substring(subject.indexOf(CONFIRMED) + CONFIRMED.length() +2, subject.indexOf(" received"));
            expectedAt = DATE_FORMAT.parse(subject.substring(subject.indexOf(ESTIMATED_DELIVERY) + ESTIMATED_DELIVERY.length())
                                                  .replaceAll("\\.", "").replace(", on", ""));
        } catch (Exception e) {
            throw new MessagingException(e.getMessage() + ": " + subject, e);
        }

        return new SeamlessConfirmation(from, to.toString(), vendor, expectedAt, getHeadersList(content), getHtmlContent(parser));
    }

    private String getHtmlContent(final MimeMessageParser parser) {
        List<String> plainContent = new ArrayList<>(Arrays.asList(parser.getPlainContent().split("\n")));
        while (!plainContent.get(0).startsWith("<")) {
            plainContent.remove(0);
        }
        StringBuilder content = new StringBuilder();
        try {
            InputStream stream = MimeUtility.decode(new ByteArrayInputStream(String.join("\n", plainContent).getBytes()),
                                                    "quoted-printable");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
            while (bufferedReader.ready()) {
                content.append(bufferedReader.readLine())
                       .append("\n");
            }
            return content.toString();
        } catch (MessagingException | IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private String findForward(final InputStream inputStream) throws IOException, MessagingException {
        Scanner scanner = new Scanner(inputStream);
        String line;
        StringBuilder builder = new StringBuilder();
        while (!scanner.nextLine().contains("Forwarded message")) {
        }
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.startsWith("Subject: ")) {
                builder.append(line)
                       .append(" ")
                       .append(scanner.nextLine());
            } else {
                builder.append(line);
            }
            builder.append("\n");
        }
        return builder.toString().trim();
    }

    private static Map<String, String> getHeadersList(final MimeMessage message) throws MessagingException {
        final Map<String, String> headers = new LinkedHashMap<>();
        final Enumeration allHeaders = message.getAllHeaders();

        while (allHeaders.hasMoreElements()) {
            final Header h = (Header) allHeaders.nextElement();
            headers.put(h.getName(), h.getValue());
        }

        return headers;
    }

}


text:
int main(int argc, char** argv){
  ros::init(argc, argv, "my_parser");
  if (argc != 2){
    ROS_ERROR("Need a urdf file as argument");
    return -1;
  }
  std::string urdf_file = argv[1];

  urdf::Model model;
  if (!model.initFile(urdf_file)){
    ROS_ERROR("Failed to parse urdf file");
    return -1;
  }
  ROS_INFO("Successfully parsed urdf file");
  return 0;
}


text:
<?php

namespace cahis\ParametrizarBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * cahis\ParametrizarBundle\Entity\Afiliacion
 *
 * @ORM\Table(name="afiliacion")
 * @ORM\Entity
 */
class Afiliacion
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="cahis\ParametrizarBundle\Entity\Paciente")
     */
    private $paciente;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="cahis\ParametrizarBundle\Entity\Cliente")
     */
    private $cliente;

    /**
     * @var string $observacion
     *
     * @ORM\Column(name="observacion", type="string", length=255, nullable=true)
     * @Assert\MaxLength(limit=255, message="El valor ingresado debe tener máximo {{ limit }} caracteres.")
     */
    private $observacion;

    /**
     * Set observacion
     *
     * @param string $observacion
     */
    public function setObservacion($observacion)
    {
        $this->observacion = $observacion;
    }

    /**
     * Get observacion
     *
     * @return string
     */
    public function getObservacion()
    {
        return $this->observacion;
    }

    /**
     * Set paciente
     *
     * @param cahis\ParametrizarBundle\Entity\Paciente $paciente
     */
    public function setPaciente(\cahis\ParametrizarBundle\Entity\Paciente $paciente)
    {
        $this->paciente = $paciente;
    }

    /**
     * Get paciente
     *
     * @return cahis\ParametrizarBundle\Entity\Paciente
     */
    public function getPaciente()
    {
        return $this->paciente;
    }

    /**
     * Set cliente
     *
     * @param cahis\ParametrizarBundle\Entity\Cliente $cliente
     */
    public function setCliente(\cahis\ParametrizarBundle\Entity\Cliente $cliente)
    {
        $this->cliente = $cliente;
    }

    /**
     * Get cliente
     *
     * @return cahis\ParametrizarBundle\Entity\Cliente
     */
    public function getCliente()
    {
        return $this->cliente;
    }
}


text:
package com.mycompany.cucumber.rest.runners;

import org.junit.runner.RunWith;

import com.mycompany.cucumber.profiles.CucumberTestProfile;

import cucumber.api.CucumberOptions;

@RunWith(CucumberTestProfile.class)
@CucumberOptions(
		plugin = {"json:target/cucumber.json"},
		tags = {"@rest"},
		glue = {"com.mycompany.cucumber.rest.steps", "com.mycompany.cucumber.steps"}, //Using service specific and common steps
		features = {"classpath:features/"}, //Path for feature files
		strict=true)
public class RunRestTests {

}


text:
package com.wut.datasources.egit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import org.eclipse.egit.github.core.Blob;
import org.eclipse.egit.github.core.Commit;
import org.eclipse.egit.github.core.CommitUser;
import org.eclipse.egit.github.core.Reference;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryBranch;
import org.eclipse.egit.github.core.RepositoryCommit;
import org.eclipse.egit.github.core.RepositoryContents;
import org.eclipse.egit.github.core.Tree;
import org.eclipse.egit.github.core.TreeEntry;
import org.eclipse.egit.github.core.TypedResource;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.CommitService;
import org.eclipse.egit.github.core.service.ContentsService;
import org.eclipse.egit.github.core.service.DataService;
import org.eclipse.egit.github.core.service.RepositoryService;

import com.wut.support.binary.Base64;
import com.wut.support.settings.SettingsManager;

public class EGitObject {

	static GitHubClient client;
	static ContentsService contentService;
	static RepositoryService service;
	static {
		client = new GitHubClient().setOAuth2Token(SettingsManager.getSystemSetting("github.token"));
		contentService = new ContentsService(client);
		service = new RepositoryService(client);
	}

	public static String pull(String owner, String repositoryName,String branch, String file, String tmpConfigFile)
			throws IOException {
		Repository repository = service.getRepository(owner, repositoryName);
		List<RepositoryContents> contents = contentService.getContents(repository, file, branch);
		byte[] fileContents = (Base64.decodeBase64(contents.get(0).getContent()));
		return saveToFile(fileContents, tmpConfigFile);

	}

	public static boolean push(String owner, String repositoryName, String branch, String path, String localFile, String commitMessage) {
		try {
			// create needed services
			CommitService commitService = new CommitService(client);
			DataService dataService = new DataService(client);

			// get some sha's from current state in git
			Repository repository = service.getRepository(owner, repositoryName);
			List<RepositoryBranch> branches = service.getBranches(repository);
			String baseCommitSha = service.getBranches(repository).get(0).getCommit().getSha();
			for (RepositoryBranch repositoryBranch : branches) {
				if (repositoryBranch.getName().equals(branch)){
					baseCommitSha = repositoryBranch.getCommit().getSha();
					break;
				}
			}
			RepositoryCommit baseCommit = commitService.getCommit(repository, baseCommitSha);
			String treeSha = baseCommit.getSha();

			// create new blob with data
			Blob blob = new Blob();
			File file = new File(localFile);
			FileInputStream fis = new FileInputStream(localFile);
			byte[] data = new byte[(int) file.length()];
			fis.read(data);
			fis.close();
			String content = new String(data, "UTF-8");
			blob.setContent(content).setEncoding(Blob.ENCODING_UTF8);
			String blob_sha = dataService.createBlob(repository, blob);
			Tree baseTree = dataService.getTree(repository, treeSha);

			// create new tree entry
			TreeEntry treeEntry = new TreeEntry();

			// working
			treeEntry.setPath(path);
			treeEntry.setMode(TreeEntry.MODE_BLOB);
			treeEntry.setType(TreeEntry.TYPE_BLOB);
			treeEntry.setSha(blob_sha);
			treeEntry.setSize(blob.getContent().length());
			Collection<TreeEntry> entries = new ArrayList<TreeEntry>();
			entries.add(treeEntry);
			Tree newTree = dataService.createTree(repository, entries, baseTree.getSha());

			// create commit
			Commit commit = new Commit();
			commit.setMessage(commitMessage);
			commit.setTree(newTree);

			CommitUser author = new CommitUser();
			author.setName(SettingsManager.getSystemSetting("github.username"));
			author.setEmail(SettingsManager.getSystemSetting("github.email"));
			Calendar now = Calendar.getInstance();
			author.setDate(now.getTime());
			commit.setAuthor(author);
			commit.setCommitter(author);

			List<Commit> listOfCommits = new ArrayList<Commit>();
			listOfCommits.add(new Commit().setSha(baseCommitSha));
			commit.setParents(listOfCommits);
			Commit newCommit = dataService.createCommit(repository, commit);

			// create resource
			TypedResource commitResource = new TypedResource();
			commitResource.setSha(newCommit.getSha());
			commitResource.setType(TypedResource.TYPE_COMMIT);
			commitResource.setUrl(newCommit.getUrl());

			// get master reference and update it
			Reference reference = dataService.getReference(repository, "refs/heads/" + branch);
			reference.setObject(commitResource);
			dataService.editReference(repository, reference, true);

			return true;

		} catch (Exception e) {
			// error
			e.printStackTrace();
			return false;
		}
	}

	public static String saveToFile(byte[] content, String path) throws IOException {
		FileOutputStream fos = null;
		File f = new File(path);
		if (!f.exists()) {
			f.getParentFile().mkdirs();
			f.createNewFile();
		}
		fos = new FileOutputStream(path);
		fos.write(content);
		fos.close();
		return path;
	}
}