text:
% Demo: demonstration of the kernel adaptive filter algorithm profiler.
% Compares the cost vs prediction error tradeoffs and convergence speeds
% for several algorithms on the Lorenz data set.

clear all
close all

%% PARAMETERS

output_dir_default = 'profiler_output';

% data and algorithm setup
data.name = 'Lorenz';
data.file = 'lorenz.dat';
data.N = 10000; % number of data points
data.embedding = 6; % time embedding
data.numsim = 5; % 10 minutes per simulation on an Intel Pentium Core2 Duo
data.offset = 50; % apply offset per simulation
data.error_measure = 'MSE';

i=0; % initialize setups

%% ALD-KRLS
i=i+1;
algorithms{i}.name = 'ALD-KRLS';
algorithms{i}.class = 'aldkrls';
algorithms{i}.figstyle = struct('color',[.75  0 .75],'marker','^');
algorithms{i}.options = struct('sweep_par','nu','sweep_val',[1E-4 2E-4 1E-3 .01 .05 .1],...
    'kerneltype','gauss','kernelpar',32);

%% Q-KLMS
i=i+1;
algorithms{i}.name = 'Q-KLMS';
algorithms{i}.class = 'qklms';
algorithms{i}.figstyle = struct('color',[1  0  0],'marker','o');
algorithms{i}.options = struct('eta',0.5,'sweep_par','epsu','sweep_val',[1 2 5 10 12 15 18],...
    'kerneltype','gauss','kernelpar',32);

%% SW-KRLS
i=i+1;
algorithms{i}.name = 'SW-KRLS';
algorithms{i}.class = 'swkrls';
algorithms{i}.figstyle = struct('color',[0  .75 .75],'marker','s');
algorithms{i}.options = struct('c',1E-6,'sweep_par','M','sweep_val',[1 2 3 4 5 10 20 50 100 200],...
    'kerneltype','gauss','kernelpar',32);

%% FB-KRLS
i=i+1;
algorithms{i}.name = 'FB-KRLS';
algorithms{i}.class = 'fbkrls';
algorithms{i}.figstyle = struct('color',[0  .5  0],'marker','d');
algorithms{i}.options = struct('lambda',1E-6,'sweep_par','M','sweep_val',[10 15 20 25 30 50 100],...
    'kerneltype','gauss','kernelpar',32);

%% KRLS-T
i=i+1;
algorithms{i}.name = 'KRLS-T';
algorithms{i}.class = 'krlst';
algorithms{i}.figstyle = struct('color',[0  0  1],'marker','+');
algorithms{i}.options = struct('sn2',1E-6,'lambda',1,'sweep_par','M','sweep_val',[10 15 17 20 24 30 50 100 200],...
    'kerneltype','gauss','kernelpar',32);

%% PROGRAM

fprintf('Running profiler for %d algorithms on %s data.\n',i,data.name);
output_dir = input('Folder for storing results (ENTER = subfolder here): ','s');
if isempty(output_dir),
    output_dir = output_dir_default;
    fprintf('Using default folder "%s" for storing results.\n', output_dir_default);
end

t1 = tic;
[data,algorithms,results] = kafbox_profiler(data,algorithms,output_dir);
t2 = toc(t1);

fprintf('Elapsed time: %d seconds\n',ceil(t2));

%% OUTPUT

mse_curves = kafbox_profiler_msecurves(results);

resinds = [1,1;2,1;3,10;4,7;5,9];
[f0,h0] = kafbox_profiler_plotconvergence(algorithms,mse_curves,resinds);

[f1,h1] = kafbox_profiler_plotresults(algorithms,mse_curves,results,{'bytes','flops'});
object_handle = get(h1);
legend(object_handle.String,'Location','NW'); % move legend

[f2,h2] = kafbox_profiler_plotresults(algorithms,mse_curves,results,{'ssmse','flops'});

[f3,h3] = kafbox_profiler_plotresults(algorithms,mse_curves,results,{'ssmse','bytes'});

[f4,h4] = kafbox_profiler_plotresults(algorithms,mse_curves,results,{'ssmse','ssplus'},1);
object_handle = get(h4);
legend(object_handle.String,'Location','SW'); % move legend

[f5,h5] = kafbox_profiler_plotresults(algorithms,mse_curves,results,{'ssmse','timeto'},-20);
object_handle = get(h5);
legend(object_handle.String,'Location','NW'); % move legend

[f6,h6] = kafbox_profiler_plotresults(algorithms,mse_curves,results,{'ssmse','timetopct'},90);
object_handle = get(h6);
legend(object_handle.String,'Location','SW'); % move legend


text:
package io.scalac.amqp

import scala.collection.immutable.Seq
import scala.concurrent.duration._

import com.typesafe.config.ConfigFactory

import org.scalatest.{FlatSpec, Matchers}

class ConnectionSettingsSpec extends FlatSpec with Matchers {
  "apply" should "be able to load configuration from TypeSafe Config" in {
    val settings = ConnectionSettings(ConfigFactory.load("reference.conf"))
    settings shouldBe ConnectionSettings(
      addresses = Seq(Address(host = "localhost", port = 5672)),
      virtualHost = "/",
      username = "guest",
      password = "guest",
      heartbeat = None,
      timeout = Duration.Inf,
      recoveryInterval = 5.seconds
    )

    def parseAndLoad(s: String) = ConfigFactory.load(ConfigFactory.parseString(s))

    ConnectionSettings(parseAndLoad("amqp.heartbeat = 5 seconds")).heartbeat shouldBe Some(5.seconds)
    ConnectionSettings(parseAndLoad("amqp.timeout = 10 seconds")).timeout shouldBe 10.seconds
  }
}

redpajama_set_name: RedPajamaGithub


text:
class UserObserver < ActiveRecord::Observer
  observe :user

  def before_validation(user)
    user.password = SecureRandom.hex(4) unless user.password || user.persisted?
  end

  def after_create(user)
    if user.has_facebook_authentication?
      Notification.create_notification_once(:temporary_password,
        user,
        {id: user.id},
        password: user.password)
    end
  end

  def before_save(user)
    user.fix_twitter_user
  end
end


text:
[![Stories in Ready](https://badge.waffle.io/yi-jiayu/bus-eta-bot-lambda.png?label=ready&title=Ready)](https://waffle.io/yi-jiayu/bus-eta-bot-lambda)
# bus-eta-bot-lambda


text:
/**
 * a module of admin operations in the system.
 * @module admin
 * */
var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    async = require('async'),
    unirest = require('unirest'),
    tools = require('../static/tools');

/**
 * Find a Admin Query in our DB
 * The Request is parased using the q= string
 * and depending on the request we will use either an
 * aggregation query or a loop through Open Muni Db and return
 * some info back. This function is used for a route to the
 * Correct function and query.
 * @param {Request} req the clients search req.
 * @param {Response} res the response to the client.
 */
exports.find = function(req, res) {
    var search = {};
    var search_str = req.query.q;
    console.log(search_str);
    switch (search_str) {
        case 'missing':
            find_missing(search_str, resposne);
            break;
        case 'unupdated':
            search = [{$match: {'date_updated': {$lte: new Date()}}}];
            aggregate(search, resposne);
            break;
        case 'not_muni':
            search = [{$match: {muni_code: ''}}];

    }
    function resposne(result) {
        var missing_vals =JSON.stringify({request: req.query.q, result: result, count: result.length});
        console.log(missing_vals);

        res.send(missing_vals);

    }
};

/**
 *  Find something missing in our DB
 *  entities which exists in Open Muni
 *  but doesn't exists in our database this function can query
 *  a bunch of operations , all of these operations should be looped
 *  for each entity in the open muni database.
 * @param {String} search the clients search req.
 * @param {Response} res the response to the client.
 */
find_missing = function(search_str, callback) {

    tools.get_collection('entities', function(err, collection, db) {
        unirest.get(tools.OPEN_MUNI).end(function(api) {
            var results = api.body.results;
            var answer = [];

            // loop through all of the results
            tools.loop_api(results, find_entity, send_missing);
            function find_entity(result, callback) {
                var code = result['code'];
                if(code == ' ' || code =='' || code == " " || code ==""){
                    callback();
                    return;
                }
                var search;
                switch (search_str) {
                    case 'missing' : search = {'omuni_id': result.id};
                }

                collection.find(search).toArray(function(err, items) {

                    if (err) { console.log(err); }

                    else if (!items.length) { // did not find this in DB
                        answer.push({code: result.code,
                            id: result.id, name: result.name});
                        callback();
                    }
                    else { // continue the loop
                        callback();
                    }
                });
            }

            // once done the function will end the connection.
            function send_missing(err) { // when we are done.
                callback(answer);
                db.close();

            }
        });
    });
};
/**
 * An aggregation search on our DB
 * @param {Array} agg a aggregation framework array
 * @param {Function} callback  a callback function
 */
aggregate = function(agg, callback) {
    agg.push({$project: {_id: 0, code: '$muni_code',name:'$name', id: '$omuni_id'}});
    tools.get_collection('entities', function(err, collection, mongoclient) {
        collection.aggregate(agg, function(err, result) {
            mongoclient.close();
            callback(result);
        });
    });
};


text:
package jsukonyan;

import java.awt.Graphics;
import javax.swing.JComponent;

/**
 * Esta clase crea los botones del juego a base de imagenes.
 * Las imagenes deben estar contenidas en la carpeta resources y debidamente ancladas a algun enum
 */
public class JMenuItem extends JComponent{
    private boolean onFocus;
    private String onFocusFile;
    private String deFocusFile;
    private int posX;
    private int posY;

    //La carpeta resources debe contener 2 archivos
    //ArchivoOnFocus.png y ArchivoDeFocus.png
    //El enum solo devolverá el nombre del archivo, por lo tanto
    //se le debe agregar el tipo de focus y la extension.
    /**
     * Crea un archivo JMenuItem.
     * @param filePath ruta de la imagen para crear el item de menu
     */
    public JMenuItem(String filePath){
        super();
        this.onFocus = false;
        this.onFocusFile = filePath+"OnFocus.png";
        this.deFocusFile = filePath +"DeFocus.png";
        this.posX = 0;
        this.posY = 0;
    }

    //Este constructor es para usar los JMenuItem como imagenes simples
    /**
     * Crea un archivo JMenuImagen en cierta posicion
     * @param filePath ruta del archivo
     * @param posX posicion en X
     * @param posY posicion en Y
     */
    public JMenuItem(String filePath, int posX, int posY){
        super();
        this.onFocus = false;
        this.onFocusFile = filePath;
        this.deFocusFile = filePath;
        this.posX = posX;
        this.posY = posY;
    }

    /**
     * Cambia el valor de focus a verdadero.
     * El focus se vuelve este boton.
     */
    public void onFocus(){
        this.onFocus = true;
        this.repaint();

    }

    /**
     * Cambia el valor de focus a negativo.
     * Quita el focus del boton
     */
    public void deFocus(){
        this.onFocus = false;
    }

    /**
     * Mueve el boton a la posicion X,Y y lo repinta.
     * @param posX posicion X para mover.
     * @param posY posicion Y para mover.
     */
    public void moveTo(int posX, int posY){
        this.posX = posX;
        this.posY = posY;
    }

    /**
     * Pinta el componente de acuerdo a sus propios estandares.
     * @param g Graphics
     */
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (onFocus){
            //Pintamos cuando el boton es el focus
            g.drawImage(new JImagen(onFocusFile).getImage(), this.posX, this.posY, null);
        }
        else{
            //Pintamos cuando el boton no es el focus
            g.drawImage(new JImagen(deFocusFile).getImage(), this.posX, this.posY, null);
        }
    }
}


text:
package io.opentelemetry.extension.trace.propagation;

import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider;

/**
 * A {@link ConfigurablePropagatorProvider} which allows enabling the {@linkplain
 * B3Propagator#injectingMultiHeaders() B3-multi propagator} with the propagator name {@code
 * b3multi}.
 */
public final class B3MultiConfigurablePropagator implements ConfigurablePropagatorProvider {
  @Override
  public TextMapPropagator getPropagator(ConfigProperties config) {
    return B3Propagator.injectingMultiHeaders();
  }

  @Override
  public String getName() {
    return "b3multi";
  }
}


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

echo.
echo ====================================================================================================
echo Starting H2 database
echo ====================================================================================================
echo.

@if not "%ECHO%" == ""  echo %ECHO%
@if "%OS%" == "Windows_NT" setlocal

if "%OS%" == "Windows_NT" (
  set "DIRNAME=%~dp0%"
) else (
  set DIRNAME=.\
)

set H2_DATABASE_JAR=%JBOSS_HOME%\modules\system\layers\base\com\h2database\h2\main\h2-1.4.190.jar
set H2DB_PID=

rem if JBoss Wildfly does not exist, show an error on the screen.
if NOT defined JBOSS_HOME (
  echo The environment variable JBOSS_HOME can not be found. JBoss Wildfly is not installed or the
  echo environment variable is not set.
  echo.
  echo If not installed, download and install JBoss Wildfly version 10.0.0 from the website:
  echo.
  echo    http://wildfly.org/downloads
  echo.
  exit /b 1
)

for /f "tokens=5" %%a in ('netstat -aon ^|find ":9092 .*LISTENING" ^|find /i " TCP " ') do set H2DB_PID=%%a
if defined H2DB_PID (
   echo.
   echo There is already a process running with PID %H2DB_PID% on tcp port 9092. This is
   echo probably the H2 database. Use the task manager to close this process or use the
   echo usef-stop-enviroment script to stop the USEF environment.
   echo.
   echo Or execute the following command to stop the H2 Database manually:
   echo    javaw -classpath %H2_DATABASE_JAR% org.h2.tools.Server -tcpShutdown "tcp://localhost" -tcpShutdownForce
   echo.
   exit /b 1
)

call java -version > nul 2> nul || set JAVA_ERROR=1
if defined JAVA_ERROR (
  echo Java can not be started. It can not be found on the Windows PATH. It looks like it is not installed.
  echo.
  echo If not installed, download and install Java from the website:
  echo.
  echo    http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html#javasejdk
  echo.
  exit /b 1
)

echo.
echo H2_DATABASE_JAR  = %H2_DATABASE_JAR%
echo.

start java -server -Xmx1024m -Xms256m -classpath %H2_DATABASE_JAR% org.h2.tools.Server -tcp -tcpPort 9092 -tcpAllowOthers -web -webAllowOthers -webPort 8082

echo.
echo ====================================================================================================
echo The USEF database has been started. Use the start-usef-environment script to start the USEF
echo environment.
echo ====================================================================================================


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>dbutils-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
    </dependencies>

</project>


text:
import { Activity24 } from "../../";

export = Activity24;


text:
title: I give up...or did I
layout: post
author: joseph.kerridge
permalink: /i-give-up...or-did-i/
source-id: 1xpM1WNFXCmPmDyROzfYnFbokc1N0fcu7hkx-kZw4afc
published: true
---

    Title
    I give up...or did I
    Date
    13/6/17

    Starting point:
    I started this lesson hating code academy and I ended liking it a bit more...only a bit though.

    Target for this lesson?
    To be calm and relaxed in the lesson, not to get worked about questions and work through everything in a nice organised fashion.

    Did I reach my target?
(add details to "Lesson Review")
    Did I do this; yes. Was it hard; yes. Do I still dislike codecademy; yes. But you can't be good at everything can you, except your if name is Matt Damon or Tom Cruise.

    Lesson Review

    How did I learn? What strategies were effective?

    In this lesson, what I did that I don't think that I did in other lesson was ask my mates for help and help my mates in order to help myself, by doing this I felt that I could learn from helping others as seeing where they went wrong and seeing where I went went wrong meant I could help me and them.

    What limited my learning? Which habits do I need to work on?

    Lack of concentration, I say this because I did what I needed to do but now because I have disliked codecademy for so long I am finding it hard to find motivation to do the work, if codecademy were to explain your mistakes in a better way then I think I would enjoy it more.

    What will I change for next time? How will I improve my learning?

    Mainly my attitude towards codecademy, next week I will really try to understand where I go wrong more and try to take a step back, get the concentration to do my work in a mature way and find the motivation to do my work in a better way.


text:
import React, {PropTypes} from 'react';
import Paper from 'material-ui/Paper';
import {PageTemplate, Header, Footer} from 'components';
import {Grid, Row, Col} from 'react-flexbox-grid';
import RaisedButton from 'material-ui/RaisedButton';
import {SchemaForm, utils} from 'react-schema-form';
import RcSelect from 'react-schema-form-rc-select/lib/RcSelect';
import ReferenceSchema from '../../../schemas/ReferenceSchema';

class FormPage extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      id: null,
      validationResult: {},
      schema: {},
      form: [],
      model: {},
      schemaJson: '',
      formJson: ''
    }
  }

  componentDidMount() {}

  componentWillMount() {

    this.setState({id: this.props.match.params.id});
    this.setState(ReferenceSchema);
  }

  onModelChange = (key, val) => {
    console.log('ExamplePage.onModelChange:', key, val);
    var newModel = this.state.model;
    utils.selectOrSet(key, newModel, val);
    this.setState({model: newModel});
    console.log(this.state.model);
  }

  onValidate = () => {
    console.log('ExamplePage.onValidate is called');
    let result = utils.validateBySchema(this.state.schema, this.state.model);
    this.setState({validationResult: result});
  }

  onFormChange = (val) => {
    try {
      let f = JSON.parse(val);
      this.setState({formJson: val, form: f});
    } catch (e) {}
  }

  onSchemaChange = () => {
    try {
      let s = JSON.parse(val);
      this.setState({schemaJson: val, schema: s});
    } catch (e) {}
  }

  render() {

    var mapper = {
      "rc-select": RcSelect
    };

    return (
      <PageTemplate header={} footer={}>
        <Grid>
          <Row>
            <Paper>
              <Col xs={12}>

Schema:

{JSON.stringify(this.state.schema,undefined,2,2)}

Form:

{JSON.stringify(this.state.form,undefined,2,2)}

                <SchemaForm schema={this.state.schema} form={this.state.form} model={this.state.model} onModelChange={this.onModelChange} mapper={mapper}/>{/* {this.state.model} */}

Model:

{JSON.stringify(this.state.model,undefined,2,2)}

Validation:

                <RaisedButton primary={true} label="Validate" onTouchTap={this.onValidate}/>

{JSON.stringify(this.state.validationResult,undefined,2,2)}

              </Col>
            </Paper>
          </Row>
        </Grid>
      </PageTemplate>
    )
  }
}

export default FormPage;


text:
module Bootstrapped
  module PanelHelper
    def panel(options = {})
      id, klass, style, options = default_options(options)

      options.merge!(class: "panel panel-default #{klass}", style: style, id: id )
      content_tag :div, options do
        yield
      end
    end

    def panel_heading(options = {})
      id, klass, style, options = default_options(options)

      options.merge!(class: "panel-heading #{klass}", style: style, id: id)
      content_tag :div, options do
        content_tag :div, class: "panel-title" do
          yield
        end
      end
    end

    def panel_body(options = {})
      id, klass, style, options = default_options(options)

      options.merge!(class: "panel-body #{klass}", style: style, id: id)
      content_tag :div, options do
        yield
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<clinical_study rank="739">
  <!-- This xml conforms to an XML Schema at:
    http://clinicaltrials.gov/ct2/html/images/info/public.xsd
 and an XML DTD at:
    http://clinicaltrials.gov/ct2/html/images/info/public.dtd -->
  <required_header>
    <download_date>ClinicalTrials.gov processed this data on May 14, 2015</download_date>
    <link_text>Link to the current ClinicalTrials.gov record.</link_text>
    <url>http://clinicaltrials.gov/show/NCT01204203</url>
  </required_header>
  <id_info>
    <org_study_id>F090917002 (UAB 0901)</org_study_id>
    <secondary_id>UAB 0901</secondary_id>
    <nct_id>NCT01204203</nct_id>
  </id_info>
  <brief_title>Pilot Study of Bisphosphonate Therapy (Zoledronic Acid) in Patients With Malignant Mesothelioma (UAB 0901)</brief_title>
  <acronym>UAB 0901</acronym>
  <official_title>A Pilot Phase 2 Study of Bisphosphonate Therapy (Zoledronic Acid) in Patients With Advanced Malignant Mesothelioma</official_title>
  <sponsors>
    <lead_sponsor>
      <agency>University of Alabama at Birmingham</agency>
      <agency_class>Other</agency_class>
    </lead_sponsor>
    <collaborator>
      <agency>Novartis Pharmaceuticals</agency>
      <agency_class>Industry</agency_class>
    </collaborator>
  </sponsors>
  <source>University of Alabama at Birmingham</source>
  <oversight_info>
    <authority>United States: Food and Drug Administration</authority>
    <has_dmc>Yes</has_dmc>
  </oversight_info>
  <brief_summary>
    <textblock>
      The primary objective of this trial is to determine the response rate of single agent
      zoledronic acid using a composite of criteria including the EORTC modified RECIST criteria
      and the EORTC tumor response criteria for 18F-FDG PET scans.
    </textblock>
  </brief_summary>
  <detailed_description>
    <textblock>
      This pilot study will examine the effect of bisphosphonate (zoledronic acid) in patients
      with malignant mesothelioma.  Evaluation will be limited to patients with standard (CT
      scans) and functional instruments (FDG PET Scans) of tumor assessment after the
      administration of standard doses of zoledronic acid (4 mg IV every 3 weeks).  We will also
      explore the biologic effect of zoledronic acid in patients using new serum markers as well
      as several blood level markers.
    </textblock>
  </detailed_description>
  <overall_status>Active, not recruiting</overall_status>
  <start_date>June 2009</start_date>
  <completion_date type="Anticipated">April 2016</completion_date>
  <primary_completion_date type="Actual">April 2015</primary_completion_date>
  <phase>Phase 2</phase>
  <study_type>Interventional</study_type>
  <study_design>Endpoint Classification: Efficacy Study, Intervention Model: Single Group Assignment, Masking: Open Label, Primary Purpose: Treatment</study_design>
  <primary_outcome>
    <measure>Evaluation of the tumor response rate following zoledronic acid</measure>
    <time_frame>CT and/or PET scans will be performed to measure tumor size approximately every 56 days until there is tumor growth</time_frame>
    <safety_issue>Yes</safety_issue>
    <description>The best objective response from either the modified RECIST (CT scan) or the Metabloic Response (PET scan) efficacy method of evaluation will be used to determine the first evaluation after 2 cycles of treatment. In subsequent evaluations for response, modified RECIST with CT scans will be the only instrument to evaluate the response to therapy.</description>
  </primary_outcome>
  <secondary_outcome>
    <measure>Evaluation of the duration of tumor response</measure>
    <time_frame>Assessments approximately every 8 weeks for the patient's life</time_frame>
    <safety_issue>No</safety_issue>
    <description>The patient's medical condition will be followed for the rest of their lives with continued CT scans being performed every 8 weeks to document tumor growth while off of the study medication.</description>
  </secondary_outcome>
  <number_of_arms>1</number_of_arms>
  <enrollment type="Actual">8</enrollment>
  <condition>Mesothelioma</condition>
  <arm_group>
    <arm_group_label>infusion of zoledronic acid</arm_group_label>
    <arm_group_type>Experimental</arm_group_type>
    <description>Zoledronic acid will be administered on Day 1 of a 3-week cycle followed by tumor assessment from CT and/or PET scans every 2 cycles.  This will continue until progression of disease and/or intolerable toxicity.</description>
  </arm_group>
  <intervention>
    <intervention_type>Drug</intervention_type>
    <intervention_name>Zometa (zoledronic acid)</intervention_name>
    <description>Zoledronic acid will be administered IV on the first day of a 21 day cycle at a concentration of 4 mg.  The treatment will take about 30-60 minutes with the infusion lasting about 15 minutes.</description>
    <arm_group_label>infusion of zoledronic acid</arm_group_label>
    <other_name>Zoledronic acid</other_name>
  </intervention>
  <eligibility>
    <criteria>
      <textblock>
        Inclusion Criteria:

          -  Males and females  > 18 years of age

          -  Life expectancy of at least 2 months

          -  Histologically confirmed unresectable malignant pleural mesothelioma (MPM)

          -  Measurable disease by CT Scan criteria and/or positive metabolic activity of 18F-FDG
             PET Scan criteria at screening

          -  ECOG Performance Status of 0-2

          -  Laboratory and clinical results within 2 weeks prior to Day 1 must be as follows:

               1. ANC ≥ 1.5 x 109/L

               2. Platelet Count ≥ 100 x 109/L

               3. Hemoglobin ≥ 9g/dL

               4. Serum bilirubin ≤ 1.5 x upper limit of normal (ULN)

               5. AST ≤ 2.5 x ULN

               6. ALT ≤ 2.5 x ULN

               7. ALK-P ≤ 3 x ULN

               8. Serum creatinine ≤ 1.8mg/dL

               9. Calculated Serum Creatinine Clearance 40 - > 60ml/min

          -  Female subjects of childbearing potential and all male subjects must be surgically
             sterile or consent to use a medically acceptable method of contraception throughout
             the trial.

          -  Willing and able to provide written informed consent.

        Exclusion Criteria:

          -  Known central nervous system (CNS) tumor involvement

          -  Evidence of other active malignancy requiring treatment

          -  Clinically significant heart disease (e.g., congestive heart failure of New York
             Heart Association Class 3 or 4 angina not well controlled by medication, or
             myocardial infarction within 6 months)

          -  Known infection with HIV or hepatitis

          -  Clinically significant arrhythmias demonstrated on electrocardiogram (ECG). Note:
             subjects with chronic atrial arrhythmia, i.e., atrial fibrillation or paroxysmal
             supraventricular tachycardia (SVT) are eligible.

          -  Active, serious systemic disease, including active bacterial or fungal infection.

          -  Subjects undergoing invasive dental procedures, significant periodontal disease or
             history of osteonecrosis of the jaw.

          -  Treatment within 4 weeks of the start of the trial with other systemic anticancer
             therapy.

          -  Breastfeeding, pregnant, or likely to become pregnant during the clinical trial.
      </textblock>
    </criteria>
    <gender>Both</gender>
    <minimum_age>19 Years</minimum_age>
    <maximum_age>N/A</maximum_age>
    <healthy_volunteers>No</healthy_volunteers>
  </eligibility>
  <overall_official>
    <last_name>Francisco Robert, M.D.</last_name>
    <role>Principal Investigator</role>
    <affiliation>University of Alabama at Birmingham</affiliation>
  </overall_official>
  <location>
    <facility>
      <name>University of Alabama at Birmingham</name>
      <address>
        <city>Birmingham</city>
        <state>Alabama</state>
        <zip>35294</zip>
        <country>United States</country>
      </address>
    </facility>
  </location>
  <location_countries>
    <country>United States</country>
  </location_countries>
  <verification_date>April 2015</verification_date>
  <lastchanged_date>May 6, 2015</lastchanged_date>
  <firstreceived_date>September 15, 2010</firstreceived_date>
  <responsible_party>
    <responsible_party_type>Sponsor</responsible_party_type>
  </responsible_party>
  <keyword>mesothelioma</keyword>
  <keyword>zoledronic acid</keyword>
  <keyword>zometa</keyword>
  <keyword>bisphosphonate therapy</keyword>
  <keyword>CT scan</keyword>
  <keyword>PET scan</keyword>
  <is_fda_regulated>Yes</is_fda_regulated>
  <is_section_801>Yes</is_section_801>
  <has_expanded_access>No</has_expanded_access>
  <condition_browse>
    <!-- CAUTION:  The following MeSH terms are assigned with an imperfect algorithm  -->
    <mesh_term>Lung Neoplasms</mesh_term>
    <mesh_term>Mesothelioma</mesh_term>
  </condition_browse>
  <intervention_browse>
    <!-- CAUTION:  The following MeSH terms are assigned with an imperfect algorithm  -->
    <mesh_term>Diphosphonates</mesh_term>
    <mesh_term>Zoledronic acid</mesh_term>
  </intervention_browse>
  <!-- Results have not yet been posted for this study                                -->
</clinical_study>


text:
(function() {
  var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "cypher");
  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }

  MT("unbalancedDoubledQuotedString",
      "[string \"a'b\"][variable c]");

  MT("unbalancedSingleQuotedString",
      "[string 'a\"b'][variable c]");

  MT("doubleQuotedString",
      "[string \"a\"][variable b]");

  MT("singleQuotedString",
      "[string 'a'][variable b]");

  MT("single attribute (with content)",
      "[node {][atom a:][string 'a'][node }]");

  MT("multiple attribute, singleQuotedString (with content)",
      "[node {][atom a:][string 'a'][node ,][atom b:][string 'b'][node }]");

  MT("multiple attribute, doubleQuotedString (with content)",
      "[node {][atom a:][string \"a\"][node ,][atom b:][string \"b\"][node }]");

  MT("single attribute (without content)",
      "[node {][atom a:][string 'a'][node }]");

  MT("multiple attribute, singleQuotedString (without content)",
      "[node {][atom a:][string ''][node ,][atom b:][string ''][node }]");

  MT("multiple attribute, doubleQuotedString (without content)",
      "[node {][atom a:][string \"\"][node ,][atom b:][string \"\"][node }]");
 })();


text:
function Map() {
    var leafletMap = L.map('map').setView([41.505, 25.00], 3);
    var countries = {};
    var currentEndCountries = [];
    var trip = []
    var tripPolyline = null;
    var markerGroup = new L.LayerGroup();

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
        attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
        maxZoom: 18,
        id: 'sophiasanchez.c3eddfe3',
        accessToken: 'pk.eyJ1Ijoic29waGlhc2FuY2hleiIsImEiOiJjaWdrMjB5NzgwMDlidWpsenRjbzBqb3p2In0.46Rk8ZSkTEtq0cK3nAJmfQ'
    }).addTo(leafletMap);

    var countryExists = function(countryName) {
      return countries.hasOwnProperty(countryName);
    };

    var forEachCountry = function(countryNames, callback) {
      for (var i = 0; i < countryNames.length; i++) {
        if (countryExists(countryNames[i])) {
          var country = countries[countryNames[i]];
          callback(country);
        }
      }
    };

    var updateTripLineMarkersAndItinerary = function() {
      drawTripLine();
      removeTripMarkers();
      addTripMarkers();
      updateItinerary();
    }

    var drawTripLine = function() {
      if (this.tripPolyline != null) {
        leafletMap.removeLayer(this.tripPolyline);
      }
      pointList = [];
      for (var i = 0; i < trip.length; i++) {
        pointList.push(countries[trip[i].country].getPolygonCenter());
      }
      this.tripPolyline = L.polyline(pointList)
      this.tripPolyline.addTo(leafletMap);
    }

    var removeTripMarkers = function() {
      leafletMap.removeLayer(markerGroup);
      markerGroup.clearLayers();
    }

    var addTripMarkers = function() {
      if (trip.length > 0) {
        firstCountry = countries[trip[0].country];
        lastCountry = countries[trip[trip.length-1].country];
        markerGroup.addLayer(firstCountry.getMarker());
        markerGroup.addLayer(lastCountry.getMarker());
        leafletMap.addLayer(markerGroup);
      }
    }

    var updateItinerary = function() {
      var list = document.getElementById('itineraryList');
      $("ul").empty(); // probably would be better to just add and subtract specific items
      var totalCost = 0;
      if (trip.length > 0) {
        for (var i = 0; i < trip.length - 1; i++) {
          if (trip[i].cost != null) {
            totalCost += trip[i].cost;
          }

          // Adds the main part of the trip entry
          fromCountryToCountry = trip[i].city + ", " + trip[i].country + " to " + trip[i+1].city + ", " + trip[i+1].country;
          mode = trip[i+1].mode
          mostRecentPrice = "Price (" + trip[i+1].year + "): " +"$" + trip[i+1].cost;
          entry = createItineraryEntryHTML(fromCountryToCountry, mode, mostRecentPrice);
          list.appendChild(entry);

          // Adds the (hidden) older prices
          allYears = Object.keys(trip[i+1].previousYears).sort(function(a, b){return b-a});
          olderPricesEntry = createOlderPricesEntryHTML(allYears, i);
          entry.appendChild(olderPricesEntry);

        }

        // Adds total cost to the bottom of the list
        totalCost += trip[trip.length - 1].cost; // gets the last cost; might wanna change
        var totalCostP = document.createElement('p');
        totalCostP.appendChild(document.createTextNode("Total cost: $" + totalCost));
        list.appendChild(totalCostP);
        setPricesAsHiddenOrShown();
      }
    }

    var createItineraryEntryHTML = function(fromCountryToCountry, mode, mostRecentPrice) {
      var entry = document.createElement('div');
      entry.setAttribute("id", "tripEntry");
      var header = document.createElement('h3');
      header.appendChild(document.createTextNode(fromCountryToCountry));
      entry.appendChild(header);
      entry.appendChild(document.createElement('br'));
      entry.appendChild(document.createTextNode("Mode: " + mode));
      entry.appendChild(document.createElement('br'));
      entry.appendChild(document.createTextNode(mostRecentPrice));
      entry.appendChild(document.createElement('br'));

      return entry;
    }

    var createOlderPricesEntryHTML = function(allYears, i) {
      var unorderedList = document.createElement('ul');
      unorderedList.setAttribute("class", "olderPrices");
      for (var j = 0; j < allYears.length; j++) {
        currYear = allYears[j];
        currPrice = trip[i+1].previousYears[currYear];
        if (currYear != trip[i+1].year) {
          var olderPrice = document.createElement('li')
          olderPrice.appendChild(document.createTextNode(currYear + ": $" + currPrice));
          unorderedList.appendChild(olderPrice);
        }
      }
      if (allYears.length == 0) {
        unorderedList.appendChild(document.createTextNode("No older prices available."))
      }
      return unorderedList;
    }

    function setPricesAsHiddenOrShown() {
      if ($('#showOlderPrices').is(':checked')) {
        $(".olderPrices").show();
      }
      else {
       $(".olderPrices").hide();
      }
    }

    var selectStartCountry = function(startCountry) {
      if (!startCountry) { return; }

      // You can't click on a country that's not red or green, if it's not the very first selection in the trip
      if (trip.length > 0 && startCountry.state === 'grey') {
        return;
      }

      // If you're going backward (deselecting), update the map accordingly
      else if (startCountry.state === 'red') {
        startCountry = backtrackOneStepAndUpdateStartCountry(startCountry);
      }

      // If you're selecting the very first country, find all possible end countries, and update map
      else if (trip.length === 0) {
        startCountry.highlightRed();
        ajaxGetCitiesInACountry(startCountry.name);
      }

      // If you're going forward in the trip, select the city and mode of transport
      else if (startCountry.state === 'green') {
        forEachCountry(currentEndCountries, function(country) { country.removeHighlight() });
        startCountry.highlightRed();
        startCities = Object.keys(startCountry.tripDetails);
        selectCityPopUp(startCities, startCountry, false);
      }
    };

    var backtrackOneStepAndUpdateStartCountry = function(startCountry) {
        startCountry.removeHighlight();
        trip.pop();
        updateTripLineMarkersAndItinerary();
        forEachCountry(currentEndCountries, function(country) { country.removeHighlight() });
        if (trip.length > 0) {
          previousCountry = trip[trip.length - 1].country;
          startCountry = countries[previousCountry];
          startCountry.highlightRed();
          ajaxQueryByStartCity(trip[trip.length - 1].city, trip[trip.length - 1].country);
        }
        else {
          startCountry = null;
        }

        return startCountry;
    }

    var getCityButtons = function(startCities) {
      cityButtons = "";
      for (var i = 0; i < startCities.length; i++) {
        button = '<input class=\"visibleInput\" type=\"radio\" name=\"city\" value=\"' + cities[i] + '\">' + " " + cities[i] + '
'
        cityButtons = cityButtons + button;
      }

      return cityButtons;
    }

    var getTransportationInfo = function(startCountry, selectedCity) {
      transportation = Object.keys(startCountry.tripDetails[selectedCity]);
      fullTripInfo = {};
      fullTripInfoButtons = "";
        for (var i = 0; i < transportation.length; i++) {
          years = Object.keys(startCountry.tripDetails[selectedCity][transportation[i]]);
          mostRecentYear = Math.max.apply(Math, years);
          cost = startCountry.tripDetails[selectedCity][transportation[i]][mostRecentYear];
          button = '<input class=\"visibleInput\" type=\"radio\" name=\"mode\" value=\"' + transportation[i] + '\">' + " " + transportation[i] + ": $" + cost + " (" + mostRecentYear + ")" + '
'
          fullTripInfo[transportation[i]] = {cost: cost, year: mostRecentYear, previousYears: {}};
          for (var j = 0; j < years.length; j++) {
              if (years[j] != mostRecentYear) {
                costForThatYear = startCountry.tripDetails[selectedCity][transportation[i]][years[j]];
                fullTripInfo[transportation[i]].previousYears[years[j]] = costForThatYear;
              }
          }
          fullTripInfoButtons = fullTripInfoButtons + button
        }

        return {'buttons': fullTripInfoButtons,
                'fullTripInfo': fullTripInfo};
      }

    var noDataAvailablePopUp = function(startCountry) {
      swal({
        title: "Oops!",
        text: "Looks like there are no data entries available for " + startCountry.name + ". Please select a different country. If you have already started your journey, you can backtrack by clicking on the country again.",
      },
      function(isConfirm) {
        cancelPopUp;
      })
    }

    var selectCityPopUp = function(startCities, startCountry, departureBool) {
      buttons = getCityButtons(startCities);
      swal({
        title: "Select City",
        text: "Please select a city in " + startCountry.name + ":

" + buttons,
        html: true,
        showCancelButton: true,
        closeOnCancel: true,
        closeOnConfirm: departureBool, // close if it's the first departure city, otherwise don't so that the transportation pop up shows up
        },
        function(isConfirm) {
          if (isConfirm) {
            selectedCity = $('input[name="city"]:checked').val();
            // if user is selecting the very first departure city, push that city to the trip and display the new end countries
            if (departureBool){
              startCountry.highlightRed();
              trip.push({country: startCountry.name, city: selectedCity, cost: null});
              ajaxQueryByStartCity(selectedCity, startCountry.name)
            }
            else {
              selectTransportationPopUp(startCountry, getTransportationInfo(startCountry, selectedCity), selectedCity);
            }
          }
          else {
            cancelPopUp(startCountry);
          }
        });
    }

    var selectTransportationPopUp = function(startCountry, tripInfo, selectedCity) {
      fullTripInfo = tripInfo.fullTripInfo;
      fullTripInfoButtons = tripInfo.buttons;
      swal({
        title: "Select Mode of Transportation",
        text: "Please select a mode of transportation to " + selectedCity + ", " + startCountry.name + ":

" + fullTripInfoButtons,
        html: true,
        showCancelButton: true,
        closeOnCancel: true,
        },
        function(isConfirm) {
          if (isConfirm) {
            previousCountry = trip[trip.length - 1].country;
            countries[previousCountry].removeHighlight();
            mode = $('input[name="mode"]:checked').val();
            trip.push({country: startCountry.name, city: selectedCity, cost: fullTripInfo[mode]["cost"], mode: mode, year: fullTripInfo[mode]["year"], previousYears: fullTripInfo[mode].previousYears});
            updateTripLineMarkersAndItinerary();
            ajaxQueryByStartCity(selectedCity, startCountry.name);
          }
          else {
            cancelPopUp(startCountry);
          }
        });
    }

    var cancelPopUp = function(startCountry) {
      startCountry.removeHighlight();
      forEachCountry(currentEndCountries, function(country) { country.removeHighlight() });
      if (trip.length > 0) {
        previousCountry = trip[trip.length - 1].country;
        countries[previousCountry].highlightRed();
        ajaxQueryByStartCity(trip[trip.length-1].city, trip[trip.length-1].country);
      }
    }

    var ajaxQueryByStartCity= function(city, country) {
      countryNoSpace = country;
      if (country.indexOf(" ") > -1) {
        countryNoSpace = country.replace(/ /g, "-");
      }
      if (city.indexOf(" ") > -1) {
        city = city.replace(/ /g, "-");
      }
      $.ajax({
        type: 'GET',
        url: '/map/queryByStartCity/' + countryNoSpace + "/" + city,
        success: function(reply) {
          endCountries = JSON.parse(reply);
          currentEndCountries = Object.keys(endCountries);
          if (currentEndCountries.length === 0) {
            noDataAvailablePopUp(countries[country]);
          }
          else {
            forEachCountry(currentEndCountries, function(country) { country.highlightGreen(); country.setTripDetails(endCountries[country.name])});
          }
        }
      });
    }

    var ajaxGetCitiesInACountry = function(ajaxCallName) {
      var ajaxCallNameNoSpace = ajaxCallName;
      if (ajaxCallName.indexOf(" ") > -1) {
        ajaxCallNameNoSpace = ajaxCallName.replace(/ /g, "-");
      }

      $.ajax({
        type: 'GET',
        url: '/map/getCitiesInACountry/' + ajaxCallNameNoSpace,
        success: function(reply) {
          citiesJSON = JSON.parse(reply);
          cities = citiesJSON[ajaxCallName]
          if (cities.length === 0) {
            noDataAvailablePopUp(countries[ajaxCallName]);
            backtrackOneStepAndUpdateStartCountry(countries[ajaxCallName]); // only want to do this because ajaxGetCitiesInACountry only called for very first country click
          }
          else {
            selectCityPopUp(cities, countries[ajaxCallName], true);
          }
        }
      });
    }

    var countryFromName = function(countryName) {
      if (!countryExists(countryName)) {
        return null;
      }
      return countries[countryName];
    };

    var countryFromEvent = function(e) {
      var countryName = e.target.feature.properties.name;
      return countryFromName(countryName);
    };

    var onCountryHighLight = function(e) {
      var country = countryFromEvent(e);

      if (!country) { return; }

      if (country.state === 'green') {
        country.addPricePopUp();
      }

      if (country.state === null) {
        country.highlightGrey();
        if (!L.Browser.ie && !L.Browser.opera) {
          e.target.bringToFront();
        }
      }
    };

    var onCountryMouseOut = function(e) {
      var country = countryFromEvent(e);

      if (!country) { return; }

      if (country.state === 'green') {
        country.closePricePopUp();
      }

      if (country.state === 'grey') {
        country.removeHighlight();
      }
    };

    var onCountryClick = function(e) {
      var country = countryFromEvent(e);
      selectStartCountry(country);
    };

    var cacheCountries = function() {
      d3.json(COUNTRIES_DATA_JSON_URL, function (json) {
        data = json.features;
        for (var i = 0; i < data.length; i++) {
          var countryName = data[i].properties.name;
          var polygonType = data[i].geometry.type;
          // takes care of countries with several islands, like Italy
          var countryCoordinates = []
          if (data[i].geometry.type === "MultiPolygon") {
            for (var j = 0; j < data[i].geometry.coordinates.length; j++) {
              countryCoordinates.push(data[i].geometry.coordinates[j]);
            }
          }
          else {
            countryCoordinates = data[i].geometry.coordinates[0];
          }
          var country = new Country(leafletMap, countryName, countryCoordinates, polygonType);
          countries[countryName] = country;
        }

        L.geoJson(json, {
          style:  {
            fillColor: "#E3E3E3",
            weight: 1,
            opacity: 0.4,
            color: 'white',
            fillOpacity: 0.3
          },
          onEachFeature: function(feature, layer) {
            countries[feature.properties.name].reversePolygon();
            layer.on({
              mouseover : onCountryHighLight,
              mouseout : onCountryMouseOut,
              click: onCountryClick
            });
          },
          onCountryMouseOut: onCountryMouseOut,
          onCountryClick: onCountryClick,
        }).addTo(leafletMap);
      });
    };
    cacheCountries();

    var resetMapVars = function() {
      currentEndCountries = [];
      trip = []
      tripPolyline = null;
    }

    var clearMap = function() {
      if (trip.length === 0) {
        return;
      }
      else {
        countryName = trip[trip.length-1].country;
        countries[countryName].removeHighlight();
        forEachCountry(currentEndCountries, function(country) { country.removeHighlight() });
        if (this.tripPolyline != null) {
          leafletMap.removeLayer(this.tripPolyline);
        }
        $("ul").empty();
      }
    }

    this.getTrip = function() {
      return trip;
    }

    this.clear = function() {
      removeTripMarkers();
      clearMap();
      resetMapVars();
    }
  };


text:
class: center, middle
# Composer

---
name: agenda
### Composer

Introduction

Installation

Autoload

---
#Introduction

---
### composer

Inspiration

--

* bundler.rb

--

* npm.js

---
### composer

communauté

--

symfony 2
--
zend 2
--
laravel 4
--
yii 2
--
Aura
--
CodeIgniter
--
CakePHP
--
slim
--
Sculpin
--
Typo3
--
Magento
--
Joomla

--

drupal 8
--
wordpress 4

---
## Composer

### Drupal 7

Composer dans un module custom

--
```php
module_load_include('php','tp1_project','vendor/autoload');
```

---
## Composer
### Wordpress

WPackagist

---
## Composer

* [Powerful component based mailing library for PHP – Swift Mailer](http://swiftmailer.org/)

--

* [Pimple - A simple PHP Dependency Injection Container](http://pimple.sensiolabs.org/)

--

* [sebastianbergmann/phpunit](https://github.com/sebastianbergmann/phpunit)

---

* [phpspec/phpspec](https://github.com/phpspec/phpspec)

--

* [fabpot/Sami](https://github.com/fabpot/Sami)

--

* [briannesbitt/Carbon](https://github.com/briannesbitt/Carbon)

--

* [igorw/compose](https://github.com/igorw/compose)

--

* [polyfractal/athletic](https://github.com/polyfractal/athletic)

--

* [nikic/iter](https://github.com/nikic/iter)

---

* [ziadoz/awesome-php](https://github.com/ziadoz/awesome-php)

---
template: agenda

---
#Installation

---
## Installation

```console
$ curl -sS https://getcomposer.org/installer | php
```

---
##Installation

composer.json

--
```console
$ php composer.phar init
```

---
## Installation
composer.json
```json
{
    "name": "denislaliberte/mypackage",
    "description": "Description of my package",
    "license": "MIT",
    "minimum-stability": "dev",
    "require": {}
}
```

---
##Installation

packagist.org

![](packagist.png)

---
##Installation
require

--

```json
"require": {
    "vendor/package": "1.*"
}
```

---
## Installation

semver.org

--

MAJOR.MINOR.PATCH

--

MAJOR version != backwards-compatible

```json
    "vendor/package": "1.2.*"
```

---
## Installation

composer.lock

```console
$ composer intall
# vs
$ composer update
```

---
template: agenda

---
#Autoload

---
## Autoload
Namespace

--

```console
Fatal error: Cannot redeclare test() (previously declared...
```

---
## Autoload
Namespace

--

```php
//Avant php 5.3
my_package_function_test();
```
--
```php
//Après php 5.3
MyPackage\function\test();
```

---
## Autoload
Namespace

```php
use MyPackage\function as f;

f\test();
```

---
## Autoload
Namespace

```php
use MyPackage\function\MyClass;

$class = new MyClass()
```

---
## Autoload

```php
//sans autoload
require 'vendor/MyPackage/function/MyClass.php';
use MyPackage\function\MyClass;
```

--

```php
//avec autoload
require 'vendor/autoload.php';

use MyPackage\function\MyClass;

```

---
## Autoload

www.php-fig.org

--

psr-4

```regexp
\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>
```

---
#Composer


text:
struct ArduinoMessage
{
  unsigned long  time_stamp;
	bool e_stop;
	float l_motor_rpm;
	float r_motor_rpm;
	float l_pid;
	float r_pid;
	float l_feedback;
	float r_feedback;
};
#endif


text:
===============================
event_store_meta
===============================

Event Store Meta Catalog

Quickstart
----------

First, set your app's secret key as an environment variable. For example, example add the following to ``.bashrc`` or ``.bash_profile``.

.. code-block:: bash

    export EVENT_STORE_META_SECRET = 'something-really-secret'

Then run the following commands to bootstrap your environment.

::

    git clone https://github.com/cwilkes/event_store_meta
    cd event_store_meta
    pip install -r requirements/dev.txt
    python manage.py db init
    python manage.py db migrate
    python manage.py db upgrade
    python manage.py server

Deployment
----------

In your production environment, make sure the ``EVENT_STORE_META_ENV`` environment variable is set to ``"prod"``.

Shell
-----

To open the interactive shell, run ::

    python manage.py shell

By default, you will have access to ``app``, ``db``, and the ``User`` model.

Running Tests
-------------

To run all tests, run ::

    python manage.py test

Migrations
----------

Whenever a database migration needs to be made. Run the following commmands:
::

    python manage.py db migrate

This will generate a new migration script. Then run:
::

    python manage.py db upgrade

To apply the migration.

For a full migration command reference, run ``python manage.py db --help``.


text:
package com.planet_ink.coffee_mud.Abilities.Fighter;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class Fighter_Sweep extends FighterSkill
{
	@Override public String ID() { return "Fighter_Sweep"; }
	private final static String localizedName = CMLib.lang().L("Sweep");
	@Override public String name() { return localizedName; }
	private static final String[] triggerStrings =I(new String[] {"SWEEP"});
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override protected int canAffectCode(){return Ability.CAN_MOBS;}
	@Override protected int canTargetCode(){return 0;}
	@Override public int classificationCode(){return Ability.ACODE_SKILL|Ability.DOMAIN_DIRTYFIGHTING;}
	@Override public int usageType(){return USAGE_MOVEMENT;}

	@Override
	public void affectPhyStats(Physical affected, PhyStats affectableStats)
	{

		final float f=(float)CMath.mul(0.1,(float)getXLEVELLevel(invoker()));
		affectableStats.setAttackAdjustment((int)Math.round(CMath.div(affectableStats.attackAdjustment(),2.0-f)));
		affectableStats.setDamage((int)Math.round(CMath.div(affectableStats.damage(),3.0-f)));
	}
	@Override
	public int castingQuality(MOB mob, Physical target)
	{
		if((mob!=null)&&(target!=null))
		{
			final Set<MOB> h=properTargets(mob,target,false);
			if(h.size()<2)
				return Ability.QUALITY_INDIFFERENT;
			for(final MOB M : h)
				if((M.rangeToTarget()<0)||(M.rangeToTarget()>0))
					h.remove(M);
			if(h.size()<2)
				return Ability.QUALITY_INDIFFERENT;
		}
		return super.castingQuality(mob,target);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(mob.isInCombat()&&(mob.rangeToTarget()>0))
		{
			mob.tell(L("You are too far away to sweep!"));
			return false;
		}
		if(!mob.isInCombat())
		{
			mob.tell(L("You must be in combat to sweep!"));
			return false;
		}
		final Set<MOB> h=properTargets(mob,givenTarget,false);
		for(final MOB M : h)
			if((M.rangeToTarget()<0)||(M.rangeToTarget()>0))
				h.remove(M);

		if(h.size()==0)
		{
			mob.tell(L("There aren't enough enough targets in range!"));
			return false;
		}

		final Item w=mob.fetchWieldedItem();
		if((w==null)||(!(w instanceof Weapon)))
		{
			mob.tell(L("You need a weapon to sweep!"));
			return false;
		}
		final Weapon wp=(Weapon)w;
		if(wp.weaponType()!=Weapon.TYPE_SLASHING)
		{
			mob.tell(L("You cannot sweep with @x1!",wp.name()));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		// now see if it worked
		final boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MSG_NOISYMOVEMENT,L("^F^<FIGHT^><S-NAME> sweep(s)!^</FIGHT^>^?"));
			CMLib.color().fixSourceFightColor(msg);
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				invoker=mob;
				mob.addEffect(this);
				mob.recoverPhyStats();
				for (final Object element : h)
				{
					final MOB target=(MOB)element;
					msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_OK_ACTION|(auto?CMMsg.MASK_ALWAYS:0),null);
					if(mob.location().okMessage(mob,msg))
					{
						mob.location().send(mob,msg);
						CMLib.combat().postAttack(mob,target,w);
					}
				}
				mob.delEffect(this);
				mob.recoverPhyStats();
			}
		}
		else
			return maliciousFizzle(mob,null,L("<S-NAME> fail(s) to sweep."));

		// return whether it worked
		return success;
	}
}


text:
package dulleh.akhyou.Search.Holder.Item;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import de.greenrobot.event.EventBus;
import dulleh.akhyou.MainActivity;
import dulleh.akhyou.MainApplication;
import dulleh.akhyou.Models.Anime;
import dulleh.akhyou.R;
import dulleh.akhyou.Search.Holder.SearchHolderFragment;
import dulleh.akhyou.Utils.AdapterClickListener;
import dulleh.akhyou.Utils.Events.OpenAnimeEvent;
import dulleh.akhyou.Utils.Events.SearchEvent;
import nucleus.factory.RequiresPresenter;
import nucleus.view.NucleusSupportFragment;

@RequiresPresenter(SearchPresenter.class)
public class SearchFragment extends NucleusSupportFragment<SearchPresenter> implements AdapterClickListener<Anime> {
    private SwipeRefreshLayout refreshLayout;
    private SearchAdapter searchAdapter;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        // must be after ^ so that getPresenter() doesn't return null
        getPresenter().setProviderType(getArguments().getInt(SearchHolderFragment.PROVIDER_TYPE_KEY, Anime.ANIME_RUSH));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        searchAdapter = new SearchAdapter(this);
        View view = inflater.inflate(R.layout.search_fragment, container, false);

        RecyclerView searchResultsView = (RecyclerView) view.findViewById(R.id.recycler_view);
        searchResultsView.setLayoutManager(new LinearLayoutManager(container.getContext(), LinearLayoutManager.VERTICAL, false));
        searchResultsView.setAdapter(searchAdapter);
        searchResultsView.setItemAnimator(new DefaultItemAnimator());

        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.accent);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPresenter().search();
            }
        });

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MainApplication.getRefWatcher(getActivity()).watch(this);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        MenuItem searchItem = menu.findItem(R.id.search_item);

        if (searchItem == null) {
            inflater.inflate(R.menu.search_menu, menu);
            searchItem = menu.findItem(R.id.search_item);
        }

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        searchView.setQueryHint(getString(R.string.search_item));
        searchView.setIconifiedByDefault(false);
        searchView.setIconified(false);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                if (!query.isEmpty()) {
                    getPresenter().onEvent(new SearchEvent(query));
                    searchView.clearFocus();
                    refreshLayout.requestFocus();
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        searchView.clearFocus();
        refreshLayout.requestFocus();
    }

    public void updateSearchResults () {
        searchAdapter.notifyDataSetChanged();
        updateRefreshing();
    }

    public void updateRefreshing () {
        if (!isRefreshing() && getPresenter().isRefreshing) {
            TypedValue typedValue = new TypedValue();
            getActivity().getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, typedValue, true);
            refreshLayout.setProgressViewOffset(false, 0, getResources().getDimensionPixelSize(typedValue.resourceId));
            refreshLayout.setRefreshing(true);
        } else {
            refreshLayout.setRefreshing(false);
        }
    }

    public boolean isRefreshing () {
        return refreshLayout.isRefreshing();
    }

    @Override
    public void onCLick(Anime anime, @Nullable Integer position) {
        ((MainActivity) getActivity()).requestFragment(MainActivity.ANIME_FRAGMENT);
        EventBus.getDefault().postSticky(new OpenAnimeEvent(anime));
    }

    @Override
    public void onLongClick(Anime item, @Nullable Integer position) {

    }

}


text: Launching<%= appName %> InstanceName <%= instanceName %>


text:
package io.github.gitbucket.markedj;

import io.github.gitbucket.markedj.rule.Rule;
import io.github.gitbucket.markedj.token.*;

import java.util.Map;
import java.util.Stack;

public class Parser {

    protected Options options;
    protected Renderer renderer;

    public Parser(Options options, Renderer renderer){
        this.options = options;
        this.renderer = renderer;
    }

    public String parse(Stack<Token> src, Map<String, Lexer.Link> links){
        Map<String, Rule> rules;
        if(options.isGfm()){
            if(options.isBreaks()){
                rules = Grammer.INLINE_BREAKS_RULES;
            } else {
                rules = Grammer.INLINE_GFM_RULES;
            }
        } else {
            rules = Grammer.INLINE_RULES;
        }

        ParserContext context = new ParserContext(src, links, rules);
        StringBuilder out = new StringBuilder();

        while(context.nextToken() != null){
            out.append(tok(context));
        }

        return out.toString();
    }

    protected String parseText(ParserContext context){
        StringBuilder body = new StringBuilder(((TextToken) context.currentToken()).getText());
        while(true){
            Token p = context.peekToken();
            if(p == null || !p.getType().equals("TextToken")){
                break;
            }
            body.append("\n" + ((TextToken) context.nextToken()).getText());
        }
        return context.getInlineLexer().output(body.toString());
    }

    protected String tok(ParserContext context){
        switch(context.currentToken().getType()){
            case "SpaceToken": {
                return "";
            }
            case "HrToken": {
                return renderer.hr();
            }
            case "HeadingToken": {
                HeadingToken t = (HeadingToken) context.currentToken();
                return renderer.heading(context.getInlineLexer().output(t.getText()), t.getDepth(), t.getText());
            }
            case "CodeToken": {
                CodeToken t = (CodeToken) context.currentToken();
                return renderer.code(t.getCode(), t.getLang(), t.isEscaped());
            }
            case "TableToken": {
                TableToken t = (TableToken) context.currentToken();
                StringBuilder outCell   = new StringBuilder();
                StringBuilder outHeader = new StringBuilder();
                StringBuilder outBody   = new StringBuilder();

                for(int i = 0; i < t.getHeader().size(); i++){
                    outCell.append(renderer.tablecell(
                            context.getInlineLexer().output(t.getHeader().get(i)), new Renderer.TableCellFlags(true, t.getAlign().get(i))));
                }
                outHeader.append(renderer.tablerow(outCell.toString()));

                for(int i = 0; i < t.getCells().size(); i++){
                    outCell.setLength(0);
                    for(int j = 0; j < t.getCells().get(i).size(); j++){
                        outCell.append(renderer.tablecell(
                                context.getInlineLexer().output(t.getCells().get(i).get(j)), new Renderer.TableCellFlags(false, t.getAlign().get(j))));
                    }
                    outBody.append(renderer.tablerow(outCell.toString()));
                }
                return renderer.table(outHeader.toString(), outBody.toString());
            }
            case "BlockquoteStartToken": {
                StringBuilder body = new StringBuilder();
                while(true){
                    Token n = context.nextToken();
                    if(n == null || n.getType().equals("BlockquoteEndToken")){
                        break;
                    }
                    body.append(tok(context));
                }
                return renderer.blockquote(body.toString());
            }
            case "ListStartToken": {
                ListStartToken t = (ListStartToken) context.currentToken();
                StringBuilder out = new StringBuilder();
                while(true){
                    Token n = context.nextToken();
                    if(n == null || n.getType().equals("ListEndToken")){
                        break;
                    }
                    out.append(tok(context));
                }
                return renderer.list(out.toString(), t.isOrderd());
            }
            case "ListItemStartToken": {
                StringBuilder out = new StringBuilder();
                while(true){
                    Token n = context.nextToken();
                    if(n == null || n.getType().equals("ListItemEndToken")){
                        break;
                    }
                    if(context.currentToken().getType().equals("TextToken")){
                        out.append(parseText(context));
                    } else {
                        out.append(tok(context));
                    }
                }
                return renderer.listitem(out.toString());
            }
            case "LooseItemStartToken": {
                StringBuilder out = new StringBuilder();
                while(true){
                    Token n = context.nextToken();
                    if(n == null || n.getType().equals("ListItemEndToken")){
                        break;
                    }
                    out.append(tok(context));
                }
                return renderer.listitem(out.toString());
            }
            case "HtmlToken": {
                HtmlToken t = (HtmlToken) context.currentToken();
                return renderer.html(context.getInlineLexer().output(t.getText()));
            }
            case "ParagraphToken": {
                ParagraphToken t = (ParagraphToken) context.currentToken();
                return renderer.paragraph(context.getInlineLexer().output(t.getText()));
            }
            case "TextToken": {
                return renderer.paragraph(parseText(context));
            }
            default: {
                throw new RuntimeException("Unexpected token: " + context.currentToken());
            }
        }
    }

    public class ParserContext {

        private Stack<Token> tokens = new Stack<>();
        private Token token = null;
        private InlineLexer inline;

        public ParserContext(Stack<Token> src, Map<String, Lexer.Link> links, Map<String, Rule> rules){
            // reverse
            tokens = new Stack<>();
            while(!src.isEmpty()){
                tokens.push(src.pop());
            }

            inline = new InlineLexer(rules, links, options, renderer);
        }

        public Token currentToken(){
            return token;
        }

        public Token nextToken(){
            if(tokens.isEmpty()){
                return null;
            } else {
                token = tokens.pop();
                return token;
            }
        }

        public Token peekToken(){
            if(tokens.isEmpty()){
                return null;
            } else {
                return tokens.get(tokens.size() - 1);
            }
        }

        public InlineLexer getInlineLexer(){
            return inline;
        }
    }
}


text:
package com.robrua.orianna.type.dto.currentgame;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.robrua.orianna.type.dto.OriannaDto;

@Entity
@Table(name = "currentgameobserver")
public class Observer extends OriannaDto {
    private static final long serialVersionUID = 1212236867210702931L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long dbId;

    private String encryptionKey;

    /*
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object obj) {
        if(this == obj) {
            return true;
        }
        if(obj == null) {
            return false;
        }
        if(!(obj instanceof Observer)) {
            return false;
        }
        final Observer other = (Observer)obj;
        if(encryptionKey == null) {
            if(other.encryptionKey != null) {
                return false;
            }
        }
        else if(!encryptionKey.equals(other.encryptionKey)) {
            return false;
        }
        return true;
    }

    @Override
    public String getDataStoreIndexField(final Class<?> keyType) {
        if(keyType.equals(Long.class)) {
            return "dbId";
        }
        return null;
    }

    /**
     * @return the encryptionKey
     */
    public String getEncryptionKey() {
        return encryptionKey;
    }

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

    /**
     * @param encryptionKey
     *            the encryptionKey to set
     */
    public void setEncryptionKey(final String encryptionKey) {
        this.encryptionKey = encryptionKey;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Observer [encryptionKey=" + encryptionKey + "]";
    }
}


text:
using System;
using System.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace LolHandbook.Converters
{
    public class VisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return IsVisible(value) ? Visibility.Visible : Visibility.Collapsed;
        }

        private static bool IsVisible(object value)
        {
            if (value == null)
            {
                return false;
            }

            if (value is bool)
            {
                return (bool)value;
            }

            ICollection collection = value as ICollection;
            if (collection != null && collection.Count == 0)
            {
                return false;
            }

            return true;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}


text:
package com.haulmont.cuba.web.gui.components.table;

import com.haulmont.cuba.gui.components.data.BindingState;
import com.haulmont.cuba.gui.components.data.GroupTableItems;
import com.haulmont.cuba.gui.data.GroupInfo;
import com.haulmont.cuba.web.widgets.data.GroupTableContainer;

import java.util.*;

public class GroupTableDataContainer<I> extends SortableDataContainer<I> implements GroupTableContainer {

    protected Set<GroupInfo> expandedGroups = new HashSet<>();

    protected List<Object> cachedItemIds;
    protected Object first;
    protected Object last;

    public GroupTableDataContainer(GroupTableItems<I> tableSource,
                                   TableItemsEventsDelegate<I> dataEventsDelegate) {
        super(tableSource, dataEventsDelegate);
    }

    protected GroupTableItems<I> getGroupTableSource() {
        return (GroupTableItems<I>) tableItems;
    }

    @Override
    public void groupBy(Object[] properties) {
        doGroup(properties);
    }

    protected Set<GroupInfo> saveState() {
        //save expanding state
        return new HashSet<>(expandedGroups);
    }

    protected void restoreState(Set<GroupInfo> expandState) {
        collapseAll();
        //restore groups expanding
        if (hasGroups()) {
            for (GroupInfo groupInfo : expandState) {
                expand(groupInfo);
            }
        }
    }

    protected void doGroup(Object[] properties) {
        Set<GroupInfo> expandState = saveState();
        getGroupTableSource().groupBy(properties);
        restoreState(expandState);
        resetCachedItems();
    }

    @Override
    public boolean isGroup(Object id) {
        return id instanceof GroupInfo && getGroupTableSource().containsGroup((GroupInfo) id);
    }

    @Override
    public Collection<?> rootGroups() {
        return getGroupTableSource().rootGroups();
    }

    @Override
    public boolean hasChildren(Object id) {
        return isGroup(id) && getGroupTableSource().hasChildren((GroupInfo) id);
    }

    @Override
    public Collection<?> getChildren(Object id) {
        if (isGroup(id)) {
            return getGroupTableSource().getChildren((GroupInfo) id);
        }
        return Collections.emptyList();
    }

    @Override
    public Object getGroupProperty(Object id) {
        if (isGroup(id)) {
            return getGroupTableSource().getGroupProperty((GroupInfo) id);
        }
        return null;
    }

    @Override
    public Object getGroupPropertyValue(Object id) {
        if (isGroup(id)) {
            return getGroupTableSource().getGroupPropertyValue((GroupInfo) id);
        }
        return null;
    }

    @Override
    public Collection<?> getGroupItemIds(Object id) {
        if (isGroup(id)) {
            return getGroupTableSource().getGroupItemIds((GroupInfo) id);
        }
        return Collections.emptyList();
    }

    @Override
    public int getGroupItemsCount(Object id) {
        if (isGroup(id)) {
            return getGroupTableSource().getGroupItemsCount((GroupInfo) id);
        }
        return 0;
    }

    @Override
    public boolean hasGroups() {
        return getGroupTableSource().hasGroups();
    }

    @Override
    public Collection<?> getGroupProperties() {
        if (hasGroups()) {
            return getGroupTableSource().getGroupProperties();
        }
        return Collections.emptyList();
    }

    @Override
    public void expandAll() {
        if (hasGroups()) {
            expandedGroups.clear();

            expand(rootGroups());
            resetCachedItems();
        }
    }

    protected void expand(Collection groupIds) {
        for (Object groupId : groupIds) {
            expandedGroups.add((GroupInfo) groupId);
            if (hasChildren(groupId)) {
                expand(getChildren(groupId));
            }
        }
    }

    @Override
    public void expand(Object id) {
        if (isGroup(id)) {
            expandedGroups.add((GroupInfo) id);
            resetCachedItems();
        }
    }

    @Override
    public void collapseAll() {
        if (hasGroups()) {
            expandedGroups.clear();
            resetCachedItems();
        }
    }

    @Override
    public void collapse(Object id) {
        if (isGroup(id)) {
            //noinspection RedundantCast
            expandedGroups.remove((GroupInfo) id);
            resetCachedItems();
        }
    }

    @Override
    public boolean isExpanded(Object id) {
        //noinspection RedundantCast
        return isGroup(id) && expandedGroups.contains((GroupInfo) id);
    }

    @Override
    public Collection<?> getItemIds() {
        if (tableItems.getState() == BindingState.INACTIVE) {
            return Collections.emptyList();
        }

        return getCachedItemIds();
    }

    protected List getCachedItemIds() {
        if (cachedItemIds == null) {
            List<Object> result = new ArrayList<>();
            //noinspection unchecked

            if (getGroupTableSource().hasGroups()) {
                List<GroupInfo> roots = getGroupTableSource().rootGroups();
                if (!roots.isEmpty()) {
                    for (GroupInfo root : roots) {
                        result.add(root);
                        collectItemIds(root, result);
                    }
                }
                cachedItemIds = result;
            } else {
                cachedItemIds = new ArrayList<>();
                //noinspection unchecked
                cachedItemIds.addAll(getGroupTableSource().getItemIds());
            }

            if (!cachedItemIds.isEmpty()) {
                first = cachedItemIds.get(0);
                last = cachedItemIds.get(cachedItemIds.size() - 1);
            }
        }
        return cachedItemIds;
    }

    protected void collectItemIds(GroupInfo groupId, List<Object> itemIds) {
        if (expandedGroups.contains(groupId)) {
            GroupTableItems<I> groupTableSource = getGroupTableSource();

            if (groupTableSource.hasChildren(groupId)) {
                List<GroupInfo> children = groupTableSource.getChildren(groupId);
                for (GroupInfo child : children) {
                    itemIds.add(child);
                    collectItemIds(child, itemIds);
                }
            } else {
                itemIds.addAll(groupTableSource.getGroupItemIds(groupId));
            }
        }
    }

    protected void resetCachedItems() {
        cachedItemIds = null;
        first = null;
        last = null;
    }

    @Override
    public int size() {
        if (hasGroups()) {
            return getItemIds().size();
        }
        return super.size();
    }

    @Override
    public Object firstItemId() {
        if (hasGroups()) {
            return first;
        }
        return super.firstItemId();
    }

    @Override
    public Object lastItemId() {
        if (hasGroups()) {
            return last;
        }
        return super.lastItemId();
    }

    @Override
    public Object nextItemId(Object itemId) {
        if (hasGroups()) {
            if (itemId == null) {
                return null;
            }
            if (isLastId(itemId)) {
                return null;
            }
            int index = getCachedItemIds().indexOf(itemId);
            return getCachedItemIds().get(index + 1);
        }
        return super.nextItemId(itemId);
    }

    @Override
    public Object prevItemId(Object itemId) {
        if (hasGroups()) {
            if (itemId == null) {
                return null;
            }

            if (isFirstId(itemId)) {
                return null;
            }
            int index = getCachedItemIds().indexOf(itemId);
            return getCachedItemIds().get(index - 1);
        }
        return super.prevItemId(itemId);
    }

    @Override
    public boolean isFirstId(Object itemId) {
        if (hasGroups()) {
            return itemId != null && itemId.equals(first);
        }
        return super.isFirstId(itemId);
    }

    @Override
    public boolean isLastId(Object itemId) {
        if (hasGroups()) {
            return itemId != null && itemId.equals(last);
        }
        return super.isLastId(itemId);
    }
}


text:
@interface UpdateOrderResponse : BaseResponse

@end


text:
package main

import (
	"fmt"
	"runtime"
)

func whisper(left, right chan int) {
	left <- 1 + <-right
}

func main() {
	// Go 1.5 defaults to using all CPU cores. gccgo doesn't yet (as of 7.1.0).
	// Set it explicitly to make the benchmarks more fair.
	runtime.GOMAXPROCS(runtime.NumCPU())

	const n = 500000
	leftmost := make(chan int)
	right := leftmost
	left := leftmost
	for i := 0; i < n; i++ {
		right = make(chan int)
		go whisper(left, right)
		left = right
	}
	go func(c chan int) { c <- 1 }(right)
	fmt.Println(<-leftmost)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MT FR exo VR</string>
</resources>


text:
<?php

namespace Gedmo\References\Mapping\Driver;

use Gedmo\Exception\InvalidMappingException;
use Gedmo\Mapping\Driver;
use Gedmo\Mapping\Driver\File;

/**
 * @author Gonzalo Vilaseca <gonzalo.vilaseca@reiss.com>
 *
 * @deprecated since gedmo/doctrine-extensions 3.5, will be removed in version 4.0.
 */
class Yaml extends File implements Driver
{
    /**
     * File extension
     *
     * @var string
     */
    protected $_extension = '.dcm.yml';

    /**
     * @var array
     */
    private $validReferences = [
        'referenceOne' => [],
        'referenceMany' => [],
        'referenceManyEmbed' => [],
    ];

    public function readExtendedMetadata($meta, array &$config)
    {
        $mapping = $this->_getMapping($meta->getName());

        if (isset($mapping['gedmo'], $mapping['gedmo']['reference'])) {
            foreach ($mapping['gedmo']['reference'] as $field => $fieldMapping) {
                $reference = $fieldMapping['reference'];

                if (!in_array($reference, array_keys($this->validReferences), true)) {
                    throw new InvalidMappingException($reference.' is not a valid reference, valid references are: '.implode(', ', array_keys($this->validReferences)));
                }

                $config[$reference][$field] = [
                    'field' => $field,
                    'type' => $fieldMapping['type'],
                    'class' => $fieldMapping['class'],
                ];

                if (array_key_exists('mappedBy', $fieldMapping)) {
                    $config[$reference][$field]['mappedBy'] = $fieldMapping['mappedBy'];
                }

                if (array_key_exists('identifier', $fieldMapping)) {
                    $config[$reference][$field]['identifier'] = $fieldMapping['identifier'];
                }

                if (array_key_exists('inversedBy', $fieldMapping)) {
                    $config[$reference][$field]['inversedBy'] = $fieldMapping['inversedBy'];
                }
            }
        }
        $config = array_merge($this->validReferences, $config);
    }

    protected function _loadMappingFile($file)
    {
        return \Symfony\Component\Yaml\Yaml::parse($file);
    }
}


text:
package org.pihisamurai;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Scanner;

public class Vision {

	static final String fileName = "program.py";
	static final String dirName = "tempPythonScript";

	ProcessBuilder pb;
	File dir;
	File program;

	public Vision() {
		String home = System.getProperty("user.home");
		dir = new File(new File(home), dirName);
		program = new File(dir, fileName);
		dir.mkdirs();
		program.deleteOnExit();
		try {
			program.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		dir.deleteOnExit();

		try {
			URL url = this.getClass().getClassLoader().getResource(fileName);

			InputStream in = url.openConnection().getInputStream();

			BufferedWriter out = new BufferedWriter(new FileWriter(program.getAbsolutePath()));

			while (in.available() > 0)
				out.write(in.read());
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		pb = new ProcessBuilder("python", program.getAbsolutePath());
		pb.directory(dir);

	}

	public String getData() {
		try {
			Process p;
			p = pb.start();
			try {
				p.waitFor();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			System.out.println(p.exitValue());
			BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			StringBuilder builder = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {
				builder.append(line);
				builder.append(System.getProperty("line.separator"));
			}
			String result = builder.toString();

			return result;
		} catch (IOException e) {
			Vision vision = new Vision();
			e.printStackTrace();
		}
		return "ERROR";
	}

	public static void main(String args[]) {
		Vision vision = new Vision();
		System.out.print(vision.getData());
	}

}


text:
/**
 */
package outagePreventionJointarget;

/**
 *
 * A representation of the model object 'Non Conform Load Group'.
 *
 *
 *
 * @see outagePreventionJointarget.OutagePreventionJointargetPackage#getNonConformLoadGroup()
 * @model
 * @generated
 */
public interface NonConformLoadGroup extends LoadGroup {
} // NonConformLoadGroup


text:
package org.workcraft.gui.properties;

import org.workcraft.gui.controls.FlatComboBox;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ChoiceCellEditor extends AbstractCellEditor implements TableCellEditor, ItemListener {

    static class ChoiceWrapper {
        public Object object;
        public String description;

        ChoiceWrapper(Object object, String description) {
            this.object = object;
            this.description = description;
        }

        @Override
        public String toString() {
            return description;
        }
    }

    private final FlatComboBox comboBox;
    private final List<ChoiceWrapper> wrappers;

    public ChoiceCellEditor(PropertyDescriptor<Object> descriptor) {
        comboBox = new FlatComboBox();
        comboBox.setFocusable(false);
        comboBox.addItemListener(this);

        Map<Object, String> choice = descriptor.getChoice();
        wrappers = new ArrayList<>();
        for (Map.Entry<Object, String> entry : choice.entrySet()) {
            ChoiceWrapper wrapper = new ChoiceWrapper(entry.getKey(), entry.getValue());
            wrappers.add(wrapper);
            comboBox.addItem(wrapper);
        }
    }

    @Override
    public Object getCellEditorValue() {
        Object selectedItem = comboBox.getSelectedItem();
        if (selectedItem instanceof ChoiceWrapper) {
            return ((ChoiceWrapper) selectedItem).object;
        }
        return null;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        comboBox.setOpaque(value == null);
        comboBox.setFont(table.getFont());
        // First select non-existent item, then select a "correct" item.
        comboBox.setSelectedItem(null);
        for (ChoiceWrapper wrapper: wrappers) {
            if (wrapper.description.equals(value)) {
                comboBox.setSelectedItem(wrapper);
                break;
            }
        }
        return comboBox;
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        fireEditingStopped();
    }

}


text:
package com.comcast.money.internal

import com.comcast.money.core.SpanId
import org.scalatest.mock.MockitoSugar

import org.scalatest.{ BeforeAndAfterEach, Matchers, WordSpec }
import org.slf4j.MDC

class SpanLocalSpec extends WordSpec with Matchers with BeforeAndAfterEach with MockitoSugar {

  override def afterEach() = {
    SpanLocal.clear()
  }

  "SpanLocal" when {
    "an item exists in span local" should {
      "return the span local value" in {
        val spanId = SpanId("1", 2L, 3L)
        SpanLocal.push(spanId)
        SpanLocal.current shouldEqual Some(spanId)
      }
      "clear the stored value" in {
        val spanId = SpanId("1", 2L, 3L)
        SpanLocal.push(spanId)

        SpanLocal.clear()
        SpanLocal.current shouldEqual None
      }
      "do nothing if trying to push a null value" in {
        val spanId = SpanId("1", 2L, 3L)
        SpanLocal.push(spanId)
        SpanLocal.current shouldEqual Some(spanId)

        SpanLocal.push(null)
        SpanLocal.current shouldEqual Some(spanId)
      }
      "add to the existing call stack" in {
        val spanId = SpanId("1", 2L, 3L)
        SpanLocal.push(spanId)
        SpanLocal.current shouldEqual Some(spanId)

        val nestedSpanId = SpanId("2", 3L, 4L)
        SpanLocal.push(nestedSpanId)
        SpanLocal.current shouldEqual Some(nestedSpanId)
      }
      "pop the last added item from the call stack" in {
        val spanId = SpanId("1", 2L, 3L)
        SpanLocal.push(spanId)
        SpanLocal.current shouldEqual Some(spanId)

        val nestedSpanId = SpanId("2", 3L, 4L)
        SpanLocal.push(nestedSpanId)
        SpanLocal.current shouldEqual Some(nestedSpanId)

        val popped = SpanLocal.pop()
        popped shouldEqual Some(nestedSpanId)
        SpanLocal.current shouldEqual Some(spanId)
      }
      "set the MDC value on push" in {
        val spanId = SpanId()
        SpanLocal.push(spanId)

        MDC.get("moneyTrace") shouldEqual MDCSupport.format(spanId)
      }
      "remove the MDC value on pop" in {
        val spanId = SpanId()
        SpanLocal.push(spanId)

        MDC.get("moneyTrace") shouldEqual MDCSupport.format(spanId)
        SpanLocal.pop()

        MDC.get("moneyTrace") shouldBe null
      }
      "remove the MDC value on clear" in {
        val spanId = SpanId()
        SpanLocal.push(spanId)

        MDC.get("moneyTrace") shouldEqual MDCSupport.format(spanId)
        SpanLocal.clear()

        MDC.get("moneyTrace") shouldBe null
      }
    }
  }
}


text:
<?php

namespace App\Http\Controllers;
use App\User;
use Entrust\Role;
use \Request;

class UsersController extends Controller
{
  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct()
  {
    $this->middleware('auth');
  }

  /**
   * Show the application dashboard to the user.
   *
   * @return Response
   */
  public function index()
  {
    return view('users.index', array('users' => User::paginate(20)));
  }

  public function edit($id = null)
  {
    $user = $id ? User::find($id) : new User();
    if ($user) {
      return $this->showLayout($user);
    } else {
      abort(404);
    }
  }

  public function store()
  {
    $id = Request::input('id');
    $user = $id ? User::find($id) : new User();
    if ($user) {
      try {
        $user->store(Request::all());
        return \Redirect::to('users/edit/' . $user->id . '?success=1');
      } catch(\Exception $e) {
        return $this->showLayout($user, $user->validation_errors);
      }
    } else {
      abort(404);
    }
  }

  public function destroy()
  {
    $id = Request::input('id');
    $user = User::find($id);
    if ($user) {
      $user->delete();
    }
  }

  protected function showLayout(User $user, $errors = array())
  {
    $roles = Role::lists('name', 'id');
    $view = view('users.edit', array('user' => $user, 'roles' => $roles, 'success' => Request::input('success', 0)));
    if (count($errors)) {
      $view->with('errors', $errors);
    }
    return $view;
  }
}


text:
(function () {

var koView = ko.views.manager.currentView.scimoz;
var currentPos = koView.currentPos;

try {
    // Group operations into a single undo
    koView.beginUndoAction();

	var prefixes = [ '', '-o-', '-ms-', '-moz-', '-webkit-' ];

    var addPrefixes = function (line) {
		var build = '';
		for ( var i = 0, len = prefixes.length; i < len; i++ ) {
			ko.commands.doCommand('cmd_lineOrSelectionDuplicate');
			ko.commands.doCommand('cmd_home');
			ko.commands.doCommand('cmd_selectEnd');
			build = prefixes[i] + line;
			koView.replaceSel( build );
		}
    };

	ko.commands.doCommand('cmd_home');
	ko.commands.doCommand('cmd_selectEnd');

    if ( !!koView.selText ) {
       addPrefixes( koView.selText );
    }

}
catch (e) {
    alert(e);
}
finally {
    // Must end undo action or may corrupt edit buffer
    koView.endUndoAction();
}
})();