text:
const React = require('react-native');

const { StyleSheet } = React;

module.exports = StyleSheet.create({
  container: {
    flex: 1,
    width: null,
    height: null,
    backgroundColor: '#FBFAFA',
  },
  iconContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    paddingLeft: 15,
  },
  icon: {
    width: 45,
    height: 45,
    justifyContent: 'center',
  },
});


text:
package com.martin.ads.vrlib.filters.advanced;

import android.content.Context;
import android.opengl.GLES20;

import com.martin.ads.vrlib.filters.base.AbsFilter;
import com.martin.ads.vrlib.object.Plane;
import com.martin.ads.vrlib.programs.GLTwoInputProgram;
import com.martin.ads.vrlib.textures.BitmapTexture;
import com.martin.ads.vrlib.utils.BufferUtils;
import com.martin.ads.vrlib.utils.PlaneTextureRotationUtils;
import com.martin.ads.vrlib.utils.TextureUtils;

import java.nio.FloatBuffer;

/**
 * Created by Ads on 2016/11/20.
 *
 * Using frameBuffer will rotate the image 180 degree around the Y-axis
 * so I rotate the texture before render
 * If you don't have enough filter, use Simpler filter to take position
 * Again,the order of filters matters ! ! !
 */

abstract class MixBlendFilter extends AbsFilter {
    private Plane plane;
    private GLTwoInputProgram twoInputProgram;
    private FloatBuffer mTexCoordinateBuffer2;
    private BitmapTexture bitmapTexture;
    private int textureHandle2;
    private Context context;

    //assumed
    private int mMixLocation;
    private float mMixturePercent;

    public MixBlendFilter(Context context,
                          final String fragmentShaderPath,
                          float mMixturePercent) {
        this.context=context;
        plane =new Plane(true);
        twoInputProgram=new GLTwoInputProgram(context, "filter/vsh/two_input.glsl",fragmentShaderPath);
        mTexCoordinateBuffer2= BufferUtils.getFloatBuffer(PlaneTextureRotationUtils.TEXTURE_NO_ROTATION,0);
        this.mMixturePercent=mMixturePercent;
        bitmapTexture=new BitmapTexture();
    }

    @Override
    public void init() {
        twoInputProgram.create();

        //assumed
        textureHandle2=GLES20.glGetUniformLocation(twoInputProgram.getProgramId()
                , "sTexture2");

        mMixLocation = GLES20.glGetUniformLocation(twoInputProgram.getProgramId(), "mixturePercent");

        bitmapTexture.loadWithAssetFile(context,"filter/imgs/texture_360_n.jpg");
    }

    @Override
    public void onPreDrawElements() {
        mTexCoordinateBuffer2.position(0);
        GLES20.glVertexAttribPointer(twoInputProgram.getMaTexture2Handle(), 2, GLES20.GL_FLOAT, false, 0, mTexCoordinateBuffer2);
        GLES20.glEnableVertexAttribArray(twoInputProgram.getMaTexture2Handle());

        plane.uploadTexCoordinateBuffer(twoInputProgram.getTextureCoordinateHandle());
        plane.uploadVerticesBuffer(twoInputProgram.getPositionHandle());

        GLES20.glUniform1f(mMixLocation,mMixturePercent);
    }

    @Override
    public void destroy() {
        twoInputProgram.onDestroy();
        bitmapTexture.destroy();
    }

    @Override
    public void onDrawFrame(int textureId) {
        twoInputProgram.use();
        onPreDrawElements();

        TextureUtils.bindTexture2D(textureId, GLES20.GL_TEXTURE0,twoInputProgram.getuTextureSamplerHandle(),0);
        TextureUtils.bindTexture2D(bitmapTexture.getImageTextureId(),GLES20.GL_TEXTURE1,textureHandle2,1);

        GLES20.glViewport(0,0,surfaceWidth,surfaceHeight);
        plane.draw();
    }

    public void setMixturePercent(float mMixturePercent) {
        this.mMixturePercent = mMixturePercent;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.perfcake.pc4idea.api.editor.modelwrapper.component;

/**
 * Created by Stanislav Kaleta on 3/11/15. TODO documentation
 */
public interface Togglable extends ComponentModelWrapper {

    /**
     *
     * @param toggle
     */
    public void setToggle(boolean toggle);
}


text:
namespace csv_opts
  {
  typedef unsigned int flag_type;

  struct opts
    {
    const flag_type flags;

    inline explicit opts(const flag_type in_flags);

    inline const opts operator+(const opts& rhs) const;
    };

  inline
  opts::opts(const flag_type in_flags)
    : flags(in_flags)
    {}

  inline
  const opts
  opts::operator+(const opts& rhs) const
    {
    const opts result( flags | rhs.flags );

    return result;
    }

  // The values below (eg. 1u << 0) are for internal Armadillo use only.
  // The values can change without notice.

  static const flag_type flag_none        = flag_type(0      );
  static const flag_type flag_trans       = flag_type(1u << 0);
  static const flag_type flag_no_header   = flag_type(1u << 1);
  static const flag_type flag_with_header = flag_type(1u << 2);
  static const flag_type flag_semicolon   = flag_type(1u << 3);

  struct opts_none        : public opts { inline opts_none()        : opts(flag_none       ) {} };
  struct opts_trans       : public opts { inline opts_trans()       : opts(flag_trans      ) {} };
  struct opts_no_header   : public opts { inline opts_no_header()   : opts(flag_no_header  ) {} };
  struct opts_with_header : public opts { inline opts_with_header() : opts(flag_with_header) {} };
  struct opts_semicolon   : public opts { inline opts_semicolon()   : opts(flag_semicolon  ) {} };

  static const opts_none        none;
  static const opts_trans       trans;
  static const opts_no_header   no_header;
  static const opts_with_header with_header;
  static const opts_semicolon   semicolon;
  }

struct csv_name
  {
  typedef field<std::string> header_type;

  const std::string    filename;
  const csv_opts::opts opts;

        header_type  header_junk;
  const header_type& header_ro;
        header_type& header_rw;

  inline
  csv_name(const std::string& in_filename, const csv_opts::opts& in_opts = csv_opts::no_header)
    : filename (in_filename)
    , opts     (in_opts    )
    , header_ro(header_junk)
    , header_rw(header_junk)
    {}

  inline
  csv_name(const std::string& in_filename,       field<std::string>& in_header)
    : filename (in_filename          )
    , opts     (csv_opts::with_header)
    , header_ro(in_header            )
    , header_rw(in_header            )
    {}

  inline
  csv_name(const std::string& in_filename, const field<std::string>& in_header)
    : filename  (in_filename          )
    , opts      (csv_opts::with_header)
    , header_ro(in_header             )
    , header_rw(header_junk           )
    {}

  inline
  csv_name(const std::string& in_filename,       field<std::string>& in_header, const csv_opts::opts& in_opts)
    : filename  (in_filename                    )
    , opts      (csv_opts::with_header + in_opts)
    , header_ro(in_header                       )
    , header_rw(in_header                       )
    {}

  inline
  csv_name(const std::string& in_filename, const field<std::string>& in_header, const csv_opts::opts& in_opts)
    : filename  (in_filename                    )
    , opts      (csv_opts::with_header + in_opts)
    , header_ro(in_header                       )
    , header_rw(header_junk                     )
    {}
  };

//! @}


text:
Logiciel pour apprendre à lire aux enfants

## Compilation
Ce logiciel est écrit pour être utilisé sur un Mac. Installez Xcode, ouvrez le projet et cliquez sur "Build".

## TODO
* Compter et reconnaitre les chiffres
* Alphabet
* Syllables complexes
* Reconnaitre les mots par thèmes


text:
require 'test_helper'
require 'generators/attr_object/attr_object_generator'

class AttrObjectGeneratorTest < Rails::Generators::TestCase
  tests AttrObjectGenerator
  destination Rails.root.join('tmp/generators')
  setup :prepare_destination

  test "generator runs without errors" do
    assert_nothing_raised do
      run_generator %w[phone]
    end

    assert_file "app/attr_objects/phone_attr.rb", /class PhoneAttr/
  end

  test "generator with class" do
    assert_nothing_raised do
      run_generator %w[position fixnum]
    end

    assert_file "app/attr_objects/position_attr.rb", /class PositionAttr < DelegateClass\(Fixnum\)/
  end

  test "generator with invalid class" do
    assert_nothing_raised do
      run_generator %w[phone invalid_ruby_class]
    end

    assert_file "app/attr_objects/phone_attr.rb", /class PhoneAttr < DelegateClass\(InvalidRubyClass\)/
  end
end


text:
<?php
namespace Frozennode\Administrator\Fields;

use Frozennode\Administrator\Validator;
use Frozennode\Administrator\Config\ConfigInterface;
use Illuminate\Database\DatabaseManager as DB;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;

class Factory {

	/**
	 * The valid field types and their associated classes
	 *
	 * @var array
	 */
	protected $fieldTypes = array(
		'key' => 'Frozennode\\Administrator\\Fields\\Key',
		'text' => 'Frozennode\\Administrator\\Fields\\Text',
		'textarea' => 'Frozennode\\Administrator\\Fields\\Text',
		'wysiwyg' => 'Frozennode\\Administrator\\Fields\\Text',
		'markdown' => 'Frozennode\\Administrator\\Fields\\Text',
		'password' => 'Frozennode\\Administrator\\Fields\\Password',
		'date' => 'Frozennode\\Administrator\\Fields\\Time',
		'time' => 'Frozennode\\Administrator\\Fields\\Time',
		'datetime' => 'Frozennode\\Administrator\\Fields\\Time',
		'number' => 'Frozennode\\Administrator\\Fields\\Number',
		'bool' => 'Frozennode\\Administrator\\Fields\\Boolean',
		'enum' => 'Frozennode\\Administrator\\Fields\\Enum',
		'image' => 'Frozennode\\Administrator\\Fields\\Image',
		'file' => 'Frozennode\\Administrator\\Fields\\File',
		'color' => 'Frozennode\\Administrator\\Fields\\Color',

		//relationships
		'belongs_to' => 'Frozennode\\Administrator\\Fields\\Relationships\\BelongsTo',
		'belongs_to_many' => 'Frozennode\\Administrator\\Fields\\Relationships\\BelongsToMany',
		'has_one' => 'Frozennode\\Administrator\\Fields\\Relationships\\HasOne',
		'has_many' => 'Frozennode\\Administrator\\Fields\\Relationships\\HasMany',

	);

	/**
	 * The base string for the relationship classes
	 */
	protected $relationshipBase = 'Illuminate\\Database\\Eloquent\\Relations\\';

	/**
	 * The base string for the relationship classes
	 */
	protected $settingsFieldExclusions = array('key', 'belongs_to', 'belongs_to_many', 'has_one', 'has_many');

	/**
	 * The validator instance
	 *
	 * @var \Frozennode\Administrator\Validator
	 */
	protected $validator;

	/**
	 * The config interface instance
	 *
	 * @var \Frozennode\Administrator\Config\ConfigInterface
	 */
	protected $config;

	/**
	 * The config instance
	 *
	 * @var \Illuminate\Database\DatabaseManager
	 */
	protected $db;

	/**
	 * The compiled filters objects
	 *
	 * @var array
	 */
	protected $filters = array();

	/**
	 * The compiled filters arrays
	 *
	 * @var array
	 */
	protected $filtersArrays = array();

	/**
	 * The compiled edit fields array
	 *
	 * @var array
	 */
	protected $editFields;

	/**
	 * The edit field objects as arrays
	 *
	 * @var array
	 */
	protected $editFieldsArrays;

	/**
	 * The edit field data model
	 *
	 * @var array
	 */
	protected $dataModel;

	/**
	 * Create a new model Config instance
	 *
	 * @param \Frozennode\Administrator\Validator 				$validator
	 * @param \Frozennode\Administrator\Config\ConfigInterface	$config
	 * @param \Illuminate\Database\DatabaseManager 				$db
	 */
	public function __construct(Validator $validator, ConfigInterface $config, DB $db)
	{
		$this->validator = $validator;
		$this->config = $config;
		$this->db = $db;
	}

	/**
	 * Makes a field given an array of options
	 *
	 * @param mixed 	$name
	 * @param mixed 	$options
	 * @param boolean	$loadRelationships	//determines whether or not to load the relationships
	 *
	 * @return mixed
	 */
	public function make($name, $options, $loadRelationships = true)
	{
		//make sure the options array has all the proper default values
		$options = $this->prepareOptions($name, $options, $loadRelationships);

		return $this->getFieldObject($options);
	}

	/**
	 * Instantiates a field object
	 *
	 * @param array 	$options
	 * @param boolean 	$loadRelationships
	 *
	 * @return Frozennode\Administrator\Fields\Field
	 */
	public function getFieldObject($options)
	{
		$class = $this->getFieldTypeClass($options['type']);
		return new $class($this->validator, $this->config, $this->db, $options);
	}

	/**
	 * Gets the class name for a field type
	 *
	 * @param string 	$type
	 *
	 * @return string
	 */
	public function getFieldTypeClass($type)
	{
		return $this->fieldTypes[$type];
	}

	/**
	 * Sets up an options array with the required base values
	 *
	 * @param mixed 	$name
	 * @param mixed 	$options
	 * @param boolean	$loadRelationships	//determines whether or not to load the relationships
	 *
	 * @return array
	 */
	public function prepareOptions($name, $options, $loadRelationships = true)
	{
		//set the options array to the format we need
		$options = $this->validateOptions($name, $options);

		//make sure the 'title' option is set
		$options['title'] = isset($options['title']) ? $options['title'] : $options['field_name'];

		//ensure the type is set and then check that the field type exists
		$this->ensureTypeIsSet($options);

		//set the proper relationship options
		$this->setRelationshipType($options, $loadRelationships);

		//check that the type is a valid field class
		$this->checkTypeExists($options);

		return $options;
	}

	/**
	 * Validates an options array item. This could be a string $name and array $options, or a positive integer $name and string $options.
	 *
	 * @param mixed		$name
	 * @param mixed		$options
	 *
	 * @return array
	 */
	public function validateOptions($name, $options)
	{
		if (is_string($options))
		{
			$name = $options;
			$options = array();
		}

		//if the name is not a string or the options is not an array at this point, throw an error because we can't do anything with it
		if (!is_string($name) || !is_array($options))
		{
			throw new \InvalidArgumentException("One of the fields in your " . $this->config->getOption('name') . " configuration file is invalid");
		}

		//in any case, make sure the 'column_name' option is set
		$options['field_name'] = $name;

		return $options;
	}

	/**
	 * Ensures that the type option is set.
	 *
	 * @param array		$options
	 *
	 * @return void
	 */
	public function ensureTypeIsSet(array &$options)
	{
		//if the 'type' option hasn't been set
		if (!isset($options['type']))
		{
			//if this is a model and the field is equal to the primary key name, set it as a key field
			if ($this->config->getType() === 'model' && $options['field_name'] === $this->config->getDataModel()->getKeyName())
			{
				$options['type'] = 'key';
			}
			//otherwise set it to the default 'text'
			else
			{
				$options['type'] = 'text';
			}
		}
	}

	/**
	 * Ensures that a relationship field is valid
	 *
	 * @param array		$options
	 * @param bool		$loadRelationships
	 *
	 * @return void
	 */
	public function setRelationshipType(array &$options, $loadRelationships)
	{
		//if this is a relationship
		if ($this->validator->arrayGet($options, 'type') === 'relationship')
		{
			//get the right key based on the relationship in the model
			$options['type'] = $this->getRelationshipKey($options['field_name']);

			//if we should load the relationships, set the option
			$options['load_relationships'] = $loadRelationships && !$this->validator->arrayGet($options, 'autocomplete', false);
		}
	}

	/**
	 * Check to see if the type is valid
	 *
	 * @param array 	$options
	 *
	 * @return void
	 */
	public function checkTypeExists(array &$options)
	{
		//if an improper value was supplied
		if (!array_key_exists($options['type'], $this->fieldTypes))
		{
			throw new \InvalidArgumentException('The ' . $options['type'] . ' field type in your ' . $this->config->getOption('name') . ' configuration file is not valid');
		}

		//if this is a settings page and a field was supplied that is excluded
		if ($this->config->getType() === 'settings' && in_array($options['type'], $this->settingsFieldExclusions))
		{
			throw new \InvalidArgumentException('The ' . $options['type'] . ' field in your ' .
							$this->config->getOption('name') . ' settings page cannot be used on a settings page');
		}
	}

	/**
	 * Given a field name, returns the type key or false
	 *
	 * @param string 	$field  	the field type to check
	 *
	 * @return string|false
	 */
	public function getRelationshipKey($field)
	{
		$model = $this->config->getDataModel();
		$invalidArgument = new \InvalidArgumentException("The '" . $field . "' relationship field you supplied for " .
								$this->config->getOption('name') . " is not a valid relationship method name on the supplied Eloquent model");

		//check if the related method exists on the model
		if (!method_exists($model, $field))
		{
			throw $invalidArgument;
		}

		//now that we know the method exists, we can determine if it's multiple or single
		$related_model = $model->{$field}();

		//check if this is a valid relationship object, and return the appropriate key
		if (is_a($related_model, $this->relationshipBase.'BelongsTo'))
		{
			return 'belongs_to';
		}
		else if (is_a($related_model, $this->relationshipBase.'BelongsToMany'))
		{
			return 'belongs_to_many';
		}
		else if (is_a($related_model, $this->relationshipBase.'HasOne'))
		{
			return 'has_one';
		}
		else if (is_a($related_model, $this->relationshipBase.'HasMany'))
		{
			return 'has_many';
		}
		else
		{
			throw $invalidArgument;
		}
	}

	/**
	 * Given a field name, this returns the field object from the edit fields array
	 *
	 * @param string	 	$field
	 *
	 * @return \Frozennode\Administrator\Fields\Field
	 */
	public function findField($field)
	{
		$fields = $this->getEditFields();

		//return either the Field object or throw an InvalidArgumentException
		if (!isset($fields[$field]))
		{
			throw new \InvalidArgumentException("The " . $field . " field does not exist on the " . $this->config->getOption('name') . " model");
		}

		return $fields[$field];
	}

	/**
	 * Given a field name, this returns the field object from the filters array
	 *
	 * @param string	 	$field
	 *
	 * @return \Frozennode\Administrator\Fields\Field
	 */
	public function findFilter($field)
	{
		$filters = $this->getFilters();

		//return either the Field object or throw an InvalidArgumentException
		if (!isset($filters[$field]))
		{
			throw new \InvalidArgumentException("The " . $field . " filter does not exist on the " . $this->config->getOption('name') . " model");
		}

		return $filters[$field];
	}

	/**
	 * Creates the edit fields as Field objects
	 *
	 * @param boolean 	$loadRelationships //if set to false, no relationship options will be loaded
	 * @param boolean 	$override //if set to true, the fields will be re-loaded, otherwise it will use the cached fields
	 *
	 * @return array
	 */
	public function getEditFields($loadRelationships = true, $override = false)
	{
		if (!sizeof($this->editFields) || $override)
		{
			$this->editFields = array();

			//iterate over each supplied edit field
			foreach ($this->config->getOption('edit_fields') as $name => $options)
			{
				$fieldObject = $this->make($name, $options, $loadRelationships);
				$this->editFields[$fieldObject->getOption('field_name')] = $fieldObject;
			}
		}

		return $this->editFields;
	}

	/**
	 * Gets the array version of the edit fields objects
	 *
	 * @param boolean 	$override 	//this will override the cached version if set to true
	 *
	 * @return array
	 */
	public function getEditFieldsArrays($override = false)
	{
		$return = array();

		foreach ($this->getEditFields(true, $override) as $fieldObject)
		{
			$return[$fieldObject->getOption('field_name')] = $fieldObject->getOptions();
		}

		//get the key field if this is a model page
		if ($this->config->getType() === 'model')
		{
			$this->fillKeyField($return);
		}

		return $return;
	}

	/**
	 * Gets the key field for a model for the getEditFieldsArrays
	 *
	 * @param array		$fields
	 *
	 * @return array
	 */
	public function fillKeyField(array &$fields)
	{
		$model = $this->config->getDataModel();
		$keyName = $model->getKeyName();

		//add the primary key field, which will be uneditable, but part of the data model
		if ($this->config->getType() === 'model' && !isset($fields[$keyName]))
		{

			$keyField = $this->make($keyName, array('visible' => false));
			$fields[$keyName] = $keyField->getOptions();
		}
	}

	/**
	 * Gets the data model given the edit fields
	 *
	 * @return array
	 */
	public function getDataModel()
	{
		$dataModel = array();
		$model = $this->config->getDataModel();

		foreach ($this->getEditFieldsArrays() as $name => $options)
		{
			//if this is a key, set it to 0
			if ($options['type'] === 'key')
			{
				$dataModel[$name] = 0;
			}
			else
			{
				//if this is a collection, convert it to an array
				if (is_a($model->$name, 'Illuminate\Database\Eloquent\Collection'))
				{
					$dataModel[$name] = $model->$name->toArray();
				}
				else
				{
					$dataModel[$name] = isset($options['value']) ? $options['value'] : null;
				}
			}
		}

		return $dataModel;
	}

	/**
	 * Gets the filters for the given model config
	 *
	 * @return array
	 */
	public function getFilters()
	{
		//get the model's filter fields
		$configFilters = $this->config->getOption('filters');

		//make sure that the filters array hasn't been created before and that there are supplied filters in the config
		if (!sizeof($this->filters) && $configFilters)
		{
			//iterate over the filters and create field objects for them
			foreach ($configFilters as $name => $filter)
			{
				if ($fieldObject = $this->make($name, $filter))
				{
					//the filters array is indexed on the field name and holds the arrayed values for the filters
					$this->filters[$fieldObject->getOption('field_name')] = $fieldObject;
				}
			}
		}

		return $this->filters;
	}

	/**
	 * Gets the filters array and converts the objects to arrays
	 *
	 * @return array
	 */
	public function getFiltersArrays()
	{
		if (!sizeof($this->filtersArrays))
		{
			foreach ($this->getFilters() as $name => $filter)
			{
				$this->filtersArrays[$name] = $filter->getOptions();
			}
		}

		return $this->filtersArrays;
	}

	/**
	 * Finds a field's options given a field name and a type (filter/edit)
	 *
	 * @param  string 		$field
	 * @param  string 		$type
	 *
	 * @return mixed
	 */
	public function getFieldObjectByName($field, $type)
	{
		$info = false;

		//we want to get the correct options depending on the type of field it is
		if ($type === 'filter')
		{
			$fields = $this->getFilters();
		}
		else
		{
			$fields = $this->getEditFields();
		}

		//iterate over the fields to get the one for this $field value
		foreach ($fields as $key => $val)
		{
			if ($key === $field)
			{
				$info = $val;
			}
		}

		return $info;
	}

	/**
	 * Given a model, field, type (filter or edit), and constraints (either int or array), returns an array of options
	 *
	 * @param string	$field
	 * @param string	$type			//either 'filter' or 'edit'
	 * @param array		$constraints	//an array of ids of the other model's items
	 * @param array		$selectedItems	//an array of ids that are currently selected
	 * @param string	$term			//the search term
	 *
	 * @return array
	 */
	public function updateRelationshipOptions($field, $type, $constraints, $selectedItems, $term = null)
	{
		//first get the related model and fetch the field's options
		$model = $this->config->getDataModel();
		$relatedModel = $model->{$field}()->getRelated();
		$relatedTable = $relatedModel->getTable();
		$relatedKeyName = $relatedModel->getKeyName();
		$relatedKeyTable = $relatedTable . '.' . $relatedKeyName;
		$fieldObject = $this->getFieldObjectByName($field, $type);

		//if we can't find the field, return an empty array
		if (!$fieldObject)
		{
			return array();
		}

		//make sure we're grouping by the model's id
		$query = $relatedModel->newQuery();

		//set up the selects
		$query->select(array($this->db->raw($this->db->getTablePrefix() . $relatedTable.'.*')));

		//format the selected items into an array
		$selectedItems = $this->formatSelectedItems($selectedItems);

		//if this is an autocomplete field, check if there is a search term. If not, just return the selected items
		if ($fieldObject->getOption('autocomplete') && !$term)
		{
			if (sizeof($selectedItems))
			{
				$this->filterQueryBySelectedItems($query, $selectedItems, $fieldObject, $relatedKeyTable);

				return $this->formatSelectOptions($fieldObject, $query->get());
			}
			else
			{
				return array();
			}
		}

		//applies constraints if there are any
		$this->applyConstraints($constraints, $query, $fieldObject);

		//if there is a search term, limit the result set by that term
		$this->filterBySearchTerm($term, $query, $fieldObject, $selectedItems, $relatedKeyTable);

		//perform any user-supplied options filter
		$filter = $fieldObject->getOption('options_filter');
		$filter($query);

		//finally we can return the options
		return $this->formatSelectOptions($fieldObject, $query->get());
	}

	/**
	 * Filters a relationship options query by a search term
	 *
	 * @param mixed										$term
	 * @param \Illuminate\Database\Query\Builder		$query
	 * @param \Frozennode\Administrator\Fields\Field	$fieldObject
	 * @param array										$selectedItems
	 * @param string									$relatedKeyTable
	 */
	public function filterBySearchTerm($term, EloquentBuilder &$query, Field $fieldObject, array $selectedItems, $relatedKeyTable)
	{
		if ($term)
		{
			$query->where(function($query) use ($term, $fieldObject)
			{
				foreach ($fieldObject->getOption('search_fields') as $search)
				{
					$query->orWhere($this->db->raw($search), 'LIKE', '%'.$term.'%');
				}
			});

			//exclude the currently-selected items if there are any
			if (count($selectedItems))
			{
				$query->whereNotIn($relatedKeyTable, $selectedItems);
			}

			//set up the limits
			$query->take($fieldObject->getOption('num_options') + count($selectedItems));
		}
	}

	/**
	 * Takes the supplied $selectedItems mixed value and formats it to a usable array
	 *
	 * @param mixed		$selectedItems
	 *
	 * @return array
	 */
	public function formatSelectedItems($selectedItems)
	{
		if ($selectedItems)
		{
			//if this isn't an array, set it up as one
			return is_array($selectedItems) ? $selectedItems : explode(',', $selectedItems);
		}
		else
		{
			return array();
		}
	}

	/**
	 * Takes the supplied $selectedItems mixed value and formats it to a usable array
	 *
	 * @param \Illuminate\Database\Query\Builder		$query
	 * @param array										$selectedItems
	 * @param \Frozennode\Administrator\Fields\Field	$fieldObject
	 * @param string									$relatedKeyTable
	 *
	 * @return array
	 */
	public function filterQueryBySelectedItems(EloquentBuilder &$query, array $selectedItems, Field $fieldObject, $relatedKeyTable)
	{
		$query->whereIn($relatedKeyTable, $selectedItems);

		//if this is a BelongsToMany and a sort field is set, order it by the sort field
		if ($fieldObject->getOption('multiple_values') && $fieldObject->getOption('sort_field'))
		{
			$query->orderBy($fieldObject->getOption('sort_field'));
		}
		//otherwise order it by the name field
		else
		{
			$query->orderBy($fieldObject->getOption('name_field'));
		}
	}

	/**
	 * Takes the supplied $selectedItems mixed value and formats it to a usable array
	 *
	 * @param mixed										$constraints
	 * @param \Illuminate\Database\Query\Builder		$query
	 * @param \Frozennode\Administrator\Fields\Field	$fieldObject
	 *
	 * @return array
	 */
	public function applyConstraints($constraints, EloquentBuilder &$query, Field $fieldObject)
	{
		$configConstraints = $fieldObject->getOption('constraints');

		if (sizeof($configConstraints))
		{
			//iterate over the config constraints
			foreach ($configConstraints as $key => $relationshipName)
			{
				//now that we're looping through the constraints, check to see if this one was supplied
				if (isset($constraints[$key]) && $constraints[$key] && sizeof($constraints[$key]))
				{
					//first we get the other model and the relationship field on it
					$model = $this->config->getDataModel();
					$relatedModel = $model->{$fieldObject->getOption('field_name')}()->getRelated();
					$otherModel = $model->{$key}()->getRelated();

					//set the data model for the config
					$this->config->setDataModel($otherModel);
					$otherField = $this->make($relationshipName, array('type' => 'relationship'), false);

					//constrain the query
					$otherField->constrainQuery($query, $relatedModel, $constraints[$key]);

					//set the data model back to the original
					$this->config->setDataModel($model);
				}
			}
		}
	}

	/**
	 * Takes an eloquent result array and turns it into an options array that can be used in the UI
	 *
	 * @param \Frozennode\Administrator\Fields\Field	$field
	 * @param \Illuminate\Database\Eloquent\Collection	$results
	 *
	 * @return array
	 */
	public function formatSelectOptions(Field $field, EloquentCollection $results)
	{
		$return = array();

		foreach ($results as $m)
		{
			$return[] = array(
				'id' => $m->getKey(),
				'text' => strval($m->{$field->getOption('name_field')}),
			);
		}

		return $return;
	}
}


text:
let form = $("#event-form")

// Allow closing the form by clicking outside of the modal
hideEventForm = function() {
    $("#event-form")[0].reset()
    $("#event-input").addClass("invisible")

    window.currentMarker.setMap(null)
    window.currentMarker = null

    $(document).off('keydown')
}

// Show event form and initialize hidden fields
showEventForm = function(lat, lng) {
    $("#event-input").removeClass("invisible")
    $("#event-form #id_latitude").val(lat.toFixed(8))
    $("#event-form #id_longitude").val(lng.toFixed(8))
    $(document).keydown(function(e) {
        if (e.keyCode == 27) { // Esc key
            hideEventForm()
        }
    })
}

$("#event-input").click(hideEventForm)

// Prevent form from closing on click
form.click(function(e) {
    e.stopPropagation()
})

form.find(".btn-cancel").click(hideEventForm)

// Add style to event-form fields
form.find("input").addClass("form-control")
form.find("textarea").addClass("form-control")

// Give styling to the tags input
chosenSettings = { width: "100%", no_results_text: "No tags with name", search_contains: true }

tagField = form.find('#id_tag')
tagField.find("option[value='']").text("None")
tagField.chosen(chosenSettings)

// Give styling to container
let chosen = tagField.parent().find(".chosen-container")

function styleChosen() {
    // Style the chosen input
    chosen.find(".chosen-search-input").attr("style", "width: 100%;")

    // Check for changes on the results
    chosen.find(".chosen-results").on("DOMSubtreeModified", function() {

        let drop = $(this).parents(".chosen-drop")
        let noResults = drop.find(".no-results")

        // If no tag was found with the searched name, ask for tag creation
        if (noResults.length) {

            // If tag creation row is not present create it
            if (!drop.find(".create-tag").length) {

                let tagName = $(".chosen-search-input").val()
                let span = noResults.find("span")
                let createTag = $(`<span class="create-tag">Create new tag with this name? <i class="fa fa-plus" aria-hidden="true"></i>`)

                // Restyle the component after tag creation
                function creationHandler(data) {
                    data = JSON.parse(data)

                    if (data.id == -1)
                        return

                    tagField.append($("<option selected value=" + data.id + ">" + tagName + "</option>"))

                    tagField.chosen('destroy')
                    tagField.chosen(chosenSettings)
                    chosen = tagField.parent().find(".chosen-container")
                    styleChosen()
                }

                drop.append(createTag)

                createTag.find(".fa.fa-plus").on("click", function() {
                    $.ajax({
                        type: "POST",
                        url: "/tag/create",
                        data: {
                            tagName: tagName,
                            csrfmiddlewaretoken: window.token
                        },
                        success: creationHandler
                    })
                })
            }
        } else {
            // Remove the row for tag creation when it's not needed
            let createTag = drop.find(".create-tag")
            if (createTag.length) {
                createTag.remove()
            }
        }

    })

    chosen.addClass("form-control")
}

styleChosen()

// Create form field for date time pickers
let pickers = []

form.find(".date-time-picker").each(function() {
    $(this).attr("data-input", "")
    let destination = $(this).parents("form").find(".date-times")

    let text = `

`

    let pTag = $(this).parents("p")

    let label = pTag.find("label")

    let newInput = $(text)
    newInput.find('.input-group').prepend($(this))
    newInput.prepend(label)

    pTag.remove()

    // Append newly generated element
    destination.append(newInput)
    // Enable and savev datetimepicker
    let element = $(this).is("#id_start_date_time") ? 'start' : 'end'

    let now = new Date()

    pickers[element] = {
        'picker': newInput.find(".flatpickr").flatpickr({
            enableTime: true,
            dateFormat: "m/d/y H:i",
            minDate: now.setTime(now.getTime() + 3600 * 1000),
            wrap: true
        }),
        'element': $(this)
    }
})

// Update minimum date for end picker when start gets changed
pickers.start.element.change(function() {
    let start = new Date(pickers.start.element.val())
    let minEnd = start.setTime(start.getTime() + 15 * 60 * 1000)

    pickers.end.picker.config.minDate = minEnd
    let end = new Date(pickers.end.element.val())
    if (end < minEnd) {
        pickers.end.element.val("")
    }
})

// Form checking before submission
form.submit(function(event) {
    function invalidStartDate(start) {
        let currentTime = new Date()
        let selectedTime = new Date(start.selectedDates[0])
        return selectedTime < currentTime
    }
    var start = pickers.start.picker
    var end = pickers.end.picker
    if (start.selectedDates == "" || end.selectedDates == "") {
        event.preventDefault()
        alert("Please fill out both date fields!")
    } else if (invalidStartDate(start)) {
        event.preventDefault()
        alert("Start date cannot be before the current time!")
    }
})


text:
package com.brein.time.utils;

import org.junit.Assert;
import org.junit.Test;

import java.time.ZoneId;

public class TestTimeModifier {

    @Test
    public void testWeeklyCutoff() {
        Assert.assertEquals(1627776000, TimeModifier.START_OF_DAY.applyModifier(1627776000));
        Assert.assertEquals(1627776000, TimeModifier.START_OF_WEEK.applyModifier(1627948289));
        Assert.assertEquals(1627776000, TimeModifier.START_OF_WEEK.applyModifier(1627776000));
    }

    @Test
    public void tesMoveTimeByUnit() {
        Assert.assertEquals(1629194400, TimeModifier.START_OF_DAY.moveTimeByUnit(1629108000, false, 1));
        Assert.assertEquals(1629280800, TimeModifier.START_OF_DAY.moveTimeByUnit(1629108000, false, 2));
        Assert.assertEquals(1629021600, TimeModifier.START_OF_DAY.moveTimeByUnit(1629108000, false, -1));
        Assert.assertEquals(1629158400, TimeModifier.START_OF_DAY.moveTimeByUnit(1629108000, true, 1));
        Assert.assertEquals(1629244800, TimeModifier.START_OF_DAY.moveTimeByUnit(1629108000, true, 2));

        Assert.assertEquals(1627776000, TimeModifier.START_OF_MONTH.moveTimeByUnit(1629108000, true, 0));
        Assert.assertEquals(1630454400, TimeModifier.START_OF_MONTH.moveTimeByUnit(1629108000, true, 1));
    }

    @Test
    public void testLastDayOfMonth() {
        Assert.assertEquals(
                1651381199L,
                TimeModifier.END_OF_MONTH.applyModifier(1649112712L, ZoneId.of("America/Chicago"))
        );
        Assert.assertEquals(
                1651388399L,
                TimeModifier.END_OF_MONTH.applyModifier(1649112712L, ZoneId.of("America/Los_Angeles"))
        );
    }
}


text:
<!DOCTYPE html>

        <title>{{ head.title }}</title>
        {{{ head.meta_tags }}}
        {{{ head.config }}}
        {{#block "head"}} {{/block}}
        <link href="{{ head.favicon }}" rel="shortcut icon">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        {{{stylesheet '/assets/css/theme.css'}}}
        {{ getFontsCollection }}

        {{{head.scripts}}}
        {{{head.rsslinks}}}

        {{inject 'themeImageSizes' theme_settings._images}}
        {{inject 'genericError' (lang 'common.generic_error')}}
        {{inject 'maintenanceMode' settings.maintenance}}
        {{inject 'urls' urls}}
        {{{snippet 'htmlhead'}}}

        <link rel="stylesheet" type="text/css" href="/content/diztinct.css">

            {{> components/common/navigation-menu}}

            +

        {{{snippet 'header'}}}

{{> components/common/icons/icon-defs }}

        {{#if settings.privacy_cookie}}
            {{> components/common/cookie}}
        {{/if}}

        {{> components/common/header }}
        {{> components/common/body }}
        {{> components/common/footer }}

        {{{footer.scripts}}}
        {{{snippet 'footer'}}}


text:
import { Component } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { ColumnChangesService } from '../services/column-changes.service';
import { NgxDatatableModule } from '../ngx-datatable.module';
import { DatatableComponent } from './datatable.component';
import { DataTableBodyRowComponent } from './body/body-row.component';
import { DataTableBodyCellComponent } from './body/body-cell.component';

let fixture: ComponentFixture<any>;
let component: any;

describe('DatatableComponent', () => {
  beforeEach(waitForAsync(() => setupTest(TestFixtureComponent)));

  it('should sort date values', () => {
    const initialRows = [
      { birthDate: new Date(1980, 11, 1) },
      { birthDate: new Date(1978, 8, 5) },
      { birthDate: new Date(1995, 4, 3) }
    ];

    const columns = [
      {
        prop: 'birthDate'
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    // sort by `birthDate` ascending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('1978', 'Ascending');
    expect(textContent({ row: 2, column: 1 })).toContain('1980', 'Ascending');
    expect(textContent({ row: 3, column: 1 })).toContain('1995', 'Ascending');

    // sort by `birthDate` descending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('1995', 'Descending');
    expect(textContent({ row: 2, column: 1 })).toContain('1980', 'Descending');
    expect(textContent({ row: 3, column: 1 })).toContain('1978', 'Descending');
  });

  it('should sort number values', () => {
    const initialRows = [{ id: 5 }, { id: 20 }, { id: 12 }];

    const columns = [
      {
        prop: 'id'
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    // sort by `id` ascending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('5', 'Ascending');
    expect(textContent({ row: 2, column: 1 })).toContain('12', 'Ascending');
    expect(textContent({ row: 3, column: 1 })).toContain('20', 'Ascending');

    // sort by `id` descending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('20', 'Descending');
    expect(textContent({ row: 2, column: 1 })).toContain('12', 'Descending');
    expect(textContent({ row: 3, column: 1 })).toContain('5', 'Descending');
  });

  it('should sort string values', () => {
    const initialRows = [{ product: 'Computers' }, { product: 'Bikes' }, { product: 'Smartphones' }];

    const columns = [
      {
        prop: 'product'
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    // sort by `product` ascending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('Bikes', 'Ascending');
    expect(textContent({ row: 2, column: 1 })).toContain('Computers', 'Ascending');
    expect(textContent({ row: 3, column: 1 })).toContain('Smartphones', 'Ascending');

    // sort by `product` descending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('Smartphones', 'Descending');
    expect(textContent({ row: 2, column: 1 })).toContain('Computers', 'Descending');
    expect(textContent({ row: 3, column: 1 })).toContain('Bikes', 'Descending');
  });

  it('should sort with a custom comparator', () => {
    const initialRows = [{ product: 'Smartphones' }, { product: 'Cars' }, { product: 'Bikes' }];

    const columns = [
      {
        prop: 'product',
        comparator: (productA: string, productB: string) => {
          return productA.length - productB.length;
        }
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    // sort by `product` ascending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('Cars', 'Ascending');
    expect(textContent({ row: 2, column: 1 })).toContain('Bikes', 'Ascending');
    expect(textContent({ row: 3, column: 1 })).toContain('Smartphones', 'Ascending');

    // sort by `product` descending
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('Smartphones', 'Descending');
    expect(textContent({ row: 2, column: 1 })).toContain('Bikes', 'Descending');
    expect(textContent({ row: 3, column: 1 })).toContain('Cars', 'Descending');
  });

  it('should sort using a stable sorting algorithm', () => {
    const initialRows = [
      { name: 'sed', state: 'CA' },
      { name: 'dolor', state: 'NY' },
      { name: 'ipsum', state: 'NY' },
      { name: 'foo', state: 'CA' },
      { name: 'bar', state: 'CA' },
      { name: 'cat', state: 'CA' },
      { name: 'sit', state: 'CA' },
      { name: 'man', state: 'CA' },
      { name: 'lorem', state: 'NY' },
      { name: 'amet', state: 'NY' },
      { name: 'maecennas', state: 'NY' }
    ];

    /**
     * assume the following sort operations take place on `initialRows`:
     * 1) initialRows.sort(byLengthOfNameProperty) (Ascending)
     * 2) initialRows.sort(byState)                (Descending)
     *
     * in browsers that do not natively implement stable sort (such as Chrome),
     * the result could be:
     *
     *  [
     *    { name: 'maecennas',  state: 'NY' },
     *    { name: 'amet',       state: 'NY' },
     *    { name: 'dolor',      state: 'NY' },
     *    { name: 'ipsum',      state: 'NY' },
     *    { name: 'lorem',      state: 'NY' },
     *    { name: 'sed',        state: 'CA' },
     *    { name: 'cat',        state: 'CA' },
     *    { name: 'man',        state: 'CA' },
     *    { name: 'foo',        state: 'CA' },
     *    { name: 'bar',        state: 'CA' },
     *    { name: 'sit',        state: 'CA' }
     *  ]
     *
     * in browsers that natively implement stable sort the result is guaranteed
     * to be:
     *
     *  [
     *    { name: 'amet',       state: 'NY' },
     *    { name: 'dolor',      state: 'NY' },
     *    { name: 'ipsum',      state: 'NY' },
     *    { name: 'lorem',      state: 'NY' },
     *    { name: 'maecennas',  state: 'NY' },
     *    { name: 'sed',        state: 'CA' },
     *    { name: 'foo',        state: 'CA' },
     *    { name: 'bar',        state: 'CA' },
     *    { name: 'cat',        state: 'CA' },
     *    { name: 'sit',        state: 'CA' },
     *    { name: 'man',        state: 'CA' }
     *  ]
     */

    const columns = [
      {
        prop: 'name',
        comparator: (nameA: string, nameB: string) => {
          return nameA.length - nameB.length;
        }
      },
      {
        prop: 'state'
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    // sort by `name` ascending
    sortBy({ column: 1 });
    fixture.detectChanges();

    // sort by `state` descending
    sortBy({ column: 2 });
    fixture.detectChanges();
    sortBy({ column: 2 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('amet');
    expect(textContent({ row: 2, column: 1 })).toContain('dolor');
    expect(textContent({ row: 3, column: 1 })).toContain('ipsum');
    expect(textContent({ row: 4, column: 1 })).toContain('lorem');
    expect(textContent({ row: 5, column: 1 })).toContain('maecennas');
    expect(textContent({ row: 6, column: 1 })).toContain('sed');
    expect(textContent({ row: 7, column: 1 })).toContain('foo');
    expect(textContent({ row: 8, column: 1 })).toContain('bar');
    expect(textContent({ row: 9, column: 1 })).toContain('cat');
    expect(textContent({ row: 10, column: 1 })).toContain('sit');
    expect(textContent({ row: 11, column: 1 })).toContain('man');
  });

  it('should sort correctly after push events', () => {
    const initialRows = [
      { name: 'sed', state: 'CA' },
      { name: 'dolor', state: 'NY' },
      { name: 'ipsum', state: 'NY' },
      { name: 'foo', state: 'CA' },
      { name: 'bar', state: 'CA' },
      { name: 'cat', state: 'CA' },
      { name: 'sit', state: 'CA' },
      { name: 'man', state: 'CA' },
      { name: 'lorem', state: 'NY' },
      { name: 'amet', state: 'NY' },
      { name: 'maecennas', state: 'NY' }
    ];
    const additionalRows = [...initialRows];

    const columns = [
      {
        prop: 'name',
        comparator: (nameA: string, nameB: string) => {
          return nameA.length - nameB.length;
        }
      },
      {
        prop: 'state'
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    // sort by `state` descending
    sortBy({ column: 2 });
    fixture.detectChanges();
    sortBy({ column: 2 });
    fixture.detectChanges();

    // sort by `name` ascending
    sortBy({ column: 1 });
    fixture.detectChanges();

    // mimic new `rows` data pushed to component
    component.rows = additionalRows;
    fixture.detectChanges();

    // sort by `state` descending
    sortBy({ column: 2 });
    fixture.detectChanges();
    sortBy({ column: 2 });
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('amet');
    expect(textContent({ row: 2, column: 1 })).toContain('dolor');
    expect(textContent({ row: 3, column: 1 })).toContain('ipsum');
    expect(textContent({ row: 4, column: 1 })).toContain('lorem');
    expect(textContent({ row: 5, column: 1 })).toContain('maecennas');
    expect(textContent({ row: 6, column: 1 })).toContain('sed');
    expect(textContent({ row: 7, column: 1 })).toContain('foo');
    expect(textContent({ row: 8, column: 1 })).toContain('bar');
    expect(textContent({ row: 9, column: 1 })).toContain('cat');
    expect(textContent({ row: 10, column: 1 })).toContain('sit');
    expect(textContent({ row: 11, column: 1 })).toContain('man');
  });

  it('should set offset to 0 when sorting by a column', () => {
    const initialRows = [{ id: 1 }, { id: 2 }, { id: 3 }];

    const columns = [
      {
        prop: 'id'
      }
    ];

    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    const datatableComponent = fixture.debugElement.query(By.directive(DatatableComponent)).componentInstance;
    datatableComponent.offset = 1;

    // sort by `id` descending
    sortBy({ column: 1 });
    fixture.detectChanges();
    sortBy({ column: 1 });
    fixture.detectChanges();

    expect(datatableComponent.offset).toBe(0);
  });

  it('should support array data', () => {
    const initialRows = [['Hello', 123]];

    const columns = [{ prop: 0 }, { prop: 1 }];

    // previously, an exception was thrown from column-helper.ts setColumnDefaults()
    component.rows = initialRows;
    component.columns = columns;
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('Hello');
    expect(textContent({ row: 1, column: 2 })).toContain('123');
  });
});

describe('DatatableComponent With Custom Templates', () => {
  beforeEach(waitForAsync(() => setupTest(TestFixtureComponentWithCustomTemplates)));

  it('should sort when the table is initially rendered if `sorts` are provided', () => {
    const initialRows = [{ id: 5 }, { id: 20 }, { id: 12 }];

    const sorts = [
      {
        prop: 'id',
        dir: 'asc'
      }
    ];

    component.rows = initialRows;
    component.sorts = sorts;
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 1 })).toContain('5', 'Ascending');
    expect(textContent({ row: 2, column: 1 })).toContain('12', 'Ascending');
    expect(textContent({ row: 3, column: 1 })).toContain('20', 'Ascending');
  });

  it('should reflect changes to input bindings of `ngx-datatable-column`', () => {
    const initialRows = [
      { id: 5, user: 'Sam', age: 35 },
      { id: 20, user: 'Bob', age: 50 },
      { id: 12, user: 'Joe', age: 60 }
    ];

    /**
     * initially display `user` column as the second column in the table
     */
    component.rows = initialRows;
    component.columnTwoProp = 'user';
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 2 })).toContain('Sam', 'Displays user');
    expect(textContent({ row: 2, column: 2 })).toContain('Bob', 'Displays user');
    expect(textContent({ row: 3, column: 2 })).toContain('Joe', 'Displays user');

    /**
     * switch to displaying `age` column as the second column in the table
     */
    component.columnTwoProp = 'age';
    fixture.detectChanges();

    expect(textContent({ row: 1, column: 2 })).toContain('35', 'Displays age');
    expect(textContent({ row: 2, column: 2 })).toContain('50', 'Displays age');
    expect(textContent({ row: 3, column: 2 })).toContain('60', 'Displays age');
  });
});

@Component({
  template: ` <ngx-datatable [columns]="columns" [rows]="rows" [sorts]="sorts"> </ngx-datatable> `
})
class TestFixtureComponent {
  columns: any[] = [];
  rows: any[] = [];
  sorts: any[] = [];
}

@Component({
  template: `
    <ngx-datatable [rows]="rows" [sorts]="sorts">
      <ngx-datatable-column name="Id" prop="id">
        <ng-template let-column="column" ngx-datatable-header-template>
          {{ column.name }}
        </ng-template>
        <ng-template let-row="row" ngx-datatable-cell-template>
          {{ row.id }}
        </ng-template>
      </ngx-datatable-column>
      <ngx-datatable-column [prop]="columnTwoProp">
        <ng-template let-column="column" ngx-datatable-header-template>
          {{ column.name }}
        </ng-template>
        <ng-template let-row="row" let-column="column" ngx-datatable-cell-template>
          {{ row[column.prop] }}
        </ng-template>
      </ngx-datatable-column>
    </ngx-datatable>
  `
})
class TestFixtureComponentWithCustomTemplates {
  rows: any[] = [];
  sorts: any[] = [];
  columnTwoProp: string;
}

function setupTest(componentClass) {
  return TestBed.configureTestingModule({
    declarations: [componentClass],
    imports: [NgxDatatableModule],
    providers: [ColumnChangesService]
  })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(componentClass);
      component = fixture.componentInstance;
    });
}

/**
 * mimics the act of a user clicking a column to sort it
 */
function sortBy({ column }: { column: number }) {
  const columnIndex = column - 1;
  const headerCellDe = fixture.debugElement.queryAll(By.css('datatable-header-cell'))[columnIndex];
  const de = headerCellDe.query(By.css('span:last-child'));
  de.triggerEventHandler('click', null);
}

/**
 * test helper function to return text content of a cell within the
 * body of the ngx-datatable component
 */
function textContent({ row, column }: { row: number; column: number }) {
  const [rowIndex, columnIndex] = [row - 1, column - 1];
  const bodyRowDe = fixture.debugElement.queryAll(By.directive(DataTableBodyRowComponent))[rowIndex];
  const bodyCellDe = bodyRowDe.queryAll(By.directive(DataTableBodyCellComponent))[columnIndex];

  return bodyCellDe.nativeElement.textContent;
}


text:
<resources>
  <string name="app_name">persistence</string>
</resources>


text:
CREATE TABLE plugin_configuration (
  id int(11) NOT NULL AUTO_INCREMENT,
  tenantId int(11) NOT NULL,
  assocTypeId int(11) NOT NULL,
  pluginId varchar(500) NOT NULL,
  pluginVersion varchar(50) NOT NULL,
  name varchar(255) NOT NULL,
  configuration text NOT NULL,
  active bit(1) NOT NULL DEFAULT b'0',
  PRIMARY KEY (id),
  UNIQUE KEY unique_configuration (tenantId,assocTypeId,pluginId(250),pluginVersion,name(250)),
  KEY idx_tenantAssoc (tenantId,assocTypeId)
) COMMENT='store plugin configurations for tenants';


text:
from sqlalchemy import String, Column
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Language(Base):
    __tablename__ = 'language'
    iso_code = Column(String(6), primary_key=True)
    english_name = Column(String(100))
    malagasy_name = Column(String(100))
    language_ancestor = Column(String(6))

    def get_schema(self):
        pass

    def serialise(self):
        return {
            'type': self.__class__.__name__,
            'iso_code': self.iso_code,
            'english_name': self.english_name,
            'malagasy_name': self.malagasy_name,
            'ancestor': self.language_ancestor
        }


text:
extern "C"
{
#endif

//*****************************************************************************
// DCSM flash offsets from flash base address (0x200000)
//
//*****************************************************************************
#define ZONE1_CSMPSWD0_OFFSET    0x00000000
#define ZONE1_CSMPSWD1_OFFSET    0x00000004
#define ZONE1_CSMPSWD2_OFFSET    0x00000008
#define ZONE1_CSMPSWD3_OFFSET    0x0000000C
#define ZONE1_ECSLPSWD0_OFFSET   0x00000010
#define ZONE1_ECSLPSWD1_OFFSET   0x00000014
#define ZONE1_GRABSECT_OFFSET    0x00000018
#define ZONE1_GRABRAM_OFFSET     0x0000001C
#define ZONE1_EXEONLY_OFFSET     0x00000020

#define ZONE2_CSMPSWD0_OFFSET    0x002FFFF0
#define ZONE2_CSMPSWD1_OFFSET    0x002FFFF4
#define ZONE2_CSMPSWD2_OFFSET    0x002FFFF8
#define ZONE2_CSMPSWD3_OFFSET    0x002FFFFC
#define ZONE2_ECSLPSWD0_OFFSET   0x002FFFE8
#define ZONE2_ECSLPSWD1_OFFSET   0x002FFFEC
#define ZONE2_GRABSECT_OFFSET    0x002FFFE4
#define ZONE2_GRABRAM_OFFSET     0x002FFFE0
#define ZONE2_EXEONLY_OFFSET     0x002FFFDC
//*****************************************************************************
// OTPSECLOCK offsets from flash base address (0x200000)
//
//*****************************************************************************

//*****************************************************************************
// Data structures to hold password keys
//
//*****************************************************************************
// define/declare the following in a common header file
typedef struct
{
    unsigned long csmkey0;
    unsigned long csmkey1;
    unsigned long csmkey2;
    unsigned long csmkey3;
} CSMPSWDKEY;
// define/declare the following in a common header file
typedef struct
{
    unsigned long ecslkey0;
    unsigned long ecslkey1;
} ECSLPSWDKEY;

//*****************************************************************************
// DCSM functions
//
//*****************************************************************************

extern void DCSMUnlockZone1CSM(CSMPSWDKEY *psCMDKey);
extern void DCSMUnlockZone1ECSL(ECSLPSWDKEY *psECSLKey);
extern void DCSMUnlockZone2CSM(CSMPSWDKEY *psCMDKey);
extern void DCSMUnlockZone2ECSL(ECSLPSWDKEY *psECSLKey);
extern void DCSMSecureZone1(void);
extern void DCSMSecureZone2(void);
extern void DCSMGrabFlashSectors(void);
extern void DCSMGrabRAMBlocks(void);
extern void DCSMReadZone1EXEONLY(void);
extern void DCSMReadZone2EXEONLY(void);
extern unsigned long DCSMGetRAMZone(unsigned long ramsection);
extern unsigned long DCSMGetFlashSectorZone(unsigned long sector);
extern unsigned long DCSMGetZone1EXEstatus(unsigned long sector);
extern unsigned long DCSMGetZone2EXEstatus(unsigned long sector);
extern unsigned long DCSMZone1CSMSecurityStatus(void);
extern unsigned long DCSMZone2CSMSecurityStatus(void);
extern unsigned long DCSMZone1ECSLSecurityStatus(void);
extern unsigned long DCSMZone2ECSLSecurityStatus(void);
//*****************************************************************************
// Mark the end of the C bindings section for C++ compilers.
//*****************************************************************************
#ifdef __cplusplus
}
#endif

#endif //  __DCSM_H__


text:
<?php

declare(strict_types=1);

namespace Sentry\Tests\Monolog;

use Monolog\Logger;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sentry\ClientInterface;
use Sentry\Event;
use Sentry\EventHint;
use Sentry\Monolog\Handler;
use Sentry\Severity;
use Sentry\State\Hub;
use Sentry\State\Scope;

final class HandlerTest extends TestCase
{
    /**
     * @dataProvider handleDataProvider
     */
    public function testHandle(bool $fillExtraContext, $record, Event $expectedEvent, EventHint $expectedHint, array $expectedExtra): void
    {
        /** @var ClientInterface&MockObject $client */
        $client = $this->createMock(ClientInterface::class);
        $client->expects($this->once())
            ->method('captureEvent')
            ->with(
                $this->callback(function (Event $event) use ($expectedEvent): bool {
                    $this->assertEquals($expectedEvent->getLevel(), $event->getLevel());
                    $this->assertSame($expectedEvent->getMessage(), $event->getMessage());
                    $this->assertSame($expectedEvent->getLogger(), $event->getLogger());

                    return true;
                }),
                $expectedHint,
                $this->callback(function (Scope $scopeArg) use ($expectedExtra): bool {
                    $event = $scopeArg->applyToEvent(Event::createEvent());

                    $this->assertNotNull($event);
                    $this->assertSame($expectedExtra, $event->getExtra());

                    return true;
                })
            );

        $handler = new Handler(new Hub($client, new Scope()), Logger::DEBUG, true, $fillExtraContext);
        $handler->handle($record);
    }

    public function handleDataProvider(): iterable
    {
        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::debug());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::DEBUG,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::DEBUG),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::info());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::INFO,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::INFO),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::info());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::NOTICE,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::NOTICE),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::warning());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::error());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::ERROR,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::ERROR),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::fatal());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::CRITICAL,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::CRITICAL),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::fatal());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::ALERT,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::ALERT),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::fatal());

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::EMERGENCY,
                'channel.foo',
                [],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::EMERGENCY),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::warning());

        $exampleException = new \Exception('exception message');

        yield [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [
                    'exception' => $exampleException,
                ],
                []
            ),
            $event,
            EventHint::fromArray([
                'exception' => $exampleException,
            ]),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::warning());

        yield 'Monolog\'s context is filled and the handler should fill the "extra" context' => [
            true,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [
                    'foo' => 'bar',
                    'bar' => 'baz',
                ],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
                'monolog.context' => [
                    'foo' => 'bar',
                    'bar' => 'baz',
                ],
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::warning());

        yield 'Monolog\'s context is filled with "exception" field and the handler should fill the "extra" context' => [
            true,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [
                    'exception' => new \Exception('exception message'),
                ],
                []
            ),
            $event,
            EventHint::fromArray([
                'exception' => $exampleException,
            ]),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::warning());

        yield 'Monolog\'s context is filled but handler should not fill the "extra" context' => [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [
                    'foo' => 'bar',
                    'bar' => 'baz',
                ],
                []
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
            ],
        ];
        yield 'Monolog\'s extra is filled and the handler should fill the "extra" context' => [
            true,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [],
                [
                    'foo' => 'bar',
                    'bar' => 'baz',
                ]
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
                'monolog.extra' => [
                    'foo' => 'bar',
                    'bar' => 'baz',
                ],
            ],
        ];

        $event = Event::createEvent();
        $event->setMessage('foo bar');
        $event->setLogger('monolog.channel.foo');
        $event->setLevel(Severity::warning());

        yield 'Monolog\'s extra is filled but handler should not fill the "extra" context' => [
            false,
            RecordFactory::create(
                'foo bar',
                Logger::WARNING,
                'channel.foo',
                [],
                [
                    'foo' => 'bar',
                    'bar' => 'baz',
                ]
            ),
            $event,
            new EventHint(),
            [
                'monolog.channel' => 'channel.foo',
                'monolog.level' => Logger::getLevelName(Logger::WARNING),
            ],
        ];
    }
}


text:
#region License

// https://github.com/TheBerkin/Rant
//
// Copyright (c) 2017 Nicholas Fleck
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#endregion

using System.Globalization;

namespace Rant.Core.Compiler
{
    internal struct Token
    {
        public static readonly Token None = new Token(R.Text, 0, -1, -1, null);
        public int Column;
        public int Index;
        public int Line;
        public R Type;
        public string Value;

        public Token(R type, int line, int lastLineStart, int index, string value)
        {
            Type = type;
            Line = line;
            Column = index - lastLineStart + 1;
            Index = index;
            Value = value;
        }

        public Token(R type, int line, int lastLineStart, int index, char value)
        {
            Type = type;
            Line = line;
            Column = index - lastLineStart + 1;
            Index = index;
            Value = value.ToString(CultureInfo.InvariantCulture);
        }

        public int Length => Value?.Length ?? 0;
        public LineCol ToLocation() => new LineCol(Line, Column, Index);
    }
}


text:
import { readAll, DuplexAsyncIterableIterator } from "mesh";

export type Message = {
  type: string;
}

export const DS_FIND   = "DS_FIND";
export const DS_INSERT = "DS_INSERT";
export const DS_UPDATE = "DS_UPDATE";
export const DS_REMOVE = "DS_REMOVE";
export const DS_TAIL   = "DS_TAIL";

export type DSMessage = Message & {
  collectionName: string,
  createdAt: number;
};

export type DSInsertRequest<T> = DSMessage & {
  data: T;
};

export type DSUpdateRequest<T, U> = DSMessage & {
  data: T;
  query: U;
};

export type DSFindRequest<T> = DSMessage & {
  data: T;
  multi: boolean;
};

export type DSTailRequest<T> = DSMessage & {
  query: T
};

export type DSRemoveRequest<T> = DSMessage & {
  query: T;
  multi: boolean;
};

export const dsMessage = (type: string, collectionName: string, props: any = {}): DSMessage => ({
  ...props,
  type,
  collectionName,
  createdAt: Date.now(),
});

export const dSInsertRequest = <T>(collectionName: string, data: T) => dsMessage(DS_INSERT, collectionName, {
  data
}) as DSInsertRequest<T>;

export const dSUpdateRequest = <T, U>(collectionName: string, data: T, query: U) => dsMessage(DS_UPDATE, collectionName, {
  data,
  query
}) as DSUpdateRequest<T, U>;

export const dSFindRequest = <T>(collectionName: string, query: T, multi: boolean = false) => dsMessage(DS_FIND, collectionName, {
  query,
  multi
}) as DSFindRequest<T>;

export const dSFindAllRequest = <T>(collectionName: string) => dsMessage(DS_FIND, collectionName, {
  query: {},
  multi: true
}) as DSFindRequest<T>;

export const dSRemoveRequest = <T>(collectionName: string, query: T, multi: boolean = false) => dsMessage(DS_REMOVE, collectionName, {
  query,
  multi
}) as DSRemoveRequest<T>;

export const dSTailRequest = <T>(collectionName: string, query: T) => dsMessage(DS_TAIL, collectionName, {
  query
}) as DSTailRequest<T>;


text:
calculation
===========

Over-engineered calculation in PHP!


text:
package com.meedamian.info;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.util.Log;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.PATCH;
import retrofit2.http.Path;

class RemoteData {

    private static final String API_URL = "https://basic-data.herokuapp.com";
    private static final String BASE_GIST_URL = "https://api.github.com";

    static final String HASH = "hash";
    static final String PHONE = "phone";
    static final String COUNTRY = "country";
    static final String CITY = "city";

    static void fetchFresh(@NonNull final DataCallback dc) {
        new Retrofit.Builder()
                .baseUrl(BASE_GIST_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(GistApi.class)
                .get("d881897abb1b251a912d8a31c2b59298")
                .enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        if (response == null) {
                            dc.onError(null);
                            return;
                        }

                        assert response.body() != null;
                        JsonElement filesRaw = response.body().get("files");
                        if (filesRaw == null) {
                            dc.onError(null);
                            return;
                        }

                        JsonObject files = filesRaw.getAsJsonObject();
                        JsonElement locRaw = files.get("location.json");
                        if (locRaw == null) {
                            dc.onError(null);
                            return;
                        }

                        JsonObject loc = locRaw.getAsJsonObject();
                        JsonElement contentString = loc.get("content");
                        if (contentString == null) {
                            dc.onError(null);
                            return;
                        }

                        JsonElement content = new JsonParser().parse(contentString.getAsString());
                        if (content == null) {
                            dc.onError(null);
                            return;
                        }

                        JsonObject data = content.getAsJsonObject();
                        BasicData bd = new BasicData(data);

                        dc.onDataReady(bd);
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        dc.onError(t.toString());
                    }
                });
    }

    static void upload(Context c, BasicData bd, final @Nullable SaveCallback sc) {
        bd.hash = RemoteData.getPrivateId(c);

        new Retrofit.Builder()
                .baseUrl(API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(BasicDataApi.class)
                .patch(bd)
                .enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        if (sc == null)
                            return;

                        if (response != null && Objects.requireNonNull(response.body()).isJsonObject()) {
                            Log.d("basic data", response.body().toString());
                            // TODO: show status of Twitter, gist and db
                            sc.onSave();
                            return;
                        }

                        String msg = response != null && response.body() != null ?
                                response.body().toString()
                                : "Unknown error";

                        sc.onError(msg);
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        if (sc == null) {
                            return;
                        }

                        sc.onError(t != null ? t.toString() : "Unknown error");
                    }
                });
    }

    static boolean isNetworkAvailable(Context c) {
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    @Nullable
    private static String hash(@NonNull String s) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] digest = messageDigest.digest(s.getBytes());
            return String.format("%064x", new java.math.BigInteger(1, digest));

        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    ;

    @SuppressLint("HardwareIds")
    private static String getPrivateId(@NonNull Context c) {
        String androidId = Settings.Secure.getString(
                c.getContentResolver(),
                Settings.Secure.ANDROID_ID
        );

        return hash(androidId + "->privateId");
    }

    interface GenericCallback {
        void onError(String msg);
    }

    interface DataCallback extends GenericCallback {
        void onDataReady(BasicData data);
    }

    interface SaveCallback extends GenericCallback {
        void onSave();
    }

    interface BasicDataApi {
        @PATCH("/")
        Call<JsonObject> patch(@Body BasicData patch);
    }

    interface GistApi {
        @Headers("User-Agent: meeDamian/Basic-Data")
        @GET("/gists/{id}")
        Call<JsonObject> get(@Path("id") String id);
    }
}


text:
.slide-element .slide-element-image{
    width: 785px;
    height: 485px;
    overflow: hidden;
    display: block;

}

.featured-sports-news-img{
    width: 380px;
    height: 235px;
    overflow: hidden;
    display: block;
        background: #eee;
    /* Internet Explorer 10 */
    display:-ms-flexbox;
    -ms-flex-pack:center;
    -ms-flex-align:center;

    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;

    /* Safari, Opera, and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;

    /* W3C */
    display:box;
    box-pack:center;
    box-align:center;
}
.section-thumbnail{
    width: 178px;
    height: 110px;
    overflow: hidden;
    display: block;
    background: #eee;
    /* Internet Explorer 10 */
    display:-ms-flexbox;
    -ms-flex-pack:center;
    -ms-flex-align:center;

    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;

    /* Safari, Opera, and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;

    /* W3C */
    display:box;
    box-pack:center;
    box-align:center;
}
.sidebar-image{
    width: 65px;
    height: 40px;
    overflow: hidden;
    display: block;
    background: #eee;
    /* Internet Explorer 10 */
    display:-ms-flexbox;
    -ms-flex-pack:center;
    -ms-flex-align:center;

    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;

    /* Safari, Opera, and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;

    /* W3C */
    display:box;
    box-pack:center;
    box-align:center;

    float: left;
    margin-right: 8px;
}
.sidebar-image img{
    float: none!important;
}


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

using System.Collections.Generic;
using System.Linq;
using System.Web.OData.Builder;
using Microsoft.OData.Edm;
using Microsoft.TestCommon;
using Moq;

namespace System.Web.OData.Routing
{
    public class UnboundFunctionPathSegmentTest
    {
        private IEdmModel _model;
        private IEdmEntityContainer _container;

        public UnboundFunctionPathSegmentTest()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntityType<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
            builder.EntitySet<MyCustomer>("Customers");
            FunctionConfiguration function = builder.Function("TopCustomer");
            function.ReturnsFromEntitySet<MyCustomer>("Customers");
            builder.Function("MyFunction").Returns<string>();
            _model = builder.GetEdmModel();
            _container = _model.EntityContainer;
        }

        [Fact]
        public void Ctor_ThrowsArgumentNull_UnboundFunction()
        {
            // Arrange
            Dictionary<string, string> parameters = new Dictionary<string, string>();

            // Act & Assert
            Assert.ThrowsArgumentNull(() => new UnboundFunctionPathSegment(function: null, model: _model, parameterValues: parameters),
                "function");
        }

        [Fact]
        public void Ctor_ThrowsArgumentNull_Model()
        {
            // Arrange
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            IEdmFunctionImport functionImport = _container.FindOperationImports("TopCustomer").SingleOrDefault() as IEdmFunctionImport;

            // Act & Assert
            Assert.ThrowsArgumentNull(() => new UnboundFunctionPathSegment(function: functionImport, model: null, parameterValues: parameters),
                "model");
        }

        [Fact]
        public void Ctor_TakingFunction_InitializesFunctionProperty()
        {
            // Arrange
            Mock<IEdmFunctionImport> edmFunction = new Mock<IEdmFunctionImport>();
            edmFunction.Setup(a => a.Name).Returns("Function");

            // Act
            UnboundFunctionPathSegment functionPathSegment = new UnboundFunctionPathSegment(edmFunction.Object, _model, null);

            // Assert
            Assert.Same(edmFunction.Object, functionPathSegment.Function);
        }

        [Fact]
        public void Ctor_TakingFunction_InitializesFunctionNameProperty()
        {
            // Arrange
            IEdmFunctionImport function = _container.FindOperationImports("MyFunction").SingleOrDefault() as IEdmFunctionImport;

            // Act
            UnboundFunctionPathSegment functionPathSegment = new UnboundFunctionPathSegment(function, _model, null);

            // Assert
            Assert.Equal("MyFunction", functionPathSegment.FunctionName);
        }

        [Fact]
        public void Property_SegmentKind_IsUnboundFunction()
        {
            // Arrange
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment("function", parameters);

            // Assert
            Assert.Equal(ODataSegmentKinds.UnboundFunction, segment.SegmentKind);
        }

        [Fact]
        public void ToString_ReturnsSameString_UnboundFunction()
        {
            // Arrange
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("Id", "123");
            parameters.Add("Name", "John");
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment("function", parameters);

            // Act
            string actual = segment.ToString();

            // Assert
            Assert.Equal("function(Id=123,Name=John)", actual);
        }

        [Fact]
        public void GetEdmType_ThrowsArgumentException_IfArgumentNotNull()
        {
            // Arrange
            var segment = new UnboundFunctionPathSegment("GetTopCustomer", parameterValues: null);
            Mock<IEdmType> edmType = new Mock<IEdmType>();

            // Act & Assert
            Assert.Throws<ArgumentException>(() => segment.GetEdmType(edmType.Object));
        }

        [Fact]
        public void GetEdmType_ReturnsNotNull_EntityType()
        {
            // Arrange
            IEdmFunctionImport functionImport = _container.FindOperationImports("TopCustomer").SingleOrDefault() as IEdmFunctionImport;
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment(functionImport, _model, parameterValues: null);

            // Act
            var result = segment.GetEdmType(previousEdmType: null);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("System.Web.OData.Routing.MyCustomer", result.FullTypeName());
        }

        [Fact]
        public void GetEdmType_ReturnsNull_IfActionNull()
        {
            // Arrange
            var segment = new UnboundActionPathSegment("TopCustomer");

            // Act
            var result = segment.GetEdmType(previousEdmType: null);

            // Assert
            Assert.Null(result);
        }

        [Fact]
        public void GetEdmType_ReturnsNotNull_PrimitiveReturnType()
        {
            // Arrange
            IEdmFunctionImport functionImport = _container.FindOperationImports("MyFunction").SingleOrDefault() as IEdmFunctionImport;
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment(functionImport, _model, parameterValues: null);

            // Act
            var result = segment.GetEdmType(previousEdmType: null);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("Edm.String", result.FullTypeName());
        }

        [Fact]
        public void GetNavigationSource_ReturnsNotNull_UnboundFunctionEntitySetType()
        {
            // Arrange
            IEdmFunctionImport functionImport = _container.FindOperationImports("TopCustomer").SingleOrDefault() as IEdmFunctionImport;
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment(functionImport, _model, parameterValues: null);

            // Act
            var result = segment.GetNavigationSource(previousNavigationSource: null);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("System.Web.OData.Routing.MyCustomer", result.EntityType().FullName());
        }

        [Fact]
        public void GetNavigationSource_ReturnsNull_UnboundFunctionEntitySetType()
        {
            // Arrange
            IEdmFunctionImport functionImport = _container.FindOperationImports("MyFunction").SingleOrDefault() as IEdmFunctionImport;
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment(functionImport, _model, parameterValues: null);

            // Act
            var result = segment.GetNavigationSource(previousNavigationSource: null);

            // Assert
            Assert.Null(result);
        }

        [Fact]
        public void TryMatch_ReturnsTrue_IfSameUnboundFunction()
        {
            // Arrange
            IEdmFunctionImport function = _container.FindOperationImports("TopCustomer").SingleOrDefault() as IEdmFunctionImport;
            UnboundFunctionPathSegment template = new UnboundFunctionPathSegment(function, _model, parameterValues: null);
            UnboundFunctionPathSegment segment = new UnboundFunctionPathSegment(function, _model, parameterValues: null);

            // Act
            Dictionary<string, object> values = new Dictionary<string, object>();
            bool result = template.TryMatch(segment, values);

            // Assert
            Assert.True(result);
            Assert.Empty(values);
        }

        internal class MyCustomer
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }
}


text:
package com.aguil.server.persistence.domain;

import javax.persistence.*;
import java.util.Collection;

/**
 * Created by Richard.
 */
@Entity
@DiscriminatorValue(value = "1")
public class Team extends Assignable {
    private Collection<Membership> memberships;

    @OneToMany(mappedBy = "team")
    public Collection<Membership> getMemberships() {
        return memberships;
    }

    public void setMemberships(Collection<Membership> memberships) {
        this.memberships = memberships;
    }
}


text:
require "thor"

require "takeoff"

module Takeoff
  class CLI < Thor
    default_task :launch

    class_option :config, aliases: "-c", desc: "Path to your Takeoff configuration file. Defaults to ./Launchfile or ./config/takeoff.rb"

    desc "launch [PLAN]", "Deploy using the specified launch plan."

    long_desc <<-LONG_DESC
      Deploys using the specified launch plan.

      PLAN can be any launch plan that comes out of the box or that you've specified in your configuration file.
      PLAN defaults to the contents of the `RACK_ENV` or `RAILS_ENV` environment variable or the default plan set in your configuration file.
    LONG_DESC

    option :skip, type: :array, aliases: "-s", desc: "Space-seperated list of full or partial names of stages to skip. Example: `-s VerifyServerNotAlreadyUpToDate` if you want to re-do a deployment."

    def launch(plan = nil)
      setup

      plan ||= ENV["RACK_ENV"] || ENV["RAILS_ENV"]
      plan = Takeoff[plan]

      options[:skip].each do |name|
        plan.stages.delete(name)
      end if options[:skip]

      plan.launch
    end

    private
      def setup
        config_path = options[:config]
        config_path ||= "./Launchfile"        if File.exist?("./Launchfile")
        config_path ||= "./config/takeoff.rb" if File.exist?("./config/takeoff.rb")

        raise "Config file not found!" unless config_path

        Takeoff.configure(File.read(config_path), config_path)
      end
  end
end


text:
class AddIsVerifyToverifyUsers < ActiveRecord::Migration
  def change
  end
end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.netbeans.rest.application.config;
/**
 * This class is generated by the NetBeans IDE,
 * and registers all REST root resources created in the project.
 * Please, DO NOT EDIT this class unless you really need and
 * understand the results of changes.
 * It is safe to change REST resources path value of
 * ApplicationPath annotation. It can be done also via UI action
 * called on RESTful Web Services node ( REST Resources Configuration dialog ).
 *
 */
@javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends javax.ws.rs.core.Application {
}


text:
APX Helper CRUD
============

## Kado

STOP AND READ THIS

APX or Apex is no longer maintained and is superseded by Kado.

A new package is available to handle all your JavaScript needs.
See [kado.org](https://kado.org) for details.

## Summary

CRUD (Create Read Update Delete) helper for APX API server actions

Requires Mongoose Models and the [mongoose-list](https://github.com/snailjs/mongoose-list) and [mongoose-merge plugin](https://github.com/eherve/mongoose-merge-plugin) plugins.

## Usage

Simply require the helper within your actions

```
$ npm install apx-helper-crud --save
```

```js
var Crud = require('apx-helper-crud')
  , Model = require('./models/test').model

//will populate all the following crud functions
// * find
// * findOne
// * list (which required the model to use the mongoose-list plugin)
// * save
// * remove
module.exports = new Crud(Model,'test','Test Module')
```

## Route Helper

Helper CRUD will also help populate route methods to cut down on repetition.

**config.js**
```js
var crud = require('apx-helper-crud')

module.exports = {
  express: {
    routes: [
      {get: {path: '/myAction', file: 'actions/myAction.js', methods: crud.methods()}}
    ]
  }
}
```

You can also supply additional routes to the methods helper.

**config.js**
```js
var crud = require('apx-helper-crud')

module.exports = {
  express: {
    routes: [
      {get: {path: '/myAction', file: 'actions/myAction.js', methods: crud.methods(['extraAction','extraAction2'])}}
    ]
  }
}
```

Alternatively a string may be passed that will be added as a single method. Also a function may be passed that returns
either a string or an array of methods.

## Constructor

The constructor only takes the following arguments.
* Model -- The model to operate on
* Name -- Name of the module
* Description -- Description the module

```js
var Crud = require('apx-helper-crud')
  , Model = require('./models/test').model
  , crud = new Crud(Model,'test','Test Module')
```

## Methods

All of the Crud methods are APX actions so they accept request data directly and return APX responses.

### Find

Find records by the criteria in the data object.

Takes a Mongoose query object as the only argument.

```js
{name: 'test doc'}
```

Returns an object of results.

```js
{results: [{name: 'test doc'}]}
```

### Find One

Find a single record by the criteriea in the data object.
Useful for finding items by ObjectID

Takes a mongoose query object as the only argument.

```js
{name: 'test doc'}
```

Returns an object of results.

```js
{result: {name: 'test doc'}}
```

### List

Utilizes the [mongoose-list](https://github.com/snailjs/mongoose-list) plugin
to iterate records in a collection.

Takes a mongoose-list arugment object.

```js
{start: 0, limit: 10, find: 'foo', sort: 'bar'}
```

Returns a results object

```js
{count: 10, results: [{name: 'test doc'}]}
```

### Save

Save one or many documents.

**IMPORTANT** requires the
[mongoose-merge plugin](https://github.com/eherve/mongoose-merge-plugin)
to be loaded in the model.

Accepts a document or an array of documents.

```js
[{name: 'test doc'}]
```

Returns a result object

```js
{results: [{name: 'test doc'}]}
```

### Remove

Remove one or many documents.

Accepts a query object or an array of query objects.

```js
[{name: 'test doc'}]
```

Returns success or error only.

## Roles

If [apx-roles](https://github.com/snailjs/apx-roles) is loaded at initialization they will be implemented by the crud
helper unless explicitly disabled.

The use of roles also requires [apx-session](https://github.com/snailjs/apx-session) to be loaded as it will look for
`apx.session.get('profile')` to test against and will default to the profile `guest`.

Take a look at the following example
```js
module.exports = new Crud(Model,'foo','my crud action')
```

This will expose the following roles.
* foo.find
* foo.save
* foo.remove

`find`, `findOne`, and `list` are all considered part of the `find` permission.

To disable roles even with the module loaded, try the following
```js
module.exports = new Crud(Model,'foo','my crud action',{useRoles: false})
```

## Changelog

### 0.2.5
* Updated to implement `'use strict';` in all files
* Implemented apx-roles support to check permissions when available
* Updated jshintrc to newest standards with other apx projects

### 0.2.4
* Fixed small issue with save trying to read the property `items` in the request
* Added testing against erroneous input for `save`, `remove` and `findOne`
* Fixed issues with error handling on `save`, `remove` and `findOne`

### 0.2.3
* Upgraded to apx 0.7.1 and apx-mongoose 0.5.1

### 0.2.2
* Added methods helper to populate routes

### 0.2.1
* Crud helper now fills name and description along with default run task
* Updated usage statement

### 0.2.0
* Completely re-imagined interface that can just extend methods of an action.
* Simplified return formats to be more predictable
* All methods are now APX actions

### 0.1.3
* Better error handling on un-sanitized input

### 0.1.2
* Fixed responses needing to be passed to `doc.toJSON({virtuals: true})`
* Updated to apx 0.3.0

### 0.1.1
* Added missing dependencies

### 0.1.0
* Initial release


text:
shirts
======

Shirt allocator for Football teams


text: require("core-js/modules/es6.typed.uint8-clamped-array");