text:
from query_parser import queryData
import datetime
from bsddb3 import db
from csv import reader

def termSearch(parsedSearch, ptermsCursor, rtermsCursor):
    termLengthTable = []
    # make a list to check the number of terms in the parsedSearch
    termLengthTable.append(len(parsedSearch[0]))    # length of pterms
    termLengthTable.append(len(parsedSearch[1]))    # length of rterms
    termLengthTable.append(len(parsedSearch[5]))    # length of part_terms
    termLengthTable.append(len(parsedSearch[6]))    # length of terms
    # check for case if no terms, but there are range searches
    if termLengthTable[0] == 0 and termLengthTable[1] == 0 and termLengthTable[2] == 0 and termLengthTable[3] == 0:
        return None
    # there exist terms, search using the terms
    resultIDs1 = list()
    resultIDs2 = list()
    resultIDs3 = list()
    resultIDs4 = list()
    index = 0
    for length in termLengthTable:
        if index == 0 and length != 0:  # if pterms has something, search in pterms.idx only
            ptermsLength = termLengthTable[0]
            for ptermsIndex in range (0, ptermsLength):
                encodedTerm = (parsedSearch[0][ptermsIndex]).encode()
                iter = ptermsCursor.get(encodedTerm, db.DB_SET_RANGE)   # move cursor to the first item that has the term
                while iter[0] == encodedTerm:
                    resultIDs1.append(iter[1])
                    iter = ptermsCursor.next()
        elif index == 1 and length !=0:   # if rterms has something, search in rterms.idx only
            rtermsLength = len(parsedSearch[1])
            for rtermsIndex in range(0, rtermsLength):
                 encodedTerm = (parsedSearch[1][rtermsIndex]).encode()
                 iter = rtermsCursor.get(encodedTerm, db.DB_SET_RANGE)
                 while iter[0] == encodedTerm:
                     resultIDs2.append(iter[1])
                     iter = rtermsCursor.next()
        elif index == 2 and length != 0:  # if part_terms has something, search for partial matching strings in pterms.idx and rterms.idx
            part_termsLength = len(parsedSearch[5])
            for part_termsIndex in range(0, part_termsLength):
                term = parsedSearch[5][part_termsIndex].strip("%")
                encodedTerm = term.encode()
                #encodedTerm = (parsedSearch[5][part_termsIndex]).encode()
                iter = rtermsCursor.get(encodedTerm, db.DB_SET_RANGE)   #search in rterms
                while (iter[0].decode()).startswith(term, 0, len(term)):
                    resultIDs3.append(iter[1])
                    iter = rtermsCursor.next()
                iter = ptermsCursor.get(encodedTerm, db.DB_SET_RANGE)   #search in pterms
                while (iter[0].decode()).startswith(term, 0, len(term)):
                    resultIDs3.append(iter[1])
                    iter = ptermsCursor.next()
        elif index == 3 and length != 0:    # if terms has something, search for the string in both pterms.idx and rterms.idx
            termsLength = termLengthTable[3]
            for termsIndex in range(0, termsLength):
                encodedTerm = parsedSearch[6][termsIndex].encode()
                iter1 = ptermsCursor.get(encodedTerm, db.DB_SET_RANGE)   # move cursor to the first item that has the term
                while iter1[0] == encodedTerm:
                    resultIDs4.append(iter1[1])
                    iter1 = ptermsCursor.next()
                iter2 = rtermsCursor.get(encodedTerm, db.DB_SET_RANGE)
                while iter2[0] == encodedTerm:
                    resultIDs4.append(iter2[1])
                    iter2 = rtermsCursor.next()
        index+=1
        # all possible IDs should be found - do range searching now to narrow results
    completeList = [resultIDs1, resultIDs2, resultIDs3, resultIDs4]
    resultIDs = set(resultIDs1 or resultIDs2 or resultIDs3 or resultIDs4)
    for results in completeList:
        if len(results) > 0:
            resultIDs = resultIDs & set(results)
    return resultIDs

def numberFilter(parsedSearch, resultIDs, lowerScoresCursor, higherScoresCursor, reviewsCursor, reviews):
    # do pprice, rscore, rdate searches on possible IDs returned from termSearch
    termLengthTable = list()
    termLengthTable.append(len(parsedSearch[2]))    # length of pprice
    termLengthTable.append(len(parsedSearch[3]))    # length of rscore
    termLengthTable.append(len(parsedSearch[4]))    # length of rdate

    index = 0
    validLowerScoreIDs = list()
    validHigherScoreIDs = list()
    for amount in range(0, termLengthTable[1]):
        signChecked = parsedSearch[3][index][1]
        numberChecked = float(parsedSearch[3][index][2])
        if signChecked == "<":    #less than search. gets all the items from beginning up to the number
            lowerIter = lowerScoresCursor.first()

            while lowerIter is not None and float(lowerIter[0].decode()) < numberChecked:
                validLowerScoreIDs.append(lowerIter[1])
                lowerIter = lowerScoresCursor.next()
        elif signChecked == ">":  #greater than search. gets all the items from end down to the number
            upperIter = higherScoresCursor.last()
            while upperIter is not None and float(upperIter[0].decode()) > numberChecked:
                validHigherScoreIDs.append(upperIter[1])
                upperIter=higherScoresCursor.prev()
        index+=1

    if resultIDs != None:
        scoreResults = resultIDs
        if termLengthTable[1] > 1:
            scoreResults = scoreResults & validLowerScoreIDs
            scoreResults = scoreResults & validHigherScoreIDs
        elif termLengthTable[1] == 1:
            if signChecked == '<':
                scoreResults = scoreResults & set(validLowerScoreIDs)
            elif signChecked == '>':
                scoreResults = scoreResults & set(validHigherScoreIDs)

    else:
        scoreResults = set()
        if termLengthTable[1] > 1:
            scoreResults = scoreResults | validLowerScoreIDs
            scoreResults = scoreResults | validHigherScoreIDs
        elif termLengthTable[1] == 1:
            if signChecked == '<':
                scoreResults = scoreResults | set(validLowerScoreIDs)
            elif signChecked == '>':
                scoreResults = scoreResults | set(validHigherScoreIDs)

    '''
    # datetime conversion
    datetime.datetime.strptime("2013/02/14","%Y/%m/%d").timestamp() #to timestamp format
    datetime.datetime.fromtimestamp(int(1369029600)).strftime("%Y/%m/%d") # from timestamp format
    '''
    dateIndex = 0 # dateIndex is terms in parsed search under rdate, 0 = no dates, 1 = 1 date, 2 = range of dates
    validLowerDateIDs = list()
    validHigherDateIDs = list()
    dateResults = list()
    if (termLengthTable[2]) > 0:   #there is some rdate criterias
        while dateIndex < termLengthTable[2]:
            for encodedID in scoreResults:
                iter = reviewsCursor.first()
                iter = reviews.get(encodedID, db.DB_SET)
                iter = iter.decode()
                iter = [entry for entry in reader([iter])][0]
                dateTerm = parsedSearch[4][dateIndex]
                extractedDate = str(datetime.datetime.strptime(parsedSearch[4][dateIndex][2],"%Y/%m/%d").timestamp())  #date of input
                currentDate = iter[7]   #date of data
                if dateTerm[1] == '<':
                        if float(currentDate) < float(extractedDate):
                            validLowerDateIDs.append(encodedID)
                if dateTerm[1] == '>':
                        if float(currentDate) > float(extractedDate):
                            validHigherDateIDs.append(encodedID)
            dateIndex += 1
    dateResults = scoreResults
    if termLengthTable[2] > 1:
        dateResults = dateResults & set(validLowerDateIDs)
        dateResults = dateResults & set(validHigherDateIDs)
    elif termLengthTable[2] == 1:
        if parsedSearch[4][0][1] == '<':
            dateResults = dateResults & set(validLowerDateIDs)
        elif parsedSearch[4][0][1] == '>':
            dateResults = dateResults & set(validHigherDateIDs)

    ppriceIndex = 0
    validLowerPriceIDs = list()
    validHigherPriceIDs = list()
    priceResults = list()
    if (termLengthTable[0])>0: #there are some pprice criteria
        while ppriceIndex < termLengthTable[0]:
            for encodedID in dateResults:
                iter = reviews.get(encodedID, db.DB_SET)
                iter = iter.decode()
                iter = [entry for entry in reader([iter])][0]
                priceTerm = parsedSearch[2][ppriceIndex]
                checkPrice = priceTerm[2]
                currentPrice = iter[2]
                if priceTerm[1] == '<':
                        if currentPrice != 'unknown' and float(currentPrice) < float(checkPrice):
                            validLowerPriceIDs.append(encodedID)
                if priceTerm[1] == '>':
                    if currentPrice != 'unknown' and float(currentPrice) > float(checkPrice):
                        validHigherPriceIDs.append(encodedID)
            ppriceIndex+=1

    priceResults = dateResults
    if termLengthTable[0] > 1:
        priceResults = priceResults & set(validLowerPriceIDs)
        priceResults = priceResults & set(validHigherPriceIDs)
    elif termLengthTable[0] == 1:
        if parsedSearch[2][0][1] == '<':
            priceResults = priceResults & set(validLowerPriceIDs)
        elif parsedSearch[2][0][1] == '>':
            priceResults = priceResults & set(validHigherPriceIDs)
    finalResults = priceResults
    return finalResults

def printReviews(finalResults, reviews):
    for ID in finalResults:
        review = reviews.get(ID, db.DB_SET)
        review = review.decode()
        review = [entry for entry in reader([review])][0]
        print("Entry:" + ID.decode())
        print("Product ID:" + review[0])
        print("Product Title:" + review[1])
        print("Product Price:" + review[2])
        print("UserID:" + review[3])
        print("Profile Name:" + review[4])
        print("Helpfulness:" + review[5])
        print("Score:" + review[6])
        print("Review Time:" + datetime.datetime.fromtimestamp(int(review[7])).strftime("%Y/%m/%d"))
        print("Review Summary:" + review[8])
        print("Review Text:" + review[9])
        print("------------")

def returnResults(query):
    #Initialization of index files using BerkeleyDB
    reviews = db.DB()
    pterms = db.DB()
    rterms = db.DB()
    scores = db.DB()
    reviews.open("rw.idx")
    pterms.open("pt.idx")
    rterms.open("rt.idx")
    scores.open("sc.idx")

    reviewsCursor = reviews.cursor()
    ptermsCursor = pterms.cursor()
    rtermsCursor = rterms.cursor()
    lowerScoresCursor = scores.cursor()
    higherScoresCursor = scores.cursor()

    parsedSearch = queryData(query)
    terms = termSearch(parsedSearch, ptermsCursor, rtermsCursor)
    filtered = numberFilter(parsedSearch, terms, lowerScoresCursor, higherScoresCursor, reviewsCursor, reviews)
    printReviews(filtered, reviews)

    reviewsCursor.close()
    ptermsCursor.close()
    rtermsCursor.close()
    lowerScoresCursor.close()
    higherScoresCursor.close()
    reviews.close()
    pterms.close()
    rterms.close()
    scores.close()

if __name__ == "__main__":
    while True:
        print("Enter nothing to exit")
        query = input("query: ")
        if query == "":
            break

        returnResults(query)


text:
<?php

error_reporting(E_STRICT | E_ALL);

// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once 'Google/Api/Ads/Dfp/Util/StatementBuilder.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';

// Set the ID of the first party audience segment to populate.
$audienceSegmentId = 'INSERT_AUDIENCE_SEGMENT_ID_HERE';

try {
  // Get DfpUser from credentials in "../auth.ini"
  // relative to the DfpUser.php file's directory.
  $user = new DfpUser();

  // Log SOAP XML request and response.
  $user->LogDefaults();

  // Get the AudienceSegmentService.
  $audienceSegmentService =
      $user->GetService('AudienceSegmentService', 'v201411');

  // Create a statement to only select a specified first party audience
  // segment.
  $statementBuilder = new StatementBuilder();
  $statementBuilder->Where('id = :id and type = :type')
      ->OrderBy('id ASC')
      ->Limit(1)
      ->WithBindVariableValue('id', $audienceSegmentId)
      ->WithBindVariableValue('type', 'FIRST_PARTY');

  // Default for total result set size.
  $totalResultSetSize = 0;

  do {
    // Get audience segments by statement.
    $page = $audienceSegmentService->getAudienceSegmentsByStatement(
        $statementBuilder->ToStatement());

    // Display results.
    if (isset($page->results)) {
      $totalResultSetSize = $page->totalResultSetSize;
      $i = $page->startIndex;
      foreach ($page->results as $audienceSegment) {
        printf("%d) Audience segment with ID %d and name '%s' will be "
            . "populated.\n", $i++, $audienceSegment->id,
            $audienceSegment->name);
      }
    }

    $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT);
  } while ($statementBuilder->GetOffset() < $totalResultSetSize);

  printf("Number of audience segments to be populated: %d\n",
      $totalResultSetSize);

  if ($totalResultSetSize > 0) {
    // Remove limit and offset from statement.
    $statementBuilder->RemoveLimitAndOffset();

    // Create action.
    $action = new PopulateAudienceSegments();

    // Perform action.
    $result = $audienceSegmentService->performAudienceSegmentAction($action,
        $statementBuilder->ToStatement());

    // Display results.
    if (isset($result) && $result->numChanges > 0) {
      printf("Number of audience segments populated: %d\n",
          $result->numChanges);
    } else {
      printf("No audience segments were populated.\n");
    }
  }
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
  printf("%s\n", $e->getMessage());
}

redpajama_set_name: RedPajamaGithub


text:
extern void log_serial(char* log_line);

void consolelogger_log(unsigned int options, char* format, ...)
{
        char temp_buf[256];
	va_list args;
	va_start(args, format);
	vsprintf(temp_buf, format, args);
	va_end(args);
        //log_serial(temp_buf);

	if (options & LOG_LINE)
	{
		//log_serial("\r\n");
	}
}


text:
package org.springframework.cloud.dataflow.server.configuration;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.batch.core.configuration.support.MapJobRegistry;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.batch.BatchDataSourceInitializer;
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.dataflow.audit.repository.AuditRecordRepository;
import org.springframework.cloud.dataflow.audit.service.AuditRecordService;
import org.springframework.cloud.dataflow.audit.service.DefaultAuditRecordService;
import org.springframework.cloud.dataflow.configuration.metadata.ApplicationConfigurationMetadataResolver;
import org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver;
import org.springframework.cloud.dataflow.registry.repository.AppRegistrationRepository;
import org.springframework.cloud.dataflow.registry.service.AppRegistryService;
import org.springframework.cloud.dataflow.registry.service.DefaultAppRegistryService;
import org.springframework.cloud.dataflow.registry.support.AppResourceCommon;
import org.springframework.cloud.dataflow.server.DockerValidatorProperties;
import org.springframework.cloud.dataflow.server.batch.JobService;
import org.springframework.cloud.dataflow.server.batch.SimpleJobServiceFactoryBean;
import org.springframework.cloud.dataflow.server.config.apps.CommonApplicationProperties;
import org.springframework.cloud.dataflow.server.controller.JobExecutionController;
import org.springframework.cloud.dataflow.server.controller.JobExecutionThinController;
import org.springframework.cloud.dataflow.server.controller.JobInstanceController;
import org.springframework.cloud.dataflow.server.controller.JobStepExecutionController;
import org.springframework.cloud.dataflow.server.controller.JobStepExecutionProgressController;
import org.springframework.cloud.dataflow.server.controller.RestControllerAdvice;
import org.springframework.cloud.dataflow.server.controller.TaskExecutionController;
import org.springframework.cloud.dataflow.server.controller.TaskPlatformController;
import org.springframework.cloud.dataflow.server.job.LauncherRepository;
import org.springframework.cloud.dataflow.server.repository.TaskDefinitionRepository;
import org.springframework.cloud.dataflow.server.repository.TaskDeploymentRepository;
import org.springframework.cloud.dataflow.server.service.TaskDeleteService;
import org.springframework.cloud.dataflow.server.service.TaskExecutionCreationService;
import org.springframework.cloud.dataflow.server.service.TaskExecutionInfoService;
import org.springframework.cloud.dataflow.server.service.TaskExecutionService;
import org.springframework.cloud.dataflow.server.service.TaskJobService;
import org.springframework.cloud.dataflow.server.service.TaskSaveService;
import org.springframework.cloud.dataflow.server.service.TaskValidationService;
import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskDeleteService;
import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskExecutionInfoService;
import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskExecutionRepositoryService;
import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskExecutionService;
import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskJobService;
import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskSaveService;
import org.springframework.cloud.dataflow.server.service.impl.TaskAppDeploymentRequestCreator;
import org.springframework.cloud.dataflow.server.service.impl.TaskConfigurationProperties;
import org.springframework.cloud.dataflow.server.service.impl.validation.DefaultTaskValidationService;
import org.springframework.cloud.deployer.resource.maven.MavenProperties;
import org.springframework.cloud.deployer.spi.task.TaskLauncher;
import org.springframework.cloud.task.batch.listener.TaskBatchDao;
import org.springframework.cloud.task.batch.listener.support.JdbcTaskBatchDao;
import org.springframework.cloud.task.repository.TaskExplorer;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.cloud.task.repository.support.SimpleTaskExplorer;
import org.springframework.cloud.task.repository.support.SimpleTaskRepository;
import org.springframework.cloud.task.repository.support.TaskExecutionDaoFactoryBean;
import org.springframework.cloud.task.repository.support.TaskRepositoryInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.map.repository.config.EnableMapRepositories;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import static org.mockito.Mockito.mock;

/**
 * @author Glenn Renfro
 * @author Gunnar Hillert
 */
@Configuration
@EnableSpringDataWebSupport
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
@ImportAutoConfiguration({ HibernateJpaAutoConfiguration.class, FlywayAutoConfiguration.class })
@EnableWebMvc
@EnableTransactionManagement
@EntityScan({
		"org.springframework.cloud.dataflow.server.audit.domain",
		"org.springframework.cloud.dataflow.core"
})
@EnableJpaRepositories(basePackages = {
		"org.springframework.cloud.dataflow.registry.repository",
		"org.springframework.cloud.dataflow.server.repository",
		"org.springframework.cloud.dataflow.audit.repository"
})
@EnableJpaAuditing
@EnableConfigurationProperties({ DockerValidatorProperties.class, TaskConfigurationProperties.class })
@EnableMapRepositories(basePackages = "org.springframework.cloud.dataflow.server.job")
public class JobDependencies {

	@Bean
	public AuditRecordService auditRecordService(AuditRecordRepository auditRecordRepository) {
		return new DefaultAuditRecordService(auditRecordRepository);
	}

	@Bean
	public TaskValidationService taskValidationService(AppRegistryService appRegistry,
			DockerValidatorProperties dockerValidatorProperties, TaskDefinitionRepository taskDefinitionRepository,
			TaskConfigurationProperties taskConfigurationProperties) {
		return new DefaultTaskValidationService(appRegistry, dockerValidatorProperties, taskDefinitionRepository,
				taskConfigurationProperties.getComposedTaskRunnerName());
	}

	@Bean
	public ApplicationConfigurationMetadataResolver metadataResolver() {
		return new BootApplicationConfigurationMetadataResolver();
	}

	@Bean
	public JobExecutionController jobExecutionController(TaskJobService repository) {
		return new JobExecutionController(repository);
	}

	@Bean
	public JobExecutionThinController jobExecutionThinController(TaskJobService repository) {
		return new JobExecutionThinController(repository);
	}

	@Bean
	public JobStepExecutionController jobStepExecutionController(JobService jobService) {
		return new JobStepExecutionController(jobService);
	}

	@Bean
	public JobStepExecutionProgressController jobStepExecutionProgressController(JobService jobService) {
		return new JobStepExecutionProgressController(jobService);
	}

	@Bean
	public JobInstanceController jobInstanceController(TaskJobService repository) {
		return new JobInstanceController(repository);
	}

	@Bean
	public TaskExecutionController taskExecutionController(TaskExplorer explorer,
			TaskExecutionService taskExecutionService,
			TaskDefinitionRepository taskDefinitionRepository, TaskExecutionInfoService taskExecutionInfoService,
			TaskDeleteService taskDeleteService) {
		return new TaskExecutionController(explorer, taskExecutionService, taskDefinitionRepository,
				taskExecutionInfoService,
				taskDeleteService);
	}

	@Bean
	public TaskPlatformController taskPlatformController(LauncherRepository launcherRepository) {
		return new TaskPlatformController(launcherRepository);
	}

	@Bean
	public TaskRepositoryInitializer taskExecutionRepository(DataSource dataSource) {
		TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer();
		taskRepositoryInitializer.setDataSource(dataSource);
		return taskRepositoryInitializer;
	}

	@Bean
	public TaskJobService taskJobExecutionRepository(JobService jobService, TaskExplorer taskExplorer,
			TaskDefinitionRepository taskDefinitionRepository, TaskExecutionService taskExecutionService,
													 TaskDeploymentRepository taskDeploymentRepository) {
		return new DefaultTaskJobService(jobService, taskExplorer, taskDefinitionRepository, taskExecutionService,
				taskDeploymentRepository);
	}

	@Bean
	public TaskDeleteService deleteTaskService(TaskExplorer taskExplorer, LauncherRepository launcherRepository,
			TaskDefinitionRepository taskDefinitionRepository,
			TaskDeploymentRepository taskDeploymentRepository,
			AuditRecordService auditRecordService) {
		return new DefaultTaskDeleteService(taskExplorer, launcherRepository, taskDefinitionRepository,
				taskDeploymentRepository,
				auditRecordService);
	}

	@Bean
	public TaskSaveService saveTaskService(TaskDefinitionRepository taskDefinitionRepository,
			AuditRecordService auditRecordService, AppRegistryService registry) {
		return new DefaultTaskSaveService(taskDefinitionRepository, auditRecordService, registry);
	}

	@Bean
	public TaskExecutionCreationService taskExecutionRepositoryService(TaskRepository taskRepository) {
		return new DefaultTaskExecutionRepositoryService(taskRepository);
	}

	@Bean
	TaskAppDeploymentRequestCreator taskAppDeploymentRequestCreator(
			CommonApplicationProperties commonApplicationProperties,
			ApplicationConfigurationMetadataResolver metadataResolver) {
		return new TaskAppDeploymentRequestCreator(commonApplicationProperties,
				metadataResolver, null);
	}

	@Bean
	public TaskExecutionService taskService(LauncherRepository launcherRepository,
			AuditRecordService auditRecordService, TaskRepository taskRepository,
			TaskExecutionInfoService taskExecutionInfoService,
			TaskDeploymentRepository taskDeploymentRepository,
			TaskExecutionCreationService taskExecutionRepositoryService,
			TaskAppDeploymentRequestCreator taskAppDeploymentRequestCreator) {
		return new DefaultTaskExecutionService(
				launcherRepository, auditRecordService,
				taskRepository,
				taskExecutionInfoService, taskDeploymentRepository,
				taskExecutionRepositoryService, taskAppDeploymentRequestCreator);
	}

	@Bean
	public TaskExecutionInfoService taskDefinitionRetriever(AppRegistryService registry,
			TaskExplorer taskExplorer, TaskDefinitionRepository taskDefinitionRepository,
			TaskConfigurationProperties taskConfigurationProperties) {
		return new DefaultTaskExecutionInfoService(new DataSourceProperties(),
				registry, taskExplorer, taskDefinitionRepository,
				taskConfigurationProperties);
	}

	@Bean
	public TaskRepository taskRepository() {
		return new SimpleTaskRepository(new TaskExecutionDaoFactoryBean());
	}

	@Bean
	public TaskBatchDao taskBatchDao(DataSource dataSource) {
		return new JdbcTaskBatchDao(dataSource);
	}

	@Bean
	public SimpleJobServiceFactoryBean simpleJobServiceFactoryBean(DataSource dataSource,
			JobRepositoryFactoryBean repositoryFactoryBean, JobExplorer jobExplorer,
			PlatformTransactionManager dataSourceTransactionManager) {
		SimpleJobServiceFactoryBean factoryBean = new SimpleJobServiceFactoryBean();
		factoryBean.setDataSource(dataSource);
		try {
			factoryBean.setJobRepository(repositoryFactoryBean.getObject());
			factoryBean.setJobLocator(new MapJobRegistry());
			factoryBean.setJobLauncher(new SimpleJobLauncher());
			factoryBean.setJobExplorer(jobExplorer);
			factoryBean.setTransactionManager(dataSourceTransactionManager);
		}
		catch (Exception e) {
			throw new IllegalStateException(e);
		}
		return factoryBean;
	}

	@Bean
	public JobRepositoryFactoryBean jobRepositoryFactoryBeanForServer(DataSource dataSource,
			PlatformTransactionManager platformTransactionManager) {
		JobRepositoryFactoryBean repositoryFactoryBean = new JobRepositoryFactoryBean();
		repositoryFactoryBean.setDataSource(dataSource);
		repositoryFactoryBean.setTransactionManager(platformTransactionManager);
		return repositoryFactoryBean;
	}

	@Bean
	public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
		return new JpaTransactionManager(entityManagerFactory);
	}

	@Bean
	public JobExplorerFactoryBean jobExplorerFactoryBeanForServer(DataSource dataSource) {
		JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
		jobExplorerFactoryBean.setDataSource(dataSource);
		return jobExplorerFactoryBean;
	}

	@Bean
	public BatchDataSourceInitializer batchRepositoryInitializerForDefaultDBForServer(DataSource dataSource,
			ResourceLoader resourceLoader, BatchProperties properties) {
		return new BatchDataSourceInitializer(dataSource, resourceLoader, properties);
	}

	@Bean
	public TaskExplorer taskExplorer(TaskExecutionDaoFactoryBean daoFactoryBean) {
		return new SimpleTaskExplorer(daoFactoryBean);
	}

	@Bean
	public TaskExecutionDaoFactoryBean taskExecutionDaoFactoryBean(DataSource dataSource) {
		return new TaskExecutionDaoFactoryBean(dataSource);
	}

	@Bean
	public RestControllerAdvice restControllerAdvice() {
		return new RestControllerAdvice();
	}

	@Bean
	public AppRegistryService appRegistryService(AppRegistrationRepository appRegistrationRepository,
			AuditRecordService auditRecordService) {
		return new DefaultAppRegistryService(appRegistrationRepository,
				new AppResourceCommon(new MavenProperties(), new DefaultResourceLoader()), auditRecordService);
	}

	@Bean
	public TaskLauncher taskLauncher() {
		return mock(TaskLauncher.class);
	}

}


text:
<%page expression_filter="h"/>
<%!
from openedx.core.djangolib.markup import HTML, Text
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.conf import settings
%>
<%inherit file="main.html" />

<%namespace name='static' file='static_content.html'/>

${_("Unsubscribe Successful!")}

      ${Text(
        _("You will no longer receive forum notification emails from {platform_name}. "
          "You may {dashboard_link_start}return to your dashboard{link_end}. "
          "If you did not mean to do this, {undo_link_start}you can re-subscribe{link_end}."
        )).format(
            platform_name=settings.PLATFORM_NAME,
            dashboard_link_start=HTML("").format(reverse('dashboard')),
            undo_link_start=HTML("").format(reverse('resubscribe_forum_update', args=[token])),
            link_end=HTML(""),
        )}


text:
"""Test Driver wrapper for running for Cast STL conformance tests.

To run:
  $ python ./run_test.py <manifest file>
"""

import sys

import test_driver

if __name__ == '__main__':
  sys.exit(0 if test_driver.Main() else 1)


text:
from mlflow.entities import Metric
from mlflow.utils.time_utils import get_current_time_millis
from tests.helper_functions import random_str, random_int

def _check(metric, key, value, timestamp, step):
    assert type(metric) == Metric
    assert metric.key == key
    assert metric.value == value
    assert metric.timestamp == timestamp
    assert metric.step == step

def test_creation_and_hydration():
    key = random_str()
    value = 10000
    ts = get_current_time_millis()
    step = random_int()

    metric = Metric(key, value, ts, step)
    _check(metric, key, value, ts, step)

    as_dict = {"key": key, "value": value, "timestamp": ts, "step": step}
    assert dict(metric) == as_dict

    proto = metric.to_proto()
    metric2 = metric.from_proto(proto)
    _check(metric2, key, value, ts, step)

    metric3 = Metric.from_dictionary(as_dict)
    _check(metric3, key, value, ts, step)


text:
/*
 * Created by IntelliJ IDEA.
 * User: Lennart
 * Date: 23-jan-03
 * Time: 9:49:30
 */
package com.compomics.dbtoolkit.io.implementations;

import com.compomics.dbtoolkit.io.interfaces.Filter;
import com.compomics.util.protein.Protein;
import org.apache.batik.script.rhino.WindowWrapper;

import java.util.HashMap;
import java.util.StringTokenizer;

/*
 * CVS information:
 *
 * $Revision: 1.3 $
 * $Date: 2007/07/06 09:52:03 $
 */

/**
 * This class implements the ProteinFilter interface for Protein mass.
 *
 * @author Lennart Martens
 */
public class FASTAProteinSequenceLengthFilter extends ProteinSequenceLengthFilter {

    /**
     * This constructor takes the upper and lower mass limits for this filter.
     *
     * @param   aParameter  String with the less than/larger than character, and the length threshold
     *                              If no less than/larger than is specified, it is taken to be minimal length
     */
    public FASTAProteinSequenceLengthFilter(String aParameter) {
        super(aParameter);
    }

    /**
     * This method returns a flag that indicates whether the specified protein sequence string
     * (in FASTA format) passes the filter.
     *
     * @param   aEntry    String with the protein sequence string in FASTA format.
     * @return  boolean 'true' if the specified Protein passes the filter, 'false' otherwise.
     */
    public boolean passesFilter(String aEntry) {
        boolean passed = false;

        // Check the header.
        HashMap hm = new HashMap(2);
        StringTokenizer lSt = new StringTokenizer(aEntry, "\n");
        hm.put("HEADER", lSt.nextToken());
        hm.put("SEQUENCE", lSt.nextToken());

        passed = this.passesFilter(hm);

        return passed;

    }

    /**
     * This method returns a flag that indicates whether the specified protein sequence string
     * (in key-value Map format) passes the filter.
     *
     * @param   aEntry    String with the protein sequence string in key-value Map format.
     * @return  boolean 'true' if the specified Protein passes the filter, 'false' otherwise.
     */
    public boolean passesFilter(HashMap aEntry) {
        boolean passed = false;

        Object os = aEntry.get("SEQUENCE");
        if(os != null) {
            int sequenceLength = ((String)os).length();
            if(iLargerThan && sequenceLength >= iLength) {
                passed = true;
            } else if(!iLargerThan && sequenceLength <= iLength) {
                passed = true;
            }
        }

        return passed;
    }
}


text:
require 'spec_helper'

RSpec.describe RailsAdmin::Config::Fields::Types::Numeric do
  it_behaves_like 'a generic field type', :integer_field, :integer

  subject do
    RailsAdmin.config('FieldTest').fields.detect do |f|
      f.name == :integer_field
    end.with(object: FieldTest.new)
  end

  describe '#view_helper' do
    it "uses the 'number' type input tag" do
      expect(subject.view_helper).to eq(:number_field)
    end
  end
end


text:
#import "NSObject.h"

#import "TSDArrangeInspectorDelegate-Protocol.h"

@class NSObject<TSDCanvasEditor>;

// Not exported
@interface TSDDrawableZOrderArranger : NSObject <TSDArrangeInspectorDelegate>
{
    NSObject<TSDCanvasEditor> *mCanvasEditor;
    _Bool mCanCoalesceZOrderCommand;
}

- (unsigned long long)p_zOrderIndex;
- (unsigned long long)p_maxIndex;
- (unsigned long long)p_minIndex;
- (id)p_zOrderSelection;
- (id)p_zOrderSiblings;
- (_Bool)shouldShowWrapOptionsForSelectedDrawables;
- (void)moveToFrontForArrangeInspector;
- (void)moveFrontForArrangeInspector;
- (void)moveBackForArrangeInspector;
- (void)moveToBackForArrangeInspector;
- (void)arrangeInspectorDidEndChangingZValue:(unsigned long long)arg1;
- (void)arrangeInspectorDidSetZValue:(unsigned long long)arg1;
- (void)arrangeInspectorWillBeginChangingZValue:(unsigned long long)arg1;
- (unsigned long long)currentZValueForArrangeInspector;
- (unsigned long long)maxZValueForArrangeInspector;
- (unsigned long long)minZValueForArrangeInspector;
- (id)commandToSetZOrderOfInfos:(id)arg1 toIndexes:(id)arg2 coalesceable:(_Bool)arg3;
- (id)initWithCanvasEditor:(id)arg1;

@end


text:
( function () {
    'use strict';

    var OSG = window.OSG;
    var osgViewer = OSG.osgViewer;
    var osg = OSG.osg;
    var osgDB = OSG.osgDB;

    function colorFloatTo255( color ) {
        return [ color[ 0 ] * 255.0, color[ 1 ] * 255.0, color[ 2 ] * 255.0 ];
    }

    function color255ToFloat( color ) {
        return [ color[ 0 ] / 255.0, color[ 1 ] / 255.0, color[ 2 ] / 255.0 ];
    }

    var Example = function () {};

    Example.prototype = {

        // the root node
        scene: undefined,
        model: undefined,
        ground: new window.Ground(),
        scale: 1.0,
        debugDiv: document.getElementById( 'debug' ),
        gui: undefined,
        params: undefined,
        viewer: undefined,

        run: function () {
            this.cacheURLs = {};

            var canvas = document.getElementById( 'View' );

            this.viewer = new osgViewer.Viewer( canvas );
            this.viewer.init();
            this.viewer.getCamera().setClearColor( [ 0.005, 0.005, 0.005, 1.0 ] );

            this.scene = new osg.Node();
            this.scene.addChild( this.ground );

            this.viewer.setSceneData( this.scene );
            this.viewer.setupManipulator();

            this.viewer.run();
            this.initGui();
            this.changeModel( 'file.osgjs' );
        },
        initGui: function () {
            this.gui = new window.dat.GUI();
            var self = this;
            // config to let dat.gui change the scale
            this.params = {
                model: 'file.osgjs',
                adjustY: 0.001,
                groundColor: colorFloatTo255( self.ground.getColor() ),
                backgroundColor: colorFloatTo255( self.viewer.getCamera().getClearColor() ),
                reset: function () {
                    self.resetHeightAndGui();
                },
            };

            var modelController = this.gui.add( this.params, 'model', [ 'file.osgjs', 'sphere' ] );
            modelController.onFinishChange( function ( value ) {
                self.changeModel( value );
            } );
            var adjustYController = this.gui.add( this.params, 'adjustY', -1.0, 1.0 );
            adjustYController.onChange( function ( value ) {
                self.ground.setNormalizedHeight( value );
            } );
            this.gui.add( this.params, 'reset' ).name( 'Reset ground height' );
            var colorController = this.gui.addColor( this.params, 'groundColor' );
            colorController.onChange( function ( color ) {
                self.ground.setColor( color255ToFloat( color ) );
            } );
            var backgroundColorController = this.gui.addColor( this.params, 'backgroundColor' );
            backgroundColorController.onChange( function ( color ) {
                var temp = [ 0.0, 0.0, 0.0 ];
                temp[ 0 ] = Math.pow( color[ 0 ] / 255.0, 2.2 );
                temp[ 1 ] = Math.pow( color[ 1 ] / 255.0, 2.2 );
                temp[ 2 ] = Math.pow( color[ 2 ] / 255.0, 2.2 );
                self.viewer.getCamera().setClearColor( temp );
            } );
        },
        resetHeightAndGui: function () {

            this.ground.setGroundFromModel( this.model );

            this.params.adjustY = this.ground.getNormalizedHeight();
            // Update gui
            for ( var i in this.gui.__controllers )
                this.gui.__controllers[ i ].updateDisplay();
        },
        setModel: function ( model ) {
            this.scene.removeChild( this.model );

            this.model = model;
            this.resetHeightAndGui();

            this.scene.addChild( this.model );
            this.viewer.getManipulator().computeHomePosition();
        },
        changeModel: function ( key ) {
            if ( this.cacheURLs[ key ] )
                return this.setModel( this.cacheURLs[ key ] );

            if ( key === 'sphere' ) {
                var sphere = this.cacheURLs[ key ] = osg.createTexturedSphere( 1.0, 20, 20 );
                return this.setModel( sphere );
            }

            osgDB.readNodeURL( '../media/models/material-test/' + key ).then( function ( model ) {
                this.cacheURLs[ key ] = model;
                this.setModel( model );
            }.bind( this ) );
        }
    };

    window.addEventListener( 'load', function () {
        var example = new Example();
        example.run();
    }, true );
} )();


text:
package org.guvnor.m2repo.backend.server;

import javax.enterprise.inject.Instance;

import org.guvnor.m2repo.backend.server.repositories.ArtifactRepository;
import org.guvnor.m2repo.backend.server.repositories.ArtifactRepositoryProducer;
import org.guvnor.m2repo.backend.server.repositories.ArtifactRepositoryService;
import org.guvnor.m2repo.preferences.ArtifactRepositoryPreference;
import org.junit.Before;
import org.junit.Test;
import org.uberfire.backend.server.cdi.workspace.WorkspaceNameResolver;
import org.uberfire.mocks.MockInstanceImpl;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class JarPathTest {

    private GuvnorM2Repository repository;

    @Before
    public void setupGuvnorM2Repository() {
        ArtifactRepositoryPreference pref = mock(ArtifactRepositoryPreference.class);
        when(pref.getGlobalM2RepoDir()).thenReturn("repositories/kie");
        when(pref.isGlobalM2RepoDirEnabled()).thenReturn(true);
        when(pref.isDistributionManagementM2RepoDirEnabled()).thenReturn(true);
        when(pref.isWorkspaceM2RepoDirEnabled()).thenReturn(false);
        WorkspaceNameResolver resolver = mock(WorkspaceNameResolver.class);
        when(resolver.getWorkspaceName()).thenReturn("global");
        ArtifactRepositoryProducer producer = new ArtifactRepositoryProducer(pref,
                                                                             resolver);
        producer.initialize();
        Instance<ArtifactRepository> repositories = new MockInstanceImpl<>(producer.produceLocalRepository(),
                                                                           producer.produceGlobalRepository(),
                                                                           producer.produceDistributionManagementRepository());
        ArtifactRepositoryService factory = new ArtifactRepositoryService(repositories);
        repository = new GuvnorM2Repository(factory);
        repository.init();
    }

    @Test
    public void testLinuxPathSeparators() {
        final M2RepoServiceImpl service = new M2RepoServiceImpl(this.repository);
        final String jarPath = service.getJarPath(repository.getM2RepositoryDir(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME) + "/a/b/c",
                                                  "/");
        assertEquals("a/b/c",
                     jarPath);
    }

    @Test
    public void testWindowsPathSeparators() {
        final M2RepoServiceImpl service = new M2RepoServiceImpl(this.repository);
        final String jarPath = service.getJarPath(repository.getM2RepositoryDir(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME) + "\\a\\b\\c",
                                                  "\\");
        assertEquals("a/b/c",
                     jarPath);
    }
}


text:
import { createStore } from 'redux';

// Reducers
import rootReducer from '../../client/reducers/index';
import data from '../../client/reducers/data_reducer';
import isError from '../../client/reducers/isError';
import isLoading from '../../client/reducers/isLoading';

// Actions
import {
  setErrored,
  setLoading,
  receive
} from '../../client/actions/index';

import { mockData } from '../mockData';

describe('Reducers', () => {
  let store;

  beforeEach(() => {
    store = createStore(rootReducer);
  });

  describe('root reducer', () => {

    test('should return the initialState', () => {
      let expected = rootReducer(undefined, {});
      let initialState = store.getState();

      expect(initialState).toEqual(expected);
    });

  });

  describe('Error reducer', () => {

    test('should handle errors for the correct data set', () => {
      let error = new TypeError('Second argument passed to "receive" action should be an array', 'actions/index.js', 31);
      let errorAction = setErrored('tournaments', error);

      let reducerResult = isError(undefined, errorAction);
      store.dispatch(errorAction);

      return expect(store.getState().isError).toEqual(reducerResult);
    });

  });

  describe('Loading reducer', () => {

    test('should handle loading events properly', () => {
      let loadTournaments = setLoading('tournaments', true);
      let gotTournaments = setLoading('tournaments', false);
      let loadPlayers = setLoading('players', true);

      store.dispatch(loadTournaments);
      expect(store.getState().isLoading).toEqual(isLoading(undefined, loadTournaments));

      store.dispatch(gotTournaments);
      store.dispatch(loadPlayers);
      expect(store.getState().isLoading).toEqual(isLoading(undefined, loadPlayers));
      store.dispatch(setLoading('players', false));
    });

  });

  describe('Data reducer', () => {

    test('should return the initialState', () => {

      expect(data(undefined, {})).toEqual({games: {}, players: {}, tournaments: {}, table: {}});
    });

    test('should return normalized state', () => {

      let action = receive('games', mockData.games);
      store.dispatch(action);
      expect(store.getState().data).toEqual(data(undefined, action));
      expect(store.getState().isError).toEqual(isError(undefined, action));
      expect(store.getState().isLoading).toEqual(isLoading(undefined, action));
    });
  });

});


text:
@import UIKit;

NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, TWLocationsPickerSource) {
    TWLocationsPickerSourceCities = 0,
    TWLocationsPickerSourceDistricts
};

@protocol TWLocationsPickerControllerDelegate;
@interface TWLocationsPickerController : UITableViewController

@property (assign) TWLocationsPickerSource pickerSource;

@property (assign) NSUInteger cityID;
@property (assign) NSUInteger districtID;

+ (instancetype)locationPickerWithDelegate:(id<TWLocationsPickerControllerDelegate>)delegate;
- (instancetype)initWithDelegate:(id<TWLocationsPickerControllerDelegate>)delegate;

@end

@protocol TWLocationsPickerControllerDelegate <NSObject>

@optional
- (void)locationsPicker:(TWLocationsPickerController *)picker didPickCity:(TWCity *)city;

- (void)locationsPicker:(TWLocationsPickerController *)picker didPickDistrict:(TWDistrict *)district;

@end
NS_ASSUME_NONNULL_END


text:
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CStockChartOleApp

BEGIN_MESSAGE_MAP(CStockChartOleApp, CWinApp)
	//{{AFX_MSG_MAP(CStockChartOleApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
		// HINWEIS - Hier werden Mapping-Makros vom Klassen-Assistenten eingefügt und entfernt.
		//    Innerhalb dieser generierten Quelltextabschnitte NICHTS VERÄNDERN!
	//}}AFX_MSG_MAP
	// Dateibasierte Standard-Dokumentbefehle
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
	// Standard-Druckbefehl "Seite einrichten"
	ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CStockChartOleApp Konstruktion

CStockChartOleApp::CStockChartOleApp()
{
	// ZU ERLEDIGEN: Hier Code zur Konstruktion einfügen
	// Alle wichtigen Initialisierungen in InitInstance platzieren
}

/////////////////////////////////////////////////////////////////////////////
// Das einzige CStockChartOleApp-Objekt

CStockChartOleApp theApp;

// Dieser Bezeichner wurde als statistisch eindeutig für Ihre Anwendung generiert.
// Sie können ihn ändern, wenn Sie einen bestimmten Bezeichnernamen bevorzugen.

// {50CB22AB-0C37-11D2-B53C-006097A8F69A}
static const CLSID clsid =
{ 0x50cb22ab, 0xc37, 0x11d2, { 0xb5, 0x3c, 0x0, 0x60, 0x97, 0xa8, 0xf6, 0x9a } };

/////////////////////////////////////////////////////////////////////////////
// CStockChartOleApp Initialisierung

BOOL CStockChartOleApp::InitInstance()
{

	// OLE-Bibliotheken initialisieren
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}

	// Standardinitialisierung
	// Wenn Sie diese Funktionen nicht nutzen und die Größe Ihrer fertigen
	//  ausführbaren Datei reduzieren wollen, sollten Sie die nachfolgenden
	//  spezifischen Initialisierungsroutinen, die Sie nicht benötigen, entfernen.

#ifdef _AFXDLL
	Enable3dControls();			// Diese Funktion bei Verwendung von MFC in gemeinsam genutzten DLLs aufrufen
#else
	Enable3dControlsStatic();	// Diese Funktion bei statischen MFC-Anbindungen aufrufen
#endif

	// Ändern des Registrierungsschlüssels, unter dem unsere Einstellungen gespeichert sind.
	// Sie sollten dieser Zeichenfolge einen geeigneten Inhalt geben
	// wie z.B. den Namen Ihrer Firma oder Organisation.
	SetRegistryKey(_T("Addison Wesley Longman"));

	LoadStdProfileSettings();  // Standard-INI-Dateioptionen einlesen (einschließlich MRU)

	// Dokumentvorlagen der Anwendung registrieren. Dokumentvorlagen
	//  dienen als Verbindung zwischen Dokumenten, Rahmenfenstern und Ansichten.

	CMultiDocTemplate* pDocTemplate;
	pDocTemplate = new CMultiDocTemplate(
		IDR_STOCKCTYPE,
		RUNTIME_CLASS(CStockChartOleDoc),
		RUNTIME_CLASS(CChildFrame), // Benutzerspezifischer MDI-Child-Rahmen
		RUNTIME_CLASS(CStockChartOleView));
	pDocTemplate->SetServerInfo(
		IDR_STOCKCTYPE_SRVR_EMB, IDR_STOCKCTYPE_SRVR_IP,
		RUNTIME_CLASS(CInPlaceFrame));
	AddDocTemplate(pDocTemplate);

	// Verbinden des COleTemplateServer mit der Dokumentvorlage.
	//  Der COleTemplateServer legt auf Basis der Informationen in der
	//  Dokumentvorlage bei der Anforderung von OLE-Containern
	//  neue Dokumente an.
	m_server.ConnectTemplate(clsid, pDocTemplate, FALSE);

	// Alle OLE-Server (-fabriken) als aktiv registrieren. Dies aktiviert die
	//  OLE-Bibliotheken, um Objekte von anderen Anwendungen zu erstellen.
	COleTemplateServer::RegisterAll();
		// Hinweis: MDI-Anwendungen registrieren alle Server-Objekte, ohne Rücksicht
		//  auf die Parameter /Embedding oder /Automation in der Befehlszeile.

	// Haupt-MDI-Rahmenfenster erzeugen
	CMainFrame* pMainFrame = new CMainFrame;
	if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
		return FALSE;
	m_pMainWnd = pMainFrame;

	// Öffnen per DragDrop aktivieren
	m_pMainWnd->DragAcceptFiles();

	// DDE-Execute-Open aktivieren
	EnableShellOpen();
	RegisterShellFileTypes(TRUE);

	// Befehlszeile parsen, um zu prüfen auf Standard-Umgebungsbefehle DDE, Datei offen
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Testen, ob Ausführung als OLE-Server
	if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated)
	{
		// Anwendung mit /Embedding oder /Automation gestartet. In diesem Fall
		//  kein Hauptfenster anzeigen.
		return TRUE;
	}

	// Wird eine Server-Anwendung im Standalone-Modus betrieben, ist es ratsam,
	//  die Systemregistrierung zu aktualisieren, falls diese beschädigt wurde.
	m_server.UpdateRegistry(OAT_INPLACE_SERVER);

	// Verteilung der in der Befehlszeile angegebenen Befehle
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// Das Hauptfenster ist initialisiert und kann jetzt angezeigt und aktualisiert werden.
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg-Dialogfeld für Anwendungsbefehl "Info"

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialogfelddaten
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// Vom Klassenassistenten generierte Überladungen virtueller Funktionen
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV-Unterstützung
	//}}AFX_VIRTUAL

// Implementierung
protected:
	//{{AFX_MSG(CAboutDlg)
		// Keine Nachrichten-Handler
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// Keine Nachrichten-Handler
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// Anwendungsbefehl, um das Dialogfeld aufzurufen
void CStockChartOleApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CStockChartOleApp-Befehle


text:
declare class C { x: number; }

var x: string = new C().x;

interface I { x: number; }

var i = new I(); // error

function testInterfaceName(o: I) {
  (o.name: string); // error, name is static
  (o.constructor.name: string); // ok
}

declare var y : { x? : string};

(y : interface { x? : string });

({ x : 3 } : interface { x : string | number });

interface J {
  x?: number;
}

class D {
  x: number;
}

(new D : J); // error, x is invariant

declare var o : {[string] : number};

(o : interface {[string] : number});
({x : 3} : interface {[string] : number});

declare var o2 : interface {[string] : number};
(o2["a"] : number);
(o2["b"] : boolean); // error

declare var o3 : {[string] : number};

(o3 : interface {[string] : boolean}); // error
({x : 3} : interface {[string] : boolean}); // error

(o3: interface {[number] : number}); // error
({x : 3} : interface {[number] : number}); // error

declare var o4 : {["asdf"] : number};

(o4 : interface {[string] : number}); // error

declare var o5 : {+["asdf"] : number};

(o5 : interface {+[string] : number});

declare var o6 : {[string] : number};

(o6 : interface {["asdf"] : number}); // error


text:
package net.blay09.mods.cookingbook.client.render;

import net.blay09.mods.cookingbook.CookingForBlockheads;
import net.blay09.mods.cookingbook.CookingConfig;
import net.blay09.mods.cookingbook.block.TileEntityFridge;
import net.blay09.mods.cookingbook.client.model.ModelFridge;
import net.blay09.mods.cookingbook.client.model.ModelSmallFridge;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;

public class TileEntityFridgeRenderer extends TileEntitySpecialRenderer {

    private static final ResourceLocation textureSmall = new ResourceLocation("cookingbook", "textures/entity/ModelSmallFridge.png");
    private static final ResourceLocation textureBig = new ResourceLocation("cookingbook", "textures/entity/ModelFridge.png");

    private ModelFridge modelBig = new ModelFridge();
    private ModelSmallFridge modelSmall = new ModelSmallFridge();
    public static final float[][] fridgeColorTable = new float[][] {{1.0F, 1.0F, 1.0F}, {0.85F, 0.5F, 0.2F}, {0.7F, 0.3F, 0.85F}, {0.4F, 0.6F, 0.85F}, {0.9F, 0.9F, 0.2F}, {0.5F, 0.8F, 0.1F}, {0.95F, 0.5F, 0.65F}, {0.3F, 0.3F, 0.3F}, {0.6F, 0.6F, 0.6F}, {0.3F, 0.5F, 0.6F}, {0.5F, 0.25F, 0.7F}, {0.2F, 0.3F, 0.7F}, {0.4F, 0.3F, 0.2F}, {0.4F, 0.5F, 0.2F}, {0.6F, 0.2F, 0.2F}, {0.1F, 0.1F, 0.1F}};

    @Override
    public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float delta) {
        int metadata = 0;
        boolean isLargeFridge = false;
        TileEntityFridge tileEntityFridge = (TileEntityFridge) tileEntity;
        boolean isDoorFlipped = tileEntityFridge.isFlipped();
        int dye = tileEntityFridge.getFridgeColor();
        if(tileEntity.hasWorldObj()) {
            metadata = tileEntity.getBlockMetadata();
            Block above = tileEntity.getWorldObj().getBlock(tileEntity.xCoord, tileEntity.yCoord + 1, tileEntity.zCoord);
            if(above == CookingForBlockheads.blockFridge) {
                isLargeFridge = true;
            }
            Block below = tileEntity.getWorldObj().getBlock(tileEntity.xCoord, tileEntity.yCoord - 1, tileEntity.zCoord);
            if(below == CookingForBlockheads.blockFridge) {
                return;
            }
        }

        GL11.glPushMatrix();
        boolean oldRescaleNormal = GL11.glIsEnabled(GL12.GL_RESCALE_NORMAL);
        if(oldRescaleNormal) {
            GL11.glEnable(GL12.GL_RESCALE_NORMAL);
        }
        GL11.glTranslatef((float) x, (float) y + 1f, (float) z);
        GL11.glTranslatef(0.5f, 0.5f, 0.5f);
        float angle;
        switch(ForgeDirection.getOrientation(metadata)) {
            case NORTH:
                angle = 0;
                break;
            case EAST:
                angle = -90;
                break;
            case SOUTH:
                angle = 180;
                break;
            case WEST:
                angle = 90;
                break;
            default:
                angle = -90;
        }
        GL11.glColor4f(1f, 1f, 1f, 1f);
        GL11.glRotatef(angle, 0f, 1f, 0f);
        GL11.glRotatef(180f, 0f, 0f, 1f);
        float doorAngle = tileEntityFridge.getPrevDoorAngle() + (tileEntityFridge.getDoorAngle() - tileEntityFridge.getPrevDoorAngle()) * delta;
        doorAngle = 1.0f - doorAngle;
        doorAngle = 1.0f - doorAngle * doorAngle * doorAngle;
        if(isLargeFridge) {
            TileEntityFridge upperFridge = tileEntityFridge.findNeighbourFridge();
            if(upperFridge != null) {
                float neighbourDoorAngle = upperFridge.getPrevDoorAngle() + (upperFridge.getDoorAngle() - upperFridge.getPrevDoorAngle()) * delta;
                if(neighbourDoorAngle > doorAngle) {
                    doorAngle = neighbourDoorAngle;
                }
            }
            modelBig.setFlipped(isDoorFlipped);
            if(isDoorFlipped) {
                modelBig.DoorFlipped.rotateAngleY = -(float) ((Math.PI / 2f) * doorAngle);
                modelBig.DoorHandleFlipped.rotateAngleY = -(float) ((Math.PI / 2f) * doorAngle);
            } else {
                modelBig.Door.rotateAngleY = (float) ((Math.PI / 2f) * doorAngle);
                modelBig.DoorHandle.rotateAngleY = (float) ((Math.PI / 2f) * doorAngle);
            }
            bindTexture(textureBig);
            modelBig.renderUncolored();
            GL11.glColor4f(fridgeColorTable[dye][0], fridgeColorTable[dye][1], fridgeColorTable[dye][2], 1f);
            modelBig.renderColored();
            if(doorAngle > 0f) {
                GL11.glColor4f(1f, 1f, 1f, 1f);
                modelBig.renderInterior();
                GL11.glRotatef(180f, 0f, 0f, -1f);
                GL11.glScalef(0.5f, 0.5f, 0.5f);
                if(!CookingConfig.disableItemRender && Minecraft.getMinecraft().gameSettings.fancyGraphics) {
                    int largeFridgeSize = tileEntityFridge.getSizeInventory() + (upperFridge != null ? upperFridge.getSizeInventory() : 0);
                    for (int i = 0; i < largeFridgeSize; i++) {
                        ItemStack itemStack = (i >= tileEntityFridge.getSizeInventory() && upperFridge != null) ? upperFridge.getStackInSlot(i - tileEntityFridge.getSizeInventory()) : tileEntityFridge.getStackInSlot(i);
                        if (itemStack != null) {
                            int shelfCapacity = largeFridgeSize / 3;
                            int relSlot = i % shelfCapacity;
                            float itemX = Math.min(8f / 9f, (float) (relSlot % 9) / 9f);
                            float itemY;
                            if (i >= shelfCapacity * 2) {
                                itemY = -0.75f;
                            } else if (i >= shelfCapacity) {
                                itemY = 0.125f;
                            } else {
                                itemY = -1.625f;
                            }
                            float itemZ = (relSlot < 9) ? 0f : -0.5f;
                            if (relSlot % 2 == 0) {
                                itemZ -= 0.1f;
                            }
                            tileEntityFridge.getRenderItem().setEntityItemStack(itemStack);
                            RenderManager.instance.renderEntityWithPosYaw(tileEntityFridge.getRenderItem(), 0.45f - itemX, itemY, 0.5f + itemZ, 0f, 5f);
                        }
                    }
                }
            }
        } else {
            modelSmall.setFlipped(isDoorFlipped);
            if(isDoorFlipped) {
                modelSmall.DoorFlipped.rotateAngleY = -(float) ((Math.PI / 2f) * doorAngle);
                modelSmall.DoorHandleFlipped.rotateAngleY = -(float) ((Math.PI / 2f) * doorAngle);
            } else {
                modelSmall.Door.rotateAngleY = (float) ((Math.PI / 2f) * doorAngle);
                modelSmall.DoorHandle.rotateAngleY = (float) ((Math.PI / 2f) * doorAngle);
            }
            bindTexture(textureSmall);
            modelSmall.renderUncolored();
            GL11.glColor4f(fridgeColorTable[dye][0], fridgeColorTable[dye][1], fridgeColorTable[dye][2], 1f);
            modelSmall.renderColored();
            if(doorAngle > 0f) {
                GL11.glColor4f(1f, 1f, 1f, 1f);
                modelSmall.renderInterior();
                GL11.glRotatef(180f, 0f, 0f, -1f);
                GL11.glScalef(0.5f, 0.5f, 0.5f);
                if(!CookingConfig.disableItemRender && Minecraft.getMinecraft().gameSettings.fancyGraphics) {
                    for (int i = 0; i < tileEntityFridge.getSizeInventory(); i++) {
                        ItemStack itemStack = tileEntityFridge.getStackInSlot(i);
                        if (itemStack != null) {
                            int relSlot = i;
                            if (i > tileEntityFridge.getSizeInventory() / 2) {
                                relSlot -= tileEntityFridge.getSizeInventory() / 2;
                            }
                            float itemX = (relSlot > 8) ? Math.min(4f / 5f, (relSlot - 9) / 5f) : Math.min(8f / 9f, (float) relSlot / 9f);
                            float itemY = (i > tileEntityFridge.getSizeInventory() / 2) ? -0.7f : 0.01f;
                            float itemZ = (relSlot > 8) ? -0.8f : -0.1f;
                            if (relSlot % 2 == 0) {
                                itemZ -= 0.1f;
                            }
                            tileEntityFridge.getRenderItem().setEntityItemStack(itemStack);
                            RenderManager.instance.renderEntityWithPosYaw(tileEntityFridge.getRenderItem(), 0.45f - itemX, -2f + itemY, 0.5f + itemZ, 0f, 0f);
                        }
                    }
                }
            }
        }
        if(!oldRescaleNormal) {
            GL11.glDisable(GL12.GL_RESCALE_NORMAL);
        }
        GL11.glPopMatrix();
        GL11.glColor4f(1f, 1f, 1f, 1f);
    }

}


text:
/*! toolbar.js 2013-04-05 */
"function" != typeof Object.create && (Object.create = function (t) {
    function o() {
    }

    return o.prototype = t, new o
}), function (t, o) {
    var e = {init: function (o, e) {
        var i = this;
        i.elem = e, i.$elem = t(e), i.options = t.extend({}, t.fn.toolbar.options, o), i.toolbar = t('
').addClass("tool-" + i.options.position).addClass("tool-rounded").append('
').append('
').appendTo("body").css("opacity", 0).hide(), i.toolbar_arrow = i.toolbar.find(".arrow"), i.initializeToolbar()
    }, initializeToolbar: function () {
        var t = this;
        t.populateContent(), t.setTrigger(), t.toolbarWidth = t.toolbar.width()
    }, setTrigger: function () {
        var e = this;
        e.$elem.on("click", function (t) {
            t.preventDefault(), e.$elem.hasClass("pressed") ? e.hide() : e.show()
        }), e.options.hideOnClick && t("html").on("click.toolbar", function (t) {
            t.target != e.elem && 0 === e.$elem.has(t.target).length && 0 === e.toolbar.has(t.target).length && e.toolbar.is(":visible") && e.hide()
        }), t(o).resize(function (t) {
            t.stopPropagation(), e.toolbar.is(":visible") && (e.toolbarCss = e.getCoordinates(e.options.position, 20), e.collisionDetection(), e.toolbar.css(e.toolbarCss), e.toolbar_arrow.css(e.arrowCss))
        })
    }, populateContent: function () {
        var o = this, e = o.toolbar.find(".tool-items"), i = t(o.options.content).clone(!0).find("a").addClass("tool-item gradient");
        e.html(i), e.find(".tool-item").on("click", function (t) {
            t.preventDefault(), o.$elem.trigger("toolbarItemClick", this)
        })
    }, calculatePosition: function () {
        var t = this;
        t.arrowCss = {}, t.toolbarCss = t.getCoordinates(t.options.position, 0), t.toolbarCss.position = "absolute", t.toolbarCss.zIndex = t.options.zIndex, t.collisionDetection(), t.toolbar.css(t.toolbarCss), t.toolbar_arrow.css(t.arrowCss)
    }, getCoordinates: function (t, o) {
        var e = this;
        switch (e.coordinates = e.$elem.offset(), e.options.adjustment && e.options.adjustment[e.options.position] && (o = e.options.adjustment[e.options.position]), e.options.position) {
            case"top":
                return{left: e.coordinates.left - e.toolbar.width() / 2 + e.$elem.outerWidth() / 2, top: e.coordinates.top - e.$elem.height() - o, right: "auto"};
            case"left":
                return{left: e.coordinates.left - e.toolbar.width() / 2 - e.$elem.width() / 2 - o, top: e.coordinates.top - e.toolbar.height() / 2 + e.$elem.outerHeight() / 2, right: "auto"};
            case"right":
                return{left: e.coordinates.left + e.toolbar.width() / 2 + e.$elem.width() / 3 + o, top: e.coordinates.top - e.toolbar.height() / 2 + e.$elem.outerHeight() / 2, right: "auto"};
            case"bottom":
                return{left: e.coordinates.left - e.toolbar.width() / 2 + e.$elem.outerWidth() / 2, top: e.coordinates.top + e.$elem.height() + o, right: "auto"}
        }
    }, collisionDetection: function () {
        var e = this, i = 20;
        ("top" == e.options.position || "bottom" == e.options.position) && (e.arrowCss = {left: "50%", right: "50%"}, i > e.toolbarCss.left ? (e.toolbarCss.left = i, e.arrowCss.left = e.$elem.offset().left + e.$elem.width() / 2 - i) : i > t(o).width() - (e.toolbarCss.left + e.toolbarWidth) && (e.toolbarCss.right = i, e.toolbarCss.left = "auto", e.arrowCss.left = "auto", e.arrowCss.right = t(o).width() - e.$elem.offset().left - e.$elem.width() / 2 - i - 5))
    }, show: function () {
        var t = this, o = {opacity: 1};
        switch (t.$elem.addClass("pressed"), t.calculatePosition(), t.options.position) {
            case"top":
                o.top = "-=20";
                break;
            case"left":
                o.left = "-=20";
                break;
            case"right":
                o.left = "+=20";
                break;
            case"bottom":
                o.top = "+=20"
        }
        t.toolbar.show().animate(o, 200), t.$elem.trigger("toolbarShown")
    }, hide: function () {
        var t = this, o = {opacity: 0};
        switch (t.$elem.removeClass("pressed"), t.options.position) {
            case"top":
                o.top = "+=20";
                break;
            case"left":
                o.left = "+=20";
                break;
            case"right":
                o.left = "-=20";
                break;
            case"bottom":
                o.top = "-=20"
        }
        t.toolbar.animate(o, 200, function () {
            t.toolbar.hide()
        }), t.$elem.trigger("toolbarHidden")
    }, getToolbarElement: function () {
        return this.toolbar.find(".tool-items")
    }};
    t.fn.toolbar = function (o) {
        if (t.isPlainObject(o))return this.each(function () {
            var i = Object.create(e);
            i.init(o, this), t(this).data("toolbarObj", i)
        });
        if ("string" == typeof o && 0 !== o.indexOf("_")) {
            var i = t(this).data("toolbarObj"), s = i[o];
            return s.apply(i, t.makeArray(arguments).slice(1))
        }
    }, t.fn.toolbar.options = {content: "#myContent", position: "top", hideOnClick: !1, zIndex: 120}
}(jQuery, window, document);


text:
<?php

namespace MtHaml\NodeVisitor;

use MtHaml\Node\Run;

class Midblock extends NodeVisitorAbstract
{
    protected $midblockRegex;

    public function __construct($midblockRegex)
    {
        $this->midblockRegex = $midblockRegex;
        $this->skip = new \SplObjectStorage;
    }

    public function enterRun(Run $node)
    {
        do {
            if (null === $prev = $node->getPreviousSibling()) {
                break;
            }
            if (!$prev instanceof Run) {
                break;
            }
            if (!preg_match($this->midblockRegex, $node->getContent())) {
                break;
            }

            $node->getParent()->removeChild($node);
            while (null !== $prev->getMidblock()) {
                $prev = $prev->getMidblock();
            }
            $prev->setMidblock($node);
        } while (false);
    }
}


text:
ROOT = ../../../../..

DIR = Providers/ManagedSystem/UNIXProviders/SchedulerUsed

include $(ROOT)/mak/config.mak

LIBRARY = UNIX_SchedulerUsedProvider

EXTRA_INCLUDES += -I/usr/local/include -I./..

SOURCES = \
	../CIMHelper.cpp \
	UNIX_SchedulerUsedMain.cpp \
	UNIX_SchedulerUsed.cpp \
	UNIX_SchedulerUsedProvider.cpp

ifeq ($(OS), aix)
	SOURCES += UNIX_SchedulerUsed_AIX.cpp
endif
ifeq ($(OS), darwin)
	SOURCES += UNIX_SchedulerUsed_DARWIN.cpp
endif
ifeq ($(OS), freebsd)
	SOURCES += UNIX_SchedulerUsed_FREEBSD.cpp
endif
ifeq ($(OS), hpux)
	SOURCES += UNIX_SchedulerUsed_HPUX.cpp
endif
ifeq ($(OS), linux)
	SOURCES += UNIX_SchedulerUsed_LINUX.cpp
endif
ifeq ($(OS), solaris)
	SOURCES += UNIX_SchedulerUsed_SOLARIS.cpp
endif
ifeq ($(OS), tru64)
	SOURCES += UNIX_SchedulerUsed_TRU64.cpp
endif
ifeq ($(OS), vms)
	SOURCES += UNIX_SchedulerUsed_VMS.cpp
endif
ifeq ($(OS), win32)
	SOURCES += UNIX_SchedulerUsed_WIN32.cpp
endif
ifeq ($(OS), zos)
	SOURCES += UNIX_SchedulerUsed_ZOS.cpp
endif
ifeq (, $(filter aix,darwin,freebsd,hpux,linux,solaris,tru64,vms,win32,zos $(OS)))

else
	SOURCES += UNIX_SchedulerUsed_STUB.cpp
endif

LIBRARIES = \
	pegprovider \
	pegclient \
	pegcommon \
	pegquerycommon \
	pegqueryexpression \
	pegcql \
	pegwql

EXTRA_LIBRARIES = \
	-pthread \
	-lutil \
	-lgeom \
	-lkvm \
	-lcam

include $(ROOT)/mak/dynamic-library.mak


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.moebuff.discord.dao.User_osu_id_DAO">
    <select id="getosuid" parameterType="java.lang.String" resultType="java.lang.String">
        select osuid from user_osu_id where userid = #{userid}
    </select>
    <insert id="setosuid" parameterType="java.util.Map">
        insert into user_osu_id values(#{userid},#{osuid})
    </insert>
</mapper>


text:
#include <af/array.h>
#include <Array.hpp>

namespace cpu
{
    template<typename T> Array<T> setUnique(const Array<T> &in,
                                            const bool is_sorted);

    template<typename T> Array<T> setUnion(const Array<T> &first,
                                           const Array<T> &second,
                                           const bool is_unique);

    template<typename T> Array<T> setIntersect(const Array<T> &first,
                                               const Array<T> &second,
                                               const bool is_unique);
}


text:
var Reference = require("./Reference");
var Period = require("./Period");

function Encounter(resourceType, id, status, eClass, patientId, periodStart, periodEnd, locationId, serviceProvider) {
	this.resourceType = resourceType;
	this.id = id;
	this.status = status;
	this.class = eClass;
	this.patientId = patientId;
	this.periodStart = periodStart;
	this.periodEnd = periodEnd;
	this.locationId = locationId;
	this.serviceProvider = serviceProvider;
};

Encounter.prototype.prettyPrint = function() {
	return "Resource Type: " + this.resourceType
	+ " ID: " + this.id
	+ " Status: "+this.status
	+ " Class: "+this.class
	+ " Patient ID: "+this.patientId
	+ " Start Time: "+this.periodStart
	+ " End Time: "+this.periodEnd
	+ " Location ID: "+this.locationId
	+ " Service Provider: "+this.serviceProvider;
};

Encounter.prototype.jsonPrint = function() {
	var slash = "/";
	return {	resourceType: this.resourceType,
		id: this.id,
		status: this.status,
		class: this.class,
		patient: new Reference("Patient" + slash + this.patientId),
		period: new Period(this.periodStart, this.periodEnd),
		location: [{ location: new Reference("Location" + slash + this.locationId) }],
		serviceProvider: new Reference("Organization" + slash + this.serviceProvider)
	};
};

Encounter.prototype.getEncounterByText = function getEncounterByText(text) {
	var encounter = JSON.parse(text);
	var resourceType = encounter.resourceType;
	var id = encounter.id;
	var status = encounter.status;
	var eClass = encounter.class;
	var patientId = encounter.patient.reference.replace("Patient/","");
	var periodStart = encounter.period.start;
	var periodEnd = encounter.period.end;
	var locationId = encounter.location[0].location.reference.replace("Location/","");
	var serviceProvider = encounter.serviceProvider.reference.replace("Organization/","");
	return new Encounter(resourceType, id, status, eClass, patientId, periodStart, periodEnd, locationId, serviceProvider);
};

module.exports = Encounter;


text:
package org.jtwig.resource.loader;

import com.google.common.base.Optional;
import org.jtwig.resource.exceptions.ResourceNotFoundException;
import org.junit.Test;

import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ClasspathResourceLoaderTest {
    private final ClassLoader classLoader = mock(ClassLoader.class);
    private ClasspathResourceLoader underTest = new ClasspathResourceLoader(classLoader);

    @Test
    public void existsWithoutRoot() throws Exception {
        URL value = new URL("file:/");

        when(classLoader.getResource("path")).thenReturn(value);

        boolean result = underTest.exists("path");

        assertThat(result, is(true));
    }

    @Test
    public void existsPathWithRoot() throws Exception {
        URL value = new URL("file:/");

        when(classLoader.getResource("path")).thenReturn(value);

        boolean result = underTest.exists("/path");

        assertThat(result, is(true));
    }

    @Test
    public void existsNotFound() throws Exception {
        when(classLoader.getResource("path")).thenReturn(null);

        boolean result = underTest.exists("/path");

        assertThat(result, is(false));
    }

    @Test
    public void loadWithoutRoot() throws Exception {
        InputStream inputStream = mock(InputStream.class);

        when(classLoader.getResourceAsStream("path")).thenReturn(inputStream);

        InputStream result = underTest.load("path");

        assertThat(result, is(inputStream));
    }

    @Test
    public void loadPathWithRoot() throws Exception {
        InputStream inputStream = mock(InputStream.class);

        when(classLoader.getResourceAsStream("path")).thenReturn(inputStream);

        InputStream result = underTest.load("/path");

        assertThat(result, is(inputStream));
    }

    @Test(expected = ResourceNotFoundException.class)
    public void loadPathNotFound() throws Exception {
        when(classLoader.getResourceAsStream("path")).thenReturn(null);

        underTest.load("/path");
    }

    @Test
    public void charset() throws Exception {
        Optional<Charset> result = underTest.getCharset("path");

        assertThat(result.isPresent(), is(false));
    }

    @Test
    public void toUrl() throws Exception {
        when(classLoader.getResource("path")).thenReturn(null);

        Optional<URL> result = underTest.toUrl("path");

        assertThat(result.isPresent(), is(false));
    }

    @Test
    public void toUrlWithRootPath() throws Exception {
        when(classLoader.getResource("path")).thenReturn(null);

        Optional<URL> result = underTest.toUrl("/path");

        assertThat(result.isPresent(), is(false));
    }

    @Test
    public void toUrlFound() throws Exception {
        URL url = new URL("file:/");
        when(classLoader.getResource("path")).thenReturn(url);

        Optional<URL> result = underTest.toUrl("/path");

        assertThat(result.get(), is(url));
    }
}


text:
package org.lagonette.app.app.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.support.annotation.NonNull;

import org.lagonette.app.app.widget.error.Error;
import org.lagonette.app.background.worker.WorkerState;
import org.lagonette.app.locator.Repo;
import org.lagonette.app.tools.arch.LiveEvent;
import org.lagonette.app.tools.arch.MutableLiveEvent;

import static org.lagonette.app.background.worker.WorkerState.ERROR;

public class DataViewModel
		extends AndroidViewModel {

	@NonNull
	private final MutableLiveData<String> mSearch;

	@NonNull
	private final LiveData<Integer> mWorkStatus;

	@NonNull
	private final LiveEvent<Error> mWorkError;

	public DataViewModel(Application application) {
		super(application);

		Repo.get().resetMetadata();

		LiveData<WorkerState> workerState = Repo.get().updateDatas();

		mWorkStatus = Transformations.map(
				workerState,
				state -> state.status
		);

		MutableLiveEvent<Error> workError = new MutableLiveEvent<>();
		workerState.observeForever(state -> {
			if (state != null && state.status == ERROR) {
				workError.sendEvent(state.error);
			}
		});
		mWorkError = workError;

		mSearch = new MutableLiveData<>();
		mSearch.setValue("");
	}

	@NonNull
	public MutableLiveData<String> getSearch() {
		return mSearch;
	}

	@NonNull
	public LiveData<Integer> getWorkStatus() {
		return mWorkStatus;
	}

	@NonNull
	public LiveData<Error> getWorkError() {
		return mWorkError;
	}

}


text:
@interface CustomObject : NSObject
{
    NSMutableDictionary *imageDictionary;
}
+ (id)sharedCustomObject;
- (void)addImage :(UIImage *)image key:(NSURL *)url;
- (BOOL)isExistImage :(NSURL *)url;
- (UIImage *)getImage :(NSURL *)url;

@end


text:
from apps.gcd.models.countstats import CountStats
from apps.gcd.models import Language, Country

for i in Language.objects.all():
    CountStats.objects.init_stats(language=i)

for i in Country.objects.all():
    CountStats.objects.init_stats(country=i)


text:
package com.cloud.network.guru;

import com.cloud.dc.DataCenter;
import com.cloud.dc.Vlan;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.network.*;
import com.cloud.network.Network;
import com.cloud.network.addr.PublicIp;
import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.user.AccountVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.vm.*;
import org.apache.log4j.Logger;
import java.net.URI;

import javax.ejb.Local;
import javax.inject.Inject;

@Local(value = NetworkGuru.class)
public class MidoNetPublicNetworkGuru extends PublicNetworkGuru {
    private static final Logger s_logger = Logger.getLogger(MidoNetPublicNetworkGuru.class);

    // Inject any stuff we need to use (DAOs etc)
    @Inject
    NetworkModel _networkModel;
    @Inject
    AccountDao _accountDao;

    // Don't need to change traffic type stuff, public is fine

    // Only change is to make broadcast domain type Mido
    @Override
    public Network design(NetworkOffering offering, DeploymentPlan plan, Network network, Account owner) {
        s_logger.debug("design called with network: " + network.toString());
        if (!canHandle(offering)) {
            return null;
        }

        if (offering.getTrafficType() == Networks.TrafficType.Public) {
            NetworkVO ntwk = new NetworkVO(offering.getTrafficType(), Networks.Mode.Static, Networks.BroadcastDomainType.Mido,
                    offering.getId(), Network.State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId());
            return ntwk;
        } else {
            return null;
        }
    }

    protected MidoNetPublicNetworkGuru() {
        super();
    }

    protected void getIp(NicProfile nic, DataCenter dc, VirtualMachineProfile<? extends VirtualMachine> vm, Network network) throws InsufficientVirtualNetworkCapcityException,
            InsufficientAddressCapacityException, ConcurrentOperationException {
        if (nic.getIp4Address() == null) {
            PublicIp ip = _networkMgr.assignPublicIpAddress(dc.getId(), null, vm.getOwner(), Vlan.VlanType.VirtualNetwork, null, null, false);
            nic.setIp4Address(ip.getAddress().toString());

            nic.setGateway(ip.getGateway());

            // Set netmask to /24 for now
            // TDO make it /32 and go via router for anything else on the subnet
            nic.setNetmask("255.255.255.0");

            // Make it the default nic so that a default route is set up.
            nic.setDefaultNic(true);

            //nic.setIsolationUri(Networks.IsolationType..Mido.toUri(ip.getVlanTag()));
            nic.setBroadcastUri(network.getBroadcastUri());
            //nic.setBroadcastType(Networks.BroadcastDomainType.Vlan);
            nic.setFormat(Networks.AddressFormat.Ip4);
            nic.setReservationId(String.valueOf(ip.getVlanTag()));
            nic.setMacAddress(ip.getMacAddress());
        }

        nic.setDns1(dc.getDns1());
        nic.setDns2(dc.getDns2());
    }

    @Override
    public void updateNicProfile(NicProfile profile, Network network) {
        s_logger.debug("updateNicProfile called with network: " + network.toString() + " profile: " + profile.toString());

        DataCenter dc = _dcDao.findById(network.getDataCenterId());
        if (profile != null) {
            profile.setDns1(dc.getDns1());
            profile.setDns2(dc.getDns2());
        }
    }

    @Override
    public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
            throws InsufficientVirtualNetworkCapcityException,
            InsufficientAddressCapacityException, ConcurrentOperationException {

        s_logger.debug("allocate called with network: " + network.toString() + " nic: " + nic.toString() + " vm: " + vm.toString());
        DataCenter dc = _dcDao.findById(network.getDataCenterId());

        if (nic != null && nic.getRequestedIpv4() != null) {
            throw new CloudRuntimeException("Does not support custom ip allocation at this time: " + nic);
        }

        if (nic == null) {
            nic = new NicProfile(Nic.ReservationStrategy.Create, null, null, null, null);
        }

        getIp(nic, dc, vm, network);

        if (nic.getIp4Address() == null) {
            nic.setStrategy(Nic.ReservationStrategy.Start);
        } else if (vm.getVirtualMachine().getType() == VirtualMachine.Type.DomainRouter){
            nic.setStrategy(Nic.ReservationStrategy.Managed);
        } else {
            nic.setStrategy(Nic.ReservationStrategy.Create);
        }

        nic.setBroadcastUri(generateBroadcastUri(network));

        return nic;
    }

    @Override
    public void reserve(NicProfile nic, Network network, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context)
            throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException {
        s_logger.debug("reserve called with network: " + network.toString() + " nic: " + nic.toString() + " vm: " + vm.toString());
        if (nic.getIp4Address() == null) {
            getIp(nic, dest.getDataCenter(), vm, network);
        }
    }

    @Override
    public boolean release(NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String reservationId) {
        s_logger.debug("release called with nic: " + nic.toString() + " vm: " + vm.toString());
        return true;
    }

    @Override
    public Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context)
            throws InsufficientVirtualNetworkCapcityException {
        s_logger.debug("implement called with network: " + network.toString());
        long dcId = destination.getDataCenter().getId();

        //get physical network id
        long physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType());

        NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), Network.State.Allocated,
                network.getDataCenterId(), physicalNetworkId);

        if (network.getGateway() != null) {
            implemented.setGateway(network.getGateway());
        }

        if (network.getCidr() != null) {
            implemented.setCidr(network.getCidr());
        }

        implemented.setBroadcastUri(generateBroadcastUri(network));

        return implemented;

    }

    @Override @DB
    public void deallocate(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) {
        s_logger.debug("deallocate called with network: " + network.toString() + " nic: " + nic.toString() + " vm: " + vm.toString());
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("public network deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIp4Address());
        }

        IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
        if (ip != null && nic.getReservationStrategy() != Nic.ReservationStrategy.Managed) {

            Transaction txn = Transaction.currentTxn();
            txn.start();

            _networkMgr.markIpAsUnavailable(ip.getId());
            _ipAddressDao.unassignIpAddress(ip.getId());

            txn.commit();
        }
        nic.deallocate();

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Deallocated nic: " + nic);
        }
    }

    @Override
    public void shutdown(NetworkProfile network, NetworkOffering offering) {
        s_logger.debug("shutdown called with network: " + network.toString());
    }

    @Override
    public boolean trash(Network network, NetworkOffering offering, Account owner) {
        s_logger.debug("trash called with network: " + network.toString());
        return true;
    }

    @Override
    public void updateNetworkProfile(NetworkProfile networkProfile) {
        DataCenter dc = _dcDao.findById(networkProfile.getDataCenterId());
        networkProfile.setDns1(dc.getDns1());
        networkProfile.setDns2(dc.getDns2());
    }

    private URI generateBroadcastUri(Network network){
        AccountVO acc = _accountDao.findById(network.getAccountId());
        String accountUUIDStr = acc.getUuid();
        String networkUUIDStr = String.valueOf(network.getId());
        return Networks.BroadcastDomainType.Mido.toUri(accountUUIDStr +
                                                       "." +
                                                       networkUUIDStr +
                                                       ":" +
                                                       networkUUIDStr);
    }

}


text:
package com.jwetherell.augmented_reality.activity;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Source extends ListActivity {
	private ArrayAdapter<ListCellData> adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		adapter = new ArrayAdapter<ListCellData>(this,
				android.R.layout.simple_list_item_1);
		setListAdapter(adapter);
		adapter.add(new ListCellData(this, "ÐÅÏ¢Óë¿ØÖÆѧԺ", new Intent(this,
				Xinkongyuan.class)));

		adapter.add(new ListCellData(this, "µç×ÓÓëÐÅÏ¢¹¤³ÌѧԺ", new Intent(this,
				Dianxinyuan.class)));

		adapter.add(new ListCellData(this, "´óÆø¿ÆѧѧԺ", new Intent(this,
				Daqikexue.class)));

		adapter.add(new ListCellData(this, "´óÆøÎïÀíѧԺ", new Intent(this,
				Daqiwuli.class)));

		adapter.add(new ListCellData(this, "Ó¦ÓÃÆøÏóѧԺ", new Intent(this,
				Yingyongqixiang.class)));

		adapter.add(new ListCellData(this, "Ë®ÎÄÆøÏóѧԺ", new Intent(this,
				Shuiwenqixiang.class)));

		adapter.add(new ListCellData(this, "µØÀíÓëÒ£¸ÐѧԺ", new Intent(this,
				Diliyuyaogan.class)));

		adapter.add(new ListCellData(this, "´«Ã½ÓëÒÕÊõѧԺ", new Intent(this,
				Chuanmeiyuyishu.class)));

		adapter.add(new ListCellData(this, "»·¾³¿ÆѧÓ빤³ÌѧԺ", new Intent(this,
				Huanke.class)));

		adapter.add(new ListCellData(this, "¼ÆËã»úÓëÈí¼þѧԺ", new Intent(this,
				Jiruan.class)));

		adapter.add(new ListCellData(this, "ÊýѧÓëͳ¼ÆѧԺ", new Intent(this,
				Shutong.class)));

		adapter.add(new ListCellData(this, "ÎïÀíÓë¹âµç¹¤³ÌѧԺ", new Intent(this,
				Wudian.class)));

		adapter.add(new ListCellData(this, "¹«¹²¹ÜÀíѧԺ", new Intent(this,
				Gongguan.class)));

		adapter.add(new ListCellData(this, "¾¼Ã¹ÜÀíѧԺ", new Intent(this,
				Jingguan.class)));

		adapter.add(new ListCellData(this, "ÓïÑÔÎÄ»¯Ñ§Ôº", new Intent(this,
				Yuyuan.class)));

		adapter.add(new ListCellData(this, "º£Ñó¿ÆѧѧԺ", new Intent(this,
				Haiyang.class)));

		adapter.add(new ListCellData(this, "À׶¡Ñ§Ôº", new Intent(this,
				Leiding.class)));

		adapter.add(new ListCellData(this, "Âí¿Ë˼Ö÷ÒåѧԺ", new Intent(this,
				Makesi.class)));
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		ListCellData data = adapter.getItem(position);
		data.startActivity();
		super.onListItemClick(l, v, position, id);
	}

}


text:
const std::string PlayState::s_playID = "PLAY";

void PlayState::update()
{
    if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE))
    {
        Game::Instance()->getStateMachine()->pushState(new PauseState());
    }

    for (int i = 0; i < m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->update();
    }

    pLevel->update();
    BulletHandler::Instance()->updateBullets();
}

void PlayState::render()
{
    pLevel->render();
    BulletHandler::Instance()->drawBullets();

    for (int i = 0; i < m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->draw();
    }
}

bool PlayState::onEnter()
{
    LevelParser levelParser;
    pLevel = levelParser.parseLevel("assets/space_tilemap.tmx");

    // Parse the states file
    StateParser stateParser;
    stateParser.parseState("assets/states-config.xml", s_playID, &m_gameObjects, &m_textureIDList);

    std::cout << "Entering PlayState" << std::endl;
    return true;
}

bool PlayState::onExit()
{
    for (int i = 0; i < m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->clean();
    }
    m_gameObjects.clear();

    // Clear the texture manager
    for (std::string textureID : m_textureIDList)
    {
        TextureManager::Instance()->clearFromTextureMap(textureID);
    }

    std::cout << "Exiting PlayState" << std::endl;
    return true;
}