text:
<?php

namespace Buzz\Test\History;

use Buzz\History\Journal;
use Buzz\Message;

class JournalTest extends \PHPUnit_Framework_TestCase
{
    protected $request1;
    protected $request2;
    protected $request3;

    protected $response1;
    protected $response2;
    protected $response3;

    protected function setUp()
    {
        $this->request1 = new Message\Request();
        $this->request1->setContent('request1');
        $this->request2 = new Message\Request();
        $this->request2->setContent('request2');
        $this->request3 = new Message\Request();
        $this->request3->setContent('request3');

        $this->response1 = new Message\Response();
        $this->response1->setContent('response1');
        $this->response2 = new Message\Response();
        $this->response2->setContent('response2');
        $this->response3 = new Message\Response();
        $this->response3->setContent('response3');
    }

    protected function tearDown()
    {
        $this->request1 = null;
        $this->request2 = null;
        $this->request3 = null;

        $this->response1 = null;
        $this->response2 = null;
        $this->response3 = null;
    }

    public function testRecordEnforcesLimit()
    {
        $journal = new Journal();
        $journal->setLimit(2);

        $journal->record($this->request1, $this->response1);
        $journal->record($this->request2, $this->response2);
        $journal->record($this->request3, $this->response3);

        $this->assertEquals(2, count($journal));
    }

    public function testGetLastReturnsTheLastEntry()
    {
        $journal = new Journal();

        $journal->record($this->request1, $this->response1);
        $journal->record($this->request2, $this->response2);

        $this->assertEquals($this->request2, $journal->getLast()->getRequest());

        return $journal;
    }

    /**
     * @depends testGetLastReturnsTheLastEntry
     */
    public function testGetLastRequestReturnsTheLastRequest(Journal $journal)
    {
        $this->assertEquals($this->request2, $journal->getLastRequest());
    }

    /**
     * @depends testGetLastReturnsTheLastEntry
     */
    public function testGetLastResponseReturnsTheLastResponse(Journal $journal)
    {
        $this->assertEquals($this->response2, $journal->getLastResponse());
    }

    /**
     * @depends testGetLastReturnsTheLastEntry
     */
    public function testClearRemovesEntries(Journal $journal)
    {
        $journal->clear();
        $this->assertEquals(0, count($journal));
    }

    /**
     * @depends testGetLastReturnsTheLastEntry
     */
    public function testForeachIteratesReversedEntries(Journal $journal)
    {
        $requests = array($this->request2, $this->request1);
        $responses = array($this->response2, $this->response1);

        foreach ($journal as $index => $entry) {
            $this->assertEquals($requests[$index], $entry->getRequest());
            $this->assertEquals($responses[$index], $entry->getResponse());
        }
    }
}


text:
package v1

import (
	"encoding/json"
	"errors"
)

// Plugin type and configuration
type Plugin struct {
	// Type of plugin
	Type string `json:"type"`
	// Conf for the specific plugin
	Conf json.RawMessage `json:"conf,omitempty"`
}

// ConfigList for the global configuration of NRI
//
// Normally located at /etc/nri/conf.json
type ConfigList struct {
	// Verion of the list
	Version string `json:"version"`
	// Plugins
	Plugins []*Plugin `json:"plugins"`
}

// Spec for the container being processed
type Spec struct {
	// Resources struct from the OCI specification
	//
	// Can be WindowsResources or LinuxResources
	Resources json.RawMessage `json:"resources"`
	// Namespaces for the container
	Namespaces map[string]string `json:"namespaces,omitempty"`
	// CgroupsPath for the container
	CgroupsPath string `json:"cgroupsPath,omitempty"`
	// Annotations passed down to the OCI runtime specification
	Annotations map[string]string `json:"annotations,omitempty"`
}

// State of the request
type State string

const (
	// Create the initial resource for the container
	Create State = "create"
	// Delete any resources for the container
	Delete State = "delete"
	// Update the resources for the container
	Update State = "update"
	// Pause action of the container
	Pause State = "pause"
	// Resume action for the container
	Resume State = "resume"
)

// Request for a plugin invocation
type Request struct {
	// Conf specific for the plugin
	Conf json.RawMessage `json:"conf,omitempty"`

	// Version of the plugin
	Version string `json:"version"`
	// State action for the request
	State State `json:"state"`
	// ID for the container
	ID string `json:"id"`
	// SandboxID for the sandbox that the request belongs to
	//
	// If ID and SandboxID are the same, this is a request for the sandbox
	// SandboxID is empty for a non sandboxed container
	SandboxID string `json:"sandboxID,omitempty"`
	// Pid of the container
	//
	// -1 if there is no pid
	Pid int `json:"pid,omitempty"`
	// Spec generated from the OCI runtime specification
	Spec *Spec `json:"spec"`
	// Labels of a sandbox
	Labels map[string]string `json:"labels,omitempty"`
	// Results from previous plugins in the chain
	Results []*Result `json:"results,omitempty"`
}

// IsSandbox returns true if the request is for a sandbox
func (r *Request) IsSandbox() bool {
	return r.ID == r.SandboxID
}

// NewResult returns a result from the original request
func (r *Request) NewResult(plugin string) *Result {
	return &Result{
		Plugin:   plugin,
		Version:  r.Version,
		Metadata: make(map[string]string),
	}
}

// Result of the plugin invocation
type Result struct {
	// Plugin name that populated the result
	Plugin string `json:"plugin"`
	// Version of the plugin
	Version string `json:"version"`
	// Error message in case of failures
	Error string `json:"error"`
	// Metadata specific to actions taken by the plugin
	Metadata map[string]string `json:"metadata,omitempty"`
}

// Err creates an Error object if ErrorMessage is populated
func (r *Result) Err() error {
	if r.Error != "" {
		return errors.New(r.Error)
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


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

-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="@dimen/ui_button_inset_horizontal"
       android:insetTop="@dimen/ui_button_inset_vertical"
       android:insetRight="@dimen/ui_button_inset_horizontal"
       android:insetBottom="@dimen/ui_button_inset_vertical">

    <selector>
        <item android:drawable="@drawable/dialog_btn_pressed"   android:state_pressed="true"/>
        <item android:drawable="@drawable/dialog_btn_pressed"   android:state_focused="true"/>
        <item android:drawable="@android:color/transparent"/>
    </selector>
</inset>


text:
from datetime import datetime, timedelta
import threading

class ClusteringCache:
    def __init__(self, clustering_obj):
        self.cl = clustering_obj # Instantiated clustering.Clustering()
        self.cluster_data = []
        self.cluster_contents = []
        self.last_gather_time = datetime.utcfromtimestamp(0) # Epoch
        self.gathering_now = threading.Lock()

    def data_is_stale(self, threshold=timedelta(minutes=5)):
        # Return True if data was gathered some threshold ago or earlier
        return self.last_gather_time < datetime.now() - threshold

    def finished_gathering_data(self):
        # Reset timestamp and generate Flot-friendly cluster data
        self.last_gather_time = datetime.now()
        self.cluster_contents = self.cl.list_clusters(self.cluster_data)

    def gather(self):
        self.gathering_now.acquire()
        self.cluster_data = self.cl.run_all() # Block and gather data
        self.gathering_now.release()
        self.finished_gathering_data()

    def refresh_data_if_old(self):
        if not self.gathering_now.locked() and self.data_is_stale():
            # Spawn a new thread, but return stale/nonexistent data for now
            # (If JS frontend gets a result indicating no data has ever been
            # gathered, it should try again, perhaps in ~5 seconds)
            th = threading.Thread(target=self.gather)
            th.daemon = True
            th.start()

    def get_data(self):
        self.refresh_data_if_old()
        return self.cluster_data

    def get_clusters(self):
        self.refresh_data_if_old()
        return self.cluster_contents


text:
This project is used by the Power BI Engineering team to build visualizations that ship with Power BI products and services.  By contributing, you can have your code ship within a Microsoft product.  For example, if you contribute a new visual, we could ship it to all Power BI users.  We're looking forward to helping you get your contributions into the repository.

Since it's our production code, we have code guidelines that must be met for changes to be accepted.  The contribution guidelines are listed below.  Let us know if you have questions on the guidelines, we're here to help.  One thing we encourage is that you fork the repo if you're planning to do substantial work. This lets you move forward at the pace you want and when it comes time to submit a pull request, we'll be able to refer to the fully working set of end to end code.

Before you start working on a feature, substantial code contribution, or interface change, please discuss it with the team to ensure it is an appropriate addition to the core product. In some situations, we may decline the changes if they would conflict with other inflight development efforts or really should be deferred until we can refactor pieces of the code base to ensure the features work in the long term.

For bug fixes, simply create an issue through GitHub to notify the team and chat about the design of the fix.

In order to speed up the process of accepting your contributions, you should try to make your pull request (PR) as small as possible, avoid any unnecessary deltas like whitespace formatting, and be sure to keep your change close to master to avoid merge conflicts.

####Third party libraries
External libraries of the PowerBI-Visuals project are located in folders:

1.	"\src\Clients\Externals\ThirdPartyIP" - this folder contains main third party libraries used in this project
2.	"node_modules" folders - these folders contain plugins used by gulp build system.

Some libraries are licensed in a way that prevents us for shipping them in our production environment. So we might decline your pull request should that happen. If your contribution changes require adding or modifying a new 3rd party library, then you should contact the Power BI team first and get approval for it. Submit an issue clearly identifying the library and version to start the process. This process takes at least 3 weeks for internal review.

####Pull Request Checklist
Pull Requests need to adhere to the checklist below. The Power BI team may ask you to make changes before accepting your changes.

##### Coding guidelines

  All changes should follow our adopted coding guidelines. A detailed description of our coding guidelines can be found [here](https://github.com/Microsoft/PowerBI-visuals/wiki/Coding-Guidelines).

##### Localization – UI strings

  Our project is localized – it means that we support multilingual text content. That's why all text strings that will be added/changed into the project should be localized in the separate resource file.

##### Adhering to common themes and styles

  When you change existing features or add new ones to the common themes and styles adhere existing styling of these files. Do not create a specific theme or style file that will be used only for your change. See the wiki documentation [here](https://github.com/Microsoft/PowerBI-visuals/wiki/Adhering-to-common-themes-and-styles).

##### New Visual Development

  Please follow our minimum requirements for implementing a new visual. See the wiki [here](https://github.com/Microsoft/PowerBI-visuals/wiki/Minimum-requirements-for-implementing-a-new-visual).

##### Security and privacy review requirements

  All changes in the code will be reviewed by the Power BI team for common security and privacy issues. None of any components of the project can do network calls to resources placed outside the Power BI domain. No data can be downloaded outside, no external content can be shown anywhere inside the domain.

##### Performance requirements

  The Power BI team will review key performance metrics including initial load time, resize performance, property change time, linear performance with respect to data volume. See our Performance guidelines wiki [here](https://github.com/Microsoft/PowerBI-visuals/wiki/Performance-requirements).

##### Licensing requirements

  The code you submit should be licensed under the MIT license as we have done for the rest of the repo.  If you use code that you did not author (like from Stack Overflow), you need to ensure correct attributions and license statements are made for those code blocks. Please work with us if you have questions.

##### Browser support matrix

  List of supported browsers is [here](https://support.powerbi.com/knowledgebase/articles/443109-supported-browsers-for-power-bi).

##### Unit tests

  Your changes should pass all unit tests. So before submitting a pull request build the project and run the tests using gulp build system. Changes that cause tests to fail will not be reviewed or modified by approvers.

  New functionality also should have appropriate unit tests for that functionality included in the pull request.

##### Description of the changes

Every pull request should include detailed description of the change and should contain:
*	Purpose of the change
*	Description of functionality that was changed
*	Bugs/issues details, if pull request fixes it

<br/>
Wow you made it to the bottom! We're looking forward to seeing what amazing contributions you provide and to helping you get them checked into the repo.

Thanks!

-The Power BI Team


text:
require 'static_model'

class Country < StaticModel::Base
  self.load_path = File.join(File.dirname(File.expand_path(__FILE__)), '../../data')
end


text:
/**
 * Stripe Product Model
 *
 * <%= whatIsThis %>.
 *
 * Refer to Stripe Documentation https://stripe.com/docs/api#products
 */

module.exports = {

	autoPK: false,

	attributes: {
		id: {
			type: 'string', //"ba_16q4nxBw8aZ7QiYmwqM3lvdR"
			primaryKey: true,
			unique: true
		},
		created: {
			type: 'datetime' //1443458925
		},
		updated: {
			type: 'datetime' //1443458925
		},
		object: {
			type: 'string' //"product"
		},
		livemode: {
			type: 'boolean' //false
		},
		name: {
			type: 'string'
		},
		caption: {
			type: 'string'
		},
		description: {
			type: 'string'
		},
		active: {
			type: 'boolean'
		},
		attributes: {
			type: 'array'
		},
		shippable: {
			type: 'boolean'
		},
		metadata: {
			type: 'json'
		},
		url: {
			type: 'string'
		},
		package_dimensions: {
			type: 'json'
		},
		images: {
			type: 'array'
		},
		skus: {
			type: 'json' //"object": "list","total_count": 0,"has_more": false,"url": "/v1/skus?product=prod_74DESReKhddEzB\u0026active=true","data": []
		},

		//Added to Model and doesn't exists in Stripe
		lastStripeEvent: {
			type: 'datetime'
		}
	},
	beforeValidate: function (values, cb){
		if(values.created){
			values.created = new Date(values.created * 1000);
		}
		if(values.updated){
			values.updated = new Date(values.updated * 1000);
		}
		cb();
	},

	// Stripe Webhook product.created
	stripeProductCreated: function (product, cb) {

		Product.findOrCreate(product.id, product)
	    .exec(function (err, foundProduct){
	      if (err) return cb(err);
	      if (foundProduct.lastStripeEvent > product.lastStripeEvent) return cb(null, foundProduct);
	      if (foundProduct.lastStripeEvent == product.lastStripeEvent) return Product.afterStripeProductCreated(foundProduct, function(err, product){ return cb(err, product)});
	      Product.update(foundProduct.id, product)
	      .exec(function(err, updatedProduct){
	      	if (err) return cb(err);
	      	if (!updatedProduct) return cb(null,null);
	      	Product.afterStripeProductCreated(updatedProduct[0], function(err, product){
	      		cb(err, product);
	      	});
	      });
	    });
	},

	afterStripeProductCreated: function(product, next){
		//Do somethings after an invoice item is created
		next(null, product);
	},

	// Stripe Webhook product.updated
	stripeProductUpdated: function (product, cb) {

		Product.findOrCreate(product.id, product)
	    .exec(function (err, foundProduct){
	      if (err) return cb(err);
	      if (foundProduct.lastStripeEvent > product.lastStripeEvent) return cb(null, foundProduct);
	      if (foundProduct.lastStripeEvent == product.lastStripeEvent) return Product.afterStripeProductUpdated(foundProduct, function(err, product){ return cb(err, product)});
	      Product.update(foundProduct.id, product)
	      .exec(function(err, updatedProduct){
	      	if (err) return cb(err);
	      	if (!updatedProduct) return cb(null,null);
	      	Product.afterStripeProductUpdated(updatedProduct[0], function(err, product){
	      		cb(err, product);
	      	});
	      });
	    });
	},

	afterStripeProductUpdated: function(product, next){
		//Do somethings after an invoice item is created
		next(null, product);
	},
}


text:
/**
 * Contains a cost-based greedy query planner.
 */
package org.gradoop.flink.model.impl.operators.matching.single.cypher.planning.plantable;


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Lint = require("tslint");
var changes_1 = require("../changes");
var memberRuleWalker_1 = require("./memberRuleWalker");
var util_1 = require("./util");
var Rule = /** @class */ (function (_super) {
    __extends(Rule, _super);
    function Rule() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Rule.prototype.applyWithProgram = function (sourceFile, program) {
        return this.applyWithWalker(new MemberRenameWalker(sourceFile, this.getOptions(), program));
    };
    return Rule;
}(Lint.Rules.TypedRule));
exports.Rule = Rule;
var MemberRenameWalker = /** @class */ (function (_super) {
    __extends(MemberRenameWalker, _super);
    function MemberRenameWalker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.configEntryName = "memberRenamings";
        return _this;
    }
    MemberRenameWalker.prototype.checkForChanges = function (node, oldParentName, oldMemberName, guess) {
        var newName = changes_1.changes[this.configEntryName][oldParentName] && changes_1.changes[this.configEntryName][oldParentName][oldMemberName];
        if (newName) {
            var targetNode = util_1.nameNodeFromNode(node);
            if (guess) {
                this.addFailureAtNode(targetNode, "This member might have been renamed to \"" + newName + "\" (assuming it is a member of type \"" + oldParentName + "\", inferred type is \"any\")");
            }
            else {
                var fix = void 0;
                if (util_1.shouldFix(this.getOptions())) {
                    fix = new Lint.Replacement(targetNode.getStart(), targetNode.getWidth(), newName);
                }
                this.addFailureAtNode(targetNode, (fix ? "(fixed) " : "") + "\"" + oldParentName + "#" + oldMemberName + "\" has been renamed to \"" + newName + "\"", fix);
            }
        }
    };
    return MemberRenameWalker;
}(memberRuleWalker_1.MemberRuleWalker));
//# sourceMappingURL=memberRenameRule.js.map


text:
import { expectTypeOf } from 'expect-type';

import { cacheFor } from '@ember/object/internals';

expectTypeOf(cacheFor).toEqualTypeOf<(obj: object, key: string) => unknown>();

expectTypeOf(cacheFor({ foo: 1 }, 'foo')).toEqualTypeOf<unknown>();
expectTypeOf(cacheFor({ foo: 1 }, 'other')).toEqualTypeOf<unknown>();


text:
Trabajar con Scripts del Cliente
================================

> Note: Esta sección se encuentra en desarrollo.

### Registrar scripts

Con el objeto [[yii\web\View]] puedes registrar scripts. Hay dos métodos dedicados a esto:
[[yii\web\View::registerJs()|registerJs()]] para scripts en línea
[[yii\web\View::registerJsFile()|registerJsFile()]] para scripts externos.
Los scripts en línea son útiles para configuración y código generado dinámicamente.
El método para agregarlos puede ser utilizado así:

```php
$this->registerJs("var options = ".json_encode($options).";", View::POS_END, 'my-options');
```

El primer argumento es el código JS real que queremos insertar en la página. El segundo argumento
determina en qué parte de la página debería ser insertado el script. Los valores posibles son:

- [[yii\web\View::POS_HEAD|View::POS_HEAD]] para la sección head.
- [[yii\web\View::POS_BEGIN|View::POS_BEGIN]] justo después de la etiqueta `<body>`.
- [[yii\web\View::POS_END|View::POS_END]] justo antes de cerrar la etiqueta `</body>`.
- [[yii\web\View::POS_READY|View::POS_READY]] para ejecutar código en el evento `ready` del documento. Esto registrará [[yii\web\JqueryAsset|jQuery]] automáticamente.
- [[yii\web\View::POS_LOAD|View::POS_LOAD]] para ejecutar código en el evento `load` del documento. Esto registrará [[yii\web\JqueryAsset|jQuery]] automáticamente.

El último argumento es un ID único del script, utilizado para identificar el bloque de código y reemplazar otro con el mismo ID
en vez de agregar uno nuevo. En caso de no proveerlo, el código JS en sí será utilizado como ID.

Un script externo puede ser agregado de esta manera:

```php
$this->registerJsFile('http://example.com/js/main.js', ['depends' => [\yii\web\JqueryAsset::class]]);
```

Los argumentos para [[yii\web\View::registerJsFile()|registerJsFile()]] son similares a los de
[[yii\web\View::registerCssFile()|registerCssFile()]]. En el ejemplo anterior,
registramos el archivo `main.js` con dependencia de `JqueryAsset`. Esto quiere decir que el archivo `main.js`
será agregado DESPUÉS de `jquery.js`. Si esta especificación de dependencia, el orden relativo entre
`main.js` y `jquery.js` sería indefinido.

Como para [[yii\web\View::registerCssFile()|registerCssFile()]], es altamente recomendable que utilices
[asset bundles](structure-assets.md) para registrar archivos JS externos más que utilizar [[yii\web\View::registerJsFile()|registerJsFile()]].

### Registrar asset bundles

Como mencionamos anteriormente, es preferible utilizar asset bundles en vez de usar CSS y JavaScript directamente. Puedes obtener detalles
de cómo definir asset bundles en la sección [gestor de assets](structure-assets.md) de esta guía. Utilizar asset bundles
ya definidos es muy sencillo:

```php
\frontend\assets\AppAsset::register($this);
```

### Registrar CSS

Puedes registrar CSS utilizando [[yii\web\View::registerCss()|registerCss()]] o [[yii\web\View::registerCssFile()|registerCssFile()]].
El primero registra un bloque de código CSS mientras que el segundo registra un archivo CSS externo. Por ejemplo,

```php
$this->registerCss("body { background: #f00; }");
```

El código anterior dará como resultado que se agregue lo siguiente a la sección head de la página:

```html
<style>
body { background: #f00; }
</style>
```

Si quieres especificar propiedades adicionales a la etiqueta style, pasa un array de claves-valores como tercer argumento.
Si necesitas asegurarte que haya sólo una etiqueta style utiliza el cuarto argumento como fue mencionado en las descripciones de meta etiquetas.

```php
$this->registerCssFile("http://example.com/css/themes/black-and-white.css", [
    'depends' => [BootstrapAsset::class],
    'media' => 'print',
], 'css-print-theme');
```

El código de arriba agregará un link al archivo CSS en la sección head de la página.

* El primer argumento especifica el archivo CSS a ser registrado.
* El segundo argumento especifica los atributos HTML de la etiqueta `<link>` resultante. La opción `depends`
  es especialmente tratada. Esta especifica de qué asset bundles depende este archivo CSS. En este caso, depende
  del asset bundle [[yii\bootstrap\BootstrapAsset|BootstrapAsset]]. Esto significa que el archivo CSS será agregado
  *después* de los archivos CSS de [[yii\bootstrap\BootstrapAsset|BootstrapAsset]].
* El último argumento especifica un ID que identifica al archivo CSS. Si no es provisto, se utilizará la URL
  del archivo.

Es altamente recomendable que ustilices [asset bundles](structure-assets.md) para registrar archivos CSS en vez de
utilizar [[yii\web\View::registerCssFile()|registerCssFile()]]. Utilizar asset bundles te permite combinar y comprimir
varios archivos CSS, deseable en sitios web de tráfico alto.


text:
/**
 * @file
 *
 * ODP queue
 */

#ifndef ODP_API_QUEUE_H_
#define ODP_API_QUEUE_H_
#include <odp/visibility_begin.h>

#ifdef __cplusplus
extern "C" {
#endif

#include <odp/api/schedule_types.h>
#include <odp/api/event.h>

/** @defgroup odp_queue ODP QUEUE
 *  Macros and operation on a queue.
 *  @{
 */

/**
 * @typedef odp_queue_t
 * ODP queue
 */

/**
 * @typedef odp_queue_group_t
 * Queue group instance type
 */

/**
 * @def ODP_QUEUE_INVALID
 * Invalid queue
 */

/**
 * @def ODP_QUEUE_NAME_LEN
 * Maximum queue name length in chars including null char
 */

/**
 * Queue type
 */
typedef enum odp_queue_type_t {
	/** Plain queue
	  *
	  * Plain queues offer simple FIFO storage of events. Application may
	  * dequeue directly from these queues. */
	ODP_QUEUE_TYPE_PLAIN = 0,

	/** Scheduled queue
	  *
	  * Scheduled queues are connected to the scheduler. Application must
	  * not dequeue events directly from these queues but use the scheduler
	  * instead. */
	ODP_QUEUE_TYPE_SCHED
} odp_queue_type_t;

/**
 * Queue operation mode
 */
typedef enum odp_queue_op_mode_t {
	/** Multithread safe operation
	  *
	  * Queue operation (enqueue or dequeue) is multithread safe. Any
	  * number of application threads may perform the operation
	  * concurrently. */
	ODP_QUEUE_OP_MT = 0,

	/** Not multithread safe operation
	  *
	  * Queue operation (enqueue or dequeue) may not be multithread safe.
	  * Application ensures synchronization between threads so that
	  * simultaneously only single thread attempts the operation on
	  * the same queue. */
	ODP_QUEUE_OP_MT_UNSAFE,

	/** Disabled
	  *
	  * Direct enqueue or dequeue operation from application is disabled.
	  * An attempt to enqueue/dequeue directly will result undefined
	  * behaviour. Various ODP functions (e.g. packet input, timer,
	  * crypto, scheduler, etc) are able to perform enqueue or
	  * dequeue operations normally on the queue.
	  * */
	ODP_QUEUE_OP_DISABLED

} odp_queue_op_mode_t;

/**
 * Queue capabilities
 */
typedef struct odp_queue_capability_t {
	/** Maximum number of event queues of any type (default size). Use
	  * this in addition to queue type specific 'max_num', if both queue
	  * types are used simultaneously. */
	uint32_t max_queues;

	/** Maximum number of ordered locks per queue */
	unsigned max_ordered_locks;

	/** Maximum number of scheduling groups */
	unsigned max_sched_groups;

	/** Number of scheduling priorities */
	unsigned sched_prios;

	/** Plain queue capabilities */
	struct {
		/** Maximum number of plain queues of the default size. */
		uint32_t max_num;

		/** Maximum number of events a plain queue can store
		  * simultaneously. The value of zero means that plain
		  * queues do not have a size limit, but a single queue can
		  * store all available events. */
		uint32_t max_size;

	} plain;

	/** Scheduled queue capabilities */
	struct {
		/** Maximum number of scheduled queues of the default size. */
		uint32_t max_num;

		/** Maximum number of events a scheduled queue can store
		  * simultaneously. The value of zero means that scheduled
		  * queues do not have a size limit, but a single queue can
		  * store all available events. */
		uint32_t max_size;

	} sched;

} odp_queue_capability_t;

/**
 * ODP Queue parameters
 */
typedef struct odp_queue_param_t {
	/** Queue type
	  *
	  * Valid values for other parameters in this structure depend on
	  * the queue type. */
	odp_queue_type_t type;

	/** Enqueue mode
	  *
	  * Default value for both queue types is ODP_QUEUE_OP_MT. Application
	  * may enable performance optimizations by defining MT_UNSAFE or
	  * DISABLED modes when applicable. */
	odp_queue_op_mode_t enq_mode;

	/** Dequeue mode
	  *
	  * For PLAIN queues, the default value is ODP_QUEUE_OP_MT. Application
	  * may enable performance optimizations by defining MT_UNSAFE or
	  * DISABLED modes when applicable. However, when a plain queue is input
	  * to the implementation (e.g. a queue for packet output), the
	  * parameter is ignored in queue creation and the value is
	  * ODP_QUEUE_OP_DISABLED.
	  *
	  * For SCHED queues, the parameter is ignored in queue creation and
	  * the value is ODP_QUEUE_OP_DISABLED. */
	odp_queue_op_mode_t deq_mode;

	/** Scheduler parameters
	  *
	  * These parameters are considered only when queue type is
	  * ODP_QUEUE_TYPE_SCHED. */
	odp_schedule_param_t sched;

	/** Queue context pointer
	  *
	  * User defined context pointer associated with the queue. The same
	  * pointer can be accessed with odp_queue_context() and
	  * odp_queue_context_set() calls. The implementation may read the
	  * pointer for prefetching the context data. Default value of the
	  * pointer is NULL. */
	void *context;

	/** Queue context data length
	  *
	  * User defined context data length in bytes for prefetching.
	  * The implementation may use this value as a hint for the number of
	  * context data bytes to prefetch. Default value is zero (no hint). */
	uint32_t context_len;

	/** Queue size
	  *
	  * The queue must be able to store at minimum this many events
	  * simultaneously. The value must not exceed 'max_size' queue
	  * capability. The value of zero means implementation specific
	  * default size. */
	uint32_t size;

} odp_queue_param_t;

/**
 * Queue create
 *
 * Create a queue according to the queue parameters. Queue type is specified by
 * queue parameter 'type'. Use odp_queue_param_init() to initialize parameters
 * into their default values. Default values are also used when 'param' pointer
 * is NULL. The default queue type is ODP_QUEUE_TYPE_PLAIN. The use of queue
 * name is optional. Unique names are not required. However, odp_queue_lookup()
 * returns only a single matching queue.
 *
 * @param name    Name of the queue or NULL. Maximum string length is
 *                ODP_QUEUE_NAME_LEN.
 * @param param   Queue parameters. Uses defaults if NULL.
 *
 * @return Queue handle
 * @retval ODP_QUEUE_INVALID on failure
 */
odp_queue_t odp_queue_create(const char *name, const odp_queue_param_t *param);

/**
 * Destroy ODP queue
 *
 * Destroys ODP queue. The queue must be empty and detached from other
 * ODP API (crypto, pktio, etc). Application must ensure that no other
 * operations on this queue are invoked in parallel. Otherwise behavior
 * is undefined.
 *
 * @param queue    Queue handle
 *
 * @retval 0 on success
 * @retval <0 on failure
 */
int odp_queue_destroy(odp_queue_t queue);

/**
 * Find a queue by name
 *
 * @param name    Queue name
 *
 * @return Handle of the first matching queue
 * @retval ODP_QUEUE_INVALID on failure
 */
odp_queue_t odp_queue_lookup(const char *name);

/**
 * Query queue capabilities
 *
 * Outputs queue capabilities on success.
 *
 * @param[out] capa   Pointer to capability structure for output
 *
 * @retval 0 on success
 * @retval <0 on failure
 */
int odp_queue_capability(odp_queue_capability_t *capa);

/**
 * Set queue context
 *
 * It is the responsibility of the user to ensure that the queue context
 * is stored in a location accessible by all threads that attempt to
 * access it.
 *
 * @param queue    Queue handle
 * @param context  Address to the queue context
 * @param len      Queue context data length in bytes
 *
 * @retval 0 on success
 * @retval <0 on failure
 */
int odp_queue_context_set(odp_queue_t queue, void *context, uint32_t len);

/**
 * Get queue context
 *
 * @param queue    Queue handle
 *
 * @return pointer to the queue context
 * @retval NULL on failure
 */
void *odp_queue_context(odp_queue_t queue);

/**
 * Queue enqueue
 *
 * Enqueue the 'ev' on 'queue'. On failure the event is not consumed, the caller
 * has to take care of it.
 *
 * @param queue   Queue handle
 * @param ev      Event handle
 *
 * @retval 0 on success
 * @retval <0 on failure
 */
int odp_queue_enq(odp_queue_t queue, odp_event_t ev);

/**
 * Enqueue multiple events to a queue
 *
 * Enqueue the events from 'events[]' on 'queue'. A successful call returns the
 * actual number of events enqueued. If return value is less than 'num', the
 * remaining events at the end of events[] are not consumed, and the caller
 * has to take care of them.
 *
 * @param queue   Queue handle
 * @param[in] events Array of event handles
 * @param num     Number of event handles to enqueue
 *
 * @return Number of events actually enqueued (0 ... num)
 * @retval <0 on failure
 */
int odp_queue_enq_multi(odp_queue_t queue, const odp_event_t events[], int num);

/**
 * Queue dequeue
 *
 * Dequeues next event from head of the queue. Cannot be used for
 * ODP_QUEUE_TYPE_SCHED type queues (use odp_schedule() instead).
 *
 * @param queue   Queue handle
 *
 * @return Event handle
 * @retval ODP_EVENT_INVALID on failure (e.g. queue empty)
 */
odp_event_t odp_queue_deq(odp_queue_t queue);

/**
 * Dequeue multiple events from a queue
 *
 * Dequeues multiple events from head of the queue. Cannot be used for
 * ODP_QUEUE_TYPE_SCHED type queues (use odp_schedule() instead).
 *
 * @param queue   Queue handle
 * @param[out] events  Array of event handles for output
 * @param num     Maximum number of events to dequeue

 * @return Number of events actually dequeued (0 ... num)
 * @retval <0 on failure
 */
int odp_queue_deq_multi(odp_queue_t queue, odp_event_t events[], int num);

/**
 * Queue type
 *
 * @param queue   Queue handle
 *
 * @return Queue type
 */
odp_queue_type_t odp_queue_type(odp_queue_t queue);

/**
 * Queue schedule type
 *
 * @param queue   Queue handle
 *
 * @return Queue schedule synchronization type
 */
odp_schedule_sync_t odp_queue_sched_type(odp_queue_t queue);

/**
 * Queue priority
 *
 * @note Passing an invalid queue_handle will result in UNDEFINED behavior
 *
 * @param queue   Queue handle
 *
 * @return Queue schedule priority
 */
odp_schedule_prio_t odp_queue_sched_prio(odp_queue_t queue);

/**
 * Queue group
 *
 * @note Passing an invalid queue_handle will result in UNDEFINED behavior
 *
 * @param queue   Queue handle
 *
 * @return Queue schedule group
 */
odp_schedule_group_t odp_queue_sched_group(odp_queue_t queue);

/**
 * Queue lock count
 *
 * Return number of ordered locks associated with this ordered queue.
 * Lock count is defined in odp_schedule_param_t.
 *
 * @param queue   Queue handle
 *
 * @return Number of ordered locks associated with this ordered queue
 * @retval <0 Specified queue is not ordered
 */
int odp_queue_lock_count(odp_queue_t queue);

/**
 * Get printable value for an odp_queue_t
 *
 * @param hdl  odp_queue_t handle to be printed
 * @return     uint64_t value that can be used to print/display this
 *             handle
 *
 * @note This routine is intended to be used for diagnostic purposes
 * to enable applications to generate a printable value that represents
 * an odp_queue_t handle.
 */
uint64_t odp_queue_to_u64(odp_queue_t hdl);

/**
 * Initialize queue params
 *
 * Initialize an odp_queue_param_t to its default values for all fields.
 * Also the schedule parameters are set to defaults, although the default queue
 * type is ODP_QUEUE_TYPE_PLAIN.
 *
 * @param param   Address of the odp_queue_param_t to be initialized
 */
void odp_queue_param_init(odp_queue_param_t *param);

/**
 * Queue information
 * Retrieve information about a queue with odp_queue_info()
 */
typedef struct odp_queue_info_t {
	const char *name;         /**< queue name */
	odp_queue_param_t param;  /**< queue parameters */
} odp_queue_info_t;

/**
 * Retrieve information about a queue
 *
 * Invalid queue handles or handles to free/destroyed queues leads to
 * undefined behaviour. Not intended for fast path use.
 *
 * @param      queue   Queue handle
 * @param[out] info    Queue info pointer for output
 *
 * @retval 0 Success
 * @retval <0 Failure.  Info could not be retrieved.
 */
int odp_queue_info(odp_queue_t queue, odp_queue_info_t *info);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#include <odp/visibility_end.h>
#endif


text:
qc::form_db
===========

part of [Docs](../index.md)

Usage
-----
`qc::form_db content args`

Description
-----------
Produce HTML to be used with JavaScript behavior dbForm

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"


text:
**To describe your load balancers**

This example describes all of your load balancers.

Command::

  aws elb describe-load-balancers

**To describe one of your load balancers**

This example describes the specified load balancer.

Command::

  aws elb describe-load-balancers --load-balancer-name my-load-balancer

The following example response is for an HTTPS load balancer in a VPC.

Output::

  {
    "LoadBalancerDescriptions": [
      {
        "Subnets": [
            "subnet-15aaab61"
        ],
        "CanonicalHostedZoneNameID": "Z3DZXE0EXAMPLE",
        "CanonicalHostedZoneName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com",
        "ListenerDescriptions": [
            {
                "Listener": {
                    "InstancePort": 80,
                    "LoadBalancerPort": 80,
                    "Protocol": "HTTP",
                    "InstanceProtocol": "HTTP"
                },
                "PolicyNames": []
            },
            {
                "Listener": {
                    "InstancePort": 443,
                    "SSLCertificateId": "arn:aws:iam::123456789012:server-certificate/my-server-cert",
                    "LoadBalancerPort": 443,
                    "Protocol": "HTTPS",
                    "InstanceProtocol": "HTTPS"
                },
                "PolicyNames": [
                    "ELBSecurityPolicy-2015-03"
                ]
            }
        ],
        "HealthCheck": {
            "HealthyThreshold": 2,
            "Interval": 30,
            "Target": "HTTP:80/png",
            "Timeout": 3,
            "UnhealthyThreshold": 2
        },
        "VPCId": "vpc-a01106c2",
        "BackendServerDescriptions": [
            {
                "InstancePort": 80,
                "PolicyNames": [
                    "my-ProxyProtocol-policy"
                ]
            }
        ],
        "Instances": [
            {
                "InstanceId": "i-207d9717"
            },
            {
                "InstanceId": "i-afefb49b"
            }
        ],
        "DNSName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com",
        "SecurityGroups": [
            "sg-a61988c3"
        ],
        "Policies": {
            "LBCookieStickinessPolicies": [
                {
                    "PolicyName": "my-duration-cookie-policy",
                    "CookieExpirationPeriod": 60
                }
            ],
            "AppCookieStickinessPolicies": [],
            "OtherPolicies": [
                "my-PublicKey-policy",
                "my-authentication-policy",
                "my-SSLNegotiation-policy",
                "my-ProxyProtocol-policy",
                "ELBSecurityPolicy-2015-03"
            ]
        },
        "LoadBalancerName": "my-load-balancer",
        "CreatedTime": "2015-03-19T03:24:02.650Z",
        "AvailabilityZones": [
            "us-west-2a"
        ],
        "Scheme": "internet-facing",
        "SourceSecurityGroup": {
            "OwnerAlias": "123456789012",
            "GroupName": "my-elb-sg"
        }
      }
    ]
  }


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using HastyAPI;

namespace Tests {
	public class Shared {
		public static string GetText(string filename) {
			var path = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\Data\" + filename);
			return File.ReadAllText(path);
		}

		public static dynamic GetJSON(string name) {
			return DynaJSON.Parse(GetText(name + ".js"));
		}

	}
}


text:
package ru.otus.l42;

import org.junit.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.*;

/**
 * 1
 * Created by tully.
 */
public class LotteryMachineTest {

    LotteryMachine lotteryMachine;

    @BeforeClass
    public static void beforeClass() {
        System.out.println("Before all LotteryMachineTest tests");
    }

    //before() is overridden in sub class
    @Before
    //public void beforeLotteryMachineTest() {
    public void before() {
        System.out.println("Before LotteryMachineTest");
        lotteryMachine = new LotteryMachine(5);
    }

    @After
    public void afterLotteryMachineTest() {
        System.out.println("After LotteryMachineTest");
        lotteryMachine.dispose();
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("After all LotteryMachineTest tests");
    }

    @Test(timeout = 10)
    public void oneEmail() throws InterruptedException {
        LotteryMachine machine = new LotteryMachine(2);
        List<String> result = machine.draw(Collections.singletonList("test"));
        Assert.assertEquals(1, result.size());
    }

    @Ignore("todo: 13131")
    @Test(timeout = 100)
    public void fiveEmails() {
        List<String> result = lotteryMachine
                .draw(Arrays.asList("0", "1", "2", "3", "4"));
        assertEquals(5, result.size());
        Assert.assertTrue(result.contains("0"));
        Assert.assertTrue(result.contains("1"));
        Assert.assertTrue(result.contains("2"));
        Assert.assertTrue(result.contains("3"));
        Assert.assertTrue(result.contains("4"));
    }

    @Test(expected = NullPointerException.class)
    public void NPETest() {
        List<String> result = lotteryMachine.setSeed(100500)
                .draw(null);
        Assert.assertEquals(0, result.size());
    }

}


text:
ACCEPTED

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

#### Published in
Stud. Mycol. 20: 42 (1980)

#### Original name
Chrysosporium synchronum Oorschot, 1980

### Remarks
null


text:
static void *
worker_routine (void *context) {
    //  Socket to talk to dispatcher
    void *receiver = zmq_socket (context, ZMQ_REP);
    zmq_connect (receiver, "inproc://workers");

    while (1) {
        char *string = s_recv (receiver);
        printf ("Received request: [%s]\n", string);
        free (string);
        //  Do some 'work'
        sleep (1);
        //  Send reply back to client
        s_send (receiver, "World");
    }
    zmq_close (receiver);
    return NULL;
}

int main (void)
{
    void *context = zmq_ctx_new ();

    //  Socket to talk to clients
    void *clients = zmq_socket (context, ZMQ_ROUTER);
    zmq_bind (clients, "tcp://*:5555");

    //  Socket to talk to workers
    void *workers = zmq_socket (context, ZMQ_DEALER);
    zmq_bind (workers, "inproc://workers");

    //  Launch pool of worker threads
    int thread_nbr;
    for (thread_nbr = 0; thread_nbr < 5; thread_nbr++) {
        pthread_t worker;
        pthread_create (&worker, NULL, worker_routine, context);
    }
    //  Connect work threads to client threads via a queue proxy
    zmq_proxy (clients, workers, NULL);

    //  We never get here, but clean up anyhow
    zmq_close (clients);
    zmq_close (workers);
    zmq_ctx_destroy (context);
    return 0;
}


text:
package com.hubspot.singularity.metrics;

import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.SingularityMainModule;
import com.hubspot.singularity.config.GraphiteConfiguration;
import com.hubspot.singularity.config.SingularityConfiguration;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.SocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class SingularityGraphiteReporter {
  private static final Logger LOG = LoggerFactory.getLogger(
    SingularityGraphiteReporter.class
  );

  private final GraphiteConfiguration graphiteConfiguration;
  private final MetricRegistry registry;
  private GraphiteReporter reporter = null;
  private Graphite graphite = null;
  private final String hostname;

  @Inject
  public SingularityGraphiteReporter(
    SingularityConfiguration configuration,
    MetricRegistry registry,
    @Named(SingularityMainModule.HOST_NAME_PROPERTY) String hostname
  ) {
    this.graphiteConfiguration = configuration.getGraphiteConfiguration();
    this.registry = registry;
    this.hostname =
      !Strings.isNullOrEmpty(graphiteConfiguration.getHostnameOmitSuffix()) &&
        hostname.endsWith(graphiteConfiguration.getHostnameOmitSuffix())
        ? hostname.substring(
          0,
          hostname.length() - graphiteConfiguration.getHostnameOmitSuffix().length()
        )
        : hostname;
  }

  private String buildGraphitePrefix() {
    if (Strings.isNullOrEmpty(graphiteConfiguration.getPrefix())) {
      return "";
    }

    return graphiteConfiguration.getPrefix().replace("{hostname}", hostname);
  }

  private Map<String, String> buildGraphiteTags() {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();

    for (Map.Entry<String, String> entry : graphiteConfiguration.getTags().entrySet()) {
      builder.put(entry.getKey(), entry.getValue().replace("{hostname}", hostname));
    }

    return builder.build();
  }

  public void start() {
    if (!graphiteConfiguration.isEnabled()) {
      LOG.info("Not reporting data points to graphite.");
      return;
    }

    final String prefix = buildGraphitePrefix();
    final Map<String, String> tags = buildGraphiteTags();

    LOG.info(
      "Reporting data points to graphite server {}:{} every {} seconds with prefix '{}', predicates '{}', and tags '{}'.",
      graphiteConfiguration.getHostname(),
      graphiteConfiguration.getPort(),
      graphiteConfiguration.getPeriodSeconds(),
      prefix,
      JavaUtils.COMMA_JOINER.join(graphiteConfiguration.getPredicates()),
      JavaUtils.COMMA_EQUALS_MAP_JOINER.join(tags)
    );

    graphite =
      new GraphiteWithTags(
        new InetSocketAddress(
          graphiteConfiguration.getHostname(),
          graphiteConfiguration.getPort()
        ),
        SocketFactory.getDefault(),
        Charsets.UTF_8,
        tags
      );

    final GraphiteReporter.Builder reporterBuilder = GraphiteReporter.forRegistry(
      registry
    );

    if (!Strings.isNullOrEmpty(prefix)) {
      reporterBuilder.prefixedWith(prefix);
    }

    if (!graphiteConfiguration.getPredicates().isEmpty()) {
      reporterBuilder.filter(
        new MetricFilter() {

          @Override
          public boolean matches(String name, Metric metric) {
            for (String predicate : graphiteConfiguration.getPredicates()) {
              if (name.startsWith(predicate)) {
                return true;
              }
            }
            return false;
          }
        }
      );
    }

    reporter = reporterBuilder.build(graphite);
    reporter.start(graphiteConfiguration.getPeriodSeconds(), TimeUnit.SECONDS);
  }

  public void stop() throws Exception {
    if (graphite != null) {
      LOG.info("Closing GraphiteSender");
      graphite.close();
      LOG.info("Closed GraphiteSender");
    }
    if (reporter != null) {
      LOG.info("Closing GraphiteReporter");
      reporter.stop();
      LOG.info("Closed GraphiteReporter");
    }
  }
}


text:
package dbhandler

import (
	"database/sql"
	"log"

	"github.com/chandanchowdhury/HSPC/models"
)

/**
Create a Student

*/
func StudentCreate(student models.Student) int64 {
	log.Print("Creating Student")

	db := getDBConn()
	stmt, err := db.Prepare("INSERT INTO student(student_name, student_grade, school_id) " +
		"VALUES($1, $2, $3) returning student_id")
	defer stmt.Close()

	if err != nil {
		log.Print("Error creating prepared statement")
		log.Panic(err)
	}

	var student_id int64
	err = stmt.QueryRow(student.StudentName, student.StudentGrade, student.SchoolID).Scan(&student_id)

	if err != nil {
		if isDuplicateKeyError(err) {
			return -1
		}

		if isForeignKeyError(err) {
			return -2
		}

		log.Panic(err)
	}

	log.Printf("New student_id = %d", student_id)

	return student_id
}

func StudentRead(student_id int64) models.Student {
	log.Printf("Reading Student ID = %d", student_id)

	db := getDBConn()

	stmt, err := db.Prepare("SELECT student_id, student_name, student_grade, school_id " +
		"FROM student WHERE student_id = $1")
	defer stmt.Close()

	if err != nil {
		log.Print("Error creating prepared statement")
		log.Panic(err)
	}

	var student = models.Student{}
	err = stmt.QueryRow(student_id).Scan(&student.StudentID, &student.StudentName, &student.StudentGrade, &student.SchoolID)

	// if no records found, return an empty struct
	if err == sql.ErrNoRows {
		return models.Student{}
	}

	if err != nil {
		log.Print("Error getting student data")
		log.Panic(err)
	}

	return student
}

func StudentUpdate(student models.Student) int64 {
	log.Printf("Updating Student ID = %d", student.StudentID)

	db := getDBConn()

	stmt, err := db.Prepare("UPDATE student SET student_name = $1, student_grade = $2, school_id = $3" +
		"WHERE student_id = $4")
	defer stmt.Close()

	if err != nil {
		log.Print("Error creating prepared statement")
		log.Panic(err)
	}

	result, err := stmt.Exec(student.StudentName, student.StudentGrade, student.SchoolID, student.StudentID)

	if err != nil {
		log.Print("Error updating student")

		if isDuplicateKeyError(err) {
			return -1
		}

		if isForeignKeyError(err) {
			return -2
		}

		log.Panic(err)
	}

	affectedCount, err := result.RowsAffected()

	if affectedCount != 1 {
		// if no records updated, just inform the caller
		if affectedCount == 0 {
			return 0
		}

		log.Panicf("Unexpected number of updates: %d", affectedCount)
	}

	return affectedCount
}

func StudentDelete(student_id int64) int64 {
	log.Printf("Deleting Student ID = %d", student_id)

	db := getDBConn()

	stmt, err := db.Prepare("DELETE FROM student WHERE student_id = $1")
	defer stmt.Close()

	if err != nil {
		log.Print("Error creating prepared statement")
		log.Panic(err)
	}

	result, err := stmt.Exec(student_id)

	if err != nil {
		log.Print("Delete Failed")

		if isForeignKeyError(err) {
			return -2
		}

		log.Panic(err)
	}

	affectedCount, err := result.RowsAffected()

	if affectedCount != 1 {
		// if no records updated, just inform the caller
		if affectedCount == 0 {
			return 0
		}

		log.Panicf("Unexpected number of updates: %d", affectedCount)
	}

	return affectedCount
}

/**
StudentListBySchool Finds and returns all Student who belongs to a School
*/
func StudentListBySchool(school_id int64) []*models.Student {
	log.Printf("Reading Student List for School ID = %d", school_id)

	db := getDBConn()

	stmt, err := db.Prepare("SELECT student_id, student_name, student_grade, school_id " +
		"FROM student WHERE school_id = $1")
	defer stmt.Close()

	if err != nil {
		log.Print("Error creating prepared statement")
		log.Panic(err)
	}

	crsr, err := stmt.Query(school_id)

	// if no records found, return an empty struct
	if err == sql.ErrNoRows {
		return []*models.Student{}
	}

	if err != nil {
		log.Print("Error getting student data")
		log.Panic(err)
	}

	student_list := make([]*models.Student, 0)
	for crsr.Next() {
		student := new(models.Student)
		crsr.Scan(&student.StudentID, &student.StudentName, &student.StudentGrade, &student.SchoolID)

		student_list = append(student_list, student)
	}

	return student_list
}


text:
require "reputation_helper"
class CommentsController < ApplicationController
  include ReputationHelper
  respond_to :html, :xml, :json, :js
  before_filter :load_commentable

  # GET /commentable/1/comments
  def index
    @comments = @commentable.comments.reverse
  end

  # GET /commentable/1/comments/new
  def new
    @comment = @commentable.comments.new
  end

  # POST /commentable/1/comments
  def create
    @comment = @commentable.comments.new(comment_params)
    @comment.user = current_user
    if @comment.save
      track_comment_activity_create(@comment)
      flash[:notice] = "Successfully saved comment."
      # points_for_commenting current_user
      respond_to do |format|
        format.html { redirect_to :back }
        format.js #create.js
        format.json {render @comment }
      end
    else
      render 'new'
    end
  end

  # POST /commentable/1/activity_comment
  def activity_comment
    @comment = @commentable.comments.new(comment_params)
    @comment.user = current_user
    @activity = Activity.find(params[:activity_id])
    if @comment.save
      track_comment_activity_create(@comment, 'create')
      respond_to do |format|
        format.html { redirect_to :back }
        format.js #activity_comment.js
        format.json {render @comment }
      end
    end
  end

  # GET /commentable/1/activitycomments/:activity_id
  def activitycomments
    activity_id = params[:activity_id]
    @activity = Activity.find(activity_id)
    respond_with(@commentable)
  end

  # GET JS /comments/showcomment
  def showcomment
    logger.debug "commentable : #{@commentable.attributes.inspect}"
    @comments = @commentable.comments
    name_id = @commentable.class.name.downcase+@commentable.id.to_s
    @comment_section_id = 'comment-list-'+name_id
    @show_comment_link_id = 'show-comment-btn-'+name_id
    respond_with(@comments)
  end

private

  def comment_params
    params.require(:comment).permit(:content)
  end

  def load_commentable
    klass = [Question, Answer, Todo,Discussion, Post].detect { |c| params["#{c.name.underscore}_id"]}
    @commentable = klass.find(params["#{klass.name.underscore}_id"])
  end

end


text:
var oauth2orize = require('oauth2orize'),
    models      = require('../models'),
    utils       = require('../utils'),

    oauth;

oauth = {

    init: function (oauthServer) {

        // remove all expired accesstokens on startup
        models.Accesstoken.destroyAllExpired();

        // remove all expired refreshtokens on startup
        models.Refreshtoken.destroyAllExpired();

        // Exchange user id and password for access tokens.  The callback accepts the
        // `client`, which is exchanging the user's name and password from the
        // authorization request for verification. If these values are validated, the
        // application issues an access token on behalf of the user who authorized the code.
        oauthServer.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) {
            // Validate the client
            models.Client.forge({slug: client.slug})
            .fetch()
            .then(function (client) {
                if (!client) {
                    return done(null, false);
                }
                // Validate the user
                return models.User.check({email: username, password: password}).then(function (user) {

                    //Everything validated, return the access- and refreshtoken
                    var accessToken = utils.uid(256),
                        refreshToken = utils.uid(256),
                        accessExpires = Date.now() + 3600 * 1000,
                        refreshExpires = Date.now() + 3600 * 24 * 1000;

                    return models.Accesstoken.add({token: accessToken, user_id: user.id, client_id: client.id, expires: accessExpires}).then(function () {
                        return models.Refreshtoken.add({token: refreshToken, user_id: user.id, client_id: client.id, expires: refreshExpires});
                    }).then(function () {
                        return done(null, accessToken, refreshToken, {expires_in: 3600});
                    }).catch(function () {
                        return done(null, false);
                    });
                }).catch(function () {
                    return done(null, false);
                });
            });
        }));

        // Exchange the refresh token to obtain an access token.  The callback accepts the
        // `client`, which is exchanging a `refreshToken` previously issued by the server
        // for verification. If these values are validated, the application issues an
        // access token on behalf of the user who authorized the code.
        oauthServer.exchange(oauth2orize.exchange.refreshToken(function (client, refreshToken, scope, done) {
            models.Refreshtoken.forge({token: refreshToken})
            .fetch()
            .then(function (model) {
                if (!model) {
                    return done(null, false);
                } else {
                    var token = model.toJSON(),
                        accessToken = utils.uid(256),
                        accessExpires = Date.now() + 3600 * 1000;

                    if (token.expires > Date.now()) {
                        models.Accesstoken.add({token: accessToken, user_id: token.user_id, client_id: token.client_id, expires: accessExpires}).then(function () {
                            return done(null, accessToken);
                        }).catch(function () {
                            return done(null, false);
                        });
                    } else {
                        done(null, false);
                    }
                }
            });
        }));
    }
};

module.exports = oauth;


text:
import pymongo

class Mongo:
    instance = None
    conn = None
    cursor = None

    def __init__(self):
        self.conn = pymongo.MongoClient("127.0.0.1", 27017).pyfetch

    @classmethod
    def get(cls):
        if cls.instance is None:
            cls.instance = cls()

        return cls.instance.conn


text:
from django.conf.urls import patterns, url

urlpatterns = patterns('vote.views',
    url('^enter/$', 'vote_enter_prompt'),
    url('^enter/submit$', 'vote_enter_submit'),
    url('^submit$', 'vote_submit'),
    url('^thanks$', 'vote_thanks'),
    url('^error$', 'vote_error'),
)


text:
\section*{E\+N\+P\+M808X -\/ \hyperlink{class_robot}{Robot} Butler }

\href{https://travis-ci.org/karanvivekbhargava/robot-butler-enpm808x}{\tt } \href{https://coveralls.io/github/karanvivekbhargava/robot-butler-enpm808x?branch=master}{\tt } \href{https://opensource.org/licenses/MIT}{\tt }

 Reference for image\+: \href{http://www.savioke.com/}{\tt link}

\subsection*{Project Overview}

The Butler product by Acme Robotics is one of its flagship products. It performs best for an environment where things are to be transported to and fro from one area to another. Equipped with a 16\+MP camera and the best of class custom lidar sensor, its the best offering one can hope for. The butler has intelligent algorithms running under its hood which allow it to percieve its environment by using these sensors. This allows the butler to avoid hitting obstacles and helps it serve you better.

\subsection*{New Feature List}

The new offerings in software are included below.
\begin{DoxyItemize}
\item Estimation of object distances using camera data\+: While other companies are defining state of the art algorithms on the road, the butler does it indoors. Making the robots less likely to crash into objects than the competitors.
\item Using lidar to map your environment\+: The butler records its surroundings in 3D so that it can see obstacles before they hit it.
\item Advanced data fusion algorithms\+: This robot is cool but don\textquotesingle{}t be fooled by its innocent appearance, it works super hard on the inside to crunch numbers faster than ever. Combining the data from both the sensors, it gets a better estimate on how it should move.
\item Path Planning\+: Using our custom sensors and the fusion technique, the butler can plan the path better to avoid obstacles

 \subsection*{The Camera}
\end{DoxyItemize}

The butler has a 16\+MP front facing camera. Its camera module consists of an F\+P\+GA which can perform custom algorithms at a mind boggling pace. Once the input image arrives, the module does a perspective transform on it. This gives us a birds eye view which is then passed to a thresholder. The binarized image from the thresholder is then used to calculate the probabilities of hitting the nearby obstacles. We use a gaussian probability distribution to compute the same.

The images below show how the camera module is manupulating the data to translate it into a probability. The left image is the input, the center image is the perspective warped image and the right image is the thresholded image after warping. After this I\textquotesingle{}m checking the distances to obstacles with different headding directions. I can use these distances to obtain probabilties using a gaussian distribution.

\subsection*{The Lidar}

The lidar gives a three dimensional point cloud representation of its surroundings. It uses this information and \textquotesingle{}flattens\textquotesingle{} it out. This results in all the points being in some eucledean plane and the robot being the origin. It computes the distances from the obstacles and returns gaussian probabilitites to all the possible heading directions of the robot.

Example\+: Consider that we have a point from the point cloud as below. PS\+: The points are preprocessed to be in the heading directions that we are going to consider.
\begin{DoxyCode}
1 p = (1, 2, 3)
\end{DoxyCode}
 The points will be flattened at first, this results in the representation of the points on the ground (euclidean plane).
\begin{DoxyCode}
1 p\_flattened = (1, 2)
\end{DoxyCode}
 We will then compute the distances of the points from the origin (this is where the robot will be at all times)
\begin{DoxyCode}
1 d = sqrt(1^2 + 2^2)
\end{DoxyCode}
 We then turn these distances into the probabilities of hitting an obstacle by
\begin{DoxyCode}
1 Probability = C*e^((d-mean)/(2*variance))
\end{DoxyCode}
 Where C is a normalization constant, mean is 0 and variance is tuned according to the data. The lidar outputs these probabilites.

\subsection*{Sensor Fusion}

After the camera and lidar do the hard work of putting the information in a sensible format, the sensor fusion module takes the two readings and selects the higher probability of the two, for each heading direction. Although this might result in some noisy outputs, it avoids obstacles effectively.

Example\+: If say we have the incoming probabilities given below where the probabilities correspond to heading directions -\/50, -\/30, -\/10, 10, 30, 50 degrees from current heading direction.
\begin{DoxyCode}
1 P\_image = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
2 P\_lidar = [0.6, 0.5, 0.4, 0.3, 0.2, 0,1];
\end{DoxyCode}
 Fused probability is given by
\begin{DoxyCode}
1 P\_fusion = max(P\_image, P\_lidar)
\end{DoxyCode}
 Which gives us,
\begin{DoxyCode}
1 P\_fusion = [0.6, 0.5, 0.4, 0.4, 0.5, 0.6];
\end{DoxyCode}

\subsection*{Path Planning}

The path planner uses the fused sensor output to determine what should be the next heading direction. This is done by selecting the heading direction which results in the least probability of hitting any obstacles.

Example\+: If the incoming fused probabilities are as given below
\begin{DoxyCode}
1 P\_fused = [0.1, 0.2, 0.0, 0.01, 0.1, 0,3];
\end{DoxyCode}
 Then the path planner can be written mathematically as
\begin{DoxyCode}
1 direction = argmin\_x( P\_fused[x] )
\end{DoxyCode}
 Then the output of the path planner would be
\begin{DoxyCode}
1 direction = 2 (index of 0.0)
\end{DoxyCode}

The robot later converts this direction into an angle by using

\begin{DoxyCode}
1 angle = (direction - 2.5)*20.0;
\end{DoxyCode}

\subsection*{The \hyperlink{class_robot}{Robot}}

The robot is the class which uses all the other modules and creates instances of a camera, lidar, sensor fusion module and path planning module. It then uses the modules to run.

 \subsection*{Results}

The software takes the camera image as well as the processed point cloud. I\textquotesingle{}ve configured the robot for three pictures by generating the respective lidar inputs.

Following are the results
\begin{DoxyEnumerate}
\item Obstacle on the left
\end{DoxyEnumerate}

\begin{DoxyCode}
1 Output:
2 [OK] Diagnostics are fine.
3 Rotate robot counter clockwise by -10
\end{DoxyCode}

\begin{DoxyEnumerate}
\item Obstacle in the center
\end{DoxyEnumerate}

\begin{DoxyCode}
1 Output:
2 [OK] Diagnostics are fine.
3 Rotate robot counter clockwise by 50
\end{DoxyCode}

\begin{DoxyEnumerate}
\item Obstacle on the right
\end{DoxyEnumerate}

\begin{DoxyCode}
1 Output:
2 [OK] Diagnostics are fine.
3 Rotate robot counter clockwise by -50
\end{DoxyCode}

 \subsection*{Solo Iterative Process Overview}

Click this link to view the product backlog, time sheets, defect logs and release backlog -\/ \href{https://docs.google.com/spreadsheets/d/1WOvV6iL4gGOF8Qacwj2R3Lom71wziKXEf_UEhdGfOuY/edit?usp=sharing}{\tt link}

Care has been taken to design the S\+IP tasks such that they have a direct relation to the previous tasks. This helps in better time estimation. For instance, the change in time taken for stub implementation is proportional to the change in time taken to implement the methods. This gave me a good idea to rethink about the allotment of time for future tasks.

 \subsection*{Dependencies}

The butler software stack has the following dependencies\+:
\begin{DoxyItemize}
\item cmake
\item googletest
\item opencv
\end{DoxyItemize}

To install opencv, follow the instructions on \href{https://docs.opencv.org/trunk/d7/d9f/tutorial_linux_install.html}{\tt link}

\#\# How to build -\/ standard install via command-\/line
\begin{DoxyCode}
1 git clone --recursive https://github.com/karanvivekbhargava/robot-butler-enpm808x
2 cd <path to repository>
3 mkdir build
4 cd build
5 cmake ..
6 make
\end{DoxyCode}

\subsection*{How to run demo}

After following the installation instructions above, you can try three different images from the data folder by specifying the argument with the program

To run for image\+\_\+left.\+jpg, kindly enter the function below
\begin{DoxyCode}
1 ./app/shell-app left
\end{DoxyCode}
 To run for image\+\_\+center.\+jpg, kindly enter the function below
\begin{DoxyCode}
1 ./app/shell-app center
\end{DoxyCode}
 To run for image\+\_\+right.\+jpg, kindly enter the function below
\begin{DoxyCode}
1 ./app/shell-app right
\end{DoxyCode}

\subsection*{How to run tests}

After following the building instructions, run the command below
\begin{DoxyCode}
1 ./test/cpp-test
\end{DoxyCode}

\subsection*{How to generate documentation}

Although the repository contains the documentation, if you\textquotesingle{}d still like to generate it then follow the instructions below.

\begin{DoxyCode}
1 sudo apt-get install doxygen
2 sudo apt-get install doxywizard
3 doxywizard
\end{DoxyCode}

Once doxywizard is open, select the workspace as the repository. Fill in the details as required and set the source code folder to the repository as well. Create a new folder in the repository and select that as the destination directory. Proceed with the default settings and generate the documentation.

Alternatively, you can run

\begin{DoxyCode}
1 doxygen -g doxygenconfig
2 doxygen doxygenconfig
\end{DoxyCode}


text:
package mockfs

import "bytes"

type FakeFile struct {
	bytes.Buffer
	Name string
}

func (self *FakeFile) Close() error {
	return nil
}

func AddTextFile(mockfs *MockFileSystem, name, content string) *FakeFile {
	f := &FakeFile{
		Name:   name,
		Buffer: *bytes.NewBufferString(content),
	}
	mockfs.EXPECT().Open(name).Return(f, nil).AnyTimes()
	return f
}


text:
class DashboardsController < ApplicationController
  before_filter :authenticate_user! ##, :except => [:get_started_content]
  # GET /dashboard
  def show
    @user = current_user
    respond_to do |format|
      format.html # show.html.slim
    end
  end
end


text:
package net.wayfarerx.dreamsleeve.data

import org.scalatest._

import scala.collection.immutable.{SortedMap, SortedSet}

/**
 * Test case for the table implementation.
 */
class TableSpec extends FlatSpec with Matchers {

  val generator = Hash.Generator()

  "A table" should "act as a hashable fragment that contains values and fragments" in {
    val e = Table()
    val o = Table(Value.Number(1) -> Value.String("1"))
    val t = Table(
      Value.Number(1) -> Value.String("1"),
      Value.Number(2) -> Value.String("2"),
      Value.Number(3) -> Value.String("3"))
    e == e shouldBe true
    e == o shouldBe false
    e == ("Hi": Any) shouldBe false
    t == t.copy(entries = t.entries + (Value.Number(3) -> Value.String("4"))) shouldBe false
    e.toString shouldBe "Table()"
    o.toString shouldBe "Table(Number(1)=String(1))"
    t.toString shouldBe "Table(Number(1)=String(1),Number(2)=String(2),Number(3)=String(3))"
    e.hash shouldBe generator.hash(Table.Header, Iterable.empty[Hash])
    o.hash shouldBe generator.hash(Table.Header, Seq(
      Value.Number(1).hash, Value.String("1").hash))
    t.hash shouldBe generator.hash(Table.Header, Seq(
      Value.Number(1).hash, Value.String("1").hash,
      Value.Number(2).hash, Value.String("2").hash,
      Value.Number(3).hash, Value.String("3").hash))
    Table.unapply(o) shouldBe Some(SortedMap[Value, Fragment](Value.Number(1) -> Value.String("1")))
  }

  it should "publish a subset of the underlying map interface" in {
    val t = Table(SortedMap[Value, Fragment](
      Value.Number(1) -> Value.String("1"),
      Value.Number(2) -> Value.String("2"),
      Value.Number(3) -> Value.String("3")))
    t.keys shouldBe SortedSet[Value](Value.Number(1), Value.Number(2), Value.Number(3))
    t.values.toVector shouldBe Vector[Fragment](Value.String("1"), Value.String("2"), Value.String("3"))
    t(Value.Number(2)) shouldBe Value.String("2")
    t.get(Value.Number(3)) shouldBe Some(Value.String("3"))
    t.get(Value.Number(4)) shouldBe None
  }

  it should "enforce stack safety for all recursive operations" in {
    StackSpec.StackOverflowTable1.equals(StackSpec.StackOverflowTable2) shouldBe false
    StackSpec.StackOverflowTable1.hash shouldNot be(null)
    StackSpec.StackOverflowTable1.toString shouldNot be(null)
  }

}


text:
ActiveRecord::Schema.define(version: 20150801221308) do

  create_table "videos", force: true do |t|
    t.string   "wistia"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "title"
  end

end


text: search_result['3523']=["topic_0000000000000875.html","JobVacancyRequestDto.PageSize Property",""];


text:
<ons-page id="chooseServicePage">
<ons-toolbar>

		<ons-back-button></ons-back-button>

</ons-toolbar>

	<ons-list id="show-service">
	<ons-lazy-repeat id="service-list"></ons-lazy-repeat>
	</ons-list>

</ons-page>