text:
#include <QtGui>
#include "finddialog.h"

FindDialog::FindDialog(QWidget *parent)
    : QDialog(parent)
{
    QLabel *findLabel = new QLabel(tr("Enter the name of a contact:"));
    lineEdit = new QLineEdit;

    findButton = new QPushButton(tr("&Find"));
    findText = "";

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(findLabel);
    layout->addWidget(lineEdit);
    layout->addWidget(findButton);

    setLayout(layout);
    setWindowTitle(tr("Find a Contact"));
    connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked()));
    connect(findButton, SIGNAL(clicked()), this, SLOT(accept()));
}

void FindDialog::findClicked()
{
    QString text = lineEdit->text();

    if (text.isEmpty()) {
        QMessageBox::information(this, tr("Empty Field"),
            tr("Please enter a name."));
        return;
    } else {
        findText = text;
        lineEdit->clear();
        hide();
    }
}

QString FindDialog::getFindText()
{
    return findText;
}


text:
package org.apache.activemq.transport.vm;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.jms.Connection;
import junit.framework.TestCase;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.bugs.embedded.ThreadExplorer;
import org.apache.activemq.network.NetworkConnector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VmTransportNetworkBrokerTest extends TestCase {

	private static final Logger LOG = LoggerFactory.getLogger(VmTransportNetworkBrokerTest.class);

    private static final String VM_BROKER_URI =
        "vm://localhost?create=false";

    CountDownLatch started = new CountDownLatch(1);
    CountDownLatch gotConnection = new CountDownLatch(1);

    public void testNoThreadLeak() throws Exception {

        // with VMConnection and simple discovery network connector
        int originalThreadCount = Thread.activeCount();
        LOG.debug(ThreadExplorer.show("threads at beginning"));

        BrokerService broker = new BrokerService();
        broker.setDedicatedTaskRunner(true);
        broker.setPersistent(false);
        broker.addConnector("tcp://localhost:61616");
        NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://wrongHostname1:61617,tcp://wrongHostname2:61618)?useExponentialBackOff=false");
        networkConnector.setDuplex(true);
        broker.start();

        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(new URI(VM_BROKER_URI));
        Connection connection = cf.createConnection("system", "manager");
        connection.start();

        // let it settle
        TimeUnit.SECONDS.sleep(5);

        int threadCountAfterStart = Thread.activeCount();
        TimeUnit.SECONDS.sleep(30);
        int threadCountAfterSleep = Thread.activeCount();

        assertTrue("Threads are leaking: " + ThreadExplorer.show("active sleep") + ", threadCount=" +threadCountAfterStart + " threadCountAfterSleep=" + threadCountAfterSleep,
                threadCountAfterSleep < threadCountAfterStart + 8);

        connection.close();
        broker.stop();
        broker.waitUntilStopped();

        // testNoDanglingThreadsAfterStop with tcp transport
        broker = new BrokerService();
        broker.setSchedulerSupport(true);
        broker.setDedicatedTaskRunner(true);
        broker.setPersistent(false);
        broker.addConnector("tcp://localhost:61616?wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000");
        broker.start();

        cf = new ActiveMQConnectionFactory("tcp://localhost:61616?wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000");
        connection = cf.createConnection("system", "manager");
        connection.start();
        connection.close();
        broker.stop();
        broker.waitUntilStopped();

        // let it settle
        TimeUnit.SECONDS.sleep(5);

        // get final threads but filter out any daemon threads that the JVM may have created.
        Thread[] threads = filterDaemonThreads(ThreadExplorer.listThreads());
        int threadCountAfterStop = threads.length;

        // lets see the thread counts at INFO level so they are always in the test log
        LOG.info(ThreadExplorer.show("active after stop"));
        LOG.info("originalThreadCount=" + originalThreadCount + " threadCountAfterStop=" + threadCountAfterStop);

        assertTrue("Threads are leaking: " +
        		ThreadExplorer.show("active after stop") +
        		". originalThreadCount=" +
        		originalThreadCount +
        		" threadCountAfterStop=" +
        		threadCountAfterStop,
            threadCountAfterStop <= originalThreadCount);
    }

    /**
     * Filters any daemon threads from the thread list.
     *
     * Thread counts before and after the test should ideally be equal.
     * However there is no guarantee that the JVM does not create any
     * additional threads itself.
     * E.g. on Mac OSX there is a JVM internal thread called
     * "Poller SunPKCS11-Darwin" created after the test go started and
     * under the main thread group.
     * When debugging tests in Eclipse another so called "Reader" thread
     * is created by Eclipse.
     * So we cannot assume that the JVM does not create additional threads
     * during the test. However for the time being we assume that any such
     * additionally created threads are daemon threads.
     *
     * @param threads - the array of threads to parse
     * @return a new array with any daemon threads removed
     */
    public Thread[] filterDaemonThreads(Thread[] threads) throws Exception {

    	List<Thread> threadList = new ArrayList<Thread>(Arrays.asList(threads));

    	// Can't use an Iterator as it would raise a
    	// ConcurrentModificationException when trying to remove an element
    	// from the list, so using standard walk through
    	for (int i = 0 ; i < threadList.size(); i++) {

    		Thread thread = threadList.get(i);
    		LOG.debug("Inspecting thread " + thread.getName());
    		if (thread.isDaemon()) {
    			LOG.debug("Removing deamon thread.");
    			threadList.remove(thread);
    			Thread.sleep(100);

    		}
    	}
    	LOG.debug("Converting list back to Array");
    	return threadList.toArray(new Thread[0]);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author: George Mathew (george2@ncsu.edu)
 */
package storm.starter.trident.octorater.models;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Model Object that holds the Word
 * @author
 *  George Mathew (george2),
 *  Kapil Somani  (kmsomani),
 *	Kumar Utsav	  (kutsav),
 *	Shubham Bhawsinka (sbhawsi)
 */
public class Word implements Serializable {
	/**
	 *
	 */
	private static final long serialVersionUID = 4184505316879531959L;

	private String name;

	private String tag;

	private float score;

	private int docCount;

	private String _id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTag() {
		return tag;
	}

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

	public float getScore() {
		return score;
	}

	public void setScore(float score) {
		this.score = score;
	}

	public String getID() {
		return _id;
	}

	public void setID(String _id){
		this._id = _id;
	}

	public int getDocCount() {
		return docCount;
	}

	public void setDocCount(int docCount) {
		this.docCount = docCount;
	}

	@Override
	public String toString() {
		return "Word [name=" + name + ", tag=" + tag + ", score=" + score + "]";
	}

	/***
	 * Utility method to convert a word object to a hash map
	 * @param word
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map toMap(){
		Map wordMap = new HashMap();
		wordMap.put("name", this.name);
		wordMap.put("tag", this.tag);
		wordMap.put("score", this.score);
		return wordMap;
	}

}


text:
* html .u0_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeesLayout_files/u0_normal.png");
}

* html .u2_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeesLayout_files/u2_normal.png");
}

* html .u4_line {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeesLayout_files/u4_line.png");
}

* html .u5_line {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeesLayout_files/u5_line.png");
}

* html .u9_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftDataMining_files/u18_normal.png");
}

* html .u11_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftDataMining_files/u18_normal.png");
}

* html .u14_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftDataMining_files/u18_normal.png");
}

* html .u20_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftDataProcessing_files/u29_normal.png");
}

* html .u22_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftDataProcessing_files/u29_normal.png");
}

* html .u25_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftDataProcessing_files/u29_normal.png");
}

* html .u28_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftEmployees_files/u28_normal.png");
}

* html .u30_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftEmployees_files/u30_normal.png");
}

* html .u37_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftEmployees_files/u37_normal.png");
}

* html .u39_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftEmployees_files/u37_normal.png");
}

* html .u41_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MLeftEmployees_files/u37_normal.png");
}

* html .u45_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeeSearchBar_files/u45_normal.png");
}

* html .u47_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeeSearchBar_files/u47_normal.png");
}

* html .u49_normal {
    background-image: none;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="MEmployeeSearchBar_files/u49_normal.png");
}


text:
SpeedupRails::Engine.routes.draw do

  resources :results, only: [:show] do
    get 'rubyprof', on: :member
  end
end

SpeedupRails::Engine.automount! if Speedup.automount?


text:
* Added support for FileView Plugin
* Added support for OnChange/UpdateAction

---

A lot of effort has been put into Sublime Rainmeter. If you like it, star the [repository](https://github.com/thatsIch/sublime-rainmeter).


text:
import logging; logger = logging.getLogger("morse." + __name__)

from bge import logic, events, render
import bgl
import blf

from morse.helpers import passive_objects

font_id =0

co = logic.getCurrentController()
keyboard = co.sensors['All_Keys']

scene = logic.getCurrentScene()

windowWidth = render.getWindowWidth()
windowHeight = render.getWindowHeight()

def write():
    """
    Write the name of all active objects on Screen
    """
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, windowWidth, 0, windowHeight)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    cam = scene.active_camera

    for obj in passive_objects.active_objects():
        # test if the object is in the view frustum
        if cam.pointInsideFrustum(obj.worldPosition):
            pos = cam.getScreenPosition(obj)

            blf.size(font_id, int(windowWidth * 0.02), 72)
            # draw a black shadow to increase contrast with white parts
            blf.enable(font_id, blf.SHADOW)
            blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)
            blf.position(font_id, pos[0]*windowWidth, (1 - pos[1])*windowHeight,0)
            blf.draw(font_id, obj.name)

def test(contr):
    """
    Show which objects are interactable
    """
    keylist = keyboard.events

    for key in keylist:
        if key[0] == events.LEFTALTKEY:
            if key[1] == logic.KX_INPUT_JUST_ACTIVATED:
                #show text over all objects
                scene.post_draw.append(write)

            elif key[1] == logic.KX_INPUT_JUST_RELEASED:
                #hide text of all objects
                scene.post_draw.remove(write)


text: g++ -o testllvm -I/usr/include/llvm-3.8 testllvm.cpp


text:
<?xml version="1.0" encoding="utf-8"?>
<LWM2M  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://openmobilealliance.org/tech/profiles/LWM2M.xsd">
    <Object ObjectType="MODefinition">
        <Name>Distance</Name>
        <Description1>This IPSO object should be used to report a distance measurement. It also provides resources for minimum and maximum measured values, as well as the minimum and maximum range that can be measured by the sensor. An example measurement unit is Meters (ucum: m).
        </Description1>
        <ObjectID>3330</ObjectID>
        <ObjectURN>urn:oma:lwm2m:ext:3330</ObjectURN>
        <MultipleInstances>Multiple</MultipleInstances>
        <Mandatory>Optional</Mandatory>
        <Resources>
            <Item ID="5700">
                <Name>Sensor Value</Name>
                <Operations>R</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Mandatory</Mandatory>
                <Type>Float</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units>Defined by "Units" resource.</Units>
                <Description>Last or Current Measured Value from the Sensor</Description>
            </Item>
            <Item ID="5701">
                <Name>Sensor Units</Name>
                <Operations>R</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>String</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units></Units>
                <Description>Measurement Units Definition e.g. "Cel" for Temperature in Celsius</Description>
            </Item>
            <Item ID="5601">
                <Name>Min Measured Value</Name>
                <Operations>R</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>Float</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units>Defined by "Units" resource.</Units>
                <Description>The minimum value measured by the sensor since power ON or reset</Description>
            </Item>
            <Item ID="5602">
                <Name>Max Measured Value</Name>
                <Operations>R</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>Float</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units>Defined by "Units" resource.</Units>
                <Description>The maximum value measured by the sensor since power ON or reset</Description>
            </Item>
            <Item ID="5603">
                <Name>Min Range Value</Name>
                <Operations>R</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>Float</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units>Defined by "Units" resource.</Units>
                <Description>The minimum value that can be measured by the sensor</Description>
            </Item>
            <Item ID="5604">
                <Name>Max Range Value</Name>
                <Operations>R</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>Float</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units>Defined by "Units" resource.</Units>
                <Description>The maximum value that can be measured by the sensor</Description>
            </Item>
            <Item ID="5605">
                <Name>Reset Min and Max Measured Values</Name>
                <Operations>E</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type></Type>
                <RangeEnumeration></RangeEnumeration>
                <Units></Units>
                <Description>Reset the Min and Max Measured Values to Current Value</Description>
            </Item>
            <Item ID="5821">
                <Name>Current Calibration</Name>
                <Operations>RW</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>String</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units></Units>
                <Description>Read or Write the current calibration coefficient</Description>
            </Item>
            <Item ID="5750">
                <Name>Application Type</Name>
                <Operations>RW</Operations>
                <MultipleInstances>Single</MultipleInstances>
                <Mandatory>Optional</Mandatory>
                <Type>String</Type>
                <RangeEnumeration></RangeEnumeration>
                <Units></Units>
                <Description>The application type of the sensor or actuator as a string depending on the use case</Description>
            </Item>
        </Resources>
        <Description2></Description2>
    </Object>
</LWM2M>


text:
WHD - Market Place Install using AWS Cloud Formation Template and AMI
---------------------------------------------------------------------

#Purpose
The primary purpose of the document is to explain the steps involved in moving Web Help Desk to AWS Cloud. This could be first step in exploring the feasibility of moving other products (related and non-related) to AWS Cloud to cut down the build and deploy time for products that are under maintenance.

#Objective
The initial objective was to create an AMI image with preinstalled Web Help desk configured and ready to go with the embedded PostgreSQL. This would be offered only on specific platforms so as to keep the number of AMI to minimum. The second step is to port it to Marketplace using CloudFormation Template stack with the option to use embedded postgreSQL or Amazon RDS.

##Issues
* WHD is currently available on lot of different platforms like CentOS, Linux, Fedora, IoS, Windows. Do we need to build different instances ?
* WHD has strong integration feature with ORION Modules for alerting, how would this be affected.
* WHD requires integration with Exchange Server and Outlook 365 for pulling calendar information and synchronizes lot of other data.
* Licensing related questions
* How can this work with On Premise databases
* Integration with other third party Asset Discovery software

#Options

##Option - 1: Preinstalled AMI

Create a new EC2 Instance preferably Amazon Linux AMI 2016.09.0 (HVM), if you want to use Python, Ruby, Perl, and Java. The repositories include Docker, PHP, MySQL, PostgreSQL, and other packages. Since WHD RPM is already equipped with TomCat and PostgreSQL, I would go with RHEL Linux AMI to start with. This would give you a clean Linux OS and you could install WebHelpDesk for Linux over that. When you create an EC2 install, you will be prompted to create or use a Key Pair which is required to ssh on to the instance remotely. So you would be required to store the private key file so that you can configure SSH terminal like putty to log on to the Console.

Once the EC2 instance is ready for use, copy the WHD Installer RPM for Linux to the EC2 instance using pscp command line (along with putty). You can also use AWS console to upload the RPM file on to S3 bucket. Once the RPM is available for you to install, run the following command to install WHD on the EC2 instance.

```sh
sudo rpm - ihv webhelpdesk-XX.X.X.XXX-1.x86_64.rpm
```

Once WHD is installed, it automatically install TomcatX.X and starts the JVM. All WebHelpDesk related files are under /usr/local/webhelpdesk. To manually start and stop the service you can run

```sh
/usr/local/webhelpdesk/whd start
/usr/local/webhelpdesk/stop
```

The configuration files are stored under /usr/local/webhelpdesk/conf folder. For WHD to update databases, PRIVILEGE_NETWORK attribute in the whd.conf needs to modified accordingly, otherwise you will not be able to performance updates to the WHD database. Restart the whd service using the above command after making changes to the above configuration file. Once this is done, WHD is ready to go. From a browser, type http://publicdns:8081. You will be prompted to selected embedded PostgreSQL database or use external Database. However, with the v1 version of AMI, embedded PostgreSQL database is the preferred option.

####Pros
Ready to go VM, Pre-installed and configured, No scripting or CLI/API knowledge required, No need for Linux knowledge
####Cons

Requires Multiple AMI for each environment, Every release requires pretty much new AMI creating which is tedious, Not possible to change components

##Option - 2: CloudFormation Template

The cloudFormation stack requires building up the instance from ground up. This requires more work but easier to maintain in the long run since it does not come pre-installed with a version of the product (WHD in this case). New version of WHD installer could be uploaded to S3 bucket and the template can be scripted to pull the latest or specific version of installer from the S3 bucket. Template also provides you with the UI to configure different parameters so the instance can be built more dynamically compared to pre-installed AMI. It could also be combined with the pre-built skeleton AMI and still use parameters to launch the instance.
WHD CloudFormation Stack

Resources
========
* WHD Server running on an Amazon Linux EC2 instance (Tomcat X.X)
* WHD Repository running in MySQL RDS instance or Embedded PostgreSQL running on the same server.
* VPC Security Group allowing SSH and HTTPS access to WHD Server
* VPC Security Group allowing WHD Server access to MySQL Repository
* Possible: VPC ID (set on two security groups as parameters)

####Note

The values for the properties will be passed from the template. There are other values required to be configured but they are not mandatory for this step and user will need to configure them after running the application using the Setup menu.
The REST call is a Http post to https://publicdns/helpdesk/WebObjects/Helpdesk.woa/ra/configuration.json?uniqueId={uniqueId}

####Pros

No need to pre-install everything, can change components, parameterize configuration, avoid creating multiple AMI for each release, just few templates specific to OS

####Cons

 Requires CloudFormation CLI/API knowledge, complex to create, requires Scripting knowledge, requires complete product specific knowledge to build resources

####Limitations

CloudFormation template by itself is a work in progress and is not available on all flavors of Linux and across regions. It requires a lot of scripting and coding to achieve conditional and look up features. The cfn bootstrap seems to vary even with in the different flavor of Linux so it is difficult to come up with a standard template to take care of all the scenarios. However, working with Amazon Linux EC2 instance seems to work fine. Inspite of the limitations, it is still a better option compared to pre-installed AMI at this time.


text:
angular.module("umbraco.services")
	.factory("UmbracoPersonalisationGroups.PipelineGroupTranslatorService", function ($http) {

	    var service = {
	        translate: function (definition) {
	            var translation = "";
	            if (definition) {
	                var selectedOrgs = JSON.parse(definition);
	                translation = selectedOrgs.length + " group" + (selectedOrgs.length != 1 ? "s" : "");
            	}
	            return translation;
	        }
	    };

	    return service;
	});


text:
#pragma once

#include "envoy/common/pure.h"
#include "envoy/event/deferred_deletable.h"
#include "envoy/upstream/upstream.h"

namespace Envoy {
namespace ConnectionPool {

/**
 * Controls the behavior of a canceled stream.
 */
enum class CancelPolicy {
  // By default, canceled streams allow a pending connection to complete and become
  // available for a future stream.
  Default,
  // When a stream is canceled, closes a pending connection if there will still be sufficient
  // connections to serve pending streams. CloseExcess is largely useful for callers that never
  // re-use connections (e.g. by closing rather than releasing connections). Using CloseExcess in
  // this situation guarantees that no idle connections will be held open by the conn pool awaiting
  // a connection stream.
  CloseExcess,
};

/**
 * Handle that allows a pending connection or stream to be canceled before it is completed.
 */
class Cancellable {
public:
  virtual ~Cancellable() = default;

  /**
   * Cancel the pending connection or stream.
   * @param cancel_policy a CancelPolicy that controls the behavior of this cancellation.
   */
  virtual void cancel(CancelPolicy cancel_policy) PURE;
};

/**
 * An instance of a generic connection pool.
 */
class Instance {
public:
  virtual ~Instance() = default;

  /**
   * Called when a connection pool has been drained of pending streams, busy connections, and
   * ready connections.
   */
  using DrainedCb = std::function<void()>;

  /**
   * Register a callback that gets called when the connection pool is fully drained. No actual
   * draining is done. The owner of the connection pool is responsible for not creating any
   * new streams.
   */
  virtual void addDrainedCallback(DrainedCb cb) PURE;

  /**
   * Actively drain all existing connection pool connections. This method can be used in cases
   * where the connection pool is not being destroyed, but the caller wishes to make sure that
   * all new streams take place on a new connection. For example, when a health check failure
   * occurs.
   */
  virtual void drainConnections() PURE;

  /**
   * @return Upstream::HostDescriptionConstSharedPtr the host for which connections are pooled.
   */
  virtual Upstream::HostDescriptionConstSharedPtr host() const PURE;

  /**
   * Prefetches an upstream connection, if existing connections do not meet both current and
   * anticipated load.
   *
   * @return true if a connection was prefetched, false otherwise.
   */
  virtual bool maybePrefetch(float prefetch_ratio) PURE;
};

enum class PoolFailureReason {
  // A resource overflowed and policy prevented a new connection from being created.
  Overflow,
  // A local connection failure took place while creating a new connection.
  LocalConnectionFailure,
  // A remote connection failure took place while creating a new connection.
  RemoteConnectionFailure,
  // A timeout occurred while creating a new connection.
  Timeout,
};

} // namespace ConnectionPool
} // namespace Envoy


text:
package TestAPR::finfo;

use strict;
use warnings FATAL => 'all';

use Apache::Test;
use Apache::TestUtil;

use Apache2::RequestRec ();
use Apache2::RequestIO ();

use TestAPRlib::finfo;

use APR::Finfo ();

use Apache2::Const -compile => 'OK';
use APR::Const    -compile => qw(FINFO_NORM);

sub handler {
    my $r = shift;

    my $tests = 1 + TestAPRlib::finfo::num_of_tests();
    plan $r, tests => $tests;

    {
        my $finfo = $r->finfo;
        my $isa = $finfo->isa('APR::Finfo');

        t_debug "\$r->finfo $finfo";
        ok $isa;
    }

    # a test assigning to $r->finfo is in TestAPI::request_rec

    TestAPRlib::finfo::test();

    Apache2::Const::OK;
}

1;


text: <title>can/route</title>


text:
Ovito tutorial
==============

https://www.ovito.org/docs/current/tutorials/marker_particles.html#tutorials-marker-particles


text:
package org.oescript.api;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public interface Extent {

    public Extent connect() throws IOException;
    public Extent disconnect() throws IOException;
    public Txn begin(long dur) throws IOException ;
    public Txn createTxn(Id tid, long exptime, TxnStatus status, Extent extent);

    public Lease writeList(List<String> list) throws IOException;
    public List<String> readList(List<String> templ) throws IOException;
    public List<String> takeList(List<String> templ) throws IOException;

    public Lease writeMap(Map<String, String> map) throws IOException;
    public Map<String,String> readMap(Map<String,String> templ) throws IOException;
    public Map<String,String> takeMap(Map<String,String> templ) throws IOException;

    public Extent setTimeout(long timeout);
    public long getTimeout();

    //ugly, set bytes before calling writeXXX and
    //get bytes after calling read/takeXXX.  remember to
    //setBytes to null when writing with no attachment
    public Extent setAttachment(byte[] bytes);
    public byte[] getAttachment();

    public Extent setLeaseDur(long dur);
    public long getLeaseDur();

    public Extent setCurrentTxn(Txn txn);
    public Txn getCurrentTxn();

    public void setMsgHook(ExtentMsgHook hook);
}


text:
require 'libgeo/formatter/compiler'
require 'libgeo/formatter/evaluator'

module Libgeo

  ##
  # Class: coordinate formatter
  #
  # Compiles sprintf-like patterns and present
  # given Coordinate as a DMS string
  #
  # Example:
  #
  #     coord = Latitude.new(:N, 48, 4, 15.7)
  #     my_format = Formatter.new('%H%d°%2M′')
  #     my_format.format(coord) # => 'N48°04.26306′'
  #
  #
  class Formatter

    ##
    # Source pattern
    #
    attr_reader :pattern

    ##
    # Create new string representing coordinate
    #
    # Params:
    # - coordinate {Latitude|Longitude} source coordinate
    # - evaluator  {Class}               private
    #
    # Returns: {String} formatted string
    #
    def format(coordinate, evaluator=Evaluator)
      evaluator.new(coordinate).instance_eval(expression)
    end

    ##
    # Represent instance as string
    #
    def inspect
      "#<Libgeo::Formatter pattern=(#{pattern})>"
    end
    alias :to_s :inspect
    alias :pretty_inspect :inspect

  private

    attr_reader :expression

    def initialize(pattern)
      @pattern    = pattern.freeze
      @expression = Compiler.new(pattern).compile
      freeze
    end

  end
end


text:
#ifndef TVM_RELAY_ATTRS_NN_H_
#define TVM_RELAY_ATTRS_NN_H_

#include <tvm/attrs.h>
#include <string>

namespace tvm {
namespace relay {

/*! \brief Attributes used in convolution operators */
struct ConvAttrs : public tvm::AttrsNode<ConvAttrs> {
  Array<IndexExpr> strides;
  Array<IndexExpr> padding;
  Array<IndexExpr> dilation;
  int groups;
  IndexExpr channels;
  Array<IndexExpr> kernel_size;
  std::string data_layout;
  std::string weight_layout;
  std::string out_layout;
  DataType out_dtype;

  TVM_DECLARE_ATTRS(ConvAttrs, "relay.attrs.ConvAttrs") {
    TVM_ATTR_FIELD(strides).set_default(Array<IndexExpr>({1, 1}))
        .describe("Specifies the strides of the convolution.");
    TVM_ATTR_FIELD(padding).set_default(Array<IndexExpr>({0, 0}))
        .describe("If padding is non-zero, then the input is implicitly zero-padded"
                  "on both sides for padding number of points");
    TVM_ATTR_FIELD(dilation).set_default(Array<IndexExpr>({1, 1}))
        .describe("Specifies the dilation rate to use for dilated convolution.");
    TVM_ATTR_FIELD(groups).set_default(1)
        .describe("Controls the connections between inputs and outputs."
                  "At groups=1, all inputs are convolved to all outputs."
                  "At groups=2, the operation becomes equivalent to having two convolution"
                  "layers side by side, each seeing half the input channels, and producing"
                  "half the output channels, and both subsequently concatenated.");
    TVM_ATTR_FIELD(channels)
        .describe("The number of output channels in the convolution."
                  " If it is not set, inferred by shape of the weight.")
        .set_default(NullValue<IndexExpr>());
    TVM_ATTR_FIELD(kernel_size)
        .describe("Specifies the dimensions of the convolution window.")
        .set_default(NullValue<Array<IndexExpr> >());
    TVM_ATTR_FIELD(data_layout).set_default("NCHW")
        .describe("Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc."
                  "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                  "dimensions respectively. Convolution is applied on the 'H' and"
                  "'W' dimensions.");
    TVM_ATTR_FIELD(weight_layout).set_default("OIHW")
        .describe("Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc."
                  "'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width"
                  "dimensions respectively.");
    TVM_ATTR_FIELD(out_layout).set_default("__undef__")
        .describe("Dimension ordering of output. Can be 'NCHW', 'NHWC', etc."
                  "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                  "dimensions respectively. Default to be same as input layout.");

    // use 0 bits to indicate none.
    TVM_ATTR_FIELD(out_dtype)
        .set_default(Int(0))
        .describe("Output data type, set to explicit type under mixed precision setting");
  }
};

/*! \brief Attributes used in softmax operators */
struct SoftmaxAttrs : public tvm::AttrsNode<SoftmaxAttrs> {
  int axis;

  TVM_DECLARE_ATTRS(SoftmaxAttrs, "relay.attrs.SoftmaxAttrs") {
      TVM_ATTR_FIELD(axis).set_default(1)
          .describe("The axis to sum over when computing softmax.");
  }
};

/*! \brief Attributes for max pool operator */
struct MaxPool2DAttrs : public tvm::AttrsNode<MaxPool2DAttrs> {
  Array<IndexExpr> pool_size;
  Array<IndexExpr> strides;
  Array<IndexExpr> padding;
  std::string layout;
  bool ceil_mode;

  TVM_DECLARE_ATTRS(MaxPool2DAttrs, "relay.attrs.MaxPool2DAttrs") {
    TVM_ATTR_FIELD(pool_size)
      .describe("Size of the pooling windows.");
    TVM_ATTR_FIELD(strides).set_default(Array<IndexExpr>({1, 1}))
      .describe("Specifies the strides of the convolution.");
    TVM_ATTR_FIELD(padding).set_default(Array<IndexExpr>({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "Padding support both symmetric and asymmetric as"
                "one int : same padding used on all sides"
                "two int : bottom, right will use same padding as top, left"
                "four int : padding width in the order of (top, left, bottom, right)");
    TVM_ATTR_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    TVM_ATTR_FIELD(ceil_mode).set_default(false)
      .describe("When true, will use ceil instead of floor to compute the output shape.");
  }
};

/*! \brief Attributes for avg pool operator */
struct AvgPool2DAttrs : public tvm::AttrsNode<AvgPool2DAttrs> {
  Array<IndexExpr> pool_size;
  Array<IndexExpr> strides;
  Array<IndexExpr> padding;
  std::string layout;
  bool ceil_mode;
  bool count_include_pad;

  TVM_DECLARE_ATTRS(AvgPool2DAttrs, "relay.attrs.AvgPool2DAttrs") {
    TVM_ATTR_FIELD(pool_size)
      .describe("Size of the pooling windows.");
    TVM_ATTR_FIELD(strides).set_default(Array<IndexExpr>({1, 1}))
      .describe("Specifies the strides of the convolution.");
    TVM_ATTR_FIELD(padding).set_default(Array<IndexExpr>({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "Padding support both symmetric and asymmetric as"
                "one int : same padding used on all sides"
                "two int : bottom, right will use same padding as top, left"
                "four int : padding width in the order of (top, left, bottom, right)");
    TVM_ATTR_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    TVM_ATTR_FIELD(ceil_mode).set_default(false)
      .describe("When true, will use ceil instead of floor to compute the output shape.");
    TVM_ATTR_FIELD(count_include_pad).set_default(false)
      .describe("When true, will include padding to compute the average");
  }
};

/*! \brief Attributes for global pool operator */
struct GlobalPool2DAttrs : public tvm::AttrsNode<GlobalPool2DAttrs> {
  std::string layout;

  TVM_DECLARE_ATTRS(GlobalPool2DAttrs, "relay.attrs.GlobalPool2DAttrs") {
    TVM_ATTR_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
  }
};

/*! \brief Attributes for upsampling operator */
struct UpSamplingAttrs : public tvm::AttrsNode<UpSamplingAttrs> {
  int scale;
  std::string layout;
  std::string method;

  TVM_DECLARE_ATTRS(UpSamplingAttrs, "relay.attrs.UpSamplingAttrs") {
    TVM_ATTR_FIELD(scale)
        .describe("Should be true to preserve the values at the corner pixels");
    TVM_ATTR_FIELD(layout).set_default("NCHW")
        .describe("Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc."
                  "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                  "dimensions respectively. Upsampling is applied on the 'H' and"
                  "'W' dimensions.");
    TVM_ATTR_FIELD(method).set_default("NEAREST_NEIGHBOR")
        .describe("Specify the mode to use for scaling."
                  "NEAREST_NEIGHBOR -  Nearest Neighbor"
                  "BILINEAR - Bilinear Interpolation");
  }
};

}  // namespace relay
}  // namespace tvm
#endif  // TVM_RELAY_ATTRS_NN_H_


text:
import Component from 'ember-component';

export default Component.extend({
  showLogoutModal: false,

  actions: {
    openLogoutModal(event) {
      event.preventDefault();
      this.set('showLogoutModal', true);
    }
  }
});


text:
<!DOCTYPE html>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>iCodeHigh</title>

    <meta name="description" content="Official Page of iCodeHigh">
    <meta name="keywords" content="Games, Android, Android Games">
    <meta name="author" content="iCodeHigh">

    <link rel="shortcut icon" href="img/favicon64.png">
    <link rel="apple-touch-icon" href="img/favicon64.png">

    <link rel="stylesheet" href="css/styles.css"/>

We make games

Loading our games...

Our games

©  iCodeHigh Standards


text:
JoppyType
=========

A typing game inspired by Ikarus Proudbottom Teaches Typing.

I started writing this game on 2013-08-31, although ended up getting distracted by other projects.
At some point I intend to continue development, but for now I'll just put a copy of my code up here.


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

namespace Juanagui.Validation
{
    public class Notification : INotification
    {
        private readonly List<NotificationMessage> _notificationMessages = new List<NotificationMessage>();

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<NotificationMessage> GetEnumerator()
        {
            return _notificationMessages.GetEnumerator();
        }

        public string this[string field]
        {
            get { return _notificationMessages.Where(msg => msg.PropertyName.Equals(field)).Select(msg => msg.ErrorMessage).FirstOrDefault(); }
        }

        public void Add(string fieldName, string message)
        {
            _notificationMessages.Add(new NotificationMessage(fieldName, message));
        }

        public Boolean IsValid()
        {
            return !_notificationMessages.Any();
        }

        public override string ToString()
        {

            return String.Join(", ", _notificationMessages.Select(nm => nm.ErrorMessage));
        }
    }
}


text:
<?php
/*
Plugin Name: Amazon Wish List Hack
Plugin URI: http://bililite.com/blog/2010/10/31/hacking-my-way-to-an-amazon-wishlist-widget/
Description: Since Amazon doesn't support getting wishlists anymore, uses screen scraping to grab my wishlist and display it.
Author: Daniel Wachsstock
Version: 2.1
Author URI: http://bililite.com/blog
*/

// Wordpress 2.8 Widget code based on http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/ and http://justcoded.com/article/wordpress-28-multi-widgets/

class Amazon_Wishlist_Hack extends WP_Widget{
	function Amazon_Wishlist_Hack(){
		$this->WP_Widget ('amazonwishlisthack', __('My Amazon Wish List'), array(
		 'description' => 'Screen scraping Amazon Wishlist widget'
		));
	} // constructor
	function widget ($args, $instance){
		extract ($args, EXTR_SKIP);
		extract ($instance, EXTR_SKIP);
		echo $before_widget.$before_title.$title.$after_title;
		echo $this->wishlist($listid, $filter, $tag, $size, $count);
		echo $after_widget;
	} // widget display code
	function update ($new, $old){
		$count = $new['count'];
		if ($count <= 0) $count = 1;
		$new['count'] = $count;
		return array_merge ($old, $new);
	} // options update
	function form ($instance){
		extract ($instance, EXTR_SKIP);
		$this->textElement ('title', 'Title', $title);
		echo '
Items to show <select name="'.$this->get_field_name('count').'">';
		for ($i = 1; $i <= 10; ++$i){
			echo "<option value=\"$i\"";
			if ($i == $count) echo ' selected="selected"';
			echo ">$i</option>";
		}
		echo '</select>
';
		$this->textElement ('listid', 'Wishlist ID', $listid);
		echo '
Filter <select name="'.$this->get_field_name('filter').'">';
		$this->optionElement('all', $filter, 'All Products');
		$this->optionElement('3', $filter, 'Books');
		$this->optionElement('94', $filter, 'DVD');
		$this->optionElement('58', $filter, 'Home Improvement');
		$this->optionElement('206', $filter, 'Jewelry');
		$this->optionElement('82', $filter, 'Kitchen');
		$this->optionElement('31', $filter, 'Toys');
		echo '</select>
';
		$this->textElement ('tag', 'Tag', $tag);
		$this->textElement ('size', 'Image Size', $size);
	} // control form
	function textElement ($index, $text, $value){
		$id = $this->get_field_id($index);
		$name = $this->get_field_name ($index);
		$text = __($text); // localize
		echo "
$text <input name=\"$name\" class=\"widefat\" value=\"$value\" id=\"$id\" />
";
	} // textElement
	function optionElement($value, $filter, $text){
		echo "<option value=\"$value\" ";
		if ($filter == $value) echo 'selected="selected"';
		echo ">$text</option>";
	}  // optionElement

	// see https://github.com/doitlikejustin/amazon-wish-lister for other ways of doing this
	function wishlist($listID, $filter, $tag, $size, $n){
		// the screen scraping
		$ret = "
See the whole list
";
		$items = $this->getwishlistitems($listID, $filter);
		shuffle($items);
		$items = array_slice ($items, 0, $n);
		foreach ($items as $item){
			$link = $this->itemxpath($item, ".//a[starts-with(@id, 'itemName')]")->item(0);
			$href = $link->attributes->getNamedItem('href')->nodeValue;
			if (preg_match ('|/dp/\w+|', $href, $matches)){
				$href = "http://amazon.com$matches[0]?tag=$tag";
			}else{
				$href = "http://amazon.com$href";
			}
			$title = $link->textContent;
			$author = $link->parentNode->nextSibling->textContent;
			if ($size){
				$image = $this->itemxpath($item,"string(.//img[1]/@src)");
				if (preg_match ('|http://ecx.images-amazon.com/images/I/[^.]+|', $image, $matches)){
					$image = $matches[0]."._SL$size.jpg";
				}else{
				$image = "http://ecx.images-amazon.com/images/G/01/x-site/icons/no-img-sm._SL${size}_.jpg";
				}
				$image = "
";
			}
			$ret .= "$image$title
$author

";
		}
		$ret .= "
Shop On Amazon
";
		return $ret;

	} // wishlist
	function getwishlistitems ($listID, $filter, $page=1){
		// ignore parsing warnings
		$wishlistdom = new DOMDocument();
		@$wishlistdom->loadHTMLFile("http://www.amazon.com/gp/registry/wishlist/$listID?disableNav=1&filter=$filter&page=$page");
		$wishlistxpath = new DOMXPath ($wishlistdom);
		$items = iterator_to_array($wishlistxpath->query("//div[starts-with(@id,'item_')]"));
		if ($wishlistxpath->evaluate("count(//li[@class='a-last'])")) { // this is the "Next->" button
			$items = array_merge($items, $this->getwishlistitems($listID, $filter, $page+1));
		}
		return $items;
	}
	function itemxpath ($node, $xpath){
		return (new DOMXPath($node->ownerDocument))->evaluate($xpath, $node);
	}
} // class Amazon_Wishlist_Hack

add_action ('widgets_init', create_function('', 'return register_widget("Amazon_Wishlist_Hack");'));
?>


text:
#ifndef _VIA_MEMMGR_H_
#define _VIA_MEMMGR_H_

#include <sys/mman.h>
#include "xf86.h"

#define TTM_PL_FLAG_SYSTEM	1
#define TTM_PL_FLAG_TT		2
#define TTM_PL_FLAG_VRAM	4

struct buffer_object {
    off_t           map_offset;
    unsigned long   handle;
    unsigned long   offset;             /* Offset into fb */
    unsigned long   pitch;
    unsigned long   size;
    void            *ptr;
    int             domain;
};

/* In via_memory.c */
Bool drm_bo_manager_init(ScrnInfoPtr pScrn);

struct buffer_object *
drm_bo_alloc_surface(ScrnInfoPtr pScrn, unsigned int width, unsigned int height,
                    int format, unsigned int alignment, int domain);
struct buffer_object *
drm_bo_alloc(ScrnInfoPtr pScrn, unsigned int size, unsigned int alignment,
                int domain);
void *drm_bo_map(ScrnInfoPtr pScrn, struct buffer_object *obj);
void drm_bo_unmap(ScrnInfoPtr pScrn, struct buffer_object *obj);
void drm_bo_free(ScrnInfoPtr pScrn, struct buffer_object *);

#endif


text:
namespace ConsumingWebServices
{
    public class Story
    {
        public string id { get; set; }

        public string title { get; set; }
    }
}


text:
var apiKey = "AqTGBsziZHIJYYxgivLBf0hVdrAk9mWO5cQcb8Yux8sW5M8c8opEC2lZqKR1ZZXf";

// initialize map when page ready
var map;
var gg = new OpenLayers.Projection("EPSG:4326");
var sm = new OpenLayers.Projection("EPSG:900913");

var init = function (onSelectFeatureFunction) {

    var vector = new OpenLayers.Layer.Vector("Vector Layer", {});

    var sprintersLayer = new OpenLayers.Layer.Vector("Sprinters", {
        styleMap: new OpenLayers.StyleMap({
            externalGraphic: "img/mobile-loc.png",
            graphicOpacity: 1.0,
            graphicWidth: 16,
            graphicHeight: 26,
            graphicYOffset: -26
        })
    });

    var sprinters = getFeatures();
    sprintersLayer.addFeatures(sprinters);

    var selectControl = new OpenLayers.Control.SelectFeature(sprintersLayer, {
        autoActivate:true,
        onSelect: onSelectFeatureFunction});

    var geolocate = new OpenLayers.Control.Geolocate({
        id: 'locate-control',
        geolocationOptions: {
            enableHighAccuracy: false,
            maximumAge: 0,
            timeout: 7000
        }
    });
    // create map
    map = new OpenLayers.Map({
        div: "map",
        theme: null,
        projection: sm,
        numZoomLevels: 18,
        controls: [
            new OpenLayers.Control.Attribution(),
            new OpenLayers.Control.TouchNavigation({
                dragPanOptions: {
                    enableKinetic: true
                }
            }),
            geolocate,
            selectControl
        ],
        layers: [
            new OpenLayers.Layer.OSM("OpenStreetMap", null, {
                transitionEffect: 'resize'
            }),
            new OpenLayers.Layer.Bing({
                key: apiKey,
                type: "Road",
                // custom metadata parameter to request the new map style - only useful
                // before May 1st, 2011
                metadataParams: {
                    mapVersion: "v1"
                },
                name: "Bing Road",
                transitionEffect: 'resize'
            }),
            new OpenLayers.Layer.Bing({
                key: apiKey,
                type: "Aerial",
                name: "Bing Aerial",
                transitionEffect: 'resize'
            }),
            new OpenLayers.Layer.Bing({
                key: apiKey,
                type: "AerialWithLabels",
                name: "Bing Aerial + Labels",
                transitionEffect: 'resize'
            }),
            vector,
            sprintersLayer
        ],
        center: new OpenLayers.LonLat(0, 0),
        zoom: 1
    });

    var style = {
        fillOpacity: 0.1,
        fillColor: '#000',
        strokeColor: '#f00',
        strokeOpacity: 0.6
    };
    geolocate.events.register("locationupdated", this, function(e) {
        vector.removeAllFeatures();
        vector.addFeatures([
            new OpenLayers.Feature.Vector(
                e.point,
                {},
                {
                    graphicName: 'cross',
                    strokeColor: '#f00',
                    strokeWidth: 2,
                    fillOpacity: 0,
                    pointRadius: 10
                }
            ),
            new OpenLayers.Feature.Vector(
                OpenLayers.Geometry.Polygon.createRegularPolygon(
                    new OpenLayers.Geometry.Point(e.point.x, e.point.y),
                    e.position.coords.accuracy / 2,
                    50,
                    0
                ),
                {},
                style
            )
        ]);
        map.zoomToExtent(vector.getDataExtent());
    });

    function getFeatures() {
        var features = {
            "type": "FeatureCollection",
            "features": [
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [1332700, 7906300]},
                    "properties": {"Name": "Igor Tihonov", "Country":"Sweden", "City":"Gothenburg"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [790300, 6573900]},
                    "properties": {"Name": "Marc Jansen", "Country":"Germany", "City":"Bonn"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [568600, 6817300]},
                    "properties": {"Name": "Bart van den Eijnden", "Country":"Netherlands", "City":"Utrecht"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [-7909900, 5215100]},
                    "properties": {"Name": "Christopher Schmidt", "Country":"United States of America", "City":"Boston"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [-937400, 5093200]},
                    "properties": {"Name": "Jorge Gustavo Rocha", "Country":"Portugal", "City":"Braga"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [-355300, 7547800]},
                    "properties": {"Name": "Jennie Fletcher ", "Country":"Scotland", "City":"Edinburgh"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [657068.53608487, 5712321.2472725]},
                    "properties": {"Name": "Bruno Binet ", "Country":"France", "City":"Chambéry"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [667250.8958124, 5668048.6072737]},
                    "properties": {"Name": "Eric Lemoine", "Country":"France", "City":"Theys"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [653518.03606319, 5721118.5122914]},
                    "properties": {"Name": "Antoine Abt", "Country":"France", "City":"La Motte Servolex"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [657985.78042416, 5711862.6251028]},
                    "properties": {"Name": "Pierre Giraud", "Country":"France", "City":"Chambéry"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [742941.93818208, 5861818.9477535]},
                    "properties": {"Name": "Stéphane Brunner", "Country":"Switzerland", "City":"Paudex"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [736082.61064069, 5908165.4649505]},
                    "properties": {"Name": "Frédéric Junod", "Country":"Switzerland", "City":"Montagny-près-Yverdon"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [771595.97057525, 5912284.7041793]},
                    "properties": {"Name": "Cédric Moullet", "Country":"Switzerland", "City":"Payerne"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [744205.23922364, 5861277.319748]},
                    "properties": {"Name": "Benoit Quartier", "Country":"Switzerland", "City":"Lutry"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [1717430.147101, 5954568.7127565]},
                    "properties": {"Name": "Andreas Hocevar", "Country":"Austria", "City":"Graz"}},
                { "type": "Feature", "geometry": {"type": "Point", "coordinates": [-12362007.067301,5729082.2365672]},
                    "properties": {"Name": "Tim Schaub", "Country":"United States of America", "City":"Bozeman"}}
            ]
        };

        var reader = new OpenLayers.Format.GeoJSON();

        return reader.read(features);
    }

};


text:
<?php

	function db_plotter ()
	{
		$user = 'root';

		$db = null;
		try
		{
			$db = new PDO('mysql:host=localhost;dbname=plotter;', $user, '');
		}
		catch(PDOException $e)
		{
			echo 'Connection failed.';
		}

		return $db;
	}

/*----------subject table-------------*/

	function add_subject($edpcode, $subject, $stime, $etime, $days, $room, $units)
	{
		$db = db_plotter();
		$sql = "insert into subject(edpcode, subject, stime, etime, days, room, units) values(?,?,?,?,?,?,?)";
		$st = $db->prepare($sql);
		$st->execute(array($edpcode, $subject, $stime, $etime, $days, $room, $units));
		$db = null;
	}

	function list_subject()
	{
		$db = db_plotter();
		$sql = "select * from subject order by 1 desc";
		$st = $db->prepare($sql);
		$st->execute();
		$rows = $st->fetchAll();
		$db = null;

		return $rows;
	}

	function search_subject($keysearch)
	{
		$keysearch = '%' . $keysearch . '%';
		$db = db_plotter();
		$sql = "select * from subject where edpcode like ? or subject like ? or days like ? or room like ?";
		$st = $db->prepare($sql);
		$st->execute(array($keysearch,$keysearch,$keysearch,$keysearch));
		$rows = $st->fetchAll();
		$db = null;

		return $rows;
	}

	function update_subject($subjNo, $edpcode, $subject, $stime, $etime, $days, $room, $units, $prereq)
	{
		$db = db_plotter();
		$sql = "update subject set edpcode=?, subject=?, stime=?, etime=?, days=?, room=?, units=?, prereq=? where subjNo=?";
		$st = $db->prepare($sql);
		$st->execute(array($edpcode, $subject, $stime, $etime, $days, $room, $units, $prereq, $subjNo));
		$db = null;
	}

	function delete_subject($subjNo)
	{
		$db = db_plotter();
		$sql = "delete from subject where subjNo=?";
		$st = $db->prepare($sql);
		$st->execute(array($subjNo));
		$db = null;
	}

	function find_edpcode($subjNo)
	{
		$db = db_plotter();
		$sql = "select * from subject where subjNo=?";
		$st = $db->prepare($sql);
		$st->execute(array($subjNo));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

	function find_duplicate($edpcode)
	{
		$db = db_plotter();
		$sql = "select * from subject where edpcode=?";
		$st = $db->prepare($sql);
		$st->execute(array($edpcode));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

/*----------student table-------------*/

	function find_student($user)
	{
		$db = db_plotter();
		$sql = "select * from student where studentno = ?";
		$st = $db->prepare($sql);
		$st -> execute(array($user));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

	function search_student($studentid)
	{
		$db = db_plotter();
		$sql = "select * from student where studentid = ?";
		$st = $db->prepare($sql);
		$st -> execute(array($studentid));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

/*----------plotter table-------------*/

	function add_student_plotter ($plottersy, $plottersem, $studentid)
	{
		$db = db_plotter();
		$sql = "insert into plotter(plottersy, plottersem, studentid) values(?,?,?)";
		$st = $db->prepare($sql);
		$st -> execute(array($plottersy, $plottersem, $studentid));
		$db = null;
	}

	function list_student_plotter ()
	{
		$db = db_plotter();
		$sql = "select * from plotter order by status, plotterid ";
		$st = $db->prepare($sql);
		$st -> execute();
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

	function search_student_plotter($keysearch)
	{
		$keysearch = '%' . $keysearch . '%';
		$db = db_plotter();
		$sql = "select * from plotter where studentid like ?";
		$st = $db->prepare($sql);
		$st->execute(array($keysearch));
		$rows = $st->fetchAll();
		$db = null;

		return $rows;
	}

	function pending_student_plotter_subject($status)
	{
		$db = db_plotter();
		$sql = "select * from plotter where status = ?";
		$st = $db->prepare($sql);
		$st ->execute(array($status));
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

	function approved_student_plotter_subject($status)
	{
		$db = db_plotter();
		$sql = "select * from plotter where status = ?";
		$st = $db->prepare($sql);
		$st ->execute(array($status));
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

	function cancel_student_plotter_subject($status,$plotterid)
	{
		$db = db_plotter();
		$sql = "update plotter set status=? where plotterid = ?";
		$st = $db->prepare($sql);
		$st ->execute(array($status, $plotterid));
		$db = null;
	}

	function view_student_approved($status, $studentid)
	{
		$db = db_plotter();
		$sql = "select * from plotter where status = ? and studentid = ?";
		$st = $db->prepare($sql);
		$st->execute(array($status, $studentid));
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

	function view_student_pending($status, $studentid)
	{
		$db = db_plotter();
		$sql = "select * from plotter where status = ? and studentid = ? ";
		$st = $db->prepare($sql);
		$st->execute(array($status, $studentid));
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

	function view_student_existing ($studentid)
	{
		$db = db_plotter();
		$sql = "select * from plotter where plotterid = ?";
		$st = $db->prepare($sql);
		$st->execute(array($studentid));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

	function find_student_existing ($studentid, $status_p)
	{
		$db = db_plotter();
		$sql = "select * from plotter where studentid = ? and status = ?";
		$st = $db->prepare($sql);
		$st->execute(array($studentid, $status_p));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

	function view_student_cancel($status, $studentid)
	{
		$db = db_plotter();
		$sql = "select * from plotter where status = ? and studentid = ?";
		$st = $db->prepare($sql);
		$st->execute(array($status, $studentid));
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

/*----------pltted_subject table-------------*/

	function add_student_plotted_subject ($plotterid,$edpcode)
	{
		$db = db_plotter();
		$sql = "insert into plotted_subject (plotterid, edpcode) values(?,?)";
		$st = $db->prepare($sql);
		$st->execute(array($plotterid,$edpcode));
		$db = null;
	}

	function search_student_plotted_subject ($plotterid, $edpcode)
	{
		$db = db_plotter();
		$sql = "select * from plotted_subject where plotterid = ? and edpcode = ?";
		$st = $db->prepare($sql);
		$st -> execute(array($plotterid, $edpcode));
		$row = $st->fetch();
		$db = null;

		return $row;
	}

	function show_student_plotted_subject ($plotterid)
	{
		$db = db_plotter();
		//$sql = "select edpcode, subject, stime, etime, days, room, units from plotted_subjects, s.subject where plotterid = ? and s.edpcode = ?";
		//$sql = "select * from plotted_subject where plotterid = ?";
		$sql = "select s.edpcode, s.subject, s.stime, s.etime, s.days, s.room, s.units from subject s, plotted_subject p where p.plotterid = ? and s.edpcode = p.edpcode";
		$st = $db->prepare($sql);
		$st->execute(array($plotterid));
		$row = $st->fetchAll();
		$db = null;

		return $row;
	}

	function cancel_student_plotted_subject($plotterid)
	{
		$db = db_plotter();
		$sql = "delete from plotted_subject where plotterid = ?";
		$st = $db->prepare($sql);
		$st->execute(array($plotterid));
		$db = null;
	}

	function delete_student_plotted_subject($edpcode)
	{
		$db = db_plotter();
		$sql = "delete from plotted_subject where edpcode = ?";
		$st = $db->prepare($sql);
		$st->execute(array($edpcode));
		$db = null;
	}

	function update_student_plotted_subject($status,$plotterid)
	{
		$db = db_plotter();
		$sql = "update plotter set status=? where plotterid = ?";
		$st = $db->prepare($sql);
		$st -> execute(array($status,$plotterid));
		$db = null;
	}

?>


text:
package org.callimachusproject.engine.events;

import javax.xml.stream.Location;

/**
 * SPARQL builtin function call.
 *
 * @author James Leigh
 *
 */
public class BuiltInCall extends Expression {
	private String function;

	public BuiltInCall(boolean start, String function, Location location) {
		super(start, location);
		this.function = function;
	}

	public String getFunction() {
		return function;
	}

	public String toString() {
		if (isStart())
			return function + "(";
		return ")";
	}
}


text:
package ch.epfl.perfNetwork.drawers

import scala.scalajs.js.Dynamic.{ global => g }
import ch.epfl.perfNetwork.webapp.Algebra._
import org.scalajs.dom.raw.CanvasRenderingContext2D
import ch.epfl.perfNetwork.jsfacade.HTMLCanvasElement
import ch.epfl.perfNetwork.jsfacade.DOMElement
import scala.scalajs.js
import scala.scalajs.js.Any.fromString
import scala.scalajs.js.Dynamic.{ global => g }

/**
 * @author Thibault Urien
 *
 * Base class forthe object that use canvas to represent some information.
 *
 */
trait Drawer {
  /**
   * @return The id of the canvas on which this object draw.
   */
  val canvasName: String
  /**
   * @return The dimensions in px of the canvas on which this object draw.
   */
  def dimensions: Vec = (canvasElem.width, canvasElem.height)
  val canvasOrig = g.document.getElementById(canvasName)
  val canvasDom = canvasOrig.asInstanceOf[DOMElement]
  val canvasElem = canvasOrig.asInstanceOf[HTMLCanvasElement]
  /**
   *  The CanvasRenderingContext2D used by this object.
   */
  val ctx = canvasElem.getContext("2d").asInstanceOf[CanvasRenderingContext2D]

  /**
   * Fill the canvas with white.
   */
  protected def newFrame = {
    ctx.clearRect(0, 0, canvasElem.width, canvasElem.height)
  }

  /**
   * @param source : The line start in the canavas coordinate system.
   * @param target : The line end in the canavas coordinate system.
   * @param strokeStyle : A CSS color value.
   * @param lineWidth : The width of theline in px.
   *
   * Draw a line in the canvas holded by this object.
   * Change the variables strokeStyle and lineWidth of this canvas.
   */
  protected def drawLine(source: Vec, target: Vec, strokeStyle: String, lineWidth: Int = 1) = {

    ctx.beginPath()
    val from = source
    ctx.moveTo(from.x, from.y)
    val to = target
    ctx.lineTo(to.x, to.y)
    ctx.strokeStyle = strokeStyle
    ctx.lineWidth = lineWidth
    ctx.stroke()
    ctx.closePath()
  }

  /**
   * @param v : The center of the disck in the canavas coordinate system.
   * @param fillStyle : A CSS color value.
   * @param disckRadius : The radius of the disck in px.
   *
   * Draw a disck in canvas holded by this object.
   *  Change the variable fillStyle of this canvas.
   */
  protected def drawDisc(v: Vec, fillStyle: String, disckRadius: Double) =
    {
      ctx.beginPath()
      ctx.moveTo(v.x + disckRadius, v.y)
      ctx.arc(v.x, v.y, disckRadius, 0, 2 * Math.PI)
      ctx.fillStyle = fillStyle
      ctx.fill()
      ctx.closePath()
    }
  /**
   * @param pos : The top left corner of the box in the canavas coordinate system.
   * @param text : A string containing the text that should be displayed.
   * @param windowMaxWidth : The maximum width the widow can reach before splitting the text in shorter lines.
   * @param fontSize : Font size in px
   * @param fontType : Name of the used font
   * @param fontColor : A CSS color value.
   * @param fontEffect : The font-style and font-variant property of a css font
   */
  protected def drawDialogueBox(pos: Vec, text: String, windowMaxWidth: Int, fontSize: Int, fontType: String, fontColor: String = "black", fontEffect: String = "") = {
    val margin = (20.0, 10.0)
    val padding = (10.0, 10.0)
    val fontHWratio = 0.9
    val interline = fontSize * 0.2
    def textLength(text: String, font: String) = {
      ctx.font = font
      ctx.measureText(text).width
    }
    val font = fontEffect + " " + fontSize + "px " + fontType
    val recutText = text
      .split("\n")
      .flatMap {
        line =>
          if (line.length() == 0)
            "" :: Nil
          else {
            val splitedLine = line.split(" ")
            splitedLine.tail.foldLeft(Seq[String](splitedLine.head)) {
              case (buffer, word) =>
                if (textLength(word, font) >= windowMaxWidth) {
                  buffer ++ word.grouped(1 max (windowMaxWidth / fontSize).toInt)
                } else if (textLength(word.length + " " + buffer.last, font) < windowMaxWidth) {
                  buffer.dropRight(1) :+ (buffer.last + " " + word)
                } else
                  buffer :+ word
            }
          }
      }
    val dialogueDim = (recutText.map(textLength(_, font)).max, (recutText.length + 1) * (fontSize + interline)) + margin
    val adjustedPos = (pos min (dimensions - dialogueDim)) max (.0, .0)
    ctx.fillStyle = "#fffAF0"
    ctx.fillRect(adjustedPos.x, adjustedPos.y, dialogueDim.x, dialogueDim.y)
    ctx.strokeStyle = fontColor
    ctx.lineWidth = 1
    ctx.strokeRect(adjustedPos.x, adjustedPos.y, dialogueDim.x, dialogueDim.y)

    recutText.zipWithIndex foreach {
      case (s, i) =>
        ctx.font = fontEffect + " " + fontSize + "px " + font
        ctx.fillStyle = "black"
        ctx.fillText(s, adjustedPos.x + padding.x, adjustedPos.y + padding.y + (i + 1) * (interline + fontSize))
    }
  }
  /**
   * @param s : Any string.
   * @return : An hexadecimal color code taken from the beginning of the hashCode of S.
   * The returned value is not formated as a CSS color, there is no # at the beginning.
   */
  protected def hashStringInColor(s: String) = s.hashCode().toHexString.padTo(6, '0').take(6)

  /**
   * @param color : An hexadecimal color code. Not prefixed with a # or anything else.
   * @param brightnessOffset : How much the brightness must be changed. Negative value make the color darker.
   * @return The hexadecimal color code of the modified color. Not prefixed with a # or anything else.
   */
  protected def changeBrightness(color: String, brightnessOffset: Double) =
    color.grouped(2).map {
      c =>
        val intcolor = Integer.parseInt(c, 16)
        math.round(math.min(math.max(0, intcolor + (intcolor * brightnessOffset)), 255))
          .toHexString
          .reverse
          .padTo(2, '0')
          .reverse

    }.mkString
}


text:
package com.example;

import android.view.View.MeasureSpec;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;

import static org.fest.assertions.api.ANDROID.assertThat;

@RunWith(RobolectricGradleTestRunner.class)
public class SquaredImageViewTest {
  @Test public void heightRespectsWidth() {
    SquaredImageView view = new SquaredImageView(Robolectric.application);

    int width = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
    int height = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);

    view.measure(width, height);

    assertThat(view).hasMeasuredWidth(100);
    assertThat(view).hasMeasuredHeight(100);
  }
}


text:
package eu.ydp.empiria.player.client.module.video;

import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Element;
import com.google.inject.Inject;
import eu.ydp.empiria.player.client.module.core.base.ISimpleModule;
import eu.ydp.empiria.player.client.module.core.base.SimpleModuleBase;
import eu.ydp.empiria.player.client.module.video.presenter.VideoPresenter;
import eu.ydp.gwtutil.client.gin.scopes.module.ModuleScoped;

public class VideoModule extends SimpleModuleBase implements ISimpleModule {

    private final VideoPresenter presenter;

    @Inject
    public VideoModule(@ModuleScoped VideoPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public Widget getView() {
        return presenter.getView();
    }

    @Override
    protected void initModule(Element element) {
        presenter.start();
    }

}


text:
import { describe, it } from 'mocha';
import { assert } from 'chai';
import { sendQuery, sendQueryAndExpect, roleUser, adminUser } from './sendQuery';

let newUser;
let tweetId;
const tweetIdOthers = '583676d3618530145474e352';

function makeUserInput(user) {
  let query = `{`;
  Object.keys(user).forEach(field => {
    query = query + `
    ${field}: "${user[field]}"`;
  });
  query = query + `
  }`;
  return query;
}

function makeTweetInput(tweet, userId) {
  if (tweet.author) {
    return `{
      authorId: "${userId ? userId : tweet.author.id}",
      coauthorsIds: ${tweet.coauthorsIds ? JSON.stringify(tweet.coauthorsIds) : JSON.stringify([])},
      body: "${tweet.body}"
    }`;
  }
  return `{
    body: "${tweet.body}"
  }`;
}

describe('test-5: user with role "user"', () => {

  before(function(done) {
    const expectedUser = {
      email: 'tobias@gmail.com',
      password: 'password',
      username: 'tobkle',
      bio: 'someone',
      role: 'user'
    };
      sendQuery({query: `
              mutation {
                createUser(input: ${makeUserInput(expectedUser)}) {
                  id
                  role
                }
              }
            `,
            userId: adminUser
      })
      .then(result => {
        assert.isNotNull(result.data);
        assert.isNotNull(result.data.createUser);
        assert.isNotNull(result.data.createUser.id);
        assert.equal(result.data.createUser.role, 'user');
        newUser = result.data.createUser.id;
        done();
      })
      .catch(err => {
        console.log(err);
        done();
      });
  });

  describe('on type "user" (part 1)...', () => {

    it('admin user created new user "tobkle" with role "user" for the next tests...', () => {
      assert.isNotNull(newUser);
    });

    it('can not create users', () => {
      const expectedUser = {
        email: 'zol@gmail.com',
        password: 'password',
        username: 'zol',
        bio: 'Maker of apps, product and engineering. Climber. Cyclist. Enthusiast. Product lead',
        role: 'editor'
      };
      return sendQuery({query: `
        mutation {
          createUser(input: ${makeUserInput(expectedUser)}) {
            id
          }
        }
      `,
      userId: newUser
      })
      .then((result) => {
        assert.isNotNull(result.data);
        assert.isNull(result.data.createUser);
      })
    });

    it('can not read other users', () => {
      return sendQueryAndExpect(`
        { user(id: "${adminUser}") { username, bio, role } }
      `, {
          user: null
       },
      newUser)
    });

    it('can read himself without field "role"', () => {
      return sendQueryAndExpect(`
        { user(id: "${newUser}") { username } }
      `, {
          user: {
            username: 'tobkle'
          }
       },
      newUser)
    });

    it('can read himself with field "role"', () => {
      return sendQueryAndExpect(`
        { user(id: "${newUser}") { username, role } }
      `, {
          user: {
            username: 'tobkle',
            role: 'user'
          }
       },
      newUser)
    });

    it('can not update other users', () => {
        const modifiedUser = {
          username: 'zoltan',
          bio: 'Maker of things, I guess',
          role: 'admin'
        };
        return sendQueryAndExpect(`
          mutation {
            updateUser(id: "${adminUser}", input: ${makeUserInput(modifiedUser)}) {
              username
              bio
              role
            }
          }
        `, { updateUser: null },
        newUser)
    });

    it('can update himself', () => {
        const modifiedUser = {
          username: 'tobkle',
          bio: 'Maker of things, I guess',
        };
        return sendQueryAndExpect(`
          mutation {
            updateUser(id: "${newUser}", input: ${makeUserInput(modifiedUser)}) {
              username
              bio
            }
          }
        `, {
            updateUser: {
              username: 'tobkle',
              bio: 'Maker of things, I guess',
            }
         },
        newUser)
    });

    it('can not update his role', () => {
        const modifiedUser = {
          username: 'tobkle',
          bio: 'Maker of things, I guess',
          role: 'admin'
        };
        return sendQueryAndExpect(`
          mutation {
            updateUser(id: "${newUser}", input: ${makeUserInput(modifiedUser)}) {
              username
              bio
              role
            }
          }
        `, {
            updateUser: {
              bio: 'Maker of things, I guess',
              role: 'user',
              username: 'tobkle',
            }
         },
        newUser)
    });

    it('can not delete other users', () => {
        return sendQueryAndExpect(`
          mutation {
            removeUser(id: "${adminUser}")
          }
        `, {
            removeUser: null
         },
        newUser)
    });

  });

  describe('on type "tweet"...', () => {

    let expectedTweet = {
      author: { id: newUser },
      body: 'This is a test tweet of user tobkle',
    };

    const expectedTweetOtherAuthor = {
      author: { id: adminUser },
      body: 'We put our hearts into this talk about a #GraphQL-first workflow and how it helped us build apps fast:',
    };

    const expectedTweetOtherAuthorNoAuthor = {
      author: null,
      body: 'We put our hearts into this talk about a #GraphQL-first workflow and how it helped us build apps fast:',
    };

    const modifiedTweet = {
      body: 'This is a modified test tweet',
    };

    before(function (done) {
      expectedTweet.author.id = newUser;
      sendQuery({ query: `
        mutation {
          createTweet(input: ${makeTweetInput(expectedTweet, newUser)}) {
            id
          }
        }
      `,
      userId: newUser
      })
      .then((result) => {
        assert.isNotNull(result.data);
        assert.isNotNull(result.data.createTweet);
        assert.isNotNull(result.data.createTweet.id);
        tweetId = result.data.createTweet.id;
        done();
      })
      .catch(err => {
        console.log(err);
        done();
      });
    });

    it('can create tweet for himself', () => {
      assert.isNotNull(tweetId);
    });

    it('can not create tweet for other author', () => {
      return sendQueryAndExpect(`
        mutation {
          createTweet(input: ${makeTweetInput(expectedTweetOtherAuthor, adminUser)}) {
            id
          }
        }
        `,
        { createTweet: null },
        newUser);
    });

    it('can read own tweet', () => {
      expectedTweet.author.id = newUser;
      return sendQueryAndExpect(
          `{ tweet(id: "${tweetId}") { author { id } body } }`,
          { tweet: expectedTweet },
          newUser)
    });

    it('can read others tweet', () => {
      return sendQueryAndExpect(
          `{ tweet(id: "${tweetIdOthers}") { author { id } body } }`,
          { tweet: expectedTweetOtherAuthorNoAuthor },
          newUser)
    });

    it('can update own tweet', () => {
      return sendQueryAndExpect(`
          mutation {
            updateTweet(id: "${tweetId}", input: ${makeTweetInput(modifiedTweet, newUser)}) {
              body
            }
          }
        `,
        { updateTweet: modifiedTweet },
        newUser)
    });

    it('can not update others tweet', () => {
      return sendQueryAndExpect(`
          mutation {
            updateTweet(id: "${tweetIdOthers}", input: ${makeTweetInput(modifiedTweet)}) {
              body
            }
          }
        `,
        { updateTweet: null },
        newUser)
    });

    it('can read updated tweet correctly', () => {
      return sendQueryAndExpect(
        `{ tweet(id: "${tweetId}") { body } }`,
        { tweet: modifiedTweet },
        newUser)
    });

    it('can remove own tweet', () => {
      return sendQueryAndExpect(
          `mutation { removeTweet(id: "${tweetId}") }`,
          { removeTweet: true },
          newUser)
    });

    it('can not remove other users tweet', () => {
      return sendQueryAndExpect(
          `mutation { removeTweet(id: "${tweetIdOthers}") }`,
          { removeTweet: null },
          newUser)
    });

    it('can not read removed tweet anymore', () => {
      return sendQueryAndExpect(
          `{ tweet(id: "${tweetId}") { body } }`,
          { tweet: null },
          newUser)
    });

  });

  describe('on type "user" (part 2)...', () => {

    it('can delete himself', () => {
        return sendQueryAndExpect(`
          mutation {
            removeUser(id: "${newUser}")
          }
        `, {
            removeUser: true
         },
        newUser)
    });

    it('user "tobkle" is deleted', () => {
        return sendQueryAndExpect(`
          { user(id: "${newUser}") { username, bio, role } }
        `, {
            user: null
         },
        newUser)
    });

  });

});


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Responsavel_Acao;

class ResponsavelAcaoController extends Controller
{
	function consultar(){
		$responsavel_acao = Responsavel_Acao::all();
		return view ('prestaAcaoRetorna', ['responsavel_acao'=>$responsavel_acao]);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Vita.Entities;

namespace Vita.Modules.Login {

  [Flags]
  public enum LoginModuleOptions {
    None = 0,

    // Hide membership - when user tries to reset password and enters email, do not disclose in api controllers if API is found or not.
    ConcealMembership = 1,

    RequireCaptchaOnNewLogin = 1 << 1,
    AskOldPasswordOnChange = 1 << 3,
    /// <summary>Instructs the system to generate simple temporary passwords, not necessarily strong ones. Example: AB7326 </summary>
    GenerateSimpleTempPasswords = 1 << 4,
    AllowPasswordResetOnSuspended = 1 << 5,

    Default = ConcealMembership | AskOldPasswordOnChange | AllowPasswordResetOnSuspended | GenerateSimpleTempPasswords,
  }

  public class LoginModuleSettings {
    public const int MaxHashSize = 250; //size of string representation of password hash in database

    public readonly LoginModuleOptions Options;
    public string GoogleAuthenticatorIdentityTemplate = "{0}:{1}"; // AppName:username, will be displayed in GoogleAuthenticator app for an account
    public readonly IPasswordHasher PasswordHasher;
    public TimeSpan? PasswordExpirationPeriod;
    public int WarnPasswordExpiresDays = 7;
    public ExtraFactorTypes DefaultPasswordResetFactors = ExtraFactorTypes.Email | ExtraFactorTypes.SecretQuestions;  //default extra factors
    public int MinQuestionsCount = 3; //minimum count of secret questions
    public TimeSpan OneTimePasswordExpiration = TimeSpan.FromHours(24);
    public int MaxFailCount = 5; //max number of failures (wrong pin) after which process is disabled

    public string DefaultEmailFrom = null;

    public Func<ILoginProcess, ILoginExtraFactor, string> PinGenerator = LoginModule.DefaultGeneratePin;  //default generator, replace with your own if you need to
    // Suspend account on multiple failures
    public int SuspendOnFailCount = 3;   // # of incidents to trigger suspension
    public int SuspendOnFailMinutes = 10;

    //Expiration periods for processes
    public TimeSpan PasswordResetTimeWindow = TimeSpan.FromMinutes(5);
    public TimeSpan FactorVerificationTimeWindow = TimeSpan.FromHours(12);
    public TimeSpan MultiFactorLoginTimeWindow = TimeSpan.FromMinutes(2);

    //Password strength
    public IPasswordStrengthChecker PasswordChecker;
    public PasswordStrength RequiredPasswordStrength = PasswordStrength.Medium;

    //Login interceptor - external method to allow login after all had been verified
    public Func<OperationContext, ILogin, LoginAttemptStatus, LoginAttemptStatus> CheckCanLoginFunc;

    // Provided by external code, enables sending messages to users (pwd reset, pins, etc)
    public ILoginMessagingService MessagingService;

    public TimeSpan LoginTokenExpiration = TimeSpan.FromDays(1);

    public LoginModuleSettings(
                 LoginModuleOptions options = LoginModuleOptions.Default,
                 ILoginMessagingService messagingService = null,
                 TimeSpan? passwordExpirationPeriod = null,
                 IPasswordHasher passwordHasher = null,
                 int bcryptWorkFactor = 10) {
      Options = options;
      MessagingService = messagingService;
      PasswordExpirationPeriod = passwordExpirationPeriod;
      PasswordHasher = passwordHasher ?? new BCryptPasswordHasher(bcryptWorkFactor);
    }
  }//class

}//ns


text:
<?xml version="1.0"?>
<ruleset name="Centreon Widget Service Monitoring">
    <description>Custom rules defined by Centreon</description>

    <exclude-pattern>vendor</exclude-pattern>

    <rule ref="PSR12"/>
    <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
        <properties>
            <property name="ignoreBlankLines" value="false"/>
        </properties>
    </rule>

    <rule ref="PSR1.Files.SideEffects.FoundWithSymbols">
        <exclude-pattern>service-monitoring/src</exclude-pattern>
    </rule>
    <rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
        <exclude-pattern>service-monitoring/src</exclude-pattern>
    </rule>
</ruleset>


text:
'use strict';

let _ = require('lodash'),
  bcrypt = require('bcrypt'),
  uuid = require('node-uuid'),
  concerns = require('./concerns'),
  connectors = require('../connectors'),
  support = require('../support'),
  is = require('./validators');

const CONCERNS = {
  encrypted: ['token', 'ssh_key']
};

module.exports = function(sequelize, DataTypes) {
  let { attributes, options } = concerns.extend({
    attributes: {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: null,
        validate: _.merge({ isEmail: true },
          is.unique({ attribute: 'email' })
        )
      },
      password_hash: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: null,
      },
      password: {
        type: DataTypes.VIRTUAL,
        allowNull: false,
        defaultValue: null,

        set: function(password) {
          /*
           * We must ensure to hit password validations first and then
           * that password_hash validations must never fail if the
           * password validations already failed.
           */
          let hash = bcrypt.hashSync(password || '*', 10);

          this.setDataValue('password', password);
          this.setDataValue('password_hash', hash);
        },
        validate: { len: [6, 128] }
      },
      provider: {
        type: DataTypes.STRING,
        allowNull: true,
        defaultValue: null,
      },
      provider_id: {
        type: DataTypes.STRING,
        allowNull: true,
        defaultValue: null,
        unique: true
      },
      encrypted_token: {
        type: DataTypes.TEXT,
        allowNull: true,
        defaultValue: null,
        unique: true
      },
      token_id: {
        type: DataTypes.UUID,
        allowNull: true,
        defaultValue: DataTypes.UUIDV1,
        unique: true
      },
      encrypted_ssh_key: {
        type: DataTypes.TEXT,
        allowNull: true,
        defaultValue: null
      }
    },
    options: {
      instanceMethods: {
        verifyPassword: function(password) {
          return bcrypt.compareSync(password, this.password_hash);
        },
        /* The encoded jwt token includes a unique universal identifier,
         * changing this identifier invalidates the token.
         *
         * This really simplify the token revokation if a user is destroyed
         * (in this case, a deleted user carries its token uuid to
         * programming heaven).
         */
        generateToken: function() {
          this.encryptToken(
            support.token.generate(this.token_id)
          );
        },
        revokeToken: function() {
          this.token_id = uuid.v1();
        },
        getSSHKeyLink: function(options) {
          let criterias = { where: { type: 'ssh_key' } };

          return this.getUserProviderLinks(criterias, options).then(_.first);
        }
      },
      classMethods: {
        associate: function(models) {
          this.hasOne(models.Profile);
          this.hasMany(models.Cluster);
          this.hasMany(models.UserProviderLink);
        }
      },
      hooks: {
        beforeCreate: function(user) {
          user.generateToken();

          return connectors.SSH.generateKey().then(key => {
            user.encryptSshKey(key);
          });
        }
      }
    }
  }, CONCERNS);
  return sequelize.define('User', attributes, options);
};


text:
class TextHud < NSView

  attr_accessor :text, :font_size, :delegate

  def ensure_tracking_area
    if @tracking_area.nil?
      @tracking_area = NSTrackingArea.alloc.initWithRect(NSZeroRect,
                                                         options: NSTrackingInVisibleRect | NSTrackingActiveAlways | NSTrackingMouseEnteredAndExited,
                                                         owner: self,
                                                         userInfo: nil)
    end
  end

  def updateTrackingAreas
    super.tap do
      ensure_tracking_area
      unless trackingAreas.include?(@tracking_area)
        addTrackingArea(@tracking_area)
      end
    end
  end

  def mouseEntered(_)
    self.delegate.hover(self) if self.delegate
  end

  def mouseExited(_)
    self.delegate.out(self) if self.delegate
  end

  def font_size
    @font_size ||= 14
  end

  def text=(value)
    @text = value
    setNeedsDisplay true
  end

  def flash
    if @flash_count == 4
      @flash_count = 0
      @is_flashing = false
      setNeedsDisplay true
      return
    end

    @flash_count ||= 0
    @flash_count += 1
    @is_flashing = true

    Dispatch::Queue.concurrent.after (0.24) do
      Dispatch::Queue.main.async do
        setNeedsDisplay true
        flash
      end
    end
  end

  def drawRect(rect)
    super.tap do
      return if text.nil?

      case Configuration.card_layout
        when :small
          ratio = TrackerLayout::KRowHeight / TrackerLayout::KSmallRowHeight
        when :medium
          ratio = TrackerLayout::KRowHeight / TrackerLayout::KMediumRowHeight
        else
          ratio = 1.0
      end

      stroke = :black.nscolor
      if @is_flashing && @flash_count % 2 == 0
        stroke = :red.nscolor
      end

      size = (font_size / ratio).round
      style = NSMutableParagraphStyle.new
      style.alignment = NSCenterTextAlignment
      name = text.attrd.paragraph_style(style)
               .font('Belwe Bd BT'.nsfont(size))
               .stroke_width(-1.5)
               .stroke_color(stroke)
               .foreground_color(Configuration.count_color)
      name.drawInRect self.bounds,
                      options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesDeviceMetrics

    end
  end
end


text:
package org.apache.bookkeeper.common.coder;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.Charsets;
import com.google.common.base.Utf8;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * A coder that encodes strings in utf-8 format.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class StringUtf8Coder implements Coder<String> {

    /**
     * Get the coder to encode strings in utf-8.
     *
     * @return string coder.
     */
    public static StringUtf8Coder of() {
        return INSTANCE;
    }

    private static final StringUtf8Coder INSTANCE = new StringUtf8Coder();

    @Override
    public void encode(String value, ByteBuf destBuf) {
        destBuf.writeBytes(value.getBytes(UTF_8));
    }

    @Override
    public int getSerializedSize(String value) {
        return Utf8.encodedLength(value);
    }

    @Override
    public String decode(byte[] data) {
        return new String(data, Charsets.UTF_8);
    }

    @Override
    public String decode(ByteBuf data) {
        byte[] bytes = ByteBufUtil.getBytes(data);
        return decode(bytes);
    }
}


text:
<?php
namespace Squid\MySql\Impl\Connectors\Generic;

use lib\DataSet;
use lib\TDBAssert;

use PHPUnit\Framework\TestCase;

class UpsertConnectorTest extends TestCase
{
	use TDBAssert;

	private $table;

	private function subject(array $data = []): UpsertConnector
	{
		$table = DataSet::table(['a', 'b', 'c'], $data);

		$connector = new UpsertConnector();
		$connector
			->setConnector(DataSet::connector())
			->setTable($table);

		DataSet::connector()
			->direct("ALTER TABLE $table ADD PRIMARY KEY (a), CHANGE `a` `a` INT(11) NOT NULL AUTO_INCREMENT")
			->executeDml();

		$this->table = $table;

		return $connector;
	}

	public function test_upsertByKeys_EmptyTable_RowInserted()
	{
		$subject = $this->subject();
		$res = $subject->upsertByKeys(['a'], self::row(1, 2, 3));

		self::assertEquals(1, $res);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByKeys_NoneMatchingRow_NewRowInserted()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertByKeys(['a'], self::row(2, 2, 3));

		self::assertEquals(1, $res);
		self::assertRowCount(2, $this->table);
		self::assertRowCount(1, $this->table, self::row(1, 2, 3));
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByKeys_MatchingRow_RowUpdated()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertByKeys(['a'], self::row(1, 4, 6));

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByKeys_UseSingleStringAsKey()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertByKeys('a', self::row(1, 4, 6));

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertAllByKeys_EmptyTable_RowInserted()
	{
		$subject = $this->subject();
		$res = $subject->upsertAllByKeys(['a'], [self::row(1, 2, 3), self::row(4, 5, 6)]);

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table, self::row(1, 2, 3));
		self::assertRowCount(1, $this->table, self::row(4, 5, 6));
	}

	public function test_upsertAllByKeys_NoneMatchingRow_NewRowInserted()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertAllByKeys(['a'], [self::row(4, 5, 6)]);

		self::assertEquals(1, $res);
		self::assertRowCount(2, $this->table);
		self::assertRowCount(1, $this->table, self::row(1, 2, 3));
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertAllByKeys_MatchingRow_RowUpdated()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertAllByKeys(['a'], [self::row(1, 4, 6)]);

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertAllByKeys_UseSingleStringAsKey()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertAllByKeys('a', [self::row(1, 4, 6)]);

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByValues_EmptyTable_RowInserted()
	{
		$subject = $this->subject();
		$res = $subject->upsertByValues(['b', 'c'], self::row(1, 2, 3));

		self::assertEquals(1, $res);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByValues_NoneMatchingRow_NewRowInserted()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertByValues(['b', 'c'], self::row(2, 2, 3));

		self::assertEquals(1, $res);
		self::assertRowCount(2, $this->table);
		self::assertRowCount(1, $this->table, self::row(1, 2, 3));
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByValues_MatchingRow_RowUpdated()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertByValues(['b', 'c'], self::row(1, 4, 6));

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertByValues_UseSingleStringAsKey()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertByValues('b', self::row(1, 4, 6));

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::row(1, 4, 3));
	}

	public function test_upsertAllByValues_EmptyTable_RowInserted()
	{
		$subject = $this->subject();
		$res = $subject->upsertAllByValues(['b', 'c'], [self::row(1, 2, 3), self::row(4, 5, 6)]);

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table, self::row(1, 2, 3));
		self::assertRowCount(1, $this->table, self::row(4, 5, 6));
	}

	public function test_upsertAllByValues_NoneMatchingRow_NewRowInserted()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertAllByValues(['b', 'c'], [self::row(4, 5, 6)]);

		self::assertEquals(1, $res);
		self::assertRowCount(2, $this->table);
		self::assertRowCount(1, $this->table, self::row(1, 2, 3));
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertAllByValues_MatchingRow_RowUpdated()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertAllByValues(['b', 'c'], [self::row(1, 4, 6)]);

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::$LAST_ROW);
	}

	public function test_upsertAllByValues_UseSingleStringAsKey()
	{
		$subject = $this->subject(self::row(1, 2, 3));
		$res = $subject->upsertAllByValues('b', [self::row(1, 4, 6)]);

		self::assertEquals(2, $res);
		self::assertRowCount(1, $this->table);
		self::assertRowCount(1, $this->table, self::row(1, 4, 3));
	}
}


text:
layout:     post
title:      Tweets
date:       2018-07-26
summary:    These are the tweets for July 26, 2018.
categories:
---