text:
package org.radargun.reporting.commons;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import org.radargun.config.Cluster;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.reporting.Report;
import org.radargun.stats.OperationStats;
import org.radargun.stats.Statistics;

/**
 * Perform aggregations and holds them
 *
 * @author Vitalii Chepeliuk <vchepeli@redhat.com>
 * @since 2.0
 */
public class TestAggregations {
   private Log log = LogFactory.getLog(getClass());

   public final String testName;
   public final String iterationsName;

   private Map<Report, List<Aggregation>> byReports = new TreeMap<>();
   private Map<Integer, Map<Report, List<Aggregation>>> byClusterSize = new TreeMap<>();
   private Map<String, Map<Report, List<Report.TestResult>>> results = new TreeMap<>();

   private int maxIterations = 0;
   private Set<String> operations = new TreeSet<>();
   private Set<Cluster> clusters = new TreeSet<>();

   public TestAggregations(String testName, List<Report.Test> tests){
      this.testName = testName;
      Set<String> iterationsNames = new TreeSet<>();

      for (Report.Test test : tests) {
         if (test.iterationsName != null) {
            iterationsNames.add(test.iterationsName);
         }
         List<Aggregation> iterations = new ArrayList<Aggregation>();
         for (Report.TestIteration it : test.getIterations()) {
            addIteration(test, iterations, it);
         }
         byReports.put(test.getReport(), iterations);
         int clusterSize = test.getReport().getCluster().getSize();
         Map<Report, List<Aggregation>> reportAggregationMap = byClusterSize.get(clusterSize);
         if (reportAggregationMap == null) {
            reportAggregationMap = new TreeMap<>();
         }
         reportAggregationMap.put(test.getReport(), iterations);
         byClusterSize.put(clusterSize, reportAggregationMap);
         maxIterations = Math.max(maxIterations, iterations.size());
         clusters.add(test.getReport().getCluster());
      }

      if (iterationsNames.isEmpty()) {
         iterationsName = null;
      } else {
         StringBuilder sb = new StringBuilder();
         for (String name : iterationsNames) {
            if (sb.length() != 0) sb.append(", ");
            sb.append(name);
         }
         iterationsName = sb.toString();
      }
   }

   private void addIteration(Report.Test test, List<Aggregation> iterations, Report.TestIteration it) {
      Statistics totalStats = null;
      int totalThreads = 0;
      List<Statistics> nodeStats = new ArrayList<>();
      List<Integer> nodeThreads = new ArrayList<>();
      for (Map.Entry<Integer, List<Statistics>> entry : it.getStatistics()) {
         int slaveIndex = entry.getKey();
         List<Statistics> list = entry.getValue();

         Statistics ns = null;
         for (Statistics s : list) {
            if (ns == null) {
               ns = s.copy();
            } else {
               ns.merge(s);
            }
         }

         if (ns != null) {
            while (nodeStats.size() <= slaveIndex) {
               nodeStats.add(null);
               nodeThreads.add(0);
            }
            nodeStats.set(slaveIndex, ns);
            nodeThreads.set(slaveIndex, list.size());

            if (totalStats == null) {
               totalStats = ns.copy();
            } else {
               totalStats.merge(ns);
            }
         }
         totalThreads += list.size();
      }
      if (totalStats == null) {
         log.warn("There are no stats for this iteration");
      } else {
         iterations.add(new Aggregation(nodeStats, nodeThreads, totalStats, totalThreads, it));
         for (Map.Entry<String, OperationStats> op : totalStats.getOperationsStats().entrySet()) {
            if (!op.getValue().isEmpty()) operations.add(op.getKey());
         }
      }

      if (it != null && it.getResults() != null) {
         for (Map.Entry<String, Report.TestResult> entry : it.getResults().entrySet()) {
            Map<Report, List<Report.TestResult>> resultsByType = results.get(entry.getKey());
            if (resultsByType == null) {
               resultsByType = new TreeMap<Report, List<Report.TestResult>>();
               results.put(entry.getKey(), resultsByType);
            }
            List<Report.TestResult> resultsList = resultsByType.get(test.getReport());
            if (resultsList == null) {
               resultsList = new ArrayList<Report.TestResult>();
               resultsByType.put(test.getReport(), resultsList);
            }
            resultsList.add(entry.getValue());
         }
      }
   }

   public Map<Report, List<Aggregation>> byReports() {
      return byReports;
   }

   public Map<Integer, Map<Report, List<Aggregation>>> byClusterSize() {
      return byClusterSize;
   }

   public Map<String, Map<Report, List<Report.TestResult>>> results() {
      return results;
   }

   public Set<String> getAllOperations() {
      return Collections.unmodifiableSet(operations);
   }

   public Set<Cluster> getAllClusters() {
      return Collections.unmodifiableSet(clusters);
   }

   public int getMaxIterations() {
      return maxIterations;
   }
}


text:
package com.lindaring.guess.repository;

import com.lindaring.guess.model.Word;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class WordJdbc {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Word> findRandomLimit(int enabled, int limit) {
        String sql = String.format("SELECT word_id, word, enabled FROM word WHERE enabled = %d ORDER BY RAND() LIMIT %d", enabled, limit);
        List<Word> result = jdbcTemplate.query(
                sql,
                (rs, rowNum) -> new Word(rs.getInt("word_id"), rs.getString("word"), rs.getInt("enabled"))
        );
        return result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099'
process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080'

const request = require('request-promise-native')
const firebase = require('@firebase/rules-unit-testing')
const { updateService } = require('../functions/service')
const { initialData } = require('../functions/initialData')
const accounts = require('../functions/accounts')

const projectId = 'tamuro01'
const password = 'password'
const apiKey = 'api_key'

const admin = firebase.initializeAdminApp({ projectId })

firebase.loadFirestoreRules({ projectId })
const db = admin.firestore()
const auth = admin.auth()
const logger = console
const context = { db, auth, logger }

const clearAuth = async () => {
  await request({
    method: 'DELETE',
    uri: 'http://localhost:9099/emulator/v1/projects/tamuro01/accounts',
    headers: {
      Authorization: 'Bearer owner'
    }
  })
}

// const deleteApp = () => admin.app().delete()

const setupService = async () => {
  await clearAuth()
  await firebase.clearFirestoreData({ projectId })
  await updateService(context, initialData)

  // set API Key.
  const serviceConfRef = db.collection('service').doc('conf')
  if (!(await serviceConfRef.get()).data().apiKey) {
    console.log('Set: service.conf.apiKey')
    await serviceConfRef.update({ apiKey })
  }

  // Create primary user.
  if ((await db.collection('accounts').get()).docs.length) {
    return true
  }

  const creteAccount = async name => {
    const account = await accounts.createAccount({
      name: name.charAt(0).toUpperCase() + name.slice(1)
    }, context)
    await accounts.setEmail({
      id: account.id,
      email: `${name}@example.com`
    }, context)
    await accounts.setPassword({ id: account.id, password }, context)
    return account.id
  }

  const primary = await creteAccount('primary')
  const manager = await creteAccount('manager')
  const admin = await creteAccount('admin')
  const tester = await creteAccount('tester')
  const user01 = await creteAccount('user01')
  const user02 = await creteAccount('user02')
  const user03 = await creteAccount('user03')
  const user04 = await creteAccount('user04')
  const user05 = await creteAccount('user05')
  const invalid = await creteAccount('invalid')
  const deleted = await creteAccount('deleted')

  await db.collection('groups').doc('managers').update({
    members: [primary, manager]
  })
  await db.collection('groups').doc('admins').update({
    members: [primary, admin]
  })
  await db.collection('groups').doc('testers').update({
    members: [tester]
  })
  await db.collection('accounts').doc(invalid).update({
    valid: false
  })
  await db.collection('accounts').doc(deleted).update({
    deletedAt: new Date()
  })
  const group1 = await db.collection('groups').add({
    name: 'Group 1',
    members: [user01, user02, user03],
    createdAt: new Date(),
    updatedAt: new Date()
  })
  const group2 = await db.collection('groups').add({
    name: 'Group 2',
    members: [user01, user04, invalid, deleted],
    createdAt: new Date(),
    updatedAt: new Date()
  })
  const group3 = await db.collection('groups').add({
    name: 'Group 3',
    members: [],
    createdAt: new Date(),
    updatedAt: new Date()
  })
  await db.collection('groups').add({
    name: 'Group deleted',
    members: [user05],
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: new Date()
  })
  await db.collection('categories').add({
    seq: 1,
    name: 'Category 1',
    groups: [group1.id, group3.id],
    createdAt: new Date(),
    updatedAt: new Date()
  })
  await db.collection('categories').add({
    seq: 2,
    name: 'Category 2',
    groups: [group2.id],
    createdAt: new Date(),
    updatedAt: new Date()
  })
  await db.collection('categories').add({
    seq: 3,
    name: 'Privileged',
    groups: ['managers', 'admins'],
    createdAt: new Date(),
    updatedAt: new Date()
  })

  return null
}

setupService()
  .then(() => {
    console.log('complete')
    // return deleteApp()
  })
  .catch(e => {
    console.error(e)
    // return deleteApp()
  })


text:
slush-simbo
===========

[![npm Package Version](https://img.shields.io/npm/v/slush-simbo.svg?style=flat-square)](https://www.npmjs.com/package/slush-simbo)
[![MIT License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](http://simbo.mit-license.org/)
[![Dependencies Status](https://img.shields.io/david/simbo/slush-simbo.svg?style=flat-square)](https://david-dm.org/simbo/slush-simbo)
[![devDependencies Status](https://img.shields.io/david/dev/simbo/slush-simbo.svg?style=flat-square)](https://david-dm.org/simbo/slush-simbo#info=devDependencies)
[![Travis Build Status](https://img.shields.io/travis/simbo/slush-simbo/master.svg?style=flat-square)](https://travis-ci.org/simbo/slush-simbo)

  > A Slush generator for web projects.

# WORK IN PROGRESS

### Usage

``` sh
# install slush and the generator
npm install -g slush slush-simbo

# create a project directory and enter
mkdir my-project
cd my-project

# start the generator
slush simbo
```


text:
@class AMUserPhone;
@protocol JavaUtilCollection;

@interface AMArrayListUserPhone : JavaUtilArrayList

#pragma mark Public

- (instancetype)init;

- (instancetype)initWithJavaUtilCollection:(id<JavaUtilCollection>)c;

- (instancetype)initWithInt:(jint)initialCapacity;

- (AMUserPhone *)getWithInt:(jint)index;

- (jboolean)isEmpty;

- (jint)size;

#pragma mark Package-Private

@end

J2OBJC_EMPTY_STATIC_INIT(AMArrayListUserPhone)

FOUNDATION_EXPORT void AMArrayListUserPhone_initWithInt_(AMArrayListUserPhone *self, jint initialCapacity);

FOUNDATION_EXPORT AMArrayListUserPhone *new_AMArrayListUserPhone_initWithInt_(jint initialCapacity) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void AMArrayListUserPhone_init(AMArrayListUserPhone *self);

FOUNDATION_EXPORT AMArrayListUserPhone *new_AMArrayListUserPhone_init() NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void AMArrayListUserPhone_initWithJavaUtilCollection_(AMArrayListUserPhone *self, id<JavaUtilCollection> c);

FOUNDATION_EXPORT AMArrayListUserPhone *new_AMArrayListUserPhone_initWithJavaUtilCollection_(id<JavaUtilCollection> c) NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(AMArrayListUserPhone)

typedef AMArrayListUserPhone ImActorModelMvvmGenericsArrayListUserPhone;

#endif // _AMArrayListUserPhone_H_


text:
import os, sys, shutil, subprocess, time

# Here is where you can set the name for the release zip file and for the install dir inside it.
# version.txt is the sole source of truth about what version this is. the version string shouldnt be hardcoded anywhere
with open('version.txt', 'r') as f:
    version = f.read()
installName = 'Rebirth Item Tracker'

# target is where we assemble our final install.
if os.path.isdir('target/'):
    shutil.rmtree('target/')
    #windows takes time to delete things, wait until it's done
    while os.path.isdir('target/'):
        time.sleep(0.3)
installDir = 'target/' + installName + '/'
os.mkdir('target/')

localpy = sys.executable

os.chdir("src_bootstrapper")
subprocess.call(localpy + " cxfreeze.py bootstrapper.py --base-name=Win32GUI --target-dir dist --icon ../mind.ico", shell=False, stdout=sys.stdout, stderr=sys.stderr)
os.chdir("..")

shutil.move('src_bootstrapper/dist/bootstrapper.exe', 'src_bootstrapper/dist/Rebirth Item Tracker.exe') # Move the dist files to our target directory
shutil.move('src_bootstrapper/dist/', installDir)

# Run the tracker build script. The results are placed in ./dist/
os.chdir("src_updater")
subprocess.call(localpy + " cxfreeze.py updater.py --base-name=Win32GUI --target-dir dist --icon ../mind.ico", shell=False, stdout=sys.stdout, stderr=sys.stderr)
os.chdir("..")
shutil.move('src_updater/dist/', installDir + "updater-lib/")

os.chdir("src")
subprocess.call(localpy + " cxfreeze.py item_tracker.py --base-name=Win32GUI --target-dir dist --icon ../mind.ico", shell=False, stdout=sys.stdout, stderr=sys.stderr)
os.chdir("..")
shutil.copy('src/options.ico', 'src/dist/options.ico')
shutil.move('src/dist/', installDir + 'tracker-lib/')

# Then copy over all the data files
shutil.copytree('collectibles/', installDir + 'collectibles/')
shutil.copytree('overlay text reference/', installDir + 'overlay text/')
# do NOT include "options.json" in a release. when it's missing, the tracker itself will generate it based on options_default
# if options.json goes into a release, it will completely overwrite users' options when they autoupdate
shutil.copy('options_default.json', installDir + "tracker-lib/")
shutil.copy('items_abplus.json', installDir)
shutil.copy('items.json', installDir)
shutil.copy('items_custom.json', installDir)
shutil.copy('LICENSE.txt', installDir)
shutil.copy('README.md', installDir + 'README.txt')
shutil.copy('version.txt', installDir)
shutil.make_archive("target/" + installName + "-" + version, "zip", 'target', installName + "/")

exit()


text: Out of this world unit testing.


text:
<!DOCTYPE html>

    <title></title>

All in the browser console - F12


text:
package org.overlord.rtgov.ui.client.model;

import java.util.HashSet;
import java.util.Set;

import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.databinding.client.api.Bindable;

/**
 * A simple data bean for returning summary information for single service.
 *
 * @author eric.wittmann@redhat.com
 */
@Portable
@Bindable
public class ServiceSummaryBean {

    private String serviceId;
    private String name;
    private String application;
    private String iface;
    private Set<BindingBean> bindings = new HashSet<BindingBean>();

    /**
     * Constructor.
     */
    public ServiceSummaryBean() {
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return the category
     */
    public String getApplication() {
        return application;
    }

    /**
     * @return the iface
     */
    public String getIface() {
        return iface;
    }

    /**
     * @return the bindings
     */
    public Set<BindingBean> getBindings() {
        return bindings;
    }

    /**
     * @param name the name to set
     */
    public ServiceSummaryBean setName(String name) {
        this.name = name;
        return this;
    }

    /**
     * @param category the category to set
     */
    public ServiceSummaryBean setApplication(String category) {
        this.application = category;
        return this;
    }

    /**
     * @param iface the iface to set
     */
    public ServiceSummaryBean setIface(String iface) {
        this.iface = iface;
        return this;
    }

    /**
     * @param bindings the address to set
     */
    public ServiceSummaryBean setBindings(Set<BindingBean> bindings) {
        this.bindings = bindings;
        return this;
    }

    /**
     * @return the serviceId
     */
    public String getServiceId() {
        return serviceId;
    }

    /**
     * @param serviceId the serviceId to set
     */
    public void setServiceId(String serviceId) {
        this.serviceId = serviceId;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());
        return result;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ServiceSummaryBean other = (ServiceSummaryBean) obj;
        if (serviceId == null) {
            if (other.serviceId != null)
                return false;
        } else if (!serviceId.equals(other.serviceId))
            return false;
        return true;
    }

}


text:
import * as FileStream from 'fs';
import { Path, File } from "../IO";
import { StringUtils } from "../Utils/index";

let projectDir = Path.resolve(__dirname, '../..');

export class CoreLogger {
    private logFile: NodeJS.WritableStream;
    private errorFile: NodeJS.WritableStream;
    static time: number = -1;

    private constructor(logFile: string, errorFile: string) {
        if (logFile != undefined) {
            File.createDirSync(Path.dirname(logFile));
            this.logFile = FileStream.createWriteStream(logFile, {'flags': 'a'});
        }
        if (errorFile != undefined) {
            File.createDirSync(Path.dirname(errorFile));
            this.errorFile = FileStream.createWriteStream(errorFile, {'flags': 'a'});
        }
    }

    private static instance: CoreLogger;

    public static get current() {
        if (CoreLogger.instance == undefined) {

            let config = {};
            if (FileStream.existsSync(`${process.cwd()}/logger.json`)) {
                config = require(`${process.cwd()}/logger.json`);
            }
            else if (FileStream.existsSync(`${projectDir}/config/logger.json`)) {
                config = require(`${projectDir}/config/logger.json`);
            }

            CoreLogger.instance = new CoreLogger(config['logFile'], config['errorFile']);
        }
        return CoreLogger.instance;
    }

    public log(message: string) {
        console.log(message);

        if(this.logFile != undefined){
            this.logFile.write(StringUtils.removeStyling(message) + '\n')
        }

        CoreLogger.time = Date.now();
    }

    public error(message: string) {
        console.error(message);

        let noStyling = StringUtils.removeStyling(message) + '\n';

        if(this.logFile != undefined){
            this.logFile.write(noStyling)
        }
        if(this.errorFile != undefined){
            this.errorFile.write(noStyling)
        }

        CoreLogger.time = Date.now();
    }
}


text:
<?php

require_once("common.inc.php");

function crowDistance($lat1, $lon1, $lat2, $lon2) {
	$theta = $lon1 - $lon2;
	$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
	$dist = acos($dist);
	$dist = rad2deg($dist);
	return $dist * 60 * 1.1515 * 1.609344;
}

function drivingInfo($jsonFile) {
	$directions = json_decode(file_get_contents($jsonFile));
	$distance = 0;
	$duration = 0;
	$route = $directions->routes[0];
	$leg = $route->legs[0];
	$distance = $leg->distance->value / 1000;
	$duration = $leg->duration->value / 3600;
	return array( "distance" => $distance, "duration" => $duration);
}

for ($i = 0; $i < count($stadia); $i++) {
	$stadiumI = $stadia[$i];
	$crowDistance = 0;
	$drivingDistance = 0;
	$drivingDuration = 0;
	for ($j = 0; $j < count($stadia); $j++) {
		if ($j == $i) {
			continue;
		}

		$stadiumJ = $stadia[$j];

		$crowDistance += crowDistance($stadiumI[$idxLat], $stadiumI[$idxLon], $stadiumJ[$idxLat], $stadiumJ[$idxLon]);
		$drivingInfo = drivingInfo($directionsDir."/".$stadiumI[$idxTeamName]." - ".$stadiumJ[$idxTeamName].".json");
		$drivingDistance += $drivingInfo["distance"];
		$drivingDuration += $drivingInfo["duration"];
	}
	echo $stadiumI[$idxTeamName]."\t".round($crowDistance, 2)."\t".round($drivingDistance, 2)."\t".round($drivingDuration, 2)."\n";
}

?>


text:
FROM zetdata/cdh:4
# MAINTAINER Your_name, Your_email_address

ADD spec.json /home/run/
ADD main.py /home/run/
ADD specparser.py /home/run/


text:
@protocol FilterSiteBrandListModel
@end

@interface FilterSiteBrandListModel : JSONModel
@property(nonatomic, copy)NSString *brand_id;
@property(nonatomic, copy)NSString *brand_sn;
@property(nonatomic, copy)NSString *brand_name;

@end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--

    DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

    Copyright (c) 2012, 2022 Oracle and/or its affiliates. All rights reserved.

    Oracle licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

<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">

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.jvnet.jax-ws-commons</groupId>
    <artifactId>mojo.it.Chebiwebservices.local</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>Chebiwebservices-local</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jaxws.plugin.version>3.0.0</jaxws.plugin.version>
        <jaxws-ri.version>3.0.0</jaxws-ri.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-rt</artifactId>
            <version>${jaxws-ri.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
        <!-- since we dont want to save copyright file into the repository,
             antrun is used to download the wsdl file to a local directory first
         -->
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <phase>initialize</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <delete dir="${project.build.directory}" />
                                <mkdir dir="${project.build.directory}" />
                                <get src="http://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl"
                                     dest="${project.build.directory}/ebi.wsdl" />
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <release>8</release>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.sun.xml.ws</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>${jaxws.plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                        <configuration>
                            <wsdlDirectory>${project.build.directory}</wsdlDirectory>
                            <wsdlFiles>
                                <wsdlFile>ebi.wsdl</wsdlFile>
                            </wsdlFiles>
                            <xnocompile>false</xnocompile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
Starter project for Angular Material Projects

![Alt text](doc/img-2.png?raw=true "Dashboard")

start-1 includes below libraries:

* [angularjs](https://angularjs.org/)
* [angular-permission](https://github.com/Narzerus/angular-permission)
* [angular-animate](https://docs.angularjs.org/guide/animations)
* [angular-aria](https://docs.angularjs.org/api/ngAria)
* [angular-messages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages)
* [angular-material](https://material.angularjs.org/latest/)
* [angular-sanitize](https://docs.angularjs.org/api/ngSanitize/service/$sanitize)
* [angular-ui-router](https://github.com/angular-ui/ui-router)
* [ngstorage](https://github.com/gsklee/ngStorage)
* [angular-filter](https://github.com/a8m/angular-filter)
* [angular-material-data-table](https://github.com/daniel-nagy/md-data-table)
* [flag-icon-css](https://github.com/lipis/flag-icon-css)
* [font-awesome](http://fontawesome.io/)
* [material-design-iconic-fonts](https://github.com/zavoloklom/material-design-iconic-font)
* [ng-letter-avatar](https://github.com/uttesh/ngletteravatar)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. indica 303. 1768

#### Original name
null

### Remarks
null


text:
class Evade:
    """
    This represents an Evade action
    """
    def __init__(self):
        """
        Constructor
        """
        pass


text:
<Title>Johnson All Pairs Shortest Paths</Title>

<TT>johnson_all_pairs_shortest_paths</TT>

// named parameter version
  template <class VertexAndEdgeListGraph, class DistanceMatrix,
            class VertexID, class Weight, class BinaryPredicate,
            class BinaryFunction, class Infinity, class DistanceZero>
  bool
  johnson_all_pairs_shortest_paths(VertexAndEdgeListGraph& g1,
               DistanceMatrix& D,
               VertexID id1, Weight w1, const BinaryPredicate& compare,
               const BinaryFunction& combine, const Infinity& inf,
               DistanceZero zero);

template <typename Graph, typename DistanceMatrix, typename P, typename T, typename R>
bool johnson_all_pairs_shortest_paths(Graph& g, DistanceMatrix& D,
  const bgl_named_params<P, T, R>& params = all defaults)

// non-named parameter version
template <typename Graph, typename DistanceMatrix,
          typename VertexIndex, typename WeightMap, typename DT>
bool
johnson_all_pairs_shortest_paths(VertexAndEdgeListGraph& g1,
  DistanceMatrix& D,
  VertexIndex i_map, WeightMap w_map, DT zero)

This algorithm finds the shortest distance between every pair of
vertices in the graph. The algorithm returns false if there is a
negative weight cycle in the graph and true otherwise. The distance
between each pair of vertices is stored in the distance matrix
<TT>D</TT>. This is one of the more time intensive graph algorithms,
having a time complexity of O(V E log V).

This algorithm should be used to compute shortest paths between
every pair of vertices for sparse graphs. For dense graphs, use floyd_warshall_all_pairs_shortest_paths.

Where Defined

<TT>boost/graph/johnson_all_pairs_shortest.hpp</TT>

Parameters

IN: <tt>Graph& g</tt>

A directed or undirected graph. The graph type must be a model of
Vertex List Graph,
Edge List Graph,
and Incidence Graph.

OUT: <tt>DistanceMatrix& D</tt>

The length of the shortest path between each pair of vertices
u,v in the graph is stored in <tt>D[u][v]</tt>. The set of
types {<tt>DistanceMatrix, vertices_size_type, D</tt>} must be a model
of BasicMatrix where <tt>D</tt> is the
value type of the <tt>DistanceMap</tt>.

Named Parameters

IN: <tt>weight_map(WeightMap w_map)</tt>

  The weight or ``length'' of each edge in the graph.
  The type <tt>WeightMap</tt> must be a model of
  Readable Property Map. The edge descriptor type of
  the graph needs to be usable as the key type for the weight
  map. The value type for the map must be
  Addable with the value type of the distance map.

  Default:  <tt>get(edge_weight, g)</tt>

UTIL: <tt>weight_map2(WeightMap2 w2_map)</tt>

  This parameter is no longer needed, and will be ignored.

IN: <tt>vertex_index_map(VertexIndexMap i_map)</tt>

  This maps each vertex to an integer in the range <tt>[0,
    num_vertices(g))</tt>. This is necessary for efficient updates of the
  heap data structure in the internal call to Dijkstra's algorithm.  The type
  <tt>VertexIndexMap</tt> must be a model of
  Readable Property Map. The value type of the map must be an
  integer type. The vertex descriptor type of the graph needs to be
  usable as the key type of the map.

  Default: <tt>get(vertex_index, g)</tt>
    Note: if you use this default, make sure your graph has
    an internal <tt>vertex_index</tt> property. For example,
    <tt>adjacenty_list</tt> with <tt>VertexList=listS</tt> does
    not have an internal <tt>vertex_index</tt> property.

UTIL: <tt>distance_map(DistanceMap d_map)</tt>

  This parameter is no longer needed, and will be ignored.

IN: <tt>distance_compare(CompareFunction cmp)</tt>

  This function is use to compare distances to determine
  which vertex is closer to the source vertex.
  The <tt>CompareFunction</tt> type must be a model of
  \stlconcept{BinaryPredicate} and have argument types that
  match the value type of the <tt>WeightMap</tt> property map.

  Default: <tt>std::less<DT></tt> with
  <tt>DT=typename property_traits<WeightMap>::value_type</tt>

IN: <tt>distance_combine(CombineFunction cmb)</tt>

  This function is used to combine distances to compute the distance
  of a path. The <tt>CombineFunction</tt> type must be a model of Binary
  Function. The first argument type of the binary function must
  match the value type of the <tt>DistanceMap</tt> property map and
  the second argument type must match the value type of the
  <tt>WeightMap</tt> property map.  The result type must be the same
  type as the distance value type.

  Default: <tt>std::plus<DT></tt> with
   <tt>DT=typename property_traits<WeightMap>::value_type</tt>

IN: <tt>distance_inf(DT inf)</tt>

  This value is used to initialize the distance for each
  vertex before the start of the algorithm.
  The type <tt>DT</tt> must be the value type of the <tt>WeigthMap</tt>.

  Default: <tt>std::numeric_limits::max()</tt>

IN: <tt>distance_zero(DT zero)</tt>

  This value is used to initialize the distance for the source
  vertex before the start of the algorithm.  The type <tt>DT</tt>
  must be the value type of the <tt>WeigthMap</tt>.

  Default: <tt>0</tt>

UTIL/OUT: <tt>color_map(ColorMap c_map)</tt>

  This is used during the execution of the algorithm to mark the
  vertices. The vertices start out white and become gray when they are
  inserted in the queue. They then turn black when they are removed
  from the queue. At the end of the algorithm, vertices reachable from
  the source vertex will have been colored black. All other vertices
  will still be white. The type <tt>ColorMap</tt> must be a model of
  Read/Write
  Property Map. A vertex descriptor must be usable as the key type
  of the map, and the value type of the map must be a model of
  Color Value.

  Default: an
  <tt>iterator_property_map</tt> created from a <tt>std::vector</tt>
  of <tt>default_color_type</tt> of size <tt>num_vertices(g)</tt> and
  using the <tt>i_map</tt> for the index map.

Complexity

The time complexity is O(V E log V).

Example

The file <tt>example/johnson-eg.cpp</tt> applies
Johnson's algorithm for all-pairs shortest paths to the example graph
from page 568 of the CLR [8].

Copyright © 2000-2001
Jeremy Siek, Indiana University (jsiek@osl.iu.edu)


text:
import { IResolvers, Maybe } from '@graphql-tools/utils';
/**
 * Additional options for merging resolvers
 */
export interface MergeResolversOptions {
    exclusions?: string[];
}
/**
 * Deep merges multiple resolver definition objects into a single definition.
 * @param resolversDefinitions Resolver definitions to be merged
 * @param options Additional options
 *
 * ```js
 * const { mergeResolvers } = require('@graphql-tools/merge');
 * const clientResolver = require('./clientResolver');
 * const productResolver = require('./productResolver');
 *
 * const resolvers = mergeResolvers([
 *  clientResolver,
 *  productResolver,
 * ]);
 * ```
 *
 * If you don't want to manually create the array of resolver objects, you can
 * also use this function along with loadFiles:
 *
 * ```js
 * const path = require('path');
 * const { mergeResolvers } = require('@graphql-tools/merge');
 * const { loadFilesSync } = require('@graphql-tools/load-files');
 *
 * const resolversArray = loadFilesSync(path.join(__dirname, './resolvers'));
 *
 * const resolvers = mergeResolvers(resolversArray)
 * ```
 */
export declare function mergeResolvers<TSource, TContext>(resolversDefinitions: Maybe<IResolvers<TSource, TContext>> | Maybe<Maybe<IResolvers<TSource, TContext>>[]>, options?: MergeResolversOptions): IResolvers<TSource, TContext>;


text:
<?php
	namespace Mvc\Db;

	use PDO;
	use PDOStatement;

	class MySqlDbDriver implements DbDriver{
		/**
		 * @var PDO
		 */
		private $connection;

		public function connect($connectionParams){
			$this->connection = new PDO("mysql:dbname={$connectionParams['db']};host={$connectionParams['host']}", $connectionParams['username'], $connectionParams['password']);

			$this->execQuery("SET NAMES UTF-8");
		}
		/**
		 *
		 * Enter description here ...
		 * @return PDOStatement
		 */
		public function execQuery($query){
			$statement = $this->connection->prepare($query);

			$statement->execute();
			return $statement;
		}

		public function getNumberAffectedRows(PDOStatement $resource){
			return $resource->rowCount();
		}

		public function fetch($query){
			$statement = $this->execQuery($query);
			return $statement->fetch(PDO::FETCH_ASSOC);
		}

		public function fetchColumn($query,$columnIndex=1){
			$statement = $this->execQuery($query);
			return $statement->fetchAll(PDO::FETCH_COLUMN,$columnIndex);
		}

		public function fetchAll($query){
			$statement = $this->execQuery($query);
			return $statement->fetchAll(PDO::FETCH_ASSOC);
		}

		public function escape($data){
			return addslashes($data);
		}

		public function startTransaction(){
			$this->connection->beginTransaction();
		}

		public function commitTransaction(){
			$this->connection->commit();
		}

		public function rollbackTransaction(){
			$this->connection->rollBack();
		}
	}


text:
package org.seasar.doma.internal.jdbc.command;

import java.util.function.Function;
import java.util.stream.Stream;
import org.seasar.doma.jdbc.domain.DomainType;

public class DomainStreamHandler<BASIC, DOMAIN, RESULT>
    extends ScalarStreamHandler<BASIC, DOMAIN, RESULT> {

  public DomainStreamHandler(
      DomainType<BASIC, DOMAIN> domainType, Function<Stream<DOMAIN>, RESULT> mapper) {
    super(domainType::createScalar, mapper);
  }
}


text:
package com.dubbo;

/**
 * @author gang.lvg
 */
public class ThriftUtils {

    /**
     * Generate class name which represents service arguments.
     *
     * @param serviceName service name
     * @param methodName method name
     * @return method args class name or null
     */
    public static String generateMethodArgsClassName( String serviceName, String methodName ) {

        int index = serviceName.lastIndexOf( "." );

        if ( index > 0 ) {

            return new StringBuilder( 32 )
                    .append( serviceName.substring( 0, index + 1 ) )
                    .append( "$__" )
                    .append( serviceName.substring( index + 1 ) )
                    .append( "Stub$" )
                    .append( methodName )
                    .append( "_args" )
                    .toString();

        } else {
            return new StringBuffer( 32 )
                    .append( "$__" )
                    .append( serviceName )
                    .append( "Stub$" )
                    .append( methodName )
                    .append( "_args" )
                    .toString();
        }

    }

    public static String generateMethodResultClassName( String serviceName, String method ) {

        int index = serviceName.lastIndexOf( "." );

        if ( index > 0 ) {

            return new StringBuilder( 32 )
                    .append( serviceName.substring( 0, index + 1 ) )
                    .append( "$__" )
                    .append( serviceName.substring( index + 1 ) )
                    .append( "Stub$" )
                    .append( method )
                    .append( "_result" )
                    .toString();

        } else {
            return new StringBuilder( 32 )
                    .append( "$__" )
                    .append( serviceName )
                    .append( "Stub$" )
                    .append( method )
                    .append( "_result" )
                    .toString();
        }

    }

    public static String generateSetMethodName( String fieldName ) {

        return new StringBuilder( 16 )
                .append( "set" )
                .append( Character.toUpperCase( fieldName.charAt( 0 ) ) )
                .append( fieldName.substring( 1 ) )
                .toString();

    }

    public static String generateGetMethodName( String fieldName ) {
        return new StringBuffer( 16 )
                .append( "get" )
                .append( Character.toUpperCase( fieldName.charAt( 0 ) ) )
                .append( fieldName.substring( 1 ) )
                .toString();
    }

    public static String generateMethodArgsClassNameThrift( String serviceName, String methodName ) {

        int index = serviceName.indexOf( "$" );

        if ( index > 0 ) {
            return new StringBuilder( 32 )
                    .append( serviceName.substring( 0, index + 1 ) )
                    .append( methodName )
                    .append( "_args" )
                    .toString();
        }

        return null;

    }

    public static String generateMethodResultClassNameThrift( String serviceName, String methodName ) {

        int index = serviceName.indexOf( "$" );

        if ( index > 0 ) {
            return new StringBuilder( 32 )
                    .append( serviceName.substring( 0, index + 1 ) )
                    .append( methodName )
                    .append( "_result" )
                    .toString();
        }

        return null;

    }

}


text:
'use strict';

/**
 * @ngdoc directive
 * @name digitalCasefileApp.directive:interview
 * @description
 * # interview
 */
angular.module('digitalCasefileApp')
  .directive('interview', function () {
    return {
      templateUrl: 'scripts/directives/interview.html',
      restrict: 'E',
      scope: {
        interview: '=data',
        store: '&',
        showspinner: '='
      },
      replace: true,
      link: function postLink() {
        //console.log('interview link', [$scope, $element, $attrs]);

      }
    };
  });


text:
layout: post
title: "Edmund Berkeley's Simon Relay Processor"
---

The following site contains description and schematic of [another relay-based processor](http://www.cs.ubc.ca/~hilpert/e/simon/index.html).

![](http://www.blinkenlights.com/classiccmp/berkeley/re1050sm.jpg)

It was created in 1950s and can be used to demonstrate principles and architecture of processors.

Here is the description taken from the site: "Simon is a Harvard architecture machine constructed from relays. The program is executed directly from paper tape. In these regards it was behind the state-of-the-art as several electronic stored-program machines were under design or construction by the late 1940s. The main data registers and ALU are 2 bits wide, data input is via either the paper tape or 5 toggle switches, output is via 5 lamps.

As an educational instrument, Simon was directed more towards the electrical implementation of logic than towards programming. As such, and as a minimal machine, programmibility is rather limited. The one saving grace may be that the program can be quite long (limited only by paper tape handling), a feature that certainly would not have been feasible in an attempt to make an inexpensive stored-program machine at the time."


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.plugin.assembler.sleigh.util;

import ghidra.app.plugin.assembler.sleigh.parse.AssemblyParseActionGotoTable;
import ghidra.app.plugin.assembler.sleigh.parse.AssemblyParseTransitionTable;
import ghidra.app.plugin.assembler.sleigh.symbol.AssemblySymbol;

/**
 * An entry in a (sparse) LR(0) transition table or LALR(1) action/goto table
 *
 * @see AssemblyParseTransitionTable
 * @see AssemblyParseActionGotoTable
 * @param <T> the type of each entry in a table cell
 */
public class TableEntry<T> extends TableEntryKey {
	private final T value;

	/**
	 * Create a new table entry with the given value at the given state and symbol
	 *
	 * @param state the row
	 * @param sym the column
	 * @param value the value
	 */
	public TableEntry(int state, AssemblySymbol sym, T value) {
		super(state, sym);
		this.value = value;
	}

	/**
	 * Get the value of the entry
	 *
	 * @return the value
	 */
	public T getValue() {
		return value;
	}
}


text:
(function($){

        var msg = $('#msgtpl').html(),
              msgline = $('#msgtpl-line').html(),
              lastsender = false,
              currentusr = '',
              uri = 'http://' + window.location.host,
              socket = io.connect(window.location.host);

        var displayUser = function (user) {
           if(user.username == currentusr){
            <% if (languageSelected == 'english') { %>user.username = "Me";<% } %>
            <% if (languageSelected == 'french') { %>user.username = "Moi";<% } %>
            <% if (languageSelected == 'german') { %>user.username = "Mir";<% } %>
          }
          $('#users').append('');
        }

        var displayMessage = function (message) {
           if(message.user.username == currentusr){
            <% if (languageSelected == 'english') { %>message.user.username = "Me";<% } %>
            <% if (languageSelected == 'french') { %>message.user.username = "Moi";<% } %>
            <% if (languageSelected == 'german') { %>message.user.username = "Mir";<% } %>
          }else{
            $('#sound')[0].play();
          }

          if(lastsender != message.user.id){
            $('#messages').append('

');
            $('#messages').append( '
' + Mustache.render(msg, message) + '
' );
            lastsender = message.user.id;
          }else{
            $('#messages').append( '
' + Mustache.render(msgline, message) + '
' );
          }
          $('#messages').animate({ scrollTop: $('#messages').prop('scrollHeight') }, 500);
        }

        var generateId = function () {
                 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz";
                 var stringLength = 8;
                 var randomstring = "";
                 for(var i = 0; i < stringLength; i++) {
                    var rnum = Math.floor(Math.random() * chars.length);
                    randomstring += chars.substring(rnum, rnum + 1);
            }
            return randomstring;
        }

        $('#msgtpl').remove();
        $('#msgtpl-line').remove();

         $.getJSON(uri + '/api/', function (data) {
          for (var message in data.messages){
            displayMessage(data.messages[message]);
          }
          for (var user in data.users){
            displayUser(data.users[user]);
          }
         });

        $('#loginform').submit(function(event){
          event.preventDefault();

          var mail = $('#mail').val().replace(/ /g, ''),
          username = $('#username').val().replace(/ /g, '');

          if(username == ''){
          <% if (languageSelected == 'english') { %>sweetAlert('Oops...', 'You must enter a nickname!', 'error');<% } %>
          <% if (languageSelected == 'french') { %>sweetAlert('Oups...', 'Vous devez entrer un pseudo !', 'error');<% } %>
          <% if (languageSelected == 'german') { %>sweetAlert('Ups! ...', 'Geben Sie bitte eine Spitznamen!', 'error');<% } %>
          }else if(mail == ''){
                socket.emit('login', {username: $('#username').val(), mail: generateId()});
          }else{
                socket.emit('login', {username: $('#username').val(), mail: $('#mail').val()});
          };
          return false;
          });

        $('#msgform').submit(function(event){
          event.preventDefault();
          var message = $('#message').val().replace(/ /g, '');
           if(message == ''){
             <% if (languageSelected == 'english') { %>sweetAlert('Oops...', 'You must enter an message!', 'error');<% } %>
             <% if (languageSelected == 'french') { %>sweetAlert('Oups...', 'Vous devez entrer un message !', 'error');<% } %>
             <% if (languageSelected == 'german') { %>sweetAlert('Ups...', 'Geben Sie bitte eine Meldung!', 'error');<% } %>
            }else{
              socket.emit('newmsg', {message : twttr.txt.autoLink(twttr.txt.htmlEscape($('#message').val())) });
              $('#message').val('');
            };
            $('#message').focus();
            return false;
        });

        socket.on('newmsg', function(message){
          displayMessage(message);
        });

        socket.on('logged', function(){
                $('#login').fadeOut();
                currentusr = $('#username').val();
                $('#message').focus();
        });

        socket.on('logerr', function(message){
           sweetAlert('Oops...', message, 'error')
         });

        socket.on('newusr', function(user){
          displayUser(user);
        });

        socket.on('disusr', function(user){
          $('#'+user.id).slideUp(100, function(){
            $('#'+user.id).remove();
          });
        });

      })(jQuery);


text:
package advent2016;

import java.awt.Point;
import java.util.HashSet;

public class Day1 {

	public int calculateDistance(final String input) {
		String[] movements = splitMovements(input);
		int x = 0;
		int y = 0;
		int direction = 0;
		// 0 - NORTH
		// 1 - EAST
		// 2 - SOUTH
		// 3 - WEST
		for (int i = 0; i < movements.length; i++) {
			String movement = movements[i];
			direction = determineDirection(direction, movement.charAt(0));

			Integer distanceFrom = distanceToTravel(movement);
			switch (direction) {
			case 0:
				y += distanceFrom;
				break;
			case 2:
				y -= distanceFrom;
				break;
			case 1:
				x += distanceFrom;
				break;
			case 3:
				x -= distanceFrom;
				break;
			default:
				throw new IllegalArgumentException(movement);
			}
		}
		return calculateDirectDistance(x, y);
	}

	private int determineDirection(int direction, final char rotation) {
		switch (rotation) {
		case 'L': // left
			direction--;
			break;
		case 'R': // right
			direction++;
			break;
		default:
			throw new IllegalArgumentException("only L and R are allowed, but was: " + rotation);
		}
		if (direction < 0) {
			direction = 3;
		}
		else if (direction > 3) {
			direction = 0;
		}
		return direction;
	}

	public int calculateDistanceToTwice(final String input) {
		Point currentPosition = new Point(0, 0);
		Direction direction = Direction.NORTH;

		HashSet<Point> points = new HashSet<>();
		String[] movements = splitMovements(input);
		for (int i = 0; i < movements.length; i++) {
			String movement = movements[i];
			direction = direction.determineDirection(movement.charAt(0));
			for (int j = 0; j < distanceToTravel(movement); j++) {
				currentPosition = direction.nextPosition(currentPosition);
				if (points.contains(currentPosition)) {
					return calculateDirectDistance(currentPosition);
				}
				else {
					points.add(currentPosition);
				}
			}
		}
		return -1;
	}

	private int calculateDirectDistance(final Point currentPosition) {
		return calculateDirectDistance(currentPosition.x, currentPosition.y);
	}

	private int calculateDirectDistance(final int x, final int y) {
		return Math.abs(x) + Math.abs(y);
	}

	private String[] splitMovements(final String input) {
		return input.split(", ");
	}

	private Integer distanceToTravel(final String movement) {
		return Integer.valueOf(movement.substring(1));
	}
}


text:
public class SysLogGenerator extends AbstractGenerator {
	private String eventId;
	private String eventType;
	private String eventTime;
	private String eventSource;
 	private String msg;
	private int line;

	public SysLogGenerator(){
		produceLog();
	}

          public native String readSystemLog();
          static {
                    System.loadLibrary("../lib/readSystemLogDll");
          }

	public void produceLog(){
                    msg=readSystemLog();
                    String [] logInfos = msg.split("##");
                    eventId = logInfos[0];
                    eventType = logInfos[1];
                    eventTime = logInfos[2];
                    eventSource = logInfos[3];

	}

	public LogItem generate() {
		super.checkStatus();
		return new LogItem(eventId, eventType, eventTime, eventSource);
	}

	public String getMsg() {
          		return msg;
          }

	public void setMsg(String message) {
                    msg=message;
                    String [] logInfos = msg.split("##");
                    eventId = logInfos[0];
                    eventType = logInfos[1];
                    eventTime = logInfos[2];
                    eventSource = logInfos[3];
	}

}


text:
using UnityEngine;
using System.Collections;

namespace StrayTech
{
    public interface ICameraState
    {
        ICameraStateSettings StateSettings { get; }
        Vector3 Position { get; set; }
        Quaternion Rotation { get; set; }
        CameraSystem.CameraStateEnum StateType { get; }
        bool AllowsModifiers { get; }

        void UpdateCamera(float deltaTime);
        void Cleanup();
    }
}


text:
package sec.geo.shape;

import org.gavaghan.geodesy.GlobalPosition;

public class Point {

    private final double longitudeDegrees;
    private final double latitudeDegrees;
    private final double altitudeMeters;

    public Point(double longitudeDegrees, double latitudeDegrees) {
        this(longitudeDegrees, latitudeDegrees, 0);
    }

    public Point(double longitudeDegrees, double latitudeDegrees, double altitudeMeters) {
        this.longitudeDegrees = longitudeDegrees;
        this.latitudeDegrees = latitudeDegrees;
        this.altitudeMeters = altitudeMeters;
    }

    public double getLongitude() {
        return longitudeDegrees;
    }

    public double getLatitude() {
        return latitudeDegrees;
    }

    public double getAltitude() {
        return altitudeMeters;
    }

    public GlobalPosition toGlobalPos() {
        return new GlobalPosition(getLatitude(), getLongitude(), getAltitude());
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Point)) {
            return false;
        }
        Point other = (Point) o;
        return (longitudeDegrees == other.longitudeDegrees) && (latitudeDegrees == other.latitudeDegrees)
                && (altitudeMeters == other.altitudeMeters);
    }

    @Override
    public String toString() {
        return "[" + longitudeDegrees + "," + latitudeDegrees + "," + altitudeMeters + "]";
    }
}


text:
import java.util.List;
import java.util.stream.Collectors;

public class Test {
  static String test(List<String> list) {
    final String sb = list.stream().filter(s -> !s.isEmpty()).map(String::trim).collect(Collectors.joining("", "ctor" + "first", ""));
      return sb.length() == 0 ? null : sb;
  }
}


text:
title: "VPC Configurations"
order: 800
---

When you [install a Rack](/docs/installing-a-rack/), most of the AWS resources used by Convox are launched inside of a new [VPC](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Introduction.html). That default behavior might not be sufficient in all cases, so we've covered a few of the common non-default VPC configurations below.

1. [Installing into an existing VPC](#installing-into-an-existing-vpc)
1. [Peering VPCs in the same region](#peering-vpcs-in-the-same-region)
1. [Connecting VPCs in different regions](#connecting-vpcs-in-different-regions)

## Installing into an existing VPC

By default, Convox Rack installations create a new VPC with subnets in two or three (when available) Availability Zones in your chosen AWS Region. If you'd like to install a Convox Rack into an existing VPC, we recommend allocating a /24 block subnet in each of three Availability Zones.

To install a Rack into an existing VPC, you'll need to provide the VPC ID and the CIDRs of the subnets into which Convox should be installed.

    convox install \
      --existing-vpc <VPC ID> \
      --vpc-cidr <VPC CIDR> \
      --subnet-cidrs <comma-separated CIDRs>

For example:

    convox install \
      --existing-vpc "vpc-abcd1234" \
      --vpc-cidr "10.0.0.0/16" \
      --subnet-cidrs "10.0.1.0/24,10.0.2.0/24,10.0.3.0/24"

### Finding the VPC ID and VPC CIDR

You can find your VPC ID and CIDR in the [AWS VPC console](https://console.aws.amazon.com/vpc). Navigate to "Your VPCs" and look in the "VPC ID" and "VPC CIDR" columns.

### Choosing suitable CIDR blocks

Your existing VPC has a CIDR block, and each of your existing subnets has its own CIDR block within that larger VPC block. From the remaining addresses in your VPC CIDR block, you'll need to create an additional subnet in each Availability Zone in which you'd like to run Convox instances. At the moment, Convox requires three subnets with /24 CIDR blocks to give your Convox installation 254 addresses per subnet—plenty of room for typical scaling needs.

Because [VPCs cannot be resized](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html#VPC_Sizing), if your VPC does not have room for these three additional /24 CIDR blocks, you'll need to create a larger VPC and migrate your instances to it.

## Installing a private Rack into an existing VPC

Installing a private Rack into an existing VPC requires specifying a couple more options. You'll need to pass the `--private` option to `convox install` as well as a set of CIDRS for three private subnets using the `--private-cidrs` option. For example:

    convox install \
      --private \
      --existing-vpc "vpc-abcd1234" \
      --vpc-cidr "10.0.0.0/16" \
      --subnet-cidrs "10.0.1.0/24,10.0.2.0/24,10.0.3.0/24" \
      --private-cidrs "10.0.4.0/24,10.0.5.0/24,10.0.6.0/24"

Keep in mind that you will need to create six /24 CIDR block subnets: three public, and three private.

## Peering VPCs in the same region

An alternative to installing a Convox Rack into an existing VPC is to install the Rack into its own isolated VPC and then peer that VPC with another containing your non-Convox infrastructure.

> A VPC peering connection allows you to route traffic between the peer VPCs using private IP addresses; as if they are part of the same network.

The above excerpt comes from the AWS [Peering Guide](http://docs.aws.amazon.com/AmazonVPC/latest/PeeringGuide/Welcome.html), a great place to learn more about this technique.

If you are ready to set up a peering connection between two VPCs, the [Working with VPC Peering Connections](http://docs.aws.amazon.com/AmazonVPC/latest/PeeringGuide/working-with-vpc-peering.html) section of that guide walks you through the steps, which include the following and more:

* Creating a VPC Peering Connection
* Accepting a VPC Peering Connection
* Updating Route Tables for Your VPC Peering Connection
* Updating Your Security Groups to Reference Peered VPC Security Groups

Keep in mind that VPC Peering has a number of [limitations](http://docs.aws.amazon.com/AmazonVPC/latest/PeeringGuide/vpc-peering-overview.html#vpc-peering-limitations) that can complicate its setup. For example, you cannot create a VPC peering connection between VPCs that have matching or overlapping CIDR blocks, or between VPCs that exist in different regions.

## Connecting VPCs in different regions

Because VPC peering is limited to VPCs in the same region, you'll need to take a different approach to connect VPCs in different regions. At the moment, the standard practice is to run an EC2 instance in each VPC and establish an IPSec VPN connection between them. The following two guides offer step-by-step instructions for that setup.

* AWS recommends [Connecting Multiple VPCs with EC2 Instances](https://aws.amazon.com/articles/5472675506466066)
* FortyCloud's [Interconnecting Two AWS VPC Regions](http://fortycloud.com/interconnecting-two-aws-vpc-regions/) covers the same approach in greater detail

When AWS [released VPC Peering](https://aws.amazon.com/blogs/aws/new-vpc-peering-for-the-amazon-virtual-private-cloud/) in 2014, it expressed an intent to build cross-region peering in the future (see excerpt below), so keep an eye out for first-class support in AWS one of these days.

> You can connect any two VPCs that are in the same AWS Region, regardless of ownership, as long as both parties agree. We plan to extend this feature to support cross-Region peering in the future.


text:
package ru.nivanov.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Nikolay Ivanov on 13.12.2017.
 */
public class LogOutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        session.removeAttribute("role");
        session.invalidate();
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.print("You are successfully logged out!");
        out.close();
        req.getRequestDispatcher("/logpage.html").forward(req, resp);
    }
}


text:
<?php

namespace Components\Tools\Models\Orm;

use Hubzero\Database\Relational;

require_once __DIR__ . DS . 'version.php';

/**
 * Tool database model
 *
 * @uses \Hubzero\Database\Relational
 */
class Tool extends Relational
{
	/**
	 * Status constants
	 */
	const STATUS_UNPUBLISHED = 0;
	const STATUS_REGISTERED  = 1;
	const STATUS_CREATED     = 2;
	const STATUS_UPLOADED    = 3;
	const STATUS_INSTALLED   = 4;
	const STATUS_UPDATED     = 5;
	const STATUS_APPROVED    = 6;
	const STATUS_PUBLISHED   = 7;
	const STATUS_RETIRED     = 8;
	const STATUS_ABANDONED   = 9;

	/**
	 * The table namespace
	 *
	 * @var string
	 **/
	protected $table = '#__tool';

	/**
	 * Fields and their validation criteria
	 *
	 * @var array
	 **/
	protected $rules = array(
		'toolname' => 'notempty',
	);

	/**
	 * Automatic fields to populate every time a row is created
	 *
	 * @var  array
	 */
	public $initiate = array(
		'registered',
		'registered_by'
	);

	/**
	 * Generates automatic owned by field value
	 *
	 * @param   array   $data  the data being saved
	 * @return  string
	 */
	public function automaticToolname($data)
	{
		$alias = $data['toolname'];
		$alias = strip_tags($alias);
		$alias = trim($alias);
		if (strlen($alias) > 64)
		{
			$alias = substr($alias . ' ', 0, 64);
			$alias = substr($alias, 0, strrpos($alias, ' '));
		}
		$alias = str_replace(' ', '_', $alias);

		return preg_replace("/[^a-zA-Z0-9_]/", '', strtolower($alias));
	}

	/**
	 * Generates automatic registered field value
	 *
	 * @param   array   $data  The data being saved
	 * @return  string
	 **/
	public function automaticRegistered($data)
	{
		return (isset($data['registered']) && $data['registered'] ? $data['registered'] : Date::toSql());
	}

	/**
	 * Generates automatic registered by field value
	 *
	 * @param   array  $data  The data being saved
	 * @return  int
	 **/
	public function automaticRegisteredBy($data)
	{
		return (isset($data['registered_by']) && $data['registered_by'] ? (int)$data['registered_by'] : (int)User::get('id'));
	}

	/**
	 * Get a list of versions
	 *
	 * @return  object
	 */
	public function versions()
	{
		return $this->oneToMany(__NAMESPACE__ . '\\Version', 'toolname', 'toolname');
	}

	/**
	 * Retrieves one row loaded by toolname field
	 *
	 * @param   string  $toolname
	 * @return  mixed
	 */
	public static function oneByToolname($toolname)
	{
		return self::blank()
			->whereEquals('toolname', $toolname)
			->row();
	}

	/**
	 * Is the tool registered?
	 *
	 * @return  boolean
	 */
	public function isRegistered()
	{
		return ($this->get('state') >= self::STATUS_REGISTERED);
	}

	/**
	 * Is the tool created?
	 *
	 * @return  boolean
	 */
	public function isCreated()
	{
		return ($this->get('state') >= self::STATUS_CREATED);
	}

	/**
	 * Is the tool installed?
	 *
	 * @return  boolean
	 */
	public function isInstalled()
	{
		return ($this->get('state') >= self::STATUS_INSTALLED);
	}
}


text:
#ifndef JLCOMPRESSFOLDER_H_
#define JLCOMPRESSFOLDER_H_

#include "quazip.h"
#include "quazipfile.h"
#include "quazipfileinfo.h"
#include <QString>
#include <QDir>
#include <QFileInfo>
#include <QFile>

/// Utility class for typical operations.
/**
  This class contains a number of useful static functions to perform
  simple operations, such as mass ZIP packing or extraction.
  */
class QUAZIP_EXPORT JlCompress {
private:
    static QStringList extractDir(QuaZip &zip, const QString &dir);
    static QStringList getFileList(QuaZip *zip);
    static QString extractFile(QuaZip &zip, QString fileName, QString fileDest);
    static QStringList extractFiles(QuaZip &zip, const QStringList &files, const QString &dir);
    /// Compress a single file.
    /**
      \param zip Opened zip to compress the file to.
      \param fileName The full path to the source file.
      \param fileDest The full name of the file inside the archive.
      \return true if success, false otherwise.
      */
    static bool compressFile(QuaZip* zip, QString fileName, QString fileDest);
    /// Compress a subdirectory.
    /**
      \param parentZip Opened zip containing the parent directory.
      \param dir The full path to the directory to pack.
      \param parentDir The full path to the directory corresponding to
      the root of the ZIP.
      \param recursive Whether to pack sub-directories as well or only
      files.
      \return true if success, false otherwise.
      */
    static bool compressSubDir(QuaZip* parentZip, QString dir, QString parentDir, bool recursive,
                               QDir::Filters filters);
    /// Extract a single file.
    /**
      \param zip The opened zip archive to extract from.
      \param fileName The full name of the file to extract.
      \param fileDest The full path to the destination file.
      \return true if success, false otherwise.
      */
    static bool extractFile(QuaZip* zip, QString fileName, QString fileDest);
    /// Remove some files.
    /**
      \param listFile The list of files to remove.
      \return true if success, false otherwise.
      */
    static bool removeFile(QStringList listFile);

public:
    /// Compress a single file.
    /**
      \param fileCompressed The name of the archive.
      \param file The file to compress.
      \return true if success, false otherwise.
      */
    static bool compressFile(QString fileCompressed, QString file);
    /// Compress a list of files.
    /**
      \param fileCompressed The name of the archive.
      \param files The file list to compress.
      \return true if success, false otherwise.
      */
    static bool compressFiles(QString fileCompressed, QStringList files);
    /// Compress a whole directory.
    /**
      Does not compress hidden files. See compressDir(QString, QString, bool, QDir::Filters).

      \param fileCompressed The name of the archive.
      \param dir The directory to compress.
      \param recursive Whether to pack the subdirectories as well, or
      just regular files.
      \return true if success, false otherwise.
      */
    static bool compressDir(QString fileCompressed, QString dir = QString(), bool recursive = true);
    /**
     * @brief Compress a whole directory.
     *
     * Unless filters are specified explicitly, packs
     * only regular non-hidden files (and subdirs, if @c recursive is true).
     * If filters are specified, they are OR-combined with
     * <tt>%QDir::AllDirs|%QDir::NoDotAndDotDot</tt> when searching for dirs
     * and with <tt>QDir::Files</tt> when searching for files.
     *
     * @param fileCompressed path to the resulting archive
     * @param dir path to the directory being compressed
     * @param recursive if true, then the subdirectories are packed as well
     * @param filters what to pack, filters are applied both when searching
     * for subdirs (if packing recursively) and when looking for files to pack
     * @return true on success, false otherwise
     */
    static bool compressDir(QString fileCompressed, QString dir,
                            bool recursive, QDir::Filters filters);

public:
    /// Extract a single file.
    /**
      \param fileCompressed The name of the archive.
      \param fileName The file to extract.
      \param fileDest The destination file, assumed to be identical to
      \a file if left empty.
      \return The list of the full paths of the files extracted, empty on failure.
      */
    static QString extractFile(QString fileCompressed, QString fileName, QString fileDest = QString());
    /// Extract a list of files.
    /**
      \param fileCompressed The name of the archive.
      \param files The file list to extract.
      \param dir The directory to put the files to, the current
      directory if left empty.
      \return The list of the full paths of the files extracted, empty on failure.
      */
    static QStringList extractFiles(QString fileCompressed, QStringList files, QString dir = QString());
    /// Extract a whole archive.
    /**
      \param fileCompressed The name of the archive.
      \param dir The directory to extract to, the current directory if
      left empty.
      \return The list of the full paths of the files extracted, empty on failure.
      */
    static QStringList extractDir(QString fileCompressed, QString dir = QString());
    /// Get the file list.
    /**
      \return The list of the files in the archive, or, more precisely, the
      list of the entries, including both files and directories if they
      are present separately.
      */
    static QStringList getFileList(QString fileCompressed);
    /// Extract a single file.
    /**
      \param ioDevice pointer to device with compressed data.
      \param fileName The file to extract.
      \param fileDest The destination file, assumed to be identical to
      \a file if left empty.
      \return The list of the full paths of the files extracted, empty on failure.
      */
    static QString extractFile(QIODevice *ioDevice, QString fileName, QString fileDest = QString());
    /// Extract a list of files.
    /**
      \param ioDevice pointer to device with compressed data.
      \param files The file list to extract.
      \param dir The directory to put the files to, the current
      directory if left empty.
      \return The list of the full paths of the files extracted, empty on failure.
      */
    static QStringList extractFiles(QIODevice *ioDevice, QStringList files, QString dir = QString());
    /// Extract a whole archive.
    /**
      \param ioDevice pointer to device with compressed data.
      \param dir The directory to extract to, the current directory if
      left empty.
      \return The list of the full paths of the files extracted, empty on failure.
      */
    static QStringList extractDir(QIODevice *ioDevice, QString dir = QString());
    /// Get the file list.
    /**
      \return The list of the files in the archive, or, more precisely, the
      list of the entries, including both files and directories if they
      are present separately.
      */
    static QStringList getFileList(QIODevice *ioDevice);
};

#endif /* JLCOMPRESSFOLDER_H_ */


text:
package hei2017.controller;

import com.fasterxml.jackson.annotation.JsonView;
import hei2017.entity.Project;
import hei2017.entity.Sprint;
import hei2017.entity.Story;
import hei2017.json.JsonViews;
import hei2017.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.inject.Inject;
import java.util.List;
import java.util.Set;

/**
 * Created by pic on 16/03/2017.
 */

@EnableWebMvc
@RestController
public class ApiSprintController {

    private final static Logger LOGGER = LoggerFactory.getLogger(ApiController.class);

    @Inject
    ProjectService projectService;

    @Inject
    SprintService sprintService;

    @Inject
    StoryService storyService;

    @Inject
    TaskService taskService;

    @Inject
    UserService userService;

    /*
     * Requêtes SPRINT
     */

    @JsonView(JsonViews.Basique.class)
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/api/sprint", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
    public List<Sprint> showSprints()
    {
        LOGGER.debug("ApiController - showSprints");
        return sprintService.findAll();
    }

    @JsonView(JsonViews.Sprint.class)
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/api/sprint/details", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
    public List<Sprint> showSprintsDetails()
    {
        LOGGER.debug("ApiController - showSprintsDetails");
        return sprintService.findAllWithAll();
    }

    @JsonView(JsonViews.Basique.class)
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/api/sprint/{id}", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
    public ResponseEntity<Sprint> showSprint(@PathVariable Long id)
    {
        LOGGER.debug("ApiController - showSprint");
        Sprint sprint = null;
        if(sprintService.exists(id))
        {
            sprint = sprintService.findOneById(id);
            return new ResponseEntity<Sprint>(sprint, HttpStatus.OK);
        }
        return new ResponseEntity<Sprint>(sprint, HttpStatus.NOT_FOUND);
    }

    @JsonView(JsonViews.Sprint.class)
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/api/sprint/{id}/details", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
    public ResponseEntity<Sprint> showSprintWithAll(@PathVariable Long id)
    {
        LOGGER.debug("ApiController - showSprint");
        Sprint sprint = null;
        if(sprintService.exists(id))
        {
            sprint = sprintService.findOneByIdWithAll(id);
            return new ResponseEntity<Sprint>(sprint, HttpStatus.OK);
        }
        return new ResponseEntity<Sprint>(sprint, HttpStatus.NOT_FOUND);
    }

    @JsonView(JsonViews.Basique.class)
    @RequestMapping(value = "/api/sprint/add", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Sprint> sendSprint(@RequestBody Sprint sprint)
    {
        LOGGER.debug("ApiController - sendSprint");
        sprint = sprintService.save(sprint);
        LOGGER.debug("ApiController - sendSprint - Sprint créé");
        return new ResponseEntity<Sprint>(sprint, HttpStatus.CREATED);
    }

    @JsonView(JsonViews.Basique.class)
    @RequestMapping(value = "/api/sprint/add/project/{idProject}", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Sprint> sendSprintLinkedToProject(@RequestBody Sprint sprint, @PathVariable Long idProject)
    {
        LOGGER.debug("ApiController - sendSprintLinkedToProject");
        Project project = projectService.findOneById(idProject);
        if(project==null)
            return new ResponseEntity<Sprint>(sprint, HttpStatus.NOT_FOUND);
        sprint.setSprintProject(project);
        sprintService.save(sprint);
        LOGGER.debug("ApiController - sendSprintLinkedToProject - Sprint créé et lié à un projet");
        return new ResponseEntity<Sprint>(sprint, HttpStatus.CREATED);

    }

    @JsonView(JsonViews.Basique.class)
    @RequestMapping(value = "/api/sprint/update/{idSprint}", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Sprint> updateSprint(@PathVariable Long idSprint, @RequestBody Sprint sprint)
    {
        LOGGER.debug("ApiController - updateSprint");

        sprintService.updateSprint(idSprint, sprint);
        LOGGER.debug("ApiController - updateSprint - Project maj");
        return new ResponseEntity<Sprint>(sprint, HttpStatus.ACCEPTED);
    }

    @JsonView(JsonViews.Basique.class)
    @RequestMapping(value = "/api/sprint/delete/{id}", method = RequestMethod.DELETE, produces = "application/json")
    public ResponseEntity<Sprint> deleteSprint(@PathVariable("id") Long id)
    {
        LOGGER.debug("ApiController - deleteSprint");

        Sprint sprint = null;
        if(sprintService.exists(id))
        {
            sprint = sprintService.findOneById(id);

            sprintService.deleteOneById(sprint.getId());

            return new ResponseEntity<Sprint>(sprint, HttpStatus.ACCEPTED);
        }
        return new ResponseEntity<Sprint>(sprint, HttpStatus.NOT_FOUND);
    }

    //Renvoie tous les SPRINTS attachés au projet d'id idProject
    @JsonView(JsonViews.Basique.class)
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/api/sprint/project/{idProject}", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
    public Set<Sprint> showSprintsAssociatedToThisProject(@PathVariable Long idProject)
    {
        LOGGER.debug("ApiController - showSprintsAssociatedToThisProject");
        Set<Sprint> sprints = sprintService.findBySprintProject(idProject);
        return sprints;
    }

    @JsonView(JsonViews.Basique.class)
    @RequestMapping(value = "/api/sprint/{idSprint}/story/{idStory}", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Sprint> linkSprintIdWithStoryId(@PathVariable Long idSprint, @PathVariable Long idStory)
    {
        LOGGER.debug("ApiController - linkSprintIdWithStoryId");

        Story story = storyService.findOneByIdWithAll(idStory);
        Sprint sprint = sprintService.findOneByIdWithAll(idSprint);

        if(null==sprint ||null ==story)
        {
            return new ResponseEntity<Sprint>(sprint, HttpStatus.NOT_FOUND);
        }

        story.setStorySprint(sprint);
        story = storyService.save(story);
        sprint = sprintService.findOneByIdWithAll(idSprint);
        return new ResponseEntity<Sprint>(sprint, HttpStatus.CREATED);
    }

}


text:
// define class name and unique id
#define MODEL_IDENTIFIER values
#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f004}"

// define model size
#define NUMBER_OF_REALS 2
#define NUMBER_OF_INTEGERS 2
#define NUMBER_OF_BOOLEANS 2
#define NUMBER_OF_STRINGS 2
#define NUMBER_OF_STATES 1
#define NUMBER_OF_EVENT_INDICATORS 0

// include fmu header files, typedefs and macros
#include "fmuTemplate.h"

// define all model variables and their value references
// conventions used here:
// - if x is a variable, then macro x_ is its variable reference
// - the vr of a variable is its index in array  r, i, b or s
// - if k is the vr of a real state, then k+1 is the vr of its derivative
#define x_          0
#define der_x_      1
#define int_in_     0
#define int_out_    1
#define bool_in_    0
#define bool_out_   1
#define string_in_  0
#define string_out_ 1

// define state vector as vector of value references
#define STATES { x_ }

const char *month[] = {
    "jan","feb","march","april","may","june","july",
    "august","sept","october","november","december"
};

// called by fmi2Instantiate
// Set values for all variables that define a start value
// Settings used unless changed by fmi2SetX before fmi2EnterInitializationMode
void setStartValues(ModelInstance *comp) {
    r(x_) = 1;
    i(int_in_) = 2;
    i(int_out_) = 0;
    b(bool_in_) = fmi2True;
    b(bool_out_) = fmi2False;
    copy(string_in_, "QTronic");
    copy(string_out_, month[0]);
}

// called by fmi2GetReal, fmi2GetInteger, fmi2GetBoolean, fmi2GetString, fmi2ExitInitialization
// if setStartValues or environment set new values through fmi2SetXXX.
// Lazy set values for all variable that are computed from other variables.
void calculateValues(ModelInstance *comp) {
    if (comp->state == modelInitializationMode) {
        // set first time event
        comp->eventInfo.nextEventTimeDefined = fmi2True;
        comp->eventInfo.nextEventTime        = 1 + comp->time;
    }
}

// called by fmi2GetReal, fmi2GetContinuousStates and fmi2GetDerivatives
fmi2Real getReal(ModelInstance *comp, fmi2ValueReference vr){
    switch (vr) {
        case x_     : return   r(x_);
        case der_x_ : return - r(x_);
        default: return 0;
    }
}

// used to set the next time event, if any.
void eventUpdate(ModelInstance *comp, fmi2EventInfo *eventInfo, int isTimeEvent) {
    if (isTimeEvent) {
        eventInfo->nextEventTimeDefined = fmi2True;
        eventInfo->nextEventTime        = 1 + comp->time;
        i(int_out_) += 1;
        b(bool_out_) = !b(bool_out_);
        if (i(int_out_) < 12) copy(string_out_, month[i(int_out_)]);
        else eventInfo->terminateSimulation = fmi2True;
    }
}

// include code that implements the FMI based on the above definitions
#include "fmuTemplate.c"


text:
package org.apache.druid.collections.bitmap;

import java.nio.ByteBuffer;
import java.util.BitSet;

/**
 * BitSetBitmapFactory implements BitmapFactory as a wrapper for java.util.BitSet
 */
public class BitSetBitmapFactory implements BitmapFactory
{
  @Override
  public MutableBitmap makeEmptyMutableBitmap()
  {
    return new WrappedBitSetBitmap();
  }

  @Override
  public ImmutableBitmap makeEmptyImmutableBitmap()
  {
    return makeEmptyMutableBitmap();
  }

  @Override
  public ImmutableBitmap makeImmutableBitmap(MutableBitmap mutableBitmap)
  {
    return mutableBitmap;
  }

  @Override
  public ImmutableBitmap mapImmutableBitmap(ByteBuffer b)
  {
    return new WrappedBitSetBitmap(BitSet.valueOf(b.array()));
  }

  @Override
  public ImmutableBitmap union(Iterable<ImmutableBitmap> b)
  {
    WrappedBitSetBitmap newSet = null;
    for (ImmutableBitmap bm : b) {
      if (null == newSet) {
        newSet = new WrappedBitSetBitmap(((WrappedBitSetBitmap) bm).cloneBitSet());
      } else {
        newSet.union(bm);
      }
    }
    return newSet;
  }

  @Override
  public ImmutableBitmap intersection(Iterable<ImmutableBitmap> b)
  {

    WrappedBitSetBitmap newSet = null;
    for (ImmutableBitmap bm : b) {
      if (null == newSet) {
        newSet = new WrappedBitSetBitmap(((WrappedBitSetBitmap) bm).cloneBitSet());
      } else {
        newSet.intersection(bm);
      }
    }
    return newSet;
  }

  @Override
  public ImmutableBitmap complement(
      ImmutableBitmap b, int length
  )
  {
    return null;
  }
}


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

package com.google.caja.config;

import com.google.caja.reporting.MessageContext;
import com.google.caja.reporting.MessageLevel;
import com.google.caja.reporting.MessagePart;
import com.google.caja.reporting.MessageType;
import com.google.caja.reporting.MessageTypeInt;

import java.io.IOException;

/**
 * Messages for the Config Parsers.
 *
 * @author mikesamuel@gmail.com
 */
public enum ConfigMessageType implements MessageTypeInt {
  MALFORMED_CONFIG("%s: malformed config file: expected %s, not %s",
                   MessageLevel.FATAL_ERROR),
  BAD_URL("%s: malformed URI: %s = %s", MessageLevel.FATAL_ERROR),
  AMBIGUOUS_DEFINITION("%s: ambiguous type definition %s != %s",
                       MessageLevel.FATAL_ERROR),
  // If a key appeared in a white list that was not recognized.
  // If "denies" is mis-spelled as "denied", then this will trigger.
  UNRECOGNIZED_KEY("%s: unrecognized key %s", MessageLevel.WARNING),
  ;

  private final String formatString;
  private final MessageLevel level;
  private final int paramCount;

  ConfigMessageType(String formatString, MessageLevel level) {
    this.formatString = formatString;
    this.level = level;
    this.paramCount = MessageType.formatStringArity(formatString);
  }

  public int getParamCount() {
    return paramCount;
  }

  public void format(MessagePart[] parts, MessageContext context,
                     Appendable out) throws IOException {
    MessageType.formatMessage(formatString, parts, context, out);
  }

  public MessageLevel getLevel() { return level; }
}


text:
package pl.javastart.overriden;

class Example {
    public static void main(String[] args) {
        Course course1 = new Course("Kurs Java", "Poznaj jeden z najbardziej popularnych języków programowania", 123);
        Course course2 = new Course("Kurs HTML", "Naucz się tworzyć strony internetowe", 99);
        System.out.println(course1.toString());
        System.out.println(course2.toString());
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hedwigia 32: 133 (1893)

#### Original name
Arthothelium puniceum Müll. Arg.

### Remarks
null


text:
import scrapy

from moovy.items import MoovyItem

class MoovySpider(scrapy.Spider):
        name = "moovy"
        allowed_domains = ["en.wikipedia.org"]
        start_urls = ["https://en.wikipedia.org/wiki/List_of_Tamil_films_of_2015"]

        def parse(self,response):
			#titles = response.selector.xpath('//table[@class="wikitable sortable"]/tr/td/i/a[contains(@href, "title")]')
			rows = response.selector.xpath('//table[@class="wikitable sortable"]/tr')

			for index, r1 in enumerate(rows):
				#cells = r1.xpath('.//td').extract()
				c1 = r1.css('td')
				#print cells
				print('This is my text %s' % c1)


text:
TBTKPlotDensity.py TBTKResults.h5

#Plot DOS using gaussian smoothing with sigma=0.15
TBTKPlotDOS.py TBTKResults.h5 0.15

#Plot eigen values
TBTKPlotEigenValues.py TBTKResults.h5

#Plot LDOS using gaussian smoothing with sigma=0.15
TBTKPlotLDOS.py TBTKResults.h5 0.15

#Plot magnetization along direction theta=0.1, phi=0.2
TBTKPlotMagnetization.py TBTKResults.h5 0.1 0.2

#Plot spin-polarized LDOS along direction theta=0.1, phi=0.2, using gaussian smoothing with sigma=0.05
TBTKPlotSpinPolarizedLDOS.py TBTKResults.h5 0.1 0.2 0.05


text:
// Generated on Fri Aug 10 16:21:20 CEST 2007
// DTD/Schema  :    http://relaxng.org/ns/structure/1.0

package org.intellij.plugins.relaxNG.xml.dom;

import javax.annotation.Nonnull;

import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.xml.Convert;
import com.intellij.util.xml.GenericAttributeValue;
import com.intellij.util.xml.Required;
import org.intellij.plugins.relaxNG.model.Include;
import org.intellij.plugins.relaxNG.xml.dom.impl.RngHrefConverter;

/**
 * http://relaxng.org/ns/structure/1.0:includeElemType interface.
 */
public interface RngInclude extends RngIncludeContent, Include<XmlElement, RngDefine> {

  /**
   * Returns the value of the href child.
   *
   * @return the value of the href child.
   */
  @Nonnull
  @Required
  @Convert(RngHrefConverter.class)
  @com.intellij.util.xml.Attribute("href")
  GenericAttributeValue<XmlFile> getIncludedFile();
}


text:
<?php

namespace Symfony\Component\Routing\Loader;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Loader\FileLoader;

/**
 * XmlFileLoader loads XML routing files.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @api
 */
class XmlFileLoader extends FileLoader
{
    /**
     * Loads an XML file.
     *
     * @param string $file An XML file path
     * @param string $type The resource type
     *
     * @return RouteCollection A RouteCollection instance
     *
     * @throws \InvalidArgumentException When a tag can't be parsed
     *
     * @api
     */
    public function load($file, $type = null)
    {
        $path = $this->locator->locate($file);

        $xml = $this->loadFile($path);

        $collection = new RouteCollection();
        $collection->addResource(new FileResource($path));

        // process routes and imports
        foreach ($xml->documentElement->childNodes as $node) {
            if (!$node instanceof \DOMElement) {
                continue;
            }

            $this->parseNode($collection, $node, $path, $file);
        }

        return $collection;
    }

    /**
     * Parses a node from a loaded XML file.
     *
     * @param RouteCollection $collection the collection to associate with the node
     * @param DOMElement      $node       the node to parse
     * @param string          $path       the path of the XML file being processed
     * @param string          $file
     */
    protected function parseNode(RouteCollection $collection, \DOMElement $node, $path, $file)
    {
        switch ($node->tagName) {
            case 'route':
                $this->parseRoute($collection, $node, $path);
                break;
            case 'import':
                $resource = (string) $node->getAttribute('resource');
                $type = (string) $node->getAttribute('type');
                $prefix = (string) $node->getAttribute('prefix');
                $this->setCurrentDir(dirname($path));
                $collection->addCollection($this->import($resource, ('' !== $type ? $type : null), false, $file), $prefix);
                break;
            default:
                throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $node->tagName));
        }
    }

    /**
     * Returns true if this class supports the given resource.
     *
     * @param mixed  $resource A resource
     * @param string $type     The resource type
     *
     * @return Boolean True if this class supports the given resource, false otherwise
     *
     * @api
     */
    public function supports($resource, $type = null)
    {
        return is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'xml' === $type);
    }

    /**
     * Parses a route and adds it to the RouteCollection.
     *
     * @param RouteCollection $collection A RouteCollection instance
     * @param \DOMElement     $definition Route definition
     * @param string          $file       An XML file path
     *
     * @throws \InvalidArgumentException When the definition cannot be parsed
     */
    protected function parseRoute(RouteCollection $collection, \DOMElement $definition, $file)
    {
        $defaults = array();
        $requirements = array();
        $options = array();

        foreach ($definition->childNodes as $node) {
            if (!$node instanceof \DOMElement) {
                continue;
            }

            switch ($node->tagName) {
                case 'default':
                    $defaults[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
                    break;
                case 'option':
                    $options[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
                    break;
                case 'requirement':
                    $requirements[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
                    break;
                default:
                    throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $node->tagName));
            }
        }

        $route = new Route((string) $definition->getAttribute('pattern'), $defaults, $requirements, $options);

        $collection->add((string) $definition->getAttribute('id'), $route);
    }

    /**
     * Loads an XML file.
     *
     * @param string $file An XML file path
     *
     * @return \DOMDocument
     *
     * @throws \InvalidArgumentException When loading of XML file returns error
     */
    protected function loadFile($file)
    {
        $dom = new \DOMDocument();
        libxml_use_internal_errors(true);
        if (!$dom->load($file, defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0)) {
            throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
        }
        $dom->validateOnParse = true;
        $dom->normalizeDocument();
        libxml_use_internal_errors(false);
        $this->validate($dom);

        return $dom;
    }

    /**
     * Validates a loaded XML file.
     *
     * @param \DOMDocument $dom A loaded XML file
     *
     * @throws \InvalidArgumentException When XML doesn't validate its XSD schema
     */
    protected function validate(\DOMDocument $dom)
    {
        $location = __DIR__.'/schema/routing/routing-1.0.xsd';

        $current = libxml_use_internal_errors(true);
        if (!$dom->schemaValidate($location)) {
            throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
        }
        libxml_use_internal_errors($current);
    }

    /**
     * Retrieves libxml errors and clears them.
     *
     * @return array An array of libxml error strings
     */
    private function getXmlErrors()
    {
        $errors = array();
        foreach (libxml_get_errors() as $error) {
            $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
                LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
                $error->code,
                trim($error->message),
                $error->file ? $error->file : 'n/a',
                $error->line,
                $error->column
            );
        }

        libxml_clear_errors();

        return $errors;
    }
}


text:
package org.conqat.engine.scripting;

import org.conqat.engine.core.driver.error.DriverException;
import org.conqat.engine.core.driver.processors.DataSinkProcessor;
import org.conqat.engine.core.logging.testutils.DriverTestBase;

/**
 * Test the DoubleCalculator class.
 *
 * @author Benjamin Hummel
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @levd.rating GREEN Hash: AA8F4C25AD15B919F2368262D879DEC8
 */
public class DoubleCalculatorTest extends DriverTestBase {

	/** Test whether integration works. */
	public void testIntegration() throws DriverException  {

		runDriver("DoubleCalculator.cqb");

		assertTrue(DataSinkProcessor.accessData("dc1").get(0) instanceof Double);
		assertTrue(DataSinkProcessor.accessData("dc2").get(0) instanceof Double);
		assertTrue(DataSinkProcessor.accessData("dc3").get(0) instanceof Double);

		assertEquals(DataSinkProcessor.accessData("dc1").get(0), 42.);
		assertEquals(DataSinkProcessor.accessData("dc2").get(0), 1.);
		assertEquals(DataSinkProcessor.accessData("dc3").get(0), 18.);
	}
}


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>jQuery Tagger</title>
<link rel="stylesheet" media="screen" type="text/css" charset="utf-8" href="bootstrap-1.1.1.css"/>
<link rel="stylesheet" media="screen" type="text/css" charset="utf-8" href="jquery.tagger.css"/>

  <form class="form-stacked" method="post" action="#">

      Enter Tags Here:

        <input type="text" class="tagger" id="tagger1" name="tagger1"/>

  </form>


text:
//-----------------------------------------------------------------------
// <copyright file="CustomerContact.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Security;
using Csla.Core;
using Csla.Serialization;

namespace cslalighttest.CslaDataProvider
{
  [Serializable]
  public class CustomerContact : BusinessBase<CustomerContact>
  {
    private CustomerContact() { }

    private static PropertyInfo<int> IdProperty = RegisterProperty<int>(c=>c.Id, "Contact Id", 0);
    public int Id
    {
      get
      {
        return GetProperty<int>(IdProperty);
      }
      set
      {
        SetProperty<int>(IdProperty, value);
      }
    }

    private static PropertyInfo<int> CustomerIdProperty = RegisterProperty<int>(c=>c.CustomerId, "Customer Id", 0);
    public int CustomerId
    {
      get
      {
        return GetProperty<int>(CustomerIdProperty);
      }
      set
      {
        SetProperty<int>(CustomerIdProperty, value);
      }
    }

    private static PropertyInfo<string>FirstNameProperty = RegisterProperty<string>(c=>c.FirstName, "Contact's First Name", "");
    public string FirstName
    {
      get
      {
        return GetProperty<string>(FirstNameProperty);
      }
      set
      {
        SetProperty<string>(FirstNameProperty, value);
      }
    }

    private static PropertyInfo<string> LastNameProperty = RegisterProperty<string>(c=>c.LastName, "Contact's Last Name", "");
    public string LastName
    {
      get
      {
        return GetProperty<string>(LastNameProperty);
      }
      set
      {
        SetProperty<string>(LastNameProperty, value);
      }
    }

    private static PropertyInfo<SmartDate> BirthdayProperty = RegisterProperty<SmartDate>(c=>c.Birthday, "Contact's Birthday");
    public string Birthday
    {
      get
      {
        return GetProperty<SmartDate>(BirthdayProperty).Text;
      }
      set
      {
        SmartDate test = new SmartDate();
        if (SmartDate.TryParse(value, ref test) == true)
        {
          SetProperty<SmartDate>(BirthdayProperty, test);
        }
      }
    }

    private static PropertyInfo<string> ParentNameProperty = RegisterProperty<string>(c=>c.ParentName, "Parent Name", "");
    public string ParentName
    {
      get
      {
        return GetProperty<string>(ParentNameProperty);
      }
      set
      {
        SetProperty<string>(ParentNameProperty, value);
      }
    }

    protected override void AddBusinessRules()
    {
      BusinessRules.AddRule(new Csla.Rules.CommonRules.MinValue<int>(IdProperty, 1));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FirstNameProperty));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(LastNameProperty));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(FirstNameProperty, 30));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(LastNameProperty, 50));
    }

    internal static CustomerContact GetCustomerContact(int customerId, int id, string firstName, string lastName, DateTime birthday)
    {
      return DataPortal.FetchChild<CustomerContact>(customerId, id, firstName, lastName, birthday);
    }

    protected void Child_DeleteSelf()
    {
#pragma warning disable CS0618 // Type or member is obsolete
      Csla.ApplicationContext.GlobalContext["CustomerContactDelete"] = "Deleted Customer Contact" + GetProperty<string>(FirstNameProperty) + ", " + GetProperty<string>(LastNameProperty);
#pragma warning restore CS0618 // Type or member is obsolete
    }

    protected void Child_Insert()
    {
#pragma warning disable CS0618 // Type or member is obsolete
      Csla.ApplicationContext.GlobalContext["CustomerContactInsert"] = "Inserted Customer Contact" + GetProperty<string>(FirstNameProperty) + ", " + GetProperty<string>(LastNameProperty);
#pragma warning restore CS0618 // Type or member is obsolete
      CustomerContactList parent = this.Parent as CustomerContactList;
      Customer grandParent = parent.MyParent;
      LoadProperty(ParentNameProperty, grandParent.Name);
    }
    protected void Child_Update()
    {
#pragma warning disable CS0618 // Type or member is obsolete
      Csla.ApplicationContext.GlobalContext["CustomerContactUpdate"] = "Updated  Customer Contact" + GetProperty<string>(FirstNameProperty) + ", " + GetProperty<string>(LastNameProperty);
#pragma warning restore CS0618 // Type or member is obsolete
      CustomerContactList parent = this.Parent as CustomerContactList;
      Customer grandParent = parent.MyParent;
      LoadProperty(ParentNameProperty,grandParent.Name);
    }

    private void Child_Fetch(int customerId, int id, string firstName, string lastName, DateTime birthday)
    {
      LoadProperty(CustomerIdProperty, customerId);
      LoadProperty(IdProperty, id);
      LoadProperty(FirstNameProperty, firstName);
      LoadProperty(LastNameProperty, lastName);
      LoadProperty(BirthdayProperty, new SmartDate(birthday));
    }
  }
}


text:
class DeleteEntity

  def initialize id
    @id = id
  end

  def run
    repository.delete(@id)
  end

  private

  def repository
    @repository ||= "#{self.class.name.gsub('Delete', '')}Repository".constantize
  end

end