text:
/****************************************************************/
/* image_correlation.c
/* rectangular window match: image-correlation pattern window ...
/* linear match: circular-correlation pattern target num_components
/* gcc -c -Di386 -DLinux -w -DGCC  -fpic  -I../c -O image_correlation.c;
   ld -shared -o image_correlation.so image_correlation.o
/* cc -c -O -Dsun4 -Bstatic -I../../c cor.c
*****************************************************************/

#include "eus.h"
#include "pix.h"
#define abs(x) ((x)<0?-(x):x)
#define imgvec(img,x,y) (&((img)->imgary[(y)*(img)->twidth + x]))

#pragma init (init_object_module)
pointer image_correlation();

static init_object_module()
  { add_module_initializer("image_correlation", image_correlation);}

static set_pixparams(piximg, eusary)
pixel_image *piximg;
pointer eusary;
{ pointer imgp;
  imgp=eusary->c.ary.entity;
/*  printf("imgp=%x\n", imgp); */
  piximg->imgary=
	(elmtypeof(imgp)==ELM_FOREIGN)?
		((unsigned char *)imgp->c.ivec.iv[0]) :
		(imgp->c.str.chars);
/*  printf("imgary=%x\n", piximg->imgary); */
  piximg->depth=8;
  piximg->twidth=intval(eusary->c.ary.dim[1]);
  piximg->theight=intval(eusary->c.ary.dim[0]);
  piximg->tsize=piximg->twidth*piximg->theight;
  piximg->width=intval(eusary->c.ary.dim[1]);
  piximg->height=intval(eusary->c.ary.dim[0]);
  piximg->wsize=piximg->width * piximg->height; }

static int img_correlation1(image,pattern,x,y)
register pixel_image *image, *pattern;
{ register unsigned char *img=image->imgary, *pat=pattern->imgary;
  register int i, j;
  register int ww=pattern->width;
  register long cor, corsum=0;
  int tiw=image->twidth, piw=pattern->twidth;
  int wh=pattern->height;

  img=imgvec(image, x, y);
  pat=imgvec(pattern, 0, 0);
  for (j=0; j<wh; j++) {
    for (i=0; i<ww; i++) {
      cor=img[i]-pat[i];
      corsum+= abs(cor);}
    img+=tiw; pat+=piw;
    }
  return(corsum);}

struct corinfo {
  long corval;
  long x,y;
  };

static int img_correlation(image,pattern,x0,y0,size,threshold,result)
pixel_image *image, *pattern;
register int size;
register int threshold;
int x0, y0;
struct corinfo *result;
{ register unsigned char *img=image->imgary, *pat=pattern->imgary;
  register int i, j;
  register int x, y;
  register int tiw=image->twidth, piw=pattern->twidth;
  register int ww=pattern->width;
  register long cor, corsum;
  register int  wh=pattern->height;
  int  found=0;

  for (y=y0; y<y0+size; y++) {
    for (x=x0; x<x0+size; x++) {
      /* compute correlation for a particular window */
      corsum=0;
      img=imgvec(image, x, y);
      pat=imgvec(pattern, 0, 0);
      for (j=0; j<wh; j++) {
        for (i=0; i<ww; i++) {
          cor=img[i]-pat[i];
	  if (cor>0) corsum+=cor;
	  else corsum-=cor;}
        if (corsum>threshold) goto nextwindow;
        img+=tiw; pat+=piw;  }

      /* correlation factor for a window is obtained in corsum */
      if (corsum<threshold) {
	if (debug) printf("cor=%ld (%d, %d)\n", corsum, x, y);
        found=1;
	threshold=corsum;
	result->corval=corsum;
	result->x=x; result->y=y;};
      /* try a next window */
      nextwindow: continue;
      } }
  return(found);}

static pointer IMAGE_CORRELATION1(ctx,n,argv)
context *ctx;
int n;
pointer argv[];
{ pointer arg0, arg1;
  pixel_image img,pat;
  int x,y, cor;
  ckarg(4);
  set_pixparams(&img, argv[0]);
  set_pixparams(&pat, argv[1]);
  x=ckintval(argv[2]); y=ckintval(argv[3]);
  cor=img_correlation1(&img, &pat, x, y);
  return(makeint(cor));}

/* (IMAGE-CORRELATION image pattern x y size threshold) */

static pointer IMAGE_CORRELATION(ctx,n,argv)
context *ctx;
int n;
pointer argv[];
{ pointer arg0, arg1;
  pixel_image img,pat;
  int x,y, cor, size, threshold;
  struct { long corval, x, y;} result;
  ckarg(6);
  set_pixparams(&img, argv[0]);
  set_pixparams(&pat, argv[1]);
  x=ckintval(argv[2]); y=ckintval(argv[3]);
  size=ckintval(argv[4]);  threshold=ckintval(argv[5]);
  cor=img_correlation(&img, &pat, x, y, size, threshold, &result);
  if (cor) {
    vpush(makeint(result.corval));
    vpush(makeint(result.x));
    vpush(makeint(result.y));
    return((pointer)stacknlist(ctx,3));}
  else return(NIL);}

static pointer CIRCULAR_CORRELATION(ctx,n,argv)
/* Actually, this is a linear correlation. */
context *ctx;
int n;
pointer argv[];
{ unsigned char *pat1, *pat2, pat2x[1024*4];
  int len, num_components, total_len, i, j, k, x, y;
  int c, cor, min_cor, min_pos, max_cor, avecor, total_cor;
  float fcor, flen;
  pointer fcorvec, r;
  numunion nu;

  ckarg(3);
  num_components=ckintval(argv[2]);
  pat1=get_string(argv[0]);
  pat2=get_string(argv[1]);
  total_len=vecsize(argv[0]);
  if (total_len != vecsize(argv[1])) error(E_VECSIZE);
  if (total_len >=1024*3) error(E_ARRAYINDEX);
  memcpy(&pat2x[0], pat2, total_len);
  memcpy(&pat2x[total_len], pat2, total_len);
  len=total_len/num_components;
  flen=len;
  fcorvec=makevector(C_FLTVECTOR, len);
  vpush(fcorvec);

  min_pos = -1; min_cor=0x3fffffff; max_cor=0; total_cor=0;

  for (i=0; i<len; i++) {
    cor=0; x=i*num_components;
    for (j=0; j<len; j++) {
      c=0; y=j*num_components;
      for (k=0; k<num_components; k++) c += abs(pat2x[x+j+k]-pat1[j+k]);
      cor += c/num_components; }
    if (cor < min_cor) { min_cor=cor; min_pos=i; }
    else if (cor>max_cor) max_cor=cor;
    total_cor += cor;
    fcorvec->c.fvec.fv[i]=(float)cor/total_len;
    }
  vpush(makeint(min_pos));
  vpush(makeflt(min_cor/(flen*num_components)));
  vpush(makeflt(total_cor/(flen*num_components*flen)));
  vpush(makeflt(max_cor/(len*num_components)));
  vpush(fcorvec);
  r=stacknlist(ctx,5);
  vpop();
  return(r);}

pointer image_correlation(ctx,n,argv)
context *ctx;
int n;
pointer argv[];
{ pointer mod=argv[0];
  defun(ctx,"IMAGE-CORRELATION1",mod,IMAGE_CORRELATION1);
  defun(ctx,"IMAGE-CORRELATION",mod,IMAGE_CORRELATION);
  defun(ctx,"CIRCULAR-CORRELATION",mod,CIRCULAR_CORRELATION);
  return(NIL);
  }


text:
/*global jQuery*/

(function($) {
  'use strict';
  $.fn.resizeMe = function(options) {
    options = $.extend({
      'example': 1500,
      'el': null
    }, options);

    var $d   = $(document);
    var from = '';
    var isTouch = 'ontouchstart' in window;

    function resizeStart(e) {
      console.log(isTouch);
      console.log(e.clientX);
      var start = {};
      start.x = isTouch ? e.touches[0].pageX : e.clientX;
      start.y = isTouch ? e.touches[0].pageY : e.clientY;
      start.width = options.el.width();
      start.height = options.el.height();
      start.top = options.el.offset().top;
      start.left = options.el.offset().left;
      $('.chromewindow__iframe').css('pointer-events', 'none');

      function resizeMove(e) {
        var current = {};
        current.x = isTouch ? e.touches[0].pageX : e.clientX;
        current.y = isTouch ? e.touches[0].pageY : e.clientY;

        if (from === 't') {
          options.el.height((start.height + (start.y - current.y)) + 'px');
          options.el.css({'transform': 'translate(' + start.left + 'px, ' + (start.top - (start.y - current.y)) + 'px)'});
        } else if (from === 'r') {
          options.el.width((start.width - (start.x - current.x)) + 'px');
        } else if (from === 'b') {
          options.el.height((start.height - (start.y - current.y)) + 'px');
        } else {
          options.el.width((start.width + (start.x - current.x)) + 'px');
          options.el.css({'transform': 'translate(' + (start.left - (start.x - current.x)) + 'px, ' + start.top + 'px)'});
        }
      }

      function resizeEnd() {
        $d.off('mousemove', resizeMove);
        $d.off('mouseup', resizeEnd);
        document.body.style.cursor = 'default';
        $('.chromewindow__iframe').css('pointer-events', 'all');
      }

      $d.on('mousemove', resizeMove);
      $d.on('mouseup', resizeEnd);

      from = $(e.target).attr('data-resizefrom');

      if ($(e.target).attr('data-resizeable') === 'ns') {
        document.body.style.cursor = 'ns-resize';
      } else {
        document.body.style.cursor = 'ew-resize';
      }
    }

    function setListeners() {
      options.el.find('.resizeable__arm').on('mousedown', resizeStart);
    }

    function init() {
      setListeners();
    }

    init();
  };
})(jQuery);

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package automata.svpa;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import org.sat4j.specs.TimeoutException;

import automata.svpa.TaggedSymbol.SymbolTag;

import theory.BooleanAlgebra;
import utilities.Pair;

public class Return extends SVPAMove {

	Integer stackState;
	U guard;

	/**
	 * Constructs an FSA Transition that starts from state from and
	 * ends at state to with input input
	 */
	public Return(Integer from, Integer to, Integer stackState, U guard) {
		super(from, to, Tag.Return);

		this.guard = guard;
		this.stackState = stackState;
	}

	public boolean isDisjointFrom(SVPAMove t, BooleanAlgebra ba) throws TimeoutException {
		if (t instanceof Return)
			if (from.equals(t.from) && stackState == ((Return) t).stackState){
				List conjuncts = new ArrayList();
				conjuncts.add(guard);
				conjuncts.add(((Return) t).guard);
				if (ba.IsSatisfiable(ba.MkAnd(conjuncts)))
					return false;
			}
		return true;
	}

	public boolean isSatisfiable(BooleanAlgebra boolal) throws TimeoutException {
		return boolal.IsSatisfiable(guard);
	}

	public Pair<Integer, Stack<Pair<Integer, S>>> getNextState(
			Pair<Integer, Stack<Pair<Integer, S>>> state,
			TaggedSymbol<S> input, BooleanAlgebra ba) throws TimeoutException {
		if (input.tag == SymbolTag.Return) {
			Integer currState = state.first;
			if (currState == from) {
				Stack<Pair<Integer, S>> currStack = state.second;
				if (currStack.size() > 0) {
					Pair<Integer, S> stackTop = currStack.peek();

					if (stackTop.first == stackState
							&& ba.HasModel(guard, stackTop.second, input.input)) {
						@SuppressWarnings("unchecked")
						Stack<Pair<Integer, S>> newStack = (Stack<Pair<Integer, S>>) currStack
								.clone();
						newStack.pop();
						return new Pair<Integer, Stack<Pair<Integer, S>>>(to,
								newStack);
					}
				}
			}

		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return String.format("R: %s -%s, %s-> %s", from, guard, stackState, to);
	}

	@Override
    public int hashCode() {
		int hashZero = (from+3)*3+from;
		int hashFirst = (hashZero+to)*to+hashZero;
    	int hashSec = (hashFirst+stackState)*hashFirst+stackState;
    	return (hashSec+guard.hashCode())*hashSec+guard.hashCode();
    }

    @Override
	public boolean equals(Object other) {
		if (other instanceof Return<?, ?>) {
			Return<?, ?> otherCasted = (Return<?, ?>) other;
			return otherCasted.from == from && otherCasted.to == to
					&& otherCasted.guard == guard
					&& otherCasted.stackState == stackState;
		}

		return false;
	}

	public Object clone() {
		return new Return(from, to, stackState, guard);
	}

	@Override
	public String toDotString() {
		return String.format("%s -> %s [label=\"R%s/%s\", fontcolor=blue]\n", from,to,guard, stackState);
	}

	@Override
	public boolean isEpsilonTransition() {
		return false;
	}

	@Override
	public S getWitness(BooleanAlgebra ba) throws TimeoutException {
		return ba.generateWitness(guard);
	}

}


text:
import datetime
import uuid

import pytest

from google.cloud import bigquery
from google.cloud import bigquery_v2

@pytest.fixture(scope="module")
def client():
    return bigquery.Client()

@pytest.fixture
def random_table_id(client, dataset_id):
    now = datetime.datetime.now()
    random_table_id = "example_table_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )
    return "{}.{}".format(dataset_id, random_table_id)

@pytest.fixture
def random_dataset_id(client):
    now = datetime.datetime.now()
    random_dataset_id = "example_dataset_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )
    yield "{}.{}".format(client.project, random_dataset_id)
    client.delete_dataset(random_dataset_id, delete_contents=True, not_found_ok=True)

@pytest.fixture
def random_routine_id(client, dataset_id):
    now = datetime.datetime.now()
    random_routine_id = "example_routine_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )
    return "{}.{}".format(dataset_id, random_routine_id)

@pytest.fixture
def dataset_id(client):
    now = datetime.datetime.now()
    dataset_id = "python_dataset_sample_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )
    dataset = client.create_dataset(dataset_id)
    yield "{}.{}".format(dataset.project, dataset.dataset_id)
    client.delete_dataset(dataset, delete_contents=True, not_found_ok=True)

@pytest.fixture
def table_id(client, dataset_id):
    now = datetime.datetime.now()
    table_id = "python_table_sample_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )

    table = bigquery.Table("{}.{}".format(dataset_id, table_id))
    table = client.create_table(table)
    yield "{}.{}.{}".format(table.project, table.dataset_id, table.table_id)
    client.delete_table(table, not_found_ok=True)

@pytest.fixture
def table_with_schema_id(client, dataset_id):
    now = datetime.datetime.now()
    table_id = "python_table_with_schema_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )
    schema = [
        bigquery.SchemaField("full_name", "STRING"),
        bigquery.SchemaField("age", "INTEGER"),
    ]
    table = bigquery.Table("{}.{}".format(dataset_id, table_id), schema=schema)
    table = client.create_table(table)
    yield "{}.{}.{}".format(table.project, table.dataset_id, table.table_id)
    client.delete_table(table, not_found_ok=True)

@pytest.fixture
def table_with_data_id(client):
    return "bigquery-public-data.samples.shakespeare"

@pytest.fixture
def routine_id(client, dataset_id):
    now = datetime.datetime.now()
    routine_id = "python_routine_sample_{}_{}".format(
        now.strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8]
    )

    routine = bigquery.Routine("{}.{}".format(dataset_id, routine_id))
    routine.type_ = "SCALAR_FUNCTION"
    routine.language = "SQL"
    routine.body = "x * 3"
    routine.arguments = [
        bigquery.RoutineArgument(
            name="x",
            data_type=bigquery_v2.types.StandardSqlDataType(
                type_kind=bigquery_v2.enums.StandardSqlDataType.TypeKind.INT64
            ),
        )
    ]

    routine = client.create_routine(routine)
    yield "{}.{}.{}".format(routine.project, routine.dataset_id, routine.routine_id)
    client.delete_routine(routine, not_found_ok=True)

@pytest.fixture
def model_id(client, dataset_id):
    model_id = "{}.{}".format(dataset_id, uuid.uuid4().hex)

    # The only way to create a model resource is via SQL.
    # Use a very small dataset (2 points), to train a model quickly.
    sql = """
    CREATE MODEL `{}`
    OPTIONS (
        model_type='linear_reg',
        max_iteration=1,
        learn_rate=0.4,
        learn_rate_strategy='constant'
    ) AS (
        SELECT 'a' AS f1, 2.0 AS label
        UNION ALL
        SELECT 'b' AS f1, 3.8 AS label
    )
    """.format(
        model_id
    )

    client.query(sql).result()
    return model_id


text:
cfpicker
========

A handy colour picker for designing in the browser with Sass.
- View a range of tints and shades for colours in a palette
- Copy the Sass code for the tint or shade you require.

Requirements
------------

- PHP
- Sass and Compass

How to use
------------------------------

- Add palette.php to your webroot and update paths to CSS and JS files as necessary.
- Add _base.scss and colour.scss to your Sass directory
- Edit the palette colours in base.scss and palette.php
- Set the increment value in colour.scss and palette.php

View a demo
-----------

http://www.regbirch.com/projects/cfpicker/palette.php

Read the blog post
------------------

http://www.regbirch.com/blog/colour-picker-for-sass


text:
<?php

namespace AdiFaidz\Base\Commands;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;

class ViewMakeCommand extends GeneratorCommand
{
    protected $signature = 'base:view {name} {--m|model=}';

    protected $description = 'Create new CRUD ready views and vue components for a model class';

    protected $type = 'View';

    public function __construct(Filesystem $filesystem)
    {
        parent::__construct();

        $this->filesystem = $filesystem;
    }

    public function handle()
    {
      $name = $this->getNameInput();
      $viewPath = $this->parseName($name, 'getViewPath', base_path());
      $vuePath = $this->parseName($name, 'getVuePath', base_path());

      $modelClass = $this->option('model');

      if(!$modelClass){
        return $this->error("Model class is required.");
      }

      $model = $this->parseName($modelClass, 'getDefaultNamespace');

      if(!$this->filesystem->exists($this->getPath($model))){
        return $this->error("Model $modelClass does not exists.");
      }

      $args = [
       'name'=> trim($this->argument('name')),
       'model'=> $model,
      ];

      $viewStubs = $this->filesystem->allFiles($this->getViewStubs());
      $vueStubs = $this->filesystem->allFiles($this->getVueStubs());

      foreach ($viewStubs as $stub) {
        $stubPath = str_replace($this->getViewStubs(), '', $stub->getPathName());
        $stubPath = str_replace('.stub', '.php', $stubPath);

        $path = $viewPath .$stubPath;
        $filename = str_replace("\\", '', $stubPath);

        if($this->filesystem->exists($path)){
          $this->info("View $filename already exists");
          continue;
        }

        $args['stub'] = $this->filesystem->get($stub->getPathName());
        $this->makeDirectory($path);
        $this->filesystem->put($path, $this->buildClass($args));
        unset($args['stub']);
      }

      foreach ($vueStubs as $stub) {
        $stubPath = str_replace($this->getVueStubs(), '', $stub->getPathName());
        $stubPath = str_replace('.stub', '.vue', $stubPath);

        $path = $vuePath .$stubPath;
        $filename = str_replace("\\", '', $stubPath);

        if($this->filesystem->exists($path)){
          $this->info("Vue component $filename already exists");
          continue;
        }

        $args['stub'] = $this->filesystem->get($stub->getPathName());
        $this->makeDirectory($path);
        $this->filesystem->put($path, $this->buildClass($args));
        unset($args['stub']);
      }

      $this->appendAppJs($name, $args);
      $this->info("{$this->type} created successfully.");
    }

    protected function getStub(){

    }

    protected function getViewStubs()
    {
        return !empty(config('base.stubs.view')) ? config('base.stubs.view') : __DIR__ . '/stubs/view/views';
    }

    protected function getVueStubs()
    {
        return !empty(config('base.stubs.vue')) ? config('base.stubs.vue') : __DIR__ . '/stubs/view/vue';
    }

    protected function getViewPath($rootNamespace)
    {
      return $rootNamespace . '\resources\views';
    }

    protected function getVuePath($rootNamespace)
    {
      return $rootNamespace . '\resources\assets\js\components';
    }

    protected function getDefaultNamespace($rootNamespace)
    {
      return $rootNamespace;
    }

    protected function get($rootNamespace)
    {
      return $rootNamespace . '\Transformers';
    }

    public function buildClass(Array $args)
    {
      $stub = $args['stub'];
      $this->replaceModel($stub, $args['model'])
           ->replaceName($stub, $args['name']);

      return $stub;
    }

    public function getNameInput(){
      return strtolower(trim($this->argument('name')));
    }

    public function replaceModel(&$stub, $model){
      $modelpos = 0;

      if(strrpos($model, '\\') !== false){
        $modelpos = strrpos($model, '\\') + 1;
      }

      $class = ucfirst(substr($model, $modelpos));
      $stub = str_replace('{{modelclass}}', $class, $stub);

      $human = preg_replace('/(?<!\ )[A-Z]/', '$0', $class);
      $stub = str_replace('{{modelhuman}}', $human, $stub);

      $varname  = strtolower($class);
      $stub = str_replace('{{modelname}}', $varname, $stub);

      return $this;
    }

    public function replaceName(&$stub, $name){
      $lastSlashPos = 0;

      if(strrpos($name, '\\') !== 0){
        $lastSlashPos = strrpos($name, '\\');
      }

      $classLength = strlen(substr($name, $lastSlashPos));
      $layoutPath = substr($name, -($lastSlashPos + $classLength),  strlen($name) - $classLength);

      $type = str_replace('\\', '.', strtolower($layoutPath));
      $stub = str_replace('{{type}}', "$type", $stub);

      $viewpath  = str_replace('\\', '.', strtolower($name));
      $stub = str_replace('{{viewpath}}', "$viewpath", $stub);

      $vuepath   = str_replace('\\', '-', strtolower($name));
      $stub = str_replace('{{vuepath}}', "$vuepath", $stub);

      return $this;
    }

    public function appendAppJs($name, $args){
      $path = config('base.app_js_path');
      $vuepath  = str_replace('\\', '-', strtolower($name));
      $vuefilepath  = str_replace('\\', '/', strtolower($name));

      $stub = $this->filesystem->get(__DIR__ . '/stubs/app.js.stub');
      $stub = str_replace('{{vuepath}}', $vuepath, $stub);
      $stub = str_replace('{{vuefilepath}}',$vuefilepath , $stub);

      if(!$this->filesystem->exists($path)){
          $this->makeDirectory($path);
          $this->filesystem->put($path, '');
      }
      else{
        $routeFile = $this->filesystem->get($path);

        if(str_contains(trim($routeFile), trim($stub))){
            $this->info('Components already registered');
            return;
        }
      }

      $this->filesystem->append($path, $stub);
    }
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <stdlib.h>
#include <typeinfo>

#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/common/timer.hh>
#include <dune/common/parametertreeparser.hh>

#include <dune/grid/common/scsgmapper.hh>
#include <dune/grid/onedgrid.hh>
#if HAVE_ALBERTA
#include <dune/grid/albertagrid.hh>
#include <dune/grid/albertagrid/dgfparser.hh>
#endif
#if HAVE_UG
#include <dune/grid/uggrid.hh>
#endif
#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#include <dune/grid/io/file/dgfparser/dgfalu.hh>
#include <dune/grid/io/file/dgfparser/dgfparser.hh>
#endif

#include <dune/ax1/common/tools.hh>
#include <dune/ax1/common/output.hh>
#include <dune/ax1/acme0/common/acme0_factory.hh>
#include <dune/ax1/acme0/common/acme0_physics.hh>
#include <dune/ax1/acme0/common/acme0_parametertree.hh>
//#ifdef ACME0_FULLY_IMPLICIT
//#include <dune/ax1/acme0/fully-implicit/acme0_Pk_fully_implicit.hh>
//#else
#include <dune/ax1/acme0/common/acme0_setup.hh>
//#endif

#include <dune/ax1/channels/channel_builder.hh>

template<typename Config, typename GV>
void run(Acme0Parameters& params, Config& config, GV& gv, std::vector<double>& coords, double dtstart, double tend)
{
  debug_verb << "Configuration '" << config.getConfigName() << "' loaded." << std::endl;

  typedef typename Acme0Factory<GV,double,Config>::PHYSICS PHYSICS;
  PHYSICS physics = Acme0Factory<GV,double,Config>::setup(config, gv, params, coords, dtstart);
  //std::cout << Tools::getTypeName(physics) << std::endl;

  // Check parameters used
  debug_verb << "==============================================" << std::endl;
  debug_verb << "LENGTH_SCALE = " << physics.getLengthScale() << std::endl;
  debug_verb << "TIME_SCALE   = " << physics.getTimeScale() << std::endl;
  for(int i=0; i<NUMBER_OF_SPECIES; ++i)
  {
    debug_verb << "con_diffWater" << ION_NAMES[i] << " = " << physics.getElectrolyte().getDiffConst(i) << std::endl;
  }
  debug_verb << "electrolyte temperature: " << physics.getElectrolyte().getTemperature() << std::endl;
  debug_verb << "electrolyte stdCon: " << physics.getElectrolyte().getStdCon() << std::endl;
  debug_verb << "poissonConstant: " << physics.getPoissonConstant() << std::endl;
  debug_verb << "==============================================" << std::endl;

#ifdef ACME0_FULLY_IMPLICIT
  //############# fully-implicit ######################
  //Acme0PkFullyImplicit<GV,PHYSICS> acme0PkFullyImplicit(gv, physics);
  //acme0PkFullyImplicit.acme0_Pk(dtstart, tend);
  Acme0Setup<GV,PHYSICS> acme0SetupFullyImplicit(gv, physics, false);
  acme0SetupFullyImplicit.setup(dtstart, tend);
  //###################################################
#else
  //############# operator-split ######################
  Acme0Setup<GV,PHYSICS> acme0SetupOperatorSplit(gv, physics, true);
  acme0SetupOperatorSplit.setup(dtstart, tend);
  //###################################################
#endif
}

//===============================================================
// Main program with grid setup
//===============================================================
int main(int argc, char** argv)
{
  try{
    //Maybe initialize Mpi
    Dune::MPIHelper& helper = Dune::MPIHelper::instance(argc, argv);
    if(Dune::MPIHelper::isFake)
      std::cout<< "This is a sequential program." << std::endl;
    else
	  {
      if(helper.rank()==0)
        std::cout << "parallel run on " << helper.size() << " process(es)" << std::endl;
	  }

    if (argc<4)
	  {
      if(helper.rank()==0)
        std::cout << "usage: ./acme0 <level> <dtstart> <tend> [config-file]" << std::endl;
      return 1;
	  }

    int level;
    sscanf(argv[1],"%d",&level);

    double dtstart;
    sscanf(argv[2],"%lg",&dtstart);

    double tend;
    sscanf(argv[3],"%lg",&tend);

    std::string configFileName;
    if (argc>=5)
    {
      configFileName = argv[4];
    } else {
      configFileName = "acme0.config";
    }
    debug_verb << "Using config file " << configFileName << std::endl;

    // sequential version
    if (1 && helper.size()==1)
    {

      // Read config file
      Acme0Parameters params;
      Dune::ParameterTreeParser::readINITree(configFileName, params, true);
      params.init();

      /*
      if(params.useLogScaling())
      {
        debug_info << "=== USING LOGARITHMIC SCALING! ====================" << std::endl;
      }

      Membrane<double>::ChannelSet channelSet = ChannelBuilder<double>::buildChannelSet(params);

      // electrolyte definition ###########################
      Ion<double>    sodium(  1.0, "na" );
      Ion<double> potassium(  1.0, "k"  );
      Ion<double>  chloride( -1.0, "cl" );

      Solvent<double> water( 80.0 );
      //Solvent<double> water( 1.0 ); // test hack
      Electrolyte<double> electro(water, 279.45, con_mol); // concentrations now given in "1 mM"
      //Electrolyte<double> electro(water, 1.0, 1.0); // test hack

      electro.addIon(sodium);
      if(NUMBER_OF_SPECIES > 1) electro.addIon(potassium);
      if(NUMBER_OF_SPECIES > 2) electro.addIon(chloride);

      Membrane<double> memb(2.0, channelSet);
      */

      // ############## grid generation ##################
      // Seed 1d grid coordinates
      double d = params.dMemb();
      std::vector<double> coords = { 0.5*d, params.xMax() };

      Tools::globalRefineVector( coords, level, params.refineMembrane() );
      //Tools::globalRefineVectorLogarithmic( coords, level );
      Output::printVector(coords);

      // mirror grid
      for (int i=coords.size()-1; i>=0; i--)
      {
        // Do not mirror coordinate x=0
        if(not std::abs(coords[i] < 1e-12))
        {
          coords.push_back( -coords[i] );
        }
      }
      sort(coords.begin(), coords.end());
      Output::printVector(coords);

      Dune::OneDGrid grid(coords);

      //typedef Dune::YaspGrid<dim>::LeafGridView GV;
      typedef Dune::OneDGrid::LeafGridView GV;
      // ############## END grid generation ###############

      const GV& gv=grid.leafView();

      /*
      //typedef GV::Codim<0>::EntityPointer ElementPointer;
      typedef GV::Codim<0>::Iterator ElementIterator;
      typedef Dune::SingleCodimSingleGeomTypeMapper<GV, 0> ElementMapper;

      // Dune mapper to map an entity to its index
      ElementMapper elementMapper(gv);

      // physics instantiation ###############################################
      typedef Physics<GV,ElementMapper,double> PHYSICS;
      PHYSICS physics(gv,elementMapper,electro,memb,params);
      physics.initPosition(coords);
      physics.setTimeStep(dtstart);
      //######################################################################

      // Custom mapper to map element indices to subdomain indices
      ElementSubdomainMapper elemSubdomainMapper;

      // Channelset containing all ion channels
      Membrane<double>::ChannelSet& channels = physics.getMembrane().getChannelSet();

      std::cout << "Initializing mappers" << std::endl;
      // Initialize Element->Group mapper and Element->MembraneElement mapper
      for(ElementIterator ep = gv.begin<0>(); ep != gv.end<0>(); ++ep)
      {
        int elemIndex = elementMapper.map(*ep);
        int subdomainIndex = 0;

        double center = ep->geometry().center();

        if(params.useMembrane() and std::abs(center) < 0.5*d)
        {
          subdomainIndex = 2;
          // Add this membrane element to channel set [M->ME]
          channels.addMembraneElement(elemIndex);
        }
        // Store subdomain of this element [M->G]
        elemSubdomainMapper.setGroup(elemIndex, subdomainIndex);

      }
      physics.setElementSubdomainMapper(elemSubdomainMapper);
      channels.resize();

      std::cout << "Channels.init()" << std::endl;
      channels.init(physics);
      physics.info();
      channels.info();
      */

      bool configFound = false;
      std::string configName = params.getConfigName();
      if(configName == "default")
      {
        DefaultConfiguration<double> config;
        run(params,config,gv,coords,dtstart,tend);
        configFound = true;
      }
      if(configName == "hamburger")
      {
        HamburgerConfiguration<double> config;
        run(params,config,gv,coords,dtstart,tend);
        configFound = true;
      }

      if(! configFound)
      {
        DUNE_THROW(Dune::Exception, "No configuration named '" << configName << "' could be found!");
      }
    }
  } catch (Dune::Exception &e){
    std::cerr << "Dune reported error: " << e << std::endl;
    return 0;
  }
}


text:
angular.module('app')
    .controller('myFamilyCtrl', ['$scope', '$timeout', '$location', 'ajax', function ($scope,$location, $timeout, ajax){
        $scope.my_family_list = [];
        $scope.clinical_history = [];
        $scope.clinical_history_arr = [];

        /**
         * 初始化家族信息
         */
        ajax.req('POST', 'user/get_all_family_info')
            .then(function (data) {
                if(data.success){
                    angular.forEach(data.data, function (family_list, index, family_array) {
                        if(family_list.relation == '10'){
                            family_list.relation = '父亲'
                        }else if(family_list.relation == '20'){
                            family_list.relation = '母亲'
                        };
                        /*if(family_list.health_status == '10'){
                            family_list.health_status = '健康';
                        }else if(family_list.health_status == '20'){
                            family_list.health_status = '亚健康';
                        }else if(family_list.health_status == '30'){
                            family_list.health_status = '疾病';
                        }*/
                        $scope.clinical_history = family_list.clinical_history.split('-');
                        $scope.clinical_history_arr = [];
                        data.data[index].clinical_history_arr = [];
                        angular.forEach($scope.clinical_history, function (clinical_history_list, index, clinical_history_array) {

                            if(clinical_history_list == '10'){
                                clinical_history_array = '手术'
                            }else if(clinical_history_list == '20'){
                                clinical_history_array = '化疗'
                            }else if(clinical_history_list == '30'){
                                clinical_history_array = '放疗'
                            }else if(clinical_history_list == '40'){
                                clinical_history_array = '靶向药物治疗'
                            }
                            $scope.clinical_history_arr.push(clinical_history_array);
                        });
                        family_array[index].clinical_history_arr = $scope.clinical_history_arr;
                        $scope.my_family_list = data.data;
                    });
                }
            });

        /**
         * 查看家族个人信息
         */
        $scope.family_info = function (family_id) {
            window.location.href = SITE_URL + 'weixin/user/family_info/'+ family_id;
        };

        /**
         * 添加家属
         */

        $scope.add_family_member = function () {
            window.location.href = SITE_URL + 'weixin/user/family_info';
        }
    }])


text:
"""Support for HomematicIP Cloud devices."""
import logging

import voluptuous as vol

from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, EVENT_HOMEASSISTANT_STOP
from homeassistant.helpers import device_registry as dr
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType, HomeAssistantType

from .const import (
    CONF_ACCESSPOINT,
    CONF_AUTHTOKEN,
    DOMAIN,
    HMIPC_AUTHTOKEN,
    HMIPC_HAPID,
    HMIPC_NAME,
)
from .generic_entity import HomematicipGenericEntity  # noqa: F401
from .hap import HomematicipAuth, HomematicipHAP  # noqa: F401
from .services import async_setup_services, async_unload_services

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    {
        vol.Optional(DOMAIN, default=[]): vol.All(
            cv.ensure_list,
            [
                vol.Schema(
                    {
                        vol.Optional(CONF_NAME, default=""): vol.Any(cv.string),
                        vol.Required(CONF_ACCESSPOINT): cv.string,
                        vol.Required(CONF_AUTHTOKEN): cv.string,
                    }
                )
            ],
        )
    },
    extra=vol.ALLOW_EXTRA,
)

async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Set up the HomematicIP Cloud component."""
    hass.data[DOMAIN] = {}

    accesspoints = config.get(DOMAIN, [])

    for conf in accesspoints:
        if conf[CONF_ACCESSPOINT] not in {
            entry.data[HMIPC_HAPID]
            for entry in hass.config_entries.async_entries(DOMAIN)
        }:
            hass.async_add_job(
                hass.config_entries.flow.async_init(
                    DOMAIN,
                    context={"source": config_entries.SOURCE_IMPORT},
                    data={
                        HMIPC_HAPID: conf[CONF_ACCESSPOINT],
                        HMIPC_AUTHTOKEN: conf[CONF_AUTHTOKEN],
                        HMIPC_NAME: conf[CONF_NAME],
                    },
                )
            )

    return True

async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
    """Set up an access point from a config entry."""

    # 0.104 introduced config entry unique id, this makes upgrading possible
    if entry.unique_id is None:
        new_data = dict(entry.data)

        hass.config_entries.async_update_entry(
            entry, unique_id=new_data[HMIPC_HAPID], data=new_data
        )

    hap = HomematicipHAP(hass, entry)
    hass.data[DOMAIN][entry.unique_id] = hap

    if not await hap.async_setup():
        return False

    await async_setup_services(hass)

    # Register on HA stop event to gracefully shutdown HomematicIP Cloud connection
    hap.reset_connection_listener = hass.bus.async_listen_once(
        EVENT_HOMEASSISTANT_STOP, hap.shutdown
    )

    # Register hap as device in registry.
    device_registry = await dr.async_get_registry(hass)
    home = hap.home
    # Add the HAP name from configuration if set.
    hapname = home.label if not home.name else f"{home.name} {home.label}"
    device_registry.async_get_or_create(
        config_entry_id=home.id,
        identifiers={(DOMAIN, home.id)},
        manufacturer="eQ-3",
        name=hapname,
        model=home.modelType,
        sw_version=home.currentAPVersion,
    )
    return True

async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    hap = hass.data[DOMAIN].pop(entry.unique_id)
    hap.reset_connection_listener()

    await async_unload_services(hass)

    return await hap.async_reset()


text:
import logging
import os
import re
import subprocess

from le_utils.constants import format_presets

from .images import ThumbnailGenerationError

LOGGER = logging.getLogger("VideoResource")
LOGGER.setLevel(logging.DEBUG)

def guess_video_preset_by_resolution(videopath):
    """
    Run `ffprobe` to find resolution classify as high resolution (video height >= 720),
    or low resolution (video height < 720).
    Return appropriate video format preset: VIDEO_HIGH_RES or VIDEO_LOW_RES.
    """
    try:
        LOGGER.debug("Entering 'guess_video_preset_by_resolution' method")
        result = subprocess.check_output(
            [
                "ffprobe",
                "-v",
                "error",
                "-print_format",
                "json",
                "-show_entries",
                "stream=width,height",
                "-of",
                "default=noprint_wrappers=1",
                str(videopath),
            ]
        )
        LOGGER.debug("ffprobe stream result = {}".format(result))
        pattern = re.compile("width=([0-9]*)[^height]+height=([0-9]*)")
        match = pattern.search(str(result))
        if match is None:
            return format_presets.VIDEO_LOW_RES
        _, height = int(match.group(1)), int(match.group(2))
        if height >= 720:
            LOGGER.info("Video preset from {} = high resolution".format(videopath))
            return format_presets.VIDEO_HIGH_RES
        else:
            LOGGER.info("Video preset from {} = low resolution".format(videopath))
            return format_presets.VIDEO_LOW_RES
    except Exception as e:
        LOGGER.warning(e)
        return format_presets.VIDEO_LOW_RES

def extract_thumbnail_from_video(fpath_in, fpath_out, overwrite=False):
    """
    Extract a thumbnail from the video given through the `fobj_in` file object.
    The thumbnail image will be written in the file object given in `fobj_out`.
    """
    try:
        result = subprocess.check_output(
            [
                "ffprobe",
                "-v",
                "error",
                "-show_entries",
                "format=duration",
                "-of",
                "default=noprint_wrappers=1:nokey=1",
                "-loglevel",
                "panic",
                str(fpath_in),
            ]
        )

        midpoint = float(re.search("\\d+\\.\\d+", str(result)).group()) / 2
        # scale parameters are from https://trac.ffmpeg.org/wiki/Scaling
        scale = "scale=400:225:force_original_aspect_ratio=decrease,pad=400:225:(ow-iw)/2:(oh-ih)/2"
        command = [
            "ffmpeg",
            "-y" if overwrite else "-n",
            "-i",
            str(fpath_in),
            "-vf",
            scale,
            "-vcodec",
            "png",
            "-nostats",
            "-ss",
            str(midpoint),
            "-vframes",
            "1",
            "-q:v",
            "2",
            "-loglevel",
            "panic",
            str(fpath_out),
        ]
        subprocess.check_output(command, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        raise ThumbnailGenerationError("{}: {}".format(e, e.output))
    except AttributeError:
        raise ThumbnailGenerationError(
            "No suitable frame for thumbnail generation was found"
        )

def _get_stream_duration(fpath_in, extension):
    result = subprocess.run(
        [
            "ffmpeg",
            "-i",
            "pipe:",
            "-f",
            "null",
            str(fpath_in),
        ],
        stderr=subprocess.PIPE,
    )
    second_last_line = result.stderr.decode("utf-8").strip().splitlines()[-2]
    time_code = second_last_line.split(" time=")[1].split(" ")[0]
    hours, minutes, seconds = time_code.split(":")
    try:
        hours = int(hours)
    except ValueError:
        hours = 0
    try:
        minutes = int(minutes)
    except ValueError:
        minutes = 0
    try:
        seconds = int(float(seconds))
    except ValueError:
        seconds = 0
    return (hours * 60 + minutes) * 60 + seconds

def extract_duration_of_media(fpath_in, extension):
    """
    For more details on these commands, refer to the ffmpeg Wiki:
    https://trac.ffmpeg.org/wiki/FFprobeTips#Formatcontainerduration
    """
    try:
        if os.path.exists(fpath_in):
            result = subprocess.check_output(
                [
                    "ffprobe",
                    "-v",
                    "error",
                    "-show_entries",
                    "format=duration",
                    "-of",
                    "default=noprint_wrappers=1:nokey=1",
                    "-loglevel",
                    "panic",
                    "-f",
                    extension,
                    str(fpath_in),
                ],
            )
            result = result.decode("utf-8").strip()
            try:
                return int(float(result))
            except ValueError:
                # This can happen if ffprobe returns N/A for the duration
                # So instead we try to stream the entire file to get the value
                return _get_stream_duration(fpath_in, extension)
    except Exception as ex:
        LOGGER.warning(ex)
        raise ex

class VideoCompressionError(Exception):
    """
    Custom error returned when `ffmpeg` compression exits with a non-zero status.
    """

def compress_video(source_file_path, target_file, overwrite=False, **kwargs):
    """
    Compress and scale video at `source_file_path` using setting provided in `kwargs`:
      - max_height (int): set a limit for maximum vertical resolution (default: 480)
      - max_width (int): set a limit for maximum horizontal resolution for video
      - crf (int): set compression constant rate factor (default 32 = compress a lot)
    Save compressed output video to `target_file`.
    """
    # scaling
    # The output width and height for ffmpeg scale param must be divisible by 2
    # using value -2 to get robust behaviour: maintains the aspect ratio and also
    # ensure the calculated dimension is divisible by 2
    if "max_width" in kwargs:
        scale = "'w=trunc(min(iw,{max_width})/2)*2:h=-2'".format(
            max_width=kwargs["max_width"]
        )
    elif "max_height" in kwargs:
        scale = "'w=-2:h=trunc(min(ih,{max_height})/2)*2'".format(
            max_height=kwargs["max_height"]
        )
    else:
        scale = "'w=-2:h=trunc(min(ih,480)/2)*2'"  # default to max-height 480px

    # set constant rate factor, see https://trac.ffmpeg.org/wiki/Encode/H.264#crf
    crf = kwargs["crf"] if "crf" in kwargs else 32

    # run command
    command = [
        "ffmpeg",
        "-y" if overwrite else "-n",
        "-i",
        source_file_path,
        "-profile:v",
        "baseline",
        "-level",
        "3.0",
        "-b:a",
        "32k",
        "-ac",
        "1",
        "-vf",
        "scale={}".format(scale),
        "-crf",
        str(crf),
        "-preset",
        "slow",
        "-v",
        "error",
        "-strict",
        "-2",
        "-stats",
        "-movflags",
        "faststart",
        target_file,
    ]
    try:
        subprocess.check_output(command, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        raise VideoCompressionError("{}: {}".format(e, e.output))

def web_faststart_video(source_file_path, target_file, overwrite=False):
    """
    Add faststart flag to an mp4 file
    """
    # run command
    command = [
        "ffmpeg",
        "-y" if overwrite else "-n",
        "-i",
        source_file_path,
        "-c",
        "copy",
        "-v",
        "error",
        "-strict",
        "-2",
        "-stats",
        "-movflags",
        "faststart",
        target_file,
    ]
    try:
        subprocess.check_output(command, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        raise VideoCompressionError("{}: {}".format(e, e.output))


text:
<?php
/**
 * Creating new user in database
 *
 * @access Command Line
 * @example sudo php create_new_user.php --username=johnsmith --password=secret@123
 */

chdir('../../');
// include auto class loader
require_once 'includes/AutoLoader.php';

if (Utils::isRunningFromCLI()) {
    $cmdArgs = $argv;
    $userName = $password = '';
    foreach ($cmdArgs as $arg) {
        if (preg_match('/--username=(\w+)/', $arg, $result)) {
            $userName = $result[1];
        }

        if (preg_match('/--password=(\w+)/', $arg, $result)) {
            $password = $result[1];
        }
    }

    // input validations
    if (empty($userName)) {
        Utils::printCLIMessages('No UserName provided, Retry!');
        exit;
    }
    if (empty($password)) {
        Utils::printCLIMessages('No Password provided, Retry!');
        exit;
    }
    if (strlen($password) < 3) {
        Utils::printCLIMessages('Password too short, Must have atleast 3 characters');
        exit;
    }
    $user = new UsersController();
    $response = json_decode($user->createUser($userName, $password), true);
    Utils::printCLIMessages(ucfirst($response['code']).'!! '.$response['msg']);
} else {
    Utils::printCLIMessages('Invalid Access! File is meant to be run from only command line.');
}

exit();


text:
import axios from 'axios';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import MockAdapter from 'axios-mock-adapter';
import * as actions from '../LocationActions';
import * as LocationGenerators from '../LocationGenerators';

describe('LocationGenerators Test', () => {

  let mock;
  const CALL_ROUTE = `${process.env.API_URL}locations/`;
  const createMockStore = configureMockStore([promise, thunk]);
  const store = createMockStore({
    userData: {
      user: {
        token: 'token'
      }
    }
  });

  beforeEach(() => {
    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    mock.restore();
    store.clearActions();
  });

  test('should getStates correctly', () => {
    const url = `${process.env.API_URL}lookup-data?states`;
    const options = {
      headers: {
        Authorization: 'token'
      }
    };
    const states = ['IN', 'OH', 'IL'];

    mock.onGet(url, options).reply(200, states);

    const expectedActions = [
      actions.getStatesSuccess(states)
    ];

    return store.dispatch(LocationGenerators.getStates())
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

  test('should getLocations successfully', () => {
    const mockResponse = { locations: 'fake locations' };
    const mockUrl = CALL_ROUTE;

    mock.onGet(mockUrl).reply(200, mockResponse);

    const expectedActions = [
      actions.getLocationsStart(),
      actions.getLocationsSuccess(mockResponse.locations)
    ];

    return store.dispatch(LocationGenerators.getLocations()).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });

  test('should getLocation with id param', () => {
    const locationId = 12;
    const mockResponse = 'fake location';
    const mockUrl = `${CALL_ROUTE}${locationId}`;

    mock.onGet(mockUrl).reply(200, {location: mockResponse });

    const expectedActions = [
      actions.getLocationStart(),
      actions.getLocationSuccess(mockResponse)
    ];

    return store.dispatch(LocationGenerators.getLocation(locationId)).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });

  test('should addNewLocation', () => {
    const mockLocation = { id: '123', name: 'testing' };
    const mockUrl = CALL_ROUTE;
    const history = [];

    mock.onPost(mockUrl, mockLocation).reply(201, actions.addLocationSuccess());

    const expectedActions = [
      actions.addLocationStart(),
      actions.addLocationSuccess()
    ];

    return store.dispatch(LocationGenerators.addNewLocation(mockLocation, history))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

  test('should updateLocation successfully', () => {
    const mockData = { location: { id: '123', name: 'testing' }, locationId: '123'};
    const mockUrl = CALL_ROUTE + mockData.locationId;
    const history = [];

    mock.onPut(mockUrl, mockData.location).reply(200, actions.updateLocationSuccess());

    const expectedActions = [
      actions.updateLocationStart(),
      actions.updateLocationSuccess()
    ];

    return store.dispatch(LocationGenerators.updateLocation(mockData, history))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

  test('should deleteLocation successfully', () => {
    const mockData = { location: { id: '123', name: 'testing' }, locationId: '123' };
    const mockUrl = CALL_ROUTE + mockData.locationId;

    mock.onDelete(mockUrl, mockData.locationId).reply(200, actions.deleteLocationSuccess(mockData.locationId));

    const expectedActions = [
      actions.deleteLocationStart(),
      actions.deleteLocationSuccess(mockData.locationId)
    ];

    return store.dispatch(LocationGenerators.deleteLocation(mockData.locationId))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

  test('should return error when calling getLocations', () => {
    const error = Error('Something went wrong');
    const mockUrl = CALL_ROUTE;

    const expectedActions = [
      actions.getLocationsStart(),
      actions.getLocationsError(error)
    ];

    mock.onGet(mockUrl).reply(404, error);
    return store.dispatch(LocationGenerators.getLocations()).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });

  });

  test('should return error message getLocation with id param', () => {
    const locationId = 123;
    const error = Error('Request failed with status code 404');
    const mockUrl = CALL_ROUTE;

    const expectedActions = [
      actions.getLocationStart(),
      actions.getLocationError(error)
    ];

    mock.onGet(mockUrl).reply(404);
    return store.dispatch(LocationGenerators.getLocation(locationId)).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });

  });

  test('should return error message addNewLocation', () => {
    const history = [];
    const error = Error('Request failed with status code 404');
    const mockUrl = CALL_ROUTE;
    const location = {
      id: '321',
      name: 'Unknown'
    };

    const expectedActions = [
      actions.addLocationStart(),
      actions.addLocationError(error)
    ];

    mock.onGet(mockUrl).reply(404);
    return store.dispatch(LocationGenerators.addNewLocation(location, history)).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });

  });

  test('should return error when calling updateLocation', () => {
    const mockData = { location: { id: '123', name: 'testing' }, locationId: '123' };
    const mockUrl = CALL_ROUTE + '222';
    const history = [];
    const err = Error('Request failed with status code 404');

    mock.onPut(mockUrl, mockData.location).reply(404, actions.updateLocationError(err));

    const expectedActions = [
      actions.updateLocationStart(),
      actions.updateLocationError(err)
    ];

    return store.dispatch(LocationGenerators.updateLocation(mockData, history))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

  test('should return error when calling deleteLocation', () => {
    const mockData = { location: { id: '123', name: 'testing' }, locationId: '123' };
    const mockUrl = CALL_ROUTE + mockData.locationId;
    const err = Error('Request failed with status code 404');

    mock.onDelete(mockUrl, mockData.locationId).reply(404);

    const expectedActions = [
      actions.deleteLocationStart(),
      actions.deleteLocationError(err)
    ];

    return store.dispatch(LocationGenerators.deleteLocation(mockData.locationId))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

  test('should return error when calling getStates', () => {
    const url = `${process.env.API_URL}lookup-data?states`;

    mock.onGet(url).timeout();

    const expectedActions = [];

    return store.dispatch(LocationGenerators.getStates())
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
  });

});


text:
<?php
/**
 * Elgg Search css
 *
 */
?>

/**********************************
Search plugin
***********************************/
.elgg-search-header {
	bottom: 5px;
	height: 23px;
	position: absolute;
	right: 0;
}
.elgg-search input[type=text] {
	width: 230px;
}
.elgg-search input[type=submit] {
	display: none;
}
.elgg-search input[type=text] {
	border-radius: 10px;
	border: 1px solid #71b9f7;
	color: white;
	font-size: 12px;
	font-weight: bold;
	padding: 2px 4px 2px 26px;
	background: transparent url(<?php echo elgg_get_site_url(); ?>_graphics/elgg_sprites.png) no-repeat 2px -934px;
}
.elgg-search input[type=text]:focus, .elgg-search input[type=text]:active {
	background-color: white;
	background-position: 2px -916px;
	border: 1px solid white;
	color: #0054A7;
}

.search-list li {
	padding: 5px 0 0;
}
.search-heading-category {
	margin-top: 20px;
	color: #666666;
}

.search-highlight {
	background-color: #bbdaf7;
}
.search-highlight-color1 {
	background-color: #bbdaf7;
}
.search-highlight-color2 {
	background-color: #A0FFFF;
}
.search-highlight-color3 {
	background-color: #FDFFC3;
}
.search-highlight-color4 {
	background-color: #ccc;
}
.search-highlight-color5 {
	background-color: #4690d6;
}


text:
module RubyFish::Levenshtein

  include ::RubyFish::DamerauLevenshtein
  extend ::RubyFish::DamerauLevenshtein

  def distance a, b, opts={}
    _distance(a, b, :allowswaps => false, :ignore_case => opts[:ignore_case])
  end

  module_function :distance

end


text:
#ifndef _M68K_IRQ_H_
#define _M68K_IRQ_H_

extern void disable_irq(unsigned int);
extern void enable_irq(unsigned int);

#include <linux/config.h>

/*
 * This should be the same as the max(NUM_X_SOURCES) for all the
 * different m68k hosts compiled into the kernel.
 * Currently the Atari has 72 and the Amiga 24, but if both are
 * supported in the kernel it is better to make room for 72.
 */
#if defined(CONFIG_ATARI)
#define NR_IRQS 72
#else
#define NR_IRQS 24
#endif

/*
 * Interrupt source definitions
 * General interrupt sources are the level 1-7.
 * Adding an interrupt service routine for one of these sources
 * results in the addition of that routine to a chain of routines.
 * Each one is called in succession.  Each individual interrupt
 * service routine should determine if the device associated with
 * that routine requires service.
 */

#define IRQ1		 (1)    /* level 1 interrupt */
#define IRQ2		 (2)    /* level 2 interrupt */
#define IRQ3		 (3)    /* level 3 interrupt */
#define IRQ4		 (4)    /* level 4 interrupt */
#define IRQ5		 (5)    /* level 5 interrupt */
#define IRQ6		 (6)    /* level 6 interrupt */
#define IRQ7		 (7)    /* level 7 interrupt (non-maskable) */

/*
 * "Generic" interrupt sources
 */

#define IRQ_SCHED_TIMER  (8)    /* interrupt source for scheduling timer */

/*
 * Machine specific interrupt sources.
 *
 * Adding an interrupt service routine for a source with this bit
 * set indicates a special machine specific interrupt source.
 * The machine specific files define these sources.
 */

#define IRQ_MACHSPEC	 (0x10000000L)

#ifndef ISRFUNC_T
struct pt_regs;
typedef void (*isrfunc) (int irq, struct pt_regs * regs, void *data);
#define ISRFUNC_T
#endif /* ISRFUNC_T */

/*
 * This structure is used to chain together the ISRs for a particular
 * interrupt source (if it supports chaining).
 */
typedef struct isr_node {
    isrfunc	    isr;
    int 	    pri;
    void            *data;
    char	    *name;
    struct isr_node *next;
} isr_node_t;

/* count of spurious interrupts */
extern volatile unsigned long num_spurious;

/*
 * This function returns a new isr_node_t
 */
extern isr_node_t *new_isr_node(void);

/*
 * This function is used to add a specific interrupt service routine
 * for the specified interrupt source.
 *
 * If the source is machine specific, it will be passed along to the
 * machine specific routine.
 *
 * "data" is user specified data which will be passed to the isr routine.
 *
 * (isrfunc is defined in linux/config.h)
 */
extern int add_isr (unsigned long source, isrfunc isr, int pri, void
		    *data, char *name);

/*
 * This routine will remove an isr for the specified interrupt source.
 */
extern int remove_isr (unsigned long source, isrfunc isr, void *data);

/*
 * This routine will insert an isr_node_t into a chain of nodes, using
 * the priority stored in the node.
 */
extern void insert_isr (isr_node_t **listp, isr_node_t *node);

/*
 * This routine will delete the isr node for isr from a chain of nodes
 */
extern void delete_isr (isr_node_t **listp, isrfunc isr, void *data);

/*
 * This routine may be used to call the isr routines in the passed list.
 */
extern void call_isr_list (int irq, isr_node_t *p, struct pt_regs *fp);

#endif /* _M68K_IRQ_H_ */


text:
var controls = controls || {};
(function (scope) {
    var Form = (function () {
        function Form(title) {
            this._title = title;
        }

        return Form;
    }());

    scope.getForm = function (title) {
        return new Form();
    };
}(controls));


text:
/**
 *
 */

package code.dws.core.instanceMap;

import gnu.trove.map.hash.THashMap;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.tuple.Pair;

import code.dws.dto.GenericTreeNode;
import code.dws.utils.Constants;
import code.dws.utils.Utilities;

/**
 * @author Arnab Dutta
 */
public class AutomatedNodeScoringWrapper {

	private DBPediaTreeOperation dbTOp = null;

	/**
	 * @param property
	 * @throws IOException
	 */
	public void buildDomRan(String property) throws IOException {

		this.dbTOp = new DBPediaTreeOperation(Constants.DBPEDIA_TBOX);

		// run the learner to score the nodes
		// the class tree hierarchy is to be build just for top-1 candidate
		// matches
		this.dbTOp.buildDomRan(new String[] { property, "1" });
	}

	public void generateClassHierarchy(String identifier) throws IOException {
		this.dbTOp.generateClassHierarchy(identifier);
	}

	public GenericTreeNode getUNTYPEDNodeDetails() {
		return this.dbTOp.getUNTYPEDNODE();
	}

	/**
	 * @param set
	 * @param fullSetOfTpes
	 * @param domRangPrefWriter
	 * @param domRangEvidenceWriter
	 * @param range
	 * @throws IOException
	 */
	public void rankTypes(Set<String> set, Set<String> fullSetOfTpes,
			BufferedWriter domRangPrefWriter,
			BufferedWriter domRangEvidenceWriter, String identifier)
			throws IOException {

		DecimalFormat df = new DecimalFormat("0.00000000000");

		List<String> dbPediaTypes = new ArrayList<String>(set);

		// System.out.println("  ***************************************** *");
		// System.out.println(set);

		this.dbTOp.getUNTYPEDNODE();

		THashMap<String, Pair<Double, Double>> testMap = this.dbTOp
				.getNodeScore(dbPediaTypes, fullSetOfTpes);

		for (Map.Entry<String, Pair<Double, Double>> entry : testMap.entrySet()) {

			domRangPrefWriter.write(entry.getKey() + "\t("
					+ entry.getValue().getLeft() + ",\t"
					+ entry.getValue().getRight() + ")\n");

			if (identifier.equals(Constants.DOMAIN))
				domRangEvidenceWriter
						.write(df.format(Utilities
								.convertProbabilityToWeight(entry.getValue()
										.getRight()))
								+ " !isOfType(\""
								+ entry.getKey().replaceAll(
										Constants.ONTOLOGY_NAMESPACE,
										"DBP#ontology/")
								+ "\",ds) v !propAsstConf(P, ns, no, ccc) v "
								+ "!sameAsConf(ds, ns, f) v "
								+ "  sameAs(ds,ns) \n");

			if (identifier.equals(Constants.RANGE))
				domRangEvidenceWriter
						.write(df.format(Utilities
								.convertProbabilityToWeight(entry.getValue()
										.getRight()))
								+ " !isOfType(\""
								+ entry.getKey().replaceAll(
										Constants.ONTOLOGY_NAMESPACE,
										"DBP#ontology/")
								+ "\",do) v !propAsstConf(P, ns, no, ccc) v "
								+ "!sameAsConf(do, no, ff) v"
								+ " sameAs(do,no)  \n");

			domRangEvidenceWriter.flush();
			domRangPrefWriter.flush();
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		BufferedWriter domRangPrefWriter = new BufferedWriter(new FileWriter(
				Constants.DOMAIN_RANGE_PREFERENCE_FILE));
		BufferedWriter domRangEvidenceWriter = new BufferedWriter(
				new FileWriter(Constants.DOMAIN_RANGE_EVIDENCE_FILE));

		AutomatedNodeScoringWrapper nodeScorer = new AutomatedNodeScoringWrapper();

		nodeScorer.buildDomRan(args[0]);
		nodeScorer.generateClassHierarchy(Constants.DOMAIN);

		domRangPrefWriter
				.write("\n======  DOMAIN PREFERENCE ================================\n");
		nodeScorer.rankTypes(Constants.SUB_SET_TYPES, null, domRangPrefWriter,
				domRangEvidenceWriter, Constants.DOMAIN);
		nodeScorer.generateClassHierarchy(Constants.RANGE);

		domRangPrefWriter
				.write("======  RANGE PREFERENCE ================================\n");
		nodeScorer.rankTypes(Constants.OBJ_SET_TYPES, null, domRangPrefWriter,
				domRangEvidenceWriter, Constants.RANGE);

		domRangPrefWriter.close();
		domRangEvidenceWriter.close();

		// if(Constants.BOOTSTRAP)
		// BootStrapMethod.doBootStrapping(nodeScorer);
	}

}


text:
using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Movement))]
public class CharacterController : MonoBehaviour {
	public float horizontalInput;
	public float verticalInput;

	private Movement movement;

  	// Use this for initialization
  	void Start () {
		movement = gameObject.GetComponent<Movement>();
	}

	// Update is called once per frame
	void Update () {
		horizontalInput = Input.GetAxisRaw("Horizontal");
		verticalInput   = Input.GetAxisRaw("Vertical");

		if (horizontalInput != 0){
		  movement.Forward(horizontalInput);
		}
	}
}


text: define({widgetLabel:"Kliza\u010d za raspon histograma"});


text:
@ECHO OFF
SETLOCAL

set BUILD_VERSION=0.0.4-alpha3

IF NOT DEFINED DevEnvDir (
	IF DEFINED vs140comntools (
		CALL "%vs140comntools%\vsvars32.bat"
	)
)

nuget restore Source\RethinkDb.Driver.sln

msbuild Source\Builder\Builder.csproj
if %errorlevel% neq 0 exit /b %errorlevel%

ECHO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ECHO        RUNNING BAU BUILDER
ECHO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Source\Builder\bin\Debug\Builder.exe %1
if %errorlevel% neq 0 exit /b %errorlevel%


text:
module Playa
  class StartupView
    include Vedeu

    def show
      trigger(:_clear_)

      render do
        view 'progress' do
          line do
            stream do
              text  'Welcome to Playa.'
              align centre
              width use('progress').width
            end
          end
        end

        view 'playlist' do
          line ''
          line ''
          line 'Playa is a simple, interactive mp3 player for your terminal.'
        end

        view 'status' do
          line do
            stream do
              text  'Press `s` to begin.'
              align centre
              width use('progress').width
            end
          end
        end
      end
    end

  end
end


text:
<!DOCTYPE HTML>

<title>NVFence (LWJGL 3.1.0 - OpenGL ES)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2016-10-30">
<link rel="stylesheet" type="text/css" href="../../../javadoc.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Deprecated

Index

Prev Class

Next Class

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package org.lwjgl.opengles

Class NVFence

java.lang.Object

org.lwjgl.opengles.NVFence

public class NVFence
extends java.lang.Object

Native bindings to the NV_fence extension.

The goal of this extension is provide a finer granularity of synchronizing GL command completion than offered by standard OpenGL, which offers only two
 mechanisms for synchronization: Flush and Finish. Since Flush merely assures the user that the commands complete in a finite (though undetermined)
 amount of time, it is, thus, of only modest utility. Finish, on the other hand, stalls CPU execution until all pending GL commands have completed. This
 extension offers a middle ground - the ability to "finish" a subset of the command stream, and the ability to determine whether a given command has
 completed or not.

This extension introduces the concept of a "fence" to the OpenGL command stream. Once the fence is inserted into the command stream, it can be queried
 for a given condition - typically, its completion. Moreover, the application may also request a partial Finish -- that is, all commands prior to the
 fence will be forced to complete until control is returned to the calling process. These new mechanisms allow for synchronization between the host CPU
 and the GPU, which may be accessing the same resources (typically memory).

This extension is useful in conjunction with NV_vertex_array_range to determine when vertex information has been pulled from the vertex array range.
 Once a fence has been tested TRUE or finished, all vertex indices issued before the fence must have been pulled. This ensures that the vertex data
 memory corresponding to the issued vertex indices can be safely modified (assuming no other outstanding vertex indices are issued subsequent to the
 fence).

Field Summary

Fields

Modifier and Type
Field and Description

static int
GL_ALL_COMPLETED_NV

Accepted by the condition parameter of SetFenceNV.

static int
GL_FENCE_CONDITION_NV

GL_FENCE_STATUS_NV

Accepted by the pname parameter of GetFenceivNV.

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
glDeleteFencesNV(int fence)

static void
glDeleteFencesNV(int[] fences)

Array version of: DeleteFencesNV

static void
glDeleteFencesNV(java.nio.IntBuffer fences)

static void
glFinishFenceNV(int fence)

static int
glGenFencesNV()

static void
glGenFencesNV(int[] fences)

Array version of: GenFencesNV

static void
glGenFencesNV(java.nio.IntBuffer fences)

static int
glGetFenceiNV(int fence,
             int pname)

static void
glGetFenceivNV(int fence,
              int pname,
              int[] params)

Array version of: GetFenceivNV

static void
glGetFenceivNV(int fence,
              int pname,
              java.nio.IntBuffer params)

static boolean
glIsFenceNV(int fence)

static void
glSetFenceNV(int fence,
            int condition)

static boolean
glTestFenceNV(int fence)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

GL_ALL_COMPLETED_NV

Accepted by the condition parameter of SetFenceNV.

GL_FENCE_STATUS_NV, GL_FENCE_CONDITION_NV

Accepted by the pname parameter of GetFenceivNV.

Method Detail

glDeleteFencesNV

public static void glDeleteFencesNV(java.nio.IntBuffer fences)

glDeleteFencesNV

public static void glDeleteFencesNV(int fence)

glGenFencesNV

public static void glGenFencesNV(java.nio.IntBuffer fences)

glGenFencesNV

public static int glGenFencesNV()

glIsFenceNV

public static boolean glIsFenceNV(int fence)

glTestFenceNV

public static boolean glTestFenceNV(int fence)

glGetFenceivNV

public static void glGetFenceivNV(int fence,
                                  int pname,
                                  java.nio.IntBuffer params)

glGetFenceiNV

public static int glGetFenceiNV(int fence,
                                int pname)

glFinishFenceNV

public static void glFinishFenceNV(int fence)

glSetFenceNV

public static void glSetFenceNV(int fence,
                                int condition)

glDeleteFencesNV

public static void glDeleteFencesNV(int[] fences)

Array version of: DeleteFencesNV

glGenFencesNV

public static void glGenFencesNV(int[] fences)

Array version of: GenFencesNV

glGetFenceivNV

public static void glGetFenceivNV(int fence,
                                  int pname,
                                  int[] params)

Array version of: GetFenceivNV

Skip navigation links

Package

Class

Deprecated

Index

Prev Class

Next Class

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright LWJGL. All Rights Reserved. License terms.


text:
<!DOCTYPE html>

    <title>Should access URI parameters</title>

    <link rel="stylesheet" href="../lib/qunit.css"/>