text:
std::pair<std::string, Parameters> matchedParameters[] = {
  std::pair<std::string, Parameters>("gamma",       p_gamma),
  std::pair<std::string, Parameters>("coef",        p_coef0),
  std::pair<std::string, Parameters>("degree",      p_degree),
  std::pair<std::string, Parameters>("rho",         p_rho),
  std::pair<std::string, Parameters>("kernel_type", p_kernel_type),
  std::pair<std::string, Parameters>("svm_type",    p_svm_type),
  std::pair<std::string, Parameters>("nr_class",    p_nr_class),
  std::pair<std::string, Parameters>("total_sv",    p_total_sv),
  std::pair<std::string, Parameters>("label",       p_label),
  std::pair<std::string, Parameters>("nr_sv",       p_nr_sv),
  std::pair<std::string, Parameters>("SV",          p_SV)
};

// Map to associate the strings with the enum values
std::map<std::string, Parameters>
mapStringToParameters(matchedParameters,
                      matchedParameters +
                      sizeof(matchedParameters)/sizeof(matchedParameters[0]));

float readFloat(FILE* input) {
  char currentCharacter;
  char floatBuffer[50];
  char* bufferPointer = floatBuffer;
  do {
    currentCharacter = fgetc(input);
    *(bufferPointer) = currentCharacter;
    bufferPointer++;
  } while ((currentCharacter >= '0' && currentCharacter <= '9') ||
	   (currentCharacter == '.') || (currentCharacter == '-') ||
	   (currentCharacter == 'e') || (currentCharacter == 'E'));
  bufferPointer--;
  *(bufferPointer) = 0;
  float result;
  sscanf(floatBuffer, "%f", &result);
	ungetc(currentCharacter, input);
  return result;
}

int readModel(const char* filename, float** alpha, float** supportVectors, int* nSVOut, int* nDimOut, Kernel_params* kp, float* p_class1Label, float* p_class2Label) {

  FILE* input = fopen(filename, "r");
  if (input == 0) {
    printf("Model File not found\n");
    return 0;
  }
  std::string line_description;

  char currentLine[80];
	int parsingParameters = 1;
	while (parsingParameters > 0) {
		fgets(currentLine, 80, input);
		line_description.clear();
		int j = 0;
		while(isalpha(currentLine[j]) || currentLine[j]=='_')
		{
			line_description.push_back(currentLine[j]);
			j++;
		}

		int foundParameter = 0;
		switch (mapStringToParameters[line_description]) {
			case p_gamma:
				//printf("Reading gamma - %s\n",line_description.c_str() );
				sscanf(&currentLine[line_description.length()+1], "%f", &(kp->gamma));
				foundParameter = 1;
				printf("Found gamma = %f\n",kp->gamma);
				break;
			case p_total_sv:
				sscanf(&currentLine[line_description.length()+1], "%d", nSVOut);
				foundParameter = 1;
				break;
			case p_rho:
				sscanf(&currentLine[line_description.length()+1], "%f", &(kp->b));
				kp->b = -kp->b;
				foundParameter = 1;
				break;
			case p_degree:
				sscanf(&currentLine[line_description.length()+1], "%d", &(kp->degree));
				foundParameter = 1;
				printf("Found degree = %d\n", kp->degree);
				break;
			case p_coef0:
				//printf("Reading coef0 - %s\n",line_description.c_str() );
				sscanf(&currentLine[line_description.length()+1], "%f", &(kp->coef0));
				foundParameter = 1;
				printf("Found coef0=%f\n",kp->coef0);
				break;
			case p_kernel_type:
				kp->kernel_type.insert(0,currentLine+line_description.length()+1);
				foundParameter = 1;
				break;
			case p_label:
        int intLabel1, intLabel2;
				sscanf(&currentLine[line_description.length()+1], "%d %d", &intLabel1, &intLabel2);
        *p_class1Label = (float)intLabel1;
        *p_class2Label = (float)intLabel2;
				foundParameter=1;
				break;
			case p_SV:
				parsingParameters = 0;
			default:
				foundParameter = 1;
				break;
		}
		if (foundParameter == 0) {
			printf("Malformed model: %s\n", currentLine);
			return 0;
		}
	}

  int nSV = *nSVOut;
  float* localAlpha = (float*)malloc(sizeof(float)*nSV);
  float* currentSV = (float*)malloc(sizeof(float)*65536);//Don't know dimension
  //guessing it will be less than 65536.  Otherwise, we'll fail
  //This should be rewritten

  localAlpha[0] = readFloat(input);
  int nDimension = 0;
  char currentCharacter = 0;
  while (currentCharacter != '\n') {
    currentCharacter = fgetc(input);
    if (currentCharacter == ':') {
      float currentCoordinate = readFloat(input);
      currentSV[nDimension] = currentCoordinate;
      nDimension++;
    }
  }
  float* localSV = (float*)malloc(sizeof(float)*nSV*nDimension);
	for(int dim = 0; dim < nDimension; dim++) {
		localSV[dim*nSV] = currentSV[dim];
	}
  free(currentSV);

  for(int sv = 1; sv < nSV; sv++) {
    localAlpha[sv] = readFloat(input);
    for(int dim = 0; dim < nDimension; dim++) {
      do {
				currentCharacter = fgetc(input);
			} while(currentCharacter != ':');
			localSV[nSV*dim + sv] = readFloat(input);
    }
		do {
			currentCharacter = fgetc(input);
		} while (((currentCharacter < '0') || (currentCharacter > '9')) && (currentCharacter != '.') && (currentCharacter != '-') && (currentCharacter != 'e') && (currentCharacter != 'E') && (currentCharacter >= 0));
		ungetc(currentCharacter, input);

  }

  *alpha = localAlpha;
  *supportVectors = localSV;
  *nSVOut = nSV;
  *nDimOut = nDimension;
  return 1;
}

int readSvm(const char* filename, float** p_data, float** p_labels, int* p_npoints, int* p_dimension, float** p_transposed_data) {
	FILE* inputFilePointer = fopen(filename, "r");
	if (inputFilePointer == 0) {
		printf("File not found\n");
		return 0;
	}
	int npoints = 0;
	int dimension = 0;
	char c;
	char firstLine = 1;
	do {
		c = fgetc(inputFilePointer);
		switch(c) {
		case '\n':
			npoints++;
			firstLine = 0;
			break;
		case ':':
			if (firstLine > 0) {
				dimension++;
			}
		default:
			;
		}

	} while (c != EOF);
	rewind(inputFilePointer);
	*(p_npoints) = npoints;
	*(p_dimension) = dimension;

	float* data = (float*)malloc(sizeof(float)*npoints*dimension);
	float* labels = (float*)malloc(sizeof(float)*npoints);
	*(p_data) = data;
	*(p_labels) = labels;
  float* transposed_data = NULL;
  if (p_transposed_data != NULL) {
    transposed_data = (float*)malloc(sizeof(float)*npoints*dimension);
    *(p_transposed_data) = transposed_data;
  }

	char* stringBuffer = (char*)malloc(65536);

	for(int i = 0; i < npoints; i++) {
		char* bufferPointer = stringBuffer;
		char validCharacter = 1;
		int currentDim = 0;
		int parsingLabel = 1;

		do {
			c = fgetc(inputFilePointer);
			if (validCharacter > 0) {
				if ((c == ' ') || (c == '\n')) {
					*(bufferPointer) = 0;
					float value;
					sscanf(stringBuffer, "%f", &value);
					if (parsingLabel > 0) {
						labels[i] = value;
						parsingLabel = 0;
					} else {
						data[currentDim*npoints + i] = value;
            if (p_transposed_data != NULL) {
              transposed_data[i*dimension + currentDim] = value;
            }
						currentDim++;
					}
					validCharacter = 0;
					bufferPointer = stringBuffer;
				} else {
					*(bufferPointer) = c;
					bufferPointer++;
				}
			}
			if (c == ':') {
				validCharacter = 1;
			}
		} while (c != '\n');
	}

	free(stringBuffer);
	fclose(inputFilePointer);
	return 1;
}

void printModel(const char* outputFile, Kernel_params kp, float* alpha, float* labels, float* data, int nPoints, int nDimension, float epsilon) {

	printf("Output File: %s\n", outputFile);
	FILE* outputFilePointer = fopen(outputFile, "w");
	if (outputFilePointer == NULL) {
		printf("Can't write %s\n", outputFile);
		exit(1);
	}

	int nSV = 0;
	int pSV = 0;
	for(int i = 0; i < nPoints; i++) {
		if (alpha[i] > epsilon) {
			if (labels[i] > 0) {
				pSV++;
			} else {
				nSV++;
			}
		}
	}

  bool printGamma = false;
  bool printCoef0 = false;
  bool printDegree = false;
  const char* kernelType = kp.kernel_type.c_str();
  if (strncmp(kernelType, "polynomial", 10) == 0) {
    printGamma = true;
    printCoef0 = true;
    printDegree = true;
  } else if (strncmp(kernelType, "rbf", 3) == 0) {
    printGamma = true;
  } else if (strncmp(kernelType, "sigmoid", 7) == 0) {
    printGamma = true;
    printCoef0 = true;
  }

	fprintf(outputFilePointer, "svm_type c_svc\n");
	fprintf(outputFilePointer, "kernel_type %s\n", kp.kernel_type.c_str());
  if (printDegree) {
    fprintf(outputFilePointer, "degree %i\n", kp.degree);
  }
  if (printGamma) {
    fprintf(outputFilePointer, "gamma %f\n", kp.gamma);
  }
  if (printCoef0) {
    fprintf(outputFilePointer, "coef0 %f\n", kp.coef0);
  }
	fprintf(outputFilePointer, "nr_class 2\n");
	fprintf(outputFilePointer, "total_sv %d\n", nSV + pSV);
	fprintf(outputFilePointer, "rho %.10f\n", kp.b);
	fprintf(outputFilePointer, "label 1 -1\n");
	fprintf(outputFilePointer, "nr_sv %d %d\n", pSV, nSV);
	fprintf(outputFilePointer, "SV\n");
	for (int i = 0; i < nPoints; i++) {
		if (alpha[i] > epsilon) {
			fprintf(outputFilePointer, "%.10f ", labels[i]*alpha[i]);
			for (int j = 0; j < nDimension; j++) {
				fprintf(outputFilePointer, "%d:%.10f ", j+1, data[j*nPoints + i]);
			}
			fprintf(outputFilePointer, "\n");
		}
	}
	fclose(outputFilePointer);
}

void printClassification(const char* outputFile, float* result, int nPoints) {
  FILE* outputFilePointer = fopen(outputFile, "w");
	if (outputFilePointer == NULL) {
		printf("Can't write %s\n", outputFile);
		exit(1);
	}
  for (int i = 0; i < nPoints; i++) {
    fprintf(outputFilePointer, "%f\n", result[i]);
  }
  fclose(outputFilePointer);
}


text:
package cz.geek.spayd;

import org.junit.Test;

import java.io.UnsupportedEncodingException;

import static cz.geek.spayd.SimpleValue.simpleValue;
import static org.junit.Assert.assertEquals;

public class SimpleValueTest {

	@Test
	public void testSpecialCharacterEscaping() throws UnsupportedEncodingException {
		String original = " abc  123\u2665\u2620**123  abc-+ěščřžýáíé---%20" ;
		assertEquals("abc  123%E2%99%A5%E2%98%A0%2A%2A123  abc-%2B%C4%9B%C5%A1%C4%8D%C5%99%C5%BE%C3%BD%C3%A1%C3%AD%C3%A9---%2520",
				simpleValue(original).asString());
	}

}

redpajama_set_name: RedPajamaGithub


text:
const Routing = require('./allrouting');
const Express = require('express');
/**
 * Router class, unlike the routes class this class
 * limits the scope of all calls and middleware to a specific
 * route, allowing for more granular middleware and better
 * route organization. This class is also not static as there can better
 * multiple instances of it
 */
class Router extends Routing {
    /**
     * Constructor method setting up basic values
     * @param {Express} express instance of express js.
     */
    constructor() {
        super();
        this.router = Express.Router();
    }
}

module.exports = Router;


text:
package org.geometerplus.fbreader.formats.xhtml;

import org.geometerplus.zlibrary.core.xml.ZLStringMap;

class XHTMLTagBodyAction extends XHTMLTagAction {
	protected void doAtStart(XHTMLReader reader, ZLStringMap xmlattributes) {
		reader.myInsideBody = true;
	}

	protected void doAtEnd(XHTMLReader reader) {
		reader.getModelReader().endParagraph();
		reader.myInsideBody = false;
	}
}


text:
This project is the frontend of a portfolio website.

## Getting Started

To get started, clone the portfolio_site repository to open the html file locally on your computer.

    $ git clone https://github.com/mediaProduct2017/portfolio_site.git

## Usage

Open the directory 'portfolio_site' and open index.html with a browser.

The content is responsive and displays on all display sizes, including desktop, mobile and tablet.

The page has a breakpoint when the viewport width reaches 660px (device independent pixel).


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

package io.minio.errors;

/** Thrown to indicate that error at XML marshalling or unmarshalling. */
public class XmlParserException extends MinioException {
  Exception exception;

  public XmlParserException(Exception exception) {
    super();
    this.exception = exception;
  }

  @Override
  public String toString() {
    return exception.toString();
  }
}


text:
package org.woehlke.twitterwall.backend.service.persist;

import org.woehlke.twitterwall.oodm.model.User;
import org.woehlke.twitterwall.oodm.model.Task;

/**
 * Created by tw on 11.07.17.
 */
public interface StoreUserFromMention {

    User storeUserFromMention(User user, Task task);
}


text:
<?php

namespace Oro\Bundle\TestFrameworkBundle\Behat\Isolation;

class TokenGenerator
{
    /**
     * @param string $prefix
     * @return string
     */
    public static function generateToken($prefix = 'p')
    {
        return str_replace('.', '', uniqid((string)$prefix, true));
    }
}


text:
<?php

namespace Apache\Avro\Tests;

use Apache\Avro\Schema\AvroName;
use Apache\Avro\Schema\AvroSchemaParseException;
use PHPUnit\Framework\TestCase;

class NameExample
{
    var $is_valid;
    var $name;
    var $namespace;
    var $default_namespace;
    var $expected_fullname;

    function __construct(
        $name,
        $namespace,
        $default_namespace,
        $is_valid,
        $expected_fullname = null
    ) {
        $this->name = $name;
        $this->namespace = $namespace;
        $this->default_namespace = $default_namespace;
        $this->is_valid = $is_valid;
        $this->expected_fullname = $expected_fullname;
    }

    function __toString()
    {
        return var_export($this, true);
    }
}

class NameTest extends TestCase
{

    function fullname_provider()
    {
        $examples = array(
            new NameExample('foo', null, null, true, 'foo'),
            new NameExample('foo', 'bar', null, true, 'bar.foo'),
            new NameExample('bar.foo', 'baz', null, true, 'bar.foo'),
            new NameExample('_bar.foo', 'baz', null, true, '_bar.foo'),
            new NameExample('bar._foo', 'baz', null, true, 'bar._foo'),
            new NameExample('3bar.foo', 'baz', null, false),
            new NameExample('bar.3foo', 'baz', null, false),
            new NameExample('b4r.foo', 'baz', null, true, 'b4r.foo'),
            new NameExample('bar.f0o', 'baz', null, true, 'bar.f0o'),
            new NameExample(' .foo', 'baz', null, false),
            new NameExample('bar. foo', 'baz', null, false),
            new NameExample('bar. ', 'baz', null, false)
        );
        $exes = array();
        foreach ($examples as $ex) {
            $exes [] = array($ex);
        }
        return $exes;
    }

    /**
     * @dataProvider fullname_provider
     */
    function test_fullname($ex)
    {
        try {
            $name = new AvroName($ex->name, $ex->namespace, $ex->default_namespace);
            $this->assertTrue($ex->is_valid);
            $this->assertEquals($ex->expected_fullname, $name->fullname());
        } catch (AvroSchemaParseException $e) {
            $this->assertFalse($ex->is_valid, sprintf("%s:\n%s",
                $ex,
                $e->getMessage()));
        }
    }

    function name_provider()
    {
        return [
            ['a', true],
            ['_', true],
            ['1a', false],
            ['', false],
            [null, false],
            [' ', false],
            ['Cons', true]
        ];
    }

    /**
     * @dataProvider name_provider
     */
    function test_name($name, $is_well_formed)
    {
        $this->assertEquals(AvroName::isWellFormedName($name), $is_well_formed);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using Flooder.CircuitBreaker;
using Flooder.Events;

namespace Flooder.Worker
{
    public class WorkerFactory
    {
        public static IMessageBroker Create(Type type, MessageBrokerOption option)
        {
            return (IMessageBroker)Activator
                .CreateInstance(type, BindingFlags.CreateInstance, null, new object[] { option }, null);
        }

        public static IMessageBroker Create<T>(MessageBrokerOption option)
        {
            return (IMessageBroker) Activator
                .CreateInstance(typeof(T), BindingFlags.CreateInstance, null, new object[] {option}, null);
        }

        public static IMessageBroker Create(string type, MessageBrokerOption option)
        {
            switch (type)
            {
                case "fluentd":
                    return new FluentMessageBroker(option);
                case "stdout":
                    return new StdOutMessageBroker(option);
                default:
                    throw new NullReferenceException(string.Format("Type[{0}] is not found.", type));
            }
        }
    }

    public class MessageBrokerOption
    {
        public MessageBrokerOption()
        {
        }

        public MessageBrokerOption(IEnumerable<Tuple<string, int, int>> hosts)
        {
            Hosts          = hosts;
            Interval       = TimeSpan.FromSeconds(1);
            RetryMaxCount  = 3;
            Capacity       = 10000;
            ExtractCount   = 10;
            CircuitBreaker = new IncrementalRetryableCircuitBreaker();
        }

        public IEnumerable<Tuple<string, int, int>> Hosts { get; private set; }
        public TimeSpan Interval { get; set; }
        public int RetryMaxCount { get; set; }
        public int Capacity { get; set; }
        public int ExtractCount { get; set; }
        public IncrementalRetryableCircuitBreaker CircuitBreaker { get; private set; }
    }
}


text:
Statistical Mechanics Notes
----------------------------

The notes are online: `http://statisticalphysics.leima.is <http://statisticalphysics.leima.is>`_

Notes for my stat mech course. I used the sphinx configuration files and exts filese from `theoretical-physics <https://github.com/certik/theoretical-physics>`_ (I kept all the commits from the original author, even though I deleted all the contents).

This project is under `CC BY-NC-SA license <http://creativecommons.org/licenses/by-nc-sa/3.0/us/>`_ .

.. image:: https://raw.github.com/GuokrUnion/GuokrBadge/master/cc/gs/cc_byncsa.flat.guokr.32.png
   :target: http://creativecommons.org/licenses/by-nc-sa/3.0/us/

Thanks to Professor Kenkre for his excellent lectures.


text:
'use strict';
angular.module('Trendicity')

.controller('IntroCtrl', function(
  $scope,
  $state,
  $timeout,
  $ionicSlideBoxDelegate,
  $ionicSideMenuDelegate,
  $ionicHistory,
  localStorageService) {
  $scope.$on('$ionicView.beforeEnter', function() {
    // Clear history since this might have been a forced redirect
    $ionicHistory.clearHistory();
    // Fix issue when coming from map
    $ionicSlideBoxDelegate.update();
  });

  // Mark intro as seen
  localStorageService.set('seenIntro', true);

  // Called to navigate to the main app
  $scope.startApp = function() {
    $state.go('app.home.map');
  };

  $scope.next = function() {
    $ionicSlideBoxDelegate.next();
  };

  $scope.previous = function() {
    $ionicSlideBoxDelegate.previous();
  };

  // Called each time the slide changes
  $scope.slideChanged = function(index) {
    $scope.slideIndex = index;
  };

  $scope.openWindow = function(url) {
    window.open(url, '_system', 'location=no,clearsessioncache=yes,clearcache=yes');
  };
});


text:
package io.apiman.test.integration.ui.tests.apis;

import static io.apiman.test.integration.ui.support.selenide.SelenideUtils.open;

import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Condition.visible;
import static org.hamcrest.Matchers.equalToIgnoringCase;

import io.apiman.test.integration.runner.annotations.version.ApiVersion;
import io.apiman.test.integration.runner.restclients.version.ApiVersions;
import io.apiman.test.integration.ui.support.selenide.base.AbstractApiUITest;
import io.apiman.test.integration.ui.support.selenide.pages.apis.detail.ApiDetailPage;
import io.apiman.manager.api.beans.apis.ApiVersionBean;

import com.jayway.restassured.builder.ResponseSpecBuilder;
import com.jayway.restassured.specification.ResponseSpecification;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author jcechace
 */
public class RetireApiVersionIT extends AbstractApiUITest {

    public static final String STATUS_RETIRED = "retired";
    public static final String STATUS_PUBLISHED = "published";

    @ApiVersion(version = "published", api = "api", unique = true)
    private ApiVersionBean publishedVersion;

    @ApiVersion(version = "unpublished", api = "api", publish = false, unique = true)
    private ApiVersionBean unpublishedVersion;

    private static ApiVersions apiVersions;

    @BeforeClass
    public static void setUp() {
        apiVersions = new ApiVersions(api);
    }

    public ResponseSpecification expectedStatus(String status) {
        ResponseSpecification expectedStatus = new ResponseSpecBuilder()
            .expectBody("status", equalToIgnoringCase(status))
            .build();
        return expectedStatus;
    }

    @Test
    public void canRetirePublishedApiVersion() {
        openApiDetailPage(publishedVersion)
            .retire().confirmDialog()
            .status().shouldHave(text(STATUS_RETIRED));
        apiVersions.peek(publishedVersion.getVersion(), expectedStatus(STATUS_RETIRED));
    }

    @Test
    public void canNotRetireApiWhenNotConfirmed() {
        openApiDetailPage(publishedVersion)
            .retire().dismissDialog()
            .status().shouldHave(text(STATUS_PUBLISHED));
        apiVersions.peek(publishedVersion.getVersion(), expectedStatus(STATUS_PUBLISHED));
    }

    @Test
    public void shouldNotShowRetireButtonNotForUnpublishedApiVersion() {
        openApiDetailPage(unpublishedVersion).retireButton().shouldNotBe(visible);
    }

    private static ApiDetailPage openApiDetailPage(ApiVersionBean version) {
        return open(ApiDetailPage.class,
            version.getApi().getOrganization().getId(),
            version.getApi().getId(),
            version.getVersion());
    }
}


text:
module Oauth2Provider
  class AuthorizeController < ApplicationController

    include Oauth2Provider::SslHelper
    include Oauth2Provider::TransactionHelper

    transaction_actions :authorize

    def index
      return unless validate_params
      render 'oauth2_provider/authorize/index.html.erb'
    end

    def authorize
      return unless validate_params
      unless params[:authorize] == 'Yes'
        redirect_to "#{params[:redirect_uri]}?error=access-denied"
        return
      end
      @authorization = @client.create_authorization_for_user_id(current_user_id_for_oauth)
      state_param = if params[:state].blank?
        ""
      else
        "&state=#{CGI.escape(params[:state])}"
      end
      redirect_to "#{params[:redirect_uri]}?code=#{@authorization.code}&expires_in=#{@authorization.expires_in}#{state_param}"
    end

    private

    VALID_RESPONSE_TYPES = ['code']

    def validate_params
      if params[:client_id].blank? || params[:response_type].blank?
        redirect_to "#{params[:redirect_uri]}?error=invalid-request"
        return false
      end
      unless VALID_RESPONSE_TYPES.include?(params[:response_type])
        redirect_to "#{params[:redirect_uri]}?error=unsupported-response-type"
        return
      end
      if params[:redirect_uri].blank?
        render :text => "You did not specify the 'redirect_uri' parameter!", :status => :bad_request
        return false
      end
      @client = Oauth2Provider::Client.find_one(:client_id, params[:client_id])
      if @client.nil?
        redirect_to "#{params[:redirect_uri]}?error=invalid-client-id"
        return false
      end
      if @client.redirect_uri != params[:redirect_uri]
        redirect_to "#{params[:redirect_uri]}?error=redirect-uri-mismatch"
        return false
      end
      true
    end
  end
end


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Goods;

/**
 * GoodsSearch represents the model behind the search form about `common\models\Goods`.
 */
class GoodsSearch extends Goods
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'category_id', 'type_id', 'brand_id', 'account_count', 'status'], 'integer'],
            [['name', 'unit', 'thumbnail', 'attributes', 'show_pictures', 'seo_title', 'seo_keyword', 'seo_description', 'detail_link', 'modified_time', 'create_time', 'goods_sku'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Goods::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'category_id' => $this->category_id,
            'type_id' => $this->type_id,
            'brand_id' => $this->brand_id,
            'account_count' => $this->account_count,
            'status' => $this->status,
            'modified_time' => $this->modified_time,
            'create_time' => $this->create_time,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'unit', $this->unit])
            ->andFilterWhere(['like', 'thumbnail', $this->thumbnail])
            ->andFilterWhere(['like', 'attributes', $this->attributes])
            ->andFilterWhere(['like', 'show_pictures', $this->show_pictures])
            ->andFilterWhere(['like', 'seo_title', $this->seo_title])
            ->andFilterWhere(['like', 'seo_keyword', $this->seo_keyword])
            ->andFilterWhere(['like', 'seo_description', $this->seo_description])
            ->andFilterWhere(['like', 'detail_link', $this->detail_link])
            ->andFilterWhere(['like', 'goods_sku', $this->goods_sku]);

        return $dataProvider;
    }
}


text:
namespace autofill {

class InfoBubbleFrame;

// Class to create and manage an information bubble for errors or tooltips.
class InfoBubble : public views::BubbleDialogDelegateView {
 public:
  InfoBubble(views::View* anchor, const base::string16& message);
  ~InfoBubble() override;

  // Shows the bubble. |widget_| will be NULL until this is called.
  void Show();

  // Hides and closes the bubble.
  void Hide();

  // Updates the position of the bubble.
  void UpdatePosition();

  // views::BubbleDialogDelegateView:
  views::NonClientFrameView* CreateNonClientFrameView(
      views::Widget* widget) override;
  gfx::Size GetPreferredSize() const override;
  void OnWidgetDestroyed(views::Widget* widget) override;
  void OnWidgetBoundsChanged(views::Widget* widget,
                             const gfx::Rect& new_bounds) override;
  int GetDialogButtons() const override;

  views::View* anchor() { return anchor_; }
  const views::View* anchor() const { return anchor_; }

  void set_align_to_anchor_edge(bool align_to_anchor_edge) {
    align_to_anchor_edge_ = align_to_anchor_edge;
  }

  void set_preferred_width(int preferred_width) {
    preferred_width_ = preferred_width;
  }

  void set_show_above_anchor(bool show_above_anchor) {
    show_above_anchor_ = show_above_anchor;
  }

 private:
  views::Widget* widget_;  // Weak, may be NULL.
  views::View* const anchor_;  // Weak.
  InfoBubbleFrame* frame_;  // Weak, owned by widget.

  // Whether the bubble should align its border to the anchor's edge rather than
  // horizontally centering the arrow on |anchor_|'s midpoint. Default is false.
  bool align_to_anchor_edge_;

  // The width this bubble prefers to be. Default is 0 (no preference).
  int preferred_width_;

  // Whether the bubble should be shown above the anchor (default is below).
  bool show_above_anchor_;

  DISALLOW_COPY_AND_ASSIGN(InfoBubble);
};

}  // namespace autofill

#endif  // CHROME_BROWSER_UI_VIEWS_AUTOFILL_INFO_BUBBLE_H_


text:
import { lazyComponent } from '@waldur/core/lazyComponent';
import { translate } from '@waldur/i18n';
import { registerOfferingType } from '@waldur/marketplace/common/registry';

import { BASIC_OFFERING_TYPE, SUPPORT_OFFERING_TYPE } from './constants';
import { serializer } from './serializer';

const OfferingConfigurationDetails = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "OfferingConfigurationDetails" */ '@waldur/support/OfferingConfigurationDetails'
    ),
  'OfferingConfigurationDetails',
);
const OfferingConfigurationForm = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "OfferingConfigurationForm" */ '@waldur/support/OfferingConfigurationForm'
    ),
  'OfferingConfigurationForm',
);
const OfferingPluginOptionsForm = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "OfferingPluginOptionsForm" */ './OfferingPluginOptionsForm'
    ),
  'OfferingPluginOptionsForm',
);
const OfferingPluginSecretOptionsForm = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "OfferingPluginSecretOptionsForm" */ './OfferingPluginSecretOptionsForm'
    ),
  'OfferingPluginSecretOptionsForm',
);

export const COMMON_OPTIONS = {
  component: OfferingConfigurationForm,
  detailsComponent: OfferingConfigurationDetails,
  pluginOptionsForm: OfferingPluginOptionsForm,
  secretOptionsForm: OfferingPluginSecretOptionsForm,
  serializer,
  showOptions: true,
  showComponents: true,
};

registerOfferingType({
  type: SUPPORT_OFFERING_TYPE,
  get label() {
    return translate('Request-based item');
  },
  ...COMMON_OPTIONS,
});

registerOfferingType({
  type: BASIC_OFFERING_TYPE,
  get label() {
    return translate('Request-based item (without Service Desk)');
  },
  ...COMMON_OPTIONS,
});


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>Angular Elessar demos</title>
		<link rel="stylesheet" href="../node_modules/elessar/elessar.css">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">

				<button class="btn btn-success" ng-click="homeCtrl.addRange()" ng-show="homeCtrl.buttonsControl.addBtnVisible">
					Add range
				</button>
				<button class="btn btn-danger" ng-click="homeCtrl.removeRange()"
				        ng-show="homeCtrl.buttonsControl.removeBtnVisible">Remove range
				</button>
				<button class="btn btn-primary" ng-click="homeCtrl.changeModel()"
				        ng-show="homeCtrl.buttonsControl.changeBtnVisible">Change range
				</button>
				<button class="btn btn-info" ng-click="homeCtrl.reloadModel()"
				        ng-show="homeCtrl.buttonsControl.reloadBtnVisible">Reload model
				</button>

			<ui-rangebar ng-model="homeCtrl.values" ui-options="homeCtrl.options"
			             ui-instance="homeCtrl.rangeBar"></ui-rangebar>

{{homeCtrl.values | json}}


text:
package me.himanshusoni.quantumflux.model.map.types;

import android.content.ContentValues;
import android.database.Cursor;

import me.himanshusoni.quantumflux.model.map.SqlColumnMapping;

public class FloatType implements SqlColumnMapping {
    @Override
    public Class<?> getJavaType() {
        return Float.class;
    }

    @Override
    public String getSqlColumnTypeName() {
        return "NUMERIC";
    }

    @Override
    public Object toSqlType(Object source) {
        return source;
    }

    @Override
    public Object getColumnValue(Cursor cursor, int columnIndex) {
        return cursor.getFloat(columnIndex);
    }

    @Override
    public void setColumnValue(ContentValues contentValues, String key, Object value) {
        contentValues.put(key, (Float) value);
    }
}


text:
REx-RemoteExportFramework
=========================


text:
/* Browser Resets */
.flex-container a:active, .flexslider a:active { outline: none; }

.slides, .flex-control-nav, .flex-direction-nav { margin: 0; padding: 0; list-style: none; }

/* FlexSlider Necessary Styles
*********************************/
.flexslider { width: 100%; margin: 0; padding: 0; }

.flexslider .slides > li { display: none; } /* Hide the slides before the JS is loaded. Avoids image jumping */

.flexslider .slides img { max-width: 100%; display: block; }

.flex-pauseplay span { text-transform: capitalize; }

/* Clearfix for the .slides element */
.slides:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }

html[xmlns] .slides { display: block; }

* html .slides { height: 1%; }

/* No JavaScript Fallback */
/* If you are not using another script, such as Modernizr, make sure you
 * include js that eliminates this class on page load */
.no-js .slides > li:first-child { display: block; }

/* FlexSlider Default Theme
*********************************/
.flexslider { position: relative; zoom: 1; }

.flexslider .slides { zoom: 1; }

.flexslider .slides > li { position: relative; }

/* Suggested container for "Slide" animation setups. Can replace this with your own, if you wish */
.flex-container { zoom: 1; position: relative; }

/* Caption style */
/* IE rgba() hack */
.flex-caption { background:none; -ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000, endColorstr=#4C000000);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000, endColorstr=#4C000000);
zoom: 1; behavior: url(js/PIE.htc); }

.flexslider h2 { color: #426587; font-size: 20px; left: 60px; line-height: 18px; margin-bottom: 20px; position: absolute; top: 85px; }

.flex-caption { background: none repeat scroll 0 0 rgba(255, 255, 255, 0.17); color: #637C95; font-size: 12px; left: 60px; line-height: 18px; padding: 2%; position: absolute; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6); top: 121px; width: 340px; }

.flexslider .button-c1 { background: none repeat scroll 0 0 rgba(0, 0, 0, 0.3); box-shadow: 0 0 0; color: #ffffff !important; left: 80px; position: absolute; text-shadow: 0 0 0 #000; top: 234px; }

.flexslider .button-c1:hover { background: none repeat scroll 0 0 rgba(255, 255, 255, 0.3); color: #333333 !important; }

.flex-caption-round { background: none repeat scroll 0 0 rgba(255, 255, 255, 0.17); border-radius: 50% 50% 50% 50%; -moz-border-radius: 50% 50% 50% 50%; -webkit-border-radius: 50% 50% 50% 50%; display: block; height: 300px; left: 80px; position: relative; text-align: center; bottom: 350px; width: 300px; behavior: url(js/PIE.htc); }

.flex-caption-round h2 { border-bottom: 1px dotted #5EC3E5; color: #426587; font-size: 20px; left: 20px; line-height: 18px; margin-bottom: 15px; padding-bottom: 15px; position: absolute; text-shadow: 1px 1px 0 #F6F6F6, 2px 2px 0 #CCCCCC; top: 72px; width: 260px; }

.flex-caption-round .flex-caption { background: none repeat scroll 0 50% transparent; color: #426587; font-size: 12px; left: 13px; line-height: 18px; position: absolute; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); top: 115px; width: 260px; }

.flex-caption-round .button-c1 { background: none repeat scroll 0 0 rgba(0, 0, 0, 0.3); box-shadow: 0 0 0; color: #ffffff !important; left: 109px; position: absolute; text-shadow: 0 0 0 #000000; top: 213px; }

.flex-caption-round .button-c1:hover { background: none repeat scroll 0 0 rgba(255, 255, 255, 0.3); }

/* Direction Nav */
.flex-direction-nav li a { width: 52px; height: 52px; margin: 0; display: block; background: url(theme/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 43%; cursor: pointer; text-indent: -9999px; }

.flex-direction-nav li .next { background-position: -52px 0; right: -93px; }

.flex-direction-nav li .prev { left: -93px; }

.flex-direction-nav li .disabled { opacity: .3; filter:alpha(opacity=30); cursor: default; }

/* Control Nav */
.flex-control-nav { width:auto; position: absolute; padding:10px 10px 0px; left: 432px; bottom: 44px; text-align: center; }

.flex-control-nav li { margin: 0 0 0 5px; display: inline-block; zoom: 1; *display: inline;
}

.flex-control-nav li:first-child { margin: 0; }

.flex-control-nav li a { width: 19px; height: 19px; display: block; background: url(theme/bg_control_nav.png) no-repeat 0 1px; cursor: pointer; text-indent: -9999px; }

.flex-control-nav li a:hover { background-position: 0 -19px; }

.flex-control-nav li a.active { background-position: 0 -38px; cursor: default; }
@media handheld and (max-width: 480px), screen and (max-device-width: 767px), screen and (max-width: 1024px) {
 .flexslider h2 {
 display: none;
}
.flex-caption {
 left: 40px;
 top: 56px;
 width: 240px;
}
.flexslider .button-c1 {
 display: none;
}
 .flex-caption-round h2 {
 display: none;
}
.flex-caption-round {
 height: 200px;
 left: 60px;
 top: -225px;
 width: 200px;
}
.flex-caption-round .flex-caption {
 left: 13px;
 top: 41px;
 width: 164px;
}
.flex-caption-round .button-c1 {
 display: none;
}
 .flex-control-nav {
left: 30px;
bottom: 20px;
border-radius: 6px 6px 6px 6px;
-webkit-border-radius: 6px 6px 6px 6px;
-moz-border-radius: 6px 6px 6px 6px;
behavior: url(js/PIE.htc);
}
.flex-direction-nav li .next { right: -42px; }

.flex-direction-nav li .prev { left: -42px; }

}
 @media handheld and (max-width: 767px), screen and (max-device-width: 767px), screen and (max-width: 767px) {
.flex-caption-round {
 display: none;
}
.flex-direction-nav li a {
 top: 23%;
}
.flex-direction-nav li .next { right: -42px; }

.flex-direction-nav li .prev { left: -42px; }

}


text:
using namespace std;

namespace Cantera
{

ReactorNet::ReactorNet() :
    m_integ(0), m_time(0.0), m_init(false), m_integrator_init(false),
    m_nv(0), m_rtol(1.0e-9), m_rtolsens(1.0e-4),
    m_atols(1.0e-15), m_atolsens(1.0e-4),
    m_maxstep(0.0), m_maxErrTestFails(0),
    m_verbose(false), m_ntotpar(0)
{
    m_integ = newIntegrator("CVODE");

    // use backward differencing, with a full Jacobian computed
    // numerically, and use a Newton linear iterator
    m_integ->setMethod(BDF_Method);
    m_integ->setProblemType(DENSE + NOJAC);
    m_integ->setIterator(Newton_Iter);
}

ReactorNet::~ReactorNet()
{
    for (size_t n = 0; n < m_reactors.size(); n++) {
        if (m_iown[n]) {
            delete m_reactors[n];
        }
        m_reactors[n] = 0;
    }
    delete m_integ;
}

void ReactorNet::initialize()
{
    size_t n, nv;
    char buf[100];
    m_nv = 0;
    writelog("Initializing reactor network.\n", m_verbose);
    if (m_reactors.empty()) {
        throw CanteraError("ReactorNet::initialize",
                           "no reactors in network!");
    }
    size_t sensParamNumber = 0;
    m_start.assign(1, 0);
    for (n = 0; n < m_reactors.size(); n++) {
        Reactor& r = *m_reactors[n];
        r.initialize(m_time);
        nv = r.neq();
        m_nparams.push_back(r.nSensParams());
        std::vector<std::pair<void*, int> > sens_objs = r.getSensitivityOrder();
        for (size_t i = 0; i < sens_objs.size(); i++) {
            std::map<size_t, size_t>& s = m_sensOrder[sens_objs[i]];
            for (std::map<size_t, size_t>::iterator iter = s.begin();
                    iter != s.end();
                    ++iter) {
                m_sensIndex.resize(std::max(iter->second + 1, m_sensIndex.size()));
                m_sensIndex[iter->second] = sensParamNumber++;
            }
        }
        m_nv += nv;
        m_start.push_back(m_nv);

        if (m_verbose) {
            sprintf(buf,"Reactor %s: %s variables.\n",
                    int2str(n).c_str(), int2str(nv).c_str());
            writelog(buf);
            sprintf(buf,"            %s sensitivity params.\n",
                    int2str(r.nSensParams()).c_str());
            writelog(buf);
        }
        if (r.type() == FlowReactorType && m_reactors.size() > 1) {
            throw CanteraError("ReactorNet::initialize",
                               "FlowReactors must be used alone.");
        }
    }

    m_ydot.resize(m_nv,0.0);
    m_atol.resize(neq());
    fill(m_atol.begin(), m_atol.end(), m_atols);
    m_integ->setTolerances(m_rtol, neq(), DATA_PTR(m_atol));
    m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
    m_integ->setMaxStepSize(m_maxstep);
    m_integ->setMaxErrTestFails(m_maxErrTestFails);
    if (m_verbose) {
        sprintf(buf, "Number of equations: %s\n", int2str(neq()).c_str());
        writelog(buf);
        sprintf(buf, "Maximum time step:   %14.6g\n", m_maxstep);
        writelog(buf);
    }
    m_integ->initialize(m_time, *this);
    m_integrator_init = true;
    m_init = true;
}

void ReactorNet::reinitialize()
{
    if (m_init) {
        writelog("Re-initializing reactor network.\n", m_verbose);
        m_integ->reinitialize(m_time, *this);
        m_integrator_init = true;
    } else {
        initialize();
    }
}

void ReactorNet::advance(doublereal time)
{
    if (!m_init) {
        initialize();
    } else if (!m_integrator_init) {
        reinitialize();
    }
    m_integ->integrate(time);
    m_time = time;
    updateState(m_integ->solution());
}

double ReactorNet::step(doublereal time)
{
    if (time != -999) {
        warn_deprecated("ReactorNet::step(t)", "The argument to this function"
            " is deprecated and will be removed after Cantera 2.3.");
    }
    if (!m_init) {
        initialize();
    } else if (!m_integrator_init) {
        reinitialize();
    }
    m_time = m_integ->step(m_time + 1.0);
    updateState(m_integ->solution());
    return m_time;
}

void ReactorNet::addReactor(Reactor& r)
{
    r.setNetwork(this);
    m_reactors.push_back(&r);
    m_iown.push_back(false);
}

void ReactorNet::eval(doublereal t, doublereal* y,
                      doublereal* ydot, doublereal* p)
{
    size_t n;
    size_t pstart = 0;
    updateState(y);
    for (n = 0; n < m_reactors.size(); n++) {
        m_reactors[n]->evalEqs(t, y + m_start[n],
                               ydot + m_start[n], p + pstart);
        pstart += m_nparams[n];
    }
    checkFinite("ydot", ydot, m_nv);
}

void ReactorNet::evalJacobian(doublereal t, doublereal* y,
                              doublereal* ydot, doublereal* p, Array2D* j)
{
    doublereal ysave, dy;
    Array2D& jac = *j;

    //evaluate the unperturbed ydot
    eval(t, y, ydot, p);
    for (size_t n = 0; n < m_nv; n++) {
        // perturb x(n)
        ysave = y[n];
        dy = m_atol[n] + fabs(ysave)*m_rtol;
        y[n] = ysave + dy;
        dy = y[n] - ysave;

        // calculate perturbed residual
        eval(t, y, DATA_PTR(m_ydot), p);

        // compute nth column of Jacobian
        for (size_t m = 0; m < m_nv; m++) {
            jac(m,n) = (m_ydot[m] - ydot[m])/dy;
        }
        y[n] = ysave;
    }
}

void ReactorNet::updateState(doublereal* y)
{
    checkFinite("y", y, m_nv);
    for (size_t n = 0; n < m_reactors.size(); n++) {
        m_reactors[n]->updateState(y + m_start[n]);
    }
}

void ReactorNet::getInitialConditions(doublereal t0,
                                      size_t leny, doublereal* y)
{
    for (size_t n = 0; n < m_reactors.size(); n++) {
        m_reactors[n]->getInitialConditions(t0, m_start[n+1]-m_start[n],
                                            y + m_start[n]);
    }
}

size_t ReactorNet::globalComponentIndex(const string& component, size_t reactor)
{
    if (!m_init) {
        initialize();
    }
    return m_start[reactor] + m_reactors[reactor]->componentIndex(component);
}

void ReactorNet::registerSensitivityReaction(void* reactor,
        size_t reactionIndex, const std::string& name, int leftright)
{
    if (m_integrator_init) {
        throw CanteraError("ReactorNet::registerSensitivityReaction",
                           "Sensitivity reactions cannot be added after the"
                           "integrator has been initialized.");
    }
    std::pair<void*, int> R = std::make_pair(reactor, leftright);
    if (m_sensOrder.count(R) &&
            m_sensOrder[R].count(reactionIndex)) {
        throw CanteraError("ReactorNet::registerSensitivityReaction",
                           "Attempted to register duplicate sensitivity reaction");
    }
    m_paramNames.push_back(name);
    m_sensOrder[R][reactionIndex] = m_ntotpar;
    m_ntotpar++;
}

}


text:
namespace LoadTests
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using EasyConsole;
    using SqlStreamStore.Streams;

    public class StreamSubscription : LoadTest
    {
        public override async Task Run(CancellationToken ct)
        {
            Output.WriteLine("");
            Output.WriteLine(ConsoleColor.Green,
                "Subscribes to multiple individual streams and appends to each of them in turn, multiple times.");
            Output.WriteLine("");

            var (streamStore, dispose) = await GetStore(ct);

            try
            {

                int numberOfStreams = Input.ReadInt(
                    "Number of independent streams, each will have it's own subscriber: ",
                    1,
                    1000);

                int numberOfAppends = Input.ReadInt("Number of times each stream will have an append: ", 1, 1000);

                string jsonData = "{}";

                var subscriptions = new List<IDisposable>();
                int messagesReceived = 0;

                for(int i = 0; i < numberOfStreams; i++)
                {
                    var subscription = streamStore.SubscribeToStream(
                        $"stream-{i}",
                        StreamVersion.None,
                        (_, __, ___) =>
                        {
                            Interlocked.Increment(ref messagesReceived);
                            return Task.CompletedTask;
                        });
                    subscriptions.Add(subscription);
                }

                int amendAcount = 0;
                int eventNumber = 1;
                var totalMessages = numberOfAppends * numberOfStreams;
                var stopwatch = Stopwatch.StartNew();

                while(amendAcount < numberOfAppends)
                {
                    for(int i = 0; i < numberOfStreams; i++)
                    {
                        var newStreamMessages = MessageFactory.CreateNewStreamMessages(jsonData, eventNumber);
                        await streamStore.AppendToStream($"stream-{i}", ExpectedVersion.Any, newStreamMessages, ct);
                        eventNumber++;
                    }

                    amendAcount++;
                    Console.Write(
                        $"\r> Appending: {amendAcount} / {numberOfAppends} . Received: {messagesReceived} / {totalMessages}");
                }

                while(messagesReceived < totalMessages)
                {
                    Console.Write(
                        $"\r> Appending: {amendAcount} / {numberOfAppends} . Received: {messagesReceived} / {totalMessages}");
                    await Task.Delay(100, ct);
                }

                Console.WriteLine(
                    $"\r> Appending: {amendAcount} / {numberOfAppends} . Received: {messagesReceived} / {totalMessages}");

                foreach(var subscription in subscriptions)
                {
                    subscription.Dispose();
                }

                Output.WriteLine($"> Complete in {stopwatch.Elapsed:c}");
            }
            finally
            {
                dispose();
            }
        }
    }
}


text:
/* eslint-disable react/prop-types */
import React from 'react';

const registerMachineForm = props => (

Register new Machine

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    <form>
      <fieldset className="uk-fieldset">

          <input className="uk-input" type="text" placeholder="Model" name="model"
            onChange={props.onChange} value={props.state.model} />

          <input className="uk-input" type="text" placeholder="Make" name="make"
            onChange={props.onChange} value={props.state.make} />

          <input className="uk-input" type="text" placeholder="vin" name="vin"
            onChange={props.onChange} value={props.state.vin} />

          <button className="uk-button uk-button-default"
            disabled={props.state._disabled} onClick={props.onSubmit}>Register</button>

      </fieldset>
    </form>

);

export default registerMachineForm;


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ali lahko svoj barvni profil delim z drugimi?</title>
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">

Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu

Novice

Forum

Kaj je Ubuntu?

Pogosta vprašanja

Skupnost

Povezave

 »  Namizni vodnik Ubuntu » Nastavitve » Upravljanje barv › Umerjanje »

 »  Namizni vodnik Ubuntu » Strojna oprema » Upravljanje barv › Umerjanje »

Ali lahko svoj barvni profil delim z drugimi?

Barvni profili, ki ste jih sami ustvarili, so določeni za strojno opremo in pogoje osvetlitve, za katero ste jih umerili. Zaslon ki je bil prižgan nekaj sto ur, bo imel zelo drugačen barvni profil kot podoben zaslon, ki je bil prižgan na tisoče ur.

To pomeni, da boste v primeru da svoj barvni profil delite z nekom, morda spravili bližje umerjanju, vendar je zavajujoče reči, da je njihov zaslon umerjen.

Podobno deljenje profila, ki ste ga ustvarili za svoje svetlobne pogoje nima smisla, če nimate v prostoru za urejanje slik  vsi popolnoma enake osvetlitve (brez sončne svetlobe z oken, črnih zidov, dnevnih žarnic).

Previdno preverite pogoje razširjanja za profile, ki ste jih prejeli s spletišč proizvajalca ali pa jih je za vas nekdo ustvaril.

Več podrobnosti

Umerjanje

Poglejte tudi

Kaj je barvni profil? — Barvni profil je enostavna datoteka, ki izrazi barvni prostor ali odziv naprave.

Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila Ubuntu dokumentacijska ekpa za Ubuntu. V slovenščino jo je prevedla skupina Ubuntu prevajalcev. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na dopisni seznam.


text:
#include "cmn.h"
#include "../Cartridge.h"

namespace tape
{

    struct Cartridge::Detail
    {
        string changerSetting;
        string setting;

        bool GetTape(LtfsTapeInfo & tape, Error & error)
        {
            LtfsError err;
            vector<LtfsTapeInfo> tapes;
            if ( ! LtfsLibraries::Instance()->GetTapeList(
                    changerSetting, tapes, err ) ) {
                LtfsLogError("Failed to get tapes from HAL: " << changerSetting);
                error.SetError(
                        Error::ERROR_NO_ENTRY,
                        string("No such tape cartridge: ") + setting );
                return false;
            }
            for ( vector<LtfsTapeInfo>::iterator i = tapes.begin();
                    i != tapes.end();
                    ++ i ) {
                if ( i->mBarcode == setting ) {
                    tape = *i;
                    return true;
                }
            }
            LtfsLogError("No such tape in HAL: "
                    << changerSetting << ":" << setting);
            error.SetError(
                    Error::ERROR_NO_ENTRY,
                    string("No such tape cartridge: ") + setting );
            return false;
        }
    };

    Cartridge::Cartridge(const string & setting)
    : detail_(new Detail())
    {
        istringstream is(setting);
        string changerSetting;
        string tapeSetting;
        is >> changerSetting >> tapeSetting;

        detail_->setting = tapeSetting;
        detail_->changerSetting = changerSetting;
    }

    Cartridge::Cartridge(const Cartridge & cartridge)
    : detail_(new Detail())
    {
        detail_->setting = cartridge.detail_->setting;
        detail_->changerSetting = cartridge.detail_->changerSetting;
    }

    void
    Cartridge::Swap(Cartridge & cartridge)
    {
        swap( detail_, cartridge.detail_ );
    }

    Cartridge::~Cartridge()
    {
        delete detail_;
    }

    bool
    Cartridge::GetBarcode(string & barcode, Error & error)
    {
        barcode = detail_->setting;
        return true;
    }

    bool
    Cartridge::GetSlotID(int & slotID, Error & error)
    {
        LtfsTapeInfo tape;
        if(!detail_->GetTape(tape, error)){
            return false;
        }

        slotID = tape.mSlotID;
        return true;
    }

}


text:
Your expense tracker

                    March 2015
                    vs Feb

                        Week
                        Month
                        Year

                      <highchart id="chart1" config="vm.chartConfig" class="small-12"></highchart>


text:
package apps.remotecontrol.tableportal;

import synergynetframework.appsystem.contentsystem.items.ContentItem;
import synergynetframework.appsystem.contentsystem.items.Frame;

import com.jme.scene.Spatial;

/**
 * The Class RadarCullManager.
 */
public class RadarCullManager {

	/** The crh. */
	private ClipRectangleHud crh;

	/**
	 * Instantiates a new radar cull manager.
	 *
	 * @param portal
	 *            the portal
	 * @param radar
	 *            the radar
	 */
	public RadarCullManager(TablePortal portal, Radar radar) {
		Frame frame = (Frame) radar.getRadarWindow().getContentSystem()
				.createContentItem(Frame.class);
		frame.setWidth((int) (radar.getRadarWindow().getWidth() * radar
				.getRadarWindow().getScale()));
		frame.setHeight((int) (radar.getRadarWindow().getHeight() * radar
				.getRadarWindow().getScale()));
		portal.getWindow().addSubItem(frame);
		frame.setLocation(radar.getRadarWindow().getLocation());
		frame.setVisible(false);
		Spatial spat = ((Spatial) (frame.getImplementationObject()));
		crh = new ClipRectangleHud(spat, frame.getWidth(), frame.getHeight());
	}

	/**
	 * Register item for clipping.
	 *
	 * @param item
	 *            the item
	 */
	public void registerItemForClipping(ContentItem item) {
		crh.setSpatialClip((Spatial) item.getImplementationObject(), true);
	}

	/**
	 * Update.
	 */
	public void update() {
		crh.updateEquations();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
		   http://www.springframework.org/schema/util
		   http://www.springframework.org/schema/util/spring-util-2.0.xsd">

	<!-- RuleSet bean for the XmlModule -->
	<bean id="XmlRuleSet" class="org.jhove2.module.assess.RuleSet"  scope="singleton">
	    <property name="name" value="XmlRuleSet"/>
	    <property name="description" value="RuleSet for Xml Module"/>
	    <property name="objectFilter" value="org.jhove2.module.format.xml.XmlModule"/>
		<property name="rules">
			<list value-type="org.jhove2.module.assess.Rule">
				<ref local="XmlStandaloneRule"/>
				<ref local="XmlValidityRule"/>
			</list>
		</property>
		<property name="enabled" value="true"/>
	</bean>

	<!-- Rule bean for evaluating xmlDeclaration.standalone value -->
	<bean id="XmlStandaloneRule" class="org.jhove2.module.assess.Rule" scope="singleton">
	    <property name="name" value="XmlStandaloneRule"/>
	    <property name="description" value="Does XML Declaration specify standalone status?"/>
		<property name="consequent" value="Is Standalone"/>
		<property name="alternative" value="Is Not Standalone"/>
	    <property name="quantifier" value="ALL_OF"/>
		<property name="predicates">
			<list value-type="java.lang.String">
				<value>xmlDeclaration.standalone == 'yes'</value>
			</list>
		</property>
		<property name="enabled" value="false"/>
	</bean>

	<!-- Rule bean for evaluating validity value -->
	<bean id="XmlValidityRule" class="org.jhove2.module.assess.Rule" scope="singleton">
	    <property name="name" value="XmlValidityRule"/>
	    <property name="description" value="Is the XML validity status acceptable?"/>
		<property name="consequent" value="Acceptable"/>
		<property name="alternative" value="Not Acceptable"/>
	    <property name="quantifier" value="ANY_OF"/>
		<property name="predicates">
			<list value-type="java.lang.String">
				<value>valid.toString() == 'true'</value>
				<value>
					<![CDATA[(valid.toString() == 'undetermined') && (wellFormed.toString() == 'true')]]>
				</value>
			</list>
		</property>
		<property name="enabled" value="true"/>
	</bean>

</beans>


text:
//------------------------------------------------------------------------------
// <copyright file="ObjectListDataBindEventArgs.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 */

using System;
using System.Security.Permissions;

namespace System.Web.UI.MobileControls
{

    /*
     * ObjectList item data binding arguments.
     *
     * Copyright (c) 2000 Microsoft Corporation
     */

    /// <include file='doc\ObjectListDataBindEventArgs.uex' path='docs/doc[@for="ObjectListDataBindEventArgs"]/*' />
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
    [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
    public class ObjectListDataBindEventArgs : EventArgs {

        private ObjectListItem _item;
        private Object _dataItem;

        /// <include file='doc\ObjectListDataBindEventArgs.uex' path='docs/doc[@for="ObjectListDataBindEventArgs.ObjectListDataBindEventArgs"]/*' />
        public ObjectListDataBindEventArgs(ObjectListItem item, Object dataItem)
        {
            _item = item;
            _dataItem = dataItem;
        }

        /// <include file='doc\ObjectListDataBindEventArgs.uex' path='docs/doc[@for="ObjectListDataBindEventArgs.ListItem"]/*' />
        public ObjectListItem ListItem
        {
            get
            {
                return _item;
            }
        }

        /// <include file='doc\ObjectListDataBindEventArgs.uex' path='docs/doc[@for="ObjectListDataBindEventArgs.DataItem"]/*' />
        public Object DataItem
        {
            get
            {
                return _dataItem;
            }
        }

    }

}


text:
package yk.senjin.shaders.gshader.analysis;

import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.builder.AstBuilder;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.control.CompilePhase;
import org.junit.Test;
import yk.jcommon.collections.*;
import yk.jcommon.match2.*;
import yk.jcommon.probe.Probe;
import yk.jcommon.probe.State;
import yk.jcommon.search.SSearch;
import yk.jcommon.utils.IO;

import static org.junit.Assert.assertEquals;
import static yk.jcommon.collections.YArrayList.al;
import static yk.jcommon.collections.YHashMap.hm;
import static yk.jcommon.collections.YHashSet.hs;
import static yk.jcommon.match2.MatcherShortNames.*;
import static yk.senjin.shaders.gshader.ShaderTranslator.isPrimitive;
import static yk.senjin.shaders.gshader.ShaderTranslator.translateType;

/**
 * Created with IntelliJ IDEA.
 * User: yuri
 * Date: 28/10/15
 * Time: 16:38
 */
public class GglslAnalyzer {

    //primitive parameters CAN be overwritten
    //primitive parameters ALL in

    //in vector
    // can't rewrite  (could, but its strange if we rewrote it but still can't modify, and I don't want do flow analysis)
    // can't modify
    // can't return (make explicit copy)

    //out vector forbidden

    //inout vector
    // can't rewrite (use explicit copyFrom)
    // can modify
    // can't return  (use explicit copy)

    //copyFrom -> glsl -> translate as '='
    //return explicit copy -> glsl -> translate as 'return without copy'

    //SUMMARY
    //primitives - do nothing
    //vector param
    // can't be rewritten
    // modified ? inout : in
    // can't be returned

    public static final YArrayList<Object> G_BODY_ACCESSORS = al(
            i(var("access")),
            p("methodsList", var("access")),
            p(MethodNode.class, "code", var("access")),
            p(MethodCallExpression.class, "getReceiver", var("access")),
            p(BlockStatement.class, "getStatements", var("access")),
            p(ExpressionStatement.class, "expression", var("access")),
            p(BinaryExpression.class, "leftExpression", var("access")),
            p(BinaryExpression.class, "rightExpression", var("access")),
            p(DeclarationExpression.class, "getLeftExpression", var("access")),
            p(DeclarationExpression.class, "getRightExpression", var("access")),
            p(UnaryMinusExpression.class, "getExpression", var("access")),
            p(UnaryPlusExpression.class, "getExpression", var("access")),
            p(ReturnStatement.class, "getExpression", var("access")),
            p(ConstructorCallExpression.class, "arguments", p("expressions", i(var("access")))),
            p(IfStatement.class, "booleanExpression", var("access")),
            p(IfStatement.class, "ifBlock", var("access")),
            p(IfStatement.class, "elseBlock", var("access"))
    );
    public static final YList<Object> G_METHOD_ACCESSORS = al(i(var("access")), p("methodsList", var("access")));

    public static final Object G_AS_ARG_PATTERN = stairs(
            deeper(G_BODY_ACCESSORS),
            p(MethodCallExpression.class, "getMethod", p("getText", var("callMethodName")), "getArguments"),
            p(ArgumentListExpression.class, "expressions"),
            i(var("argIndex")),
            p("variable", var("name")));

    public static final Object G_FIELD_AS_ARG_PATTERN = stairs(
            deeper(G_BODY_ACCESSORS),
            p(MethodCallExpression.class,
                    "getMethod", p("getText", var("METHOD_NAME")),
                    "getArguments"),
            p(ArgumentListExpression.class, "expressions"),
            i(var("ARG_INDEX")),
            p(PropertyExpression.class,
                    "getObjectExpression", p(VariableExpression.class,
                            "variable", var("OBJ_NAME")),
                    "getProperty", p("value", var("FIELD_NAME"))));

    public static final Object G_WRITE_FIELD_PATTERN = stairs(
            deeper(G_BODY_ACCESSORS),
            p(BinaryExpression.class, "operation", p("text", "="), "leftExpression"),
            p(PropertyExpression.class, "objectExpression"),
            p(VariableExpression.class, "variable", "OBJ_NAME"));

    @Test
    public void testCalcCallers() {
        String src = IO.readFile("src/main/java/yk/senjin/shaders/gshader/analysis/TestGroovyClass.groovy");
        assertEquals("{foo=[foo1], foo1=[foo2]}", calcCallers(new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, src)).toString());

        src = IO.readFile("/home/yuri/1/public/senjin/src/main/java/yk/senjin/shaders/gshader/examples/blend/BlendF.groovy");

        Probe probe = new Probe(new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, src), p(MethodCallExpression.class, "getMethod", p("getText", "foo"))){{
            skipMethods = hs("getMethodAsString", "getFirstStatement", "getVariableScope", "getDeclaringClass");
        }};
        SSearch.Node<State> node = probe.nextSolution(100000);
        if (node != null) System.out.println("!" + node.state.stackTrace.toString("\n"));

        src = IO.readFile("src/main/java/yk/senjin/shaders/gshader/analysis/TestGroovyClass2.groovy");
        assertEquals("{foo=[foo1]}", calcCallers(new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, src)).toString());
    }

    public static YMap<String, YSet<String>> calcCallers(Object data) {
        YMap<String, YSet<String>> result = hm();
        YSet<YMap<String, Object>> methods = new Matcher().match(data, stairs(deeper(G_METHOD_ACCESSORS), var("method"), p(MethodNode.class, "name"), var("methodName")));
        for (YMap<String, Object> mp : methods) {
            Object methodCalls = stairs(deeper(G_BODY_ACCESSORS), p(MethodCallExpression.class, "getMethod"), p("getText"), var("callMethodName"));
            for (YMap<String, Object> mcp : new Matcher().match(mp.get("method"), methodCalls)) {
                result.put((String) mp.get("methodName"), result.getOr((String) mp.get("methodName"), hs()).with((String) mcp.get("callMethodName")));
            }

            //TODO statics in other class
            methodCalls = stairs(deeper(G_BODY_ACCESSORS), p(StaticMethodCallExpression.class, "getMethod"), var("callMethodName"));
            for (YMap<String, Object> mcp : new Matcher().match(mp.get("method"), methodCalls)) {
                result.put((String) mp.get("methodName"), result.getOr((String) mp.get("methodName"), hs()).with((String) mcp.get("callMethodName")));
            }
        }
        return result;
    }

    @Test
    public void testArgModifiersCollect() {
        String src = IO.readFile("src/main/java/yk/senjin/shaders/gshader/analysis/BlendF.groovy");
        YHashMap<String, YSet<String>> modifiers = inferInOutModifiers(new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, src));
        assertEquals("{main:1=[inout], testFoo:0=[inout]}", modifiers.toString());
    }

    //SUMMARY
    //primitives - do nothing
    //vector param
    // can't be rewritten     //done in gAsserts
    // can't be returned      //in gAsserts
    // modified ?  =>   inout : in

    public static YHashMap<String, YSet<String>> inferInOutModifiers(Object nodes) {
        YList<Object> accessors = YArrayList.al(new MatchByIndex(new MatchVar("access")));
        YList<Object> accessors2 = accessors.with(MatchProperty.p("methodsList", new MatchVar("access")));
        YSet<YMap<String, Object>> method = new Matcher().match(nodes, new MatchDeeper(accessors2, var("method", p(MethodNode.class, "name", var("methodName")))));
        YHashMap<String, YSet<String>> modifiers = hm();
        int oldModifiersCount = 0;
        while (true) {

            for (YMap<String, Object> m : method) {
//                System.out.println("method: " + m.get("methodName"));
                getArgsModifiers((MethodNode) m.get("method"), modifiers);
//                System.out.println(modifiers);
            }
            int newModifiersCount = modifiers.values().reduce(0, (i, ss) -> i + ss.size());
            if (newModifiersCount == oldModifiersCount) break;
//            System.out.println("AND AGAIN");
            oldModifiersCount = newModifiersCount;
        }
        return modifiers;
    }

    public static YMap<String, YSet<String>> getArgsModifiers(MethodNode methodNode, YMap<String, YSet<String>> result) {

        Object fieldWritePattern = new MatchDeeper(G_BODY_ACCESSORS,
                p(BinaryExpression.class, "operation", p("text", "="),
                        "leftExpression", p(PropertyExpression.class, "objectExpression", p(VariableExpression.class, "variable", var("name")), "property", p("value", var("value")))
                ));

        YSet<YMap<String, Object>> paramMm = new Matcher().match(methodNode, p("parameters", i(var("paramIndex"), p("name", var("paramName")))));
        for (YMap<String, Object> paramM : paramMm) if (!isPrimitive(translateType((String) paramM.get("paramName")))) {
            String paramName = (String) paramM.get("paramName");
            String paramFullName = methodNode.getName() + ":" + paramM.get("paramIndex");
            if (new Matcher().match(methodNode, fieldWritePattern, hm("name", paramName)).notEmpty()) result.put(paramFullName, result.getOr(paramFullName, hs()).with("inout"));

            YSet<YMap<String, Object>> asArgMm = new Matcher().match(methodNode, G_AS_ARG_PATTERN, hm("name", paramName));
            for (YMap<String, Object> asArgM : asArgMm) {
                Object callMethodName = asArgM.get("callMethodName");
                Object asArgIndex = asArgM.get("argIndex");
                result.put(paramFullName, result.getOr(paramFullName, hs()).with(result.getOr(callMethodName + ":" + asArgIndex, hs())));
            }
        }
        return result;
    }

    @Test
    public void testAsserts() {
        String src = IO.readFile("src/main/java/yk/senjin/shaders/gshader/analysis/BlendF.groovy");
        assertEquals("(method main) field 'kSize' is rewritten, but it's forbidden in gglsl\n" +
                        "(method main) field 'direction' is used as inout arg, but it's forbidden in gglsl\n" +
                        "(method testFoo) parameter 'modified' is rewritten, but it's forbidden in gglsl (use explicity copyFrom)\n" +
                        "(method foo) parameter 'd' is used as return value, but it's forbidden in gglsl (use explicity copy)\n" +
                        "(method foo) field 'direction' is used as return value, but it's forbidden in gglsl",
                gAsserts(new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, src), hm("testFoo:0", hs("in", "inout"))).toString("\n"));

    }

    //ShaderInOut can't write         //done in gAsserts
    //ShaderInOut can't read
    //ShaderInOut can't as arg        //TODO just forbid non-glsl types
    //ShaderIn.x  can't write
    //ShaderIn.x  can't as inout-arg

    //ShaderOut.x can write
    //ShaderOut.x can as inout-arg

    public static YList<String> gAssertsVarying(MethodNode methodNode, YMap<String, YSet<String>> modifiers) {

        Object refReadPattern = stairs(
                deeper(G_BODY_ACCESSORS),
                p(BinaryExpression.class, "operation", p("text", "="), "rightExpression"),
                deeper(G_BODY_ACCESSORS),
                p(VariableExpression.class, "variable", var("name")));

        Object refReadPattern2 = stairs(
                deeper(G_BODY_ACCESSORS),
                p(ReturnStatement.class, "getExpression"),
                deeper(G_BODY_ACCESSORS),
                p(VariableExpression.class, "variable", var("name")));

        Object fieldReadPattern = new MatchDeeper(G_BODY_ACCESSORS,
                p("operation", p("text", "="), "rightExpression", new MatchDeeper(G_BODY_ACCESSORS,
                        p("objectExpression", p("variable", var("name"))))));

        return null;
    }

    public static YList<String> gAsserts(Object mainClass, YMap<String, YSet<String>> modifiers) {
        YList<String> errors = al();

        Object varWritePattern = stairs(
                deeper(G_BODY_ACCESSORS),
                p(BinaryExpression.class, "operation", p("text", "="), "leftExpression"),
                p(VariableExpression.class, "variable", var("VAR_NAME")));

        Object varReturnPattern = stairs(
                deeper(G_BODY_ACCESSORS),
                p(ReturnStatement.class, "getExpression"),
                p(VariableExpression.class, "variable", var("VAR_NAME")));

        for (YMap<String, Object> m : new Matcher().match(mainClass, stairs(deeper(G_METHOD_ACCESSORS), var("method"), p(MethodNode.class, "name"), var("methodName")))) {
            Object methodName = m.get("methodName");
            String prefix = "(method " + methodName + ") ";
            for (Parameter parameter : ((MethodNode)m.get("method")).getParameters()) if (!isPrimitive(translateType(parameter.getType().getName()))) {//TODO match type
                //can't rewrite vector (use explicit copyFrom)
                if (new Matcher().match(m.get("method"), varWritePattern, hm("VAR_NAME", parameter.getName())).notEmpty()) {
                    errors.add(prefix + "parameter '" + parameter.getName() + " " + translateType(parameter.getType().getName()) + "' is rewritten, but it's forbidden in gglsl (use explicity copyFrom)");
                }
                //can't return vector (use explicit copy)
                if (new Matcher().match(m.get("method"), varReturnPattern, hm("VAR_NAME", parameter.getName())).notEmpty()) {
                    errors.add(prefix + "parameter '" + parameter.getName() + "' is used as return value, but it's forbidden in gglsl (use explicity copy)");
                }
            }

            YSet<YMap<String, Object>> fieldsMm = new Matcher().match(mainClass, stairs(i(), p(ClassNode.class, "getFields"), i(), p(FieldNode.class, "getName"), var("fieldName")));
            for (YMap<String, Object> fieldM : fieldsMm) {

                String fieldName = (String) fieldM.get("fieldName");

                //can't return uniform (use explicit copy)
                if (new Matcher().match(m.get("method"), varReturnPattern, hm("VAR_NAME", fieldName)).notEmpty()) {
                    errors.add(prefix + "field '" + fieldName + "' is used as return value, but it's forbidden in gglsl");
                }

                //uniform.x as inout-arg
                //seems like couldn't be (because all fields are primitive)
                for (YMap<String, Object> asArgM : new Matcher().match(m.get("method"), G_FIELD_AS_ARG_PATTERN, hm("OBJ_NAME", fieldName))) {
                    String argIndexedName = asArgM.get("callMethodName") + ":" + asArgM.get("argIndex");
                    YSet<String> argQualifiers = modifiers.getOr(argIndexedName, hs());
                    if (argQualifiers.contains("inout")) {
                        errors.add(prefix + "" + fieldName + "." + asArgM.get("FIELD_NAME") + " is used as inout arg, but it's forbidden in gglsl");
                    }
                }

                //uniform as inout-arg
                for (YMap<String, Object> asArgM : new Matcher().match(m.get("method"), G_AS_ARG_PATTERN, hm("name", fieldName))) {
                    String argIndexedName = asArgM.get("callMethodName") + ":" + asArgM.get("argIndex");
                    YSet<String> argQualifiers = modifiers.getOr(argIndexedName, hs());
                    if (argQualifiers.contains("inout")) {
                        errors.add(prefix + "field '" + fieldName + "' is used as inout arg, but it's forbidden in gglsl");
                    }
                }

                //uniform write
                if (new Matcher().match(m.get("method"), varWritePattern, hm("VAR_NAME", fieldName)).notEmpty()) {
                    errors.add(prefix + "field '" + fieldName + "' is rewritten, but it's forbidden in gglsl");
                }

                //uniform.x write
                if (new Matcher().match(m.get("method"), G_WRITE_FIELD_PATTERN, hm("OBJ_NAME", fieldName)).notEmpty()) {
                    errors.add(prefix + "field '" + fieldName + "' is modified, but it's forbidden in gglsl");
                }
            }

        }
        return errors;
    }
}


text:
#ifndef __openma_base_subject_h
#define __openma_base_subject_h

#include "openma/base/node.h"
#include "openma/base/any.h"
#include "openma/base/macros.h" // _OPENMA_NOEXCEPT

namespace ma
{
  class OPENMA_BASE_EXPORT Subject : public Node
  {
    OPENMA_DECLARE_NODEID(Subject, Node)

  public:
    Subject(const std::string& name, std::unordered_map<std::string, Any>&& properties = std::unordered_map<std::string, Any>{}, Node* parent = nullptr);
    ~Subject() _OPENMA_NOEXCEPT;

    Subject(const Node& ) = delete;
    Subject(Node&& ) _OPENMA_NOEXCEPT = delete;
    Subject& operator=(const Subject& ) = delete;
    Subject& operator=(Subject&& ) _OPENMA_NOEXCEPT = delete;

  protected:
    virtual Node* allocateNew() const override;
  };
};

OPENMA_EXPORT_STATIC_TYPEID(ma::Subject, OPENMA_BASE_EXPORT);

#endif // __openma_base_subject_h


text:
from model.groups import Group
import random
import string
import jsonpickle
import os.path
import getopt
import sys

try:
    opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
    getopt.usage()
    sys.exit(2)

n = 5
f = "data/groups.json"

for o, a in opts:
    if o == "-n":
        n = int(a)
    elif o =="-f":
        f=a

def random_string(prefix, maxlen):
    #symbols = string.ascii_letters + string.digits + string.punctuation + " "*10
    symbols = string.ascii_letters + string.digits + " " * 1
    return prefix +"".join([random.choice(symbols) for i in range(random.randrange(maxlen))])

testdata = [Group(name="", header="",footer="")] + [
    Group(name=random_string("name", 10), header=random_string("header", 20),footer=random_string("footer", 20))
    for i in range(n)
]

file=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)

with open(file, "w") as out:
    jsonpickle.set_encoder_options("json", indent=2)
    out.write(jsonpickle.encode(testdata))


text:
from copy import deepcopy
from mock import patch

from djangosanetesting import UnitTestCase

from mypage.pages.models import Page
from mypage.pages.layout import Layout, WidgetInLayout

stored_layout = {
    'static_containers': [[
        {
            'widget_ct_id': 1,
            'widget_id': 1,
            'config': {},
            'state': WidgetInLayout.STATE_NEW,
        }
    ]],
    'containers': [[
        {
            'widget_ct_id': 1,
            'widget_id': 2,
            'config': {},
            'state': WidgetInLayout.STATE_NEW,
        },
        {
            'widget_ct_id': 1,
            'widget_id': 3,
            'config': {},
            'state': WidgetInLayout.STATE_NEW,
        },
    ]]
}

def dummy_render(instance, context={}, allow_fetch=False, tab=None):
    return '%d:%d:%s' % (instance.widget_ct_id, instance.widget_id, tab)

class TestLayoutRendering(UnitTestCase):

    def setUp(self):
        super(TestLayoutRendering, self).setUp()
        self.page = Page(pk=1)
        self.layout = deepcopy(stored_layout)

    @patch('mypage.pages.layout.WidgetInLayout.render', dummy_render)
    def test_render(self):
        layout = Layout(self.page, self.layout)
        self.assert_equals(
                layout.render(context={}),
                {'static_containers': [['1:1:None']], 'containers': [['1:2:None', '1:3:None']]})

    @patch('mypage.pages.layout.WidgetInLayout.render', dummy_render)
    def test_render_with_settab(self):
        layout = Layout(self.page, self.layout)
        self.assert_equals(
                layout.render(context={}, settab=dict(widget_ct_id=1, widget_id=2, tab='sometab')),
                {'static_containers': [['1:1:None']], 'containers': [['1:2:sometab', '1:3:None']]})


text:
//
//  Repeller.h
//  Ex45ParticleRepeller
//
//  Created by Ilya Rostovtsev on 7/3/13.
//
//  HWH Maintenance 8/19/13
//

#ifndef __Ex45ParticleRepeller__Repeller__
#define __Ex45ParticleRepeller__Repeller__

#include "Math.h"
#include "cinder/gl/gl.h"
#include "Particle.h"

using namespace ci;

class Repeller {

public:
    Repeller( const Vec2f& location_ );

    void setLocation( const Vec2i& mouse );
    Vec2f repel( const Vec2f& particlePosition ) const;
    void draw() const;

private:
    Vec2f location;
    const float radius;
    const float strength;

};

#endif /* defined(__Ex45ParticleRepeller__Repeller__) */


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { BlockCollapseComponent } from './block-collapse.component';
import { MarkdownDirective } from '../directives/markdown.directive';

describe('BlockCollapseComponent', () => {
  let component: BlockCollapseComponent;
  let fixture: ComponentFixture<BlockCollapseComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BlockCollapseComponent, MarkdownDirective ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BlockCollapseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  describe('toggle()', () => {
    it('should change opened state', () => {
      expect(component.opened).toBeFalsy();
      component.toggle();
      expect(component.opened).toBeTruthy();
      component.toggle();
      expect(component.opened).toBeFalsy();
    });
  });
});


text:
    <button class="btn btn-small" data-bind="click: function() {SEE.session.MainVM.Modal.ShowOrganizationInfoModal(orgInfo)}"></button>
    <button class="btn btn-small" data-bind="click: function () { orgInfo.Clone(SEE.session.Organization); }">Me</button>


text:
require "spec_helper"

describe Mongoid::Finders do

  describe ".all_in" do

    let(:criteria) do
      Person.all_in(aliases: [ "Bond", "007" ])
    end

    it "returns a new criteria with select conditions added" do
      criteria.selector.should eq({ aliases: { "$all" => [ "Bond", "007" ] } })
    end
  end

  describe ".any_in" do

    let(:criteria) do
      Person.any_in(aliases: [ "Bond", "007" ])
    end

    it "returns a new criteria with select conditions added" do
      criteria.selector.should eq({ aliases: { "$in" => [ "Bond", "007" ] } })
    end
  end

  describe ".excludes" do

    let(:criteria) do
      Person.excludes(title: "Sir")
    end

    it "returns a new criteria with select conditions added" do
      criteria.selector.should eq({ title: { "$ne" => "Sir" } })
    end
  end

  describe "#find" do

    context "when using integer ids" do

      before(:all) do
        Person.field(:_id, type: Integer)
      end

      after(:all) do
        Person.field(
          :_id,
          type: BSON::ObjectId,
          pre_processed: true,
          default: ->{ BSON::ObjectId.new }
        )
      end

      context "when passed a string" do

        let!(:person) do
          Person.create do |doc|
            doc._id = 1
          end
        end

        let(:from_db) do
          Person.find("1")
        end

        it "returns the matching document" do
          from_db.should eq(person)
        end
      end

      context "when passed an array of strings" do

        let!(:person) do
          Person.create do |doc|
            doc._id = 2
          end
        end

        let(:from_db) do
          Person.find([ "2" ])
        end

        it "returns the matching documents" do
          from_db.should eq([ person ])
        end
      end
    end

    context "when using string ids" do

      let!(:person) do
        Person.create(title: "Mrs.")
      end

      let!(:documents) do
        3.times.map do |n|
          Person.create(title: "Mr.")
        end
      end

      before(:all) do
        Person.field(
          :_id,
          type: String,
          pre_processed: true,
          default: ->{ BSON::ObjectId.new.to_s }
        )
      end

      after(:all) do
        Person.field(
          :_id,
          type: BSON::ObjectId,
          pre_processed: true,
          default: ->{ BSON::ObjectId.new }
        )
      end

      context "with an id as an argument" do

        context "when the document is found" do

          it "returns the document" do
            Person.find(person.id).should eq(person)
          end
        end

        context "when the document is not found" do

          it "raises an error" do
            expect {
              Person.find(BSON::ObjectId.new.to_s)
            }.to raise_error(Mongoid::Errors::DocumentNotFound)
          end
        end

        context "when the identity map is enabled" do

          before do
            Mongoid.identity_map_enabled = true
          end

          after do
            Mongoid.identity_map_enabled = false
          end

          context "when the document is found in the map" do

            before do
              Mongoid::IdentityMap.set(person)
            end

            let(:from_map) do
              Person.find(person.id)
            end

            it "returns the document" do
              from_map.should eq(person)
            end

            it "returns the same instance" do
              from_map.should equal(person)
            end
          end

          context "when the document is not found in the map" do

            let(:from_db) do
              Person.find(person.id)
            end

            it "returns the document from the database" do
              from_db.should eq(person)
            end

            it "returns a different instance" do
              from_db.should_not equal(person)
            end
          end
        end
      end

      context "when passed an array of ids" do

        context "when the documents are found" do

          let(:people) do
            Person.find(documents.map(&:id))
          end

          it "returns an array of the documents" do
            people.should eq(documents)
          end
        end

        context "when no documents found" do

          it "raises an error" do
            expect {
              Person.find([
                BSON::ObjectId.new.to_s, BSON::ObjectId.new.to_s
              ])
            }.to raise_error(Mongoid::Errors::DocumentNotFound)
          end
        end
      end

      context "when passing an empty array" do

        let(:people) do
          Person.find([])
        end

        it "returns an empty array" do
          people.should be_empty
        end
      end
    end

    context "when using object ids" do

      let!(:person) do
        Person.create(title: "Mrs.")
      end

      let!(:documents) do
        3.times.map do |n|
          Person.create(title: "Mr.")
        end
      end

      before(:all) do
        Person.field(
          :_id,
          type: BSON::ObjectId,
          pre_processed: true,
          default: ->{ BSON::ObjectId.new }
        )
      end

      context "when passed a BSON::ObjectId as an argument" do

        context "when the document is found" do

          it "returns the document" do
            Person.find(person.id).should eq(person)
          end
        end

        context "when the document is not found" do

          it "raises an error" do
            expect {
              Person.find(BSON::ObjectId.new)
            }.to raise_error(Mongoid::Errors::DocumentNotFound)
          end
        end
      end

      context "when passed a string id as an argument" do

        context "when the document is found" do

          it "returns the document" do
            Person.find(person.id.to_s).should eq(person)
          end
        end

        context "when the document is not found" do

          it "raises an error" do
            expect {
              Person.find(BSON::ObjectId.new.to_s)
            }.to raise_error(Mongoid::Errors::DocumentNotFound)
          end
        end
      end

      context "when passed an array of ids as args" do

        context "when the documents are found" do

          let(:people) do
            Person.find(documents.map(&:id))
          end

          it "returns an array of the documents" do
            people.should eq(documents)
          end
        end

        context "when no documents found" do

          it "raises an error" do
            expect {
              Person.find([
                BSON::ObjectId.new, BSON::ObjectId.new
              ])
            }.to raise_error(Mongoid::Errors::DocumentNotFound)
          end
        end
      end
    end
  end

  describe ".find_or_create_by" do

    context "when the document is found" do

      let!(:person) do
        Person.create(title: "Senior")
      end

      it "returns the document" do
        Person.find_or_create_by(title: "Senior").should eq(person)
      end
    end

    context "when the document is not found" do

      context "when not providing a block" do

        let!(:person) do
          Person.find_or_create_by(title: "Senorita")
        end

        it "creates a persisted document" do
          person.should be_persisted
        end

        it "sets the attributes" do
          person.title.should eq("Senorita")
        end
      end

      context "when providing a block" do

        let!(:person) do
          Person.find_or_create_by(title: "Senorita") do |person|
            person.pets = true
          end
        end

        it "creates a persisted document" do
          person.should be_persisted
        end

        it "sets the attributes" do
          person.title.should eq("Senorita")
        end

        it "calls the block" do
          person.pets.should be_true
        end
      end
    end
  end

  describe ".find_or_initialize_by" do

    context "when the document is found" do

      let!(:person) do
        Person.create(title: "Senior")
      end

      it "returns the document" do
        Person.find_or_initialize_by(title: "Senior").should eq(person)
      end
    end

    context "when the document is not found" do

      context "when not providing a block" do

        let!(:person) do
          Person.find_or_initialize_by(title: "Senorita")
        end

        it "creates a new document" do
          person.should be_new_record
        end

        it "sets the attributes" do
          person.title.should eq("Senorita")
        end
      end

      context "when providing a block" do

        let!(:person) do
          Person.find_or_initialize_by(title: "Senorita") do |person|
            person.pets = true
          end
        end

        it "creates a new document" do
          person.should be_new_record
        end

        it "sets the attributes" do
          person.title.should eq("Senorita")
        end

        it "calls the block" do
          person.pets.should be_true
        end
      end
    end
  end

  describe ".find_by" do

    context "when the document is found" do

      let!(:person) do
        Person.create(title: "sir")
      end

      it "returns the document" do
        Person.find_by(title: "sir").should eq(person)
      end
    end

    context "when the document is not found" do

      it "raises an error" do
        expect {
          Person.find_by(ssn: "333-22-1111")
        }.to raise_error(Mongoid::Errors::DocumentNotFound)
      end
    end
  end

  describe ".only" do

    let(:criteria) do
      Person.only(:title, :age)
    end

    it "returns a new criteria with select conditions added" do
      criteria.options.should eq({ fields: {_type: 1, title: 1, age: 1} })
    end
  end

  describe ".where" do

    let(:criteria) do
      Person.where(title: "Sir")
    end

    it "returns a new criteria with select conditions added" do
      criteria.selector.should eq({ title: "Sir" })
    end
  end

  describe ".near" do

    let(:criteria) do
      Address.near(latlng: [37.761523, -122.423575, 1])
    end

    it "returns a new criteria with select conditions added" do
      criteria.selector.should eq(
        { latlng: { "$near" => [37.761523, -122.423575, 1] }}
      )
    end
  end
end


text:
namespace PhotoShare.Client.Core.Commands
{
    using System;

    using Contracts;

    public class ShareAlbumCommand : ICommand
    {
        public ShareAlbumCommand()
        {

        }
        // ShareAlbum <albumId> <username> <permission>
        // For example:
        // ShareAlbum 4 dragon321 Owner
        // ShareAlbum 4 dragon11 Viewer
        public string Execute(string[] data)
        {
            throw new NotImplementedException();
        }
    }
}


text:
import * as React from 'react';
import toArray from 'rc-util/lib/Children/toArray';
import type { Tab } from 'rc-tabs/lib/interface';
import type { TabsProps, TabPaneProps } from '..';
import warning from '../../_util/warning';

function filter<T>(items: (T | null)[]): T[] {
  return items.filter(item => item) as T[];
}

export default function useLegacyItems(items?: TabsProps['items'], children?: React.ReactNode) {
  if (items) {
    return items;
  }

  warning(!children, 'Tabs', 'Tabs.TabPane is deprecated. Please use `items` directly.');

  const childrenItems = toArray(children).map((node: React.ReactElement<TabPaneProps>) => {
    if (React.isValidElement(node)) {
      const { key, props } = node;
      const { tab, ...restProps } = props || {};

      const item: Tab = {
        key: String(key),
        ...restProps,
        label: tab,
      };
      return item;
    }

    return null;
  });

  return filter(childrenItems);
}


text:
classdef result < sl.obj.display_class
    %
    %   Class:
    %   sci.time_series.calculators.regression.result
    %
    %   See Also
    %   ---------
    %   sci.time_series.calculators.regression
    %   sci.time_series.calculators.regression.theil_sen_result
    %   sci.time_series.calculators.regression.linear_regression_result

    properties (Abstract)
        training_data
    end

    properties (Dependent)
        residuals
        t_training
        y_training
    end

    methods
        function value = get.residuals(obj)
           value = obj.y_training - obj.y_hat;
        end
        function value = get.t_training(obj)
            [~,value] = obj.training_data.getRawDataAndTime();
        end
        function value = get.y_training(obj)
            value = obj.training_data.getRawDataAndTime();
        end
    end
end


text:
<?php

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

/* @var $this yii\web\View */
/* @var $model app\models\AttachmentsSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'regulations_id') ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'created') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

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


text:
package com.github.mdr.mash.view.render.browser

import com.github.mdr.mash.view.render.{ KeyHint, LinesAndCursorPos, MashRenderingContext }
import com.github.mdr.mash.repl.browser.TextLinesBrowserState
import com.github.mdr.mash.screen.Style.StylableString
import com.github.mdr.mash.screen._
import com.github.mdr.mash.utils.Dimensions
import com.github.mdr.mash.utils.Utils._

class TextLinesBrowserRenderer(state: TextLinesBrowserState,
                               terminalSize: Dimensions,
                               mashRenderingContext: MashRenderingContext)
  extends AbstractBrowserRenderer(state, terminalSize, mashRenderingContext) {

  protected def renderDataLines: Seq[Line] =
    for {
      (lineContents, index) ← state.model.renderedLines.zipWithIndex.window(state.firstRow, windowSize)
      isSelected = index == state.selectedRow && state.expressionStateOpt.isEmpty
      actualLineContents = if (isSelected && lineContents.isEmpty) " " else lineContents
    } yield Line(actualLineContents.style(Style(inverse = isSelected)))

  protected def renderLines: LinesAndCursorPos =
    combineUpperStatusLines(renderUpperStatusLines, renderDataLines ++ Seq(renderStatusLine))

  private def renderRegularStatusLine = {
    import KeyHint._
    val hints = Seq(Exit, Back, InsertWhole, NextParentResult, PreviousParentResult)
    val countChars = renderCount(state.selectedRow + 1, state.model.renderedLines.size)
    Line(countChars + " (".style + renderKeyHints(hints) + ")".style)
  }

  private def renderStatusLine: Line =
    state.expressionStateOpt match {
      case Some(_) ⇒ StatusLineRenderers.renderExpressionInputStatusLine
      case None    ⇒ renderRegularStatusLine
    }

  protected val windowSize = state.windowSize(terminalSize.rows)

}