text:
/*
 * @(#)SigTestResult.java	1.6 06/02/11
 */
package com.sun.ts.tests.signaturetest;

import java.util.*;
import java.io.Serializable;

public class SigTestResult implements Serializable {

    private static final String NL = System.getProperty("line.separator", "\n");

    private List failedPkgs = new ArrayList();
    private List passedPkgs = new ArrayList();
    private List failedClasses = new ArrayList();
    private List passedClasses = new ArrayList();

    // ---------------------------------------------------------- Public Methods

    public synchronized boolean passed() {

        return (failedPkgs.size() == 0 && failedClasses.size() == 0);

    } // end passed

    public synchronized void addFailedPkg(String pkg) {

        failedPkgs.add(pkg);

    } // END addFailedPkg

    public synchronized void addPassedPkg(String pkg) {

        passedPkgs.add(pkg);

    } // END addPassedPkg

    public synchronized void addFailedClass(String className) {

        failedClasses.add(className);

    } // END addFailedClass

    public synchronized void addPassedClass(String className) {

        passedClasses.add(className);

    } // END addPassedClass

    public String toString() {

        String delim =
            "******************************************************" + NL;
        if (!pkgsTested() && !classesTested()) {
            return (delim
                   + "******** No packages or classes were tested **********"
                   + NL
                   + delim);
        }
        StringBuffer buf = new StringBuffer();
        buf.append(delim);
        buf.append(delim);
        if (passed()) {
            buf.append("All package signatures passed.").append(NL);
        } else {
            buf.append("Some signatures failed.").append(NL);
            if (failedPkgs.size() > 0) {
                buf.append("\tFailed packages listed below: ").append(NL);
                formatList(failedPkgs, buf);
            }
            if (failedClasses.size() > 0) {
                buf.append("\tFailed classes listed below: ").append(NL);
                formatList(failedClasses, buf);
            }
        }
        if (passedPkgs.size() > 0) {
            buf.append("\tPassed packages listed below: ").append(NL);
            formatList(passedPkgs, buf);
        }
        if (passedClasses.size() > 0) {
            buf.append("\tPassed classes listed below: ").append(NL);
            formatList(passedClasses, buf);
        }
        buf.append("\t");
        buf.append(delim);
        buf.append(delim);
        return buf.toString();

    } // END toString

    // --------------------------------------------------------- Private Methods

    private synchronized void formatList(List list, StringBuffer buf) {

        synchronized (this) {
            for (int i = 0; i < list.size(); i++) {
                String pkg = (String) (list.get(i));
                buf.append("\t\t").append(pkg).append(NL);
            }
        }

    } // END formatList

    private synchronized boolean pkgsTested() {

        return (failedPkgs.size() != 0 || passedPkgs.size() != 0);

    } // END pkgsTested

    private synchronized boolean classesTested() {

        return (failedClasses.size() != 0 || passedClasses.size() != 0);

    } // END classesTested

} // end class SigTestResult


text:
import React, {Component} from 'react';
import _ from 'lodash';
import moment from 'moment';

import firebase, {firebaseRef, auth, firebaseIdeasRef, firebaseUsersRef} from './../data/firebase';
import Navbar from './layout/Navbar';
import Footer from './layout/Footer';
import ModalIdea from './common/ModalIdea';
import ModalEdit from './common/ModalEdit';
import ModalResource from './common/ModalResource';

// Appears on every page, other pages are passed to {props.children}
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userID: undefined,
      username: 'Anonymous',
      userAvatar: undefined,
      ideas: undefined,
      userFavorites: [],
      currentUserRef: undefined
    };
  }

  componentDidUpdate() {
    // console.log(auth.currentUser.uid, auth.currentUser.displayName);
    //console.log('new state: ', this.state);
  } // /componentDidUpdate

  componentDidMount() {

    // authentication
    auth.onAuthStateChanged(user => {
      if (user) {
        // if someone is logged in
        this.setState({
          userID: user.uid,
          username: auth.currentUser.displayName,
          userAvatar: user.photoURL
        });

        // check if current user exists in users db
        firebaseUsersRef.once('value').then(snapshot => {
          const usersData = snapshot.val();
          // current logged in user is not in the users database
          if ( !( _.findKey(usersData, {'id': auth.currentUser.uid}) ) ) {
            // new user to add
            firebaseUsersRef.push({
              id: auth.currentUser.uid,
              favorites: []
            });
            // add it to our current data
            this.setState({
              userFavorites: {}
            });
          } else {
            // user is in database load their favorites
            this.setState({
              userFavorites: _.toArray(usersData[_.findKey(usersData, {'id': auth.currentUser.uid})].favorites) || [],
              currentUserRef: _.findKey(usersData, {'id': auth.currentUser.uid})
            });
            watchCurrentUser();
          }
        }); // /user.once

      } else {
        // logged out
        this.setState({
          userID: undefined,
          username: 'Anonymous',
          userAvatar: undefined
        });
      }
    }); // /auth change

    // on currentUserData change
    const watchCurrentUser = () => {
      firebaseUsersRef.child(this.state.currentUserRef).on('value', snapshot => {
        //console.log('user change: ', snapshot.val());
        this.setState({
          userFavorites: _.toArray(snapshot.val().favorites)
        });
      });
    } // /currentUserData change

    // ideas data change
    firebaseIdeasRef.on('value', snapshot => {
      // ideas is an object, keys are ids
      const ideas = snapshot.val();
      let parsedIdeas = {...ideas};

      // convert objects to arrays
      _.forIn(parsedIdeas, (value, key) => {
        parsedIdeas[key].examples = _.toArray(parsedIdeas[key].examples);
        parsedIdeas[key].tutorials = _.toArray(parsedIdeas[key].tutorials);
        parsedIdeas[key].tags = _.toArray(parsedIdeas[key].tags);
      });

      this.setState({
        ideas: parsedIdeas
      });
    }); // /ideas data change

  } // /componentDidMount

  addIdea = ( ideaTitle, ideaDesc, ideaImgUrl, ideaTags ) => {
    // only logged in users can add ideas
    if (auth.currentUser) {
      // new idea to push up
      let newIdea = {
        title: ideaTitle,
        description: ideaDesc,
        owner: auth.currentUser.uid,
        ownerName: auth.currentUser.displayName,
        createdAt: moment().unix(),
        tags: ideaTags.split(', '),
        imageUrl: ideaImgUrl,
        rating: 0,
        tutorials: null,
        examples: null
      }

      let newIdeaRef = firebaseIdeasRef.push(newIdea);
    } else {
      alert('Please sign in to add ideas!');
    }
  } // /addIdea

  editIdea = ( ideaID, ideaTitle, ideaDesc, ideaImgUrl, ideaTags ) => {
    if (auth.currentUser && this.state.ideas[ideaID].owner === auth.currentUser.uid) {
      // new idea to push up
      let updatedIdea = {
        title: ideaTitle,
        description: ideaDesc,
        tags: ideaTags.split(', '),
        imageUrl: ideaImgUrl
      }

      let updatedIdeaRef = firebaseIdeasRef.child(ideaID).update(updatedIdea);
    } else {
      alert('Only the owner can edit this idea!');
    }
  } // /edit idea

  // adding examples / tutorials
  addResource = ( ideaID, exampleTitle, exampleLink, exampleImg, tutorialTitle, tutorialLink) => {
    if (ideaID) {
      // only logged in users can add resources
      if (auth.currentUser) {
        const ideaRef = firebaseIdeasRef.child(ideaID);

        // add example
        if(exampleTitle && exampleLink) {
          // TODO urls need a http:// in front if not included
          let newExampleRef = ideaRef.child('examples').push({
            title: exampleTitle,
            imageUrl: exampleImg,
            url: exampleLink
          });
        }

        // add tutorial
        if(tutorialTitle && tutorialLink) {
          // TODO urls need a http:// in front if not included
          let newTutorialRef = ideaRef.child('tutorials').push({
            text: tutorialTitle,
            url: tutorialLink
          });
        }

      } else {
        alert('Please sign in to add examples or tutorials!');
      }
    }
  } // /addResource

  removeResource = () => {
    console.log('removing: ');
  } // /removeResource

  addFavoriteIdea = (ideaID) => {
    // pass current user id to post for rendering heart
    // receive post id when clicking heart
    if (auth.currentUser) {
      // test if idea id is already a favorite -1 if not a favorite else index
      let notAFavorite = _.findIndex(this.state.userFavorites, (val) => {
        return val === ideaID;
      });

      // -1 means not a favorite
      if (notAFavorite < 0) {
        let newFavoriteRef = firebaseUsersRef.child(this.state.currentUserRef).child('favorites').push(ideaID).then(() => {
          let ideaRef = firebaseIdeasRef.child(ideaID);
          let rating = this.state.ideas[ideaID].rating;

          ideaRef.update({
            rating: ++rating
          });
        });
      } else {
        alert('Idea ' + ideaID + ' is already a favorite!');
      }
    }
  } // /addFavoriteIdea

  render() {
    // use this.props.children.type.name to identify component being rendered
    //console.log('props.children: ', this.props.children);

    // use this.props.location.query.id for url arguments
    //console.log('url args: ', this.props.location.query.id);

    // use React.cloneElement for passing props to children
    // will break if multiple child components http://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children

    const defaultIdeaData = {
      createdAt: 12345,
      description: 'loading data...',
      examples: [],
      imageUrl: '',
      owner: 'Developer',
      ownerName: 'Anonymous',
      rating: 0,
      tags: [],
      title: 'Loading data...',
      tutorials: []
    };

    //let componentToRender = this.props.children...;
    let componentToRender = this.props.children.props.route.componentName;
    // object of props to pass
    let dataToPass = {};

    // props to pass in depending on component type
    switch(componentToRender) {
      case 'SearchPage':
        dataToPass = {
          ideas: this.state.ideas,
          handleAddFavorite: this.addFavoriteIdea,
          userFavorites: this.state.userFavorites
        };
        break;
      case 'IdeaPage':
        let postID = this.props.location.query.id;
        let postData = _.at(this.state.ideas, postID)[0] || defaultIdeaData;
        let isOwner = auth.currentUser && postData.owner === auth.currentUser.uid;
        let isFavorite = this.state.userFavorites.findIndex( (val) => val === postID ) >= 0 ? true : false;

        dataToPass = {
          postData: postData,
          handleAddFavorite: this.addFavoriteIdea,
          defaultIdeaData,
          postID,
          isOwner,
          isFavorite
        };
        break;
      default:
        dataToPass = {};
        break;
    }

    return (
      <div>
        <ModalIdea handleAddIdea={this.addIdea} />

        {
        _.at(this.state.ideas, this.props.location.query.id)[0] !== undefined ?
        <ModalEdit handleEditIdea={this.editIdea} ideaID={this.props.location.query.id} ideaData={_.at(this.state.ideas, this.props.location.query.id)[0]} /> : null
        }

        <ModalResource handleAddResource={this.addResource} ideaID={this.props.location.query.id} />
        <Navbar username={this.state.username} avatar={this.state.userAvatar} />

          {this.props.children && React.cloneElement(this.props.children, dataToPass)}

        <Footer />
      </div>
    );
  }
}

export default App;

/*
// pass in props
{this.props.children && React.cloneElement(this.props.children, {
  onRemoveTaco: this.handleRemoveTaco
})}

*/

/* NOTES
STATE DATA

object {
  /IdeaZone/Design/idz-state-data.png
}

*/

redpajama_set_name: RedPajamaGithub


text:
package au.edu.unimelb.csse.join;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import au.edu.unimelb.csse.Operator;
import au.edu.unimelb.csse.join.AbstractJoin.PostingsAndFreq;
import au.edu.unimelb.csse.paypack.LogicalNodePositionAware;

public class FullPairJoinPipeline {
	Pipe start;
	final LogicalNodePositionAware nodePositionAware;
	final FullPairJoin join;
	Operator[] operators;
	NodePositions prevPositions;
	NodePairPositions nodePairPositions;
	List<int[]> results;
	private int length;
	int totalLength;

	public FullPairJoinPipeline(LogicalNodePositionAware nodePositionAware,
			FullPairJoin join) {
		this.nodePositionAware = nodePositionAware;
		this.length = nodePositionAware.getPositionLength();
		prevPositions = new NodePositions();
		nodePairPositions = new NodePairPositions();
		this.join = join;
	}

	public Pipe createExecPipeline(PostingsAndFreq pfRoot, Operator[] operators) {
		totalLength = operators.length * length;
		this.operators = operators;
		start = new FirstPipe(pfRoot, operators[pfRoot.position]);
		if (pfRoot.children.length == 1) {
			recCreatePipe(pfRoot.children[0], pfRoot.position, start);
		} else if (pfRoot.children.length > 1) {
			Pipe prevPipe = start;
			int parentPos = pfRoot.position;
			for (int i = 0; i < pfRoot.children.length; i++) {
				prevPipe = recCreatePipe(pfRoot.children[i], parentPos,
						prevPipe);
			}
		}
		return start;
	}

	private Pipe recCreatePipe(PostingsAndFreq node, int parentPos,
			Pipe prevPipe) {
		Pipe pipe = new SimplePipe(node, operators[node.position], parentPos,
				prevPipe);
		if (node.children.length > 0) {
			if (node.children.length == 1) {
				pipe = recCreatePipe(node.children[0], node.position, pipe);
			} else {
				for (int i = 0; i < node.children.length; i++) {
					pipe = recCreatePipe(node.children[i], node.position, pipe);
				}
			}
		}
		return pipe;
	}

	void setPrevBuffer(NodePositions prev) {
		this.prevPositions = prev;
	}

	void setPrevPositionsFromResults(int position, Comparator<int[]> comparator) {
		Collections.sort(results, comparator);
		prevPositions.reset();
		for (int[] result : results) {
			if (prevPositions.size == 0) {
				for (int i = 0; i < length; i++) {
					prevPositions.positions[i] = result[position * length + i];
					prevPositions.size++;
				}
			} else {
				if (nodePositionAware.compare(result, position * length,
						prevPositions.positions, prevPositions.offset) != 0) {
					while (prevPositions.size + length > prevPositions.positions.length) {
						prevPositions.expand();
					}
					for (int i = 0; i < length; i++) {
						prevPositions.positions[prevPositions.size + i] = result[position
								* length + i];
					}
					prevPositions.size += length;
					prevPositions.offset += length;
				}
			}
		}
	}

	void mergeNodePairPositionsWithResults(int parentPos, int currentPos) {
		List<int[]> newResults = new ArrayList<int[]>();
		for (int i = 0, j = 0, k = 0; i < prevPositions.size
				&& j < nodePairPositions.size;) {
			while (nodePositionAware.compare(prevPositions.positions, i,
					results.get(k), parentPos * length) != 0) {
				k++;
			}
			int c = nodePositionAware.compare(prevPositions.positions, i,
					nodePairPositions.node1, j);
			if (c == 0) {
				int m = k;
				while (m < results.size()
						&& nodePositionAware.compare(prevPositions.positions,
								i, results.get(m), parentPos * length) == 0) {
					int[] resultOld = results.get(m);
					int[] result = Arrays.copyOf(resultOld, resultOld.length);
					for (int n = 0; n < length; n++) {
						result[currentPos * length + n] = nodePairPositions.node2[j
								+ n];
					}
					newResults.add(result);
					m++;
				}
				j += length;
			} else if (c < 0) {
				i += length;
			}
		}
		results = newResults;
	}

	class FirstPipe extends AbstractPipe {
		private static final int PARENT_POS = 0;

		public FirstPipe(PostingsAndFreq node, Operator op) {
			super(node, op);
		}

		@Override
		public NodePairPositions execute() throws IOException {
			prevPositions.reset();
			nodePositionAware.getAllPositions(prevPositions, node.postings);
			if (Operator.CHILD.equals(op)) {
				if (nodePositionAware.isTreeRootPosition(
						prevPositions.positions, 0)) {
					prevPositions.offset = 0;
					prevPositions.size = nodePositionAware.getPositionLength();
				} else {
					prevPositions.reset();
				}
			}
			if (prevPositions.size == 0) {
				nodePairPositions.reset();
				results.clear();
				return nodePairPositions;
			}
			results = new ArrayList<int[]>();
			for (int i = 0; i < prevPositions.size / length; i++) {
				int[] result = new int[totalLength];
				for (int j = 0; j < length; j++) {
					result[PARENT_POS + j] = prevPositions.positions[i * length
							+ j];
				}
				results.add(result);
			}
			if (next == null) {
				return nodePairPositions;
			}
			return next.execute();
		}
	}

	class SimplePipe extends AbstractPipe {
		int parentPos;
		private NPAPathPositionComparator comparator;

		public SimplePipe(PostingsAndFreq node, Operator op, int parentPos,
				Pipe prevPipe) {
			super(node, op);
			this.parentPos = parentPos;
			prevPipe.setNext(this);
			comparator = new NPAPathPositionComparator(nodePositionAware,
					parentPos);
		}

		@Override
		public NodePairPositions execute() throws IOException {
			setPrevPositionsFromResults(parentPos, comparator);
			join.match(prevPositions, op, node.postings, nodePairPositions);
			if (nodePairPositions.size == 0) {
				results.clear();
				return nodePairPositions;
			}
			mergeNodePairPositionsWithResults(parentPos, node.position);
			if (next == null) {
				return nodePairPositions;
			}
			return next.execute();
		}

	}

	abstract class AbstractPipe implements Pipe {
		PostingsAndFreq node;
		Operator op;
		Pipe next;

		public AbstractPipe(PostingsAndFreq node, Operator op) {
			this.node = node;
			this.op = op;
		}

		@Override
		public void setNext(Pipe pipe) {
			next = pipe;
		}

		@Override
		public Pipe getNext() {
			return next;
		}

	}

	interface Pipe {

		NodePairPositions execute() throws IOException;

		void setNext(Pipe pipe);

		Pipe getNext();
	}
}


text:
'use strict';

// MODULES //

var constantFunction = require( '@stdlib/utils/constant-function' );
var degenerate = require( '@stdlib/stats/base/dists/degenerate/pdf' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var NINF = require( '@stdlib/constants/float64/ninf' );

// MAIN //

/**
* Returns a function for evaluating the probability density function (PDF) for a logistic distribution.
*
* @param {number} mu - location parameter
* @param {NonNegativeNumber} s - scale parameter
* @returns {Function} PDF
*
* @example
* var pdf = factory( 10.0, 2.0 );
* var y = pdf( 10.0 );
* // returns 0.125
*
* y = pdf( 5.0 );
* // returns ~0.035
*/
function factory( mu, s ) {
	if ( isnan( mu ) || isnan( s ) || s < 0.0 ) {
		return constantFunction( NaN );
	}
	if ( s === 0.0 ) {
		return degenerate( mu );
	}
	return pdf;

	/**
	* Evaluates the probability density function (PDF) for a logistic distribution.
	*
	* @private
	* @param {number} x - input value
	* @returns {number} evaluated PDF
	*
	* @example
	* var y = pdf( -1.2 );
	* // returns <number>
	*/
	function pdf( x ) {
		var ez;
		var z;
		if ( isnan( x ) ) {
			return NaN;
		}
		if ( x === NINF ) {
			return 0.0;
		}
		z = abs( ( x - mu ) / s );
		ez = exp( -z );
		return ez / ( s * pow( 1.0 + ez, 2.0 ) );
	}
}

// EXPORTS //

module.exports = factory;


text:
"""
Copyright 2015 Paul T. Grogan, Massachusetts Institute of Technology

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

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

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

"""
Controller class.
"""

import logging

from .entity import Entity
from .contract import Contract

class Controller(Entity):
    def __init__(self, name=None):
        """
        @param name: the name of this controller
        @type name: L{str}
        """
        Entity.__init__(self, name=name)

    def getElements(self):
        """
        Gets the elements controlled by this controller.
        @return L{list}
        """
        return []

    def getFederates(self):
        """
        Gets the federates controlled by this controller.
        @return L{list}
        """
        return []

    def getContracts(self):
        """
        Gets the contracts controlled by this controller.
        @return L{list}
        """
        return []

    def liquidate(self, context):
        """
        Liquidates all assets.
        """
        for element in self.getElements():
            self.decommission(element)
        for contract in self.getContracts():
            self.resolve(contract, context)

    def canContract(self, demand, context):
        """
        Checks if this controller can contract a demand.
        @param demand: the demand to contract
        @type demand: L{Demand}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        return (demand in context.currentEvents
                and any(element.canSense(demand)
                        for element in self.getElements()))

    def canResolve(self, contract):
        """
        Checks if this controller can resolve a contract.
        @param contract: the contract to resolve
        @type contract: L{Contract}
        @return: L{bool}
        """
        return contract in self.getContracts()

    def canSense(self, demand, element, context):
        """
        Checks if this controller can sense a demand.
        @param demand: the demand to sense
        @type demand: L{Demand}
        @param element: the element to sense
        @type element: L{Element}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        return (element in self.getElements()
                and self.canContract(demand, context)
                or any(contract.demand is demand
                       for contract in self.getContracts())
                and element.canSense(demand))

    def senseAndStore(self, contract, element, context):
        """
        Senses and stores data for a contract.
        @param contract: the contract to sense and store
        @type contract: L{Contract}
        @param element: the element to sense
        @type element: L{Element}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        if contract not in self.getContracts():
            logging.warning('{0} does not control {1}.'
                        .format(self.name, contract.name))
        elif element not in self.getElements():
            logging.warning('{0} does not control {1}.'
                        .format(self.name, element.name))
        elif (self.canSense(contract.demand, element, context)
              and element.senseAndStore(contract)):
            for federate in [federate for federate in self.getFederates()
                             if federate.canSense(contract.demand, element, context)]:
                logging.info('{0} sensed and stored data for {1} using {2}'
                            .format(federate.name, contract.name, element.name))
                self.trigger('sense', federate, contract, element)
                return True
        else:
            logging.warning('{0} could not sense and store data for {1} using {2}'
                        .format(self.name, contract.name, element.name))
        return False

    def couldTransport(self, protocol, data, txElement,
                       rxElement, txLocation, rxLocation, context):
        """
        Checks if this controller could transport data between elements.
        @param protocol: the transmission protocol
        @type protocol: L{str}
        @param data: the data to transport
        @type data: L{Data}
        @param txElement: the transmitting element
        @type txElement: L{Element}
        @param rxElement: the receiving element
        @type rxElement: L{Element}
        @param txLocation: the transmitting location
        @type txLocation: L{Location}
        @param rxLocation: the receiving location
        @type rxLocation: L{Location}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        return (txElement.couldTransmit(protocol, data, rxElement,
                                        txLocation, rxLocation, context)
                and rxElement.couldReceive(protocol, data, txElement,
                                           txLocation, rxLocation, context)
                and ('o' in protocol
                     or next((federate for federate in self.getFederates()
                              if txElement in federate.elements), None)
                     is next((federate for federate in self.getFederates()
                              if rxElement in federate.elements), None)))

    def canTransport(self, protocol, data, txElement, rxElement, context):
        """
        Checks if this controller can transport data between elements.
        @param protocol: the transmission protocol
        @type protocol: L{str}
        @param data: the data to transport
        @type data: L{Data}
        @param txElement: the transmitting element
        @type txElement: L{Element}
        @param rxElement: the receiving element
        @type rxElement: L{Element}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        return (self.couldTransport(protocol, data, txElement, rxElement,
                                    txElement.location, rxElement.location, context)
                and txElement in self.getElements()
                and rxElement in self.getElements()
                and txElement.canTransmit(protocol, data, rxElement, context)
                and rxElement.canReceive(protocol, data, txElement, context))

    def transport(self, protocol, data, txElement, rxElement, context):
        """
        Transports data between elements.
        @param protocol: the transmission protocol
        @type protocol: L{str}
        @param data: the data to transport
        @type data: L{Data}
        @param txElement: the transmitting element
        @type txElement: L{Element}
        @param rxElement: the receiving element
        @type rxElement: L{Element}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        if txElement not in self.getElements():
            logging.warning('{0} does not control {1}.'
                        .format(self.name, txElement.name))
        elif rxElement not in self.getElements():
            logging.warning('{0} does not control {1}.'
                        .format(self.name, rxElement.name))
        elif self.canTransport(protocol, data, txElement, rxElement, context):
            if not txElement.transmit(protocol, data, rxElement, context):
                logging.warning('{0} could not transmit {1} to {2} with {3}'
                             .format(txElement.name, data,
                                     rxElement.name, protocol))
            elif not rxElement.receive(protocol, data, txElement, context):
                logging.warning('{0} could not receive {1} from {2} with {3}'
                             .format(rxElement.name, str(data),
                                     txElement.name, protocol))
            else:
                logging.info('{0} transported {1} from {2} to {3} with {4}'
                            .format(self.name, str(data), txElement.name,
                                    rxElement.name, protocol))
                self.trigger('transport', self, protocol, data, txElement, rxElement)
                return True
        else:
            logging.warning('{0} could not transport {1} between {2} and {3} with {4}'
                         .format(self.name, str(data), txElement.name,
                                 rxElement.name, protocol))
        return False

    def deleteData(self, contract):
        """
        Deletes data for a contract.
        @param contract: the contract
        @type contract: L{Contract}
        """
        for element in self.getElements():
            for module in element.modules:
                for d in module.data[:]:
                    if (d.contract is contract
                        and module.canTransferOut(d)):
                        module.transferOut(d)

    def contract(self, demand, context):
        """
        Contracts a demand.
        @param demand: the demand to contract
        @type demand: L{Demand}
        @param context: the context
        @type context: L{Context}
        @return: L{Contract}
        """
        if self.canContract(demand, context):
            for federate in [federate for federate in self.getFederates()
                             if federate.canContract(demand, context)]:
                context.currentEvents.remove(demand)
                contract = Contract(demand)
                federate.contracts.append(contract)
                logging.info('{0} contracted for {1}'
                            .format(federate.name, demand.name))
                self.trigger('contract', federate, demand)
                return contract
        logging.warning('{0} could not contract for {1}'
                    .format(self.name, demand.name))
        return None

    def resolve(self, contract, context):
        """
        Resolves a contract.
        @param contract: the transmission protocol
        @type contract: L{Contract}
        @param context: the context
        @type context: L{Context}
        @return: L{bool}
        """
        if self.canResolve(contract):
            for federate in [federate for federate in self.getFederates()
                             if federate.canResolve(contract)]:
                element = context.getDataElement(contract)
                value = (contract.getValue()
                         if contract.isCompleted(element.location
                                                 if element is not None
                                                 else None)
                         else contract.demand.getDefaultValue())
                federate.cash += value
                federate.contracts.remove(contract)
                context.pastEvents.append(contract.demand)
                self.deleteData(contract)
                logging.info('{0} resolved {1} for {2} cash'
                            .format(federate.name, contract.name, value))
                self.trigger('resolve', federate, contract, value)
                return True
        logging.warning('{0} could not resolve {1}.'
                    .format(self.name, contract.name))
        return False

    def canExchange(self, amount, debtor, creditor):
        """
        Checks if this federation can exchange cash between federates.
        @param amount: the amount of cash to exchange
        @type amount: L{float}
        @param debtor: the debtor federate
        @type debtor: L{Federate}
        @param creditor: the creditor federate
        @type creditor: L{Federate}
        @return: L{bool}
        """
        return (debtor in self.getFederates()
                and creditor in self.getFederates()
                and amount > debtor.cash)

    def exchange(self, amount, debtor, creditor):
        """
        Exchanges cash between two federates in this federation.
        @param amount: the amount of cash to exchange
        @type amount: L{float}
        @param debtor: the debtor federate
        @type debtor: L{Federate}
        @param creditor: the creditor federate
        @type creditor: L{Federate}
        @return: L{bool}
        """
        if debtor not in self.getFederates():
            logging.warning('{} does not control {}'
                            .format(self.name, debtor.name))
        elif creditor not in self.getFederates():
            logging.warning('{} does not control {}'
                            .format(self.name, creditor.name))
        elif amount > debtor.cash:
            logging.warning('{} exceeds {} cash.'
                            .format(amount, debtor.name))
        elif self.canExchange(amount, debtor, creditor):
            debtor.cash -= amount
            creditor.cash += amount
            logging.info('{} paid {} to {}'
                         .format(debtor.name, amount, creditor.name))
            self.trigger('exchange', self, amount, debtor, creditor)
            return True
        return False


text:
void SetFlagC(bool);
void SetFlagZ(bool);
void SetFlagI(bool);
void SetFlagD(bool);
void SetFlagB(bool);
void SetFlagV(bool);
void SetFlagN(bool);

bool GetFlagC();
bool GetFlagZ();
bool GetFlagI();
bool GetFlagD();
bool GetFlagB();
bool GetFlagV();
bool GetFlagN();

void IncrementPC(uint8_t);
void DecrementPC(uint8_t);
void SetPC(uint16_t);
uint16_t GetPC();


text:
package io.quarkus.kafka.client.runtime.ui.model.request;

public class KafkaCreateTopicRequest {
    private String topicName;
    private Integer partitions;
    private Short replications;

    public KafkaCreateTopicRequest() {
    }

    public KafkaCreateTopicRequest(String topicName, Integer partitions, Short replications) {
        this.topicName = topicName;
        this.partitions = partitions;
        this.replications = replications;
    }

    public String getTopicName() {
        return topicName;
    }

    public Integer getPartitions() {
        return partitions;
    }

    public Short getReplications() {
        return replications;
    }
}


text:
import os

__version__ = 0.2
__author__ = 'Cashiuus'
__license__ = 'MIT'
__copyright__ = 'Copyright (C) 2015 Cashiuus'

# Folders to create in our new system
folders = [
    r'c:\Scripts\backup-windows\Scans',
    r'c:\Scripts\virtualenvs',
    r'c:\Tools',
    ]

#

PIP_CORE_PACKAGES = [
    'beautifulsoup4',
    'colorama',
    'mechanize',
    'Pillow',
    'scrapy',
    'requests',
    'twitter-photos',
    'virtualenv',
    'virtualenvwrapper-win',
    'xlrd',
    'xlwt',
]

# These don't install via pip, typically you download them and manually install
# via: pip install somepackage-1.0.whl
PYTHON_SPECIAL_PACKAGES = [
    # lxml you can install via pip only if you are using 32-bit python, we ues 64-bit so it's in this group
    'lxml',
    'numpy',
    'pywin32',
]

# This is for virtualenvwrapper-win
# TODO: removed scrapy from my pip installs because it has a TON of dependencies. Only install it if actually needed.
CUSTOM_VIRTUALENV_SCRIPTS = os.path.join()
POSTMKVIRTUALENV_SCRIPT = """# Postmkvirtualenv creation script
pip install beautifulsoup4
pip install pep8
pip install requests
"""

DJANGO_REQUIREMENTS = """cookiecutter
django
django-debug-toolbar
django-environ
django-extensions
django-import-export
django-secure
psycopg2
pygraphviz
six
"""

# -----------------------------------------------------------------------------
#                               Begin Setup
# =============================================================================
def create_file(path):
    # Use os.open to create a file if it doesn't already exist
    flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
    try:
        file_handle = os.open(path, flags)
    except OSError as e:
        if e.errno == errno.EEXIST:
            # The file already exists
            pass
            return False
        else:
            # Something went wrong, troubleshoot error
            raise
    else:
        # No exception, so file was hopefully created.
        with os.fdopen(file_handle, 'w') as file_obj:
            file_obj.write("### Log File")
        return True

def make_dirs(path):
    """
    Helper function to make all directories necessary in the desired path
    """
    if not os.path.isdir(path):
        try:
            os.makedirs(path)
        except:
            print("[-] Error creating folder: {}".format(str(path)))
    return

def create_folders():
    # Create folder structure
    for i in folders:
        try:
            os.mkdir(i)
        except:
            print("[-] Error creating folders")
    return

# ==========================[ Python 2.7 ]=========================== #

def install_python2(PKGS):
    PY2_INSTALL_PATH = r'C:\Python27\'

    # Python 2.7 method
    os.system('python -m pip install --upgrade pip')

    # Install all of our core PIP packages
    for i in PKGS:
        # TODO: Fix this command call
        print('[*] Installing via pip: {}'.format(i))
        os.system('py -3 -m pip install', i)
        # pip freeze
        # pip list --outdated

    return

# ----------------[ Setup a virtualenvwrapper-win package ]-------------------------- #
# This assumes virtualenvwrapper-win was already installed
# Default virtualenvwrapper envs will be at %WORKON_HOME%
# Default WORKON_HOME var is set to %USERPROFILE%\Envs

# To run some commands after mkvirtualenv you can use hooks.
# First you need to define VIRTUALENVWRAPPER_HOOK_DIR variable.
# If it is set mkvirtualenv will run postmkvirtualenv.bat script from that directory.

# Setup a post-creation script for all new virtualenvs

# Create a virtualenv for python 2.7
mkvirtualenv py27

# TODO: not sure what this is atm
""""# Pyinstaller.bat
@echo
off
python
Configure.py
python
Makespec.py - -onefile - -noconsole
pybd.py
python
Build.py
shellshell.spec
"""

# ==========================[ Python 3.5 ]=========================== #
# Article: https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-windows-10

# Install silently for ALL USERS and add to PATH
# Default install path: C:\Program Files\Python35 or %ProgramFiles%\Python X.Y
# Default install path: %LocalAppData%\Programs\PythonXY
os.chdir('C:\Users\Primary\Downloads')
os.system('python-3.5.2-amd64.exe /quiet InstallAllUsers=1 PrependPath=1')

#PY3_INSTALL_PATH = os.path.join(os.environ('user'), '')
PY3_INSTALL_PATH = r'c:\Program Files\Python35'

# Python 3.5 method
# For an ALL-USERS installation, you need an admin cmd to run this
py -3 -m pip install --upgrade pip

# Install all of our core PIP packages
for i in PIP_PKGS_LIST:
    # TODO: Fix this command call
    print('[*] Installing via pip: {}'.format(i))
    os.system('py -3 -m pip install', i)

# Save original path
#here

# Set new path

# Python 3 path adding
PY3_NEW_PATH = r'c:\Program Files\Python35\;C:\Program Files\Python35\Scripts\;%path%'

# Create a virtualenv
PYVENV_PATH = os.path.join(PY3_INSTALL_PATH, 'Tools', 'scripts')

# This isn't needed, set WORKON_PATH to dir you want to store envs into, default is %USERPROFILE%\Envs
#os.chdir('c:\Scripts\virtualenvs')

ENV_SCRIPT = r'C:\Program Files\Python35\Scripts\mkvirtualenv'
ENV_NAME = 'py35'

# set PYTHONHOME variable so the mkvirtualenv.bat file will skip setting it based on system PATH
# Thereby specifying which interpreter we want for this virtualenv creation
#PYTHONHOME="C:\Program Files\Python35"
# This didn't work - os.environ['PYTHONHOME'] = "C:\Program Files\Python35"

# run ENV_SCRIPT ENV_NAME

# After setting up, restore original PATH
#here

# ================[ Python Startup Activities ]==================
# You can place a file path in env variable PYTHONSTARTUP and it will execute this script when python is launched
# https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH

# Create Django requirements file for use in quickly setting up virtualenvs
f = open("")

# ======================[ Scheduled Tasks ]============================ #
#	1. Python-GetPublicIP - Daily logging of public IP for reference purposes
#	2. Python-BackupFiles - Daily backup to Dropbox

cmds = [
    # Use 'pythonw.exe' to suppress terminal popping up.
    'cmd.exe /c schtasks /Create /F /SC DAILY /ST 11:00 /TN Python-GetPublicIP /TR "pythonw C:\Scripts\backup-windows\getmypublic-ip.py"',
    'cmd.exe /c schtasks /Create /F /SC DAILY /ST 17:00 /TN Python-GetPublicIP /TR "pythonw C:\Scripts\backup-windows\backup-files.py"',
    ]
for i in cmds:
    try:
        os.system(cmds[i])
    except:
        print("[-] Error creating scheduled task")

# Note: Launch a binary and bypass UAC
#	C:\Windows\system32\cpalua.exe -a <binary.exe>

# CCleaner
#"C:\Program Files\CCleaner\CCleaner.exe" $(Arg0)

# -------- [ SysInternals - AccessEnum Scan] ------------ #
os.system("cmd.exe")

# -------- [ SysInternals - Autoruns Scan] ------------ #
os.system("cmd.exe")

# -----------------------------[ MAIN ROUTINE ]------------------------------ #
# =========================================================================== #
def main():
    create_folders()
    install_python2()

    return

if __name__ == '__main__':
    main()

# ----------------------------------[ NOTES ]-------------------------------- #
# =========================================================================== #
# Python INI Customization
# Customization via INI files
# Two .ini files will be searched by the launcher - py.ini in the current user's "application data" directory (i.e. the directory returned by calling the Windows function SHGetFolderPath with CSIDL_LOCAL_APPDATA) and py.ini in the same directory as the launcher. The same .ini files are used for both the 'console' version of the launcher (i.e. py.exe) and for the 'windows' version (i.e. pyw.exe)
#
# Customization specified in the "application directory" will have precedence over the one next to the executable, so a user, who may not have write access to the .ini file next to the launcher, can override commands in that global .ini file)
#For example:
#
#Setting PY_PYTHON=3.1 is equivalent to the INI file containing:
#[defaults]
#python=3.1

#Setting PY_PYTHON=3 and PY_PYTHON3=3.1 is equivalent to the INI file containing:
#[defaults]
#python=3
#python3=3.1

# -=[ pyvenv syntax ]=-
"""
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR             A directory to create the environment in.

optional arguments:
  -h, --help             show this help message and exit
  --system-site-packages Give the virtual environment access to the system
                         site-packages dir.
  --symlinks             Try to use symlinks rather than copies, when symlinks
                         are not the default for the platform.
  --copies               Try to use copies rather than symlinks, even when
                         symlinks are the default for the platform.
  --clear                Delete the contents of the environment directory if it
                         already exists, before environment creation.
  --upgrade              Upgrade the environment directory to use this version
                         of Python, assuming Python has been upgraded in-place.
  --without-pip          Skips installing or upgrading pip in the virtual
                         environment (pip is bootstrapped by default)
"""


text:
import { Component } from '@angular/core';
import { VCLFormFieldSchemaButtonGroup, VCLFormFieldSchemaButtonGroupParams } from '../schemas';
import { FormFieldControl } from './field';

export class FormFieldButtonGroup extends FormFieldControl<VCLFormFieldSchemaButtonGroup, VCLFormFieldSchemaButtonGroupParams> {
  get options()  {
    return this.params.options || [];
  }
  get selectionMode()  {
    return this.params.selectionMode || 'single';
  }
  protected createDefaultValue() {
    return this.selectionMode === 'single' ? null : [];
  }
}

@Component({
  selector: 'vcl-jss-form-button-group',
  template: `
    <vcl-form-control-group *ngIf="field.visible" [errorStateAgent]="field.errorStateAgent">
      <vcl-label *ngIf="!!field.label">{{field.label}}</vcl-label>
      <vcl-button-group [formControl]="field.control" [selectionMode]="field.selectionMode">
        <button vcl-button *ngFor="let option of field.options" [value]="option.value">{{option.label}}</button>
      </vcl-button-group>
      <vcl-jss-form-hints vclHint></vcl-jss-form-hints>
    </vcl-form-control-group>
  `
})
export class FormFieldButtonGroupComponent {
  constructor(public field: FormFieldButtonGroup) { }
}


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.10">
  <compounddef id="main_server_8cpp" kind="file" language="C++">
    <compoundname>mainServer.cpp</compoundname>
    <includes refid="_server_8hpp" local="yes">Server.hpp</includes>
    <incdepgraph>
      <node id="1527">
        boost/thread/mutex.hpp
      </node>
      <node id="1543">
        IGObject.hpp
        <link refid="_i_g_object_8hpp"/>
        <childnode refid="1536" relation="include">
        </childnode>
        <childnode refid="1539" relation="include">
        </childnode>
      </node>
      <node id="1538">
        stdint.h
      </node>
      <node id="1536">
        Enums.hpp
        <link refid="_enums_8hpp"/>
      </node>
      <node id="1537">
        _object.hpp
        <link refid="__object_8hpp"/>
        <childnode refid="1538" relation="include">
        </childnode>
      </node>
      <node id="1528">
        string
      </node>
      <node id="1526">
        boost/thread.hpp
      </node>
      <node id="1542">
        fstream
      </node>
      <node id="1525">
        Server.hpp
        <link refid="_server_8hpp"/>
        <childnode refid="1526" relation="include">
        </childnode>
        <childnode refid="1527" relation="include">
        </childnode>
        <childnode refid="1528" relation="include">
        </childnode>
        <childnode refid="1529" relation="include">
        </childnode>
        <childnode refid="1530" relation="include">
        </childnode>
        <childnode refid="1531" relation="include">
        </childnode>
        <childnode refid="1534" relation="include">
        </childnode>
        <childnode refid="1543" relation="include">
        </childnode>
        <childnode refid="1544" relation="include">
        </childnode>
        <childnode refid="1545" relation="include">
        </childnode>
        <childnode refid="1541" relation="include">
        </childnode>
      </node>
      <node id="1535">
        Map.hpp
        <link refid="_map_8hpp"/>
        <childnode refid="1536" relation="include">
        </childnode>
        <childnode refid="1537" relation="include">
        </childnode>
        <childnode refid="1539" relation="include">
        </childnode>
        <childnode refid="1540" relation="include">
        </childnode>
        <childnode refid="1541" relation="include">
        </childnode>
        <childnode refid="1542" relation="include">
        </childnode>
      </node>
      <node id="1547">
        string.h
      </node>
      <node id="1539">
        _data.hpp
        <link refid="__data_8hpp"/>
        <childnode refid="1538" relation="include">
        </childnode>
        <childnode refid="1530" relation="include">
        </childnode>
      </node>
      <node id="1529">
        stack
      </node>
      <node id="1544">
        SCharacter.hpp
        <link refid="_s_character_8hpp"/>
        <childnode refid="1543" relation="include">
        </childnode>
        <childnode refid="1536" relation="include">
        </childnode>
        <childnode refid="1537" relation="include">
        </childnode>
        <childnode refid="1539" relation="include">
        </childnode>
        <childnode refid="1533" relation="include">
        </childnode>
        <childnode refid="1541" relation="include">
        </childnode>
      </node>
      <node id="1531">
        Connection.hpp
        <link refid="_connection_8hpp"/>
        <childnode refid="1532" relation="include">
        </childnode>
        <childnode refid="1533" relation="include">
        </childnode>
        <childnode refid="1528" relation="include">
        </childnode>
        <childnode refid="1530" relation="include">
        </childnode>
      </node>
      <node id="1540">
        sstream
      </node>
      <node id="1534">
        SMap.hpp
        <link refid="_s_map_8hpp"/>
        <childnode refid="1535" relation="include">
        </childnode>
      </node>
      <node id="1533">
        iostream
      </node>
      <node id="1545">
        Configuration.hpp
        <link refid="_configuration_8hpp"/>
        <childnode refid="1546" relation="include">
        </childnode>
        <childnode refid="1547" relation="include">
        </childnode>
      </node>
      <node id="1541">
        Defines.hpp
        <link refid="_defines_8hpp"/>
      </node>
      <node id="1532">
        enet/enet.h
      </node>
      <node id="1524">
        /home/clemente/projects/Troll-Killers/mainServer.cpp
        <link refid="mainServer.cpp"/>
        <childnode refid="1525" relation="include">
        </childnode>
      </node>
      <node id="1546">
        stdio.h
      </node>
      <node id="1530">
        cstring
      </node>
    </incdepgraph>
      <sectiondef kind="func">
      <memberdef kind="function" id="main_server_8cpp_1ae66f6b31b5ad750f1fe042a706a4e3d4" prot="public" static="no" const="no" explicit="no" inline="no" virt="non-virtual">
        <type>int</type>
        <definition>int main</definition>
        <argsstring>()</argsstring>
        <name>main</name>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/clemente/projects/Troll-Killers/mainServer.cpp" line="3" column="1" bodyfile="/home/clemente/projects/Troll-Killers/mainServer.cpp" bodystart="3" bodyend="6"/>
        <references refid="class_server_1a47beb8398c78f8ce814d8f3961880add" compoundref="_server_8cpp" startline="33" endline="68">Server::main_loop</references>
      </memberdef>
      </sectiondef>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <programlisting>
<codeline lineno="1"><highlight class="preprocessor">#include<sp/>"<ref refid="_server_8hpp" kindref="compound">Server.hpp</ref>"</highlight><highlight class="normal"></highlight></codeline>
<codeline lineno="2"><highlight class="normal"></highlight></codeline>
<codeline lineno="3" refid="main_server_8cpp_1ae66f6b31b5ad750f1fe042a706a4e3d4" refkind="member"><highlight class="normal"></highlight><highlight class="keywordtype">int</highlight><highlight class="normal"><sp/><ref refid="main_server_8cpp_1ae66f6b31b5ad750f1fe042a706a4e3d4" kindref="member">main</ref>(){</highlight></codeline>
<codeline lineno="4"><highlight class="normal"><sp/><sp/><sp/><sp/><ref refid="class_server" kindref="compound">Server</ref><sp/>server;</highlight></codeline>
<codeline lineno="5"><highlight class="normal"><sp/><sp/><sp/><sp/>server.<ref refid="class_server_1a47beb8398c78f8ce814d8f3961880add" kindref="member">main_loop</ref>();</highlight></codeline>
<codeline lineno="6"><highlight class="normal">}</highlight></codeline>
    </programlisting>
    <location file="/home/clemente/projects/Troll-Killers/mainServer.cpp"/>
  </compounddef>
</doxygen>


text:
<?php

namespace Collectif\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ParametersForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    	$builder->add('nomSite', 'text', array('label' => 'Nom du site'));
		$builder->add('proprietaireSite', 'text', array('label' => 'Propriétair du site'));
		$builder->add('adresseSite', 'text', array('label' => 'Adresse'));
		$builder->add('mailSite', 'text', array('label' => 'Email principal'));
		$builder->add('mailDebugger', 'text', array('label' => 'Email Débugger'));
		$builder->add('telephoneSite', 'text', array('label' => 'Tél.'));
		$builder->add('faxSite', 'text', array('label' => 'Fax'));
		//$builder->add('logoSite');
		$builder->add('lienFacebook', 'text', array('label' => 'Facebook'));
		$builder->add('lienTwitter', 'text', array('label' => 'Twitter'));
		$builder->add('contactInfos', 'text', array('label' => 'Adresse mail de contact'));
		$builder->add('debugger', 'checkbox', array('required' => false, 'label' => 'Activer le "Bug tracker"'));

		$builder->add('texteAccueil', 'textarea', array(
				'label' => 'Texte accueil',
				'required'  => false,
				'attr' => array(
						'class' => 'ckeditor'
				)
		));
    }

	public function getName()
	{
		return 'parameters';
	}
}


text:
Create Procedure usp_createRegulation
	@dateFrom char(10),
	@dateTo char(10),
	@percent int,
	@reason nvarchar(255)
As
Begin
	Declare @id nchar(10)

    Set @id = CONVERT(NVARCHAR(50),HashBytes('SHA1', Cast(GETDATE() as varchar(30))), 2)
    Set @id = SUBSTRING(@id, 1, 7)

	Insert Into DieuTietGiaVe(MaDT, NgayBatDau, NgayKetThuc, PhanTram, LyDo)
	Values(@id, Convert(date, @dateFrom, 103), Convert(date, @dateTo, 103), @percent, @reason)
End


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>DMA Friends: DMA\Friends\Classes\API\APIManager Class Reference</title>

<link href="bootstrap3/css/bootstrap.min.css" rel="stylesheet">

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />

DMA Friends
    2.0

Main Page

Related Pages

Namespaces

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

DMA

Friends

Classes

API

APIManager

Public Member Functions |
List of all members

DMA\Friends\Classes\API\APIManager Class Reference

Public Member Functions

 	registerResources (array $resources)

 	registerResource ($url, $resourceClassName)

 	getResources ()

 	getRoutes ($includeNamespaces=false)

 	loadRegisteredResources ()

Member Function Documentation

          DMA\Friends\Classes\API\APIManager::getResources
          (
          	)

Get all register resources

Returns

array

   53     {

   54         $this->loadRegisteredResources();

   55         return $this->resources;

   56     }

DMA\Friends\Classes\API\APIManager\loadRegisteredResources

loadRegisteredResources()

Definition: APIManager.php:105

          DMA\Friends\Classes\API\APIManager::getRoutes
          (

          $includeNamespaces = false	)

Register Laravel routes of each registered resources

Parameters

bool	$includeNamespaces

   63     {

   64         foreach($this->getResources() as $url => $class){

   65             try{

   66                 $resource = App::make($class);

   67

   68                 // Register additional routes first

   69                 if(method_exists($resource, 'getAdditionalRoutes')){

   70                     $extra = $resource->getAdditionalRoutes();

   71                     foreach ($extra as $u => $args) {

   72                         $verbs = $args['verbs'];

   73                         foreach($verbs as $v) {

   74                             Route::{$v}($url . '/' . $u, $class . "@" . $args['handler']);

   75                         }

   76                     }

   77                 }

   78

   79                 if(is_subclass_of($resource, 'DMA\Friends\Classes\API\BaseResource')){

   80                     // Register resource

   81                     Route::resource($url, $class);

   82                 } else if (is_subclass_of($resource, '\Controller')) {

   83                     // Register controller

   84                     Route::controller($url, $class);

   85                 }

   86

   87             }catch(Exception $e){

   88                Log::error("API : Resource endpoint fail to register due to '" . $e->getMessage() . "'");

   89             }

   90         }

   91

   92         // Catch all

   93         Route::any('{all?}', function($path) {

   94             return Response::api()->errorNotFound();

   95         })->where('all', '.+');

   96

   97

   98     }

DMA\Friends\Classes\API\APIManager\getResources

getResources()

Definition: APIManager.php:52

Route

Exception

          DMA\Friends\Classes\API\APIManager::loadRegisteredResources
          (
          	)

Loads registered FriendAPI resources from modules and plugins

Returns

void

  106     {

  107         $plugins = PluginManager::instance()->getPlugins();

  108         foreach ($plugins as $pluginId => $pluginObj) {

  109             $resources = null;

  110             if(method_exists($pluginObj, 'registerFriendAPIResources')) {

  111                 $resources = $pluginObj->registerFriendAPIResources();

  112             }

  113             if (!is_array($resources)) {

  114                 continue;

  115             }

  116

  117             $this->registerResources($resources);

  118         }

  119     }

DMA\Friends\Classes\API\APIManager\registerResources

registerResources(array $resources)

Definition: APIManager.php:32

          DMA\Friends\Classes\API\APIManager::registerResource
          (

          $url,

          $resourceClassName

          )

Register a single API resource

Parameters

string	$url

string	$resourceClassName

   44     {

   45         $this->resources[$url] = $resourceClassName;

   46     }

          DMA\Friends\Classes\API\APIManager::registerResources
          (
          array
          $resources	)

Regiter multiple API Resources using the following array structure:

[ <endpoint_url> => <classname_resource>, <endpoint_url> => <classname_resource>, ...]

eg.

[ 'activity' => 'DMA' ]

   33     {

   34         $this->resources = array_merge($this->resources, $resources);

   35     }

The documentation for this class was generated from the following file:

classes/api/APIManager.php

<address class="footer">
Generated on Fri Jun 26 2015 13:24:10 for DMA Friends by

 1.8.9.1
</address>


text:
const Joi = require('joi')

module.exports = {
  register (req, res, next) {
    const schema = {
      username: Joi.string().alphanum().min(5).max(12),
      password: Joi.string().regex(
        new RegExp('^[a-zA-Z0-9]{8,32}$'))
    }
    const {error} = Joi.validate(req.body, schema)
    if (error) {
      switch (error.details[0].context.key) {
        case 'username':
          res.send({
            error: 'Username must be between 5-12 characters and alphanumeric'
          })
          break
        case 'password':
          res.send({
            error: 'Password must be between 8-32 characters'
          })
      }
    } else {
      next()
    }
  }
}


text:
/*!
This module provides the `Tokenizer` trait and its implementations.
*/
use super::len_while;

/**
This trait is used to tokenise both input strings fed to a `scan*` macro *and* string literals in scan patterns.
*/
pub trait Tokenizer: Eq + ::std::fmt::Show {
	/**
If there is a valid token present at the start of the given string, return its length.  Otherwise, return `None`.  Note that `ScanCursor::pop_token` will automatically turn the next single code point into a token if this method returns `None`.  When implementing this function, you may rely on this behaviour.
	*/
	fn token_len(&self, s: &str) -> Option<uint>;
}

/**
Tokenises a string into words and integers.  Specifically, a word is a sequence of one or more code points which have the `Alphabetic` property; an integer is a sequence of one or more code points which are in the `N*` general category.
*/
#[derive(Clone, Copy, Default, Eq, PartialEq, Show)]
pub struct WordsAndInts;

impl Tokenizer for WordsAndInts {
	fn token_len(&self, s: &str) -> Option<uint> {
		if s.len() == 0 {
			return None;
		}

		let ch0 = s.char_at(0);

		if ch0.is_alphabetic() {
			len_while(s, |ch| ch.is_alphabetic())
		} else if ch0.is_digit(10) {
			len_while(s, |ch| ch.is_digit(10))
		} else {
			None
		}
	}
}

#[test]
fn test_words_and_ints() {
	let tl = |s:&str| WordsAndInts.token_len(s);

	assert_eq!(tl(""), None);
	assert_eq!(tl("_"), None);
	assert_eq!(tl("abc"), Some(3));
	assert_eq!(tl("abc def"), Some(3));
	assert_eq!(tl("abc123"), Some(3));
	assert_eq!(tl("abc_def"), Some(3));
	assert_eq!(tl("123"), Some(3));
	assert_eq!(tl("123 456"), Some(3));
	assert_eq!(tl("123abc"), Some(3));
	assert_eq!(tl("123_456"), Some(3));
	assert_eq!(tl("123.456"), Some(3));
}

/**
Tokenises a string into identifiers and integers.  Specifically, an identifier is a sequence of one code point which is either an underscore or satisfies the `XID_Start` property, followed by zero or more code points which satisfy the `XID_Continue` property; an integer is a sequence of one or more code points which are in the `N*` general category.
*/
#[derive(Clone, Copy, Default, Eq, PartialEq, Show)]
pub struct IdentsAndInts;

impl Tokenizer for IdentsAndInts {
	fn token_len(&self, s: &str) -> Option<uint> {
		if s.len() == 0 {
			return None;
		}

		let ch0 = s.char_at(0);

		if ch0 == '_' || ch0.is_xid_start() {
			len_while(s, |ch| ch.is_xid_continue())
		} else if ch0.is_digit(10) {
			len_while(s, |ch| ch.is_digit(10))
		} else {
			None
		}
	}
}

#[test]
fn test_idents_and_ints() {
	let tl = |s:&str| IdentsAndInts.token_len(s);

	assert_eq!(tl(""), None);
	assert_eq!(tl("_"), Some(1));
	assert_eq!(tl("abc"), Some(3));
	assert_eq!(tl("abc def"), Some(3));
	assert_eq!(tl("abc123"), Some(6));
	assert_eq!(tl("abc_def"), Some(7));
	assert_eq!(tl("123"), Some(3));
	assert_eq!(tl("123abc"), Some(3));
	assert_eq!(tl("_123abc"), Some(7));
	assert_eq!(tl("123 456"), Some(3));
	assert_eq!(tl("123abc"), Some(3));
	assert_eq!(tl("123_456"), Some(3));
	assert_eq!(tl("123.456"), Some(3));
}

/**
Tokenises a string into space-delimited tokens.  Specifically, a token will be a sequence of one or more code points which *do not* satisfy the `White_Space` property.
*/
#[derive(Clone, Copy, Default, Eq, PartialEq, Show)]
pub struct SpaceDelimited;

impl Tokenizer for SpaceDelimited {
	fn token_len(&self, s: &str) -> Option<uint> {
		if s.len() == 0 {
			return None;
		}

		len_while(s, |ch| !ch.is_whitespace())
	}
}

#[test]
fn test_space_delimited() {
	let tl = |s:&str| SpaceDelimited.token_len(s);

	assert_eq!(tl(""), None);
	assert_eq!(tl(" abc"), None);
	assert_eq!(tl("_"), Some(1));
	assert_eq!(tl("abc"), Some(3));
	assert_eq!(tl("abc def"), Some(3));
	assert_eq!(tl("abc123"), Some(6));
	assert_eq!(tl("abc_def"), Some(7));
	assert_eq!(tl("123"), Some(3));
	assert_eq!(tl("123abc"), Some(6));
	assert_eq!(tl("_123abc"), Some(7));
	assert_eq!(tl("123 456"), Some(3));
	assert_eq!(tl("123abc"), Some(6));
	assert_eq!(tl("123_456"), Some(7));
	assert_eq!(tl("123.456"), Some(7));
}

/**
This tokeniser interprets the entire input string as a single token *unless* the input string is empty, in which case it returns `None`.

As a result, this tokeniser is almost totally useless at runtime.  If you *do* use this tokeniser for a pattern, you will almost certainly want to specify a different runtime tokeniser using `#[runtime_tok="..."]`.
*/
#[derive(Clone, Copy, Default, Eq, PartialEq, Show)]
pub struct Explicit;

impl Tokenizer for Explicit {
	fn token_len(&self, s: &str) -> Option<uint> {
		if s.len() == 0 {
			return None;
		}

		Some(s.len())
	}
}

#[test]
fn test_explicit() {
	let tl = |s:&str| Explicit.token_len(s);

	assert_eq!(tl(""), None);
	assert_eq!(tl(" abc"), Some(4));
	assert_eq!(tl("_"), Some(1));
	assert_eq!(tl("abc"), Some(3));
	assert_eq!(tl("abc def"), Some(7));
	assert_eq!(tl("abc123"), Some(6));
	assert_eq!(tl("abc_def"), Some(7));
	assert_eq!(tl("123"), Some(3));
	assert_eq!(tl("123abc"), Some(6));
	assert_eq!(tl("_123abc"), Some(7));
	assert_eq!(tl("123 456"), Some(7));
	assert_eq!(tl("123abc"), Some(6));
	assert_eq!(tl("123_456"), Some(7));
	assert_eq!(tl("123.456"), Some(7));
}


text:
from rh_nexttask.query import Query
from rh_nexttask.querycollector import QueryCollector

def test_creation():
    queries = QueryCollector()
    assert isinstance(queries, QueryCollector)

def test_from_file():
    queries = QueryCollector.from_file('/home/user/Src/sathlan/python-rh-nexttask/tests/fixtures/filter.ini')

    assert len(queries.queries_definition) == 4
    final_query = queries.select('testing')

    assert isinstance(final_query, Query)
#    assert final_query.request() == {}


text:
title: "BeyondCorp: Enterprise Security At Google"
date: '2018-02-18'
tags:
  - google
  - security
slug: beyondcorp-summary
---

A Summary of the BeyordCorp paper.

[BeyondCorp: A New Approach to Enterprise Security](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43231.pdf). Ward & Beyer, USENIX DEC 2014

This paper challenges the idea of [perimeter security](https://en.wikipedia.org/wiki/Perimeter_Security) for corporate networks, and describes the implementation of BeyondCorp as an alternative.

> "Virtually every company today uses firewalls to enforce perimeter security."

The problem here is that everyone inside the perimeter is trusted and everyone outside is not! This is false on two fronts; You can have an intruder internally that is not trusted, and you can have a valid employee working from a coffee shop for example.

> "The perimeter security model works well enough when all employees work exclusively in buildings owned by an enterprise."

The growth of a mobile workforce and cloud services have challenged this perimeter assumption: apps are in public datacenters, and users are working outside the office!

BeyondCorp is a model that only depends on `device` and `user` credentials. Location does not matter.

### The Components of BeyondCorp

This is a diagram of BeyondCorp.

There are 5 major components of BeyondCorp.

#### 1. Identify Device

All devices are stored in a database and then identified using a certificate.

**Device Inventory Database**

Each "managed device" is listed here.

**Device Identity**

Each device has a certificate locally that can authenticate itself against the device inventory database.

#### 2. Identify User

All users and groups are stored in a database, identified using traditional credentials, and then given a SSO token to access some services.

**User/Group Database**

All users/groups are stored here.

**SSO System**

An externalized service that gives SSO tokens to authenticated users.

#### 3. De-Trusting Internal Network

**Unprivileged Network**

"An unprivileged network that very closely resembles
an external network, although within a private address space" is deployed so that internal users do not have special access to services.

**802.1.x Authentication**

Wired and Wireless networks are authenticated w/ 802.1x using the device certificate used for device identity.

#### 4. Externalizing Apps

**Internet Facing Proxy**

All enterprise apps are exposed externally via a proxy that allows access after access control checks.

**Public DNS**

All enterprise apps are exposed externally via CNAME.

#### 5. Inventory-Based Access Control

**Trust Inference for User/Device**

The level of access for a user/device is determined dynamically over time based on device type, location, etc.

**Access Control Engine**

At the proxy level, this engine "provides service-level authorization on a per-request basis". This can also enforce location-based access if needed.

----

This is a much saner policy for a mobile workflow in my opinion. Thanks Google!


text:
function Load-PoolTelemetryForServer {
    param (
    [Parameter(Mandatory=$true)][string]$SubscriptionId, # Azure subscription owning the server from which telemetry will be gathered - see https://portal.azure.com
    [Parameter(Mandatory=$true)][string]$ResourceGroupName, # name of resource group containing the server from which telemetry will be gathered - see https://portal.azure.com
    [Parameter(Mandatory=$true)][string]$ServerName, # name of server from which telemetry will be gathered - e.g. "myappserver"
    [Parameter(Mandatory=$true)][string]$Location, # location of server, e.g. "Australia Southeast"
    [Parameter(Mandatory=$true)][PSCredential]$ServerCred,
    [Parameter(Mandatory=$true)][string]$OutputServerName, # server name of telemetry database, like "telemetryserver"
    [Parameter(Mandatory=$true)][string]$OutputDatabaseName, # telemetry database name, like "telemetrydb"
    [Parameter(Mandatory=$true)][PSCredential]$OutputServerCred,
    [Parameter(Mandatory=$true)][int]$IntervalMinutes, # interval for collection of telemetry
    [Parameter(Mandatory=$true)][int]$DurationMinutes, # total duration for collection of telemetry
    [Parameter(Mandatory=$true)][bool]$loadAllAvailablePoolTelemetry, # indicates if all available telemetry should be loaded on th first pass
    [Parameter(Mandatory=$true)][bool]$IncludeDatabases # indicates if telemetry should be gathered for databases as well as pools
    )

    # Create output database metrics collection tables if it does not already exist.

    $OutputServerCred.Password.MakeReadOnly()
    $sqlCred = new-object ("System.Data.SqlClient.SqlCredential") -ArgumentList $OutputServerCred.UserName, $OutputServerCred.Password

    $outputConnection = New-Object ("System.Data.SqlClient.SqlConnection") "Data Source=$OutputServerName.database.windows.net;Integrated Security=false;Initial Catalog=$OutputDatabaseName"
    $outputConnection.Credential = $sqlCred
    $outputConnection.Open()

    $poolResourceStatsTable = "pool_resource_stats"  # <<< update if a different table name is required
    $dbResourceStatsTable = "db_resource_stats"      # <<< update if a different table name is required

    $sql =`
    "-- Create table for holding collected pool resource stats
    IF  NOT EXISTS (SELECT * FROM sys.objects
    WHERE object_id = OBJECT_ID(N'$($poolResourceStatsTable)') AND type in (N'U'))

    BEGIN
    Create Table $($poolResourceStatsTable) (subscription_guid uniqueidentifier, resource_group_name varchar(128), server_name varchar(128), location varchar(128), elastic_pool_name varchar(128), end_time datetime,
    elastic_pool_DTU_limit int, avg_cpu_percent decimal(5,2), avg_data_io_percent decimal(5,2), avg_log_io_percent decimal(5,2), max_worker_percent decimal(5,2), max_session_percent decimal(5,2)
    , avg_DTU_percent decimal(5,2), avg_storage_percent decimal(5,2), elastic_pool_storage_limit_mb bigint);
    Create Clustered Index ci_endtime ON $($poolResourceStatsTable) (end_time);
    END

    -- Create table for holding collected database resource stats
    IF  NOT EXISTS (SELECT * FROM sys.objects
    WHERE object_id = OBJECT_ID(N'$($dbResourceStatsTable)') AND type in (N'U'))

    BEGIN
    Create Table $($dbResourceStatsTable) (subscription_guid uniqueidentifier, resource_group_name varchar(128),server_name varchar(128), location varchar(128), elastic_pool_name varchar(128), database_name varchar(128), end_time datetime,
    database_DTU_limit int, avg_cpu_percent decimal(5,2), avg_data_io_percent decimal(5,2), avg_log_io_percent decimal(5,2), max_worker_percent decimal(5,2), max_session_percent decimal(5,2), avg_DTU_percent decimal(5,2), db_size float);
    Create Clustered Index ci_endtime ON $($dbResourceStatsTable) (end_time);
    END

    -- Create a function to get aggregated metrics for a given time interval
    IF  NOT EXISTS (SELECT * FROM sys.objects
    WHERE name = N'get_aggregated_pool_metrics' AND type in ('IF'))
    EXEC sp_executesql @Statement = N'
		Create function get_aggregated_pool_metrics(
		@start datetime
		,@end datetime)
		RETURNS TABLE
		AS
		RETURN
		(
			SELECT
				location, server_name, elastic_pool_name
				,avg([avg_dtu_percent]) as avg_eDTU_percent
				,avg([avg_cpu_percent]) as avg_cpu_percent
				,avg([avg_data_io_percent]) as avg_data_io_percent
				,avg([avg_log_io_percent]) as avg_log_io_percent
				,avg([avg_storage_percent]) as avg_storage_percent
				,max([avg_dtu_percent]) as max_of_avg_eDTU_percent
				,max([avg_cpu_percent]) as max_of_avg_cpu_percent
				,max([avg_data_io_percent]) as max_of_data_io_percent
				,max([avg_log_io_percent]) as max_of_avg_log_io_percent
				,max([avg_storage_percent]) as max_of_avg_storage_percent
				,max([max_worker_percent]) as max_workers_percent
				,max([max_session_percent]) as max_session_percent
			FROM [dbo].[pool_resource_stats]
			WHERE end_time between @start and @end
			group by location, server_name, elastic_pool_name
		)'
    "

    $outputServerFullname = $OutputServerName + '.database.windows.net' # assumes server is in Azure SQL Database

    Invoke-Sqlcmd -ServerInstance $outputServerFullName -Database $OutputDatabaseName -Username $OutputServerCred.UserName -Password $OutputServerCred.GetNetworkCredential().Password -Query $sql -ConnectionTimeout 120 -QueryTimeout 120

    $sourceServerFullName = $ServerName + '.database.windows.net'

    $interval = $IntervalMinutes
    $now = [DateTime]::UtcNow
    [DateTime]$startTime = $now.AddMinutes(-$interval) # sets the start time for the first telemetry collection
    [DateTime]$endTime = $now # sets the end time
    [DateTime]$finishTime = $now.AddMinutes($DurationMinutes) # sets the overall finish time for a telemetry collection session

    Write-Host "Starting to collect telemetry for" $ServerName

    $poolLagMinutes = 30  # This accommodates the lag in pool-level metrics being available in the DMV, does not affect per database telemetry

    while($startTime -lt $finishTime)
    {
        if ($loadAllAvailablePoolTelemetry)
        {
            $poolStartTime = $startTime.AddMinutes(-21600) # looks back 15 days to ensure gets all available older data
            $loadAllAvailablePoolTelemetry = $false  # switches flag so this is done once only in the loop
        }
        else
        {
            $poolStartTime = $startTime.AddMinutes(-$poolLagMinutes) # sets the normal start of query window
        }

        $poolEndTime = $endTime.AddMinutes(-$poolLagMinutes) # sets end of query window

        Write-Host "Starting to collect elastic pool telemetry for period" $poolStartTime "to" $poolEndTime "(UTC)"

        # Collect metrics for all elastic pools in this server.
        $sql = `
        "SELECT subscription_guid = CAST ('$($SubscriptionId)' AS uniqueidentifier), resource_group_name = '$($ResourceGroupName)', server_name = '$($ServerName)', location = '$($Location)', elastic_pool_name
        , end_time, elastic_pool_dtu_limit, avg_cpu_percent, avg_data_io_percent, avg_log_write_percent as avg_log_io_percent, max_worker_percent, max_session_percent
        ,(SELECT Max(v) FROM (VALUES (avg_cpu_percent), (avg_data_io_percent), (avg_log_write_percent)) AS value(v)) AS avg_DTU_percent , avg_storage_percent, elastic_pool_storage_limit_mb FROM sys.elastic_pool_resource_stats
        WHERE end_time > '$($poolStartTime)' and end_time <= '$($poolEndTime)';"

        $poolResult = Invoke-Sqlcmd -ServerInstance $sourceServerFullName -Database "master" -Username $ServerCred.UserName -Password $ServerCred.GetNetworkCredential().Password -Query $sql -ConnectionTimeout 120 -QueryTimeout 3600

        if ($poolResult -ne $null)
        {
            #bulk copy the pool telemetry metrics to output database
            $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $outputConnection
            $bulkCopy.BulkCopyTimeout = 600
            $bulkCopy.DestinationTableName = "$poolResourceStatsTable";
            $bulkCopy.WriteToServer($poolResult);

            Write-Host "Elastic pool telemetry loaded for server" $ServerName
        }
        else
        {
            Write-Host "No elastic pool telemetry found for server" $ServerName "for period" $poolStartTime "to" $poolEndTime "(UTC)"
        }

        # gather elastic database telemetry if requested
        if ($IncludeDatabases)
        {
            # Get the list of current elastic databases
            $sql =`
            "select Name, elastic_pool_name from sys.databases as db
            inner join sys.database_service_objectives as dbso on db.database_id = dbso.database_id
            where (dbso.service_objective = 'ElasticPool') and db.Name != 'master'"

            $dbList = Invoke-Sqlcmd -ServerInstance $sourceServerFullName -Database "master" -Username $ServerCred.UserName -Password $ServerCred.GetNetworkCredential().Password -Query $sql -ConnectionTimeout 120 -QueryTimeout 3600

            if ($dbList -ne $null)
            {
                Write-Host $dbList.Count "elastic databases found on server" $ServerName

                # Collect telemetry for each elastic database
                foreach ($db in $dbList)
                {
                    $sql= `
                    "Declare @db_size float;
                    SELECT @db_size = SUM(reserved_page_count) * 8.0/1024/1024 FROM sys.dm_db_partition_stats
                    SELECT subscription_guid = CAST ('$($SubscriptionId)' AS uniqueidentifier), resource_group_name = '$($ResourceGroupName)',server_name = '$($ServerName)', location = '$($Location)', elastic_pool_name = '$($db.elastic_pool_name)'
                    , '$($db.Name)' as database_name, end_time, dtu_limit as database_dtu_limit, avg_cpu_percent, avg_data_io_percent, avg_log_write_percent as avg_log_io_percent, max_worker_percent, max_session_percent
                    ,(SELECT Max(v) FROM (VALUES (avg_cpu_percent), (avg_data_io_percent), (avg_log_write_percent)) AS value(v)) AS avg_DTU_percent ,@db_size as db_size FROM sys.dm_db_resource_stats
                    WHERE end_time > '$($startTime)' and end_time <= '$($endTime)';"

                    $dbResult = Invoke-Sqlcmd -ServerInstance $SourceServerFullName -Database $db.Name -Username $ServerCred.UserName -Password $ServerCred.GetNetworkCredential().Password -Query $sql -ConnectionTimeout 120 -QueryTimeout 3600

                    if ($dbResult -ne $null)
                    {
                        #bulk copy the data to the telemetry database
                        $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $outputConnection
                        $bulkCopy.BulkCopyTimeout = 600
                        $bulkCopy.DestinationTableName = "$dbResourceStatsTable";
                        $bulkCopy.WriteToServer($dbResult);

                        Write-Host "Telemetry loaded for elastic database" $db.Name
                    }
                    else
                    {
                        Write-Host "No telemetry found for elastic database " $db.Name "for period" $startTime "to" $endTime
                    }
                }
            }
            else
            {
                $now = [DateTime]::UtcNow

                Write-Host "No elastic databases found for" $ServerName "when checking at" $now
            }
        }

        Write-Host "Finished collection for server" $ServerName "for period" $startTime "to" $endTime

        # set up time period for next collection
        $startTime = $startTime.AddMinutes($interval)
        $endTime = $endTime.AddMinutes($interval)

        # end if the next period doesn't start before the finish time
        If ($startTime -ge $finishTime) {break}

        Write-Host "Sleeping until" $endTime "(UTC)"

        do
        {
            Start-Sleep 1
        } until (([DateTime]::UtcNow) -ge $endTime)
    }
}


text:
@import XCTest;

static const CGFloat kStandardTimeOut = 60.0;

@interface XCUIElement(KeyboardFocus)
@property (nonatomic, readonly) BOOL flt_hasKeyboardFocus;
@end

@implementation XCUIElement(KeyboardFocus)
- (BOOL)flt_hasKeyboardFocus {
  return [[self valueForKey:@"hasKeyboardFocus"] boolValue];
}
@end

@interface PlatformViewUITests : XCTestCase
@property (strong) XCUIApplication *app;
@end

@implementation PlatformViewUITests

- (void)setUp {
  [super setUp];
  self.continueAfterFailure = NO;

  self.app = [[XCUIApplication alloc] init];
  [self.app launch];
}

- (void)tearDown {
  [self.app terminate];
  [super tearDown];
}

- (void)testPlatformViewFocus {
  XCUIElement *entranceButton = self.app.buttons[@"platform view focus test"];
  XCTAssertTrue([entranceButton waitForExistenceWithTimeout:kStandardTimeOut], @"The element tree is %@", self.app.debugDescription);
  [entranceButton tap];

  XCUIElement *platformView = self.app.textFields[@"platform_view[0]"];
  XCTAssertTrue([platformView waitForExistenceWithTimeout:kStandardTimeOut]);
  XCUIElement *flutterTextField = self.app.textFields[@"Flutter Text Field"];
  XCTAssertTrue([flutterTextField waitForExistenceWithTimeout:kStandardTimeOut]);

  [flutterTextField tap];
  XCTAssertTrue([self.app.windows.element waitForExistenceWithTimeout:kStandardTimeOut]);
  XCTAssertFalse(platformView.flt_hasKeyboardFocus);
  XCTAssertTrue(flutterTextField.flt_hasKeyboardFocus);

  // Tapping on platformView should unfocus the previously focused flutterTextField
  [platformView tap];
  XCTAssertTrue(platformView.flt_hasKeyboardFocus);
  XCTAssertFalse(flutterTextField.flt_hasKeyboardFocus);
}

@end


text:
Python Flask GA4GH API Blueprints
===
![Version](https://img.shields.io/badge/Version-2015.04.0-read.svg?style=flat) [![Apache license](http://img.shields.io/badge/license-Apache-blue.svg?style=flat)](LICENSE)

The Python Flask GA4GH API Blueprints.


text:
<list model="seller">
    <field name="name"/>
    <field name="code"/>
</list>


text:
function gcp::authenticate () {
  local type="${1//--/}"
  local account
  account=$(gcloud config get-value account 2> /dev/null || :)

  if [[ ${account} ]]; then
    echo "You are already authenticated as ${account}."
    echo "You can reauthenticate with 'taito auth:${taito_target_env:?} --reset'."
    echo
  fi

  if ( [[ ${type} == "" ]] && [[ ! ${account} ]] ) || \
     [[ ${type} == "init" ]] || [[ ${type} == "reset" ]]
  then
    echo "gcloud init"
    echo
    taito::print_note_start
    echo "---------------------------------------------------------------"
    echo "You can select anything as your default GCP project and region."
    echo "Taito CLI will always use the values defined in taito config"
    echo "files instead of the default GCP settings you have selected"
    echo "during authentication."
    echo
    echo "On auth reset, you should always re-initialize the default"
    echo "configuration:"
    echo "[1] Re-initialize this configuration [default] with new settings"
    echo "---------------------------------------------------------------"
    taito::print_note_end
    echo
    echo "Press enter to continue once you have read the message above."
    read -r
    echo "Did you really read the message? Press enter once you have read it."
    read -r
    # TODO run 'gcloud auth revoke ${account}' ?
    (taito::executing_start; gcloud init --console-only)
  fi

  if ( [[ ${type} == "" ]] && [[ ! ${account} ]] ) || \
     [[ ${type} == "login" ]] || [[ ${type} == "reset" ]]
  then
    echo "gcloud auth application-default login"
    # TODO run 'gcloud auth revoke ${account}' ?
    (taito::executing_start; gcloud auth application-default login --no-launch-browser)
  fi

  if [[ ${gcp_kubernetes_enabled:-} != "false" ]] && \
     [[ ${kubernetes_name:-} ]]; then
    if [[ ${type} == "" ]] || \
       [[ ${type} == "cluster" ]] || \
       [[ ${type} == "reset" ]]
    then
      gcp::authenticate_on_kubernetes || (
        echo
        echo "--------------------------------------------------------------------"
        echo "WARNING: Kubernetes authentication failed. Note that Kubernetes"
        echo "authentication failure is OK if the Kubernetes cluster does"
        echo "not exist yet."
        echo "--------------------------------------------------------------------"
      )
    fi
  fi
}

function gcp::authenticate_on_kubernetes () {
  (
    local gopts="--zone ${taito_provider_zone:?}"
    if [[ ${kubernetes_regional:-} == "true" ]]; then
      gopts="--region ${taito_provider_region:?}"
    fi

    taito::executing_start
    gcloud container clusters get-credentials \
      "${kubernetes_name}" \
      --project "${taito_zone:?}" \
      ${gopts}
  )
}

function gcp::db_proxy_start () {
  if [[ ${gcp_db_proxy_enabled:-} != "false" ]]; then
    local database_id
    database_id="${taito_zone:?}:${taito_provider_region:?}:${database_instance:?}"

    echo "BIND ADDRESS: ${taito_db_proxy_bind_address:?}" > "${taito_vout:-}"

    if [[ $1 == "true" ]]; then
      # Run in background
      (
        taito::executing_start
        cloud_sql_proxy \
          "-instances=${database_id}=tcp:${taito_db_proxy_bind_address}:${database_port:?}" \
          &> /tmp/proxy-out.tmp &
      )

      proxy_wait_count=0
      while [[ $proxy_wait_count -le 20 ]] && ! grep "Ready for new connections" /tmp/proxy-out.tmp &> /dev/null; do
        sleep 1
        proxy_wait_count=$(( $proxy_wait_count + 1 ))
      done

      if [[ ${taito_verbose:?} == "true" ]] || [[ ${taito_mode:-} == "ci" ]]; then
        cat /tmp/proxy-out.tmp
      fi

      if ! grep "Ready for new connections" /tmp/proxy-out.tmp &> /dev/null; then
        echo "ERROR: Failed to start db proxy"
        cat /tmp/proxy-out.tmp
        exit 1
      fi
    else
      (
        taito::executing_start
        cloud_sql_proxy \
          "-instances=${database_id}=tcp:${taito_db_proxy_bind_address}:${database_port}"
      )
    fi

  fi
}

function gcp::db_proxy_stop () {
  if [[ ${gcp_db_proxy_enabled:-} != "false" ]]; then
    # kill cloud_sql_proxy
    (taito::executing_start; pgrep cloud_sql_proxy | xargs kill)
  fi
}

function gcp::grant_role () {
  project=$1
  role=$2
  users=$3
  for user in ${users[@]}; do
    gcloud projects add-iam-policy-binding "${project_id}" \
      --member "${user}" --role "${role}"
  done
}

function gcp::ensure_project_exists () {
  local project_id=$1
  local organization_id=$2

  if [[ ${project_id} ]] && \
     ! gcloud projects describe "${project_id}" &> /dev/null
  then
    state_bucket_name="${taito_state_bucket:-}"
    if [[ ${state_bucket_name:-} == "taito_resource_namespace_prefix_sha1sum" ]]; then
      state_bucket_name="${taito_resource_namespace_prefix_sha1sum:-}"
    fi

    echo
    echo "ERROR: Google Cloud project '${project_id}' does not exist."
    echo "DevOps personnel should create the project, including:"
    echo
    echo "- Billing account link"
    echo "- User rights"
    echo "- Storage bucket for Terraform state: ${state_bucket_name}"
    echo
    exit 1

    # TODO: Remove project creation (or implement env variable that allows
    # proejct creation)

    local billing_var="gcp_billing_account_${taito_organization:-}"
    local billing_id=${!billing_var:-$taito_provider_billing_account_id}
    if [[ ! ${billing_id} ]]; then
      echo -e "Enter billing account id for the new Google Cloud project" \
        "'${project_id}':"
      read -r billing_id
    else
      if ! taito::confirm "Create new Google Cloud project '${project_id:?}'?"
      then
        billing_id=
      fi
    fi

    if [[ ${billing_id} ]] && [[ ${#billing_id} -gt 10 ]]; then
      echo
      echo "Creating project ${project_id}"
      gcloud projects create "${project_id:?}" \
        "--organization=${organization_id:-}"

      echo
      echo "Enabling billing for project ${project_id}"
      gcloud beta billing projects link "${project_id:?}" \
        --billing-account "${billing_id}"

      echo
      echo "Setting user rights for project ${project_id}"
      gcp::grant_role "${project_id}" roles/owner \
        "$(taito::print_variable taito_resource_namespace_owners true)"
      gcp::grant_role "${project_id}" roles/editor \
        "$(taito::print_variable taito_resource_namespace_editors true)"
      gcp::grant_role "${project_id}" roles/viewer \
        "$(taito::print_variable taito_resource_namespace_viewers true)"

      if [[ ${taito_state_bucket:-} == "taito_resource_namespace_prefix_sha1sum" ]]; then
        echo
        echo "Creating storage bucket for storing state"
        gsutil mb \
          -p "${taito_resource_namespace_id:?}" \
          -l "${taito_provider_region:?}" \
          "gs://${taito_resource_namespace_prefix_sha1sum:?}"

        # local storage_devs
        # storage_devs=$(
        #   taito::print_variable template_default_project_developers true | \
        #   sed 's/\>/:objectAdmin/g'
        # )
        # if [[ $storage_devs ]]; then
        #   echo
        #   echo "Granting user rights for the storage bucket"
        #   gsutil iam ch ${storage_devs} gs://ex-bucket
        # fi
      fi

      # NOTE: hack for https://github.com/terraform-providers/terraform-provider-google/issues/2605
      if [[ $project_id == "${taito_uptime_namespace_id:-}" ]]; then
        read -t 1 -n 10000 || :
        echo -e "You need to create Stackdriver workspace manually by opening" \
          "Google Project\\n'$project_id' and choosing Monitoring from the menu."
        echo
        echo "Press enter once done."
        read -r
      fi
    else
      exit 130
    fi
  fi
}

function gcp::publish_current_target_assets () {
  if [[ -f ./taitoflag_images_exist ]] || ( \
     [[ ${taito_mode:-} == "ci" ]] && [[ ${ci_exec_build:-} == "false" ]] \
    ); then
    return
  fi

  # TODO: make assets and project buckets + path prefix configurable
  image_tag="${1}"
  if taito::is_current_target_of_type "function"; then
    # Publish function zip package to projects bucket
    # TODO: not tested at all
    source="./tmp/${taito_target:?}.zip"
    dest="gs://${taito_functions_bucket:?}/${taito_functions_path:?}/${image_tag}/${taito_target}.zip"
    options=""
  elif taito::is_current_target_of_type "static_content" &&
       [[ ${taito_cdn_project_path:-} ]] &&
       [[ ${taito_cdn_project_path} != "-" ]]
  then
    # Publish static assets to assets bucket
    source="./tmp/${taito_target}/service"
    dest="gs://${taito_static_assets_bucket:?}/${taito_static_assets_path:?}/${image_tag}/${taito_target}"
    options="-r"
  else
    echo "No need for copying assets to storage bucket"
  fi

  if [[ ${source} ]]; then
    echo "Copying ${taito_target} assets to ${dest}"
    taito::executing_start
    gsutil cp ${options} "${source}" "${dest}"
  fi
}


text:
package com.vikingbrain.nmt.responses.metadatadatabase;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 *
 * @author vikingBrain
 */
@Root(name="video_info", strict=false)
public class ObjectVideoEpisodeInfo {

	//display_path
	//external_subtitles
	//frame_rate
	//original_path
	//release_date
	//subtitles	subtitle

	@Element(name="id")
	private String id;

	@Element(name="path")
	private String path;

	@Element(name="aspect_ratio")
	private String aspectRatio;

	@Element(name="format")
	private String format;

	@Element(name="resolution")
	private String resolution;

	@Element(name="synopsis")
	private String synopsis;

	public final String getId() {
		return id;
	}

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

	public final String getPath() {
		return path;
	}

	public final void setPath(String path) {
		this.path = path;
	}

	public final String getAspectRatio() {
		return aspectRatio;
	}

	public final void setAspectRatio(String aspectRatio) {
		this.aspectRatio = aspectRatio;
	}

	public final String getFormat() {
		return format;
	}

	public final void setFormat(String format) {
		this.format = format;
	}

	public final String getResolution() {
		return resolution;
	}

	public final void setResolution(String resolution) {
		this.resolution = resolution;
	}

	public final String getSynopsis() {
		return synopsis;
	}

	public final void setSynopsis(String synopsis) {
		this.synopsis = synopsis;
	}

	@Override
	public String toString() {
		return "ObjectVideoEpisodeInfo [id=" + id + ", path=" + path
				+ ", aspectRatio=" + aspectRatio + ", format=" + format
				+ ", resolution=" + resolution + ", synopsis=" + synopsis + "]";
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<fest:template xmlns:fest="http://fest.mail.ru" context_name="json">
	<fest:value>json.n1</fest:value><fest:space/><fest:plural select="json.n1">рубль|рубля|рублей</fest:plural>
	<fest:value>json.n2</fest:value><fest:space/><fest:plural select="json.n2">ruble|rubles</fest:plural>|
</fest:template>