text:
"""
variety_model.py

Defines the modular/submodular variety model used in the paper:
Mark Fuge, Josh Stroud, Alice Agogino. "Automatically Inferring Metrics for Design Creativity," in Proceedings of ASME 2013 International Design Engineering Technical Conferences & Computers and Information in Engineering Conference, August 4-2, 2013, Portland, USA
http://www.markfuge.com/papers/Fuge_DETC2013-12620.pdf

Authors: Josh Stroud and Mark Fuge
"""
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn import cross_validation

from concept_transforms import *

### Ported from mIDGenes/user_functions_public.js               ###

# Shah's variety metric: variety = summation(fj * summation(Sk*bk/n))
# fj :=  arbitrary weight based on judged importance of function fj
# Sk := weight for level k
# bk := # of nodes for level k
# n  := total number of concepts
# this metric is in concept space

# Assume here that fj is 1, and only 1 fj,
# eqn simplifies to: summation(Sk*bk/n)

def variety_shah_simplified(conceptTree):
    ''' Implements Shah et al.'s conceptual variety metric:
        "Metrics for measuring ideation effectiveness"
        doi:10.1016/S0142-694X(02)00034-0

        Takes a concept tree as input and returns a numerical variety score
    '''
    assert conceptTree.spaceType == "concept", "tree argument not in concept space, please convert"

    # level weights from highest to lowest levels of abstraction
    if(conceptTree.numLevels == 4):
        level_weights = [10., 6., 3., 1.]
    else:
        level_weights = np.linspace(10.0, 1.0, conceptTree.numLevels)
    variety = 0.0

    for iter_level in xrange(0,len(level_weights)):
        Sk = level_weights[iter_level]
        bk = np.count_nonzero(conceptTree.set[iter_level])
        variety += Sk*bk
    variety /= conceptTree.numConcepts
    return variety

# Verhaegen's Pave Herfindahl variety metric: Vk = 10 * (1 / (n * summation(pi)))
# Idea-space metric (# of nodes versus # of trees)
# This metric calculates variety on a per-level basis (level number should be an argument)
# n := total number of ideas
# bk := # of nodes for level k
# pi := probability of each node i in summation from 1 to bk (for each node in level, basically)
# Herfindahl index is calculated for each level, it is the sum of the square of pi for each node

def variety_verhaegen(conceptTree, level):
    ''' Implements Verhaegen et al.'s conceptual variety metric:
        https://github.com/paularmand/mIDGenes

        Takes a concept tree as input and returns a numerical variety score
    '''
    assert conceptTree.spaceType == "idea", "tree argument not in idea space, please convert"
    herfindahl = 0
    for node in conceptTree.set[level]:
        probability_of_node = node / conceptTree.numConcepts
        herfindahl += probability_of_node * probability_of_node

    return 10 / (conceptTree.numConcepts * herfindahl)

def variety_verhaegen_tree(conceptTree,tree_depth=4):
    va = 0.0
    for i in xrange(0,tree_depth):
        va += variety_verhaegen(conceptTree,i)
    # Averages over tree depth to provide a normalized score
    return va/tree_depth

### End Ported Functions                ###

def noisyCompareTrees(A,B,percentError,metric):
    ''' Compares two concept trees, A and B, and returns 1, -1, or 0 depending
        on which concept is greater.
        PercentError controls the amount of additional random noise which is added to both concepts.
        metric selects which variety function should be used to simulate users
    '''
    if metric == 'verhaegen':
        vfunc = variety_verhaegen_tree
    else:
        vfunc = variety_shah_simplified

    # Get the ground truth variety
    va = vfunc(A)
    vb = vfunc(B)

    # Calculate the ground truth label for this comparison
    if(va > vb):
        ground_truth = 1
    elif(va < vb):
        ground_truth = -1
    else:
        ground_truth = 0

    # Add error to the measurements to simulate noise
    nva = va + np.random.randn() * percentError
    nvb = vb + np.random.randn() * percentError

    # Produce the noisy training data
    if(nva > nvb):
        return (1,ground_truth)
    elif(nva < nvb):
        return (-1,ground_truth)
    else:
        return (0,ground_truth)

def calcTreeRho(conceptTree, coverType = "set"):
    ''' Applying the submodular transform across each level of the tree consists
        of summing the submodular function across each sub branches of the tree.
    '''
    l = len(conceptTree.set)
    returnVector = np.array([])
    for i in xrange(0,l):
        returnVector = np.hstack([returnVector, rho_func(conceptTree.set[i], coverType)])
    return returnVector

def rho_func(vector, coverType = "set") :
    ''' Transforms a given vector using a submodular set transformation, given
        by coverType.
    '''
    sum = 0.
    # theta represents a hyperparameter that could be optimized in the future
    theta = .75
    i = 0
    for v in vector:
        rv = 0.
        if(coverType == "set"):
            if(v > 0):
                rv = 1.
        elif(coverType == "prob"):
            theta = .75
            rv = 1. - np.exp(-theta*v)
        elif(coverType == "log"):
            theta = 1.5
            rv = np.log(theta*v + 1)
        elif(coverType == "mod"):
            if(v > 0):
                rv = v
        else:
            raise SyntaxError("wrong cover type in rho_func")
        sum += rv
        i += 1
    return sum

def generate_random_trees(numLevels = 4,numConceptsPerTree = 10, numTrees = 1000):
    ''' Randomly constructs sets of concept trees for use during testing'''
    treeArray = []
    for i in xrange(0,numTrees):
        treeArray.append(genRandConceptTree(numConceptsPerTree))
    return treeArray

def remove_zero_training_labels(X,Y,Ytrue):
    ''' Since the logistic regression is just a binary classifier, we throw out
        any comparisons where the variety is equal. This reduces the amount of
        training data somewhat, but not by much. Future work involves improving the
        model to handle the equal variety case.'''
    ind = np.where(Y[:,0]==0)[0]
    Y=np.delete(Y,ind,axis=0)
    Ytrue=np.delete(Ytrue,ind,axis=0)
    X=np.delete(X,ind,axis=0)
    return X,Y,Ytrue

def generate_comparison_data(numConceptsPerTree = 10, numComparisons = 1000,
                             numLevels = 4, cover_type = None, metric = "shah", E = [0.0]):
    ''' Generates two data matrices for training the model.
        X is a numComparisons by numFeatures matrix
        Y is a numComparisons by len(E) matrix
           - Each coefficient in E corresponds to one column of Y. This way you
             can use different columns of Y to test different error amounts
    '''
    if(metric == "shah"):
        #compareFunc = compareTreesShah
        #noisyCompareFunc = noisyCompareTreesShah
        spaceType = "concept"
        if(not cover_type):
            cover_type = "set"
    elif(metric == "verhaegen"):
        #compareFunc = compareTreesVerhaegen
        #noisyCompareFunc = noisyCompareTreesVerhaegen
        spaceType = "ideas"
        if(not cover_type):
            cover_type = "prob"

    # Time to build the data arrays
    numRho = numLevels
    num_error_coeffs = len(E)
    # Preallocating Array space
    X = np.zeros([numComparisons, numRho])
    Y = np.zeros([numComparisons,num_error_coeffs])
    Ytrue = np.zeros([numComparisons,num_error_coeffs])
    # Generate the data
    for i in xrange(0,numComparisons):
        # Go through each pair and determine the feature vector and the ratings
        A = genRandConceptTree(numConceptsPerTree, numLevels = numLevels)
        B = genRandConceptTree(numConceptsPerTree, numLevels = numLevels)
        if spaceType == "concept":
            A.convertToConceptSpace()
            B.convertToConceptSpace()
        # Calculate submodular feature vector:
        X[i] = calcTreeRho(A, cover_type) - calcTreeRho(B, cover_type)
        # Calculate training votes
        for j in xrange(0,num_error_coeffs):
            Y[i][j],Ytrue[i][j] = noisyCompareTrees(A,B,E[j],metric)

    # Normalizes the matrix - not strictly necessary, but improves performance
    X = X/ float(numConceptsPerTree)

    # Remove any 0 training cases to binarize the data
    X,Y,Ytrue = remove_zero_training_labels(X,Y,Ytrue)

    return X,Y,Ytrue

def runSklearn(X,Y,Ytrue,numTrain,numRetest = 5):
    ''' Conducts actual model inference using Scikit-learn's logistic regression
    '''
    interceptOn = False

    # Split the dataset up into segments that have numTrain # of training
    # examples. Rerun the experiment numRetest number of times, for robustness
    # We set test_size to a constant only for consistency across experiment cases
    n = len(X)
    datasamples = cross_validation.ShuffleSplit(n,
                                                n_iter=numRetest,
                                                test_size=7500,
                                                train_size=numTrain,
                                                random_state=0)

    tolerance = 0.0001  # Specifies final covergence of coefficients
    C = 1.    # Specifies the strength of the regularization,
              # the smaller it is the bigger is the regularization.
              # Currently this is not optimized, though it could be in the future.

    intercept = 0.0001
    # if interceptOn is true, enable default intercept = 1.0
    clf_l1_LR = LogisticRegression(C=C, penalty='l1', tol=tolerance, fit_intercept=interceptOn, intercept_scaling = intercept)
    # If you would prefer to try L2 regularized logistic regression, you can
    # uncomment the below line. For instances where you are unsure of the weight
    # distribution, L2 would be the correct choice. Since we are expecting different
    # weight distributions across the features, we use L1 regularization.
    #clf_l2_LR = LogisticRegression(C=C, penalty='l2', tol=tolerance, fit_intercept=interceptOn, intercept_scaling = intercept)

    # Run a cross-validated estimator over the L1 Logistic Regression
    numErr = len(Y[0])
    errScores = []
    gterrScores = []
    for i in xrange(0,len(Y[0])):
        cv_scores = []
        gtcv_scores = []
        y = Y[:,i]
        ytrue = Ytrue[:,i]
        for train_index, test_index in datasamples:
            X_train, X_test = X[train_index], X[test_index]
            y_train, y_test = y[train_index], y[test_index]
            ytrue_test = ytrue[test_index]
            clf_l1_LR.fit(X_train,y_train)
            cv_scores.append(clf_l1_LR.score(X_test,y_test))
            gtcv_scores.append(clf_l1_LR.score(X_test,ytrue_test))
        cv_scores = np.array(cv_scores)
        gtcv_scores = np.array(gtcv_scores)
        errScores.append((cv_scores.mean(), cv_scores.std()))
        gterrScores.append((gtcv_scores.mean(), gtcv_scores.std()))
    return errScores, gterrScores

### Older example and test code which might be helpful in understanding some of
### The fundamental functions

def examples():
    '''
        Demonstrate how to use the ConceptTree class and the variety model to
        predict how random trees will be used for training and prediction.
    '''
    numConcepts = 5

    print "* start test"
    print "** testing idea space generation..."
    for i in xrange(0,5):
        print "*** generating",numConcepts,"concepts into a tree..."
        concepts = genRandConceptTree(numConcepts)
        shah_score = variety_shah_simplified(concepts)
        print "random concept set:\n", concepts.printSet()
        print "shah's variety score on set: ", shah_score

    numComparisons = 10
    print "** testing tree pair comparison..."
    print "*** generating and comparing", numComparisons, "trees..."

    compareVector = np.zeros([numComparisons])
    for i in xrange(0,numComparisons):
        (A,B) = genTwoTrees()
        compareVector[i] = compareTreesShah(A,B)

    print "results vector: ", compareVector

    print "** testing rho function..."

    print "*** set cover"
	# should compare tree, not compareVector
    rho = rho_func(compareVector, "set")
    print rho

    print "*** probabilistic cover"
    rho = rho_func(compareVector, "prob")
    print rho

    print "*** logarithmic cover"
    rho = rho_func(compareVector, "log")
    print rho

def noisyCompareTreesShah(A, B, percentError):
    va = variety_shah_simplified(A)
    va += np.random.randn() * percentError

    vb = variety_shah_simplified(B)
    vb += np.random.randn() * percentError

    if(va > vb):
        return 1
    elif(va < vb):
        return -1
    else:
        return 0

def compareTreesShah(A, B):

    va = variety_shah_simplified(A)
    vb = variety_shah_simplified(B)

    if(va > vb):
        return 1
    elif(va < vb):
        return -1
    else:
        return 0

def compareTreesVerhaegen(A, B):
    va = 0.0
    vb = 0.0
    for i in xrange(0,4):
        va += variety_verhaegen(A,i)
        vb += variety_verhaegen(B,i)

    if(va > vb):
        return 1
    elif(va < vb):
        return -1
    else:
        return 0

def noisyCompareTreesVerhaegen(A, B, percentError):
    va = 0.0
    vb = 0.0
    for i in xrange(0,4):
        va += variety_verhaegen(A,i)
        vb += variety_verhaegen(B,i)

    va += np.random.randn() * percentError
    vb += np.random.randn() * percentError

    if(va > vb):
        return 1
    elif(va < vb):
        return -1
    else:
        return 0


text:
import pyodbc
import psycopg2
import pymysql

CONNECTION_DRIVER_CHOICES = (
    ('mysql', 'MySQL'),
    ('pgsql', 'PostgreSQL'),
    ('mssql', 'Microsoft SQL Server'),
)

def get_column_type(type):
    if type in [str, 'character varying', 'text', 'varchar']:
        return 'String'
    elif type in [int, float, 'integer', 'bigint', 'int', 'smallint', 'tinyint', 'real']:
        return 'Number'
    elif type in ['date', 'timestamp', 'timestamp without time zone']:
        return 'Date/Time'
    elif type in [bool, 'boolean']:
        return 'Boolean'
    if type in [bytearray, bytes, 'bytea']:
        return 'Binary'
    else:
        # return 'UNDEFINED'
        return type

class MyDB(object):
    _db_connection = None
    _db_cur = None
    con_string = ""

    def __init__(self, dataset):
        if dataset.connection_driver == 'mysql':
            self._db_connection = pymysql.connect(host=dataset.connection_server,
                                                  port=dataset.connection_port,
                                                  user=dataset.connection_user,
                                                  passwd=dataset.connection_password,
                                                  db=dataset.connection_database)
        elif dataset.connection_driver == 'pgsql':
            con_string = 'host=%s port=%s user=%s password=%s dbname=%s' % (dataset.connection_server,
                                                                            dataset.connection_port,
                                                                            dataset.connection_user,
                                                                            dataset.connection_password,
                                                                            dataset.connection_database)
            self._db_connection = psycopg2.connect(con_string)

        elif dataset.connection_driver == 'mssql':
            # con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % ('sqlserverdatasource',
            #                                                                  dataset.connection_user,
            #                                                                  dataset.connection_password,
            #                                                                  dataset.connection_database)
            con_string = 'DRIVER=FreeTDS;SERVER=%s;PORT=%s;UID=%s;PWD=%s;DATABASE=%s;' % \
                         (dataset.connection_server,
                          dataset.connection_port,
                          dataset.connection_user,
                          dataset.connection_password,
                          dataset.connection_database)
            self._db_connection = pyodbc.connect(con_string)

        self._db_cur = self._db_connection.cursor()

    def query(self, query, params=None):
        if params:
            self._db_cur.execute(query, params)
        else:
            self._db_cur.execute(query)
        return self._db_cur

    def __del__(self):
        self._db_connection.close()

    def __str__(self):
        self.con_string

def is_connecting(dataset):
    try:
        db = MyDB(dataset)
        results = db.query("SELECT VERSION()").fetchone()
        if results:
            return True
    except:
        return False

    return False

def get_table_list(dataset):
    db = MyDB(dataset)
    if dataset.connection_driver == 'mssql':
        rows = db.query('SELECT table_name FROM information_schema.tables').fetchall()
    elif dataset.connection_driver == 'pgsql':
        rows = db.query("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';").fetchall()
    tables = []
    for row in rows:
        tables += [row[0]]
    tables.sort()
    return tables

# def get_table_list(dataset):
#     if dataset.connection_driver == 'SQLServer':
#     #if True:
#         dsn = 'sqlserverdatasource'
#         user = 'sinapse'
#         password = '51n4p53dbmS'
#         database = 'SISTEMA_ACADEMICO'
#
#         con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
#         try:
#             cnxn = pyodbc.connect(con_string)
#         except:
#             return []
#
#         cursor = cnxn.cursor()
#         cursor.execute('SELECT * FROM information_schema.tables')
#         rows = cursor.fetchall()
#         tables = []
#         for row in rows:
#             tables += [row[2]]
#     else:
#         tables = ['bananaa', 'maça', 'abacaxi', 'beterraba']
#     tables.sort()
#     return tables

def get_column_list(datatable):
    db = MyDB(datatable.data_set)
    columns = []
    if datatable.data_set.connection_driver == 'mssql':
        descriptions = db.query("SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='%s';" % datatable.name)
        for desc in descriptions:
                columns += [(desc[0], get_column_type(desc[1]))]
    elif datatable.data_set.connection_driver == 'pgsql':
        descriptions = db.query("select column_name, data_type from information_schema.columns where table_name='%s';" % datatable.name)
        for desc in descriptions:
            columns += [(desc[0], get_column_type(desc[1]))]
    columns.sort()
    return columns

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace STAGE\IndexBundle\Controller;

use STAGE\IndexBundle\STAGEIndexBundle;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

// Accés à la base de données
use STAGE\IndexBundle\Entity\ProjectEntity;

// gestion formulaire
use STAGE\IndexBundle\Form\ProjectEntityType;

class ProjectsController extends Controller
{

	// Affichage de la page Projects : Vues Index qui contient vues search et Liste
	public function projectsAction(request $request)
	{

		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit

		//$limit <==> $_GET["page_limit"]
		$limit = $request->query->get( 'page_limit' );

		// si la valeur n'existe pas, on recupère la valeur qui a été enregistrée le coup d'avant dans la variable Session
		if(!$limit){
			//$page <===> $_SESSION["page"]
			$limit = $session->get("page_limit");
			 if ($limit != 0) { $limit=$limit;}
		}

		// au sinon, elle existe et on la rentre dans la variable Session
		$session->set("page_limit",$limit);

		//$page <==> $_GET["page"]
		$page = $request->query->get( "page" );
		if(!$page){
			//$page <===> $_SESSION["page"]
			$page = $session->get("page");
		}
		$session->set("page",$page);

		// partie correspondant à la première version du moteur de recherche avec deux champs
		/* //$title <==> $_GET["title"]
		$title = $request->query->get( "title" );
		if(!$title)   {
			//$title <===> $_SESSION["title"]
			//$title = $session->get("title");
			$title='';
		}
		$session->set("title",$title); */

		//$content <==> $_GET["content"]
		$content = $request->query->get( "content" );
		if(!$content){
			//$content <===> $_SESSION["content"]
			//$content = $session->get("content");

			 $content='';
		}
		$session->set("content",$content);

		if( !$page) {
			$page = 1;
		}

		if($page <= 0){
			$page = 1;
		}

		// On appelle le repository dans lequel se trouve toutes les informations de notre DB

		$repository = $this
			->getDoctrine()
			->getManager()
			->getRepository('STAGEIndexBundle:ProjectEntity')
		;
		// préparation requête
		$em   = $this->getDoctrine()->getManager();
		$qb   = $em->getRepository( 'STAGEIndexBundle:ProjectEntity' )->createQueryBuilder( 'm' );
		$qb2  = $em->getRepository( 'STAGEIndexBundle:ProjectEntity' )->findAll();
		$projects = $qb ->where( '1 = 1' )
		;

		// fichier contenant requête à la DB
		include ("requestDB.php" );

		$result = $projects->getQuery()->getResult();

		// ->>>>  Combien avons-nous d'élements qui répondent à notre recherche ?????
		$counter = count($result);

		// calcul de la dernière page
		$last = ($limit != 0) ? ceil($counter / $limit) : 1;

		$session->set("last",$last);

		if ($last==0 && $limit!=0) {
			$last=1;
		}

		// vérification en cas de changement d'élements par page et que l'on dépasse le nbre d"élément dans la DB
		// on revient sur la dernière page

		if (($page * $limit) > $counter) {
			$page = $last;
		}

		// Fonctionnalité Pagination
		// cas où $limit n'est ni nul ni égal à 0, on effectue le calcul

		if ($limit != NULL && $limit != 0) {
			$projects->setMaxResults($limit)->setFirstResult(($page - 1) * $limit);
		} else {
			$page = 1;
		}

		// on récupère les resultats du Query
		$Projects = $projects->getQuery()->getResult();

		//nbre de characteres provenant du champ de recherche
		$nbrchar=strlen($content);

		// Au sinon, on continue et on affiche la vue associée en faisant passer en paramètres les informations récupérées de la DB
		return $this->render('STAGEIndexBundle:Projects:index.html.twig',
			array( 'Projects' => $Projects,
			       'Page'    => $page,
			       'offset'  => $limit,
			       'count'   => $counter,
			       'last'    => $last,
			       /* 'title'   => $title, */ /* appartient à la premiere version du moteur de recherche */
			       'content' => $content,
			)
		);
	}

	// Méthode qui sert pour calculer les requêtes et afficher que la liste des résultats
	public function listeAction(request $request)
	{
		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit qui vient de la vue "Liste"

		//$limit <==> $_GET["page_limit"]
		$limit = $request->query->get( 'page_limit' );

		// si la valeur n'existe pas, on recupère la valeur qui a été enregistrée le coup d'avant dans la variable Session
		if(!$limit){
			//$page <===> $_SESSION["page"]
			$limit = $session->get("page_limit");

			if ($limit != 0) { $limit=0;}
		}

		// au sinon, elle existe et on la rentre dans la variable Session
		$session->set("page_limit",$limit);

		//$page <==> $_GET["page"]
		$page = $request->query->get( "page" );
		if(!$page){
			//$page <===> $_SESSION["page"]
			$page = $session->get("page");
		}
		$session->set("page",$page);

		// partie correspondant à la première version du moteur de recherche avec deux champs
		/* //$title <==> $_GET["title"]
		$title = $request->query->get( "title" );
		if(!$title)   {
			//$title <===> $_SESSION["title"]
			//$title = $session->get("title");
			$title='';
		}
		$session->set("title",$title); */

		//$content <==> $_GET["content"]
		$content = $request->query->get( "content" );
		if(!$content){
			//$content <===> $_SESSION["content"]
			//$content = $session->get("content");

			$content='';
		}
		$session->set("content",$content);

		if( !$page) {
			$page = 1;
		}

		if($page <= 0){
			$page = 1;
		}

		// On appelle le repository dans lequel se trouve toutes les informations de notre DB

		$repository = $this
			->getDoctrine()
			->getManager()
			->getRepository('STAGEIndexBundle:ProjectEntity')
		;
		// préparation acces à la DB
		$em   = $this->getDoctrine()->getManager();
		$qb   = $em->getRepository( 'STAGEIndexBundle:ProjectEntity' )->createQueryBuilder( 'm' );
		$qb2  = $em->getRepository( 'STAGEIndexBundle:ProjectEntity' )->findAll();
		$projects = $qb ->where( '1 = 1' )
		;

		// fichier contenant requête à la DB
		include ("requestDB.php" );

		$result = $projects->getQuery()->getResult();

		// ->>>>  Combien avons-nous d'élements qui répondent à notre recherche ?????
		$counter = count($result);

		// calcul de la dernière page
		$last = ($limit != 0) ? ceil($counter / $limit) : 1;

		if ($last==0 && $limit!=0) {
			$last=1;
		}

		// vérification en cas de changement d'élements par page et que l'on dépasse le nbre d"élément dans la DB
		// on revient sur la dernière page

		if (($page * $limit) > $counter) {
			$page = $last;
		}

		// Fonctionnalité Pagination
		// cas où $limit n'est ni nul ni égal à 0, on effectue le calcul

		if ($limit != NULL && $limit != 0) {
			$projects->setMaxResults($limit)->setFirstResult(($page - 1) * $limit);
		} else {
			$page = 1;
		}

		// on récupère les resultats du Query
		$Projects = $projects->getQuery()->getResult();

		//nbre de characteres provenant du champ de recherche
		$nbrchar=strlen($content);

		// Au sinon, on continue et on affiche la vue associée en faisant passer en paramètres les informations récupérées de la DB
		return $this->render('STAGEIndexBundle:Projects:liste.html.twig',
			array( 'Projects' => $Projects,
			       'Page' => $page,
			       'offset'=> $limit,
			       'count' => $counter,
			       'last' => $last,
			       'title' => $title,
			       'content' => $content,
			       'nbrchars' =>$nbrchar,
			)
		);
	}

	// Méthode qui sert pour la partie "Moteur de Recherche"
	public function searchAction(request $request)
	{
		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit qui vient de la vue "Liste"

		//$limit <==> $_GET["page_limit"]
		$limit = $request->query->get( 'page_limit' );

		// si la valeur n'existe pas, on recupère la valeur qui a été enregistrée le coup d'avant dans la variable Session
		if(!$limit){
			//$page <===> $_SESSION["page"]
			$limit = $session->get("page_limit");

			if ($limit != 0) { $limit=0;}
		}

		// au sinon, elle existe et on la rentre dans la variable Session
		$session->set("page_limit",$limit);

		//$page <==> $_GET["page"]
		$page = $request->query->get( "page" );
		if(!$page){
			//$page <===> $_SESSION["page"]
			$page = $session->get("page");
		}
		$session->set("page",$page);

		// partie correspondant à la première version du moteur de recherche avec deux champs
		/* //$title <==> $_GET["title"]
		$title = $request->query->get( "title" );
		if(!$title)   {
			//$title <===> $_SESSION["title"]
			//$title = $session->get("title");
			$title='';
		}
		$session->set("title",$title); */

		//$content <==> $_GET["content"]
		$content = $request->query->get( "content" );
		if(!$content){
			//$content <===> $_SESSION["content"]
			//$content = $session->get("content");
			 $content='';
		}
		$session->set("content",$content);

		if( !$page) {
			$page = 1;
		}

		if($page <= 0){
			$page = 1;
		}

		// On appelle le repository dans lequel se trouve toutes les informations de notre DB

		$repository = $this
			->getDoctrine()
			->getManager()
			->getRepository('STAGEIndexBundle:ProjectEntity')
		;
		// préparation acces DB
		$em   = $this->getDoctrine()->getManager();
		$qb   = $em->getRepository( 'STAGEIndexBundle:ProjectEntity' )->createQueryBuilder( 'm' );
		$qb2  = $em->getRepository( 'STAGEIndexBundle:ProjectEntity' )->findAll();
		$projects = $qb ->where( '1 = 1' )
		;

		// fichier contenant requête à la DB
		include ("requestDB.php" );

		$result = $projects->getQuery()->getResult();

		// ->>>>  Combien avons-nous d'élements qui répondent à notre recherche ?????
		$counter = count($result);

		// calcul de la dernière page
		$last = ($limit != 0) ? ceil($counter / $limit) : 1;

		if ($last==0 && $limit!=0) {
			$last=1;
		}

		// vérification en cas de changement d'élements par page et que l'on dépasse le nbre d"élément dans la DB
		// on revient sur la dernière page

		if (($page * $limit) > $counter) {
			$page = $last;
		}

		// Fonctionnalité Pagination
		// cas où $limit n'est ni nul ni égal à 0, on effectue le calcul

		if ($limit != NULL && $limit != 0) {
			$projects->setMaxResults($limit)->setFirstResult(($page - 1) * $limit);
		} else {
			$page = 1;
		}

		// on récupère les resultats du Query
		$Projects = $projects->getQuery()->getResult();

		//nbre de characteres provenant du champ de recherche
		$nbrchar=strlen($content);

		// Au sinon, on continue et on affiche la vue associée en faisant passer en paramètres les informations récupérées de la DB
		return $this->render('STAGEIndexBundle:Projects:search.html.twig',
			array( 'Projects' => $Projects,
			       'Page' => $page,
			       'offset'=> $limit,
			       'count' => $counter,
			       'last' => $last,
			       'title' => $title,
			       'content' => $content,
			       'nbrchars' =>$nbrchar,

			)
		);
	}

	// Appel d'un formulaire et insertion en base de données
	public function newAction(Request $request)
	{
		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit, la dernière page en cours et la valeur recherché dans "content"

		$limit    = $session->get("page_limit");
		$last     = $session->get("last");
		$content  = $session->get("content");

		// On crée un objet vide Project Entity (sans titre, sans date, sans content)
		$project = new ProjectEntity();

		// On rempli le formulaire ProjectEntityType avec les valeurs $project (projTitle = $project->getTitle() ...)
		$form= $this->get('form.factory')->create(new ProjectEntityType,$project);

		if ($form->handleRequest($request)->isValid()) {
			$em = $this->getDoctrine()->getManager();
			$em->persist($project);
			$em->flush();

			$request->getSession()->getFlashBag()->add('project', 'project saved.');

			return $this->redirect($this->generateUrl('projects_index_homepage',
				array(
					'page_limit' => $limit,
					'content'    => $content,

					// une fois que l'on a rentré les infos, on va sur la dernière page
					'page'       => $last,
				))

			);

		}

		return $this->render('STAGEIndexBundle:Projects:new.html.twig', array(
			'form' => $form->createView(),
		));
	}

	// Entrée forcée d'informations dans la DB
	public function new2Action(Request $request)
	{

		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit, la derniere page encours et la valeur de recherche

		//$limit <==> $_GET["page_limit"]

		$limit   = $session->get("page_limit");
		$last    = $session->get("last");
		$content = $session->get("content");

		// Création de l'entité
		$project = new ProjectEntity();

		$project -> setProjDate(new \Datetime());
		$project -> setProjTitle('Project Template Name');
		$project -> setProjDescr('Project Template Content');

		// On récupère l'EntityManager
		$doctrine= $this-> getDoctrine();
		$em = $doctrine -> getManager();

		// Étape 1 : On « persiste » l'entité
		$em->persist($project);

		// Étape 2 : On « flush » tout ce qui a été persisté avant
		$em->flush();

		// on se redirige vers la liste des éléménts
		return $this->redirect($this->generateUrl('projects_index_homepage',
			array(
				'page_limit' => $limit,

				// une fois que l'on a rentré les infos, on veut aller sur la dernière page
				'page'       => $last,
			))

		);
	}

	public function modifyAction(Request $request,$id)
	{
		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit, la page en cours et le contenu du champ de recherche

		$limit    = $session->get("page_limit");
		$page     = $session->get("page");

		// si on a effectué une recherche, on recupere les mots clés pour pouvoir revenir sur la page de recherche avec ces mots cles
		if ($session->get("content")) {

			$content = $session->get("content");
			$session->set("content",$content);

		} else {
			// sinon on n'a pas fait de recherche particulière et on veut afficher la totalité des élements de la base de données.
			$content='';
		}

		$em = $this->getDoctrine()->getManager();

		// On recupère un objet remplis Project Entity (abec titre, avec date, avec content)
		$project = $em-> getRepository('STAGEIndexBundle:ProjectEntity')->find($id);

		// On rempli le formulaire ProjectEntityType avec les valeurs $project (projTitle = $project->getTitle() ...)
		$form= $this->get('form.factory')->create(new ProjectEntityType,$project);

		if ($form->handleRequest($request)->isValid()) {
			$em = $this->getDoctrine()->getManager();
			$em->persist($project);
			$em->flush();

			$request->getSession()->getFlashBag()->add('project', 'project modified.');

			return $this->redirect($this->generateUrl('projects_index_homepage',
				array(
						'page'   => $page,
				    	'offset' => $limit,

						//permet de revenir sur la page avec la recherche en cours
						'content' => $content,
				)
			));
		}

		return $this->render('STAGEIndexBundle:Projects:modify.html.twig', array(
			'form' => $form->createView(),
		));
	}

	// Effacement d'une ligne dans la DB
	public function deleteAction(Request $request,$id)
	{
		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit, la page encours et le contenu du champ recherche

		$limit   = $session->get("page_limit");
		$page    = $session->get("page");
		$content = $session->get("content");

		//récupération de l'entityManager
		$em = $this->container->get('doctrine')->getEntityManager();

		// on récupére l'id qui nous interresse
		$project = $em->find('STAGEIndexBundle:ProjectEntity', $id);

		// si le projet demandé n'existe pas
		if (!$project)
		{
			return $this->render('STAGEIndexBundle:Projects:delete.html.twig',
				array( 'info'=> "doesn't exist", ));
		}

		// au sinon, il existe et on le supprime
		$em->remove($project);

		// on valide
		$em->flush();

		// on se redirige vers la page projets
		return $this->redirect($this->generateUrl('projects_index_homepage',
			array(
				'page'    => $page,
				'offset'  => $limit,

				//permet de revenir sur la page avec la recherche en cours
				'content' => $content,

			)
		));
	}

	public function viewAction(Request $request,$id)
	{

		//$session <===> $_SESSION[]
		$session = $request->getSession();

		// on récupère en get la valeur page_limit, la page encours et le contenu du champ recherche

		$limit   = $session->get("page_limit");
		$page    = $session->get("page");

		// si on a effectué une recherche, on recupere les mots clés pour pouvoir revenir sur la page de recherche avec ces mots cles
		if ($session->get("content")) {
			$content = $session->get("content");
			$session->set("content",$content);
		}else {
			// sinon on n'a pas fait de recherche particulière et on veut afficher la totalité des élements de la base de données.
			$content='';
		}

		$doctrine= $this->getDoctrine();
		$em = $doctrine -> getManager();

		// On récupère l'id entré avec la méthode find() dans le repository lié à notre Entité
		$project2 = $em->getRepository('STAGEIndexBundle:ProjectEntity')->find($id);

		return $this->render('STAGEIndexBundle:Projects:view.html.twig',
			array(
				'project' => $project2,

				//permet de revenir sur la page avec la recherche en cours
				'content' => $content,
			)

		);
	}

}


text:
package synergynet.table.apps.conceptmap.graphcomponents.nodes;

import java.net.URL;

import synergynet.contentsystem.ContentSystem;
import synergynet.contentsystem.items.ImageTextLabel;
import synergynet.table.apps.conceptmap.utility.GraphManager;

public class ImageTextNode extends EditableQuadNode{

	protected ImageTextLabel imageTextLabel;

	public ImageTextNode(ContentSystem contentSystem, GraphManager gManager) {
		super(contentSystem, gManager);
		imageTextLabel = (ImageTextLabel) contentSystem.createContentItem(ImageTextLabel.class);
		this.setNodeContent(imageTextLabel);
	}

	public void setText(String text){
		imageTextLabel.setCRLFSeparatedString(text);
		updateNode();
	}

	public String getText(){
		String text = "";
		for(String line: imageTextLabel.getLines())
			text+=line+"\n";
		if(text != null && !text.equals(""))
			text = text.substring(0, text.lastIndexOf("\n"));
		return text;
	}

	public void setImageResource(URL imageResource){
		imageTextLabel.setImageInfo(imageResource);
	}

	public ImageTextLabel getImageTextLabel(){
		return imageTextLabel;
	}
}


text:
using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using FileSharperCore;

namespace FileSharperUIHelpers
{
    public class TypeNameToConditionConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
            return ConditionCatalog.Instance.Conditions.Where(x => x.GetType().FullName == (string)value).FirstOrDefault();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value?.GetType().FullName;
        }
    }
}


text:
export function makeBBox(coords) {
    return `ST_SetSRID(ST_MakeBox2D(ST_Point(${coords[0]}, ${coords[1]}), ST_Point(${coords[2]}, ${coords[3]})), 4326)`;
}

export function inBBox(coords) {
    return `the_geom && ${makeBBox(coords)}`;
}

export function fromCenterOfBBox(coords) {
    return `ST_Distance(the_geom, ST_Centroid(${makeBBox(coords)}))`;
}


text:
require 'cases/helper'
require 'models/developer'
require 'models/owner'
require 'models/pet'
require 'models/toy'
require 'models/car'

class TimestampTest < ActiveRecord::TestCase
  fixtures :developers, :owners, :pets, :toys, :cars

  def setup
    @developer = Developer.first
    @previously_updated_at = @developer.updated_at
    @car = Car.first
  end

  def test_saving_a_changed_record_updates_its_timestamp
    @developer.name = "Jack Bauer"
    @developer.save!

    assert_not_equal @previously_updated_at, @developer.updated_at
  end

  def test_saving_a_unchanged_record_doesnt_update_its_timestamp
    @developer.save!

    assert_equal @previously_updated_at, @developer.updated_at
  end

  def test_touching_a_record_updates_its_timestamp
    previous_salary = @developer.salary
    @developer.salary = previous_salary + 10000
    @developer.touch

    assert_not_equal @previously_updated_at, @developer.updated_at
    assert_equal previous_salary + 10000, @developer.salary
    assert @developer.salary_changed?, 'developer salary should have changed'
    assert @developer.changed?, 'developer should be marked as changed'
    @developer.reload
    assert_equal previous_salary, @developer.salary
  end

  def test_saving_when_record_timestamps_is_false_doesnt_update_its_timestamp
    Developer.record_timestamps = false
    @developer.name = "John Smith"
    @developer.save!

    assert_equal @previously_updated_at, @developer.updated_at
  ensure
    Developer.record_timestamps = true
  end

  def test_touching_a_different_attribute
    previously_created_at = @developer.created_at
    @developer.touch(:created_at)

    assert !@developer.created_at_changed? , 'created_at should not be changed'
    assert !@developer.changed?, 'record should not be changed'
    assert_not_equal previously_created_at, @developer.created_at
    assert_not_equal @previously_updated_at, @developer.updated_at
  end

  def test_touch_a_record_without_timestamps
    assert_nothing_raised { @car.touch }
  end

  def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at
    pet   = Pet.first
    owner = pet.owner
    previously_owner_updated_at = owner.updated_at

    pet.name = "Fluffy the Third"
    pet.save

    assert_not_equal previously_owner_updated_at, pet.owner.updated_at
  end

  def test_destroying_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at
    pet   = Pet.first
    owner = pet.owner
    previously_owner_updated_at = owner.updated_at

    pet.destroy

    assert_not_equal previously_owner_updated_at, pet.owner.updated_at
  end

  def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute
    Pet.belongs_to :owner, :touch => :happy_at

    pet   = Pet.first
    owner = pet.owner
    previously_owner_happy_at = owner.happy_at

    pet.name = "Fluffy the Third"
    pet.save

    assert_not_equal previously_owner_happy_at, pet.owner.happy_at
  ensure
    Pet.belongs_to :owner, :touch => true
  end

  def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent
    Pet.belongs_to :owner, :counter_cache => :use_count, :touch => true

    pet = Pet.first
    owner = pet.owner
    owner.update_attribute(:happy_at, (time = 3.days.ago))
    previously_owner_updated_at = owner.updated_at

    pet.name = "I'm a parrot"
    pet.save

    assert_not_equal previously_owner_updated_at, pet.owner.updated_at
  ensure
    Pet.belongs_to :owner, :touch => true
  end

  def test_touching_a_record_touches_parent_record_and_grandparent_record
    Toy.belongs_to :pet, :touch => true
    Pet.belongs_to :owner, :touch => true

    toy = Toy.first
    pet = toy.pet
    owner = pet.owner

    owner.update_attribute(:updated_at, (time = 3.days.ago))
    toy.touch

    assert_not_equal time, owner.updated_at
  ensure
    Toy.belongs_to :pet
  end
end


text:
<?php

namespace SearchApi\Models;

/**
 * Class Synonym - This will be the class that defines how synonyms are structured
 */
class Synonym {
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include "arrow/util/future.h"

#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <numeric>

#include "arrow/util/checked_cast.h"
#include "arrow/util/logging.h"
#include "arrow/util/thread_pool.h"
#include "arrow/util/tracing_internal.h"

namespace arrow {

using internal::checked_cast;

class ConcreteFutureImpl : public FutureImpl {
 public:
  void DoMarkFinished() { DoMarkFinishedOrFailed(FutureState::SUCCESS); }

  void DoMarkFailed() { DoMarkFinishedOrFailed(FutureState::FAILURE); }

  void CheckOptions(const CallbackOptions& opts) {
    if (opts.should_schedule != ShouldSchedule::Never) {
      DCHECK_NE(opts.executor, nullptr)
          << "An executor must be specified when adding a callback that might schedule";
    }
  }

  void AddCallback(Callback callback, CallbackOptions opts) {
    CheckOptions(opts);
    std::unique_lock<std::mutex> lock(mutex_);
#ifdef ARROW_WITH_OPENTELEMETRY
    struct SpanWrapper {
      void operator()(const FutureImpl& impl) {
        auto scope = ::arrow::internal::tracing::GetTracer()->WithActiveSpan(active_span);
        std::move(func)(impl);
      }
      Callback func;
      opentelemetry::nostd::shared_ptr<opentelemetry::trace::Span> active_span;
    };
    SpanWrapper wrapper{std::move(callback),
                        ::arrow::internal::tracing::GetTracer()->GetCurrentSpan()};
    callback = std::move(wrapper);
#endif
    CallbackRecord callback_record{std::move(callback), opts};
    if (IsFutureFinished(state_)) {
      lock.unlock();
      RunOrScheduleCallback(shared_from_this(), std::move(callback_record),
                            /*in_add_callback=*/true);
    } else {
      callbacks_.push_back(std::move(callback_record));
    }
  }

  bool TryAddCallback(const std::function<Callback()>& callback_factory,
                      CallbackOptions opts) {
    CheckOptions(opts);
    std::unique_lock<std::mutex> lock(mutex_);
    if (IsFutureFinished(state_)) {
      return false;
    } else {
      callbacks_.push_back({callback_factory(), opts});
      return true;
    }
  }

  static bool ShouldScheduleCallback(const CallbackRecord& callback_record,
                                     bool in_add_callback) {
    switch (callback_record.options.should_schedule) {
      case ShouldSchedule::Never:
        return false;
      case ShouldSchedule::Always:
        return true;
      case ShouldSchedule::IfUnfinished:
        return !in_add_callback;
      case ShouldSchedule::IfDifferentExecutor:
        return !callback_record.options.executor->OwnsThisThread();
      default:
        DCHECK(false) << "Unrecognized ShouldSchedule option";
        return false;
    }
  }

  static void RunOrScheduleCallback(const std::shared_ptr<FutureImpl>& self,
                                    CallbackRecord&& callback_record,
                                    bool in_add_callback) {
    if (ShouldScheduleCallback(callback_record, in_add_callback)) {
      struct CallbackTask {
        void operator()() { std::move(callback)(*self); }

        Callback callback;
        std::shared_ptr<FutureImpl> self;
      };
      // Need to keep `this` alive until the callback has a chance to be scheduled.
      CallbackTask task{std::move(callback_record.callback), self};
      DCHECK_OK(callback_record.options.executor->Spawn(std::move(task)));
    } else {
      std::move(callback_record.callback)(*self);
    }
  }

  void DoMarkFinishedOrFailed(FutureState state) {
    std::vector<CallbackRecord> callbacks;
    std::shared_ptr<FutureImpl> self;
    {
      std::unique_lock<std::mutex> lock(mutex_);
#ifdef ARROW_WITH_OPENTELEMETRY
      if (this->span_) {
        util::tracing::Span& span = *span_;
        END_SPAN(span);
      }
#endif

      DCHECK(!IsFutureFinished(state_)) << "Future already marked finished";
      if (!callbacks_.empty()) {
        callbacks = std::move(callbacks_);
        auto self_inner = shared_from_this();
        self = std::move(self_inner);
      }

      state_ = state;
      // We need to notify while holding the lock.  This notify often triggers
      // waiters to delete the future and it is not safe to delete a cv_ while
      // it is performing a notify_all
      cv_.notify_all();
    }
    if (callbacks.empty()) return;

    // run callbacks, lock not needed since the future is finished by this
    // point so nothing else can modify the callbacks list and it is safe
    // to iterate.
    //
    // In fact, it is important not to hold the locks because the callback
    // may be slow or do its own locking on other resources
    for (auto& callback_record : callbacks) {
      RunOrScheduleCallback(self, std::move(callback_record), /*in_add_callback=*/false);
    }
  }

  void DoWait() {
    std::unique_lock<std::mutex> lock(mutex_);

    cv_.wait(lock, [this] { return IsFutureFinished(state_); });
  }

  bool DoWait(double seconds) {
    std::unique_lock<std::mutex> lock(mutex_);

    cv_.wait_for(lock, std::chrono::duration<double>(seconds),
                 [this] { return IsFutureFinished(state_); });
    return IsFutureFinished(state_);
  }

  std::mutex mutex_;
  std::condition_variable cv_;
};

namespace {

ConcreteFutureImpl* GetConcreteFuture(FutureImpl* future) {
  return checked_cast<ConcreteFutureImpl*>(future);
}

}  // namespace

std::unique_ptr<FutureImpl> FutureImpl::Make() {
  return std::unique_ptr<FutureImpl>(new ConcreteFutureImpl());
}

std::unique_ptr<FutureImpl> FutureImpl::MakeFinished(FutureState state) {
  std::unique_ptr<ConcreteFutureImpl> ptr(new ConcreteFutureImpl());
  ptr->state_ = state;
  return std::move(ptr);
}

FutureImpl::FutureImpl() : state_(FutureState::PENDING) {}

void FutureImpl::Wait() { GetConcreteFuture(this)->DoWait(); }

bool FutureImpl::Wait(double seconds) { return GetConcreteFuture(this)->DoWait(seconds); }

void FutureImpl::MarkFinished() { GetConcreteFuture(this)->DoMarkFinished(); }

void FutureImpl::MarkFailed() { GetConcreteFuture(this)->DoMarkFailed(); }

void FutureImpl::AddCallback(Callback callback, CallbackOptions opts) {
  GetConcreteFuture(this)->AddCallback(std::move(callback), opts);
}

bool FutureImpl::TryAddCallback(const std::function<Callback()>& callback_factory,
                                CallbackOptions opts) {
  return GetConcreteFuture(this)->TryAddCallback(callback_factory, opts);
}

Future<> AllComplete(const std::vector<Future<>>& futures) {
  struct State {
    explicit State(int64_t n_futures) : mutex(), n_remaining(n_futures) {}

    std::mutex mutex;
    std::atomic<size_t> n_remaining;
  };

  if (futures.empty()) {
    return Future<>::MakeFinished();
  }

  auto state = std::make_shared<State>(futures.size());
  auto out = Future<>::Make();
  for (const auto& future : futures) {
    future.AddCallback([state, out](const Status& status) mutable {
      if (!status.ok()) {
        std::unique_lock<std::mutex> lock(state->mutex);
        if (!out.is_finished()) {
          out.MarkFinished(status);
        }
        return;
      }
      if (state->n_remaining.fetch_sub(1) != 1) return;
      out.MarkFinished();
    });
  }
  return out;
}

Future<> AllFinished(const std::vector<Future<>>& futures) {
  return All(futures).Then([](const std::vector<Result<internal::Empty>>& results) {
    for (const auto& res : results) {
      if (!res.ok()) {
        return res.status();
      }
    }
    return Status::OK();
  });
}

}  // namespace arrow


text:
<?php

namespace Magento\Shipping\Test\Block\Adminhtml\Shipment;

use Magento\Ui\Test\Block\Adminhtml\DataGrid as GridInterface;

/**
 * Shipment grid on shipment index page.
 */
class Grid extends GridInterface
{
    /**
     * Locator value for "View" link inside action column.
     *
     * @var string
     */
    protected $editLink = '.data-grid-actions-cell a';

    /**
     * Filters array mapping.
     *
     * @var array
     */
    protected $filters = [
        'id' => [
            'selector' => 'input[name="increment_id"]',
        ],
        'order_id' => [
            'selector' => 'input[name="order_increment_id"]',
        ],
        'total_qty_from' => [
            'selector' => 'input[name="total_qty[from]"',
        ],
        'total_qty_to' => [
            'selector' => 'input[name="total_qty][to]"',
        ],
    ];
}


text:
using System;
using System.Reflection.Emit;
using JetBrains.Annotations;

namespace ILGeneratorExtensions
{
    /// <summary>
    /// Contains extension methods for dealing with the manipulation of the type of objects on the stack
    /// </summary>
    [PublicAPI]
    public static class TypeManipulation
    {
        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes a reference of the given type if the object is an instance of that type, otherwise the null reference is pushed
        /// </summary>
        /// <typeparam name="T">The type to attempt to cast to</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator IsInstanceOfType<T>(this ILGenerator generator) => generator.IsInstanceOfType(typeof(T));

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes a reference of the given type if the object is an instance of the given type, otherwise the null reference is pushed
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type to attempt to cast to</param>
        [PublicAPI]
        public static ILGenerator IsInstanceOfType(this ILGenerator generator, Type type) => generator.FluentEmit(OpCodes.Isinst, type);

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes a reference of the given type if the object is an instance of that type, otherwise an <see cref="InvalidCastException" /> is thrown
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type to attempt to cast to</param>
        [PublicAPI]
        public static ILGenerator CastClass(this ILGenerator generator, Type type)
        {
            if (type.IsValueType)
            {
                throw new InvalidOperationException("Cannot cast to a value type");
            }

            return generator.FluentEmit(OpCodes.Castclass, type);
        }

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes a reference of the given type if the object is an instance of that type, otherwise an <see cref="InvalidCastException" /> is thrown
        /// </summary>
        /// <typeparam name="T">The type to attempt to cast to</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator CastClass<T>(this ILGenerator generator) where T : class => generator.CastClass(typeof (T));

        /// <summary>
        /// Pops a value type object from the evaluation stack, and pushes a reference to a new boxed instance of the object onto the evaluation stack
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the value type object</param>
        [PublicAPI]
        public static ILGenerator Box(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("Can only box value types");
            }

            return generator.FluentEmit(OpCodes.Box, type);
        }

        /// <summary>
        /// Pops a value type object from the evaluation stack, and pushes a reference to a new boxed instance of the object onto the evaluation stack
        /// </summary>
        /// <typeparam name="T">The type of the value type object</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator Box<T>(this ILGenerator generator) where T : struct => generator.Box(typeof (T));

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes the address of the boxed value type of the given type
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the boxed value type</param>
        [PublicAPI]
        public static ILGenerator Unbox(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("Cannot unbox non-value types");
            }

            return generator.FluentEmit(OpCodes.Unbox, type);
        }

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes the address of the boxed value type of the given type
        /// </summary>
        /// <typeparam name="T">The type of the boxed value type</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator Unbox<T>(this ILGenerator generator) where T : struct => generator.Unbox(typeof (T));

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes the value type object if the object is a boxed value type, or a reference of the given type if the object is a reference type and is an instance of that type
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type to unbox to</param>
        [PublicAPI]
        public static ILGenerator UnboxAny(this ILGenerator generator, Type type) => generator.FluentEmit(OpCodes.Unbox_Any, type);

        /// <summary>
        /// Pops a reference from the evaluation stack, and pushes the value type object if the object is a boxed value type, or a reference of the given type if the object is a reference type and is an instance of that type
        /// </summary>
        /// <typeparam name="T">The type to unbox to</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator UnboxAny<T>(this ILGenerator generator) => generator.UnboxAny(typeof (T));

        /// <summary>
        /// Pushes the number of bytes required to store the given type, for reference types this will always be the size of a reference, not the size of an object of that type itself
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type to get the size of</param>
        [PublicAPI]
        public static ILGenerator SizeOf(this ILGenerator generator, Type type) => generator.FluentEmit(OpCodes.Sizeof, type);

        /// <summary>
        /// Pushes the number of bytes required to store the given type, for reference types this will always be the size of a reference, not the size of an object of that type itself
        /// </summary>
        /// <typeparam name="T">The type to get the size of</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator SizeOf<T>(this ILGenerator generator) => generator.SizeOf(typeof(T));
    }
}


text:
cask 'toau' do
  version :latest
  sha256 :no_check

  url 'http://toauapp.com/download/Toau.zip'
  appcast 'http://toauapp.com/up/updates.xml'
  name 'Toau'
  homepage 'http://toauapp.com'
  license :commercial

  app 'Toau.app'
end


text:
require 'spec_helper'

describe FuelMarket do
  it { should have_many :market_prices }
  it { should have_many(:games).through(:market_prices) }
  it { should have_many :generator_types }
  it { should have_many(:generators).through(:generator_types) }

  it { should validate_presence_of :name }
  it { should validate_presence_of :initial_average_price }
  it { should validate_presence_of :initial_standard_deviation }
  it { should validate_presence_of :supply_slope }

  it { should respond_to :friendly_id }

  it "should initialize for a game based on average price and std. dev." do
    market = Factory :fuel_market
    game = Factory :game
    proc { market.initialize_for(game) }.should change(
        MarketPrice, :count).by(1)
    price = market.market_prices.find_by_game_id(game)
    price.price.should be >= market.initial_average_price - market.initial_standard_deviation
    price.price.should be <= market.initial_average_price + market.initial_standard_deviation
  end

  context "A FuelMarket instance" do
    before do
      @price = Factory :market_price
      @market = @price.fuel_market
      @game = @price.game
      @state = Factory :state, :game => @game
      @city = Factory :city, :state => @state, :customers => 100000
      @generator_type = Factory :generator_type, :fuel_market => @market
      @generator = Factory :generator, :city => @city,
          :generator_type => @generator_type
      @another_price = Factory :market_price
      @another_game = @another_price.game
      @another_state = Factory :another_state, :game => @another_game
      @another_city = Factory :another_city, :state => @another_state
    end

    context "with stubbed time" do
      before do
        stub_time
      end

      it "should know the instantaneous demand in a game" do
        demand = @game.generators(@market).inject(0) {|demand, gen|
          demand + gen.fuel_burn_rate
        }
        @market.demand(@game).should eq(demand)
      end

      it "should know the average demand for the fuel now in a game" do
        average = @game.generators(@market).inject(0) {|demand, gen|
          demand + gen.average_fuel_burn_rate
        }
        @market.average_demand(@game).should eq(average)
      end

      it "should have a current price for the overall market in a game" do
        (@market.current_price(@game)).should eq(
            @game.market_prices.find_by_fuel_market_id(@market,
                :order => "created_at DESC").price)
      end

      it "should have a current/timed price helper" do
        @market.price(@game).should eq(@market.current_price(@game))
        @market.price(@game, Time.now).should eq(
            @market.price_at(@game, Time.now))
      end

      it "should return the price discount for a city" do
        @market.discount_for(@city).should eq(
            @city.natural_resource_index(@market.related_natural_resource) /
              @state.natural_resource_index(@market.related_natural_resource) /
              FuelMarket::LOCAL_RESOURCE_SCALE_FACTOR)
      end

      it "should have a current price a specific city" do
        @market.current_local_price(@city).should eq(
            @market.current_price(@city.game) *
            ((100.0 - @market.discount_for(@city)) / 100.0))
      end

      it "should grab the most recent price for current price" do
        new_price = 42
        @market.market_prices.create(:price => new_price, :game => @game)
        @market.current_price(@game).should eq(new_price)
      end

      it "should have the price for an arbitrary day" do
        @market.price_at(@game, Time.now).should eq(
            @market.current_price(@game))
      end

      it "should have a lower coal price in a city with coal"

      it "should average the price over all games" do
        sum = @market.games.inject(0) {|sum, game|
          sum + @market.current_price(game)
        }
        @market.average_price.should eq(sum / @market.games.length)
      end
    end

    it "should know the avg demand for the fuel on an arbitrary day in game" do
      @generator = Factory :generator, :city => @city,
          :generator_type => @generator_type, :created_at => 2.days.ago
      time = 1.day.ago
      average = @game.generators(@market).inject(0) {|demand, gen|
        if gen.created_at >= time
          demand
        else
          demand + gen.average_fuel_burn_rate(time)
        end
      }
      stub_time
      @market.average_demand(@game, time).should eq(average)
    end

    it "should only count generators that exist in the average demand" do
      @market.average_demand(@game, 1.day.ago).should eq(0)
    end

    context "clearing market" do
      before do
        @market.clear @game
        @original_price = @market.current_price @game
        @another_market = Factory :fuel_market, :supply_slope => 2
        @another_price = Factory :market_price, :fuel_market => @another_market,
            :price => @price.price, :game => @game
        @another_generator_type = Factory :generator_type,
            :fuel_market => @another_market
        @another_generator = Factory :generator, :city => @city,
            :generator_type => @another_generator_type
      end

      it "should not recalculate price the first time the market clears" do
        @another_market.clear(@game)
        @another_market.current_price(@game).should eq(@original_price)
      end

      it "should recalculate prices based on supply of fuel"

      it "should recalculate prices based on demand" do
        another_generator = Factory :generator, :city => @city,
            :generator_type => @generator_type
        @market.reload
        @market.clear(@game)
        @market.current_price(@game).should be > @original_price
      end
    end
  end
end


text:
Public Class GradoSalarial
    Public Property IdGradoSalarial As Int32
    Public Property Grado As String
    Public Property RemuneracionMinima As Decimal
    Public Property RemuneracionMaxima As Decimal
    Public Property RemuneracionPromedio As Decimal
    Public Property Secuencia As GradoSalarial
End Class


text: export default class Environment { }


text:
package org.apache.hadoop.security;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.security.Groups;
import org.apache.hadoop.security.ShellBasedUnixGroupsMapping;

public class TestGroupsCaching {
  public static final Log LOG = LogFactory.getLog(TestGroupsCaching.class);
  private static String[] myGroups = {"grp1", "grp2"};
  private Configuration conf;

  @Before
  public void setup() {
    conf = new Configuration();
    conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING,
      FakeGroupMapping.class,
      ShellBasedUnixGroupsMapping.class);
  }

  public static class FakeGroupMapping extends ShellBasedUnixGroupsMapping {
    // any to n mapping
    private static Set<String> allGroups = new HashSet<String>();
    private static Set<String> blackList = new HashSet<String>();

    @Override
    public List<String> getGroups(String user) throws IOException {
      LOG.info("Getting groups for " + user);
      if (blackList.contains(user)) {
        return new LinkedList<String>();
      }
      return new LinkedList<String>(allGroups);
    }

    @Override
    public void cacheGroupsRefresh() throws IOException {
      LOG.info("Cache is being refreshed.");
      clearBlackList();
      return;
    }

    public static void clearBlackList() throws IOException {
      LOG.info("Clearing the blacklist");
      blackList.clear();
    }

    @Override
    public void cacheGroupsAdd(List<String> groups) throws IOException {
      LOG.info("Adding " + groups + " to groups.");
      allGroups.addAll(groups);
    }

    public static void addToBlackList(String user) throws IOException {
      LOG.info("Adding " + user + " to the blacklist");
      blackList.add(user);
    }
  }

  @Test
  public void testGroupsCaching() throws Exception {
    Groups groups = new Groups(conf);
    groups.cacheGroupsAdd(Arrays.asList(myGroups));
    groups.refresh();
    FakeGroupMapping.clearBlackList();
    FakeGroupMapping.addToBlackList("user1");

    // regular entry
    assertTrue(groups.getGroups("me").size() == 2);

    // this must be cached. blacklisting should have no effect.
    FakeGroupMapping.addToBlackList("me");
    assertTrue(groups.getGroups("me").size() == 2);

    // ask for a negative entry
    try {
      LOG.error("We are not supposed to get here." + groups.getGroups("user1").toString());
      fail();
    } catch (IOException ioe) {
      if(!ioe.getMessage().startsWith("No groups found")) {
        LOG.error("Got unexpected exception: " + ioe.getMessage());
        fail();
      }
    }

    // this shouldn't be cached. remove from the black list and retry.
    FakeGroupMapping.clearBlackList();
    assertTrue(groups.getGroups("user1").size() == 2);
  }

  public static class FakeunPrivilegedGroupMapping extends FakeGroupMapping {
    private static boolean invoked = false;
    @Override
    public List<String> getGroups(String user) throws IOException {
      invoked = true;
      return super.getGroups(user);
    }
  }

  /*
   * Group lookup should not happen for static users
   */
  @Test
  public void testGroupLookupForStaticUsers() throws Exception {
    conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING,
        FakeunPrivilegedGroupMapping.class, ShellBasedUnixGroupsMapping.class);
    conf.set(CommonConfigurationKeys.HADOOP_USER_GROUP_STATIC_OVERRIDES, "me=;user1=group1;user2=group1,group2");
    Groups groups = new Groups(conf);
    List<String> userGroups = groups.getGroups("me");
    assertTrue("non-empty groups for static user", userGroups.isEmpty());
    assertFalse("group lookup done for static user",
        FakeunPrivilegedGroupMapping.invoked);

    List<String> expected = new ArrayList<String>();
    expected.add("group1");

    FakeunPrivilegedGroupMapping.invoked = false;
    userGroups = groups.getGroups("user1");
    assertTrue("groups not correct", expected.equals(userGroups));
    assertFalse("group lookup done for unprivileged user",
        FakeunPrivilegedGroupMapping.invoked);

    expected.add("group2");
    FakeunPrivilegedGroupMapping.invoked = false;
    userGroups = groups.getGroups("user2");
    assertTrue("groups not correct", expected.equals(userGroups));
    assertFalse("group lookup done for unprivileged user",
        FakeunPrivilegedGroupMapping.invoked);

  }
}


text:
require 'json'

class WonderApp < Sinatra::Base
  get '/journey_times' do
    erb :journey_times
  end

  get '/journey_times.json' do
  	content_type :json

  	results = JourneyTime.find_by_sql('select * from journey_times where id in (select max(id) from journey_times group by from_point, to_point)').map do |record|
  		{
			:type => 'LineString',
	        :coordinates => [[record.to_point.x, record.to_point.y], [record.from_point.x, record.from_point.y]],
	        :properties => {
	        	:name => record.name,
                :estimated_time => record.estimated_time,
                :ideal_time => record.ideal_time
            }
		}
  	end

  	results.to_json
  end

  get '/journey_times/nerarby_routes' do
    content_type :json

    lat = params[:lat]
    long = params[:long]
    radius = params[:radius]

    results = DBHelpers.get_intersecting_journey_time_records(lat, long, radius).map do |record|
      ratio = record.ideal_time / record.estimated_time

      if(ratio > 1.2)
        severity = "severe"
      end

      if(ratio > 1.1 and ratio <= 1.2)
        severity = "moderate"
      end

      if(ratio > 0.9 and ratio <= 1.1)
        severity = "normal"
      end

      if (ratio <= 0.9)
        severity = "clear"
      end

      {
        :timestamp => record.recorded_timestamp,

        :coordinates =>  {
          :from => [record.from_point.y, record.from_point.x],
          :to => [record.to_point.y, record.to_point.x]
        },

        :difference => record.ideal_time - record.estimated_time,
        :severity => severity,
        :ratio => ratio.to_f,
        :description => Helpers.shorten_description(record.name)
      }
      end
    results.to_json
  end
end


text:
"use strict";

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var _story = require("./story");

var _story2 = _interopRequireDefault(_story);

module.exports = {
  Story: _story2["default"]
};


text:
|PyPI Version| |Conda Version| |License| |Azure CI Build Status|
|Codecov Coverage| |Coveralls Coverage| |PyPI downloads| |Conda downloads|

About statsmodels
=================

statsmodels is a Python package that provides a complement to scipy for
statistical computations including descriptive statistics and estimation
and inference for statistical models.

Documentation
=============

The documentation for the latest release is at

https://www.statsmodels.org/stable/

The documentation for the development version is at

https://www.statsmodels.org/dev/

Recent improvements are highlighted in the release notes

https://www.statsmodels.org/stable/release/

Backups of documentation are available at https://statsmodels.github.io/stable/
and https://statsmodels.github.io/dev/.

Main Features
=============

* Linear regression models:

  - Ordinary least squares
  - Generalized least squares
  - Weighted least squares
  - Least squares with autoregressive errors
  - Quantile regression
  - Recursive least squares

* Mixed Linear Model with mixed effects and variance components
* GLM: Generalized linear models with support for all of the one-parameter
  exponential family distributions
* Bayesian Mixed GLM for Binomial and Poisson
* GEE: Generalized Estimating Equations for one-way clustered or longitudinal data
* Discrete models:

  - Logit and Probit
  - Multinomial logit (MNLogit)
  - Poisson and Generalized Poisson regression
  - Negative Binomial regression
  - Zero-Inflated Count models

* RLM: Robust linear models with support for several M-estimators.
* Time Series Analysis: models for time series analysis

  - Complete StateSpace modeling framework

    - Seasonal ARIMA and ARIMAX models
    - VARMA and VARMAX models
    - Dynamic Factor models
    - Unobserved Component models

  - Markov switching models (MSAR), also known as Hidden Markov Models (HMM)
  - Univariate time series analysis: AR, ARIMA
  - Vector autoregressive models, VAR and structural VAR
  - Vector error correction model, VECM
  - exponential smoothing, Holt-Winters
  - Hypothesis tests for time series: unit root, cointegration and others
  - Descriptive statistics and process models for time series analysis

* Survival analysis:

  - Proportional hazards regression (Cox models)
  - Survivor function estimation (Kaplan-Meier)
  - Cumulative incidence function estimation

* Multivariate:

  - Principal Component Analysis with missing data
  - Factor Analysis with rotation
  - MANOVA
  - Canonical Correlation

* Nonparametric statistics: Univariate and multivariate kernel density estimators
* Datasets: Datasets used for examples and in testing
* Statistics: a wide range of statistical tests

  - diagnostics and specification tests
  - goodness-of-fit and normality tests
  - functions for multiple testing
  - various additional statistical tests

* Imputation with MICE, regression on order statistic and Gaussian imputation
* Mediation analysis
* Graphics includes plot functions for visual analysis of data and model results

* I/O

  - Tools for reading Stata .dta files, but pandas has a more recent version
  - Table output to ascii, latex, and html

* Miscellaneous models
* Sandbox: statsmodels contains a sandbox folder with code in various stages of
  development and testing which is not considered "production ready".  This covers
  among others

  - Generalized method of moments (GMM) estimators
  - Kernel regression
  - Various extensions to scipy.stats.distributions
  - Panel data models
  - Information theoretic measures

How to get it
=============
The main branch on GitHub is the most up to date code

https://www.github.com/statsmodels/statsmodels

Source download of release tags are available on GitHub

https://github.com/statsmodels/statsmodels/tags

Binaries and source distributions are available from PyPi

https://pypi.org/project/statsmodels/

Binaries can be installed in Anaconda

conda install statsmodels

Installing from sources
=======================

See INSTALL.txt for requirements or see the documentation

https://statsmodels.github.io/dev/install.html

Contributing
============
Contributions in any form are welcome, including:

* Documentation improvements
* Additional tests
* New features to existing models
* New models

https://www.statsmodels.org/stable/dev/test_notes

for instructions on installing statsmodels in *editable* mode.

License
=======

Modified BSD (3-clause)

Discussion and Development
==========================

Discussions take place on the mailing list

https://groups.google.com/group/pystatsmodels

and in the issue tracker. We are very interested in feedback
about usability and suggestions for improvements.

Bug Reports
===========

Bug reports can be submitted to the issue tracker at

https://github.com/statsmodels/statsmodels/issues

.. |Azure CI Build Status| image:: https://dev.azure.com/statsmodels/statsmodels-testing/_apis/build/status/statsmodels.statsmodels?branchName=main
   :target: https://dev.azure.com/statsmodels/statsmodels-testing/_build/latest?definitionId=1&branchName=main
.. |Codecov Coverage| image:: https://codecov.io/gh/statsmodels/statsmodels/branch/main/graph/badge.svg
   :target: https://codecov.io/gh/statsmodels/statsmodels
.. |Coveralls Coverage| image:: https://coveralls.io/repos/github/statsmodels/statsmodels/badge.svg?branch=main
   :target: https://coveralls.io/github/statsmodels/statsmodels?branch=main
.. |PyPI downloads| image:: https://img.shields.io/pypi/dm/statsmodels?label=PyPI%20Downloads
   :alt: PyPI - Downloads
   :target: https://pypi.org/project/statsmodels/
.. |Conda downloads| image:: https://img.shields.io/conda/dn/conda-forge/statsmodels.svg?label=Conda%20downloads
   :target: https://anaconda.org/conda-forge/statsmodels/
.. |PyPI Version| image:: https://img.shields.io/pypi/v/statsmodels.svg
   :target: https://pypi.org/project/statsmodels/
.. |Conda Version| image:: https://anaconda.org/conda-forge/statsmodels/badges/version.svg
   :target: https://anaconda.org/conda-forge/statsmodels/
.. |License| image:: https://img.shields.io/pypi/l/statsmodels.svg
   :target: https://github.com/statsmodels/statsmodels/blob/main/LICENSE.txt


text:
<?php

namespace LIN3S\AdminBundle\Registry;

/**
 * This exception should be thrown by service registry
 * when given type already exists.
 *
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class ExistingServiceException extends \InvalidArgumentException
{
    public function __construct($context, $type)
    {
        parent::__construct(sprintf('%s of type "%s" already exists.', $context, $type));
    }
}


text:
@implementation UserLocalDataLoader
{
    NSString *_searchString;
}

- (id)init {
    self = [super init];
    if (self) {
        NSFetchedResultsController * fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:[User getFetchRequest]
                                                                                managedObjectContext:[CoreDataStore mainQueueContext]
                                                                                sectionNameKeyPath:nil
                                                                                cacheName:nil];
        [self setFetchedResultsController:fetchResultController];

    }
    return self;
}

-(void)changeSearchString:(NSString *)searchString
{
    _searchString = searchString;
    [self refreshPredicate];
}

- (void)refreshPredicate
{
    [self setPredicate:[User getPredicateBySearchInput:_searchString]];

}

@end


text:
class Attractor {
public:
    Attractor() {
        amp  = 1;
        ampD = 0;
    }
    ofVec2f pos;
    float   amp; // 0 - 1;
    float   ampD;
    int     side;

    float getAmp() {
        return ofClamp(amp, 0, 1);
    }
    void setAmp(float v) {
        ampD = v;
    }

    void update() {
        amp += (ampD-amp) * 0.7;
    }

    void draw() {

        ofSetColor(255);
        ofCircle(pos, 25);
        ofSetColor(255, 0, 255);
        ofCircle(pos, 5+(20*getAmp()));

        ofSetColor(0, 250, 250);
        ofDrawBitmapString(AudioManager::getSideName(side), pos);

    }
};

class TextureScene : public BaseScene {

private:
protected:
public:

    void setup();
    void update();
    void draw();
	virtual void drawGui();
    void keyPressed(int key);
    void addPoints();
    void makeObstacles();
    void addShape();
    void respondToNewComplimentaryColours();
    void enterScene() {
        generateComplimentaryColours();
        respondToNewComplimentaryColours();
        ofRegisterMouseEvents(&gui);
    }
    void exitScene();

	void handleCommands(TwitterCommand& cmd, Effects& fx);

    vector <ofTexture> textures;

    ofxBox2d box2d;
    vector <ofxBox2dCircle> obsticals;
    vector <TexturedShape>   shapes;
    vector <ofVec2f>         pts;
    vector <TriangleShape>   tris;

    vector <Attractor>      attractors;

    bool     circleFrcFlip;
    ofVec2f circleFrc;
    ofxFloatSlider releaseRate;
	ofxFloatSlider repulsionForce;
	ofxFloatSlider attractionForce;
	ofxFloatSlider shapeBounceForce;
	ofxFloatSlider radialForce;
	ofxFloatSlider peakValue;
    ofxFloatSlider attractionDamping;

    ofxIntSlider   maxShapesOnScreen;

};


text:
[clappr](../../index.md) / [io.clappr.player.components](../index.md) / [Playback](index.md) / [selectedMediaOptionList](./selected-media-option-list.md)

# selectedMediaOptionList

`var selectedMediaOptionList: `[`ArrayList`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html)`<`[`MediaOption`](../-media-option/index.md)`>`


text:
package org.codepond.wizardroid.sample.wizards;

import android.view.View;

import com.softvelopment.wizardroid.activity.helper.ActivityValidateResult;

import org.codepond.wizardroid.WizardFlow;
import org.codepond.wizardroid.layouts.BasicWizardLayout;
import org.codepond.wizardroid.layouts.SoftvelopmentWizardLayout;
import org.codepond.wizardroid.sample.steps.TutorialStep1;
import org.codepond.wizardroid.sample.steps.TutorialStep2;

public class TutorialWizard extends SoftvelopmentWizardLayout {

    /**
     * Note that we inherit from {@link android.support.v4.app.Fragment} and therefore must have an empty constructor
     */
    public TutorialWizard() {
        super();
    }

    @Override
    public String getWizardName() {
        return "tutorial_wizard";
    }

    @Override
    public int getWizardFileResourceId() {
        return org.codepond.wizardroid.sample.R.raw.wizards;
    }

    /*
        You'd normally override onWizardComplete to access the wizard context and/or close the wizard
     */
    @Override
    public void onWizardComplete() {
        super.onWizardComplete();   //Make sure to first call the super method before anything else
        getActivity().finish();     //Terminate the wizard
    }

}


text:
require 'msgpack'
require 'easy-serve'

def EasyServe.manage_remote_eval_client msg
  $VERBOSE = msg["verbose"]
  service_names, services_list, log_level, eval_string, host =
    msg.values_at(*%w{service_names services_list log_level eval_string host})

  services = {}
  service_names = Marshal.load(service_names)
  services_list = Marshal.load(services_list)
  services_list.each do |service|
    services[service.name] = service
  end

  log_args = msg["log"]
  log =
    case log_args
    when Array
      Logger.new(*log_args)
    when true
      EasyServe.default_logger
    when nil, false
      EasyServe.null_logger
    end

  EasyServe.start services: services, log: log do |ez|
    log = ez.log
    log.level = log_level
    log.formatter = nil if $VERBOSE

    ez.local(*service_names) do |*conns|
      begin
        pr = eval "proc do |conns, host, log| #{eval_string}; end"
        pr[conns, host, log]
      rescue => ex
        puts "ez error", ex.inspect
        lineno = (Integer(ex.backtrace[0][/(\d+):/, 1]) rescue nil)
        if lineno
          lines = eval_string.lines
          puts "    #{lineno-1} --> " + lines[lineno-1]
        end
        puts ex.backtrace
      end
    end

    log.info "done"
  end
rescue LoadError, ScriptError, StandardError => ex
  puts "ez error", ex, ex.backtrace
end

$stdout.sync = true

def EasyServe.handle_remote_eval_messages
  unpacker = MessagePack::Unpacker.new($stdin)
  unpacker.each do |msg|
    case
    when msg["service_names"]
      Thread.new {manage_remote_eval_client(msg); exit}
    when msg["exit"]
      puts "exiting"
      exit
    when msg["request"]
      response = self.send(*msg["command"])
      puts "response: #{response.inspect}"
    else
      puts "unhandled: #{msg.inspect}"
    end
  end

rescue => ex
  puts "ez error", ex, ex.backtrace
end


text:
namespace {
const int kBytesPerSample = 2;
const int kBitsPerSample = kBytesPerSample * 8;
// Conversion factor from 100ns to 1ms.
const int k100nsPerMillisecond = 10000;

// Tolerance for catching packets of silence. If all samples have absolute
// value less than this threshold, the packet will be counted as a packet of
// silence. A value of 2 was chosen, because Windows can give samples of 1 and
// -1, even when no audio is playing.
const int kSilenceThreshold = 2;

// Lower bound for timer intervals, in milliseconds.
const int kMinTimerInterval = 30;

// Upper bound for the timer precision error, in milliseconds.
// Timers are supposed to be accurate to 20ms, so we use 30ms to be safe.
const int kMaxExpectedTimerLag = 30;

}  // namespace

namespace remoting {

AudioCapturerWin::AudioCapturerWin()
    : sampling_rate_(AudioPacket::SAMPLING_RATE_INVALID),
      volume_filter_(kSilenceThreshold),
      last_capture_error_(S_OK) {
  thread_checker_.DetachFromThread();
}

AudioCapturerWin::~AudioCapturerWin() {
  DCHECK(thread_checker_.CalledOnValidThread());
  Deinitialize();
}

bool AudioCapturerWin::Start(const PacketCapturedCallback& callback) {
  callback_ = callback;

  if (!Initialize()) {
    return false;
  }

  // Initialize the capture timer and start capturing. Note, this timer won't
  // be reset or restarted in ResetAndInitialize() function. Which means we
  // expect the audio_device_period_ is a system wide configuration, it would
  // not be changed with the default audio device.
  capture_timer_ = std::make_unique<base::RepeatingTimer>();
  capture_timer_->Start(FROM_HERE, audio_device_period_, this,
                        &AudioCapturerWin::DoCapture);
  return true;
}

bool AudioCapturerWin::ResetAndInitialize() {
  Deinitialize();
  if (!Initialize()) {
    Deinitialize();
    return false;
  }
  return true;
}

void AudioCapturerWin::Deinitialize() {
  DCHECK(thread_checker_.CalledOnValidThread());
  wave_format_ex_.Reset(nullptr);
  default_device_detector_.reset();
  audio_capture_client_.Reset();
  if (audio_client_) {
    audio_client_->Stop();
  }
  audio_client_.Reset();
  mm_device_.Reset();
}

bool AudioCapturerWin::Initialize() {
  DCHECK(!audio_capture_client_.Get());
  DCHECK(!audio_client_.Get());
  DCHECK(!mm_device_.Get());
  DCHECK(static_cast<PWAVEFORMATEX>(wave_format_ex_) == nullptr);
  DCHECK(thread_checker_.CalledOnValidThread());

  HRESULT hr = S_OK;
  Microsoft::WRL::ComPtr<IMMDeviceEnumerator> mm_device_enumerator;
  hr = ::CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
                          IID_PPV_ARGS(&mm_device_enumerator));
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to create IMMDeviceEnumerator. Error " << hr;
    return false;
  }

  default_device_detector_ =
      std::make_unique<DefaultAudioDeviceChangeDetector>(mm_device_enumerator);

  // Get the audio endpoint.
  hr = mm_device_enumerator->GetDefaultAudioEndpoint(eRender, eConsole,
                                                     &mm_device_);
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to get IMMDevice. Error " << hr;
    return false;
  }

  // Get an audio client.
  hr = mm_device_->Activate(__uuidof(IAudioClient),
                            CLSCTX_ALL,
                            nullptr,
                            &audio_client_);
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to get an IAudioClient. Error " << hr;
    return false;
  }

  REFERENCE_TIME device_period;
  hr = audio_client_->GetDevicePeriod(&device_period, nullptr);
  if (FAILED(hr)) {
    LOG(ERROR) << "IAudioClient::GetDevicePeriod failed. Error " << hr;
    return false;
  }
  // We round up, if |device_period| / |k100nsPerMillisecond|
  // is not a whole number.
  int device_period_in_milliseconds =
      1 + ((device_period - 1) / k100nsPerMillisecond);
  audio_device_period_ = base::Milliseconds(
      std::max(device_period_in_milliseconds, kMinTimerInterval));

  // Get the wave format.
  hr = audio_client_->GetMixFormat(&wave_format_ex_);
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to get WAVEFORMATEX. Error " << hr;
    return false;
  }

  if (wave_format_ex_->wFormatTag != WAVE_FORMAT_IEEE_FLOAT &&
      wave_format_ex_->wFormatTag != WAVE_FORMAT_PCM &&
      wave_format_ex_->wFormatTag != WAVE_FORMAT_EXTENSIBLE) {
    LOG(ERROR) << "Failed to force 16-bit PCM";
    return false;
  }

  if (!AudioCapturer::IsValidSampleRate(wave_format_ex_->nSamplesPerSec)) {
    LOG(ERROR) << "Host sampling rate is neither 44.1 kHz nor 48 kHz. "
               << wave_format_ex_->nSamplesPerSec;
    return false;
  }

  // We support from mono to 7.1. This check should be consistent with
  // AudioPacket::Channels.
  if (wave_format_ex_->nChannels > 8 || wave_format_ex_->nChannels <= 0) {
    LOG(ERROR) << "Unsupported channels " << wave_format_ex_->nChannels;
    return false;
  }

  sampling_rate_ = static_cast<AudioPacket::SamplingRate>(
      wave_format_ex_->nSamplesPerSec);

  wave_format_ex_->wBitsPerSample = kBitsPerSample;
  wave_format_ex_->nBlockAlign = wave_format_ex_->nChannels * kBytesPerSample;
  wave_format_ex_->nAvgBytesPerSec =
      sampling_rate_ * wave_format_ex_->nBlockAlign;

  if (wave_format_ex_->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
    PWAVEFORMATEXTENSIBLE wave_format_extensible =
        reinterpret_cast<WAVEFORMATEXTENSIBLE*>(
        static_cast<WAVEFORMATEX*>(wave_format_ex_));
    if (!IsEqualGUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT,
                     wave_format_extensible->SubFormat) &&
        !IsEqualGUID(KSDATAFORMAT_SUBTYPE_PCM,
                     wave_format_extensible->SubFormat)) {
      LOG(ERROR) << "Failed to force 16-bit samples";
      return false;
    }

    wave_format_extensible->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
    wave_format_extensible->Samples.wValidBitsPerSample = kBitsPerSample;
  } else {
    wave_format_ex_->wFormatTag = WAVE_FORMAT_PCM;
  }

  // Initialize the IAudioClient.
  hr = audio_client_->Initialize(
      AUDCLNT_SHAREMODE_SHARED,
      AUDCLNT_STREAMFLAGS_LOOPBACK,
      (kMaxExpectedTimerLag + audio_device_period_.InMilliseconds()) *
      k100nsPerMillisecond,
      0,
      wave_format_ex_,
      nullptr);
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to initialize IAudioClient. Error " << hr;
    return false;
  }

  // Get an IAudioCaptureClient.
  hr = audio_client_->GetService(IID_PPV_ARGS(&audio_capture_client_));
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to get an IAudioCaptureClient. Error " << hr;
    return false;
  }

  // Start the IAudioClient.
  hr = audio_client_->Start();
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to start IAudioClient. Error " << hr;
    return false;
  }

  volume_filter_.ActivateBy(mm_device_.Get());
  volume_filter_.Initialize(sampling_rate_, wave_format_ex_->nChannels);

  return true;
}

bool AudioCapturerWin::is_initialized() const {
  // All Com components should be initialized / deinitialized together.
  return !!audio_client_;
}

void AudioCapturerWin::DoCapture() {
  DCHECK(AudioCapturer::IsValidSampleRate(sampling_rate_));
  DCHECK(thread_checker_.CalledOnValidThread());

  if (!is_initialized() || default_device_detector_->GetAndReset()) {
    if (!ResetAndInitialize()) {
      // Initialization failed, we should wait for next DoCapture call.
      return;
    }
  }

  // Fetch all packets from the audio capture endpoint buffer.
  HRESULT hr = S_OK;
  while (true) {
    UINT32 next_packet_size;
    hr = audio_capture_client_->GetNextPacketSize(&next_packet_size);
    if (FAILED(hr))
      break;

    if (next_packet_size <= 0) {
      return;
    }

    BYTE* data;
    UINT32 frames;
    DWORD flags;
    hr = audio_capture_client_->GetBuffer(&data, &frames, &flags, nullptr,
                                          nullptr);
    if (FAILED(hr))
      break;

    if (volume_filter_.Apply(reinterpret_cast<int16_t*>(data), frames)) {
      std::unique_ptr<AudioPacket> packet(new AudioPacket());
      packet->add_data(data, frames * wave_format_ex_->nBlockAlign);
      packet->set_encoding(AudioPacket::ENCODING_RAW);
      packet->set_sampling_rate(sampling_rate_);
      packet->set_bytes_per_sample(AudioPacket::BYTES_PER_SAMPLE_2);
      // Only the count of channels is taken into account now, we should also
      // consider dwChannelMask.
      // TODO(zijiehe): Convert dwChannelMask to layout and pass it to
      // AudioPump. So the stream can be downmixed properly with both number and
      // layouts of speakers.
      packet->set_channels(static_cast<AudioPacket::Channels>(
          wave_format_ex_->nChannels));

      callback_.Run(std::move(packet));
    }

    hr = audio_capture_client_->ReleaseBuffer(frames);
    if (FAILED(hr))
      break;
  }

  // There is nothing to capture if the audio endpoint device has been unplugged
  // or disabled.
  if (hr == AUDCLNT_E_DEVICE_INVALIDATED)
    return;

  // Avoid reporting the same error multiple times.
  if (FAILED(hr) && hr != last_capture_error_) {
    last_capture_error_ = hr;
    LOG(ERROR) << "Failed to capture an audio packet: 0x"
               << std::hex << hr << std::dec << ".";
  }
}

bool AudioCapturer::IsSupported() {
  return true;
}

std::unique_ptr<AudioCapturer> AudioCapturer::Create() {
  return base::WrapUnique(new AudioCapturerWin());
}

}  // namespace remoting


text:
angular.module("uib/template/carousel/slide.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("uib/template/carousel/slide.html",
    "

\n" +
    "");
}]);


text:
import React from 'react'

export default ({ list_by_membership }) =>

Select Membership

    <form className='member-analysis-form' onSubmit={e => {
      e.preventDefault()
      list_by_membership(e.target[0].value)
    }}
    >
      <select className='member-analysis-dropdown'>
        <option value='annual-single'>Annual Single</option>
        <option value='annual-double'>Annual Double</option>
        <option value='annual-family'>Annual Family</option>
        <option value='annual-corporate'>Annual Corporate</option>
        <option value='annual-group'>Annual Group</option>
        <option value='life-single'>Life Single</option>
        <option value='life-double'>Life Double</option>
        <option value='accounts'>Accounts</option>
      </select>
      <button type='submit'>Search</button>
    </form>


text:
package com.google.code.apis.rest.client.Tree;

import java.util.Vector;

import com.google.code.apis.rest.client.GUI.GuiFactory;
import com.google.code.apis.rest.client.GUI.SettingsDialog;
import com.google.code.apis.rest.client.Util.SyntaxHighlighter;
import com.google.code.apis.rest.client.Wadl.MethodNode;
import com.google.code.apis.rest.client.Wadl.ResponseNode;
import com.google.code.apis.rest.client.Wadl.WadlXml;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;

public class ResponseItem extends Composite {
  public ResponseItem(final MethodNode method, final TreeItem methodTreeItem) {
    HorizontalPanel containerPanel = new HorizontalPanel();
    HTML response = new HTML(SyntaxHighlighter.highlight("<" + WadlXml.responseNode + ">"));
    containerPanel.add(response);

    // remove response hyperlink
    Hyperlink removeResponseLink = new Hyperlink(GuiFactory.strings.remove(), true, "");
    removeResponseLink.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        method.removeResponse(method.getResponse());
        listResponse(method, methodTreeItem);
      }
    });
    containerPanel.add(removeResponseLink);

    initWidget(containerPanel);
  }

  public static void listResponse(final MethodNode method, final TreeItem methodTreeItem) {
    Vector buttonTreeItems = WadlTreeRoot.removeChildrenXKeepButtons(methodTreeItem, WadlXml.responseNode);

    ResponseNode response = method.getResponse();
    if (response == null) {
      Button addResponseButton = new Button(GuiFactory.strings.addResponse());
      addResponseButton.addClickListener(new ClickListener() {
        public void onClick(Widget sender) {
          method.addResponse(new ResponseNode(method, method.getApplication()));
          listResponse(method, methodTreeItem);
        }
      });
      TreeItem addResponseTreeItem = new TreeItem(addResponseButton);
      addResponseTreeItem.setUserObject(WadlXml.responseNode);
      methodTreeItem.addItem(addResponseTreeItem);
      return;
    }
    ResponseItem responseItem = new ResponseItem(method, methodTreeItem);
    TreeItem responseTreeItem = new TreeItem(responseItem);
    responseTreeItem.setUserObject(WadlXml.responseNode);

    methodTreeItem.addItem(responseTreeItem);
    responseTreeItem.setState(SettingsDialog.treeItemsAlwaysOpen);

    // representations
    RepresentationItem.listRepresentations(response, responseTreeItem);

    // faults
    FaultItem.listFaults(response, responseTreeItem);

    // parameters
    String requestString = "";
    if (response.getApplication() != null) {
      requestString = response.getApplication().getAnalyzer().getRequestString();
    }
    ParamItem.listParams(response,
        responseTreeItem,
        requestString);

    GenericClosingItem responseCloseItem = new GenericClosingItem(WadlXml.responseNode);
    TreeItem responseCloseTreeItem = new TreeItem(responseCloseItem);
    responseCloseTreeItem.setUserObject(WadlXml.responseNode);
    methodTreeItem.addItem(responseCloseTreeItem);

    WadlTreeRoot.addButtons(buttonTreeItems, methodTreeItem);

    methodTreeItem.setState(SettingsDialog.treeItemsAlwaysOpen);
  }
}