text:
package org.openspaces.core.config;

import org.openspaces.core.space.filter.replication.DefaultReplicationFilterProviderFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

/**
 * A bean definition parser for {@link org.openspaces.core.space.filter.replication.DefaultReplicationFilterProviderFactory}.
 *
 * @author kimchy
 */
public class SpaceReplicationFilterBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {

    protected Class getBeanClass(Element element) {
        return DefaultReplicationFilterProviderFactory.class;
    }

    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
        super.doParse(element, parserContext, builder);

        Element filterEle = DomUtils.getChildElementByTagName(element, "input-filter");
        if (filterEle != null) {
            Object filter = parserContext.getDelegate().parsePropertyValue(filterEle, builder.getRawBeanDefinition(), "input-filter");
            builder.addPropertyValue("inputFilter", filter);
        }

        filterEle = DomUtils.getChildElementByTagName(element, "output-filter");
        if (filterEle != null) {
            Object filter = parserContext.getDelegate().parsePropertyValue(filterEle, builder.getRawBeanDefinition(), "output-filter");
            builder.addPropertyValue("outputFilter", filter);
        }
    }
}


text:
<!DOCTYPE html>

<?php
$selected = $_POST['city_choice'];
echo $selected;
include 'city.html';
?>
</html>

redpajama_set_name: RedPajamaGithub


text:
angular.module('remoteWork.controllers', ['ngSanitize']).

  /* Drivers controller */
  controller('vacanciesController', function($scope, ergastAPIservice) {
    $scope.nameFilter = null;
    $scope.vacanciesList = [];

    $scope.searchFilter = function (vacancy) {
        var re = new RegExp($scope.nameFilter, 'i');
        return !$scope.nameFilter || re.test(vacancy.name);// || re.test(driver.Driver.familyName);
    };

    ergastAPIservice.getVacancies(1).success(function (response) {
        //Digging into the response to get the relevant data
        $scope.vacanciesList = response.items;
    });

    /*
    ergastAPIservice.getVacancies(2).success(function (response) {
        //Digging into the response to get the relevant data
        console.log(response.items);
        $scope.vacanciesList2 = response.items;
    });
    */
  }).

  /* Driver controller */
  controller('vacancyController', function($scope, $routeParams, ergastAPIservice) {
    $scope.id = $routeParams.id;
    $scope.races = [];
    $scope.vacancy = null;
    $scope.chartCol = [0, 1, 2, 3];
    $scope.onlyNumbers = /^\d+$/;
    $scope.dataSample = [
      {"cat": "One", "val": 20},
      {"cat": "Two", "val": 10},
      {"cat": "Three", "val": -30},
      {"cat": "Four", "val": 40},
    ];
    var chart = new Chart();
    chart.drawBar($scope.dataSample);
    ergastAPIservice.getVacancyDetails($scope.id).success(function (response) {
        console.log(response);
        $scope.vacancy = response;
    });

    $scope.getGraph = function () {
        //Digging into the response to get the relevant data
        $scope.vacanciesList = response.items;
    };

    $scope.updateGraph = function () {
      chart.clear();
      chart.drawBar($scope.dataSample);
    };

    $scope.addData = function (id) {
      $scope.dataSample.push({"cat": "Simple", "val": 20});
      $scope.updateGraph();
    };

    ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
        $scope.races = response.MRData.RaceTable.Races;
    });
  });


text:
package liquibase.sqlgenerator.core;

import liquibase.database.Database;
import liquibase.database.core.InformixDatabase;
import liquibase.database.core.SybaseDatabase;
import liquibase.datatype.DataTypeFactory;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.statement.ColumnConstraint;
import liquibase.statement.NotNullConstraint;
import liquibase.statement.core.CreateDatabaseChangeLogTableStatement;
import liquibase.statement.core.CreateTableStatement;

public class CreateDatabaseChangeLogTableGenerator extends AbstractSqlGenerator<CreateDatabaseChangeLogTableStatement> {

    @Override
    public boolean supports(CreateDatabaseChangeLogTableStatement statement, Database database) {
        return (!(database instanceof SybaseDatabase));
    }

    @Override
    public ValidationErrors validate(CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        return new ValidationErrors();
    }

    @Override
    public Sql[] generateSql(CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {

        CreateTableStatement createTableStatement = new CreateTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
                .setTablespace(database.getLiquibaseTablespaceName())
                .addColumn("ID", DataTypeFactory.getInstance().fromDescription("VARCHAR(" + getIdColumnSize() + ")", database), null, null, null, new NotNullConstraint())
                .addColumn("AUTHOR", DataTypeFactory.getInstance().fromDescription("VARCHAR(" + getAuthorColumnSize() + ")", database), null, null, null, new NotNullConstraint())
                .addColumn("FILENAME", DataTypeFactory.getInstance().fromDescription("VARCHAR(" + getFilenameColumnSize() + ")", database), null, null, null, new NotNullConstraint())
                .addColumn("DATEEXECUTED", DataTypeFactory.getInstance().fromDescription("datetime", database), null, null, new NotNullConstraint())
                .addColumn("ORDEREXECUTED", DataTypeFactory.getInstance().fromDescription("INT", database), new NotNullConstraint())
                .addColumn("EXECTYPE", DataTypeFactory.getInstance().fromDescription("VARCHAR(10)", database), new NotNullConstraint())
                .addColumn("MD5SUM", DataTypeFactory.getInstance().fromDescription("VARCHAR(35)", database))
                .addColumn("DESCRIPTION", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)", database))
                .addColumn("COMMENTS", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)", database))
                .addColumn("TAG", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)", database))
                .addColumn("LIQUIBASE", DataTypeFactory.getInstance().fromDescription("VARCHAR(20)", database));

        return SqlGeneratorFactory.getInstance().generateSql(createTableStatement, database);
    }

    protected String getIdColumnSize() {
        return "255";
    }

    protected String getAuthorColumnSize() {
        return "255";
    }

    protected String getFilenameColumnSize() {
        return "255";
    }
}


text:
package hr.fer.zemris.jcms.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@Table(name="course_component_task_upload")
public class CourseComponentTaskUpload implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long id;
	private CourseComponentTaskAssignment courseComponentTaskAssignment;
	private String mimeType;
	private String charset;
	private String fileName;
	private String tag;
	private Date uploadedOn;

	public CourseComponentTaskUpload() {
	}

	@Id @GeneratedValue
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@ManyToOne(fetch=FetchType.EAGER)
	@Fetch(FetchMode.SELECT)
	@JoinColumn(nullable=false)
	public CourseComponentTaskAssignment getCourseComponentTaskAssignment() {
		return courseComponentTaskAssignment;
	}

	public void setCourseComponentTaskAssignment(
			CourseComponentTaskAssignment courseComponentTaskAssignment) {
		this.courseComponentTaskAssignment = courseComponentTaskAssignment;
	}

	@Column(length=40)
	public String getMimeType() {
		return mimeType;
	}

	public void setMimeType(String mimeType) {
		this.mimeType = mimeType;
	}

	@Column(length=20)
	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	@Column(length=100)
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	@Column(length=10)
	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}

	@Temporal(TemporalType.TIMESTAMP)
	public Date getUploadedOn() {
		return uploadedOn;
	}

	public void setUploadedOn(Date uploadedOn) {
		this.uploadedOn = uploadedOn;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime
				* result
				+ ((getCourseComponentTaskAssignment() == null) ? 0
						: getCourseComponentTaskAssignment().hashCode());
		result = prime * result
				+ ((getFileName() == null) ? 0 : getFileName().hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof CourseComponentTaskUpload))
			return false;
		final CourseComponentTaskUpload other = (CourseComponentTaskUpload) obj;
		if (getCourseComponentTaskAssignment() == null) {
			if (other.getCourseComponentTaskAssignment() != null)
				return false;
		} else if (!getCourseComponentTaskAssignment()
				.equals(other.getCourseComponentTaskAssignment()))
			return false;
		if (getFileName() == null) {
			if (other.getFileName() != null)
				return false;
		} else if (!getFileName().equals(other.getFileName()))
			return false;
		return true;
	}
}


text:
__author__ = 'sstober'

import numpy as np

class ChannelLayout(object):

    def channel_names(self):
        raise NotImplementedError('not implemented')

    def num_channels(self):
        raise NotImplementedError('not implemented')

    def sphere_coords(self):
        raise NotImplementedError('not implemented')

    def sphere_radius(self):
        raise NotImplementedError('not implemented')

    def xyz_coords(self):
        raise NotImplementedError('not implemented')

    def get_channel_number(self, channel_name):
        raise NotImplementedError('not implemented')

    def projected_xy_coords(self):
        raise NotImplementedError('not implemented')

class XYPlotChannelLayout(object):

    def names_layout(self):
        raise NotImplementedError('not implemented')

    def numbers_layout(self):
        raise NotImplementedError('not implemented')

    def number_positions(self):
        raise NotImplementedError('not implemented')


text:
<template name="blankLayout">

    <!-- Main view  -->
    {{>Template.dynamic template=content}}

</template>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <parent>
    <groupId>org.wso2.appserver</groupId>
    <artifactId>common-artifacts</artifactId>
    <version>5.3.0-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <artifactId>jstl12-example</artifactId>
  <packaging>war</packaging>
  <version>1.0.0-SNAPSHOT</version>
  <name>WSO2 AppServer - Test JSTL and EL</name>
  <url>http://wso2.org</url>

  <dependencies>
    <dependency>
      <groupId>org.wso2.tomcat</groupId>
      <artifactId>tomcat</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.wso2.tomcat</groupId>
      <artifactId>tomcat-servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>jstl12-example</finalName>
  </build>
</project>


text:
@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong) DMCircularScrollView *collectionScrollView;
@property(nonatomic, strong) NSArray *collectionItemsArray;
@end
static NSString *JCCellIdentifier = @"JCCellIdentifier";
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self initCollectionScrollView];

    __weak ViewController *weakSelf = self;

    _collectionItemsArray = [self generateCollectionViews:15 width:WIDTH];

    [_collectionScrollView setPageCount:[_collectionItemsArray count]
                         withDataSource:^UIView *(NSUInteger pageIndex) {
                             return [weakSelf.collectionItemsArray objectAtIndex:pageIndex];
                         }];

    // How to handle page events change
    _collectionScrollView.handlePageChange =  ^(NSUInteger currentPageIndex,NSUInteger previousPageIndex) {
        NSLog(@"COLLECTIONS HAS CHANGED. CURRENT COLLECTIONS IS %lu (prev=%lu)",(unsigned long)currentPageIndex,(unsigned long)previousPageIndex);

        [weakSelf.collectionItemsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
            for (UIView *sb in [(UIView*)obj subviews]) {
                if ([sb isKindOfClass:[UICollectionView class]]) {
                    UICollectionView *cv = (UICollectionView*)sb ;
                    if (idx == currentPageIndex) {
                    }
                    else{
                        [cv setScrollsToTop:YES];
                        [cv setContentOffset:CGPointZero animated:NO];
                    }
                }
            }
        }];
    };

    [self.view addSubview:_collectionScrollView];
}

-(void)initCollectionScrollView
{
    _collectionScrollView =[[DMCircularScrollView alloc] initWithFrame:CGRectMake(10, 64, WIDTH, 440)];
    _collectionScrollView.userInteractionEnabled = YES;
    _collectionScrollView.pageWidth = 300;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *) generateCollectionViews:(NSUInteger) number width:(CGFloat) wd {
    NSMutableArray *views_list = [[NSMutableArray alloc] init];

    for (NSUInteger k = 0;  k < number;  k++) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        [flowLayout setItemSize:CGSizeMake(wd, 300)];
        [flowLayout setSectionInset:UIEdgeInsetsMake(13, 0, 25, 0)];
        [flowLayout setMinimumLineSpacing:10];
        [flowLayout setMinimumInteritemSpacing:10];

        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, wd, 440)];
        UICollectionView *cv = [[UICollectionView alloc]initWithFrame:backView.bounds                                     collectionViewLayout:flowLayout];
        [cv registerClass:[JCCollectionViewCell class] forCellWithReuseIdentifier:JCCellIdentifier];
        cv.tag = k;
        cv.delegate = self;
        cv.dataSource = self;
        cv.backgroundColor = [UIColor clearColor];
        [backView addSubview:cv];
        [views_list addObject:backView];;
    }
    return views_list;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JCCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:JCCellIdentifier forIndexPath:indexPath];

    [cell startAnimation];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@"COLLECTIONS HAS SELECTED. SELECTED COLLECTIONS IS %lu (tag=%lu)",indexPath.item, collectionView.tag);
}

@end


text:
<?php

namespace Zend\XmlRpc\Value;

use Zend\XmlRpc\AbstractValue;

abstract class AbstractCollection extends AbstractValue
{
    /**
     * Set the value of a collection type (array and struct) native types
     *
     * @param array $value
     */
    public function __construct($value)
    {
        $values = (array) $value;   // Make sure that the value is an array
        foreach ($values as $key => $value) {
            // If the elements of the given array are not Zend\XmlRpc\Value objects,
            // we need to convert them as such (using auto-detection from PHP value)
            if (!$value instanceof parent) {
                $value = static::getXmlRpcValue($value, self::AUTO_DETECT_TYPE);
            }
            $this->value[$key] = $value;
        }
    }

    /**
     * Return the value of this object, convert the XML-RPC native collection values into a PHP array
     *
     * @return array
     */
    public function getValue()
    {
        $values = (array) $this->value;
        foreach ($values as $key => $value) {
            $values[$key] = $value->getValue();
        }
        return $values;
    }
}


text:
package com.agileapes.webexport.concurrent.impl;

import com.agileapes.webexport.concurrent.ActionDescriptor;
import com.agileapes.webexport.concurrent.ActionQueue;
import org.apache.log4j.Logger;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Mohammad Milad Naseri (m.m.naseri@gmail.com)
 * @since 1.0 (2013/2/26, 14:56)
 */
public class DefaultActionQueue<A extends ActionDescriptor> implements ActionQueue<A> {

    private final Set<A> scheduled = new CopyOnWriteArraySet<A>();
    private final Set<A> done = new CopyOnWriteArraySet<A>();
    private final String name;

    public DefaultActionQueue(String name) {
        this.name = name;
    }

    @Override
    public synchronized boolean hasNext() {
        return !scheduled.isEmpty();
    }

    @Override
    public synchronized A next() {
        if (hasNext()) {
            final Logger logger = Logger.getLogger(DefaultActionQueue.class.getName() + "." + name);
            final A action = scheduled.iterator().next();
            scheduled.remove(action);
            done.add(action);
            logger.info("Dispensing action: " + action);
            logger.info("Scheduled: " + scheduled.size());
            logger.info("Done: " + done.size());
            return action;
        }
        return null;
    }

    @Override
    public synchronized void schedule(A action) {
        if (done.contains(action)) {
            return;
        }
        scheduled.add(action);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        ">

    <jdbc:embedded-database id="dataSource" type="H2">
        <jdbc:script location="classpath:init.sql" execution="INIT"/>
    </jdbc:embedded-database>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="mappingResources">
            <list>
                <value>mappings/Ping.orm.xml</value>
            </list>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="insert"/>
            <tx:method name="findAll" read-only="true"/>
            <tx:method name="findOne" read-only="true"/>
            <tx:method name="updateOne"/>
            <tx:method name="deleteOne"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="txPointcut"
                      expression="execution(* me.wbprime.springdbusecase.springdatajpa.xml.services.PingServiceI.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

    <jpa:repositories base-package="me.wbprime.springdbusecase.springdatajpa.xml.dao" />
</beans>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Placodium subcandicans Müll. Arg.

### Remarks
null


text:
package mts

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

// MediaInfoJob is a nested struct in mts response
type MediaInfoJob struct {
	CreationTime     string           `json:"CreationTime" xml:"CreationTime"`
	Message          string           `json:"Message" xml:"Message"`
	PipelineId       string           `json:"PipelineId" xml:"PipelineId"`
	State            string           `json:"State" xml:"State"`
	Code             string           `json:"Code" xml:"Code"`
	UserData         string           `json:"UserData" xml:"UserData"`
	JobId            string           `json:"JobId" xml:"JobId"`
	MNSMessageResult MNSMessageResult `json:"MNSMessageResult" xml:"MNSMessageResult"`
	Input            Input            `json:"Input" xml:"Input"`
	Properties       Properties       `json:"Properties" xml:"Properties"`
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using Elasticsearch.Net;
using Elasticsearch.Net.Diagnostics;
using StackExchange.Profiling.Internal;
using StackExchange.Profiling.Elasticsearch.Internal;

namespace StackExchange.Profiling.Elasticsearch;

/// <summary>
/// Diagnostic listener for NEST and Elasticsearch.Net events.
/// </summary>
public class ElasticDiagnosticListener : IObserver<DiagnosticListener>, IMiniProfilerDiagnosticListener, IDisposable {
    private bool disposedValue;
    private ConcurrentBag<IDisposable> Disposables { get; } = new ConcurrentBag<IDisposable>();

    /// <inheritdoc />
    public void OnError(Exception error) => Trace.WriteLine(error);

    /// <inheritdoc />
    public bool Completed { get; private set; }

    /// <inheritdoc />
    public string ListenerName => DiagnosticSources.RequestPipeline.SourceName;

    /// <inheritdoc />
    public void OnCompleted() => Completed = true;

    /// <inheritdoc />
    public void OnNext(DiagnosticListener value) {
        TrySubscribe(DiagnosticSources.RequestPipeline.SourceName,
            () => new RequestPipelineDiagnosticObserver(
                v => WriteToProfiler(v.Key, v.Value),
                v => WriteToProfiler(v.Key, v.Value)
            ), value);

        //TrySubscribe(DiagnosticSources.AuditTrailEvents.SourceName,
        //    () => new AuditDiagnosticObserver(
        //        v => WriteToProfiler(v.Key, v.Value)
        //    ), value);

        //TrySubscribe(DiagnosticSources.Serializer.SourceName,
        //    () => new SerializerDiagnosticObserver(
        //        v => WriteToProfiler(v.Key, v.Value)
        //    ), value);

        //TrySubscribe(DiagnosticSources.HttpConnection.SourceName,
        //    () => new HttpConnectionDiagnosticObserver(
        //        v => WriteToProfiler(v.Key, v.Value),
        //        v => WriteToProfiler(v.Key, v.Value)
        //    ), value);
    }

    /// <inheritdoc />
    public void OnNext(KeyValuePair<string, object> diagnosticEvent) {
        var eventName = diagnosticEvent.Key;
        var data = diagnosticEvent.Value;
        switch (data) {
            case IApiCallDetails apiCallDetails:
                WriteToProfiler(eventName, apiCallDetails);
                break;
        }
    }

    /// <inheritdoc />
    protected virtual void Dispose(bool disposing) {
        if (!disposedValue) {
            if (disposing) {
                foreach (var d in Disposables) {
                    d.Dispose();
                }
            }

            disposedValue = true;
        }
    }

    /// <inheritdoc />
    public void Dispose() {
        Dispose(disposing: true);
    }

    private void TrySubscribe(string sourceName, Func<IObserver<KeyValuePair<string, object?>>> listener, DiagnosticListener value) {
        if (value.Name != sourceName) return;

        var subscription = value.Subscribe(listener());
        Disposables.Add(subscription);
    }

    private static void WriteToProfiler(string eventName, IApiCallDetails data) {
        MiniProfilerElasticsearch.HandleResponse(data);
    }

    private static void WriteToProfiler(string eventName, RequestData data) {
        // skip these events
    }
}


text:
require File.dirname(__FILE__) + '/../../../spec_helper'
require File.dirname(__FILE__) + '/shared/constants'

describe "Digest::MD5#==" do

  it 'should be equal to itself' do
    cur_digest = Digest::MD5.new
    cur_digest.should == cur_digest
  end

  it 'should be equal to string representing its hexdigest' do
    cur_digest = Digest::MD5.new
    cur_digest.should == MD5Constants::BlankHexdigest
  end

  it 'should be equal to appropriate object that responds to to_str' do
    # blank digest
    cur_digest = Digest::MD5.new
    (obj = mock(MD5Constants::BlankHexdigest)).should_receive(:to_str).and_return(MD5Constants::BlankHexdigest)
    cur_digest.should == obj

    # non-blank digest
    cur_digest = Digest::MD5.new
    cur_digest << "test"
    d_value = cur_digest.hexdigest
    (obj = mock(d_value)).should_receive(:to_str).and_return(d_value)
    cur_digest.should == obj
  end

  it 'should be equal for same digest different object' do
    cur_digest = Digest::MD5.new
    cur_digest2 = Digest::MD5.new
    cur_digest.should == cur_digest2
  end

end


text:
<?php
declare(strict_types=1);

namespace Upgate\LaravelJsonRpc\ServiceProvider;

use Illuminate\Support\ServiceProvider;
use Upgate\LaravelJsonRpc\Contract\ServerInterface as JsonRpcServerContract;
use Upgate\LaravelJsonRpc\Server\ServerFactory;

class JsonRpcServerServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->singleton(
            ServerFactory::class,
            function () {
                return new ServerFactory($this->app);
            }
        );

        $this->app->singleton(
            JsonRpcServerContract::class,
            function () {
                return $this->app->make(ServerFactory::class)->make();
            }
        );
    }

}


text:
using System;

namespace YanZhiwei.DotNet.Core.Config.Model
{
    /// <summary>
    /// WebApi缓存配置项
    /// </summary>
    /// <seealso cref="YanZhiwei.DotNet.Core.Config.Model.ConfigFileBase" />
    [Serializable]
    public class WebApiOutputCacheConfig : ConfigFileBase
    {
        /// <summary>
        /// 是否启用缓存
        /// </summary>
        public bool EnableOutputCache
        {
            get;
            set;
        }
    }
}


text:
using GlobalManifesto.Products.Helpers;
using GlobalManifesto.Products.Models;
using GlobalManifesto.Products.Models.Content;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Examine.Linq;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;

namespace GlobalManifesto.Products
{
	public class ProductListingController : RenderMvcController
	{
		public override ActionResult Index(RenderModel model)
		{
			var nodeUrl = model.Content.Url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
			var currentUrl = Request.Url.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

			if (currentUrl.Length > nodeUrl.Length)
			{
				var product = getProductByName(currentUrl.Last());

				if (product != null)
				{
					ContentLocationHelper.SetLocalParent(model.Content);

					return View("Product", new ProductRenderModel(new ProductListing(model.Content), product));
				}
			}

			return base.Index(model);
		}

		protected Product getProductByName(string productUrlName)
		{
			return new Index<Product>().Where(c => c.Name == productUrlName).FirstOrDefault();
		}
	}
}


text:
<?php
namespace Flipside\Http\Rest;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

class SerializationMiddleware
{
    protected $format = null;

    private function getFormatFromHeader($request)
    {
        $mimeType = $request->getHeaderLine('Accept');
        switch($mimeType)
        {
            case 'text/csv':
                return 'csv';
            case 'text/x-vCard':
                return 'vcard';
            default:
                return 'json';
        }
    }

    private function getParamFromArrayIfSet($array, $param, $default = null)
    {
        if(isset($array[$param]))
        {
            return $array[$param];
        }
        return $default;
    }

    private function getFormat($request, $response)
    {
        $params = $request->getQueryParams();
        $this->format = $this->getParamFromArrayIfSet($params, 'fmt');
        if($this->format === null)
        {
            $this->format = $this->getParamFromArrayIfSet($params, '$format');
            if($this->format === null)
            {
                $this->format = $this->getFormatFromHeader($request);
            }
            else if($this->format === 'json')
            {
                //OData json is different from notmal json
                $this->format = 'odata-json';
            }
        }
        if(strstr($this->format, 'odata.streaming=true'))
        {
            return $response->withStatus(406);
        }
        return $response;
    }

    protected function reserializeBody($response, $serializer)
    {
        $body = $response->getBody();
        $body->rewind();
        $data = json_decode($body->getContents());
        $serializer = new $serializer();
        $res = $serializer->serializeData($this->format, $data);
        $response = $response->withBody(new \Slim\Http\Body(fopen('php://temp', 'r+')));
        $response->getBody()->write($res);
        return $response->withHeader('Content-Type', $this->format);
    }

    public function __invoke($request, $response, $next)
    {
        $response = $this->getFormat($request, $response);
        if($response->getStatusCode() !== 200)
        {
            return $response;
        }
        $request = $request->withAttribute('format', $this->format)->withAttribute('serializeOverrides', new \Slim\Collection());
        $response = $next($request, $response);
        if($response->getHeaderLine('Content-Type') !== 'application/json;charset=utf-8' && $response->getHeaderLine('Content-Type') !== 'application/json')
        {
            //The underlying API call gave us back a different content type. Just pass that on...
            return $response;
        }
	$overrides = $request->getAttribute('serializeOverrides');
        if($overrides->has($this->format))
        {
            return $this->reserializeBody($response, $overrides->get($this->format));
        }
        switch($this->format)
        {
            case 'application/json':
            case 'application/x-javascript':
            case 'text/javascript':
            case 'text/x-javascript':
            case 'text/x-json':
            case 'json':
                return $response;
            case 'json-ss':
            case 'json-ss-dt':
                return $this->reserializeBody($response, '\Flipside\Serialize\JsonSpreadSheet');
            case 'data-table':
                //This is a special case for json...
                $body = $response->getBody();
                $body->rewind();
                $data = json_decode($body->getContents());
                return $response->withJson(array('data'=>$data));
            case 'odata-json':
                //This is a special case for json...
                $body = $response->getBody();
                $body->rewind();
                $data = json_decode($body->getContents());
                return $response->withJson(array('value'=>$data));
            case 'xml':
            case 'application/xml':
            case 'text/xml':
                return $this->reserializeBody($response, '\Flipside\Serialize\XMLSerializer');
            case 'csv':
            case 'text/csv':
                return $this->reserializeBody($response, '\Flipside\Serialize\CSVSerializer');
            case 'xlsx':
            case 'xls':
            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
            case 'application/vnd.ms-excel':
                return $this->reserializeBody($response, '\Flipside\Serialize\ExcelSerializer');
            case 'yaml':
            case 'application/x-yaml':
            case 'text/x-yaml':
                return $this->reserializeBody($response, '\Flipside\Serialize\YAMLSerializer');
            default:
                print_r($this->format); die();
                break;
        }
        return $response;
    }
}


text:
#ifndef CUHKSZ_RANDOM_NORMALDISTRIBUTION
#define CUHKSZ_RANDOM_NORMALDISTRIBUTION

#include "random/Distribution.h"
namespace cuhksz {

/**
  Samples the random real numbers according to [Normal
  distribution](https://en.wikipedia.org/wiki/Normal_distribution).
  It has parameters `mean` and `stddev` (standard deviation).

  PDF:<br/>
  \f$f(x)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\f$

  where \f$\mu\f$ is the `mean` parameter, and \f$\sigma\f$ is the `stddev`
  parameter.

  Usage:
  ```
  NormalDistribution dist();  // standard normal distribution
  dist.next();
  ```
**/
class NormalDistribution : public Distribution<double> {
 public:
  /**
    Construct a Normal distribution sampler with a new `Random` generator.
    @param mean The mean
    @param stddev The standard deviation
  **/
  explicit NormalDistribution(double mean = 0, double stddev = 1)
      : Distribution() {
    init(mean, stddev);
  }

  /**
    Construct a Gamma distribution sampler with an existing `Random` generator.
    @param[in] r The `Random` generator to use.
    @param mean The mean
    @param stddev The standard deviation
  **/
  explicit NormalDistribution(Random& r, double mean = 0, double stddev = 1)
      : Distribution(r) {
    init(mean, stddev);
  }

  virtual ~NormalDistribution() {}

  /**
    Sample a real number according to Normal distribution.
  **/
  double next() override;

  /**
    Returns the parameter `mean`.
  **/
  double mean() { return mean_; }

  /**
    Returns the parameter `stddev`.
  **/
  double stddev() { return stddev_; }

 private:
  double mean_;
  double stddev_;
  double spareResult;
  bool hasSpare = false;
  void init(double mean, double stddev);
};
}  // namespace cuhksz

#endif  // CUHKSZ_RANDOM_NORMALDISTRIBUTION


text:
using base::Time;

namespace autofill {

AutofillWebDataService::AutofillWebDataService(
    scoped_refptr<WebDatabaseService> wdbs,
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> db_task_runner)
    : WebDataServiceBase(std::move(wdbs), ui_task_runner),
      ui_task_runner_(std::move(ui_task_runner)),
      db_task_runner_(std::move(db_task_runner)),
      autofill_backend_(nullptr) {
  base::RepeatingClosure on_changed_callback = base::BindRepeating(
      &AutofillWebDataService::NotifyAutofillMultipleChangedOnUISequence,
      weak_ptr_factory_.GetWeakPtr());
  base::RepeatingClosure on_address_conversion_completed_callback =
      base::BindRepeating(
          &AutofillWebDataService::
              NotifyAutofillAddressConversionCompletedOnUISequence,
          weak_ptr_factory_.GetWeakPtr());
  base::RepeatingCallback<void(syncer::ModelType)> on_sync_started_callback =
      base::BindRepeating(
          &AutofillWebDataService::NotifySyncStartedOnUISequence,
          weak_ptr_factory_.GetWeakPtr());
  autofill_backend_ = new AutofillWebDataBackendImpl(
      wdbs_->GetBackend(), ui_task_runner_, db_task_runner_,
      on_changed_callback, on_address_conversion_completed_callback,
      on_sync_started_callback);
}

AutofillWebDataService::AutofillWebDataService(
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> db_task_runner)
    : WebDataServiceBase(nullptr, ui_task_runner),
      ui_task_runner_(std::move(ui_task_runner)),
      db_task_runner_(std::move(db_task_runner)),
      autofill_backend_(new AutofillWebDataBackendImpl(
          nullptr,
          ui_task_runner_,
          db_task_runner_,
          base::Closure(),
          base::Closure(),
          base::Callback<void(syncer::ModelType)>())) {}

void AutofillWebDataService::ShutdownOnUISequence() {
  weak_ptr_factory_.InvalidateWeakPtrs();
  db_task_runner_->PostTask(
      FROM_HERE,
      BindOnce(&AutofillWebDataBackendImpl::ResetUserData, autofill_backend_));
  WebDataServiceBase::ShutdownOnUISequence();
}

void AutofillWebDataService::AddFormFields(
    const std::vector<FormFieldData>& fields) {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::AddFormElements,
                                autofill_backend_, fields));
}

WebDataServiceBase::Handle AutofillWebDataService::GetFormValuesForElementName(
    const base::string16& name, const base::string16& prefix, int limit,
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetFormValuesForElementName,
                     autofill_backend_, name, prefix, limit),
      consumer);
}

void AutofillWebDataService::RemoveFormElementsAddedBetween(
    const Time& delete_begin, const Time& delete_end) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(
          &AutofillWebDataBackendImpl::RemoveFormElementsAddedBetween,
          autofill_backend_, delete_begin, delete_end));
}

void AutofillWebDataService::RemoveFormValueForElementName(
    const base::string16& name, const base::string16& value) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::RemoveFormValueForElementName,
                     autofill_backend_, name, value));
}

void AutofillWebDataService::AddAutofillProfile(
    const AutofillProfile& profile) {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::AddAutofillProfile,
                                autofill_backend_, profile));
}

void AutofillWebDataService::SetAutofillProfileChangedCallback(
    base::RepeatingCallback<void(const AutofillProfileDeepChange&)> change_cb) {
  autofill_backend_->SetAutofillProfileChangedCallback(std::move(change_cb));
}

void AutofillWebDataService::UpdateAutofillProfile(
    const AutofillProfile& profile) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::UpdateAutofillProfile,
                     autofill_backend_, profile));
}

void AutofillWebDataService::RemoveAutofillProfile(
    const std::string& guid) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::RemoveAutofillProfile,
                     autofill_backend_, guid));
}

WebDataServiceBase::Handle AutofillWebDataService::GetAutofillProfiles(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetAutofillProfiles,
                     autofill_backend_),
      consumer);
}

WebDataServiceBase::Handle AutofillWebDataService::GetServerProfiles(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetServerProfiles,
                     autofill_backend_),
      consumer);
}

void AutofillWebDataService::ConvertWalletAddressesAndUpdateWalletCards(
    const std::string& app_locale,
    const std::string& primary_account_email) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::
                         ConvertWalletAddressesAndUpdateWalletCards,
                     autofill_backend_, app_locale, primary_account_email));
}

WebDataServiceBase::Handle
    AutofillWebDataService::GetCountOfValuesContainedBetween(
        const Time& begin, const Time& end, WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(
          &AutofillWebDataBackendImpl::GetCountOfValuesContainedBetween,
          autofill_backend_, begin, end),
      consumer);
}

void AutofillWebDataService::UpdateAutofillEntries(
    const std::vector<AutofillEntry>& autofill_entries) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::UpdateAutofillEntries,
                     autofill_backend_, autofill_entries));
}

void AutofillWebDataService::AddCreditCard(const CreditCard& credit_card) {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::AddCreditCard,
                                autofill_backend_, credit_card));
}

void AutofillWebDataService::UpdateCreditCard(
    const CreditCard& credit_card) {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::UpdateCreditCard,
                                autofill_backend_, credit_card));
}

void AutofillWebDataService::RemoveCreditCard(const std::string& guid) {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::RemoveCreditCard,
                                autofill_backend_, guid));
}

void AutofillWebDataService::AddFullServerCreditCard(
    const CreditCard& credit_card) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::AddFullServerCreditCard,
                     autofill_backend_, credit_card));
}

WebDataServiceBase::Handle AutofillWebDataService::GetCreditCards(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetCreditCards,
                     autofill_backend_),
      consumer);
}

WebDataServiceBase::Handle AutofillWebDataService::GetServerCreditCards(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetServerCreditCards,
                     autofill_backend_),
      consumer);
}

void AutofillWebDataService::UnmaskServerCreditCard(
    const CreditCard& credit_card,
    const base::string16& full_number) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::UnmaskServerCreditCard,
                     autofill_backend_, credit_card, full_number));
}

void AutofillWebDataService::MaskServerCreditCard(const std::string& id) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::MaskServerCreditCard,
                     autofill_backend_, id));
}

void AutofillWebDataService::AddUpiId(const std::string& upi_id) {
  wdbs_->ScheduleDBTask(FROM_HERE,
                        base::BindOnce(&AutofillWebDataBackendImpl::AddUpiId,
                                       autofill_backend_, upi_id));
}

WebDataServiceBase::Handle AutofillWebDataService::GetAllUpiIds(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetAllUpiIds,
                     autofill_backend_),
      consumer);
}

WebDataServiceBase::Handle AutofillWebDataService::GetPaymentsCustomerData(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetPaymentsCustomerData,
                     autofill_backend_),
      consumer);
}

WebDataServiceBase::Handle AutofillWebDataService::GetCreditCardCloudTokenData(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::GetCreditCardCloudTokenData,
                     autofill_backend_),
      consumer);
}

void AutofillWebDataService::ClearAllServerData() {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::ClearAllServerData,
                                autofill_backend_));
}

void AutofillWebDataService::ClearAllLocalData() {
  wdbs_->ScheduleDBTask(
      FROM_HERE, base::BindOnce(&AutofillWebDataBackendImpl::ClearAllLocalData,
                                autofill_backend_));
}

void AutofillWebDataService::UpdateServerCardMetadata(
    const CreditCard& credit_card) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::UpdateServerCardMetadata,
                     autofill_backend_, credit_card));
}

void AutofillWebDataService::UpdateServerAddressMetadata(
    const AutofillProfile& profile) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::UpdateServerAddressMetadata,
                     autofill_backend_, profile));
}

void AutofillWebDataService::RemoveAutofillDataModifiedBetween(
    const Time& delete_begin,
    const Time& delete_end) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(
          &AutofillWebDataBackendImpl::RemoveAutofillDataModifiedBetween,
          autofill_backend_, delete_begin, delete_end));
}

void AutofillWebDataService::RemoveOriginURLsModifiedBetween(
    const Time& delete_begin, const Time& delete_end) {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(
          &AutofillWebDataBackendImpl::RemoveOriginURLsModifiedBetween,
          autofill_backend_, delete_begin, delete_end));
}

void AutofillWebDataService::RemoveOrphanAutofillTableRows() {
  wdbs_->ScheduleDBTask(
      FROM_HERE,
      base::BindOnce(&AutofillWebDataBackendImpl::RemoveOrphanAutofillTableRows,
                     autofill_backend_));
}

void AutofillWebDataService::AddObserver(
    AutofillWebDataServiceObserverOnDBSequence* observer) {
  DCHECK(db_task_runner_->RunsTasksInCurrentSequence());
  if (autofill_backend_)
    autofill_backend_->AddObserver(observer);
}

void AutofillWebDataService::RemoveObserver(
    AutofillWebDataServiceObserverOnDBSequence* observer) {
  DCHECK(db_task_runner_->RunsTasksInCurrentSequence());
  if (autofill_backend_)
    autofill_backend_->RemoveObserver(observer);
}

void AutofillWebDataService::AddObserver(
    AutofillWebDataServiceObserverOnUISequence* observer) {
  DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
  ui_observer_list_.AddObserver(observer);
}

void AutofillWebDataService::RemoveObserver(
    AutofillWebDataServiceObserverOnUISequence* observer) {
  DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
  ui_observer_list_.RemoveObserver(observer);
}

base::SupportsUserData* AutofillWebDataService::GetDBUserData() {
  DCHECK(db_task_runner_->RunsTasksInCurrentSequence());
  return autofill_backend_->GetDBUserData();
}

void AutofillWebDataService::GetAutofillBackend(
    base::OnceCallback<void(AutofillWebDataBackend*)> callback) {
  db_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback),
                                base::RetainedRef(autofill_backend_)));
}

base::SingleThreadTaskRunner* AutofillWebDataService::GetDBTaskRunner() {
  return db_task_runner_.get();
}

WebDataServiceBase::Handle
AutofillWebDataService::RemoveExpiredAutocompleteEntries(
    WebDataServiceConsumer* consumer) {
  return wdbs_->ScheduleDBTaskWithResult(
      FROM_HERE,
      base::BindOnce(
          &AutofillWebDataBackendImpl::RemoveExpiredAutocompleteEntries,
          autofill_backend_),
      consumer);
}

AutofillWebDataService::~AutofillWebDataService() {
}

void AutofillWebDataService::NotifyAutofillMultipleChangedOnUISequence() {
  DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
  for (auto& ui_observer : ui_observer_list_)
    ui_observer.AutofillMultipleChangedBySync();
}

void AutofillWebDataService::
    NotifyAutofillAddressConversionCompletedOnUISequence() {
  DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
  for (auto& ui_observer : ui_observer_list_)
    ui_observer.AutofillAddressConversionCompleted();
}

void AutofillWebDataService::NotifySyncStartedOnUISequence(
    syncer::ModelType model_type) {
  DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
  for (auto& ui_observer : ui_observer_list_)
    ui_observer.SyncStarted(model_type);
}

}  // namespace autofill


text:
export function InstallWizard(params) {
  return {
    'mail.use-tls': {
      field: {
        disabledReason: null,
        default: false,
        required: true,
        disabled: false,
        allowEmpty: true,
        isSet: true,
      },
    },
    'mail.username': {
      field: {
        disabledReason: null,
        default: '',
        required: true,
        disabled: false,
        allowEmpty: true,
        isSet: true,
      },
    },
    'mail.port': {
      field: {
        disabledReason: null,
        default: 25,
        required: true,
        disabled: false,
        allowEmpty: false,
        isSet: true,
      },
    },
    'system.admin-email': {
      field: {
        disabledReason: null,
        default: '',
        required: true,
        disabled: false,
        allowEmpty: false,
        isSet: true,
      },
    },
    'mail.password': {
      field: {
        disabledReason: null,
        default: '',
        required: true,
        disabled: false,
        allowEmpty: true,
        isSet: true,
      },
    },
    'mail.from': {
      field: {
        disabledReason: null,
        default: 'root@localhost',
        required: true,
        disabled: false,
        allowEmpty: false,
        isSet: true,
      },
    },
    'system.url-prefix': {
      field: {
        disabledReason: 'diskPriority',
        default: '',
        required: true,
        disabled: true,
        allowEmpty: false,
        isSet: true,
      },
    },
    'auth.allow-registration': {
      field: {
        disabledReason: null,
        default: false,
        required: true,
        disabled: false,
        allowEmpty: true,
        isSet: true,
      },
    },
    'beacon.anonymous': {
      field: {
        disabledReason: null,
        default: false,
        required: true,
        disabled: false,
        allowEmpty: true,
        isSet: true,
      },
    },
    'mail.host': {
      field: {
        disabledReason: null,
        default: 'localhost',
        required: true,
        disabled: false,
        allowEmpty: false,
        isSet: true,
      },
    },
    ...params,
  };
}


text:
void
cblas_srotmg (float *d1, float *d2, float *b1, const float b2, float *P)
{
#define BASE float
#include "source_rotmg.h"
#undef BASE
}


text:
use glib::{Value, Type};
use glib::translate::{from_glib_full, ToGlibPtr, from_glib};
use ffi;
use {TreeIter, TreePath};
use libc::c_void;
use glib;

pub struct TreeModel {
    pointer: *mut ffi::C_GtkTreeModel
}

impl TreeModel {
    pub fn get_flags(&self) -> ::TreeModelFlags {
        unsafe { ffi::gtk_tree_model_get_flags(self.pointer) }
    }

    pub fn get_n_columns(&self) -> i32 {
        unsafe { ffi::gtk_tree_model_get_n_columns(self.pointer) }
    }

    pub fn get_column_type(&self, index_: i32) -> Type {
        unsafe { from_glib(ffi::gtk_tree_model_get_column_type(self.pointer, index_)) }
    }

    pub fn get_iter(&self, iter: &mut TreeIter, path: &TreePath) -> bool {
        match unsafe { ffi::gtk_tree_model_get_iter(self.pointer, iter.unwrap_pointer(), path.unwrap_pointer()) } {
            0 => false,
            _ => true
        }
    }

    pub fn get_iter_from_string(&self, iter: &mut TreeIter, path_string: &str) -> bool {
        match unsafe { ffi::gtk_tree_model_get_iter_from_string(self.pointer, iter.unwrap_pointer(), path_string.to_glib_none().0) } {
                0 => false,
                _ => true
            }
    }

    pub fn get_iter_first(&self, iter: &mut TreeIter) -> bool {
        match unsafe { ffi::gtk_tree_model_get_iter_first(self.pointer, iter.unwrap_pointer()) } {
            0 => false,
            _ => true
        }
    }

    pub fn get_path(&self, iter: &TreeIter) -> Option<TreePath> {
        let tmp_pointer = unsafe { ffi::gtk_tree_model_get_path(self.pointer, iter.unwrap_pointer()) };

        if tmp_pointer.is_null() {
            None
        } else {
            Some(TreePath::wrap_pointer(tmp_pointer))
        }
    }

    pub fn get_value(&self, iter: &TreeIter, column: i32) -> Value {
        unsafe {
            let mut value = Value::new();
            ffi::gtk_tree_model_get_value(self.pointer, iter.unwrap_pointer(), column,
                value.as_mut_ptr());
            value
        }
    }

    pub fn iter_next(&self, iter: &mut TreeIter) -> bool {
        match unsafe { ffi::gtk_tree_model_iter_next(self.pointer, iter.unwrap_pointer()) } {
            0 => false,
            _ => true
        }
    }

    pub fn iter_previous(&self, iter: &mut TreeIter) -> bool {
        match unsafe { ffi::gtk_tree_model_iter_previous(self.pointer, iter.unwrap_pointer()) } {
            0 => false,
            _ => true
        }
    }

    pub fn iter_children(&self, iter: &mut TreeIter, parent: Option<&TreeIter>) -> bool {
        match unsafe {
            ffi::gtk_tree_model_iter_children(self.pointer,
                                              iter.unwrap_pointer(),
                                              if parent.is_none() { ::std::ptr::null_mut() } else { parent.unwrap().unwrap_pointer() })
        } {
            0 => false,
            _ => true
        }
    }

    pub fn iter_has_child(&self, iter: &TreeIter) -> bool {
        match unsafe { ffi::gtk_tree_model_iter_has_child(self.pointer, iter.unwrap_pointer()) } {
            0 => false,
            _ => true
        }
    }

    pub fn iter_n_children(&self, iter: Option<&TreeIter>) -> i32 {
        unsafe { ffi::gtk_tree_model_iter_n_children(self.pointer, match iter {
                Some(i) => i.unwrap_pointer(),
                None => ::std::ptr::null_mut()
            }) }
    }

    pub fn iter_nth_child(&self, iter: &mut TreeIter, parent: Option<&TreeIter>, n: i32) -> bool {
        match unsafe {
            ffi::gtk_tree_model_iter_nth_child(self.pointer,
                iter.unwrap_pointer(),
                match parent {
                    Some(p) => p.unwrap_pointer(),
                    None => ::std::ptr::null_mut()
                },
                n)
        } {
            0 => false,
            _ => true
        }
    }

    pub fn iter_parent(&self, iter: &mut TreeIter, child: &TreeIter) -> bool {
        match unsafe { ffi::gtk_tree_model_iter_parent(self.pointer, iter.unwrap_pointer(), child.unwrap_pointer()) } {
            0 => false,
            _ => true
        }
    }

    pub fn get_string_from_iter(&self, iter: &TreeIter) -> Option<String> {
        unsafe {
            from_glib_full(
                ffi::gtk_tree_model_get_string_from_iter(self.pointer,
                                                         iter.unwrap_pointer()))
        }
    }

    pub fn row_changed(&self, path: &TreePath, iter: &TreeIter) {
        unsafe { ffi::gtk_tree_model_row_changed(self.pointer, path.unwrap_pointer(), iter.unwrap_pointer()) }
    }

    pub fn row_inserted(&self, path: &TreePath, iter: &TreeIter) {
        unsafe { ffi::gtk_tree_model_row_inserted(self.pointer, path.unwrap_pointer(), iter.unwrap_pointer()) }
    }

    pub fn row_has_child_toggled(&self, path: &TreePath, iter: &TreeIter) {
        unsafe { ffi::gtk_tree_model_row_has_child_toggled(self.pointer, path.unwrap_pointer(), iter.unwrap_pointer()) }
    }

    pub fn row_deleted(&self, path: &TreePath) {
        unsafe { ffi::gtk_tree_model_row_deleted(self.pointer, path.unwrap_pointer()) }
    }

    pub fn rows_reordered(&self, path: &TreePath, iter: Option<&TreeIter>, new_order: &mut [i32]) {
        unsafe {
            ffi::gtk_tree_model_rows_reordered(self.pointer,
                                               path.unwrap_pointer(),
                                               if iter.is_none() { ::std::ptr::null_mut() } else { iter.unwrap().unwrap_pointer() },
                                               new_order.as_mut_ptr())
        }
    }

    pub fn ref_node(&self, iter: &TreeIter) {
        unsafe { ffi::gtk_tree_model_ref_node(self.pointer, iter.unwrap_pointer()) }
    }

    pub fn unref_node(&self, iter: &TreeIter) {
        unsafe { ffi::gtk_tree_model_unref_node(self.pointer, iter.unwrap_pointer()) }
    }

    pub fn foreach<T>(&self, func: fn(&mut TreeModel, &mut TreePath, &mut TreeIter, data: &mut T) -> bool, user_data: &mut T) {
        let t = &(func, user_data);
        let ca = t as *const (fn(&mut TreeModel, &mut TreePath, &mut TreeIter, data: &mut T) -> bool, &mut T);

        unsafe { ffi::gtk_tree_model_foreach(self.pointer, my_fn as ffi::gpointer, ca as ffi::gpointer) }
    }

    #[doc(hidden)]
    pub fn unwrap_pointer(&self) -> *mut ffi::C_GtkTreeModel {
        self.pointer
    }

    #[doc(hidden)]
    pub fn wrap_pointer(c_treemodel: *mut ffi::C_GtkTreeModel) -> TreeModel {
        TreeModel {
            pointer: c_treemodel
        }
    }
}

fn my_fn(model: *mut ffi::C_GtkTreeModel, path: *mut ffi::C_GtkTreePath, iter: *mut ffi::C_GtkTreeIter,
    data: &mut (fn(&mut TreeModel, &mut TreePath, &mut TreeIter, data: *mut c_void) -> bool, &mut c_void)) -> ffi::Gboolean {
    glib::to_gboolean(data.0(&mut TreeModel::wrap_pointer(model), &mut TreePath::wrap_pointer(path), &mut TreeIter::wrap_pointer(iter), data.1))
}

impl_drop!(TreeModel, GTK_TREE_MODEL);


text:
import time
from bs4 import BeautifulSoup
import urllib.request
from analyzer.database import Database
import re
from datetime import datetime

def run():
	rip_site()

def load(id):
	url = "http://www.cinemetrics.lv/data.php?movie_ID={}".format(id)
	try:
		request = urllib.request.Request(url)
		webpage_bytes = urllib.request.urlopen(request)
		soup = BeautifulSoup(webpage_bytes, 'lxml')
	except urllib.error.URLError as err:
		print(err)
		return None
	else:
		return soup

HEADERS = ["title", "year", "director", "country", "submittedBy", "mode", "date", "asl", "msl", "stdev"]

def int_representation(s):
	try:
		i = int(s)
		return i
	except ValueError:
		return None

def float_representation(s):
	try:
		i = float(s)
		return i
	except ValueError:
		return None

def none_empty_string(s):
	if len(s):
		return s
	else:
		return None

def date_time(s):
	date_object = datetime.strptime('2016-10-06', '%Y-%m-%d')
	return date_object

def rip_movie_list(path):
	db = Database()

	try:
		data = open(path).read()
		soup = BeautifulSoup(data, 'lxml')
	# soup = BeautifulSoup(str, 'lxml')
	except urllib.error.URLError as err:
		print(err)
		db.close()
		return None
	else:
		rows = soup.find_all("tr")
		movie_id_regex = re.compile("(?<=movie_ID=).*[0-9]")

		for row in rows:
			if "onclick" in row.attrs:
				onclick = row.attrs['onclick']
				id_match = movie_id_regex.search(onclick)

				if id_match:
					movie_id = int_representation(id_match.group(0))
					entities = row.find_all("td")

					meta_dict = {
						HEADERS[0]: none_empty_string(entities[0].text),
						HEADERS[1]: int_representation(entities[1].text),
						HEADERS[2]: none_empty_string(entities[2].text),
						HEADERS[3]: none_empty_string(entities[3].text),
						HEADERS[4]: none_empty_string(entities[4].text),
						HEADERS[5]: none_empty_string(entities[5].text),
						HEADERS[6]: date_time(entities[6]),
						HEADERS[7]: float_representation(entities[7].text),
						HEADERS[8]: float_representation(entities[8].text),
						HEADERS[9]: float_representation(entities[9].text),
						"id": movie_id
					}

					db.context.cinemetrics.update_one(
						{"id": movie_id},
						{"$set": meta_dict},
						True,
						True
					)
					print(movie_id)
	db.close()

def rip_site(start=0, end=25004):
	db = Database()

	for id in range(start, end):
		soup = load(id)
		shots = parse(soup)
		result = {"shots": shots, "id": id}

		db.context.cinemetrics.update_one(
			{"id": id},
			{"$set": result},
			True
		)

		print(id)
		time.sleep(0.25)

def parse(soup):
	table = soup.find("table")
	headers = []
	for th in table.find_all("th"):
		span = th.a.find("span")
		description = span.text
		span.unwrap()
		identifier = th.a.text.replace(description, "")
		headers.append({"identifier": identifier, "description": description})

	rows = [[td.text for td in tr.find_all("td")] for tr in table.find_all('tr')]

	# ensure that empty rows are represented as empty lists
	if len(rows) == 0:
		rows = [[] for _ in headers]

	converted_rows = []
	for row in rows:
		if not len(row):
			continue

		dict = {}
		for i, entity in enumerate(row):
			if len(headers) <= i:
				continue

			header = headers[i]
			if header["identifier"] != "Type":
				entity = int_representation(entity)

			dict[header["identifier"]] = entity

		if len(dict) > 0:
			converted_rows.append(dict)

	return converted_rows

def parse_lists(soup):
	table = soup.find("table")
	headers = []
	for th in table.find_all("th"):
		span = th.a.find("span")
		description = span.text
		span.unwrap()
		identifier = th.a.text.replace(description, "")
		headers.append({"identifier": identifier, "description": description})

	rows = [[td.text for td in tr.find_all("td")] for tr in table.find_all('tr')]
	values = list(map(list, zip(*rows)))

	# ensure that empty rows are represented as empty lists
	if len(values) == 0:
		values = [[] for _ in headers]

	# convert
	result = {}
	for i, header in enumerate(headers):
		if header["identifier"] is not "Type":
			rows = values[i]
			values[i] = map(int, rows)

		result[header["identifier"]] = values[i]

	return result


text:
import Marionette from 'backbone.marionette';
import template from 'templates/404Root.ejs';

export default Marionette.LayoutView.extend({
  template,

  behaviors: {
    l20n: {}
  }
});


text:
package controllers

import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers._
import service.KeystoreService

import scala.concurrent.Future
import uk.gov.hmrc.http.{ HeaderCarrier, SessionKeys }

class TaxYearSelectionSpec extends test.BaseSpec {
  val endPointURL = "/paac/taxyearselection"

  trait ControllerWithMockKeystore extends MockKeystoreFixture {
    object ControllerWithMockKeystore extends TaxYearSelectionController with AppTestSettings {
      val keystorekey = "TaxYearSelection"
      def keystore: KeystoreService = MockKeystore
    }
  }

  "TaxYearSelection" when {
    "GET with routes".should {
      "not return result NOT_FOUND" in {
        val result: Option[Future[Result]] = route(FakeRequest(GET, endPointURL))
        result.isDefined shouldBe true
        status(result.get) should not be NOT_FOUND
      }
      "return 303 for valid GET request" in {
        val result: Option[Future[Result]] = route(FakeRequest(GET, endPointURL))
        status(result.get) shouldBe 303
      }
      "not return 200 for valid GET request" in {
        val result: Option[Future[Result]] = route(FakeRequest(GET, endPointURL))
        status(result.get) should not be 200
      }
    }

    "onPageLoad with GET request" should {
      "have keystore with no values and display Tax Year Selection options" in new ControllerWithMockKeystore {
        // setup
        val request = FakeRequest(GET,"").withSession{(SessionKeys.sessionId,SESSION_ID)}

        // test
        val result : Future[Result] = ControllerWithMockKeystore.onPageLoad()(request)

        // check
        status(result) shouldBe 200
        val htmlPage = contentAsString(await(result))
        dumpHtml("empty_taxyearselection", htmlPage)
      }

      "have keystore with TaxYearSelection value when page is revisited" in new ControllerWithMockKeystore {
        // setup
        MockKeystore.map = MockKeystore.map + ("TaxYearSelection" -> "2015")
        implicit val hc = HeaderCarrier()
        val request = FakeRequest(GET,"").withSession{(SessionKeys.sessionId,SESSION_ID)}
        // test
        val result : Future[Result] = ControllerWithMockKeystore.onPageLoad()(request)

        // check
        status(result) shouldBe 200
        MockKeystore.map should contain key ("TaxYearSelection")
        MockKeystore.map should contain value ("2015")
        val htmlPage = contentAsString(await(result))
        dumpHtml("taxyearselection", htmlPage)
      }

      "if TaxYearSelection value in keystore displays checked checkboxes" in new ControllerWithMockKeystore {
        // set up
        MockKeystore.map = MockKeystore.map + (KeystoreService.SELECTED_INPUT_YEARS_KEY -> "2015,2014")
        implicit val hc = HeaderCarrier()
        val request = FakeRequest(GET,"").withSession{(SessionKeys.sessionId,SESSION_ID)}

        // test
        val result : Future[Result] = ControllerWithMockKeystore.onPageLoad()(request)

        // check
        status(result) shouldBe 200
        val htmlPage = contentAsString(await(result))
        htmlPage should include ("""<input id="TaxYear2015" type="checkbox" name="TaxYear2015" checked>""")
        htmlPage should include ("""<input id="TaxYear2016" type="checkbox" name="TaxYear2016" >""")

      }
    }
  }

  "onYearSelected with POST request" should {
    "display error message if no years selected" in new ControllerWithMockKeystore {
      // set up
      implicit val hc = HeaderCarrier()
      implicit val request = FakeRequest(POST, endPointURL).withSession((SessionKeys.sessionId,SESSION_ID)).withFormUrlEncodedBody(("csrfToken" -> "blah"),("previous"->""))

      // test
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(request)

      // check
      status(result) shouldBe 200
      val htmlPage = contentAsString(await(result))
      htmlPage should include ("""Choose at least 1 tax year.""")
      dumpHtml("error_taxyearselection", htmlPage)
    }

    "not return result NOT_FOUND" in {
      val result: Option[Future[Result]] = route(FakeRequest(POST, endPointURL))
      result.isDefined shouldBe true
      status(result.get) should not be NOT_FOUND
    }

    "return 303 for valid GET request" in new ControllerWithMockKeystore {
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(FakeRequest(POST, endPointURL))
      status(result) shouldBe 303
    }

    "have valid TaxYearSelection saved to keystore" in new ControllerWithMockKeystore {
      // set up
      implicit val hc = HeaderCarrier()
      implicit val request = FakeRequest(POST, endPointURL).withSession((SessionKeys.sessionId,SESSION_ID)).withFormUrlEncodedBody(("csrfToken" -> "blah"),("TaxYear2015" -> "2015"),("previous"->""))
      MockKeystore.map = MockKeystore.map + ("TaxYearSelection" -> "2015")
      MockKeystore.map = MockKeystore.map + (KeystoreService.IS_EDIT_KEY -> "false")
      MockKeystore.map = MockKeystore.map + (KeystoreService.TE_YES_NO_KEY -> "false")

      // test
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(request)

      // check
      status(result) shouldBe 303
      MockKeystore.map(KeystoreService.CURRENT_INPUT_YEAR_KEY) shouldBe ("2015")
      MockKeystore.map(KeystoreService.SELECTED_INPUT_YEARS_KEY) shouldBe ("2015")
      redirectLocation(result) shouldBe Some("/paac/scheme/2015")
    }

    "when unselecting a previously selected year reset year's data value" in new ControllerWithMockKeystore {
      // set up
      implicit val hc = HeaderCarrier()
      implicit val request = FakeRequest(POST, endPointURL).withSession((SessionKeys.sessionId,SESSION_ID)).withFormUrlEncodedBody(("csrfToken" -> "blah"),("TaxYear2014" -> "2014"),("previous"->"2014,2013"))
      MockKeystore.map = MockKeystore.map + ("TaxYearSelection" -> "2014,2013")
      MockKeystore.map = MockKeystore.map + (KeystoreService.IS_EDIT_KEY -> "false")
      MockKeystore.map = MockKeystore.map + (KeystoreService.TE_YES_NO_KEY -> "false")
      MockKeystore.map = MockKeystore.map + (KeystoreService.DB_PREFIX + "2013" -> "100")
      MockKeystore.map = MockKeystore.map + (KeystoreService.DC_PREFIX + "2013" -> "200")

      // test
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(request)

      // check
      status(result) shouldBe 303
      MockKeystore.map(KeystoreService.DB_PREFIX + "2013") shouldBe ("")
      MockKeystore.map(KeystoreService.DC_PREFIX + "2013") shouldBe ("")
      MockKeystore.map(KeystoreService.CURRENT_INPUT_YEAR_KEY) shouldBe ("2014")
      MockKeystore.map(KeystoreService.SELECTED_INPUT_YEARS_KEY) shouldBe ("2014")
    }

    "when unselecting 2015 when previously selected reset 2015's data values" in new ControllerWithMockKeystore {
      // set up
      implicit val hc = HeaderCarrier()
      implicit val request = FakeRequest(POST, endPointURL).withSession((SessionKeys.sessionId,SESSION_ID)).withFormUrlEncodedBody(("csrfToken" -> "blah"),("TaxYear2014" -> "2014"),("previous"->"2015,2013"))
      MockKeystore.map = MockKeystore.map + ("TaxYearSelection" -> "2014")
      MockKeystore.map = MockKeystore.map + (KeystoreService.IS_EDIT_KEY -> "false")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P1_DB_KEY -> "100")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P1_DC_KEY -> "200")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P2_DB_KEY -> "300")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P2_DC_KEY -> "400")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P1_TRIGGER_DC_KEY -> "500")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P2_TRIGGER_DC_KEY -> "600")
      MockKeystore.map = MockKeystore.map + (KeystoreService.TRIGGER_DATE_KEY -> "2015-11-1")
      MockKeystore.map = MockKeystore.map + (KeystoreService.TE_YES_NO_KEY -> "Yes")

      // test
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(request)

      // check
      status(result) shouldBe 303
      MockKeystore.map(KeystoreService.CURRENT_INPUT_YEAR_KEY) shouldBe ("2014")
      MockKeystore.map(KeystoreService.SELECTED_INPUT_YEARS_KEY) shouldBe ("2014")
      MockKeystore.map(KeystoreService.P1_DB_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.P1_DC_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.P2_DB_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.P2_DC_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.P1_TRIGGER_DC_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.P2_TRIGGER_DC_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.TRIGGER_DATE_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.TE_YES_NO_KEY) shouldBe ("")
    }

    "when unselecting 2016 when previously selected reset 2016's data values" in new ControllerWithMockKeystore {
      // set up
      implicit val hc = HeaderCarrier()
      implicit val request = FakeRequest(POST, endPointURL).withSession((SessionKeys.sessionId,SESSION_ID)).withFormUrlEncodedBody(("csrfToken" -> "blah"),("TaxYear2014" -> "2014"),("previous"->"2016,2013"))
      MockKeystore.map = MockKeystore.map + ("TaxYearSelection" -> "2014")
      MockKeystore.map = MockKeystore.map + (KeystoreService.IS_EDIT_KEY -> "false")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P1_DB_KEY -> "100")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P1_DC_KEY -> "200")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P2_DB_KEY -> "300")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P2_DC_KEY -> "400")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P1_TRIGGER_DC_KEY -> "500")
      MockKeystore.map = MockKeystore.map + (KeystoreService.P2_TRIGGER_DC_KEY -> "600")
      MockKeystore.map = MockKeystore.map + (KeystoreService.TRIGGER_DATE_KEY -> "2015-11-1")
      MockKeystore.map = MockKeystore.map + (KeystoreService.TE_YES_NO_KEY -> "Yes")

      // test
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(request)

      // check
      status(result) shouldBe 303
      MockKeystore.map(KeystoreService.CURRENT_INPUT_YEAR_KEY) shouldBe ("2014")
      MockKeystore.map(KeystoreService.SELECTED_INPUT_YEARS_KEY) shouldBe ("2014")
      MockKeystore.map(KeystoreService.TRIGGER_DATE_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.TRIGGER_DC_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.FIRST_DC_YEAR_KEY) shouldBe ("")
      MockKeystore.map(KeystoreService.TI_YES_NO_KEY_PREFIX) shouldBe ("")
      MockKeystore.map(KeystoreService.DB_PREFIX+"2016") shouldBe ("")
      MockKeystore.map(KeystoreService.DC_PREFIX+"2016") shouldBe ("")
      MockKeystore.map(KeystoreService.DB_FLAG_PREFIX+"2016") shouldBe ("")
      MockKeystore.map(KeystoreService.DC_FLAG_PREFIX+"2016") shouldBe ("")
      MockKeystore.map(KeystoreService.TH_PREFIX+"2016") shouldBe ("")
      MockKeystore.map(KeystoreService.AI_PREFIX+"2016") shouldBe ("")
      MockKeystore.map(KeystoreService.TA_PREFIX+"2016") shouldBe ("")
    }

    "return TaxYearSelection results from keystore" in new ControllerWithMockKeystore {
      // set up
      val request = FakeRequest(POST, endPointURL).withSession {(SessionKeys.sessionId,SESSION_ID)}

      // test
      val result: Future[Result] = ControllerWithMockKeystore.onYearSelected()(request)

      // check
      val htmlSummaryPage = contentAsString(await(result))
      htmlSummaryPage should include ("Choose tax years")
    }
  }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace Forseti
{
	public class PiEMOSConfiger : HashPacketListener
	{
		private HashConnection conn;
		private string piemosAddress;
		private string config;
		private bool done;

		public PiEMOSConfiger (string piemosAddress, int listen, int send, string config)
		{
			this.conn = new HashConnection(listen, send);
			this.conn.AddHashConPacketListener(this);
			this.piemosAddress = piemosAddress;
			this.config = config;
			this.done = false;
			//			this.SendCommand ("Reset");
		}

		public bool Running
		{
			get;
			set;
		}

		public void Start()
		{
			Thread runner = new Thread(this.Run);
			runner.Start();
		}

		public void Run()
		{
			long startTime = DateTime.Now.Ticks / TimeSpan.TicksPerSecond;

			this.conn.Start();
			this.Running = true;
			while(this.Running)
			{
				// Heartbeat
				long time = DateTime.Now.Ticks / TimeSpan.TicksPerSecond - startTime;
				Hashtable t = new Hashtable();
				t["Type"] = "Health";
				t["Uptime"] = time;
				//				Console.WriteLine("time=" + time);
				this.conn.SendTable(t, this.piemosAddress);

				this.SendCommand("Reset");

//				if(!done)
//				{
//					this.SendConfigData (this.config);
//				}

				Thread.Sleep (500);
			}
		}

		public void HashPacketReceived (Hashtable t, string senderAddress)
		{
			if (t.ContainsKey("Health"))
			{
				Hashtable payload = (Hashtable) t["Health"];
				string piemos_state = (string)payload["PiEMOSState"];
				if(piemos_state.Equals ("MatchStartWaiting"))
				{
					Console.WriteLine ("Config Received!!!!!!!!");
					done = true;
				}
			}
		}

		private void Send(string name, Hashtable t)
		{
			Hashtable wrapper = new Hashtable();
			wrapper[name] = t;
			this.conn.SendTable(wrapper, this.piemosAddress);
		}

		private void Send( Hashtable t)
		{
			this.conn.SendTable(t, this.piemosAddress);
		}

		public bool ConfigIsBlueAlliance;
		public int ConfigTeamNumber;
		public string ConfigTeamName;

		public void SendConfigData(string configFile){
			string txt = configFile;//configText.text;
			txt = txt.Replace("\r", "").Replace("\n", "").Replace("\t", "");

			Hashtable table = new Hashtable();

			table.Add("ConfigFile", txt);
			table.Add("IsBlueAlliance", false);
			table.Add("TeamNumber", 99);
			table.Add("TeamName", "Jank");

			ArrayList fieldObjects = new ArrayList();//fieldObjectsText.text.arrayListFromJson();
			table.Add("FieldObjects", fieldObjects);

			Send("ConfigData",table);
		}

		public void SendCommand(string cmd){
			Hashtable table = new Hashtable();
			table.Add("Command", cmd);
			Send(table);
		}

		public bool autonomous;
		public bool teleop;
		public bool robot;
		public bool halt;
		public byte matchTime;
		public string stage;

		void SendControlData(){
			Hashtable table = new Hashtable();

			Hashtable opMode = new Hashtable();

			opMode.Add("FieldAutonomousEnabled", autonomous);
			opMode.Add("FieldTeleopEnabled", teleop);
			opMode.Add("FieldRobotEnabled", robot);
			opMode.Add("HaltRadio", halt);

			table.Add("OperationMode", opMode);

			Hashtable match = new Hashtable();
			match.Add("Time", (float)matchTime);
			match.Add("Stage", stage);

			table.Add("Match", match);

			Send("ControlData", table);
		}
	}
}


text:
describe('DayGrid event rendering', function() {
  pushOptions({
    defaultDate: '2014-08-01', // 2014-07-27 - 2014-10-07 (excl)
    defaultView: 'month'
  })

  describe('when LTR', function() {
    initMonthTesting(false)
  })
  describe('when RTL', function() {
    initMonthTesting(true)
  })

  function initMonthTesting(isRTL) {
    it('correctly renders an event starting before view\'s start', function() {
      var options = {}
      options.events = [
        { start: '2014-07-26', end: '2014-07-30' }
      ]

      var testSegOptions = {
        firstCol: 0,
        lastCol: 2,
        isStart: false,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event starting at view\'s start', function() {
      var options = {}
      options.events = [
        { start: '2014-07-27', end: '2014-07-29' }
      ]

      var testSegOptions = {
        firstCol: 0,
        lastCol: 1,
        isStart: true,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event starting after view\'s start', function() {
      var options = {}
      options.events = [
        { start: '2014-08-01', end: '2014-08-02' }
      ]

      var testSegOptions = {
        firstCol: 5,
        lastCol: 5,
        isStart: true,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event starting on a hidden day at week start', function() {
      var options = {}
      options.weekends = false
      options.events = [
        { start: '2014-07-27', end: '2014-07-30' }
      ]

      var testSegOptions = {
        firstCol: 0,
        lastCol: 1,
        isStart: false,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event starting on a hidden day in middle of week', function() {
      var options = {}
      options.hiddenDays = [ 2 ] // hide Tues
      options.events = [
        { start: '2014-07-29', end: '2014-08-01' }
      ]

      var testSegOptions = {
        firstCol: 2,
        lastCol: 3,
        isStart: false,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event ending before view\'s end', function() {
      var options = {}
      options.events = [
        { start: '2014-09-02', end: '2014-09-05' }
      ]
      var testSegOptions = {
        row: 5,
        firstCol: 2,
        lastCol: 4,
        isStart: true,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event ending at view\'s end', function() {
      var options = {}
      options.events = [
        { start: '2014-09-04', end: '2014-09-07' }
      ]

      var testSegOptions = {
        row: 5,
        firstCol: 4,
        lastCol: 6,
        isStart: true,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event ending after view\'s end', function() {
      var options = {}
      options.events = [
        { start: '2014-09-04', end: '2014-09-08' }
      ]
      var testSegOptions = {
        row: 5,
        firstCol: 4,
        lastCol: 6,
        isStart: true,
        isEnd: false
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event ending at a week\'s end', function() {
      var options = {}
      options.events = [
        { start: '2014-08-28', end: '2014-08-31' }
      ]
      var testSegOptions = {
        row: 4,
        firstCol: 4,
        lastCol: 6,
        isStart: true,
        isEnd: true
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event ending on a hidden day at week end', function() {
      var options = {}
      options.weekends = false
      options.events = [
        { start: '2014-07-30', end: '2014-08-03' }
      ]
      var testSegOptions = {
        firstCol: 2,
        lastCol: 4,
        isStart: true,
        isEnd: false
      }
      testSeg(options, testSegOptions)
    })

    it('correctly renders an event ending on a hidden day in middle of week', function() {
      var options = {}
      options.hiddenDays = [ 4 ] // Thurs
      options.events = [
        { start: '2014-07-28', end: '2014-08-01' }
      ]
      var testSegOptions = {
        firstCol: 1,
        lastCol: 3,
        isStart: true,
        isEnd: false
      }
      testSeg(options, testSegOptions)
    })

    function testSeg(calendarOptions, testSegOptions) {
      calendarOptions.isRTL = isRTL
      initCalendar(calendarOptions)
      directionallyTestSeg(testSegOptions, isRTL)
    }
  }

  it('rendering of events across weeks stays consistent', function() {
    var options = {}
    options.events = [
      {
        title: 'event1',
        start: '2014-08-01',
        end: '2014-08-04',
        className: 'event1'
      },
      {
        title: 'event2',
        start: '2014-08-02',
        end: '2014-08-05',
        className: 'event2'
      }
    ]
    initCalendar(options)
    var row0 = $('.fc-day-grid .fc-row:eq(0)')
    var row0event1 = row0.find('.event1')
    var row0event2 = row0.find('.event2')
    var row1 = $('.fc-day-grid .fc-row:eq(1)')
    var row1event1 = row1.find('.event1')
    var row1event2 = row1.find('.event2')
    expect(row0event1.offset().top).toBeLessThan(row0event2.offset().top)
    expect(row1event1.offset().top).toBeLessThan(row1event2.offset().top)
  })

  it('renders an event with no url with no <a> href', function() {
    var options = {}
    options.events = [ {
      title: 'event1',
      start: '2014-08-01'
    } ]
    initCalendar(options)
    var seg = $('.fc-event')
    expect(seg).not.toHaveAttr('href')
  })

  it('renders an event with a url with an <a> href', function() {
    var options = {}
    options.events = [ {
      title: 'event1',
      start: '2014-08-01',
      url: 'http://google.com/'
    } ]
    initCalendar(options)
    var seg = $('.fc-event')
    expect(seg).toHaveAttr('href')
  })

  /*
  opts:
    - el (optional)
    - row (optional)
    - firstCol
    - lastCol
    - isStart
    - isEnd
  */
  function directionallyTestSeg(opts, isRTL) {
    var el = $(opts.el || '.fc-event:first')

    var row = opts.row || 0
    var rowTds = $('.fc-day-grid .fc-row:eq(' + row + ') .fc-day')
    expect(rowTds.length).toBeGreaterThan(1)

    var leftCol
    var rightCol
    if (isRTL) {
      leftCol = rowTds.length - opts.lastCol - 1
      rightCol = rowTds.length - opts.firstCol - 1
    } else {
      leftCol = opts.firstCol
      rightCol = opts.lastCol
    }

    var col, td

    for (col = leftCol; col <= rightCol; col++) {
      td = rowTds.eq(col)
      expect(el).toIntersectWith(td)
    }

    for (col = 0; col < rowTds.length; col++) {
      if (col < leftCol || col > rightCol) {
        td = rowTds.eq(col)
        expect(el).not.toIntersectWith(td)
      }
    }

    if (opts.isStart) {
      expect(el).toHaveClass('fc-start')
    } else {
      expect(el).not.toHaveClass('fc-start')
    }

    if (opts.isEnd) {
      expect(el).toHaveClass('fc-end')
    } else {
      expect(el).not.toHaveClass('fc-end')
    }
  }

})


text:
-- phpMyAdmin SQL Dump
-- version 4.2.12deb2+deb8u1
-- http://www.phpmyadmin.net
--
-- Client :  sqletud.univ-mlv.fr
-- Généré le :  Sam 20 Février 2016 à 11:35
-- Version du serveur :  5.5.40-0+wheezy1-log
-- Version de PHP :  5.6.14-0+deb8u1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Base de données :  `jchattou_db`
--

-- --------------------------------------------------------

--
-- Structure de la table `Personnels`
--

CREATE TABLE IF NOT EXISTS `Personnels` (
`personnel_id` int(11) NOT NULL,
  `nom` varchar(32) COLLATE latin1_general_ci NOT NULL,
  `prenom` varchar(32) COLLATE latin1_general_ci NOT NULL,
  `num_adeli` varchar(32) COLLATE latin1_general_ci DEFAULT NULL,
  `num_RPPS` varchar(32) COLLATE latin1_general_ci DEFAULT NULL,
  `telephone_mobile` varchar(12) COLLATE latin1_general_ci DEFAULT NULL,
  `telephone_fixe` varchar(12) COLLATE latin1_general_ci DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `pole_id` int(11) NOT NULL,
  `poleResponsable_id` int(11) NOT NULL,
  `services_id` int(11) NOT NULL,
  `servicesResponsable_id` int(11) NOT NULL,
  `specialite_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

--
-- Index pour les tables exportées
--

--
-- Index pour la table `Personnels`
--
ALTER TABLE `Personnels`
 ADD PRIMARY KEY (`personnel_id`), ADD KEY `FK_Personnels_pole_id` (`pole_id`), ADD KEY `FK_Personnels_pole_id_Poles` (`poleResponsable_id`), ADD KEY `FK_Personnels_services_id` (`services_id`), ADD KEY `FK_Personnels_services_id_Services` (`servicesResponsable_id`), ADD KEY `FK_Personnels_specialite_id` (`specialite_id`);

--
-- AUTO_INCREMENT pour les tables exportées
--

--
-- AUTO_INCREMENT pour la table `Personnels`
--
ALTER TABLE `Personnels`
MODIFY `personnel_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=21;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
<!DOCTYPE html>

    <title>EasyJob</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.5/sweetalert2.min.css">
    <link rel="stylesheet" href="assets/css/ng-animate.css">
    <link rel="stylesheet" href="assets/css/style.css">


text:
package org.kurento.test.functional.player;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;
import org.kurento.client.EndOfStreamEvent;
import org.kurento.client.EventListener;
import org.kurento.client.MediaPipeline;
import org.kurento.client.PlayerEndpoint;
import org.kurento.client.WebRtcEndpoint;
import org.kurento.test.base.FunctionalTest;
import org.kurento.test.browser.WebRtcChannel;
import org.kurento.test.browser.WebRtcMode;
import org.kurento.test.config.TestScenario;

/**
 * Test of a the stop/release features for a PlayerEndpoint.
 *

 * Media Pipeline(s):
 *

 *
PlayerEndpoint -> WebRtcEndpoint

 *

 * Browser(s):
 *

 *
Chrome

 *
Firefox

 *

 * Test logic:
 *

 *
(KMS) During the playback of a stream from a PlayerEndpoint to a WebRtcEndpoint, the
 * PlayerEndpoint is stopped/released

 *
(Browser) WebRtcPeer in rcv-only receives media

 *

 * Main assertion(s):
 *

 *
EndOfStream event cannot be received since the stop is done before the end of the video

 *

 * Secondary assertion(s):
 *

 *
Playing event should be received in remote video tag

 *

 *
 * @author Boni Garcia (bgarcia@gsyc.es)
 * @since 6.1.1
 */
public class PlayerEndTest extends FunctionalTest {

  @Parameters(name = "{index}: {0}")
  public static Collection<Object[]> data() {
    return TestScenario.localChromeAndFirefox();
  }

  private enum PlayerOperation {
    STOP, RELEASE;
  }

  @Test
  public void testPlayerStop() throws Exception {
    doTest(PlayerOperation.STOP);
  }

  @Test
  public void testPlayerRelease() throws Exception {
    doTest(PlayerOperation.RELEASE);
  }

  public void doTest(PlayerOperation playerOperation) throws Exception {
    // Test data
    final String mediaUrl = "http://" + getTestFilesHttpPath() + "/video/format/small.webm";
    final int guardTimeSeconds = 10;

    // Media Pipeline
    MediaPipeline mp = kurentoClient.createMediaPipeline();
    PlayerEndpoint playerEp = new PlayerEndpoint.Builder(mp, mediaUrl).build();
    WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(mp).build();
    playerEp.connect(webRtcEp);

    // Subscription to EOS event
    final boolean[] eos = new boolean[1];
    eos[0] = false;
    playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
      @Override
      public void onEvent(EndOfStreamEvent event) {
        log.error("EOS event received: {} {}", event.getType(), event.getTimestampMillis());
        eos[0] = true;
      }
    });

    // WebRTC in receive-only mode
    getPage().subscribeEvents("playing");
    getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
    playerEp.play();
    Assert.assertTrue("Not received media (timeout waiting playing event)",
        getPage().waitForEvent("playing"));

    // Stop/release stream and wait x seconds
    switch (playerOperation) {
      case STOP:
        playerEp.stop();
        break;
      case RELEASE:
        playerEp.release();
        break;
    }
    Thread.sleep(TimeUnit.SECONDS.toMillis(guardTimeSeconds));

    // Verify that EOS event has not being received
    Assert.assertFalse("EOS event has been received. "
        + "This should not be happenning because the stream has been stopped", eos[0]);

    // Release Media Pipeline
    mp.release();
  }
}


text:
package org.elasticsearch.action.admin.cluster.storedscripts;

import org.elasticsearch.action.Action;
import org.elasticsearch.client.ElasticsearchClient;

/**
 */
public class GetStoredScriptAction extends Action<GetStoredScriptRequest, GetStoredScriptResponse,
        GetStoredScriptRequestBuilder> {

    public static final GetStoredScriptAction INSTANCE = new GetStoredScriptAction();
    public static final String NAME = "cluster:admin/script/get";

    private GetStoredScriptAction() {
        super(NAME);
    }

    @Override
    public GetStoredScriptResponse newResponse() {
        return new GetStoredScriptResponse();
    }

    @Override
    public GetStoredScriptRequestBuilder newRequestBuilder(ElasticsearchClient client) {
        return new GetStoredScriptRequestBuilder(client, this);
    }

}