text:
package org.openntf.cockpit;

import java.io.Serializable;
import java.util.Vector;

import lotus.domino.Document;
import lotus.domino.Session;

import org.openntf.domino.utils.XSPUtil;

public class RightsManagement implements Serializable {
	private static final long serialVersionUID = 8157811105680678241L;

	public RightsManagement() {
	}

	/**
	 * Calculate all name fields to canonical form
	 *
	 * @param doc
	 */
	@SuppressWarnings("unchecked")
	public void setNames(Document doc) {
		Session session = XSPUtil.getCurrentSession();
		Vector names = null;
		// item names as array
		String items[] = { "ticketResponsible" };
		try {
			for (String item : items) {
				if (doc.hasItem(item)) {
					names = session.evaluate("@Name([Canonicalize]; " + item + ")", doc);
					doc.replaceItemValue(item, names);
				}
			}
			doc.save();
		} catch (Exception e) {
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
set -euo pipefail
AIRFLOW_SOURCES="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../" && pwd)"
cd "${AIRFLOW_SOURCES}"

# [START download]
rm docker-context-files/*.whl docker-context-files/*.tar.gz docker-context-files/*.txt || true

curl -Lo "docker-context-files/constraints-3.7.txt" \
    https://raw.githubusercontent.com/apache/airflow/constraints-2.0.2/constraints-3.7.txt

# For Airflow pre 2.1 you need to use PIP 20.2.4 to install/download Airflow packages.
pip install pip==20.2.4

pip download --dest docker-context-files \
    --constraint docker-context-files/constraints-3.7.txt  \
    "apache-airflow[async,aws,azure,celery,dask,elasticsearch,gcp,kubernetes,postgres,redis,slack,ssh,statsd,virtualenv]==2.0.2"
# [END download]

# [START build]
docker build . \
    --build-arg PYTHON_BASE_IMAGE="python:3.7-slim-buster" \
    --build-arg AIRFLOW_INSTALLATION_METHOD="apache-airflow" \
    --build-arg AIRFLOW_VERSION="2.0.2" \
    --build-arg INSTALL_MYSQL_CLIENT="false" \
    --build-arg AIRFLOW_PRE_CACHED_PIP_PACKAGES="false" \
    --build-arg INSTALL_FROM_DOCKER_CONTEXT_FILES="true" \
    --build-arg AIRFLOW_CONSTRAINTS_LOCATION="/docker-context-files/constraints-3.7.txt" \
    --tag my-restricted-environment:0.0.1
# [END build]


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

    <title>React App</title>


text:
package rere.ql.options

import rere.ql.queries.values

trait MaxResultsOptions {

  sealed trait MaxResultsOptions extends ComposableOptions

  case object DefaultMaxResults extends MaxResultsOptions with DefaultOption

  case class MaxResults(n: Int) extends MaxResultsOptions with NonDefaultOption {
    def view = "max_results" -> values.expr(n) :: Nil
  }

}


text:
namespace TennisTableWPF.Services
{
    public class DialogService : IDialogService
    {
        public MessageBoxResult ShowMessageBox(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon)
        {
            return (MessageBoxResult)System.Windows.MessageBox.Show(message, caption,(System.Windows.MessageBoxButton)buttons,(System.Windows.MessageBoxImage)icon);
        }
    }
}


text:
require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/../../lib/etsy4r'

describe Etsy4r::ListingCommands do
  include Etsy4rSpecHelper

  before do
    @client = etsy4r_client
    @listing_commands = Etsy4r::ListingCommands.new(@client)
  end

  describe 'initialize' do
    it 'set the client' do
      @listing_commands.client.class.should == Etsy4r::Client
    end
  end

  describe 'get_listing_details' do
    it 'should return details' do
      @res = @listing_commands.get_listing_details(19749826)
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take the detail_level optional param' do
      @res = @listing_commands.get_listing_details(19749826, :detail_level => 'high')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_listings_by_tags' do
    it 'should take an array of tags' do
      @res = @listing_commands.get_listings_by_tags(['bags_and_purses', 'art', 'shoulder bag'])
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take the optional params sort_on and sort_order' do
      @res = @listing_commands.get_listings_by_tags(['bags_and_purses', 'art', 'shoulder bag'], :sort_on => 'price', :sort_order => 'down')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_listings_by_keywords' do
    it 'should take an array of keywords' do
      @res = @listing_commands.get_listings_by_keywords(['bags_and_purses', 'art', 'shoulder bag'])
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take the optional params sort_on and sort_order' do
      @res = @listing_commands.get_listings_by_keywords(['bags_and_purses', 'art', 'shoulder bag'], :sort_on => 'price', :sort_order => 'down')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take the optional params min_price and max_prce' do
      @res = @listing_commands.get_listings_by_keywords(['bags_and_purses', 'art', 'shoulder bag'], :min_price => 0, :max_price => 22.99)
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_front_featured_listings' do
    it 'should return the listings' do
      @res = @listing_commands.get_front_featured_listings
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take optional params' do
      @res = @listing_commands.get_front_featured_listings(:detail_level => 'medium', :limit => 45, :offset => 45)
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_all_listings' do
    it 'should return listings' do
      @res = @listing_commands.get_all_listings
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take optional params' do
      @res = @listing_commands.get_all_listings(:detail_level => 'medium', :limit => 45, :offset => 45, :sort_on => 'ending', :sort_order => 'down')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_listings_by_category' do
    it 'should return listings' do
      @res = @listing_commands.get_listings_by_category('bags_and_purses')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should return listings when given a category with spaces' do
      @res = @listing_commands.get_listings_by_category('bags and purses')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take optional params' do
      @res = @listing_commands.get_listings_by_category('bags and purses', :detail_level => 'medium', :limit => 45, :offset => 45, :sort_on => 'price', :sort_order => 'down')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_listings_by_color' do
    it 'should return listings when given 6 hex digits' do
      @res = @listing_commands.get_listings_by_color('FFFFFF')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should return listings when given 6 hex digits with a pound sign' do
      @res = @listing_commands.get_listings_by_color('#FFFFFF')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should return listings when given an HSV format' do
      @res = @listing_commands.get_listings_by_color('360;100;100')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take optional params' do
      @res = @listing_commands.get_listings_by_color('FFFFFF', :detail_level => 'medium', :limit => 45, :offset => 45, :wiggle => 10)
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_listings_by_materials' do
    it 'should take an array of materials' do
      @res = @listing_commands.get_listings_by_materials(['cotton', 'wool'])
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take the optional params sort_on and sort_order' do
      @res = @listing_commands.get_listings_by_materials(['cotton', 'wool'], :sort_on => 'price', :sort_order => 'down')
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

  describe 'get_listings_by_color_and_keywords' do
    it 'should return listings when a hex color and keywords' do
      @res = @listing_commands.get_listings_by_color_and_keywords('FFFFFF', ['bags', 'bracelets'])
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should return listings when given a hex color with pound and keywords' do
      @res = @listing_commands.get_listings_by_color_and_keywords('#FFFFFF', ['bags', 'bracelets'])
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should return listings when given an HSV color and keywords' do
      @res = @listing_commands.get_listings_by_color_and_keywords('360;100;100', ['bags', 'bracelets'])
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end

    it 'should take optional params' do
      @res = @listing_commands.get_listings_by_color_and_keywords('FFFFFF', ['bags', 'bracelets'], :detail_level => 'medium', :limit => 45, :offset => 45, :wiggle => 10)
      @res.should be_success
      @res.results.should_not be_nil
      @res.error_message.should be_blank
    end
  end

end


text:
[![Build Status](https://travis-ci.org/heap/cryptohat.svg?branch=master)](https://travis-ci.org/heap/cryptohat)
[![Coverage Status](https://coveralls.io/repos/github/heap/cryptohat/badge.svg?branch=master)](https://coveralls.io/github/heap/cryptohat?branch=master)
[![Dependency Status](https://gemnasium.com/heap/cryptohat.svg)](https://gemnasium.com/heap/cryptohat)
[![NPM Version](http://img.shields.io/npm/v/cryptohat.svg)](https://www.npmjs.org/package/cryptohat)

This is a [node.js](https://nodejs.org/) package that implements
[hat](https://www.npmjs.com/package/hat)'s main API, but uses a
[cryptographically secure pseudo-random number generator](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator)
to generate the random identifiers. This is especially beneficial when using
older versions of [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine))
that exhibit [this bug](https://bugs.chromium.org/p/v8/issues/detail?id=4566).

In our use cases, `cryptohat` takes up to 3x more time to produce a random
string than `hat`. However, `cryptohat` also exposes an alternative API that
produces random *numbers* up to 2x faster than `hat`, while still using a
CSPRNG.

## Prerequisites

This package should work on any reasonably modern browser or node.js version.

Every commit is tested using [continuous integration](https://travis-ci.org/)
on node.js 0.10 and above. Releases are also tested against the most recent
versions of [Chrome](https://www.google.com/chrome/),
[Firefox](https://www.mozilla.org/firefox/),
[Safari](http://www.apple.com/safari/), and
[Internet Explorer](http://windows.microsoft.com/internet-explorer/).

## Installation

Install using [npm](https://www.npmjs.com/) or [bower](http://bower.io/).

```bash
npm install cryptohat@1.x --save
bower install cryptohat@1.x --save
```

## Usage

`cryptohat` implements the `hat(bits, base)` API. The function takes in the
desired number of bits of randomness and the
[base/radix](https://en.wikipedia.org/wiki/Radix) that will be used to
represent the returned random number, and returns a string. The returned
strings are guaranteed to have the same length for a given bits/base
combination. As long as you don't need the `hat.rack` method, `cryptohat` can
be used as a drop-in replacement.

```javascript
var hat = require('cryptohat');

hat();  // '39a00e331acce7516a8ea69b85e191f0'
hat();  // '00549f7401ac0ba9ea1b791f50bc7b1e'
hat(53, 10);  // '6738095220277140'
```

Pass in zero (0) for the base argument to get a number. This is significantly
faster than obtaining a string and converting it into a number. Keep in mind
that JavaScript numbers can accurately represent integers of at most 53 bits.

```javascript
var cryptohat = require('cryptohat');

cryptohat(53, 0);  // 6738095220277140
cryptohat(32, 0);  // 3840742823
cryptohat(63, 0);  // RangeError: JavaScript numbers can accurately represent at most 53 bits
```

For maximum throughput, use the `cryptohat.generator` API. It takes exactly the
same arguments as the `hat` API, but it returns a generator function. Calling
the function yields random numbers or identifiers.

```javascript
var rng1 = cryptohat.generator(53, 0);
rng1();  // 4438236126178078
rng1();  // 187896805323588

var rng2 = cryptohat.generator(32, 10);
rng2();  // '0053668130'
rng2();  // '1939036909'
```

## Development

After cloning the repository, install the dependencies.

```bash
npm install
node node_modules/.bin/bower install
```

Make sure the tests pass after making a change.

```bash
SKIP_BENCHMARKS=1 npm test
```

When adding new functionality, make sure it has good test coverage and that it
does not regress the code's performance.

```bash
SKIP_BENCHMARKS=1 npm run cov
npm test
```

When adding new functionality, also make sure that the documentation looks
reasonable.

```bash
npm run doc
```

When modifying code around or inside feature detection blocks (combinations of
`if` and `typeof`), make sure the tests pass at least in Chrome and Firefox, by
opening [test/index.html](./test/index.html) in the browsers.

```bash
open test/index.html  # On OSX.
xdg-open test/index.html  # On Linux.
```

When testing against a browser in a VM (e.g., for Internet Explorer), spawn a
local Web server inside the source tree and visit it inside the VM
(e.g., `http://10.0.2.2:8080/test/index.html`).

```bash
node node_modules/.bin/http-server
```

If you submit a
[pull request](https://help.github.com/articles/using-pull-requests/),
[Travis CI](https://travis-ci.org/) will run the test suite against your code
on the node versions that we support. Please fix any errors that it reports.

## Copyright

Copyright (c) 2016 Heap Inc., released under the MIT license.


text:
import os
import sys

sys.path.insert(0, '/app/apps')

os.path.dirname(os.path.realpath(__file__))


text:
"""
Performs in-place replacement of a chain identifier by another.

Usage:
    python pdb_rplchain.py -<from>:<to> <pdb file>

Example:
    python pdb_rplchain.py -A:B 1CTF.pdb # Replaces chain A for chain B

This program is part of the `pdb-tools` suite of utilities and should not be
distributed isolatedly. The `pdb-tools` were created to quickly manipulate PDB
files using the terminal, and can be used sequentially, with one tool streaming
data to another. They are based on old FORTRAN77 code that was taking too much
effort to maintain and compile. RIP.
"""

import os
import sys

__author__ = "Joao Rodrigues"
__email__ = "j.p.g.l.m.rodrigues@gmail.com"

def check_input(args):
    """Checks whether to read from stdin/file and validates user input/options.
    """

    # Defaults
    option = ':'
    fh = sys.stdin  # file handle

    if not len(args):
        # Reading from pipe with default option
        if sys.stdin.isatty():
            sys.stderr.write(__doc__)
            sys.exit(1)

    elif len(args) == 1:
        # One option: option & Pipe
        if args[0].startswith('-'):
            option = args[0][1:]
            if sys.stdin.isatty():  # ensure the PDB data is streamed in
                emsg = 'ERROR!! No data to process!\n'
                sys.stderr.write(emsg)
                sys.stderr.write(__doc__)
                sys.exit(1)

    elif len(args) == 2:
        # Two options: option & File
        if not args[0].startswith('-'):
            emsg = 'ERROR! First argument is not an option: \'{}\'\n'
            sys.stderr.write(emsg.format(args[0]))
            sys.stderr.write(__doc__)
            sys.exit(1)

        if not os.path.isfile(args[1]):
            emsg = 'ERROR!! File not found or not readable: \'{}\'\n'
            sys.stderr.write(emsg.format(args[1]))
            sys.stderr.write(__doc__)
            sys.exit(1)

        option = args[0][1:]
        fh = open(args[1], 'r')

    else:  # Whatever ...
        sys.stderr.write(__doc__)
        sys.exit(1)

    # Validate option
    if option.count(':') != 1 and len(option.split(':')) != 2:
        emsg = 'ERROR!! Invalid option value: \'{}\'\n'
        sys.stderr.write(emsg.format(option))
        sys.exit(1)

    chain_from, chain_to = option.split(':')

    if chain_from == chain_to == '':
        emsg = 'ERROR!! You did not provide any chain identifiers to replace'
        sys.stderr.write(emsg)
        sys.exit(1)

    if len(chain_from) > 1:
        emsg = 'ERROR!! Chain identifiers must be a single character: \'{}\''
        sys.stderr.write(emsg.format(chain_from))
        sys.exit(1)

    if len(chain_to) > 1:
        emsg = 'ERROR!! Chain identifiers must be a single character: \'{}\''
        sys.stderr.write(emsg.format(chain_to))
        sys.exit(1)

    if chain_from == '':
        chain_from = ' '
    if chain_to == '':
        chain_to = ' '

    return (fh, (chain_from, chain_to))

def run(fhandle, chain_ids):
    """
    Replace one chain identifier by another in the PDB file.

    This function is a generator.

    Parameters
    ----------
    fhandle : a line-by-line iterator of the original PDB file.

    chain_ids : tuple
        Two element tuple, where first item is the original chain id
        and the second element is the modified chain id.

    Yields
    ------
    str (line-by-line)
        The modified (or not) PDB line.
    """
    chain_from, chain_to = chain_ids

    records = ('ATOM', 'HETATM', 'TER', 'ANISOU')
    for line in fhandle:
        if line.startswith(records):
            if line[21] == chain_from:
                yield line[:21] + chain_to + line[22:]
                continue
        yield line

replace_chain_identifiers = run

def main():
    # Check Input
    pdbfh, chain_ids = check_input(sys.argv[1:])

    # Do the job
    new_pdb = run(pdbfh, chain_ids)

    try:
        _buffer = []
        _buffer_size = 5000  # write N lines at a time
        for lineno, line in enumerate(new_pdb):
            if not (lineno % _buffer_size):
                sys.stdout.write(''.join(_buffer))
                _buffer = []
            _buffer.append(line)

        sys.stdout.write(''.join(_buffer))
        sys.stdout.flush()
    except IOError:
        # This is here to catch Broken Pipes
        # for example to use 'head' or 'tail' without
        # the error message showing up
        pass

    # last line of the script
    # We can close it even if it is sys.stdin
    pdbfh.close()
    sys.exit(0)

if __name__ == '__main__':
    main()


text:
using Newtonsoft.Json.Linq;
using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;

namespace ShopifySharp
{
    /// <summary>
    /// A service for manipulating Shopify customers.
    /// </summary>
    public class CustomerAddressService : ShopifyService
    {
        /// <summary>
        /// Creates a new instance of <see cref="CustomerAddressService" />.
        /// </summary>
        /// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
        /// <param name="shopAccessToken">An API access token for the shop.</param>
        public CustomerAddressService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }

        /// <summary>
        /// Gets a list of up to 250 of the shop customers's addresses.
        /// </summary>
        /// <param name="customerId">The id of the customer to retrieve.</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<Address>> ListAsync(long customerId, ListFilter filter = null)
        {
            var req = PrepareRequest($"customers/{customerId}/addresses.json");

            if (filter != null)
            {
                req.QueryParams.AddRange(filter.ToParameters());
            }

            return await ExecuteRequestAsync<List<Address>>(req, HttpMethod.Get, rootElement: "addresses");
        }

        /// <summary>
        /// Retrieves the <see cref="Address"/> with the given id.
        /// </summary>
        /// <param name="customerId">The id of the customer to retrieve.</param>
        /// <param name="addressId">The id of the customer address to retrieve.</param>
        /// <param name="fields">A comma-separated list of fields to return.</param>
        /// <returns>The <see cref="Address"/>.</returns>
        public virtual async Task<Address> GetAsync(long customerId, long addressId, string fields = null)
        {
            var req = PrepareRequest($"customers/{customerId}/addresses/{addressId}.json");

            if (string.IsNullOrEmpty(fields) == false)
            {
                req.QueryParams.Add("fields", fields);
            }

            return await ExecuteRequestAsync<Address>(req, HttpMethod.Get, rootElement: "customer_address");
        }

        /// <summary>
        /// Creates a new <see cref="Address"/> on the store.
        /// </summary>
        /// <param name="customerId">The id of the customer to create address for.</param>
        /// <param name="address">A new <see cref="Address"/>. Id should be set to null.</param>
        /// <returns>The new <see cref="Address"/>.</returns>
        public virtual async Task<Address> CreateAsync(long customerId, Address address)
        {
            var req = PrepareRequest($"customers/{customerId}/addresses.json");
            var addressBody = address.ToDictionary();
            var content = new JsonContent(new
            {
                address = addressBody
            });

            return await ExecuteRequestAsync<Address>(req, HttpMethod.Post, content, "customer_address");
        }

        /// <summary>
        /// Updates the given <see cref="Address"/>.
        /// </summary>
        /// <param name="customerId">Id of the customer object being updated.</param>
        /// <param name="addressId">Id of the address object being updated.</param>
        /// <param name="address">The <see cref="Address"/> to update.</param>
        /// <returns>The updated <see cref="Customer"/>.</returns>
        public virtual async Task<Address> UpdateAsync(long customerId, long addressId, Address address)
        {
            var req = PrepareRequest($"customers/{customerId}/addresses/{addressId}.json");
            var addressBody = address.ToDictionary();

            var content = new JsonContent(new
            {
                address = addressBody
            });

            return await ExecuteRequestAsync<Address>(req, HttpMethod.Put, content, "customer_address");
        }

        /// <summary>
        /// Deletes a address with the given Id from a customer.
        /// </summary>
        /// <param name="customerId">The customer object's Id.</param>
        /// <param name="addressId">The address object's Id.</param>
        public virtual async Task DeleteAsync(long customerId, long addressId)
        {
            var req = PrepareRequest($"customers/{customerId}/addresses/{addressId}.json");

            await ExecuteRequestAsync(req, HttpMethod.Delete);
        }

        /// <summary>
        /// Sets the specified address as the default for a customer
        /// </summary>
        /// <param name="customerId">The customer object's Id.</param>
        /// <param name="addressId">The address object's Id.</param>
        /// <returns></returns>
        public virtual async Task<Address> SetDefault(long customerId, long addressId)
        {
            var req = PrepareRequest($"customers/{customerId}/addresses/{addressId}/default.json");

            return await ExecuteRequestAsync<Address>(req, HttpMethod.Put, rootElement: "customer_address");

        }

    }
}


text: cp python/*.py $PREFIX/bin/


text:
package cn.bishiti.base.service;

import java.util.List;
import java.util.Map;

import cn.bishiti.base.commons.page.Page;
import cn.bishiti.base.model.TUser;

public interface TUserService {
	List<TUser> selectPageByParam(Map<String,Object> map,Page page);

	int deleteByPrimaryKey(Integer id);

    int insert(TUser record);

    int insertSelective(TUser record);

    TUser selectByPrimaryKey(Integer id);

    List<TUser> selectByParam(Map<String,Object> map);

    int updateByPrimaryKeySelective(TUser record);

    int updateByPrimaryKey(TUser record);
}


text:
def setup_boxen
  puts `sudo mkdir -p /opt/boxen`
  puts `sudo chown ${USER}:staff /opt/boxen`
  puts `git clone https://github.com/kenmazaika/firehose-boxen.git /opt/boxen/repo`
  puts
  puts
  puts "You're bootstrapped with boxen.  Run the following command in the terminal:"
  puts "cd /opt/boxen/repo && ./script/boxen"
end

setup_boxen


text:
<?php
    require_once('dbconfig.php');
    require "vendor/autoload.php";
    date_default_timezone_set('UTC');
	//PUT YOUR SID and TOKEN.
    $account_sid = 'zzz';
    $auth_token = 'zzz';

    $con=mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die("Error " . mysqli_error($con));

    $client = new Services_Twilio($account_sid, $auth_token);
    $messages = $client->account->messages->getIterator(0, 50, array(
        //'To' => "xxx-xxx-xxx",// PUT NUMBER TO SEND SMS
        //'DateSent'=>'"'.date('Y-m-d').'"'
        //'DateSent'=>'"'.date('Y-m-d').'"'
    ));
    foreach($messages as $message){
        $sid=isset($message->sid)?$message->sid:'';
        $date_created=isset($message->date_created)?$message->date_created:'';
	$date_updated=isset($message->date_updated)?$message->date_updated:'';
        $date_sent=isset($message->date_sent)?$message->date_sent:'';
        $account_sid=isset($message->account_sid)?$message->account_sid:'';
        $num_to=isset($message->to)?$message->to:'';
        $num_from=isset($message->from)?$message->from:'';
        $body=isset($message->body)?$message->body:'';
        $status=isset($message->status)?$message->status:'';
        $num_segments=isset($message->num_segments)?$message->num_segments:1;
        $num_media=isset($message->num_media)?$message->num_media:0;
        $direction=isset($message->direction)?$message->direction:'';
        $api_version=isset($message->api_version)?$message->api_version:'';
        $price=isset($message->price)?$message->price:0.0;
        $price_unit=isset($message->price_unit)?$message->price_unit:'';
        $error_code=isset($message->error_code)?$message->error_code:0;
        $error_message=isset($message->error_message)?$message->error_message:'';

	$smallcasedBody=strtolower(trim(trim($body, "\"")));
	if((strpos($smallcasedBody, 'cancel')===0)||(strpos($smallcasedBody, 'usage')===0)){
		echo $smallcasedBody;
		//continue;

        $sqlCheck="SELECT COUNT(*) AS TOTAL ".
            "FROM messages ".
            "WHERE ".
            "sid='".$sid."';";
        $result=mysqli_query($con, $sqlCheck);
        $result=mysqli_fetch_array($result, MYSQLI_ASSOC);
        $res=$result['TOTAL'];
        if($res>0){
            $sqlUpdate="UPDATE messages SET ".
                "date_created='".mysqli_real_escape_string($con, $date_created)."', ".
                "date_updated='".mysqli_real_escape_string($con, $date_updated)."', ".
                "date_sent='".mysqli_real_escape_string($con, $date_sent)."', ".
                "account_sid='".mysqli_real_escape_string($con, $account_sid)."', ".
                "num_to='".mysqli_real_escape_string($con, $num_to)."', ".
                "num_from='".mysqli_real_escape_string($con, $num_from)."', ".
                "body='".mysqli_real_escape_string($con, $body)."', ".
                "status='".mysqli_real_escape_string($con, $status)."', ".
                "num_segments=".mysqli_real_escape_string($con, $num_segments).", ".
                "num_media=".mysqli_real_escape_string($con, $num_media).", ".
                "direction='".mysqli_real_escape_string($con, $direction)."', ".
                "api_version='".mysqli_real_escape_string($con, $api_version)."', ".
                "price=".mysqli_real_escape_string($con, $price).", ".
                "price_unit='".mysqli_real_escape_string($con, $price_unit)."', ".
                "error_code=".mysqli_real_escape_string($con, $error_code).", ".
                "error_message='".mysqli_real_escape_string($con, $error_message)."', ".
		"modified=now() WHERE ".
                "sid='".$sid."';";
		//echo $sqlUpdate.PHP_EOL;
		$result=mysqli_query($con, $sqlUpdate);
		if($result){
			echo "(sid)=($sid) Updated Properly.".PHP_EOL;
		}else{
			echo "(sid)=($sid) Not Updated.".PHP_EOL;
		}
	}else{
	     $sqlInsert="INSERT INTO messages(".
                "sid,".
                "date_created,".
                "date_updated,".
                "date_sent,".
                "account_sid,".
                "num_to,".
                "num_from,".
                "body,".
                "status,".
                "num_segments,".
                "num_media,".
                "direction,".
                "api_version,".
                "price,".
                "price_unit,".
                "error_code,".
                "error_message,".
                "created) VALUES(".
                "'".mysqli_real_escape_string($con, $sid)."',".
                "'".mysqli_real_escape_string($con, $date_created)."',".
                "'".mysqli_real_escape_string($con, $date_updated)."',".
                "'".mysqli_real_escape_string($con, $date_sent)."',".
                "'".mysqli_real_escape_string($con, $account_sid)."',".
                "'".mysqli_real_escape_string($con, $num_to)."',".
                "'".mysqli_real_escape_string($con, $num_from)."',".
                "'".mysqli_real_escape_string($con, $body)."',".
                "'".mysqli_real_escape_string($con, $status)."',".
                "'".mysqli_real_escape_string($con, $num_segments)."',".
                "'".mysqli_real_escape_string($con, $num_media)."',".
                "'".mysqli_real_escape_string($con, $direction)."',".
                "'".mysqli_real_escape_string($con, $api_version)."',".
                "'".mysqli_real_escape_string($con, $price)."',".
                "'".mysqli_real_escape_string($con, $price_unit)."',".
		"'".mysqli_real_escape_string($con, $error_code)."',".
                "'".mysqli_real_escape_string($con, $error_message)."',".
                "now());";
            //echo $sqlInsert.PHP_EOL;
            $result=mysqli_query($con, $sqlInsert);
	    if($result){
		echo "(sid)=($sid) Inserted Properly.".PHP_EOL;
	    }else{
		echo "(sid)=($sid) Not Inserted.".PHP_EOL;
	    }
	}
	}
    }
?>


text:
import {cpus} from 'os';
import WorkerPool from './WorkerPool';
import Farm from './Farm';
import {
  FarmOptions,
  PoolExitResult,
  WorkerPoolInterface,
  WorkerPoolOptions,
} from './types';

function getExposedMethods(
  workerPath: string,
  options: FarmOptions,
): ReadonlyArray<string> {
  let exposedMethods = options.exposedMethods;

  // If no methods list is given, try getting it by auto-requiring the module.
  if (!exposedMethods) {
    const module: Function | Record<string, any> = require(workerPath);

    exposedMethods = Object.keys(module).filter(
      // @ts-ignore: no index
      name => typeof module[name] === 'function',
    );

    if (typeof module === 'function') {
      exposedMethods = [...exposedMethods, 'default'];
    }
  }

  return exposedMethods;
}

/**
 * The Jest farm (publicly called "Worker") is a class that allows you to queue
 * methods across multiple child processes, in order to parallelize work. This
 * is done by providing an absolute path to a module that will be loaded on each
 * of the child processes, and bridged to the main process.
 *
 * Bridged methods are specified by using the "exposedMethods" property of the
 * "options" object. This is an array of strings, where each of them corresponds
 * to the exported name in the loaded module.
 *
 * You can also control the amount of workers by using the "numWorkers" property
 * of the "options" object, and the settings passed to fork the process through
 * the "forkOptions" property. The amount of workers defaults to the amount of
 * CPUS minus one.
 *
 * Queueing calls can be done in two ways:
 *   - Standard method: calls will be redirected to the first available worker,
 *     so they will get executed as soon as they can.
 *
 *   - Sticky method: if a "computeWorkerKey" method is provided within the
 *     config, the resulting string of this method will be used as a key.
 *     Every time this key is returned, it is guaranteed that your job will be
 *     processed by the same worker. This is specially useful if your workers
 *     are caching results.
 */
export default class JestWorker {
  private _ending: boolean;
  private _farm: Farm;
  private _options: FarmOptions;
  private _workerPool: WorkerPoolInterface;

  constructor(workerPath: string, options?: FarmOptions) {
    this._options = {...options};
    this._ending = false;

    const workerPoolOptions: WorkerPoolOptions = {
      enableWorkerThreads: this._options.enableWorkerThreads || false,
      forkOptions: this._options.forkOptions || {},
      maxRetries: this._options.maxRetries || 3,
      numWorkers: this._options.numWorkers || Math.max(cpus().length - 1, 1),
      setupArgs: this._options.setupArgs || [],
    };

    if (this._options.WorkerPool) {
      // @ts-ignore: constructor target any?
      this._workerPool = new this._options.WorkerPool(
        workerPath,
        workerPoolOptions,
      );
    } else {
      this._workerPool = new WorkerPool(workerPath, workerPoolOptions);
    }

    this._farm = new Farm(
      workerPoolOptions.numWorkers,
      this._workerPool.send.bind(this._workerPool),
      this._options.computeWorkerKey,
    );

    this._bindExposedWorkerMethods(workerPath, this._options);
  }

  private _bindExposedWorkerMethods(
    workerPath: string,
    options: FarmOptions,
  ): void {
    getExposedMethods(workerPath, options).forEach(name => {
      if (name.startsWith('_')) {
        return;
      }

      if (this.constructor.prototype.hasOwnProperty(name)) {
        throw new TypeError('Cannot define a method called ' + name);
      }

      // @ts-ignore: dynamic extension of the class instance is expected.
      this[name] = this._callFunctionWithArgs.bind(this, name);
    });
  }

  private _callFunctionWithArgs(
    method: string,
    ...args: Array<any>
  ): Promise<any> {
    if (this._ending) {
      throw new Error('Farm is ended, no more calls can be done to it');
    }

    return this._farm.doWork(method, ...args);
  }

  getStderr(): NodeJS.ReadableStream {
    return this._workerPool.getStderr();
  }

  getStdout(): NodeJS.ReadableStream {
    return this._workerPool.getStdout();
  }

  async end(): Promise<PoolExitResult> {
    if (this._ending) {
      throw new Error('Farm is ended, no more calls can be done to it');
    }
    this._ending = true;

    return this._workerPool.end();
  }
}


text:
layout: doc_fr
title: Comment faire
previous: Outils - Analyse de la Mémoire
previous_url: tools/memory-analysis
next: Ecrire un Ticket
next_url: how-to/write-a-ticket
review: true
---

1. [Ecrire un ticket](/doc/en/how-to/write-a-ticket/)
1. [Ecrire un Test Ruby](/doc/en/how-to/write-a-ruby-spec/)
1. [Corriger un Test En Echec](/doc/en/how-to/fix-a-failing-spec/)
1. [Ecrire des Benchmarks](/doc/en/how-to/write-benchmarks/)
1. [Ecrire un Billet pour le Blog](/doc/en/how-to/write-a-blog-post/)
1. [Ecrire de la Documentation](/doc/en/how-to/write-documentation/)
1. [Traduire la Documentation](/doc/en/how-to/translate-documentation/)


text:
package gomail

import (
	"strings"
	"testing"
)

type testMessage struct {
	error            string
	waited, excluded []string
}

func checkMessage(t *testing.T, message *Message, test *testMessage) {
	messageString := message.String()

	for _, waited := range test.waited {
		if !strings.Contains(messageString, waited) {
			t.Errorf("%s, wait: %q, got: %q", test.error, test.waited, messageString)
		}
	}

	for _, excluded := range test.excluded {
		if strings.Contains(messageString, excluded) {
			t.Errorf("%s, not wait: %q, got: %q", test.error, test.waited, messageString)
		}
	}
}

/**
 * Tests.
 */
func TestMessageHeaderFromWithoutName(t *testing.T) {
	message := NewMessage()
	message.From.Address = "test@test.com"

	checkMessage(t, message, &testMessage{
		waited: []string{"From: <test@test.com>\n"},
		error:  "Mail with From header without name",
	})
	checkMessage(t, message, &testMessage{
		waited: []string{"Reply-To: <test@test.com>\n"},
		error:  "Mail with From header without name and without Reply-to header",
	})
}

func TestMessageHeaderFromWithName(t *testing.T) {
	message := NewMessage()
	message.From.Address = "test@test.com"
	message.From.Name = "test test"

	checkMessage(t, message, &testMessage{
		waited: []string{"From: \"test test\" <test@test.com>\n"},
		error:  "Mail with From header with name",
	})
	checkMessage(t, message, &testMessage{
		waited: []string{"Reply-To: \"test test\" <test@test.com>\n"},
		error:  "Mail with From header without name and without Reply-to header",
	})
}

func TestMessageHeaderReplyToWithoutName(t *testing.T) {
	message := NewMessage()
	message.ReplyTo.Address = "test@test.com"

	checkMessage(t, message, &testMessage{
		waited: []string{"Reply-To: <test@test.com>\n"},
		error:  "Mail with Reply-To header without name",
	})
}

func TestMessageHeaderReplyToWithName(t *testing.T) {
	message := NewMessage()
	message.ReplyTo.Address = "test@test.com"
	message.ReplyTo.Name = "test test"

	checkMessage(t, message, &testMessage{
		waited: []string{"Reply-To: \"test test\" <test@test.com>\n"},
		error:  "Mail with Reply-To header with name",
	})
}

func TestMessageHeaderToWithoutName(t *testing.T) {
	message := NewMessage()
	message.To.Address = "test@test.com"

	checkMessage(t, message, &testMessage{
		waited: []string{"To: <test@test.com>\n"},
		error:  "Mail with To header without name",
	})
}

func TestMessageHeaderToWithName(t *testing.T) {
	message := NewMessage()
	message.To.Address = "test@test.com"
	message.To.Name = "test test"

	checkMessage(t, message, &testMessage{
		waited: []string{"To: \"test test\" <test@test.com>\n"},
		error:  "Mail with To header with name",
	})
}

func TestMessageSubjectWithoutQuotedPrintableEncoding(t *testing.T) {
	message := NewMessage()
	message.Subject = "This is a simple, subject = of a mail."
	message.QuotedPrintable = false

	checkMessage(t, message, &testMessage{
		waited: []string{"Subject: This is a simple, subject = of a mail.\n"},
		error:  "Mail with Subject without quoted-printable encoding",
	})
}

func TestMessageSubjectWithQuotedPrintableEncoding(t *testing.T) {
	message := NewMessage()
	message.Subject = "This is a simple, subject = of a mail."
	message.QuotedPrintable = true

	checkMessage(t, message, &testMessage{
		waited: []string{"Subject: This is a simple, subject =3D of a mail.\n"},
		error:  "Mail with Subject with quoted-printable encoding",
	})
}

func TestMessageWithSinglePartWithoutQuotedPrintableEncoding(t *testing.T) {
	message := NewMessage()
	message.AddPart("Single part = of a mail.", "text/plain", "UTF-8")
	message.QuotedPrintable = false

	checkMessage(t, message, &testMessage{
		waited: []string{"Content-Type: text/plain; charset=UTF-8\n\nSingle part = of a mail.\n\n"},
		excluded: []string{
			"Content-Type: multipart/alternative;",
			"This is a MIME message.\n\n",
		},
		error: "Mail with a single part without quoted-printable encoding",
	})
}

func TestMessageWithSinglePartWithQuotedPrintableEncoding(t *testing.T) {
	message := NewMessage()
	message.AddPart("Single part = of a mail.", "text/plain", "UTF-8")
	message.QuotedPrintable = true

	checkMessage(t, message, &testMessage{
		waited: []string{"Content-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: quoted-printable\n\nSingle part =3D of a mail.\n\n"},
		excluded: []string{
			"Content-Type: multipart/alternative;",
			"This is a MIME message.\n\n",
		},
		error: "Mail with a single part with quoted-printable encoding",
	})
}

func TestMessageWithMultiPartsWithoutQuotedPrintableEncoding(t *testing.T) {
	message := NewMessage()
	message.AddPart("Single part = of a mail.", "text/plain", "UTF-8")
	message.AddPart("
Single part = of a mail.
", "text/html", "UTF-8")
	message.QuotedPrintable = false

	checkMessage(t, message, &testMessage{
		waited: []string{
			"Content-Type: multipart/alternative; boundary=",
			"This is a MIME message.\n\n",
			"Content-Type: text/plain; charset=UTF-8\n\nSingle part = of a mail.\n\n",
			"Content-Type: text/html; charset=UTF-8\n\n
Single part = of a mail.
\n\n",
		},
		error: "Mail with multi parts without quoted-printable encoding",
	})
}

func TestMessageWithMultiPartsWithQuotedPrintableEncoding(t *testing.T) {
	message := NewMessage()
	message.AddPart("Single part = of a mail.", "text/plain", "UTF-8")
	message.AddPart("
Single part = of a mail.
", "text/html", "UTF-8")
	message.QuotedPrintable = true

	checkMessage(t, message, &testMessage{
		waited: []string{
			"Content-Type: multipart/alternative; boundary=",
			"This is a MIME message.\n\n",
			"Content-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: quoted-printable\n\nSingle part =3D of a mail.\n\n",
			"Content-Type: text/html; charset=UTF-8\nContent-Transfer-Encoding: quoted-printable\n\n
Single part =3D of a mail.
\n\n",
		},
		error: "Mail with multi parts with quoted-printable encoding",
	})
}


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

package com.google.devtools.j2objc.translate;

import com.google.devtools.j2objc.GenerationTest;

import java.io.IOException;

/**
 * Unit tests for {@link VarargsRewriter} class.
 *
 * @author Tom Ball, Keith Stanger
 */
public class VarargsRewriterTest extends GenerationTest {

  // Issue 360: a null argument for a varargs parameter should not be rewritten
  // as an array.
  public void testNilVarargs() throws IOException {
    String source =
        "public class Test { "
        + "  void foo(char... chars) {}"
        + "  void test() { foo(null); }}";
    String translation = translateSourceFile(source, "Test", "Test.m");
    assertTranslation(translation, "[self fooWithCharArray:nil];");
    assertNotInTranslation(translation,
        "[self fooWithCharArray:[IOSCharArray arrayWithChars:(unichar[]){ nil } count:1]];");
  }

  // Verify that a single object array argument to an object varargs method is passed unchanged.
  public void testObjectArrayVarargs() throws IOException {
    String translation = translateSourceFile(
        "class Test { void test(Object[] array) { java.util.Arrays.asList(array); }}",
        "Test", "Test.m");
    assertTranslation(translation, "JavaUtilArrays_asListWithNSObjectArray_(array);");
  }

  // Verify that a single primitive array argument to a primitive varargs method is
  // passed unchanged.
  public void testPrimitiveArrayVarargs() throws IOException {
    String translation = translateSourceFile(
        "class Test { void doVarargs(int... ints) {}"
        + "void test(int[] array) { doVarargs(array); }}",
        "Test", "Test.m");
    assertTranslation(translation, "[self doVarargsWithIntArray:array];");
  }

  // Verify that a single primitive array argument to an object varargs method is just treated
  // like any other object.
  public void testPrimitiveArrayToObjectVarargs() throws IOException {
    String translation = translateSourceFile(
        "class Test { void test(float[] array) { java.util.Arrays.asList(array); }}",
        "Test", "Test.m");
    assertTranslation(translation, "JavaUtilArrays_asListWithNSObjectArray_("
        + "[IOSObjectArray arrayWithObjects:(id[]){ array } count:1 "
        + "type:IOSClass_floatArray(1)]);");
  }

  public void testMultiDimPrimitiveArrayPassedToTypeVariableVarargs() throws IOException {
    String translation = translateSourceFile(
        "class Test { void test(int[][] array) { java.util.Arrays.asList(array); } }",
        "Test", "Test.m");
    // Array should be passed as it is.
    assertTranslation(translation, "JavaUtilArrays_asListWithNSObjectArray_(array);");
  }

  public void testTwoDimObjectArrayPassedToObjectVarargs() throws IOException {
    String translation = translateSourceFile(
        "class Test { void foo(Object... args) {} void test(Object[][] array) { foo(array); } }",
        "Test", "Test.m");
    // Array should be passed as it is.
    assertTranslation(translation, "[self fooWithNSObjectArray:array];");
  }
}


text:
package com.rgpt.serverhandler;

import java.util.Vector;

public interface ImageHandlerInterface
{
   // This identifies the different modes supported for uploading the Image. They
   // incude Image downloaded from Server, Client Machiene, or from Flickr
   public static int SERVER_IMAGES = 0;
   // This is to show Desktop Images
   public static int DESKTOP_IMAGES = 1;
   public static int FLICKR_IMAGES = 2;
   // This constant is used for Uploading Desktop Images by Opening the File System
   public static int UPLOAD_DESKTOP_IMAGES = 3;

   // There could be many Themes that could be loaded from the server. This will
   // all have number starting from the Hundred series
   public static int THEME_IMAGES = 100;

   // This DPI configuration is used for Down Sampling the Actual Image.
   public static int IMAGE_DIAPLAY_DPI = 150;
   public static int IMAGE_PRINT_DPI = 300;

   // This function is called by the ImageUploadImterface to handle the new
   // images downloaded from one of the modes defined above.
   public void handleImagesUploaded(Vector imageHolders,
                                    int imageDownloadMode) throws Exception;

   // This API is to show Busy Cursor when the Image is getting uploaded
   public void showBusyCursor();
}


text:
@implementation WASPopList

@end


text:
const fs = require('fs');
const path = require('path');

/**
 * Recursively create a directory if it doesn't exist.
 *
 * @param {string} directory - Directory to create.
 *
 * @returns {Promise} - Fullfills with undefined upon success.
 */
async function mkdirs(directory) {
  let createDirectory = false;
  try {
    await fs.promises.access(directory, fs.constants.R_OK | fs.constants.W_OK);
  } catch (e) {
    createDirectory = true;
  }
  if (createDirectory) {
    await fs.promises.mkdir(directory, {recursive: true});
  }
  return Promise.resolve();
}

/**
 * Recursively list files in a directory.
 *
 * @param {string} directory - Directory to recursively list.
 *
 * @returns {Promise<string[]>} - Fullfills with a list of files under the
 * specified directory.
 */
async function walkDirectory(directory) {
  let files = [];
  for (const directoryEntry of
       await fs.promises.readdir(directory, {withFileTypes: true})) {
    let filename = path.resolve(directory, directoryEntry.name);
    files.push(filename);
    if (directoryEntry.isDirectory()) {
      files.push(...await walkDirectory(filename));
    }
  }
  return Promise.resolve(files.sort());
}

/**
 * Write a text file creating intermediate directories if required.
 *
 * @param {string} filename - File to write.
 * @param {string} contents - Text to write to the file.
 *
 * @returns {Promise} - Fullfills with the absolute path to the written file
 * upon success.
 */
async function writeFile(filename, contents) {
  await mkdirs(path.dirname(filename));
  await fs.promises.writeFile(filename, contents);
  return Promise.resolve(path.resolve(__dirname, filename));
}

exports.mkdirs = mkdirs;
exports.walkDirectory = walkDirectory;
exports.writeFile = writeFile;


text:
package uk.ac.ncl.openlab.intake24.services.foodindex.english

import javatools.parsers.PlingStemmer
import org.workcraft.phrasesearch.CaseInsensitiveString
import com.google.inject.Singleton

@Singleton
case class EnglishWordOpsPlingImpl() extends EnglishWordOps {
  def stem(word: CaseInsensitiveString) = CaseInsensitiveString(PlingStemmer.stem(word.lowerCase))

  def splitCompound(word: CaseInsensitiveString): Seq[CaseInsensitiveString] = Seq(word) // no need to split compound words in English
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using Magecrawl.Actors;
using Magecrawl.EngineInterfaces;
using Magecrawl.GameEngine.Magic;
using Magecrawl.GameEngine.Skills;
using Magecrawl.Interfaces;
using Magecrawl.Items;
using Magecrawl.StatusEffects.Interfaces;
using Magecrawl.Utilities;

namespace Magecrawl.GameEngine
{
    internal sealed class Player : Character, IPlayer, IXmlSerializable
    {
        private Random s_random = new Random();

        public IArmor ChestArmor { get; internal set; }
        public IArmor Headpiece { get; internal set; }
        public IArmor Gloves { get; internal set; }
        public IArmor Boots { get; internal set; }

        public int SkillPoints { get; internal set; }

        private List<Item> m_itemList;
        private List<Skill> m_skills;

        public int LastTurnSeenAMonster { get; set; }

        public Player() : base()
        {
            m_itemList = null;
            m_skills = null;
            m_currentStamina = 0;
            m_baseMaxStamina = 0;
            m_currentHealth = 0;
            m_baseMaxHealth = 0;
            m_baseCurrentMP = 0;
            m_baseMaxStamina = 0;
            LastTurnSeenAMonster = 0;
            SkillPoints = 0;

            m_itemList = new List<Item>();
            m_skills = new List<Skill>();
        }

        public Player(string name, Point p) : base(name, p)
        {
            m_itemList = new List<Item>();
            m_skills = new List<Skill>();

            m_baseMaxStamina = 0;
            m_currentStamina = m_baseMaxStamina;

            m_baseMaxHealth = 70;
            m_currentHealth = m_baseMaxHealth;

            m_baseMaxMP = 5;
            m_baseCurrentMP = m_baseMaxMP;

            LastTurnSeenAMonster = 0;
        }

        public override int Vision
        {
            get
            {
                return 6 + GetTotalAttributeValue("VisionBonus");
            }
        }

        #region HP/MP

        internal void SetHPMPMax()
        {
            m_currentStamina = MaxStamina;
            m_currentHealth = MaxHealth;
            m_baseCurrentMP = MaxMP;
        }

        private int m_currentStamina;
        public int CurrentStamina
        {
            get
            {
                return m_currentStamina;
            }
        }

        private int m_currentHealth;
        public int CurrentHealth
        {
            get
            {
                return m_currentHealth;
            }
        }

        public override int CurrentHP
        {
            get
            {
                return CurrentHealth + CurrentStamina;
            }
        }

        private int m_baseMaxStamina;
        public int MaxStamina
        {
            get
            {
                int baseMaxStamina = m_baseMaxStamina + CombatDefenseCalculator.CalculateArmorStaminaBonus(this);
                double staminaPercentageBonus = 1 + (GetTotalAttributeValue("StaminaPercentageBonus") / 100.0);
                return (int)Math.Round(baseMaxStamina * staminaPercentageBonus) + GetTotalAttributeValue("BonusStamina");
            }
        }

        private int m_baseMaxHealth;
        public int MaxHealth
        {
            get
            {
                return m_baseMaxHealth + GetTotalAttributeValue("BonusHealth");
            }
        }

        public override int MaxHP
        {
            get
            {
                return MaxHealth + MaxStamina;
            }
        }

        private int m_baseCurrentMP;
        public int CurrentMP
        {
            get
            {
                return m_baseCurrentMP;
            }
        }

        // Similar logic is found in Spell::SustainingCost
        public int MaxMP
        {
            get
            {

                return (int)Math.Round(MaxPossibleMP * (1 - ((double)m_effects.OfType<ILongTermStatusEffect>().Sum(x => Math.Min(1, x.MPCost / 100.0)))));
            }
        }

        private int m_baseMaxMP;
        public int MaxPossibleMP
        {
            get
            {
                return m_baseMaxMP + GetTotalAttributeValue("MPBonus");
            }
        }

        private void ResetMaxStaminaIfNowOver()
        {
            if (CurrentStamina > MaxStamina)
                m_currentStamina = MaxStamina;
        }

        private void ResetMaxMPIfNowOver()
        {
            if (CurrentMP > MaxMP)
                m_baseCurrentMP = MaxMP;
        }

        // Returns amount actually healed by
        public override int Heal(int toHeal, bool magical)
        {
            if (toHeal < 0)
                throw new InvalidOperationException("Heal with < 0.");

            int amountOfDamageToHeal = toHeal;
            int amountInTotalHealed = 0;
            if (magical)
            {
                int amountOfHealthMissing = MaxHealth - CurrentHealth;
                if (amountOfHealthMissing > 0)
                {
                    int amountOfHealthToHeal = Math.Min(amountOfDamageToHeal, amountOfHealthMissing);
                    m_currentHealth += amountOfHealthToHeal;
                    amountOfDamageToHeal -= amountOfHealthToHeal;
                    amountInTotalHealed = amountOfHealthToHeal;
                }
            }
            if (amountOfDamageToHeal > 0)
            {
                int amountOfStaminaMissing = MaxStamina - CurrentStamina;
                if (amountOfStaminaMissing > 0)
                {
                    int amountOfStaminaToHeal = Math.Min(amountOfDamageToHeal, amountOfStaminaMissing);
                    m_currentStamina += amountOfStaminaToHeal;
                    amountInTotalHealed += amountOfStaminaToHeal;
                }
            }
            return amountInTotalHealed;
        }

        public void EmptyStamina()
        {
            m_currentStamina = 0;
        }

        public override void DamageJustStamina(int dmg)
        {
            // Any extra damage is ignored
            int actualStaminaDamage = Math.Min(m_currentStamina, dmg);
            m_currentStamina -= actualStaminaDamage;
        }

        public override void Damage(int dmg)
        {
            double percentageOfStaminaGone = (MaxStamina - CurrentStamina) / (double)MaxStamina;

            // Based on the percetage of stamina left, that percentage of damage might leak through
            const double StaminaThreshholdForDamageLeaking = .20;
            bool damageLeaksThrough = percentageOfStaminaGone >= StaminaThreshholdForDamageLeaking && s_random.Chance(percentageOfStaminaGone - StaminaThreshholdForDamageLeaking);

            if (damageLeaksThrough)
            {
                // Some damage leaks through, no more than half
                int leakedDamage = (int)Math.Round(dmg * Math.Min(percentageOfStaminaGone - StaminaThreshholdForDamageLeaking, .5));
                int staminaDamage = dmg - leakedDamage;

                int actualStaminaDamage = Math.Min(m_currentStamina, staminaDamage);
                m_currentStamina -= actualStaminaDamage;

                m_currentHealth -= leakedDamage + (staminaDamage - actualStaminaDamage);
            }
            else
            {
                int amountOfDamageLeftToDo = dmg;
                int actualStaminaDamage = Math.Min(m_currentStamina, amountOfDamageLeftToDo);
                m_currentStamina -= actualStaminaDamage;
                amountOfDamageLeftToDo -= actualStaminaDamage;

                if (amountOfDamageLeftToDo > 0)
                {
                    int amountOfDamageToHealth = Math.Min(m_currentHealth, amountOfDamageLeftToDo);
                    m_currentHealth -= amountOfDamageToHealth;
                }
            }
        }

        public override bool IsDead
        {
            get
            {
                // We're still dead if our stamina is > 0 but leaked damage brings health < 0
                return CurrentHealth <= 0;
            }
        }

        public bool IsRegenerating
        {
            get
            {
                return HasAttribute("Regeneration");
            }
        }

        public void GainMP(int amount)
        {
            m_baseCurrentMP += amount;
            if (m_baseCurrentMP > MaxMP)
                m_baseCurrentMP = MaxMP;
        }

        public void SpendMP(int amount)
        {
            m_baseCurrentMP -= amount;
        }

        #endregion

        public IEnumerable<ISpell> Spells
        {
            get
            {
                List<ISpell> returnList = new List<ISpell>();
                foreach (Skill skill in m_skills.Where(s => s.Attributes.ContainsKey("AddSpell")))
                    returnList.Add(SpellFactory.Instance.CreateSpell(skill.Attributes["AddSpell"]));
                return returnList;
            }
        }

        public int SpellStrength(string spellType)
        {
            return 1 + GetTotalAttributeValue(spellType + "Proficiency");
        }

        public bool CouldCastSpell(ISpell spell)
        {
            return (CurrentMP - ((Spell)spell).SustainingCost) >= ((Spell)spell).Cost;
        }

        public override int GetTotalAttributeValue(string attribute)
        {
            int skillBonus = m_skills.Sum(s => s.Attributes.GetNumbericIfAny(attribute));
            int effectBonus = StatusEffects.OfType<IStatusEffectCore>().Where(e => e.ContainsKey(attribute)).Select(e => int.Parse(e.GetAttribute(attribute))).Sum();
            return effectBonus + skillBonus;
        }

        public override double GetTotalDoubleAttributeValue(string attribute)
        {
            int skillBonus = m_skills.Sum(s => s.Attributes.GetNumbericIfAny(attribute));
            double effectBonus = StatusEffects.OfType<IStatusEffectCore>().Where(e => e.ContainsKey(attribute)).Select(e => double.Parse(e.GetAttribute(attribute))).Sum();
            return effectBonus + skillBonus;
        }

        public override bool HasAttribute(string attribute)
        {
            bool existsInSkills = m_skills.Exists(s => s.Attributes.ContainsKey(attribute));
            bool existsInEffects = StatusEffects.OfType<IStatusEffectCore>().Any(e => e.ContainsKey(attribute));
            return existsInSkills || existsInEffects;
        }

        public IEnumerable<IItem> Items
        {
            get
            {
                foreach (Item i in m_itemList)
                {
                    yield return i;
                }
            }
        }

        public IEnumerable<IStatusEffect> StatusEffects
        {
            get
            {
                foreach (IStatusEffectCore e in m_effects)
                {
                    yield return e;
                }
            }
        }

        public IEnumerable<ISkill> Skills
        {
            get
            {
                foreach (Skill s in m_skills)
                {
                    yield return s;
                }
            }
        }

        public override void AddEffect(IStatusEffectCore effectToAdd)
        {
            base.AddEffect(effectToAdd);
            ResetMaxStaminaIfNowOver();
            ResetMaxMPIfNowOver();
        }

        public override void RemoveEffect(IStatusEffectCore effectToRemove)
        {
            base.RemoveEffect(effectToRemove);
            ResetMaxStaminaIfNowOver();
            ResetMaxMPIfNowOver();
        }

        public void AddSkill(ISkill skill)
        {
             m_skills.Add((Skill)skill);
        }

        private Weapon m_equipedWeapon;
        public override IWeapon CurrentWeapon
        {
            get
            {
                if (m_equipedWeapon == null)
                    return ItemFactory.Instance.CreateMeleeWeapon(this);
                return m_equipedWeapon;
            }
        }

        private Weapon m_secondaryWeapon;
        public IWeapon SecondaryWeapon
        {
            get
            {
                if (m_secondaryWeapon == null)
                    return ItemFactory.Instance.CreateMeleeWeapon(this);
                return m_secondaryWeapon;
            }
        }

        internal IItem Equip(IItem item)
        {
            if (item is IWeapon)
                return EquipWeapon((IWeapon)item);

            if (item is IArmor)
            {
                IArmor itemAsArmor = (IArmor)item;
                IItem previousArmor = null;
                switch (itemAsArmor.Type)
                {
                    case "ChestArmor":
                        previousArmor = ChestArmor;
                        ChestArmor = (IArmor)item;
                        break;
                    case "Helm":
                        previousArmor = Headpiece;
                        Headpiece = (IArmor)item;
                        break;
                    case "Gloves":
                        previousArmor = Gloves;
                        Gloves = (IArmor)item;
                        break;
                    case "Boots":
                        previousArmor = Boots;
                        Boots = (IArmor)item;
                        break;
                }
                ResetMaxStaminaIfNowOver();
                return previousArmor;
            }

            throw new System.InvalidOperationException("Don't know how to equip - " + item.GetType());
        }

        internal IItem Unequip(IItem item)
        {
            if (item is IWeapon)
                return UnequipWeapon();

            if (item is IArmor)
            {
                IArmor itemAsArmor = (IArmor)item;
                IItem previousArmor = null;
                switch (itemAsArmor.Type)
                {
                    case "ChestArmor":
                        previousArmor = ChestArmor;
                        ChestArmor = null;
                        break;
                    case "Helm":
                        previousArmor = Headpiece;
                        Headpiece = null;
                        break;
                    case "Gloves":
                        previousArmor = Gloves;
                        Gloves = null;
                        break;
                    case "Boots":
                        previousArmor = Boots;
                        Boots = null;
                        break;
                }
                ResetMaxStaminaIfNowOver();
                return previousArmor;
            }
            throw new System.InvalidOperationException("Don't know how to unequip - " + item.GetType());
        }

        private IWeapon EquipWeapon(IWeapon weapon)
        {
            if (weapon == null)
                throw new System.ArgumentException("EquipWeapon - Null weapon");

            Weapon oldWeapon = UnequipWeapon();

            m_equipedWeapon = (Weapon)weapon;
            if (m_equipedWeapon.IsRanged)
                m_equipedWeapon.LoadWeapon();

            return oldWeapon;
        }

        private Weapon UnequipWeapon()
        {
            if (m_equipedWeapon == null)
                return null;

            Weapon oldWeapon = (Weapon)m_equipedWeapon;
            m_equipedWeapon = null;
            return oldWeapon;
        }

        internal IWeapon EquipSecondaryWeapon(IWeapon weapon)
        {
            if (weapon == null)
                throw new System.ArgumentException("EquipSecondaryWeapon - Null weapon");

            IWeapon oldWeapon = UnequipSecondaryWeapon();

            m_secondaryWeapon = (Weapon)weapon;
            if (m_secondaryWeapon.IsRanged)
                m_secondaryWeapon.LoadWeapon();

            return oldWeapon;
        }

        public IWeapon UnequipSecondaryWeapon()
        {
            if (m_secondaryWeapon == null)
                return null;
            Weapon oldWeapon = (Weapon)m_secondaryWeapon;
            m_secondaryWeapon = null;
            return oldWeapon;
        }

        internal bool SwapPrimarySecondaryWeapons()
        {
            // If we're swapping to Melee and we're Melee
            if (CurrentWeapon.GetType() == typeof(MeleeWeapon) && SecondaryWeapon.GetType() == typeof(MeleeWeapon))
                return false;

            IWeapon mainWeapon = UnequipWeapon();
            IWeapon secondaryWeapon = UnequipSecondaryWeapon();

            if (secondaryWeapon != null)
                Equip(secondaryWeapon);

            if (mainWeapon != null)
                EquipSecondaryWeapon(mainWeapon);

            return true;
        }

        internal void TakeItem(Item i)
        {
            m_itemList.Add(i);
        }

        internal void RemoveItem(Item i)
        {
            m_itemList.Remove(i);
        }

        public override DiceRoll MeleeDamage
        {
            get
            {
                return new DiceRoll(7, 3);
            }
        }

        public override double MeleeCTCost
        {
            get
            {
                return 1.0;
            }
        }

        public override double Evade
        {
            get
            {
                return CombatDefenseCalculator.CalculateArmorEvade(this);
            }
        }

        public IList<EquipArmorReasons> CanNotEquipArmorReasons(IArmor armor)
        {
            List<EquipArmorReasons> reasonsList = new List<EquipArmorReasons>();
            if (armor.Type == "Boots" && ChestArmor != null)
            {
                // If I'm equiping boots and have chest armor, check to that the armor doesn't prevent that type
                if (((Item)ChestArmor).ContainsAttribute("RobesPreventBoots"))
                    reasonsList.Add(EquipArmorReasons.RobesPreventBoots);
            }
            if (armor.Type == "ChestArmor" && Boots != null)
            {
                // If I"m equipping chest armor that prevents wearing boots, make sure that I'm not already wearing some.
                if (((Item)armor).ContainsAttribute("RobesPreventBoots"))
                    reasonsList.Add(EquipArmorReasons.BootsPreventRobes);
            }

            switch (armor.Weight)
            {
                case ArmorWeight.Light:
                    break;
                case ArmorWeight.Standard:
                    if (!HasAttribute("StandardArmorProficiency"))
                        reasonsList.Add(EquipArmorReasons.Weight);
                    break;
                case ArmorWeight.Heavy:
                    if (!HasAttribute("HeavyArmorProficiency"))
                        reasonsList.Add(EquipArmorReasons.Weight);
                    break;
                default:
                    throw new System.InvalidOperationException("CouldEquip doesn't know how to handle type - " + armor.Weight.ToString());
            }
            return reasonsList;
        }

        public bool CanEquipArmor(IArmor armor)
        {
            return CanNotEquipArmorReasons(armor).Count == 0;
        }

        public bool CanEquipWeapon(IWeapon weapon)
        {
            return HasAttribute("Basic" + weapon.Type + "Proficiency");
        }

        #region SaveLoad

        public override void ReadXml(XmlReader reader)
        {
            reader.ReadStartElement();
            base.ReadXml(reader);

            m_equipedWeapon = ReadWeaponFromSave(reader);
            m_secondaryWeapon = ReadWeaponFromSave(reader);

            m_currentHealth = reader.ReadElementContentAsInt();
            m_baseMaxHealth = reader.ReadElementContentAsInt();

            m_currentStamina = reader.ReadElementContentAsInt();
            m_baseMaxStamina = reader.ReadElementContentAsInt();

            m_baseCurrentMP = reader.ReadElementContentAsInt();
            m_baseMaxMP = reader.ReadElementContentAsInt();

            SkillPoints = reader.ReadElementContentAsInt();

            LastTurnSeenAMonster = reader.ReadElementContentAsInt();

            ChestArmor = (IArmor)Item.ReadXmlEntireNode(reader);
            Headpiece = (IArmor)Item.ReadXmlEntireNode(reader);
            Gloves = (IArmor)Item.ReadXmlEntireNode(reader);
            Boots = (IArmor)Item.ReadXmlEntireNode(reader);

            m_itemList = new List<Item>();
            ReadListFromXMLCore readItemDelegate = new ReadListFromXMLCore(delegate
            {
                string typeString = reader.ReadElementContentAsString();
                Item newItem = ItemFactory.Instance.CreateBaseItem(typeString);
                newItem.ReadXml(reader);
                m_itemList.Add(newItem);
            });
            ListSerialization.ReadListFromXML(reader, readItemDelegate);

            m_skills = new List<Skill>();
            ReadListFromXMLCore readSkillDelegate = new ReadListFromXMLCore(delegate
            {
                string skillName = reader.ReadElementContentAsString();
                m_skills.Add(SkillFactory.Instance.CreateSkill(skillName));
            });
            ListSerialization.ReadListFromXML(reader, readSkillDelegate);
            reader.ReadEndElement();
        }

        public override void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("Player");
            base.WriteXml(writer);

            WriteWeaponToSave(writer, m_equipedWeapon);
            WriteWeaponToSave(writer, m_secondaryWeapon);

            writer.WriteElementString("BaseCurrentHealth", m_currentHealth.ToString());
            writer.WriteElementString("BaseMaxHealth", m_baseMaxHealth.ToString());

            writer.WriteElementString("BaseCurrentStamina", m_currentStamina.ToString());
            writer.WriteElementString("BaseMaxStamina", m_baseMaxStamina.ToString());

            writer.WriteElementString("BaseCurrentMagic", m_baseCurrentMP.ToString());
            writer.WriteElementString("BaseMaxMagic", m_baseMaxMP.ToString());

            writer.WriteElementString("SkillPoints", SkillPoints.ToString());

            writer.WriteElementString("LastTurnSeenAMonster", LastTurnSeenAMonster.ToString());

            Item.WriteXmlEntireNode((Item)ChestArmor, "ChestArmor", writer);
            Item.WriteXmlEntireNode((Item)Headpiece, "Headpiece", writer);
            Item.WriteXmlEntireNode((Item)Gloves, "Gloves", writer);
            Item.WriteXmlEntireNode((Item)Boots, "Boots", writer);

            ListSerialization.WriteListToXML(writer, m_itemList, "Items");
            ListSerialization.WriteListToXML(writer, m_skills, "Skills");

            writer.WriteEndElement();
        }

        private Weapon ReadWeaponFromSave(XmlReader reader)
        {
            Weapon readWeapon = (Weapon)Item.ReadXmlEntireNode(reader);
            if (readWeapon is MeleeWeapon)
                ((MeleeWeapon)readWeapon).SetWielder(this);
            return readWeapon;
        }

        private void WriteWeaponToSave(XmlWriter writer, Weapon weapon)
        {
            Item.WriteXmlEntireNode(weapon, "EquipedWeapon", writer);
        }

        #endregion
    }
}


text:
Posts = new Meteor.Collection("posts");

Posts.isQuestion = function(text){
  return Questions.find({question: text}, {reactive: false}).count();
}


text:
package config;

public class InnerButton
{
	String type;
	String url;
    String title;

	public InnerButton(String type, String url, String title) {
		super();
		this.type = type;
		this.url = url;
		this.title = title;
	}
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public InnerButton() {
		super();
		// TODO Auto-generated constructor stub
	}

}


text:
/*jslint node: true */
"use strict";

var NobleDevice = require('noble-device');

var Bean = require('./lib/Bean');

var ScratchOne = require('./lib/ScratchOne');
var ScratchTwo = require('./lib/ScratchTwo');
var ScratchThree = require('./lib/ScratchThree');
var ScratchFour = require('./lib/ScratchFour');
var ScratchFive = require('./lib/ScratchFive');

NobleDevice.Util.mixin(Bean, NobleDevice.BatteryService);
NobleDevice.Util.mixin(Bean, NobleDevice.DeviceInformationService);

NobleDevice.Util.mixin(Bean, ScratchOne);
NobleDevice.Util.mixin(Bean, ScratchTwo);
NobleDevice.Util.mixin(Bean, ScratchThree);
NobleDevice.Util.mixin(Bean, ScratchFour);
NobleDevice.Util.mixin(Bean, ScratchFive);

module.exports = Bean;


text:
typedef struct ConsoleOptionsDialog ConsoleOptionsDialog;
struct ConsoleOptionsDialog {
        int32_t unknown[0];
};


text:
layout: example.html
title: Limited Layer Extent
shortdesc: Restricting layer rendering to a limited extent.
docs: >
  This example uses the layer.setExtent() method to
  modify the extent of the overlay layer.  Use the controls above
  to limit rendering based on an extent (approximate country bounds).
tags: "extent, tilejson"
cloak:
- key: pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2t0cGdwMHVnMGdlbzMxbDhwazBic2xrNSJ9.WbcTL9uj8JPAsnT9mgb7oQ
  value: Your Mapbox access token from https://mapbox.com/ here
---

<button type="button" class="btn btn-default" id="India">India</button>
<button type="button" class="btn btn-default" id="Argentina">Argentina</button>
<button type="button" class="btn btn-default" id="Nigeria">Nigeria</button>
<button type="button" class="btn btn-default" id="Sweden">Sweden</button>


text:
import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib import animation

import constants
from Car import Car
from Street import Street

def time_to_steps(t):
    return int(t/dt +1)

def prob(p):
    a = random.uniform(0,1)
    if a<p:
        return True
    else:
        return False

def generate_cars(i):
    """ generates cars with random initial values and adds them to the street, using the add_cars() funtion inside the Street class. """
    if i%generation_step == 0:
        #later : check if there's no car in the generating point
        target_v = 7 #random.uniform(5, 10)
        x, v, min_dist = 0, random.uniform(1, target_v), random.uniform(1,5)
        print "car created with:", x, v, min_dist, target_v, "\n"
        c = Car(x, v, min_dist, target_v)
        s.add_car(c)
        lines.append(ax2.plot([], [], '-', lw=1)[0])

# taking inputs from the user:
# for testing purposes, I've commented them so not being stuck with typing inputs every time we test the main.py
# hint: a way of getting inputs as argument values should be implemented

"""
v_i = float( input("please enter the initial velocity in term of km/h = ") )
max_cars = int( input("please enter the max number of cars in the street = ") )
dt = float( input("please enter the time step for computation (e.g. 0.1, 0.01, ...) = ") )
total_time = float( input("please enter the total time of simulation (in seconds) = ") )
time_interval = float( input("please enter the time interval for adding new car to street (in seconds) = ") )
"""

t = 0.0
dt = constants.time_step
total_time = 200 # seconds
street_length = 500 # meters
max_cars = 20
#time_interval = 10
generation_step = time_to_steps(1)
max_steps = time_to_steps(total_time)

s = Street(street_length)

# First set up the figure, the axis, and the plot element we want to animate

""" Start: Plot Presetup """
fig = plt.figure()

ax1 = fig.add_subplot(211, autoscale_on=False, xlim=
(0, street_length), ylim=(-2, 2))
#ax1.grid()
ax1.set_title('Traffic Jam')

ax1.plot((0,street_length),(0.5,0.5),c='black')
ax1.plot((0,street_length),(-0.5,-0.5),c='black')
ax1.set_yticks([])

ax2 =fig.add_subplot(212, autoscale_on=False, xlim=(0, street_length), ylim=(0, 50))
ax2.set_ylabel('Time (s)')
ax2.set_xlabel('Cars Positions (m)')

#Animate the cars
line1, = ax1.plot([], [], marker='s',lw=0,markersize=3)

#Create a list that stores the plot for each cars history
lines = []

# initialization function: plot the background of each frame
def init():
    line1.set_data([], [])
    return line1

""" End: Plot Presetup """

def animate(i):
    """ This function does the main job, as well as generating the animation. This will be iterated by the Matplotlib's animation.FuncAnimation() function. """
    generate_cars(i) #Checks if should generate a new car, and does it

    #sets time and gets the position of each car. y position is set to zero by default.
    t=i*dt

    """
    # added these to stop a car for a while
    if len(s.cars)>1:
        if prob(0.1):
            bad_car = s.cars_[ random.randint( 0, len(s.cars) -1 ) ]
    """

    if len(s.cars)>2 and len(s.cars) < 20:
        bad_car = s.cars_[1]
        if t>15 and t< 20:
            bad_car.stop_ = True
        else:
            bad_car.stop_ = False

    if len(s.cars)>20:
        bad_car = s.cars_[15]
        if t>25 and t< 30:
            bad_car.stop_ = True
        else:
            bad_car.stop_ = False

    if len(s.cars)>30:
        bad_car = s.cars_[29]
        if t>34 and t< 40:
            bad_car.stop_ = True
        else:
            bad_car.stop_ = False

    x = s.x_list
    y = np.zeros(len(x))

    #updates the position of each car in the graph.
    line1.set_data(x,y)

    #stores the history of each car in its correspondant plot.
    j=0

    for linita in lines:
        linita.set_xdata(np.append(linita.get_xdata(),x[j]))
        linita.set_ydata(np.append(linita.get_ydata(),t))
        j=j+1

    #calls the function that updates the position of the cars

    s.update_cars()
    return line1, lines

# call the animator.  blit=True means only re-draw the parts that have changed.

anim = animation.FuncAnimation(fig, animate, np.arange(0, max_steps),interval=20, blit=False, init_func=init)
plt.show()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>at.ac.tuwien.infosys.jcloudscale.messaging.objects Class Hierarchy (JCloudScale 0.4.1-SNAPSHOT API)</title>
<meta name="date" content="2014-02-05">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package at.ac.tuwien.infosys.jcloudscale.messaging.objects

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

at.ac.tuwien.infosys.jcloudscale.messaging.objects.MessageObject (implements java.io.Serializable)

at.ac.tuwien.infosys.jcloudscale.messaging.objects.IsAliveObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.IsDeadObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.LogObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.RedirectedOutputObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.RequestObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.CreateObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.DeleteObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.GetFieldValueObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.GetStaticValueObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.KeepaliveObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.SetFieldValueObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.SetStaticValueRequest

at.ac.tuwien.infosys.jcloudscale.messaging.objects.ShutdownObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.StartCallbackObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.StartInvokationObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.ReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.CreateReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.DeleteReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.GetFieldValueResponseObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.GetStaticValueReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.InvocationResultReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.SetFieldValueReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.StartCallbackResponseObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.StartInvokationReturnObject

at.ac.tuwien.infosys.jcloudscale.messaging.objects.StaticHostsObject

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014. All Rights Reserved.


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$this->title = 'Написать отчет';
?>

        <?php $form = ActiveForm::begin(); ?>

        <?php
            $count = 0;
            foreach ($reports as $index => $report) {
                echo $form->field($report, "[$index]manager_id")->hiddenInput(['value' => $projects[$count]->manager_id])->label(false);
                echo $form->field($report, "[$index]user_id")->hiddenInput(['value' => Yii::$app->user->getId()])->label(false);
                echo $form->field($projects[$count], 'title')->textInput(['disabled' => true])->label('Проект');
                echo $form->field($report, "[$index]project_title")->hiddenInput(['value' => $projects[$count]->title])->label(false);
                echo $form->field($report, "[$index]text")->textArea(['rows' => 6]);
                $count++;
                echo '

';
            }
        ?>

            <?= Html::submitButton('Отправить', ['class' =>'btn btn-success']) ?>

        <?php ActiveForm::end(); ?>


text:
<?php

namespace FSi\Component\Cache\Exception;

class ApcCacheException extends CacheException
{
}


text:
import { parse } from './ast';
import { emitString } from './emitter';
import {
  transform,
  TypeInjectorTransformer,
  FunctionBlockTransformer,
  AnonymousFunctionTransformer
} from './transformers';
import * as fs from 'fs';

declare function require(name: string): any;
declare var process: any;
const util = require('util');

export const typewrite = (file: string, outputFilePath: string): void => {
  const result = getTypeWrittenString(file);
  fs.writeFileSync(outputFilePath, result);
};

export const getTypeWrittenString = (file: string): string => {
  const { sourceFile, typeChecker } = parse([file]);
  const transformers = [
    new FunctionBlockTransformer(),
    new TypeInjectorTransformer(typeChecker),
    new AnonymousFunctionTransformer(typeChecker)
  ];
  const transformedSourceFile = transform(sourceFile, transformers);
  return emitString(transformedSourceFile, { include_headers: '' });
};


text:
========
term2048
========

.. image:: https://img.shields.io/travis/bfontaine/term2048.svg
   :target: https://travis-ci.org/bfontaine/term2048
   :alt: Build status

.. image:: https://img.shields.io/coveralls/bfontaine/term2048/master.svg
   :target: https://coveralls.io/r/bfontaine/term2048?branch=master
   :alt: Coverage status

.. image:: https://img.shields.io/pypi/v/term2048.svg
   :target: https://pypi.python.org/pypi/term2048
   :alt: Pypi package

**term2048** is a terminal-based version of 2048_.

.. _2048: http://gabrielecirulli.github.io/2048/

.. image:: https://github.com/bfontaine/term2048/raw/master/img/term2048.png

Install
-------

.. code-block::

    pip install term2048

To upgrade a previous installation, use:

.. code-block::

    pip install -U term2048

To install via `snap`_:

::

    sudo snap install term2048

.. _snap: https://www.snapcraft.io

Install from source
~~~~~~~~~~~~~~~~~~~

.. code-block::

    git clone https://github.com/bfontaine/term2048.git && cd term2048
    [sudo] python setup.py install

Play
----

.. code-block::

    term2048

Then use arrow keys to move. VI keys (h,j,k,l) are also supported.

Use ``-h`` to check the list of available options, and ``--rules`` for the
game rules. Press ``<space>`` at any time during the game to pause it. You can
resume it later using ``term2048 --resume``.

Tests
-----

Clone this repo, then: ::

    [sudo] make deps
    make check

Note: while ``term2048`` should work on Windows, tests are meant to run on
UNIX-like OSes and ``term2048.keypress``-related tests may fail on Windows.

Contributions
-------------

* ``--version`` flag added by @aminb
* ``--rules`` flag added by @cardern
* Short ``-r`` and ``-v`` flags added by @yankuangshi
* Resume feature added by @pravj
* Snap installation method added by @LaughingLove

v0.2.0
~~~~~~

* Python 2.6 and 3.x support by @shaunduncan
* Tests instructions fixed by @olafleur
* Spawn probabilities fixed by @frankh
* Colors improved by @idosch
* hjkl keys support by @aminb
* Windows support by @valtron
* AZ mode by @JosephRedfern
* The first file-related tests were added by @taeram


text:
require 'spec_helper'

module Homestead
  describe Office do
    subject { FactoryGirl.create :office }

    it 'has agents' do
      expect(subject.agents.count).to eq(2)
    end
    it 'has an agent named Chris' do
      expect(subject.agents.map(&:first_name)).to include('Chris')
    end

    it 'has three listings' do
      expect(subject.listings.count).to eq(3)
    end
  end
end


text:
import numpy
import logging
import sys
import scipy.sparse.linalg
from apgl.util.Sampling import Sampling
from apgl.util.ProfileUtils import ProfileUtils
from exp.util.SparseUtils import SparseUtils
from exp.util.LinOperatorUtils import LinOperatorUtils
from sppy import csarray
from sppy.linalg import GeneralLinearOperator

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

class GeneralLinearOperatorProfile(object):
    def __init__(self):
        numpy.random.seed(21)

        #Create a low rank matrix
        n = 500000
        m = 500000
        self.r = 200
        k = 10**6

        print("Generating low rank")
        self.X = SparseUtils.generateSparseLowRank((n, m), self.r, k)
        print("Generating csarray")
        self.X = csarray.fromScipySparse(self.X, storageType="rowMajor")
        print("Done")

    def profilePowerIteration(self):

        p = 200
        q = 5
        omega = numpy.random.randn(self.X.shape[1], p)
        L = GeneralLinearOperator.asLinearOperator(self.X)

        def run():
            Y = L.matmat(omega)

            for i in range(q):
                Y = L.rmatmat(Y)
                Y = L.matmat(Y)

        ProfileUtils.profile('run()', globals(), locals())

    def profilePowerIteration2(self):

        p = 100
        q = 5
        omega = numpy.random.randn(self.X.shape[1], p)
        L = GeneralLinearOperator.asLinearOperator(self.X, parallel=True)

        def run():
            Y = L.matmat(omega)

            for i in range(q):
                Y = L.rmatmat(Y)
                Y = L.matmat(Y)

        ProfileUtils.profile('run()', globals(), locals())

if __name__ == '__main__':
    profiler = GeneralLinearOperatorProfile()
    profiler.profilePowerIteration()
    profiler.profilePowerIteration2()


text:
/* tslint:disable */
/* eslint-disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ArtistConsignHeader_artist = {
    readonly name: string | null;
    readonly href: string | null;
    readonly " $fragmentRefs": FragmentRefs<"ArtistConsignHeaderImages_artist">;
    readonly " $refType": "ArtistConsignHeader_artist";
};
export type ArtistConsignHeader_artist$data = ArtistConsignHeader_artist;
export type ArtistConsignHeader_artist$key = {
    readonly " $data"?: ArtistConsignHeader_artist$data;
    readonly " $fragmentRefs": FragmentRefs<"ArtistConsignHeader_artist">;
};

const node: ReaderFragment = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "ArtistConsignHeader_artist",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "name",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "href",
      "storageKey": null
    },
    {
      "args": null,
      "kind": "FragmentSpread",
      "name": "ArtistConsignHeaderImages_artist"
    }
  ],
  "type": "Artist"
};
(node as any).hash = '7d3a03283b2d243183694c0120190387';
export default node;


text:
package org.neo4j.server.rrd;

public class UnableToSampleException extends RuntimeException
{

    private static final long serialVersionUID = 112443232112435425L;

    public UnableToSampleException( String message )
    {
        super( message );
    }

    public UnableToSampleException( String message, Exception cause )
    {
        super( message, cause );
    }
}


text:
import type { Screen } from '../../types'

export const ADD_BOOKMARK: 'Bookmarks/ADD_BOOKMARK' = 'Bookmarks/ADD_BOOKMARK'
export const REMOVE_BOOKMARK: 'Bookmarks/REMOVE_BOOKMARK' =
  'Bookmarks/REMOVE_BOOKMARK'

export const Actions = {
  ADD_BOOKMARK,
  REMOVE_BOOKMARK,
}

export type AddBookmark = {
  type: typeof ADD_BOOKMARK,
  key: string,
  screen: Screen,
}

export type RemoveBookmark = {
  type: typeof REMOVE_BOOKMARK,
  key: string,
}

export type Action = AddBookmark | RemoveBookmark


text:
package de.htwg.zeta.server.model.modelValidator.validator.rules.metaModelDependent

import scala.collection.mutable.ListBuffer

import de.htwg.zeta.common.models.project.concept.Concept
import de.htwg.zeta.common.models.project.concept.elements.AttributeValue
import de.htwg.zeta.common.models.project.concept.elements.AttributeValue.BoolValue
import de.htwg.zeta.common.models.project.concept.elements.AttributeValue.DoubleValue
import de.htwg.zeta.common.models.project.concept.elements.AttributeValue.EnumValue
import de.htwg.zeta.common.models.project.concept.elements.AttributeValue.IntValue
import de.htwg.zeta.common.models.project.concept.elements.AttributeValue.StringValue
import de.htwg.zeta.common.models.project.concept.elements.MClass
import de.htwg.zeta.common.models.project.instance.elements.NodeInstance
import de.htwg.zeta.server.model.modelValidator.Util
import de.htwg.zeta.server.model.modelValidator.validator.ModelValidationResult
import de.htwg.zeta.server.model.modelValidator.validator.rules.DslRule
import de.htwg.zeta.server.model.modelValidator.validator.rules.GeneratorRule
import de.htwg.zeta.server.model.modelValidator.validator.rules.NodesRule

/**
 * This file was created by Tobias Droth as part of his master thesis at HTWG Konstanz (03/2017 - 09/2017).
 */
class NodeAttributesGlobalUnique(val nodeTypes: Seq[String], val attributeType: String) extends NodesRule with DslRule {
  override val name: String = getClass.getSimpleName
  override val description: String =
    s"Every value of attribute $attributeType in nodes of types ${Util.stringSeqToSeqString(nodeTypes)} must be globally unique."
  override val possibleFix: String =
    s"Remove duplicated values of attribute $attributeType in nodes of type ${Util.stringSeqToSeqString(nodeTypes)}."

  def handleStrings(values: Seq[AttributeValue]): Seq[String] = values.collect { case v: StringValue => v }.map(_.value)
  def handleBooleans(values: Seq[AttributeValue]): Seq[String] = values.collect { case v: BoolValue => v }.map(_.value.toString)
  def handleInts(values: Seq[AttributeValue]): Seq[String] = values.collect { case v: IntValue => v }.map(_.value.toString)
  def handleDoubles(values: Seq[AttributeValue]): Seq[String] = values.collect { case v: DoubleValue => v }.map(_.value.toString)
  def handleEnums(values: Seq[AttributeValue]): Seq[String] = values.collect { case v: EnumValue => v }.map(_.toString)

  override def check(elements: Seq[NodeInstance]): Seq[ModelValidationResult] = {

    val nodes = elements.filter(node => nodeTypes.contains(node.className))

    val attributes: Seq[(String, List[AttributeValue])] = nodes.flatMap(_.attributeValues).filter(_._1 == attributeType)
    val attributeValues: Seq[AttributeValue] = attributes.flatMap(_._2)

    // convert all attribute values to string for comparison.
    val attributeValuesStrings: Seq[String] = attributeValues.headOption match {
      case None => Seq()
      case Some(_: StringValue) => handleStrings(attributeValues)
      case Some(_: BoolValue) => handleBooleans(attributeValues)
      case Some(_: IntValue) => handleInts(attributeValues)
      case Some(_: DoubleValue) => handleDoubles(attributeValues)
      case Some(_: EnumValue) => handleEnums(attributeValues)
    }

    // find duplicate values
    val attributesGrouped: Map[String, Seq[String]] = attributeValuesStrings.groupBy(identity)
    val duplicateAttributeValues: Seq[String] = attributesGrouped.filter(_._2.size > 1).keys.toSeq

    def checkNodeDuplicateValues(acc: Seq[ModelValidationResult], currentNode: NodeInstance): Seq[ModelValidationResult] = {
      val attributeValues = currentNode.attributeValues.values.toSeq.flatten

      val attributeValuesStrings: Seq[String] = attributeValues.headOption match {
        case None => Seq()
        case Some(_: StringValue) => handleStrings(attributeValues)
        case Some(_: BoolValue) => handleBooleans(attributeValues)
        case Some(_: IntValue) => handleInts(attributeValues)
        case Some(_: DoubleValue) => handleDoubles(attributeValues)
        case Some(_: EnumValue) => handleEnums(attributeValues)
      }

      val valid = attributeValuesStrings.foldLeft(true) { (acc, currentString) =>
        if (duplicateAttributeValues.contains(currentString)) false else acc
      }

      acc :+ ModelValidationResult(rule = this, valid = valid, modelElement = Some(Left(currentNode)))
    }

    // check which nodes contains one or more of the duplicated values.
    nodes.foldLeft(Seq[ModelValidationResult]())(checkNodeDuplicateValues)

  }

  override val dslStatement: String = s"""Attributes ofType "$attributeType" inNodes ${Util.stringSeqToSeqString(nodeTypes)} areGlobalUnique ()"""
}

object NodeAttributesGlobalUnique extends GeneratorRule {

  override def generateFor(metaModel: Concept): Seq[DslRule] = {

    val graph = metaModel.classes

    val inheritanceRelationships = graph.map(el => (el, getInheritanceRelationship(el, graph)))

    val inheritanceWithAttribute = for {
      inheritanceRelationship <- inheritanceRelationships
      attribute <- inheritanceRelationship._1.attributes if attribute.globalUnique
    } yield (inheritanceRelationship._1, inheritanceRelationship._2, attribute)

    val globalUniqueAttributes = inheritanceWithAttribute.groupBy(rec => (rec._2, rec._3)).keySet

    val ruleData = ListBuffer[(Seq[String], String)]()

    for {globalUniqueAttribute <- globalUniqueAttributes} {
      val elSet = globalUniqueAttribute._1.filter { el =>
        el.attributes.exists(att => att.name == globalUniqueAttribute._2.name && att.globalUnique)
      }
      ruleData += ((elSet.map(_.name), globalUniqueAttribute._2.name))
    }

    ruleData.distinct.map(rule => new NodeAttributesGlobalUnique(rule._1, rule._2))

  }

  def getInheritanceRelationship(el: MClass, graph: Seq[MClass]): Seq[MClass] = {

    def getSuperClasses: Seq[MClass] = {

      def getSuperClassesRec(current: MClass, acc: Set[MClass]): Set[MClass] = {
        if (current.superTypeNames.isEmpty) {
          acc
        } else {
          val superTypes = current.superTypeNames.flatMap(elName => graph.find(_.name == elName))
          superTypes.flatMap(getSuperClassesRec(_, acc ++ superTypes)).toSet
        }
      }

      getSuperClassesRec(el, Set()).toSeq

    }

    def getSubClasses: Seq[MClass] = {

      def getSubClassesRec(current: MClass, acc: Set[MClass]): Set[MClass] = {
        val sub = graph.filter(_.superTypeNames.contains(current.name))
        if (sub.isEmpty) {
          acc
        } else {
          val subTypes = sub.flatMap(elName => graph.find(_.name == elName))
          subTypes.flatMap(getSubClassesRec(_, acc ++ subTypes)).toSet
        }
      }

      getSubClassesRec(el, Set()).toSeq
    }

    (getSuperClasses :+ el) ++ getSubClasses

  }

}