text:
#ifndef _XENO_ASM_NIOS2_CALIBRATION_H
#define _XENO_ASM_NIOS2_CALIBRATION_H

#ifndef _XENO_ASM_NIOS2_BITS_INIT_H
#error "please don't include asm/calibration.h directly"
#endif

static inline unsigned long xnarch_get_sched_latency (void)
{
#if CONFIG_XENO_OPT_TIMING_SCHEDLAT != 0
#define __sched_latency CONFIG_XENO_OPT_TIMING_SCHEDLAT
#else
#ifdef CONFIG_ALTERA_DE2
#define __sched_latency  10000
#elif CONFIG_NEEK
#define __sched_latency  10000
#else
#error "unsupported NIOS2 platform"
#endif
#endif /* CONFIG_XENO_OPT_TIMING_SCHEDLAT */

    return __sched_latency;
}

#undef __sched_latency

#endif /* !_XENO_ASM_NIOS2_CALIBRATION_H */


text:
package session

import (
	"context"
	"testing"
	"time"

	"github.com/gravitational/teleport/lib/backend"
	"github.com/gravitational/teleport/lib/backend/lite"
	"github.com/gravitational/teleport/lib/defaults"
	"github.com/gravitational/teleport/lib/utils"

	"github.com/gravitational/trace"
	"github.com/jonboulle/clockwork"
	. "gopkg.in/check.v1"
)

func TestSessions(t *testing.T) { TestingT(t) }

type SessionSuite struct {
	dir   string
	srv   *server
	bk    backend.Backend
	clock clockwork.FakeClock
}

var _ = Suite(&SessionSuite{})

func (s *SessionSuite) SetUpSuite(c *C) {
	utils.InitLoggerForTests(testing.Verbose())
}

func (s *SessionSuite) SetUpTest(c *C) {
	var err error

	s.clock = clockwork.NewFakeClockAt(time.Date(2016, 9, 8, 7, 6, 5, 0, time.UTC))
	s.dir = c.MkDir()

	s.bk, err = lite.New(context.TODO(), backend.Params{"path": s.dir})
	c.Assert(err, IsNil)

	(s.bk.(*lite.LiteBackend)).SetClock(s.clock)

	srv, err := New(s.bk)
	srv.(*server).clock = s.clock
	s.srv = srv.(*server)
	c.Assert(err, IsNil)
}

func (s *SessionSuite) TearDownTest(c *C) {
	c.Assert(s.bk.Close(), IsNil)
}

func (s *SessionSuite) TestID(c *C) {
	id := NewID()
	id2, err := ParseID(id.String())
	c.Assert(err, IsNil)
	c.Assert(id, Equals, *id2)

	for _, val := range []string{"garbage", "", "   ", string(id) + "extra"} {
		id := ID(val)
		c.Assert(id.Check(), NotNil)
	}
}

func (s *SessionSuite) TestSessionsCRUD(c *C) {
	out, err := s.srv.GetSessions(defaults.Namespace)
	c.Assert(err, IsNil)
	c.Assert(len(out), Equals, 0)

	sess := Session{
		ID:             NewID(),
		Namespace:      defaults.Namespace,
		Active:         true,
		TerminalParams: TerminalParams{W: 100, H: 100},
		Login:          "bob",
		LastActive:     s.clock.Now().UTC(),
		Created:        s.clock.Now().UTC(),
	}
	c.Assert(s.srv.CreateSession(sess), IsNil)

	out, err = s.srv.GetSessions(defaults.Namespace)
	c.Assert(err, IsNil)
	c.Assert(out, DeepEquals, []Session{sess})

	s2, err := s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(err, IsNil)
	c.Assert(s2, DeepEquals, &sess)

	// Mark session inactive
	err = s.srv.UpdateSession(UpdateRequest{
		ID:        sess.ID,
		Namespace: defaults.Namespace,
		Active:    Bool(false),
	})
	c.Assert(err, IsNil)

	sess.Active = false
	s2, err = s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(err, IsNil)
	c.Assert(s2, DeepEquals, &sess)

	// Update session terminal parameter
	err = s.srv.UpdateSession(UpdateRequest{
		ID:             sess.ID,
		Namespace:      defaults.Namespace,
		TerminalParams: &TerminalParams{W: 101, H: 101},
	})
	c.Assert(err, IsNil)

	sess.TerminalParams = TerminalParams{W: 101, H: 101}
	s2, err = s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(err, IsNil)
	c.Assert(s2, DeepEquals, &sess)
}

// TestSessionsInactivity makes sure that session will be marked
// as inactive after period of inactivity
func (s *SessionSuite) TestSessionsInactivity(c *C) {
	sess := Session{
		ID:             NewID(),
		Namespace:      defaults.Namespace,
		Active:         true,
		TerminalParams: TerminalParams{W: 100, H: 100},
		Login:          "bob",
		LastActive:     s.clock.Now().UTC(),
		Created:        s.clock.Now().UTC(),
	}
	c.Assert(s.srv.CreateSession(sess), IsNil)

	// move forward in time:
	s.clock.Advance(defaults.ActiveSessionTTL + time.Second)

	// should not be in active sessions:
	s2, err := s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(err, NotNil)
	c.Assert(trace.IsNotFound(err), Equals, true)
	c.Assert(s2, IsNil)
}

func (s *SessionSuite) TestPartiesCRUD(c *C) {
	// create session:
	sess := Session{
		ID:             NewID(),
		Namespace:      defaults.Namespace,
		Active:         true,
		TerminalParams: TerminalParams{W: 100, H: 100},
		Login:          "vincent",
		LastActive:     s.clock.Now().UTC(),
		Created:        s.clock.Now().UTC(),
	}
	c.Assert(s.srv.CreateSession(sess), IsNil)
	// add two people:
	parties := []Party{
		{
			ID:         NewID(),
			RemoteAddr: "1_remote_addr",
			User:       "first",
			ServerID:   "luna",
			LastActive: s.clock.Now().UTC(),
		},
		{
			ID:         NewID(),
			RemoteAddr: "2_remote_addr",
			User:       "second",
			ServerID:   "luna",
			LastActive: s.clock.Now().UTC(),
		},
	}
	s.srv.UpdateSession(UpdateRequest{
		ID:        sess.ID,
		Namespace: defaults.Namespace,
		Parties:   &parties,
	})
	// verify they're in the session:
	copy, err := s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(err, IsNil)
	c.Assert(len(copy.Parties), Equals, 2)

	// empty update (list of parties must not change)
	s.srv.UpdateSession(UpdateRequest{ID: sess.ID, Namespace: defaults.Namespace})
	copy, _ = s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(len(copy.Parties), Equals, 2)

	// remove the 2nd party:
	deleted := copy.RemoveParty(parties[1].ID)
	c.Assert(deleted, Equals, true)
	s.srv.UpdateSession(UpdateRequest{ID: copy.ID,
		Parties: &copy.Parties, Namespace: defaults.Namespace})
	copy, _ = s.srv.GetSession(defaults.Namespace, sess.ID)
	c.Assert(len(copy.Parties), Equals, 1)

	// we still have the 1st party in:
	c.Assert(parties[0].ID, Equals, copy.Parties[0].ID)
}

redpajama_set_name: RedPajamaGithub


text:
"""
    unit test for loop functions
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :copyright: 2007 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''
ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''
EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''
CONTEXTVARS = '''{% for item in seq %}\
{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
   loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{
   loop.even }}|{{ loop.odd }}|{{ loop.length }}###{% endfor %}'''
CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\
{% for item in seq %}{% cycle through %}{% endfor %}'''
SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''
VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}'''
NONITER = '''{% for item in none %}...{% endfor %}'''

def test_simple(env):
    tmpl = env.from_string(SIMPLE)
    assert tmpl.render(seq=range(10)) == '0123456789'

def test_else(env):
    tmpl = env.from_string(ELSE)
    assert tmpl.render() == '...'

def test_empty_blocks(env):
    tmpl = env.from_string(EMPTYBLOCKS)
    assert tmpl.render() == '<>'

def test_context_vars(env):
    tmpl = env.from_string(CONTEXTVARS)
    one, two, _ = tmpl.render(seq=[0, 1]).split('###')
    (one_index, one_index0, one_revindex, one_revindex0, one_first,
     one_last, one_even, one_odd, one_length) = one.split('|')
    (two_index, two_index0, two_revindex, two_revindex0, two_first,
     two_last, two_even, two_odd, two_length) = two.split('|')

    assert int(one_index) == 1 and int(two_index) == 2
    assert int(one_index0) == 0 and int(two_index0) == 1
    assert int(one_revindex) == 2 and int(two_revindex) == 1
    assert int(one_revindex0) == 1 and int(two_revindex0) == 0
    assert one_first == 'True' and two_first == 'False'
    assert one_last == 'False' and two_last == 'True'
    assert one_even == 'False' and two_even == 'True'
    assert one_odd == 'True' and two_odd == 'False'
    assert one_length == two_length == '2'

def test_cycling(env):
    tmpl = env.from_string(CYCLING)
    output = tmpl.render(seq=range(4), through=('<1>', '<2>'))
    assert output == '<1><2>' * 4

def test_scope(env):
    tmpl = env.from_string(SCOPE)
    output = tmpl.render(seq=range(10))
    assert not output

def test_varlen(env):
    def inner():
        for item in range(5):
            yield item
    tmpl = env.from_string(VARLEN)
    output = tmpl.render(iter=inner())
    assert output == '01234'

def test_noniter(env):
    tmpl = env.from_string(NONITER)
    assert not tmpl.render()


text:
id: 587d7db7367417b2b2512b9c
title: Find One or More Criminals in a Hunt
challengeType: 1
forumTopicId: 301343
localeTitle: Найти одного или нескольких преступников в охоте
---

## Description

Время для приостановки и тестирования ваших новых навыков написания регулярных выражений. Группа преступников убежала из тюрьмы и убежала, но вы не знаете, сколько. Однако вы знаете, что они остаются рядом друг с другом, когда они вокруг других людей. Вы несете ответственность за обнаружение всех преступников сразу. Вот пример, чтобы посмотреть, как это сделать: regex /z+/ соответствует букве z когда она появляется один или несколько раз подряд. Он найдет совпадения во всех следующих строках:
 «Г»
 "Zzzzzz"
 "ABCzzzz"
 "ZzzzABC"
 "Abczzzzzzzzzzzzzzzzzzzzzabc"
 Но он не находит совпадений в следующих строках, поскольку буквы буквы z :
 «»
 "ABC"
 "Abcabc"

## Instructions

Напишите greedy регулярное выражение, которое находит одного или нескольких преступников внутри группы других людей. Преступник представлен заглавной буквой C

## Tests

```yml
tests:
  - text: Your regex should match <code>one</code> criminal (<code>C</code>) in <code>"C"</code>
    testString: assert('C'.match(reCriminals) && 'C'.match(reCriminals)[0] == 'C');
  - text: Your regex should match <code>two</code> criminals (<code>CC</code>) in <code>"CC"</code>
    testString: assert('CC'.match(reCriminals) && 'CC'.match(reCriminals)[0] == 'CC');
  - text: Your regex should match <code>three</code> criminals (<code>CCC</code>) in <code>"P1P5P4CCCP2P6P3"</code>
    testString: assert('P1P5P4CCCP2P6P3'.match(reCriminals) && 'P1P5P4CCCP2P6P3'.match(reCriminals)[0] == 'CCC');
  - text: Your regex should match <code>five</code> criminals (<code>CCCCC</code>) in <code>"P6P2P7P4P5CCCCCP3P1"</code>
    testString: assert('P6P2P7P4P5CCCCCP3P1'.match(reCriminals) && 'P6P2P7P4P5CCCCCP3P1'.match(reCriminals)[0] == 'CCCCC');
  - text: Your regex should not match any criminals in <code>""</code>
    testString: assert(!reCriminals.test(''));
  - text: Your regex should not match any criminals in <code>"P1P2P3"</code>
    testString: assert(!reCriminals.test('P1P2P3'));
  - text: Your regex should match <code>fifty</code> criminals (<code>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</code>) in <code>"P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"</code>.
    testString: assert('P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'.match(reCriminals) && 'P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'.match(reCriminals)[0] == "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC");

```

## Challenge Seed

```js
// example crowd gathering
let crowd = 'P1P2P3P4P5P6CCCP7P8P9';

let reCriminals = /./; // Change this line

let matchedCriminals = crowd.match(reCriminals);
console.log(matchedCriminals);

```

## Solution

```js
// example crowd gathering
let crowd = 'P1P2P3P4P5P6CCCP7P8P9';

let reCriminals = /C+/; // Change this line

let matchedCriminals = crowd.match(reCriminals);
```


text:
redirect_from: /docs/1.0.22/classes/url.urlrouter.html
---
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>UrlRouter | @uirouter/angularjs</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">
	<link rel="stylesheet" href="../assets/css/uirouter.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@uirouter/angularjs

						Options

							<input type="checkbox" id="tsd-filter-externals" checked />
							Internal UI-Router API

					Menu

					@uirouter/angularjs

					url

					UrlRouter

Class UrlRouter

Updates URL and responds to URL changes

Deprecation warning:

This class is now considered to be an internal API
						Use the UrlService instead.
					For configuring URL rules, use the UrlRules which can be found as UrlService.rules.

Hierarchy

						UrlRouter

Index

Properties

url<wbr>Rule<wbr>Factory

Accessors

intercept<wbr>Deferred

Methods

defer<wbr>Intercept

href

initial

listen

match

otherwise

push

remove<wbr>Rule

rule

rules

sort

sync

update

when

Properties

url<wbr>Rule<wbr>Factory: UrlRuleFactory

 used to create UrlRule objects for common cases

used to create UrlRule objects for common cases

Defined in ui-router-core/src/url/urlRouter.ts:30

Accessors

get interceptDeferred(): boolean

deprecated

use [[UrlService.interceptDeferred]]

Returns boolean

Defined in ui-router-core/src/url/urlRouter.ts:119

Methods

defer<wbr>Intercept(defer?: boolean): void

Parameters

defer: Optional  boolean

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:117

href(urlMatcher: UrlMatcher, params?: any, options?: object): string

 Builds and returns a URL with interpolated parameters

Builds and returns a URL with interpolated parameters

Example:

matcher = $umf.compile("/about/:person");
params = { person: "bob" };
$bob = $urlRouter.href(matcher, params);
// $bob == "/about/bob";

Parameters

urlMatcher UrlMatcher

									:

The UrlMatcher object which is used as the template of the URL to generate.

params: Optional  any

									:

An object of parameter values to fill the matcher's required parameters.

options: Optional  object

									:

Options object. The options are:

absolute - {boolean=false},  If true will generate an absolute url, e.g. "http://www.example.com/fullurl".

absolute: boolean

Returns string

								:
Returns the fully compiled URL, or null if params fail validation against urlMatcher

Defined in ui-router-core/src/url/urlRouter.ts:87

initial(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef): void

Parameters

handler string | UrlRuleHandlerFn | TargetState | TargetStateDef

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:127

listen(enabled?: boolean): Function

Parameters

enabled: Optional  boolean

Returns Function

Defined in ui-router-core/src/url/urlRouter.ts:115

match(urlParts: UrlParts): MatchResult

Parameters

urlParts UrlParts

Returns MatchResult

Defined in ui-router-core/src/url/urlRouter.ts:123

otherwise(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef): void

Parameters

handler string | UrlRuleHandlerFn | TargetState | TargetStateDef

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:130

push(urlMatcher: UrlMatcher, params?: RawParams, options?: object): void

 Internal API.

Internal API.

Pushes a new location to the browser history.

Parameters

urlMatcher UrlMatcher

									:

params: Optional  RawParams

									:

options: Optional  object

									:

Optional replace?: string | boolean

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:63

remove<wbr>Rule(rule: UrlRule): void

Parameters

rule UrlRule

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:133

rule(rule: UrlRule): Function

Parameters

rule UrlRule

Returns Function

Defined in ui-router-core/src/url/urlRouter.ts:135

rules(): UrlRule[]

Returns UrlRule[]

Defined in ui-router-core/src/url/urlRouter.ts:137

sort(compareFn?: function): void

Parameters

compareFn: Optional  function

(a: UrlRule, b: UrlRule): number

Parameters

a UrlRule

b UrlRule

Returns number

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:139

sync(evt?: any): void

Parameters

evt: Optional  any

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:113

update(read?: boolean): void

 Internal API.

Internal API.

Parameters

read: Optional  boolean

Returns void

Defined in ui-router-core/src/url/urlRouter.ts:42

when(matcher: RegExp | UrlMatcher | string, handler: string | UrlRuleHandlerFn, options?: object): UrlRule

Parameters

matcher RegExp | UrlMatcher | string

handler string | UrlRuleHandlerFn

options: Optional  object

priority: number

Returns UrlRule

Defined in ui-router-core/src/url/urlRouter.ts:141

						@uirouter/angularjs

						Public API

						common

						core

						directives

						injectables

						ng1

						ng1_<wbr>state_<wbr>events

						params

						resolve

						state

						transition

						url

						view

						Internal UI-<wbr><wbr>Router API

						common_<wbr>hof

						common_<wbr>predicates

						common_<wbr>strings

						hooks

						path

						trace

						vanilla

						Base<wbr>Url<wbr>Rule

						Param<wbr>Factory

						Url<wbr>Config

						Url<wbr>Matcher

						Url<wbr>Matcher<wbr>Factory

						Url<wbr>Router

								url<wbr>Rule<wbr>Factory

								intercept<wbr>Deferred

								defer<wbr>Intercept

								href

								initial

								listen

								match

								otherwise

								push

								remove<wbr>Rule

								rule

								rules

								sort

								sync

								update

								when

						Url<wbr>Router<wbr>Provider

						Url<wbr>Rule<wbr>Factory

						Url<wbr>Rules

						Url<wbr>Service

						Match<wbr>Result

						Matcher<wbr>Url<wbr>Rule

						Raw<wbr>Ng1<wbr>Rule<wbr>Function

						Reg<wbr>Exp<wbr>Rule

						State<wbr>Rule

						Url<wbr>Config<wbr>Api

						Url<wbr>Matcher<wbr>Compile<wbr>Config

						Url<wbr>Matcher<wbr>Config

						Url<wbr>Parts

						Url<wbr>Rule

						Url<wbr>Rule<wbr>Handler<wbr>Fn

						Url<wbr>Rule<wbr>Match<wbr>Fn

						Url<wbr>Rules<wbr>Api

						Url<wbr>Sync<wbr>Api

						Url<wbr>Rule<wbr>Type

						default<wbr>Rule<wbr>Sort<wbr>Fn

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
//
//  CCPathRenderingTestScene.h
//  CCPathRenderingDemo
//
//  Created by bman on 3/9/14.
//
//

#ifndef __CCPathRenderingDemo__CCPathRenderingTestScene__
#define __CCPathRenderingDemo__CCPathRenderingTestScene__

#include "cocos2d.h"
#include "cocos-ext.h"

//#include "MonkVG/openvg.h"
//#include "MonkVG/vgu.h"
//#include "MonkVG/vgext.h"

#include "CCPathRendering/CCGraphicsNode.h"
#include "CCPathRendering/CCPathRenderingPaint.h"
#include "CCPathRendering/CCPathRenderingPath.h"

USING_NS_CC;
USING_NS_CC_EXT;

class CCPathRenderingTestScene : public Layer
{
private:
    CustomCommand _customRenderCommand;

//    VGPath	_path;
//	VGPaint _paint;
//	VGPaint _linearGradientPaint;
//	VGPaint _radialGradientPaint;
//    //	VGImage _image;
//    //	VGImage	_bitmapFont;
//	//	VGImage _gradientImage;
//	VGPath _linearGradientPath;
//	VGPath _radialGradientPath;
//	VGFont	_font;
//	VGfloat _lineHeight;

    GraphicsNode* _graphicsNode;

public:
    static Scene* scene();
    CREATE_FUNC(CCPathRenderingTestScene);

    virtual ~CCPathRenderingTestScene ();

    virtual bool init();

    // update
    virtual void update (float delta) override;

    // draw
    virtual void draw (Renderer* renderer, const kmMat4 &transform, bool transformUpdated) override;
    void render ();

    // touch callback
    virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event) override;
    virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event) override;
    virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *event) override;
    virtual void onTouchesCancelled(const std::vector<Touch*>& touches, Event *event) override;
};

#endif /* defined(__CCPathRenderingDemo__CCPathRenderingTestScene__) */


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Options;

final class RabbitMqOptions
{
    public function __construct(
        public readonly bool $enabled = false,
        /** @deprecated */
        public readonly bool $legacyVisitsPublishing = false,
    ) {
    }
}


text:
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		body {
		    background-color: #DDDDDD;
		    font: 30px sans-serif;
		}
		canvas {
		    background-color: white;
		}
	</style>
</head>
<body>

<canvas id="mainCanvs" width="640" height="960"></canvas>

<script src="http://code.createjs.com/easeljs-0.7.1.min.js"></script>
<script src="http://code.createjs.com/preloadjs-0.4.1.min.js"></script>
<script src="http://code.createjs.com/tweenjs-0.5.1.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

<script>

$(function(){
	init();
});

var stage;
var myBitmap;
var canvasObject;

//var top;
var top2;
var bottom;
var right;
var left;
var currentSide;

var easings = [
	createjs.Ease.circIn,
	createjs.Ease.bounceOut,
	createjs.Ease.elasticInOut
];

var sides = ["left","top","right","bottom"];
var lengths;
var lengthstotal = 0;

function init() {

	var file = "img/target1.png";
	var loader = new createjs.LoadQueue(false);

	loader.addEventListener("fileload",draw);
	loader.loadFile(file);

	canvasObject = document.getElementById("mainCanvs");
	top2 = 0;
	left = 0;
	right = canvasObject.width;
	bottom = canvasObject.height;

	stage = new createjs.Stage(canvasObject);
}

function draw(eventObject) {
	var myImage = eventObject.result;
	myBitmap = new createjs.Bitmap(myImage);

	setGeometricData(myImage.width / 2,myImage.height / 2);

	myBitmap.regX = myImage.width / 2;
	myBitmap.regY = myImage.height / 2;

	myBitmap.x = myImage.width / 2;
	myBitmap.y = (top2 + bottom) / 2;

	stage.addChild(myBitmap);
	stage.update();

	setRandomTween(myBitmap,"left");

	createjs.Ticker.addEventListener("tick",stage);

}

function setGeometricData(offsetX,offsetY) {
	top2 += offsetY;
	bottom  -= offsetY;
	left  += offsetX;
	right -= offsetX;

	var width = right - left;
	var height = bottom - top2;
	lengths = [height,width,height,width];
	lengthstotal = height + width + height + width;

}

function setRandomTween(target,side) {
	var pos = getNextPosition(side);
	var nextPoint = getPoint(pos);

	var randomTime = Math.random() * 3000 + 500;
	var easing = easings[Math.floor(Math.random() * easings.length)];

	setTween(target,nextPoint,randomTime,easing);

}

function setTween(target,myPoint,time,easing) {
	createjs.Tween.get(target)
	.to({x:myPoint.x,y:myPoint.y},time,easing)
	.call(setRandomTween,[target,currentSide]);

}

function getNextPosition(mySide) {
	var index = sides.indexOf(mySide);
	var range = lengthstotal - lengths[index];
	var position = range * Math.random();
	var returnObject;
	var count = lengths.length;
	for (var i = 1; i < count; i++) {
		var indexNext = (index + i) % count;
		var length = lengths[indexNext];
		if(position <= length) {
			var side = sides[indexNext];
			returnObject = {side:side,position:position};
			currentSide = side;
			break;
		} else {
			position -= length;
		}
	};

	return returnObject;
}

function getPoint(position) {
	var myPoint = new createjs.Point();
	var side = position.side;
	var value = position.position;
	switch(side) {
		case "top":
			myPoint.x = value + left;
			myPoint.y = top2;
			break;
		case "bottom":
			myPoint.x = value + left;
			myPoint.y = bottom;
			break;
		case "left":
			myPoint.x = left;
			myPoint.y = value + top2;
			break;
		case "right":
			myPoint.x = right;
			myPoint.y = value + top2;
			break;
	}

	return myPoint;
}

</script>

</body>
</html>


text:
/* This file is auto-generated! Any changes to this file will be lost! */
package woothee

import (
	"testing"
)

func Test_mobilephone_misc(t *testing.T) {
	var result *Result
	var err error
	result, err = Parse(`Mozilla/5.0 (jig browser core; SH03B)`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/5.0 (jig browser core; SH03B)': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/5.0 (jig browser core; SH03B)`, result.Category)
		}
		if result.Name != "jig browser" {
			t.Errorf("Expected result.Name for '%s' to be 'jig browser', but got '%s'", `Mozilla/5.0 (jig browser core; SH03B)`, result.Name)
		}
		if true && result.Os != "jig" {
			t.Errorf("Expected result.Os for '%s' to be 'jig', but got '%s'", `Mozilla/5.0 (jig browser core; SH03B)`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (jig browser core; SH03B)`, result.OsVersion)
		}
		if true && result.Version != "SH03B" {
			t.Errorf("Expected result.Version for '%s' to be 'SH03B', but got '%s'", `Mozilla/5.0 (jig browser core; SH03B)`, result.Version)
		}
	}
	result, err = Parse(`Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)`, result.Category)
		}
		if result.Name != "jig browser" {
			t.Errorf("Expected result.Name for '%s' to be 'jig browser', but got '%s'", `Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)`, result.Name)
		}
		if true && result.Os != "jig" {
			t.Errorf("Expected result.Os for '%s' to be 'jig', but got '%s'", `Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)`, result.OsVersion)
		}
		if true && result.Version != "F10B" {
			t.Errorf("Expected result.Version for '%s' to be 'F10B', but got '%s'", `Mozilla/4.0 (jig browser9i 1.5.0; F10B; 2004)`, result.Version)
		}
	}
	result, err = Parse(`Mozilla/4.0 (jig browser9)`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/4.0 (jig browser9)': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/4.0 (jig browser9)`, result.Category)
		}
		if result.Name != "jig browser" {
			t.Errorf("Expected result.Name for '%s' to be 'jig browser', but got '%s'", `Mozilla/4.0 (jig browser9)`, result.Name)
		}
		if true && result.Os != "jig" {
			t.Errorf("Expected result.Os for '%s' to be 'jig', but got '%s'", `Mozilla/4.0 (jig browser9)`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/4.0 (jig browser9)`, result.OsVersion)
		}
		if true && result.Version != "UNKNOWN" {
			t.Errorf("Expected result.Version for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/4.0 (jig browser9)`, result.Version)
		}
	}
	result, err = Parse(`emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4`)
	if err != nil {
		t.Errorf(`Failed to parse 'emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4`, result.Category)
		}
		if result.Name != "emobile" {
			t.Errorf("Expected result.Name for '%s' to be 'emobile', but got '%s'", `emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4`, result.Name)
		}
		if true && result.Os != "emobile" {
			t.Errorf("Expected result.Os for '%s' to be 'emobile', but got '%s'", `emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4`, result.OsVersion)
		}
		if false && result.Version != "UNKNOWN" {
			t.Errorf("Expected result.Version for '%s' to be 'UNKNOWN', but got '%s'", `emobile/1.0.0 (H11T; like Gecko; Wireless) NetFront/3.4`, result.Version)
		}
	}
	result, err = Parse(`IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0`)
	if err != nil {
		t.Errorf(`Failed to parse 'IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0`, result.Category)
		}
		if result.Name != "emobile" {
			t.Errorf("Expected result.Name for '%s' to be 'emobile', but got '%s'", `IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0`, result.Name)
		}
		if true && result.Os != "emobile" {
			t.Errorf("Expected result.Os for '%s' to be 'emobile', but got '%s'", `IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0`, result.OsVersion)
		}
		if false && result.Version != "UNKNOWN" {
			t.Errorf("Expected result.Version for '%s' to be 'UNKNOWN', but got '%s'", `IAC/1.0 (H31IA;like Gecko;OpenBrowser) WWW Browser/ver1.0`, result.Version)
		}
	}
	result, err = Parse(`Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4`, result.Category)
		}
		if result.Name != "emobile" {
			t.Errorf("Expected result.Name for '%s' to be 'emobile', but got '%s'", `Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4`, result.Name)
		}
		if true && result.Os != "emobile" {
			t.Errorf("Expected result.Os for '%s' to be 'emobile', but got '%s'", `Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4`, result.OsVersion)
		}
		if false && result.Version != "UNKNOWN" {
			t.Errorf("Expected result.Version for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (H11T; like Gecko; OpenBrowser) NetFront/3.4`, result.Version)
		}
	}
	result, err = Parse(`Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A`)
	if err != nil {
		t.Errorf(`Failed to parse 'Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A`, result.Category)
		}
		if result.Name != "emobile" {
			t.Errorf("Expected result.Name for '%s' to be 'emobile', but got '%s'", `Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A`, result.Name)
		}
		if true && result.Os != "emobile" {
			t.Errorf("Expected result.Os for '%s' to be 'emobile', but got '%s'", `Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A`, result.OsVersion)
		}
		if false && result.Version != "UNKNOWN" {
			t.Errorf("Expected result.Version for '%s' to be 'UNKNOWN', but got '%s'", `Huawei/1.0/H12HW/B000 Browser/Obigo-Browser/Q04A`, result.Version)
		}
	}
	result, err = Parse(`Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413`, result.Category)
		}
		if result.Name != "Safari" {
			t.Errorf("Expected result.Name for '%s' to be 'Safari', but got '%s'", `Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413`, result.Name)
		}
		if true && result.Os != "SymbianOS" {
			t.Errorf("Expected result.Os for '%s' to be 'SymbianOS', but got '%s'", `Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413`, result.OsVersion)
		}
		if true && result.Version != "UNKNOWN" {
			t.Errorf("Expected result.Version for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaE66-1/500.21.009; Profile/MIDP-2.0 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413`, result.Version)
		}
	}
	result, err = Parse(`Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14`, result.Category)
		}
		if result.Name != "Mobile Transcoder" {
			t.Errorf("Expected result.Name for '%s' to be 'Mobile Transcoder', but got '%s'", `Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14`, result.Name)
		}
		if true && result.Os != "Mobile Transcoder" {
			t.Errorf("Expected result.Os for '%s' to be 'Mobile Transcoder', but got '%s'", `Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14`, result.OsVersion)
		}
		if true && result.Version != "Google" {
			t.Errorf("Expected result.Version for '%s' to be 'Google', but got '%s'", `Mozilla/5.0 (en-us) AppleWebKit/534.14 (KHTML, like Gecko; Google Wireless Transcoder) Chrome/9.0.597 Safari/534.14`, result.Version)
		}
	}
	result, err = Parse(`Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)`)
	if err != nil {
		t.Errorf(`Failed to parse 'Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)': %s`, err)
	} else {
		if result.Category != "mobilephone" {
			t.Errorf("Expected result.Category for '%s' to be 'mobilephone', but got '%s'", `Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)`, result.Category)
		}
		if result.Name != "Mobile Transcoder" {
			t.Errorf("Expected result.Name for '%s' to be 'Mobile Transcoder', but got '%s'", `Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)`, result.Name)
		}
		if true && result.Os != "Mobile Transcoder" {
			t.Errorf("Expected result.Os for '%s' to be 'Mobile Transcoder', but got '%s'", `Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)`, result.Os)
		}
		if false && result.OsVersion != "UNKNOWN" {
			t.Errorf("Expected result.OsVersion for '%s' to be 'UNKNOWN', but got '%s'", `Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)`, result.OsVersion)
		}
		if true && result.Version != "livedoor" {
			t.Errorf("Expected result.Version for '%s' to be 'livedoor', but got '%s'", `Mozilla/5.0 (compatible; livedoor-Mobile-Gateway/0.02; +http://p.m.livedoor.com/help.html)`, result.Version)
		}
	}

}


text:
package storm.starter;

import org.apache.storm.Config;
import org.apache.storm.LocalCluster;
import org.apache.storm.StormSubmitter;
import org.apache.storm.task.ShellBolt;
import org.apache.storm.topology.BasicOutputCollector;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.topology.base.BaseBasicBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import storm.starter.spout.RandomSentenceSpout;

import java.util.HashMap;
import java.util.Map;

/**
 * This topology demonstrates Storm's stream groupings and multilang capabilities.
 */
public class WordCountTopology {
    public static class SplitSentence extends ShellBolt implements IRichBolt {

        public SplitSentence() {
            super("python", "/Users/ahan/work/ahan/amery_base_java/storm/src/main/resources/splitsentence.py");
        }

        @Override
        public void declareOutputFields(OutputFieldsDeclarer declarer) {
            declarer.declare(new Fields("word"));
        }

        @Override
        public Map<String, Object> getComponentConfiguration() {
            return null;
        }
    }

    public static class WordCount extends BaseBasicBolt {
        Map<String, Integer> counts = new HashMap<String, Integer>();

        @Override
        public void execute(Tuple tuple, BasicOutputCollector collector) {
            String word = tuple.getString(0);
            Integer count = counts.get(word);
            if (count == null)
                count = 0;
            count++;
            counts.put(word, count);
            collector.emit(new Values(word, count));
        }

        @Override
        public void declareOutputFields(OutputFieldsDeclarer declarer) {
            declarer.declare(new Fields("word", "count"));
        }
    }

    public static void main(String[] args) throws Exception {

        TopologyBuilder builder = new TopologyBuilder();

        builder.setSpout("spout", new RandomSentenceSpout(), 5);

        builder.setBolt("split", new SplitSentence(), 8).shuffleGrouping("spout");
        builder.setBolt("count", new WordCount(), 12).fieldsGrouping("split", new Fields("word"));

        Config conf = new Config();
        conf.setDebug(true);

        if (args != null && args.length > 0) {
            conf.setNumWorkers(3);

            StormSubmitter.submitTopology(args[0], conf, builder.createTopology());
        } else {
            conf.setMaxTaskParallelism(3);

            LocalCluster cluster = new LocalCluster();
            cluster.submitTopology("word-count", conf, builder.createTopology());

            Thread.sleep(10000);

            cluster.shutdown();
        }
    }
}


text:
from PyQt4 import QtCore,QtGui
import re
# Initialize Qt resources from file resources.py
from sessionClasses import *
from sqlalchemy import MetaData, Column, Table, ForeignKey
from sqlalchemy import *
import sys
from mmasgisDb_sqlalchemy import *
#from sqlAlchemyQueryClass import *
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, mapper, relation, sessionmaker
from elixir import *
import sqlalchemy
from sqlalchemy.ext import compiler
from sqlalchemy.sql.expression import Executable, ClauseElement
from provincia import *
from environment_constants import *
from funzioni import *
from profilo import *

#from Odict import *
#sys.path.append("/home/giuseppe/eclipse/plugins/org.python.pydev.debug_2.3.0.2011121518/pysrc/")
#from pydevd import *

class DataSource():
	"""
	gestisce le operazioni di lettura e scrittura sulle tabelle del db mmasgis per la gestione degli utenti dei profili, delle aree utente e dei censimenti
	"""
	def __init__(self,utonto,create=False):
		"""
		@param string: connectionstring
		@note: nellla connection string deve essere omesso il nome del db se si vuole che venga creato in automatico
"root:@localhost"
		"""
		self.cons=dbCons
		self.activeDb=utonto.getActiveDb()

		dbfile=self.activeDb.getUserName()+":"+self.activeDb.getPassword()+'@'+self.activeDb.getHost()+":"+str(self.activeDb.getPort())
		family=self.activeDb.getRDBMS()
		print "dbfile", dbfile
		self.family=self.cons.queries[family]
		#"mysql://"+dbfile
		#print "url","{0}://".format(family['family'])+dbfile
		self.engine = create_engine("{0}://".format(self.family['family'])+dbfile)#+"?charset=utf8&use_unicode=1",convert_unicode=True)
		metadata = MetaData(bind=self.engine)
		try:
			self.engine.execute(self.family['use'])
		except sqlalchemy.exc.DatabaseError:
			print "db non esiste"
		Session = sessionmaker(bind=self.engine)
		self.session=Session()

	def writeProfile(self,p,profile_id,company_id=1):
		profilo=profilo_std()
		profilo.nome_profilo=p['nome']
		profilo.azienda_id=company_id
		profilo.amministratore=p['amministratore']
		profilo.profilo_id=profile_id
		self.session.add(profilo)
		self.session.flush()
		self.session.refresh(profilo)
		profilo_Id=profilo.profilo_id
		print "profilo_id",profilo_Id
		for i in  p['funzioni']:
			rpf=rel_profilo_funzioni()
			rpf.profilo_id=profilo_Id
			rpf.funzione_id=i
			self.session.add(rpf)
		self.session.commit()

	def createDb(self,data,create=True):

		try:
			if create:
				self.engine.execute(self.family['drop']) #cancello il vecchio db
				self.engine.execute(self.family['create']) #create db
		except sqlalchemy.exc.ProgrammingError:
			print " il db esiste"
		try:
			self.engine.execute(self.family['use']) # select new db
		except sqlalchemy.exc.OperationalError:
			print "db non esiste"
		Base.metadata.create_all(self.engine)
		Session = sessionmaker(bind=self.engine)
		self.session=Session()
		#self.initDB(dbfile)
		#creo l'utente metmi
		#self.engine.execute("CREATE USER metmi IDENTIFIED BY  'metmi'")
		users=self.session.query(utente).count()#engine.execute(self.family['look4metmi']).first()[0]
		self.engine.execute(self.family['grant%'])
		#devo creare lo stesso utente pure su localhost
		self.engine.execute(self.family['grant*'])
		self.engine.execute(self.family['use'])
		user=utente()
		user=utente()
		user.nome_utente=data['admin']
		user.azienda_id=1
		user.password=""
		user.amministratore=1
		user.clruolo_id=1
		self.session.add(user)
		user.password=data['adminPass']
		self.session.add(user)
		self.session.flush()
		id_amministratore=user.utente_id
		r=ruolo()
		r.nome="amministratore"
		r.clruolo_id=1
		self.session.add(r)
		#aggiungo una riga alla tabella azienda
		az=company()
		az.nome_azienda="home"
		self.session.add(az)
		#rendo l'utente super user per le aree
		area=aree()
		area.amministratore=1
		area.utente_id=id_amministratore
		self.session.add(area)
		#rendo l'utente super user per le funzioni
		profile=profilo()
		profile.utente_id=id_amministratore
		profile.amministratore=1
		self.session.add(profile)
		dbs=rel_utente_dbmmas()
		dbs.amministratore=1
		dbs.utente_id=id_amministratore
		self.session.add(dbs)
		for f in functions:
			F=funzione()
			F.categoria=f['classe']
			F.nome=f['nome']
			self.session.add(F)
		for n,p in enumerate(profili):
			self.writeProfile(p, n+1)
		#rendo l'utente super user per i db
		self.session.commit()
		# rendo metmi amministratore su tutti i db e gli consento di accedere da remoto
		#self.engine.execute("GRANT ALL PRIVILEGES ON *.* TO metmi@'%' IDENTIFIED BY 'metmi' WITH GRANT OPTION")
		#g
		#self.session=Session()

		#self.initDB(dbfile)
		# self.session.query(provincia).count()
		#verifico che la tabella provincia si popolata
		c=self.session.query(provincia).count()
		if c==0:
			print "la tabella 'provincia' non e' ancora popolata"
			print "provvedo a popolare la tabella di servizio provincia"
			n=0
			# create a database connection
			#conn = self.engine.connect()
			#ins=provincia.insert()
			#self.engine.execute("use mmasgisDB")
			for p in province:
				n+=1
				pr=provincia(p[1],p[2])
				self.session.add(pr)

				#new_pr=ins.values(sigla=p[1],provincia=p[2])
				#conn.execute(new_pr)
				#self.engine.execute("insert into provincia(sigla,provincia)values({0},{1}".format(p[1],p[2]))
			self.session.commit()
			print "ho inserito {0} province ".format(n)

	def isNametaken(self,name,company_id):
		""" ritorna True se il nome utente e' gia' presente per una certa azienda
		@param string: nome utente
		@param int:company_id
		@return: bool
		"""
		c=self.session.query(utente).filter_by(nome_utente=name).filter_by(azienda_id=company_id).count()
		if c >0:
			return True
		else:
			return False
	def initDB(self,dbfile):
		"""
		@param string:stringa di connessione al db, con il seguente formato di stringa "user:pwd@host/nomedb" esempio root:xxxxx@localhost/parafarmacie
		inizializza il db
		"""
		MetaData.bind = "mysql://%s"%dbfile

		setup_all()

	def getUserCount(self):
		"""ritorna il valore attuale di UserCounter
		@return: int
		"""
		c= self.ds.value("UserCounter", 0).toInt()[0]
		return c

	def updateProfiles(self,userQname,profile):
		""" aggiorna il profilo utente, memorizzato nell'oggetto profiles
		@param User.qSettingsName: identificativo univoco dell'utente nel sistema nel formato user\d+
		@param {classesObject.qName:classesObject}:
		"""
		if self.ds.contains("profiles"):
			#recupero il dizionario dei profili
			profiles=self.ds.value("profiles").toPyObject()
			print profiles
		else:
			#creo un dizionario dei profili
			profiles=Relations()
		profiles.setCategory("profiles")
		profiles.updateRelations(userQname,profile)
		self.ds.setValue(profiles.getCategory(),profiles)

	def getUser(self, uname,pwd):
		"""ritorna l'utente identificato da uname e password
		@param string: user-name
		@param string: password
		@return: User
		"""
		for u in self.session.query(utente).filter_by(nome_utente=uname).filter_by(password=pwd):
			pass
		user=User(u.nome_utente,u.utente_id)
		user.setProfile(self.getUserProfile(u.utente_id))
		user.setId(u.utente_id)
		user.setRuolo(u.clruolo_id)
		user.setAmministratore(u.amministratore)
		user.setCompany(u.azienda_id)
		user.setDbs(self.getUserDbs(u.utente_id))
		user.setZone(self.getUserArea(u.utente_id))
		return user

	def getUsersList(self,company_id):
		"""ritorna la lista degli utenti registrati sul db per company_id
		@param int:company_id
		@return [User]
		"""
		users=[]
		for u in  self.session.query(utente).filter_by(azienda_id=company_id):
			user=self.getUserById(u.utente_id)
			users.append(user)
		return users

	def getUserById(self, Id):
		"""ritorna l'utente identificato da uname e password
		@param int: user_Id
		@return: User
		"""
		u=self.session.query(utente).filter_by(utente_id=Id).first()
		user=User(u.nome_utente,u.utente_id)
		user.setProfile(self.getUserProfile(u.utente_id))
		user.setId(u.utente_id)
		user.setRuolo(u.clruolo_id)
		user.setCompany(u.azienda_id)
		user.setAmministratore(u.amministratore)
		user.setDbset(self.getUserDbs(u.utente_id))
		user.setZone(self.getUserArea(u.utente_id))
		return user

	def getDbs(self,company_id):
		""" ritorna la lista dei db registrati all'azienda
		@param int: company_id
		@return: [Db]
		"""
		l=[]
		for  d in self.session.query(dbmmas).filter_by(azienda_id=company_id):
			db=Db(d.nome_db,d.db_id)
			l.append(db)
		return l

	def updateZones(self,userQname,profile):
		""" aggiorna le aree utente, memorizzate nell'oggetto zones
		@param User.qSettingsName: identificativo univoco dell'utente nel sistema nel formato user\d+
		@param {classesObject.qName:classesObject}:
		"""

		if self.ds.contains("zones"):
			#recupero il dizionario dei profili
			profiles=self.ds.value("zones").toPyObject()
			print profiles
			#creo un dizionario dei profili
		profiles=Relations()
		profiles.setCategory("zones")
		profiles.updateRelations(userQname,profile)
		self.ds.setValue(profiles.getCategory(),profiles)

	def setZones(self,relations):
		"""forza l'oggetto zones di Qsettings
		@param Relations:
		"""
		self.ds.setValue("zones",relations)

	def registerUser(self,user, qName):
		"""
		registra un utente  nel file di sistema con l'etichetta passata come parametro
		@param User:
		@param string: etichetta di identificazione utente
		"""
		#aggiorno il profilo memorizzato in profiles
		self.updateProfiles(qName, user.getProfile())
		#aggiorno i dbs memorizzati in dbs
		self.updateDbs(qName, user.getDbs()) #voglio inserire solo le chiavi in Qsettings
		#aggiorno le aree agente
		self.updateZones(qName, user.getZones)
		#resetto i profili  i db e le zone dell'utente per salvare in Qsettings solo dict vuoti
		user.resetProfile()
		user.resetDbs()
		user.resetZones()
		self.ds.setValue(qName, user)

	def setUserCounter(self,c):
		"""setta il valore di UserCount
		@param int: nuovo valore di userCount
		"""
		self.ds.setValue("userCounter",c)

	def setDbCounter(self,c):
		"""setta il valore di DbCounter
		@param int: nuovo valore di userCount
		"""
		self.ds.setValue("dbCounter",c)

	def getDbCount(self):
		"""ritorna il valore attuale di dbCounter
		@return: int
		"""
		c= self.ds.value("dbCounter",0).toInt()[0]
		return c

	def insertUser(self,nome,cl,passwd):
		"""
		inserisce un utente nel db
		@param string:nome utente
		@param int: clruolo_id
		@param string: password
		@attention: perche' le modifiche siano permanenti occorre invocare commitOperations
		"""
		user=utente()
		user.nome_utente=nome
		user.password=passwd
		user.clruolo_id=cl
		self.session.add(user)

	def countUsers(self):
		"""
		ritorna il numero di utenti registrati nel db
		@return: int
		"""
		c=self.session.query(utente).count()
		return c

	def deleteUserDbs(self,user_id):
		for i in self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id):
			self.session.delete(i)

	def deleteUserZone(self,user_id):
		for i in self.session.query(aree).filter_by(utente_id=user_id):
			self.session.delete(i)

	def getUserDbs(self,user_id,item=False):
		"""ritorna i db regfistrati ad un utente
		@param int:user_id
		@param bool: opzionale, se True ritorna la lista direl_utente_dbmmas
		@return: Dbset
		"""
		profile={}			#self.session.query(Pv).filter_by(pv_id=Id)

		#se un utente e' amministratore  per i db tutte le righe di profilo hanno settato amministratore a 1
		if self.isDbAdministrator(user_id):
			profile=DbSet(-1)
		else:
			for p in self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id):
				profile[p.db_id]=self.getDbMMas(p.db_id)
			profile=DbSet(profile)
		return profile
	def getUserDbRelations(self,user_id):
		return self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id)

	def getItemUtente(self,Id):
		"""ritorna il mapper di sqlalchemy per utente
		@param int:utente_id
		@return: mmasgisDb_sqlalchemy.utente
		"""
		return self.session.query(utente).filter_by(utente_id=Id).first()

	def createNewProfile(self):
		"""ritorna il mapper di sqlalchemy per un nuovo utente
		@return: mmasgisDb_sqlalchemy.utente
		"""
		return profilo()

	def createNewUser(self):
		"""ritorna il mapper di sqlalchemy per un nuovo utente
		@return: mmasgisDb_sqlalchemy.utente
		"""
		return utente()

	def getAllRDU(self,user_id,db_Id):
		"""
		ritorna le relazioni utente db
		@return: mmasgisDb_sqlalchemy.rel_utente_dbmmas
		"""
		return self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id).filter_by(db_id=db_Id).all()
	def getRDU(self,user_id,db_Id):
		"""
		ritorna la relazione utente db
		@return: mmasgisDb_sqlalchemy.rel_utente_dbmmas
		"""
		return self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id).filter_by(db_id=db_Id).first()

	def createNewRDU(self):
		"""ritorna il mapper di sqlalchemy per una nuova relazione utente_db
		@return: mmasgisDb_sqlalchemy.rel_utente_dbmmas
		"""
		return rel_utente_dbmmas()

	def getAllProfile(self,user_id):
		"""
		ritorna le relazioni utente funzione
		@return: mmasgisDb_sqlalchemy.profilo
		"""
		return self.session.query(profilo).filter_by(utente_id=user_id).all()

	def deleteProfile(self,user_id):
		for i in self.session.query(profilo).filter_by(utente_id=user_id).all():
			self.session.delete(i)
	def getProfile(self,user_id,function_id):
		"""
		ritorna la relazione utente funzione
		@return: mmasgisDb_sqlalchemy.profilo
		"""
		return self.session.query(profilo).filter_by(utente_id=user_id).filter_by(funzione_id=function_id).first()

	def deleteObject(self,obj):
		"""cancella un oggetto dalla sessione
		@param mmasgisDb_sqlalchemy:
		"""
		self.session.delete(obj)

	def getFunctions(self):
		"""ritorna la lista delle funzioni definite nel sistema
		@return: [Functions]
		"""
		l=[]
		for f in self.session.query(funzione).all():
			F=Function(f.nome,f.funzione_id)
			F.setCategory(f.categoria)
			l.append(F)
		return l

	def getUserArea(self,user_id):
		"""ritorna le aree di pertinenza  di un utente
		@return: <[string]> per l'utenteordinario<int> per l'utente root
		"""
		#se un utente e' amministratore tutte le righe di profilo hanno settato amministratore a 1
		profile={}
		if self.isAreaAdministrator(user_id):
				profile=Zone(-1)
		else:
			for p in self.session.query(aree).filter_by(utente_id=user_id):
				profile[p.UTB_id]=self.getUTB(p.UTB_id)
			profile=Zone(profile)
		return profile

	def getUserProfile(self,user_id):
		"""ritorna il profilo di un utente
		@return: <[int]> per l'utenteordinario<int> per l'utente root
		"""
		profile={}			#self.session.query(Pv).filter_by(pv_id=Id)

		#se un utente e' amministratore tutte le righe di profilo hanno settato amministratore a 1
		if self.isFunctionAdministrator(user_id):
			profile=Profile(-1)
		else:
			for p in self.session.query(profilo).filter_by(utente_id=user_id):
						if p is not None:
							profile[p.funzione_id]=self.getFunction(p.funzione_id)
			profile=Profile(profile)
		return profile

	def deleteUser(self,user_id):
		"""elimina un utente e tutte le sue  relazioni dal db
		@param int:user_id
		"""
		user=self.getItemUtente(user_id)
		self.session.delete(user)
		self.deleteProfile(user_id)
		self.deleteUserDbs(user_id)
		self.deleteUserZone(user_id)

	def getDbMMas(self,db_Id):
		"""
		ritorna il censimento relativo allo id passato
		@param int:db_id
		@return: Db
		"""
		DBMMAS=self.session.query(dbmmas).filter_by(db_id=db_Id).one()
		url=str(self.engine.url)
		#estraggo lo  host dallo url
		url=url[url.find('@')+1:]
		host=url[0:url.find('/')]
		db=Db('metmi','metmi',host,self.engine.name)
		db.setId(DBMMAS.db_id)
		db.setNameDb(DBMMAS.nome_db)
		return db

	def getFunction(self,function_id):
		"""
		ritorna la funzione con  id function_id
		@param int:function_id
		@return: Function
		"""
		f=self.session.query(funzione).filter_by(funzione_id=function_id).first()
		function=Function(f.nome,f.funzione_id)
		function.setCategory(f.categoria)
		return function

	def setAreaAdministrator(self,user_id,amministratore):
		"""
		rende l'utente amministratore per le aree
		@param int:utente_id
		@param bool:se True setta l'utente come amministratore
		@note: invocare commitOperations per rendere permanenti le modifiche
		"""
		l=lambda y:1 if y==True else 0
		for p in self.session.query(aree).filter_by(utente_id=user_id):
			p.amministratore=l(amministratore)

	def setProfileAdministrator(self,user_id,amministratore):
		"""
		rende l'utente amministratore per le funzioni
		@param int:utente_id
		@param bool:se True setta l'utente come amministratore
		@note: invocare commitOperations per rendere permanenti le modifiche
		"""
		l=lambda y:1 if y==True else 0
		for p in self.session.query(profilo).filter_by(utente_id=user_id):
			p.amministratore=l(amministratore)

	def setDbsAdministrator(self,user_id,amministratore):
		"""
		rende l'utente amministratore per i db
		@param int:utente_id
		@param bool:se True setta l'utente come amministratore
		@note: invocare commitOperations per rendere permanenti le modifiche
		"""
		l=lambda y:1 if y==True else 0
		for p in self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id):
			p.amministratore=l(amministratore)

	def addObject(self,obj):
		"""aggiunge un elemento alla sessione
		@param SQLalchemy.Element: riga daaggiungere
		"""
		self.session.add(obj)

	def isDbAdministrator(self,user_id):
		""" verifica chel'utente sia amministratore per i censimenti
		@param int:user_id
		@return: bool
		"""
		a=self.session.query(utente).filter_by(utente_id=user_id).first()
		if a is None:
			return False
		if a.amministratore!=1:
			return False
		else:
			return True

	def isAreaAdministrator(self,user_id):
		""" verifica chel'utente sia amministratore per le aree
		@param int:user_id
		@return: bool
		"""
		a=self.session.query(utente).filter_by(utente_id=user_id).first()
		if a is None:
			return False
		if a.amministratore!=1:
			return False
		else:
			return True

	def isFunctionAdministrator(self,user_id):
		""" verifica chel'utente sia amministratore per le funzioni
		@param int:user_id
		@return: bool
		"""
		a=self.session.query(utente).filter_by(utente_id=user_id).first()
		if a is None:
			return False
		if a.amministratore!=1:
			return False
		else:
			return True

	"""def addCensimento(self,name,censimento,versione, ins_utente):
			nome_db=Column(String(10))
	censimento=Column(Integer)
	versione=Column(Integer)
	ins_data=Column(DateTime)
	mod_data=Column(DateTime)
	ins_utente=Column(Integer)
	mod_utente=Column(Integer)"""

	def addArea(self,utente_id,area_id,administrator=False):
			"""
			aggiunge una funzione/abilita al profilo dell'utente
			@param int:utente_id
			@param string:signature della UTB
			@param bool opzionale:  se True setta a uno il campo amministratore della riga inserita in rel_utente_funzione
			@note: il campo amminisatratore della tabella profilo e' settato a 0 di default, cioe' come se fosse un utente ordinario
			@note: il parametro amministratore dovrebbe avere ilvalore ottenuto invocando isAdministrator
			@attention: perche' le modifiche siano permanenti occorre invocare commitOperations
			"""
			p=aree()
			p.utente_id=utente_id
			p.UTB_id=area_id
			if administrator:
				p.amministratore=1
			p.amministratore=0 #0 e' il valore di default per l'utente ordinario
			self.session.add(p)

	def addFunction(self,utente_id,funzione_id,administrator=False):
			"""
			aggiunge una funzione/abilita al profilo dell'utente
			@param int:utente_id
			@param int:function_id
			@param bool opzionale:  se True setta a uno il campo amministratore della riga inserita in rel_utente_funzione
			@note: il campo amminisatratore della tabella profilo e' settato a 0 di default, cioe' come se fosse un utente ordinario
			@note: il parametro amministratore dovrebbe avere ilvalore ottenuto invocando isAdministrator
			@attention: perche' le modifiche siano permanenti occorre invocare commitOperations
			"""
			p=profilo()
			p.utente_id=utente_id
			p.funzione_id=funzione_id
			if administrator:
				p.amministratore=1
			p.amministratore=0 #0 e' il valore di default per l'utente ordinario
			self.session.add(p)

	def addDb(self,user_id,db_id,administrator=False):
			"""
			aggiunge una funzione/abilita al profilo dell'utente
			@param int:utente_id
			@param int:function_id
			@param bool opzionale:  se True setta a uno il campo amministratore della riga inserita in rel_utente_funzione
			@note: il campo amminisatratore della tabella profilo e' settato a 0 di default, cioe' come se fosse un utente ordinario
			@note: il parametro amministratore dovrebbe avere ilvalore ottenuto invocando isAdministrator
			@attention: perche' le modifiche siano permanenti occorre invocare commitOperations
			"""
			p=rel_utente_dbmmas()
			p.utente_id=user_id
			p.db_id=db_id
			if administrator:
				p.amministratore=1
			p.amministratore=0 #0 e' il valore di default per l'utente ordinario
			self.session.add(p)

	def removeFunction(self,user_id,function_id):
		"""rimuove una funzione dal profilo utente
		@param int: utente_id
		@param int:funzione_id
		@attention: rimuovere una funzione non ha effetto se l'utente e' amministratore
		"""
		for f in self.session.query(profilo).filter_by(utente_id=user_id).filter_by(funzione_id=function_id):
			self.session.delete(f)

	def removeDb(self,user_id,db_Id):
		"""rimuove un db  da i dbs a sua disposizione
		@param int: utente_id
		@param int:funzione_id
		@attention: rimuovere una funzione non ha effetto se l'utente e' amministratore
		"""
		for f in self.session.query(rel_utente_dbmmas).filter_by(utente_id=user_id).filter_by(db_id=db_Id):
			self.session.delete(f)

	def removeArea(self,user_id,area_id):
		"""rimuove un'area dalle zone utente
		@param int: utente_id
		@param string:UTB_signature
		@attention: rimuovere una funzione non ha effetto se l'utente e' amministratore
		"""
		for f in self.session.query(aree).filter_by(utente_id=user_id).filter_by(UTB_id=area_id):
			self.session.delete(f)

	def deleteElement(self,row):
		"""
		invoca il delete di un oggetto nella sessione
		@param sqlalchemy.entity: oggetto da rimuovere
		"""
		self.session.delete(row)

	def commitOperations(self):
		"""
		esegue il commit della sessione
		"""
		self.session.commit()

	def flushOperations(self):
		"""
		esegue il flush della sessione
		"""
		self.session.commit()

	def isRegistered(self, uname,pwd):
		""" verifica che le credenziali siano corrette
		@param string: nome utente
		@param string:password
		@return: bool: True se le credenziali coincidono con quelle di un utente registrato
		"""
		u=self.session.query(utente).filter_by(nome_utente=uname).filter_by(password=pwd).count()
		if u!=0:
			return True
		else:
			return False

	def parser(self,txt,pattern):
		""" ritorna la lista di tutte le occorrenze del pattern nella stringa passata
		@param string:  stringa da esaminare
		@param string:  pattern da applicare
		@return: [string]
		"""
		match=re.compile(pattern)
		return match.findall(txt)

	def getObject(self,uname):
		"""ritorna l'oggetto registrato con uname
		@param string: username come appare nella lista  di QSettings
		@return User
		"""
		return self.ds.value(uname).toPyObject()

	def getUserList(self):
		""" ritorna la lista degli utenti registrati
		@return  [User]
		"""
		self.chiavi=self.ds.allKeys()
		userNames=[ str(i) for i in self.parser(self.chiavi.join("|"), "\user\d+")]
		users=[]
		for i in userNames:
			users.append(self.getObject(i))
		return users

	def removeDBs(self):
		"""rimuove i db registrati nel sistema
		"""
		self.chiavi=self.ds.allKeys()
		dbNames=[ str(i) for i in self.parser(self.chiavi.join("|"), "db\d+")]
		for db in dbNames:
			self.ds.remove(db)

	def getDbList(self):
		""" ritorna la lista degli utenti registrati
		@return  [extendedDb]
		"""
		self.chiavi=self.ds.allKeys()
		dbNames=[ str(i) for i in self.parser(self.chiavi.join("|"), "db\d+")]
		dbs=[]
		for i in dbNames:
			dbs.append(self.getObject(i))
		return dbs

	def registerDb(self,db):
		"""registra un db nel sistema
			e incrementa dbCounter
		@param extendedDb:
		"""
		self.chiavi=self.ds.allKeys()
		Id=self.ds.value("dbCounter", 0).toInt()[0]
		#registro il db
		#db.setSettingsName("db{0}".format(Id))
		print "registro il db:db{0}".format(Id)
		self.ds.setValue("db{0}".format(Id),db)
		# incremento il contatore
		Id+=1
		self.ds.setValue("dbCounter",Id)
		print "dbCounter",Id


text:
/* @flow */

import type { Headers, Query, Body, Method } from './http'

import { Merge, UrlJoin } from './http'
import { isNil, propEither } from './lib.js'

export type Auth =
  { user     : string
  , password : string
  }

export type Timeout =
  { connection : ?number
  , socket     : ?number
  }

export type TimeoutOpt = number | Timeout

export type Retry = (retry: number, error: any) => number

export type Input =
  { url?            : string
  , method?         : Method
  , auth?           : Auth
  , is_json?        : boolean
  , timeout?        : ?TimeoutOpt
  , retries?        : number | Retry
  , encoding?       : string
  , headers?        : Headers
  , query?          : string | Query
  , body?           : Body
  , followRedirect? : boolean
  }

export type LibraryOptions =
  { url?            : string
  , method          : Method
  , headers?        : Headers
  , query?          : string | Query
  , body?           : Body
  , auth?           : string
  , is_json?        : boolean
  , encoding?       : string
  , timeout?        : ?TimeoutOpt
  , retries?        : number | Retry
  , followRedirect? : boolean
  }

const DEFAULT_INPUT = {
  url: undefined
, method: "GET"
, headers: {}
, query: {}
, body: {}
, auth: undefined
, is_json: false
, encoding: "utf8"
, timeout: undefined
, retries: undefined
, followRedirect: undefined
}

export function AuthToString(a: Auth): string {
  return `${a.user}:${a.password}`
}

export function InputToLibraryOptions(i: Input): LibraryOptions {

  return {
    url            : i.url
  , method         : i.method || "GET"
  , headers        : i.headers
  , query          : i.query
  , body           : i.body
  , auth           : i.auth ? AuthToString(i.auth) : undefined
  , is_json        : i.is_json
  , encoding       : i.encoding
  , timeout        : i.timeout
  , retries        : i.retries
  , followRedirect : i.followRedirect
  }

}

function __mergeTimeoutOpt(x: ?TimeoutOpt, y: ?TimeoutOpt) : ?TimeoutOpt {
  if (x === undefined) return y;
  if (y === undefined) return x;

  if (typeof x === 'object' && typeof y === 'object')
    return Object.assign({}, x, y)

  return y
}

export function InputMerge(x: Input, y: Input): Input {

  if (!x) return y
  if (!y) return x

  return {
    url: UrlJoin(x.url, y.url)
  , method: propEither('method', x, y)
  , headers: Object.assign({}, x.headers, y.headers)
  , query: Merge(x.query, y.query)
  , body: Merge(x.body, y.body)
  , auth: propEither('auth', x, y)
  , is_json: propEither('is_json', x, y)
  , encoding: propEither('encoding', x, y)
  , timeout: __mergeTimeoutOpt(x.timeout, y.timeout)
  , retries: propEither('retries', x, y)
  , followRedirect: propEither('followRedirect', x, y)
  }
}

function __InputReducer(x: Input, y: Input): Input {
  return InputMerge(x, y)
}

export function InputMergeAll(...args: Array<Input>): Input {
  return args.reduce(__InputReducer, DEFAULT_INPUT)
}


text:
class Emailer < ActionMailer::Base
  def state_change(opts)
    @job = opts[:job]
    mail(to: opts[:to],
         subject: "Codem Notification: Job #{@job.id} has entered #{opts[:state]}")
  end
end


text:
package org.d2rq.functional_tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.d2rq.D2RQTestUtil;
import org.d2rq.jena.ModelD2RQ;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.DC;

/**
 * Functional test suite for D2RQ. These are functional tests (as opposed to
 * unit tests). The suite runs different find queries against the
 * ISWC database, using the example map provided with the D2RQ manual.
 * To run the test, you must have the MySQL version accessible.
 * You may have to adapt the JDBC connection information at the beginning
 * of the map file to fit your database server.
 *
 * Functional tests that exercise a ModelD2RQ by calling Model API functions. For
 * notes on running the tests, see {@link AllTests}.
 *
 * To see debug information, uncomment the enableDebug() call in the setUp() method.
 *
 * @author Richard Cyganiak (richard@cyganiak.de)
 */
public class ModelAPITest {
	private ModelD2RQ model;

	@Before
	public void setUp() throws Exception {
		model = new ModelD2RQ(
				D2RQTestUtil.loadTurtle("example/mapping-iswc.ttl"), "http://test/");
	}

	@After
	public void tearDown() throws Exception {
		model.close();
	}

	@Test
	public void testListStatements() {
		StmtIterator iter = model.listStatements();
		int count = 0;
		while (iter.hasNext()) {
			Statement stmt = iter.nextStatement();
			stmt.toString();
			count++;
		}
		assertEquals(322, count);
	}

	@Test
	public void testHasProperty() {
		assertTrue(model.getResource("http://test/papers/1").hasProperty(DC.creator));
	}
}


text:
import os
import mock

from common import context
from upvote.gae.datastore.models import singleton
from upvote.gae.lib.bit9 import utils as bit9_utils
from upvote.gae.lib.testing import basetest
from absl.testing import absltest

class Bit9TestCase(basetest.UpvoteTestCase):

  def setUp(self, **kwargs):

    super(Bit9TestCase, self).setUp(**kwargs)

    # Set up a fake Bit9ApiAuth entity in Datastore.
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(
        absltest.get_default_test_srcdir(),
        'upvote/gae/lib/bit9',
        'fake_credentials.json')
    self.Patch(
        bit9_utils.singleton.kms_ndb.EncryptedBlobProperty, '_Encrypt',
        return_value='blah')
    self.Patch(
        bit9_utils.singleton.kms_ndb.EncryptedBlobProperty, '_Decrypt',
        return_value='blah')
    singleton.Bit9ApiAuth.SetInstance(api_key='blah')

    self.mock_ctx = mock.Mock(spec=bit9_utils.api.Context)
    self.Patch(
        bit9_utils.api, 'Context', return_value=self.mock_ctx)

  def tearDown(self):

    super(Bit9TestCase, self).tearDown()

    # We have to reset the LazyProxy in utils, otherwise utils.CONTEXT will
    # cache the mock context and break subsequent tests.
    context.ResetLazyProxies()

  def PatchApiRequests(self, *results):
    requests = []
    for batch in results:
      if isinstance(batch, list):
        requests.append([obj.to_raw_dict() for obj in batch])
      else:
        requests.append(batch.to_raw_dict())
    self.mock_ctx.ExecuteRequest.side_effect = requests


text:
class BotWorker
  include Sidekiq::Worker
  include OpenMensa

  def perform
    token = '228539999:AAFBC-Ea2hC9E2OdFED02p6_8HOw_J0HxHw'

    Telegram::Bot::Client.run(token) do |bot|
      api_helper = OpenMensa::Api.new

      bot.listen do |message|
        case message.text
        when '/start'
          bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}")
        when '/stop'
          bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}")
        when '/essen'
          bot.api.send_message(chat_id: message.chat.id, text: api_helper.meal_list, parse_mode: 'HTML')
        end
      end
    end
  end
end


text:
/*!
  \file   version.c
  \brief  Version numbering for LAME.

  Contains functions which describe the version of LAME.

  \author A.L. Faber
  \version \$Id: version.c,v 1.1 2007-04-15 00:43:43 dave Exp $
  \ingroup libmp3lame
*/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdio.h>
#include "version.h"    /* macros of version numbers */

#ifdef WITH_DMALLOC
#include <dmalloc.h>
#endif

/*! Stringify \a x. */
#define STR(x)   #x
/*! Stringify \a x, perform macro expansion. */
#define XSTR(x)  STR(x)

/*! Get the LAME version string. */
/*!
  \param void
  \return a pointer to a string which describes the version of LAME.
*/
const char*  get_lame_version ( void )		/* primary to write screen reports */
{
    /* Here we can also add informations about compile time configurations */

#if   LAME_ALPHA_VERSION
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) " "
        "(alpha " XSTR(LAME_PATCH_VERSION) ", " __DATE__ " " __TIME__ ")";
#elif LAME_BETA_VERSION
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) " "
        "(beta " XSTR(LAME_PATCH_VERSION) ", " __DATE__ ")";
#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) "." XSTR(LAME_PATCH_VERSION);
#else
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION);
#endif

    return str;
}

/*! Get the short LAME version string. */
/*!
  It's mainly for inclusion into the MP3 stream.

  \param void
  \return a pointer to the short version of the LAME version string.
*/
const char*  get_lame_short_version ( void )
{
    /* adding date and time to version string makes it harder for output
       validation */

#if   LAME_ALPHA_VERSION
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) " (alpha)";
#elif LAME_BETA_VERSION
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) " (beta)";
#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) "." XSTR(LAME_PATCH_VERSION);
#else
    static /*@observer@*/ const char *const str =
        XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION);
#endif

    return str;
}

/*! Get the _very_ short LAME version string. */
/*!
  It's used in the LAME VBR tag only.

  \param void
  \return a pointer to the short version of the LAME version string.
*/
const char*  get_lame_very_short_version ( void )
{
    /* adding date and time to version string makes it harder for output
       validation */

#if   LAME_ALPHA_VERSION
    static /*@observer@*/ const char *const str =
       "LAME" XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) "a";
#elif LAME_BETA_VERSION
    static /*@observer@*/ const char *const str =
       "LAME" XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) "b";
#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)
    static /*@observer@*/ const char *const str =
       "LAME" XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) "r";
#else
    static /*@observer@*/ const char *const str =
       "LAME" XSTR(LAME_MAJOR_VERSION) "." XSTR(LAME_MINOR_VERSION) " ";
#endif

    return str;
}

/*! Get the version string for GPSYCHO. */
/*!
  \param void
  \return a pointer to a string which describes the version of GPSYCHO.
*/
const char*  get_psy_version ( void )
{
#if   PSY_ALPHA_VERSION > 0
    static /*@observer@*/ const char *const str =
        XSTR(PSY_MAJOR_VERSION) "." XSTR(PSY_MINOR_VERSION)
        " (alpha " XSTR(PSY_ALPHA_VERSION) ", " __DATE__ " " __TIME__ ")";
#elif PSY_BETA_VERSION > 0
    static /*@observer@*/ const char *const str =
        XSTR(PSY_MAJOR_VERSION) "." XSTR(PSY_MINOR_VERSION)
        " (beta " XSTR(PSY_BETA_VERSION) ", " __DATE__ ")";
#else
    static /*@observer@*/ const char *const str =
        XSTR(PSY_MAJOR_VERSION) "." XSTR(PSY_MINOR_VERSION);
#endif

    return str;
}

/*! Get the URL for the LAME website. */
/*!
  \param void
  \return a pointer to a string which is a URL for the LAME website.
*/
const char*  get_lame_url ( void )
{
    static /*@observer@*/ const char *const str = LAME_URL;

    return str;
}

/*! Get the numerical representation of the version. */
/*!
  Writes the numerical representation of the version of LAME and
  GPSYCHO into lvp.

  \param lvp
*/
void get_lame_version_numerical ( lame_version_t *const lvp )
{
    static /*@observer@*/ const char *const features = "";  /* obsolete */

    /* generic version */
    lvp->major = LAME_MAJOR_VERSION;
    lvp->minor = LAME_MINOR_VERSION;
#if LAME_ALPHA_VERSION
    lvp->alpha = LAME_PATCH_VERSION;
    lvp->beta  = 0;
#elif LAME_BETA_VERSION
    lvp->alpha = 0;
    lvp->beta  = LAME_PATCH_VERSION;
#else
    lvp->alpha = 0;
    lvp->beta  = 0;
#endif

    /* psy version */
    lvp->psy_major = PSY_MAJOR_VERSION;
    lvp->psy_minor = PSY_MINOR_VERSION;
    lvp->psy_alpha = PSY_ALPHA_VERSION;
    lvp->psy_beta  = PSY_BETA_VERSION;

    /* compile time features */
    /*@-mustfree@*/
    lvp->features = features;
    /*@=mustfree@*/
}

const char*  get_lame_os_bitness ( void )
{
    static /*@observer@*/ const char *const strXX = "";
    static /*@observer@*/ const char *const str32 = "32bits";
    static /*@observer@*/ const char *const str64 = "64bits";

    switch (sizeof(void*)){
    case 4:
        return str32;
        break;
    case 8:
        return str64;
        break;
    default:
        return strXX;
    }
}

/* end of version.c */


text:
/**
 * EG1302A - Spring 2014
 * Badr Basager
 * 2/20/2014
 * Worksheet Assignment 12
 **/

#include <stdio.h>
#include <stdlib.h>

/*
   The goal of this program is to create an invoice for the user.
   You will ask the user for price and quantity for two items,
   calculate tax, and print out the total cost for the user.
*/

/* TODO: Create a #define statement to define your COMPANY_NAME */ #define COMPANY_NAME "Badr's Company"
/* TODO: Create a #define statement to define the invoice number */ #define INVOICE_NUMBER 3

int main()
{

   /* TODO: Create your variables to hold:
          item 1 and item 2 counts
	  item 1 and item 2 prices
	  tax information
   */
    int quantity1;
    int quantity2;
    float price1;
    float price2;
    float taxinformation;
    float subtotal;
    float taxdollars;
    float totalcost;

   /* TODO: Ask the user for the quantity of item 1 */
   printf(" Enter item 1 quantity: ");
   scanf("%d", &quantity1);
   /* TODO: Ask the user for the price of item 1 */
   printf(" Enter Item 1 price: $");
   scanf("%f", &price1);
   /* TODO: Ask the user for the quantity of item 2 */
   printf(" Enter item 2 quantity: ");
   scanf("%d", &quantity2);
   /* TODO: Ask the user for the price of item 2 */
   printf(" Enter Item 2 price: $");
   scanf("%f", &price2);
   /* TODO: Ask the user for the tax rate in percent */
   printf("Enter the tax rate (in percent): ");
   scanf("%f", &taxinformation);

   /* TODO: Calculate the total cost for the user:
        Don't forget: the user enters the tax rate as
        a percentage and you must change it into a value to
        use to calculate the total
   */
   subtotal = quantity1 * price1 + quantity2 * price2;
   taxdollars = (taxinformation / 100.0) * subtotal;
   totalcost = subtotal + taxdollars;

   /* TODO: Print the invoice for the user (make sure to
          use tabs to line up all the columns!):
          Company name
	  Invoice number
	  Item 1 cost, number ordered, total amount
	  Item 2 cost, number ordered, total amount
	  Tax rate in percent
	  Tax amount in $
	  Total cost for all the items and tax
   */
    printf(" %s\n", COMPANY_NAME);
    printf(" Invoice #%d\n", INVOICE_NUMBER);
    printf(" Item 1: %d @ $%.2f per item $%.2f  \n", quantity1, price1, quantity1*price1 );
    printf(" Item 2: %d @ $%.2f per item $%.2f \n", quantity2, price2, quantity2*price2 );
    printf(" Tax rate: %.2f \n", taxinformation);
    printf(" Tax amount: $%.2f \n", taxdollars);
    printf(" Total cost: $%.2f \n", totalcost);

   /* EXAMPLE RUN OF THE CODE:

      Enter Item 1 quantity: 1
      Enter Item 1 price: $5
      Enter Item 2 quantity: 10
      Enter Item 2 price: $3
      Enter the tax rate (in percent): 10

          Price Industries, Inc.
	  Invoice #12345

	  Item 1: 1 @ $5.00 per item    $5.00
	  Item 2: 10 @ $3.00 per item   $30.00
	  Tax rate:                     10.00%
	  Tax amount:                   $3.50
	  Total cost:                   $38.50
   */

   return 0;
}


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../actions';
import MainDesktop from './desktop/main';
import MobileComponent from './mobile/mobile_component';
import Responsive from 'react-responsive';

const Desktop = ({ children }) => <Responsive minWidth={768} children={children} />;
const Mobile = ({ children }) => <Responsive maxWidth={767} children={children} />;
class App extends Component {
  componentWillMount() {
    const userLang = this.setLanguage();
    this.props.selectedLanguage(userLang);
  }
  setLanguage(){
    return (navigator.language || navigator.userLanguage) == "en-US" ? "EN" : "CA"  ;
  }
  render() {
    return (
      <div>
          <Mobile>
           <MobileComponent />
          </Mobile>
          <Desktop>
              <MainDesktop></MainDesktop>
          </Desktop>
    </div>
    );
  }
}

export default connect (null,actions)(App);


text:
namespace Bit.BlazorUI;

/// <summary>
/// Represents an object that can be either a single value or an array of values. This is used for type safe js-interop.
/// </summary>
/// <typeparam name="T">The type of data this <see cref="BitChartIndexableOption{T}"/> is supposed to hold.</typeparam>
[Newtonsoft.Json.JsonConverter(typeof(IndexableOptionConverter))]   // newtonsoft for now
public class BitChartIndexableOption<T> : IEquatable<BitChartIndexableOption<T>>
{
    /// <summary>
    /// The compile-time name of the property which gets the wrapped value. This is used internally for serialization.
    /// </summary>
    internal const string PropertyName = nameof(BoxedValue);

    // for serialization, there has to be a cast to object anyway
    internal object BoxedValue => IsIndexed ? (object)IndexedValues : SingleValue;

    private readonly T[] _indexedValues;

    /// <summary>
    /// The indexed values represented by this instance.
    /// </summary>
    public T[] IndexedValues
    {
        get
        {
            if (!IsIndexed)
                throw new InvalidOperationException("This instance represents a single value. The indexed values are not available.");

            return _indexedValues;
        }
    }

    private readonly T _singleValue;

    /// <summary>
    /// The single value represented by this instance.
    /// </summary>
    public T SingleValue
    {
        get
        {
            if (IsIndexed)
                throw new InvalidOperationException("This instance represents an array of values. The single value is not available.");

            return _singleValue;
        }
    }

    /// <summary>
    /// Gets the value indicating whether the option wrapped in this <see cref="BitChartIndexableOption{T}"/> is indexed.
    /// <para>True if the wrapped value represents an array of <typeparamref name="T"/>, false if it represents a single value of <typeparamref name="T"/>.</para>
    /// </summary>
    public bool IsIndexed { get; }

    /// <summary>
    /// Creates a new instance of <see cref="BitChartIndexableOption{T}"/> which represents a single value.
    /// </summary>
    /// <param name="singleValue">The single value this <see cref="BitChartIndexableOption{T}"/> should represent.</param>
    public BitChartIndexableOption(T singleValue)
    {
        _singleValue = singleValue != null ? singleValue : throw new ArgumentNullException(nameof(singleValue));
        IsIndexed = false;
    }

    /// <summary>
    /// Creates a new instance of <see cref="BitChartIndexableOption{T}"/> which represents an array of values.
    /// </summary>
    /// <param name="indexedValues">The array of values this <see cref="BitChartIndexableOption{T}"/> should represent.</param>
    public BitChartIndexableOption(T[] indexedValues)
    {
        _indexedValues = indexedValues ?? throw new ArgumentNullException(nameof(indexedValues));
        IsIndexed = true;
    }

    /// <summary>
    /// Implicitly wraps a single value of <typeparamref name="T"/> to a new instance of <see cref="BitChartIndexableOption{T}"/>.
    /// </summary>
    /// <param name="singleValue">The single value to wrap</param>
    public static implicit operator BitChartIndexableOption<T>(T singleValue)
    {
        CheckIsNotIndexableOption(singleValue.GetType());

        return new BitChartIndexableOption<T>(singleValue);
    }

    /// <summary>
    /// Implicitly wraps an array of values of <typeparamref name="T"/> to a new instance of <see cref="BitChartIndexableOption{T}"/>.
    /// </summary>
    /// <param name="indexedValues">The array of values to wrap</param>
    public static implicit operator BitChartIndexableOption<T>(T[] indexedValues)
    {
        CheckIsNotIndexableOption(indexedValues.GetType().GetElementType());

        return new BitChartIndexableOption<T>(indexedValues);
    }

    private static void CheckIsNotIndexableOption(Type type)
    {
        if (!type.IsGenericType) return;
        if (type.GetGenericTypeDefinition() == typeof(BitChartIndexableOption<>))
            throw new ArgumentException("You cannot use an indexable option inside an indexable option.");
    }

    /// <summary>
    /// Determines whether the specified <see cref="BitChartIndexableOption{T}"/> instance is considered equal to the current instance.
    /// </summary>
    /// <param name="other">The <see cref="BitChartIndexableOption{T}"/> to compare with.</param>
    /// <returns>true if the objects are considered equal; otherwise, false.</returns>
    public bool Equals(BitChartIndexableOption<T> other)
    {
        if (IsIndexed != other.IsIndexed) return false;

        if (IsIndexed)
        {
            if (IndexedValues == other.IndexedValues) return true;

            return Enumerable.SequenceEqual(IndexedValues, other.IndexedValues);
        }
        else
        {
            return EqualityComparer<T>.Default.Equals(SingleValue, other.SingleValue);
        }
    }

    /// <summary>
    /// Determines whether the specified object instance is considered equal to the current instance.
    /// </summary>
    /// <param name="obj">The object to compare with.</param>
    /// <returns>true if the objects are considered equal; otherwise, false.</returns>
    public override bool Equals(object obj)
    {
        // an indexable option cannot store null
        if (obj == null) return false;

        if (obj is BitChartIndexableOption<T> option)
        {
            return Equals(option);
        }
        else
        {
            if (IsIndexed)
            {
                return IndexedValues.Equals(obj);
            }
            else
            {
                return SingleValue.Equals(obj);
            }
        }
    }

    /// <summary>
    /// Returns the hash of the underlying object.
    /// </summary>
    /// <returns>The hash of the underlying object.</returns>
    public override int GetHashCode()
    {
        var hashCode = -506568782;
        hashCode = hashCode * -1521134295 + EqualityComparer<T[]>.Default.GetHashCode(_indexedValues);
        hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(_singleValue);
        hashCode = hashCode * -1521134295 + IsIndexed.GetHashCode();
        return hashCode;
    }

    /// <summary>
    /// Determines whether two specified <see cref="BitChartIndexableOption{T}"/> instances contain the same value.
    /// </summary>
    /// <param name="a">The first <see cref="BitChartIndexableOption{T}"/> to compare</param>
    /// <param name="b">The second <see cref="BitChartIndexableOption{T}"/> to compare</param>
    /// <returns>true if the value of a is the same as the value of b; otherwise, false.</returns>
    public static bool operator ==(BitChartIndexableOption<T> a, BitChartIndexableOption<T> b) => a.Equals(b);

    /// <summary>
    /// Determines whether two specified <see cref="BitChartIndexableOption{T}"/> instances contain different values.
    /// </summary>
    /// <param name="a">The first <see cref="BitChartIndexableOption{T}"/> to compare</param>
    /// <param name="b">The second <see cref="BitChartIndexableOption{T}"/> to compare</param>
    /// <returns>true if the value of a is different from the value of b; otherwise, false.</returns>
    public static bool operator !=(BitChartIndexableOption<T> a, BitChartIndexableOption<T> b) => !(a == b);
}


text:
<!DOCTYPE html>

  	<meta charset="utf-8">
  	<title>La production documentaire d'une région à l'autre</title>
  	<link rel="shortcut icon" href="Logos/logo-etude-violet.svg" />

    <link href="css/stylesheet.css" rel="stylesheet">
    <link href="css/dataStyle.css" rel="stylesheet">
    <link rel="stylesheet" href="css/bar.css">
    <link rel="stylesheet" href="css/donut2.css">

    <link href='https://fonts.googleapis.com/css?family=Lato:400,100,100italic,300,300italic,700,400italic,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="./css/jquery-jvectormap-2.0.3.css" type="text/css" media="screen"/>

LA PRODUCTION
DOCUMENTAIRE
D'UNE RÉGION À L'AUTRE

EN DATAVISUALISATION,
ÇA DONNE QUOI ?

LA PRODUCTION DOCUMENTAIRE
D'UNE RÉGION À L'AUTRE

Films en Bretagne, avec l'aide de sept étudiants, vous propose une data visualisation réalisée dans le cadre du projet Hyblab organisé par OuestMédiaLab. Cette étude est le résultat d'un travail collectif entre des étudiants Nantais de Sciences com,  de l'école AGR et de Polytech.

Cette nouvelle technique journalistique permet une analyse et une lecture visuelle des données de manière  interactive et personnalisable.

Les cartographies interactives utilisées pour ce projet de data journalisme illustrent la réalité de la production documentaire pour chaque Région entre 2012 et 2014. Cette datavisualisation s'articule autour de différentes données relatives aux sociétés de production, aux auteurs et aux financements des collectivités territoriales.

INTRO

Producteurs

Auteurs

Financement

INTERVIEW
Estelle ROBIN

Répartition des sociétés de production de documentaires par région

Cette carte représente la part des sociétés de production de documentaires aidées par les collectivités territoriales, pour chaque Région, par rapport à l'ensemble des sociétés de production de documentaire aidées. En cliquant sur la Région de votre choix, vous aurez accès à des données complémentaires.

            SOURCES & CONTACTS

Cliquez sur une région
 pour plus d'informations

INTRO

Producteurs

Auteurs

Financement

INTERVIEW
Estelle ROBIN

Nombre d'auteurs de documentaires audiovisuels par région

Cette carte représente la répartition des auteurs de documentaires audiovisuels. Les différentes couleurs illustrent une densité moyenne par Région sur les trois années 2012-2013-2014. En cliquant sur la Région de votre choix, des données complémentaires vous permettent de découvrir le nombre d'auteurs présents dans chaque Région et de le comparer au nombre d'auteurs résidant en Île-de-France et dans le reste des régions.

            SOURCES & CONTACTS

Cliquez sur une région pour plus d'informations

2012

2013

2014

INTRO

Producteurs

Auteurs

Financement

INTERVIEW
Estelle ROBIN

Part de financement des collectivités territoriales attribuée à la production régionale

Cette carte représente le budget attribué par chaque Région au financement de la production audiovisuelle et cinématographique. Les différentes couleurs illustrent une intervention moyenne sur les trois années 2012-2013-2014. En cliquant sur la Région de votre choix, des données complémentaires vous permettent de découvrir et de comparer les montants attribués par chaque Région à la production de documentaires ainsi qu'à la production audiovisuelle et cinématographique tous genres confondus.

            SOURCES & CONTACTS

Cliquez sur une région
 pour plus d'informations

INTRO

Producteurs

Auteurs

Financement

INTERVIEW
Estelle ROBIN

Cette data visualisation permet de rendre compte du dynamisme des régions en matière de production de documentaires audiovisuels et cinématographiques. Elle montre la répartition des acteurs : auteurs et producteurs ; et permet d'obtenir une photographie des politiques territoriales à la veille de la création des nouvelles régions.

Sources :
Ciclic - Agence régionale du Centre pour le livre, l'image et la culture numérique
SCAM - Société civile des auteurs multimédia

Elisabeth CLÉMENT
Sophie FLEISCHL
Isabelle GUIVARC'H

Sixtine COUDERT
Marine GUILLEMOT

Manon MOREAU
Vincent MOULINEC

Laura JACQUEL
Pierre MICHEL
Valentin PREZELIN

              Un projet issu des ateliers du Hyblab


text:
tx_news.templateLayouts {
    10 = Neuste Beiträge
}


text:
package de.oliver_heger.linedj.extract.metadata

/**
 * Definition of a trait providing direct access to the most important meta
 * data tags for audio files.
 *
 * Through the interface defined here values for central meta data can be
 * queried without having to respect a specific version. Because all tags
 * may be absent the methods return ''Option'' objects.
 */
trait MetaDataProvider {
  /**
   * Returns the title of the song.
   * @return an option for the song title
   */
  def title: Option[String]

  /**
   * Returns the name of the performing artist.
   * @return an option for the artist name
   */
  def artist: Option[String]

  /**
   * Returns the name of the album.
   * @return an option for the album name
   */
  def album: Option[String]

  /**
   * Returns a string value for the inception year.
   * @return an option for the inception year as string
   */
  def inceptionYearString: Option[String]

  /**
   * Returns a string value for the track number.
   * @return an option for the track number as string
   */
  def trackNoString: Option[String]

  /**
   * Returns the inception year.
   * @return an option for the inception year
   */
  def inceptionYear: Option[Int] =
    inceptionYearString flatMap parseNumericProperty

  /**
   * Returns the numeric track number.
   * @return an option for the track number
   */
  def trackNo: Option[Int] =
    trackNoString flatMap parseNumericProperty

  /**
   * Parses a (partly) numeric property in string form. If the property value
   * is not numeric, ''None'' is returned. Otherwise, the leading part of the
   * value that consists only of digits is parsed into a numeric value.
   *
   * @param value the value of the property as a string
   * @return an option for the corresponding numeric value
   */
  private def parseNumericProperty(value: String): Option[Int] = {
    val numericValue = value takeWhile Character.isDigit
    if (numericValue.isEmpty) {
      None
    } else {
      Some(numericValue.toInt)
    }
  }
}


text:
if [[ ! $INSTALL_SCRIPT ]]; then
  echo "(!) Error: You must use the installer script."
  exit
fi

echo "[+] Install PNPM (Phantom NPM)"

curl -fsSL https://get.pnpm.io/install.sh | sh -

echo "[+] An entry was added into ~/.bashrc at the bottom"
echo "[+] Reload to use command with: $ source ~/.bashrc"

echo "[+] Recommended: Add an alias to your ~/.bashrc or other sourced file:"
echo "    alias pn=pnpm"

echo -e "\n[+] Install node with: $ pnpm env use --global lts"
echo -e "[+] You can install everything with $ pn / $ pnpm i -g rather than npm also"


text:
module Guard
  FOODCRITIC_VERSION = '3.0.0'.freeze
end