text:
"use strict";

var pgutil = require('./pgutil.js');

pgutil.setupDatabase( function (results) {

console.log('database setup finished with result: '+results);

});


text:
package ws.ucm.cliente.descarga;

import javax.xml.bind.annotation.XmlRegistry;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the ws.ucm.cliente.descarga package.
 * <p>An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ws.ucm.cliente.descarga
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link FileInfo }
     *
     */
    public FileInfo createFileInfo() {
        return new FileInfo();
    }

    /**
     * Create an instance of {@link ProcessResponse }
     *
     */
    public ProcessResponse createProcessResponse() {
        return new ProcessResponse();
    }

    /**
     * Create an instance of {@link IdcPropertyList }
     *
     */
    public IdcPropertyList createIdcPropertyList() {
        return new IdcPropertyList();
    }

    /**
     * Create an instance of {@link IdcFile }
     *
     */
    public IdcFile createIdcFile() {
        return new IdcFile();
    }

    /**
     * Create an instance of {@link IdcProperty }
     *
     */
    public IdcProperty createIdcProperty() {
        return new IdcProperty();
    }

    /**
     * Create an instance of {@link Process }
     *
     */
    public Process createProcess() {
        return new Process();
    }

    /**
     * Create an instance of {@link StatusInfo }
     *
     */
    public StatusInfo createStatusInfo() {
        return new StatusInfo();
    }

    /**
     * Create an instance of {@link GetFileByIDResult }
     *
     */
    public GetFileByIDResult createGetFileByIDResult() {
        return new GetFileByIDResult();
    }

}

redpajama_set_name: RedPajamaGithub


text:
[![](https://img.shields.io/github/license/falahati/WinFormAnimation.svg?style=flat-square)](https://github.com/falahati/WinFormAnimation/blob/master/LICENSE)
[![](https://img.shields.io/github/commit-activity/y/falahati/WinFormAnimation.svg?style=flat-square)](https://github.com/falahati/WinFormAnimation/commits/master)
[![](https://img.shields.io/github/issues/falahati/WinFormAnimation.svg?style=flat-square)](https://github.com/falahati/WinFormAnimation/issues)

A simple library for animating controls/values in .Net WinForm (.Net 3.5 and later). Key frame (Path) based and fully customizable.

*Please note that even though this library designed for WinForm but its usage is not limited to WinForm and can be used in other environments. Only reference of the library is to 'System.Drawing' name space.*

## How to get
[![](https://img.shields.io/nuget/dt/WinFormAnimation.svg?style=flat-square)](https://www.nuget.org/packages/WinFormAnimation)
[![](https://img.shields.io/nuget/v/WinFormAnimation.svg?style=flat-square)](https://www.nuget.org/packages/WinFormAnimation)

This library is available as a NuGet package at [nuget.org](https://www.nuget.org/packages/WinFormAnimation/).

## Help me fund my own Death Star

[![](https://img.shields.io/badge/crypto-CoinPayments-8a00a3.svg?style=flat-square)](https://www.coinpayments.net/index.php?cmd=_donate&reset=1&merchant=820707aded07845511b841f9c4c335cd&item_name=Donate&currency=USD&amountf=20.00000000&allow_amount=1&want_shipping=0&allow_extra=1)
[![](https://img.shields.io/badge/shetab-ZarinPal-8a00a3.svg?style=flat-square)](https://zarinp.al/@falahati)
[![](https://img.shields.io/badge/usd-Paypal-8a00a3.svg?style=flat-square)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ramin.graphix@gmail.com&lc=US&item_name=Donate&no_note=0&cn=&curency_code=USD&bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted)

**--OR--**

You can always donate your time by contributing to the project or by introducing it to others..

## Documentation

* `Float2D`: A class containing two `float` values as Vertical and Horizontal coordinates representing a point in a 2D plane.
* `Float3D`: A class containing three `float` values as Vertical, Horizontal and Depth coordinates representing a point in a 3D plane.
* `Path`: A class containing a `float` starting and a `float` ending point for a single dimensional animation as well as duration and the function to control the animation.
* `Path2D`: A class containing a `Float2D` starting and a `Float2D` ending point for a two dimensional animation as well as duration and the function to control the animation.
* `Path3D`: A class containing a `Float3D` starting and a `Float3D` ending point for a three dimensional animation as well as duration and the function to control the animation.
* `Animator`: A class for animating an array of `Path` objects. This class is one of the main classes and starting points of a basic animation.
* `Animator2D`: A class for animating an array of `Path2D` objects. This class is one of the main classes and starting points of a basic animation.
* `Animator2D`: A class for animating an array of `Path3D` objects. This class is one of the main classes and starting points of a basic animation.
* `SafeInvoker`: A class holding a reference to a function to invoke in the correct thread, detected by a `Control` object passed to it. Useful for easier UI manipulations.
* `SafeInvoker<T>`: Same as `SafeInvoker` class but with a generic argument for the function to invoke.

For full documentation of the classes and their members, please take a look at our doxygen page at [falahati.github.io](https://falahati.github.io/WinFormAnimation/doxygen).

## Basic examples
### ONE DIMENSIONAL ANIMATION OF A PROPERTY
Following code animates a property named `Value` of a `ProgressBar` named `pb_progress` in 5 seconds from zero to one hundred:
```C#
new Animator(new Path(0, 100, 5000))
    .Play(pb_progress, Animator.KnownProperties.Value);
```

### TWO DIMENSIONAL ANIMATION OF A PROPERTY
Following code animates a `Form` in two paths. First one moves the `Form` from (0, -100) to (100, 200) and second path waits for 3 seconds and then moved the `Form` to its initial location in 2 seconds. (`this` is a `Form`)
```C#
new Animator2D(
        new Path2D(0, 100, -100, 200, 5000).ContinueTo(this.Location.ToFloat2D(), 2000, 3000))
    .Play(this, Animator2D.KnownProperties.Location);
```

### THREE DIMENSIONAL ANIMATION OF A PROPERTY
Following code animates a property named `CustomColor` of a `Control` named `c_customLabel` in 2 seconds and after a delay of 1 second using the `AnimationFunctions.CubicEaseIn` function and with maximum of 10 frames per second.
```C#
new Animator3D(
        new Path3D(Color.Blue.ToFloat3D(), Color.Red.ToFloat3D(), 2000, 1000, AnimationFunctions.CubicEaseIn),
        FPSLimiterKnownValues.LimitTen)
    .Play(c_customLabel, "CustomColor");
```

### KEYFRAMES
There are extension methods for `Path`, `Path2D`, `Path3D` and their arrays to let you continue the path easily and define the key frames as fast as possible. For example, following code moves a `Control` named `c_control` in a rectangular path infinitely:
```C#
new Animator2D(
    new Path2D(new Float2D(100, 100), new Float2D(200, 100), 1000)
        .ContinueTo(new Float2D(200, 200), 1000)
        .ContinueTo(new Float2D(100, 200), 1000)
        .ContinueTo(new Float2D(100, 100), 1000))
{
    Repeat = true
}.Play(c_control, Animator2D.KnownProperties.Location);
```

### CALLBACKS
It is possible to define a custom callback as frame handler as well as defining a call back to handle the end of the animation. Following example will call a method named `CustomSetMethod` for setting new values and handle the frames, and starts the animation in reverse path after its end for one more time:

```C#
var animator = new Animator(new Path(100, 200, 1000).ContinueTo(400, 500));
animator.Play(new SafeInvoker<float>(CustomSetMethod), new SafeInvoker(() =>
{
    animator.Paths = animator.Paths.Select(path => path.Reverse()).Reverse().ToArray();
    animator.Play(new SafeInvoker<float>(CustomSetMethod));
}));
```

## Demo
Check the 'WinFormAnimation.Samples' project for simple usage examples.
![Screenshot](/screenshot.gif?raw=true "Screenshot")

## License
The MIT License (MIT)

Copyright (c) 2016-2020 Soroush Falahati

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
<?php

namespace DbEtreeOrg\Controller;
use Zend\Mvc\Controller\AbstractActionController
    , Zend\View\Model\ViewModel
    , Db\Entity\Checksum as ChecksumEntity
    , Zend\Form\Annotation\AnnotationBuilder
    , Db\Filter\Normalize
    , Zend\View\Model\JsonModel
    ;

class ChecksumController extends AbstractActionController
{
    public function indexAction()
    {
        return array(
        );
    }

    public function detailAction()
    {
        $id = $this->getRequest()->getQuery()->get('id');
        if (!$id)
            return $this->plugin('redirect')->toUrl('/source');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        $checksum = $em->getRepository('Db\Entity\Checksum')->find($id);

        if (!$checksum)
            throw new \Exception("Checksum $id not found");

        return array(
            'checksum' => $checksum
        );
    }

    public function createAction()
    {
        if (!$this->getServiceLocator()->get('zfcuser_auth_service')->hasIdentity())
            return $this->plugin('redirect')->toUrl('/user/login');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $checksum = new ChecksumEntity();
        $builder = new AnnotationBuilder();
        $form = $builder->createForm($checksum);

        $id = $this->getRequest()->getQuery()->get('id');
        $source = $em->getRepository('Db\Entity\Source')->find($id);

        if (!$source)
            throw new \Exception("Source $id not found");

        if ($this->getRequest()->isPost()) {
            $form->setData($this->getRequest()->getPost()->toArray());
            $form->setUseInputFilterDefaults(false);
            $form->setInputFilter($checksum->getInputFilter());

            if ($form->isValid()) {
                $data = $form->getData();
                $checksum->exchangeArray($form->getData());
                $checksum->setSource($source);

                $em->persist($checksum);
                $em->flush();

                die();
            }
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setVariable('form', $form);
        $viewModel->setVariable('source', $source);
        return $viewModel;
    }

    public function editAction()
    {
        if (!$this->getServiceLocator()->get('zfcuser_auth_service')->hasIdentity())
            return $this->plugin('redirect')->toUrl('/user/login');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $id = $this->getRequest()->getQuery()->get('id');
        $checksum = $em->getRepository('Db\Entity\Checksum')->find($id);

        if (!$checksum)
            throw new \Exception("Checksum $id not found");

        $builder = new AnnotationBuilder();
        $form = $builder->createForm($checksum);
        $form->setData($checksum->getArrayCopy());

        if ($this->getRequest()->isPost()) {
            $form->setData($this->getRequest()->getPost()->toArray());
            $form->setUseInputFilterDefaults(false);
            $form->setInputFilter($checksum->getInputFilter());

            if ($form->isValid()) {
                $data = $form->getData();
                $checksum->exchangeArray($form->getData());

                $em->persist($checksum);
                $em->flush();

                die();
            }
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setVariable('form', $form);
        $viewModel->setVariable('checksum', $checksum);
        return $viewModel;
    }

    public function deleteAction()
    {
        if (!$this->getServiceLocator()->get('zfcuser_auth_service')->hasIdentity())
            return $this->plugin('redirect')->toUrl('/user/login');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $id = $this->getRequest()->getQuery()->get('id');
        $checksum = $em->getRepository('Db\Entity\Checksum')->find($id);
        if (!$checksum)
            return $this->plugin('redirect')->toUrl('/');

#        if (!sizeof($venue->getPerformances())
#            and !sizeof($venue->getVenueGroups())
#            and !sizeof($venue->getLinks())
#            and !sizeof($venue->getComments()))
#        {
        $sourceId = $checksum->getSource()->getId();
        $em->remove($checksum);
        $em->flush();
#        }

        return $this->plugin('redirect')->toUrl('/source/detail?id=' . $sourceId);
    }

    public function searchJsonAction()
    {
        $query = $this->getRequest()->getQuery()->get('q');

        $filterNormalize = new Normalize();

        $query = $filterNormalize(trim($query));

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $venues = $em->getRepository('Db\Entity\Venue')->findLike(array(
            'nameNormalize' => '%' . $query . '%',
        ), array(), 20);

        $return = array();
        $i = 0;
        foreach ($venues as $venue) {
            if (++$i > 25) break;
            $return[] = $venue->getArrayCopy();
        }

        $jsonModel = new JsonModel;
        $jsonModel->setVariable('venues', $return);

        return $jsonModel;
    }
}


text:
package alerting

import (
	"fmt"
	"net/http"
	"strings"
	"sync"
	"time"

	"bosun.org/graphite"
	"github.com/hashicorp/golang-lru"
	"github.com/raintank/worldping-api/pkg/log"
	m "github.com/raintank/worldping-api/pkg/models"
	"github.com/raintank/worldping-api/pkg/setting"
	"gopkg.in/raintank/schema.v1"
)

func ChanExecutor(jobQueue <-chan *m.AlertingJob, cache *lru.Cache) {
	executorNum.Inc(1)
	defer executorNum.Dec(1)
	var wg sync.WaitGroup
	for j := range jobQueue {
		wg.Add(1)
		go func(job *m.AlertingJob) {
			jobQueueInternalItems.Value(int64(len(jobQueue)))
			jobQueueInternalSize.Value(int64(setting.Alerting.InternalJobQueueSize))
			execute(job, cache)
			wg.Done()
		}(j)
	}
	log.Info("Alerting: chanExecutor jobQueue closed")
	// dont return untl all jobs have executed.
	wg.Wait()
	log.Info("Alerting: chanExecutor all pending jobs executed.")
}

// execute executes an alerting job.
func execute(job *m.AlertingJob, cache *lru.Cache) {
	key := fmt.Sprintf("%d-%d", job.Id, job.LastPointTs.Unix())

	if time.Now().Sub(job.GeneratedAt) > time.Minute*time.Duration(10) {
		executorNumTooOld.Inc(1)
		return
	}

	if found, _ := cache.ContainsOrAdd(key, true); found {
		executorNumAlreadyDone.Inc(1)
		log.Debug("Alerting: skipping job which has already been seen. jobId: %s", key)
		return
	}

	executorNumOriginalTodo.Inc(1)

	preExec := time.Now()
	executorJobExecDelay.Value(preExec.Sub(job.LastPointTs))

	headers := make(http.Header)
	headers.Add("x-org-id", fmt.Sprintf("%d", job.OrgId))
	start := job.LastPointTs.Add(time.Duration(int64(-1)*job.Frequency*int64(job.HealthSettings.Steps)) * time.Second)
	req := graphite.Request{
		Start:   &start,
		End:     &job.LastPointTs,
		Targets: []string{fmt.Sprintf("worldping.%s.*.%s.error_state", job.Slug, strings.ToLower(job.CheckForAlertDTO.Type))},
	}
	log.Debug("Alerting: querying graphite with /render?target=%s&from=%d&until=%d", req.Targets[0], req.Start.Unix(), req.End.Unix())
	res, err := req.Query(setting.Alerting.GraphiteUrl+"render", headers)
	durationExec := time.Since(preExec)
	executorJobQueryGraphite.Value(durationExec)
	log.Debug("Alerting: job results - job:%v err:%v res:%v", job, err, res)

	if err != nil {
		executorAlertOutcomesErr.Inc(1)
		log.Error(3, "Alerting: query failed for job %q : %s", job, err.Error())
		return
	}

	newState, err := eval(res, job.HealthSettings)
	if err != nil {
		executorAlertOutcomesErr.Inc(1)
		log.Error(3, "Alerting: eval failed for job %q : %s", job, err.Error())
		return
	}
	job.NewState = newState
	job.TimeExec = preExec

	// lets only update the stateCheck value every second check, which will half the load we place on the DB.
	if job.State != job.NewState || job.TimeExec.Sub(job.StateCheck) > (time.Second*time.Duration(job.Frequency*2)) {
		ProcessResult(job)
	}

	//store the result in graphite.
	StoreResult(job)

	switch newState {
	case m.EvalResultOK:
		executorAlertOutcomesOk.Inc(1)
	case m.EvalResultCrit:
		executorAlertOutcomesCrit.Inc(1)
	case m.EvalResultUnknown:
		executorAlertOutcomesUnkn.Inc(1)
	}
}

func eval(res graphite.Response, healthSettings *m.CheckHealthSettings) (m.CheckEvalResult, error) {
	if len(res) == 0 {
		executorGraphiteEmptyResponse.Inc(1)
		return m.EvalResultUnknown, fmt.Errorf("fatal: no data returned for job")
	}
	badEndpoints := 0
	endpointsWithData := 0
	for _, ep := range res {
		curStreak := 0
		maxStreak := 0
		nonNullPoints := 0
		for _, dp := range ep.Datapoints {
			if dp[0].String() == "null" || dp[0].String() == "" {
				continue
			}
			nonNullPoints++
			val, err := dp[0].Float64()
			if err != nil {
				log.Error(3, "Alerting: failed to parse graphite response. value %s=[%s, %s] not a number. %s", ep.Target, dp[0].String(), dp[1].String(), err.Error())
				return m.EvalResultUnknown, err
			}
			if val > 0.0 {
				curStreak++
			} else {
				if curStreak > maxStreak {
					maxStreak = curStreak
				}
				curStreak = 0
			}
		}
		if nonNullPoints > 0 {
			endpointsWithData++
		}
		if curStreak > maxStreak {
			maxStreak = curStreak
		}

		if maxStreak >= healthSettings.Steps {
			badEndpoints++
		}
	}

	if endpointsWithData == 0 {
		return m.EvalResultUnknown, nil
	}

	if badEndpoints >= healthSettings.NumProbes {
		return m.EvalResultCrit, nil
	}

	return m.EvalResultOK, nil
}

func StoreResult(job *m.AlertingJob) {
	metrics := make([]*schema.MetricData, 3)
	metricNames := [3]string{"ok_state", "warn_state", "error_state"}
	for pos, state := range metricNames {
		metrics[pos] = &schema.MetricData{
			OrgId:    int(job.OrgId),
			Name:     fmt.Sprintf("health.%s.%s.%s", job.Slug, strings.ToLower(job.CheckForAlertDTO.Type), state),
			Metric:   fmt.Sprintf("health.%s.%s.%s", job.Slug, strings.ToLower(job.CheckForAlertDTO.Type), state),
			Interval: int(job.Frequency),
			Value:    0.0,
			Unit:     "state",
			Time:     job.LastPointTs.Unix(),
			Mtype:    "gauge",
			Tags:     nil,
		}
		metrics[pos].SetId()
	}
	if int(job.NewState) >= 0 {
		metrics[int(job.NewState)].Value = 1.0
	}

	metricsPublisher.Add(metrics)
}


text:
package com.example.android.navigationdrawer;
//Interface for different variations

import android.view.animation.Transformation;
import android.widget.ImageView;

public interface Arrangement {
    void transformImageBitmap(ImageView child, Transformation t, int i, int j, CoverFlow coverFlow);

    int getDelta();
}


text:
#include "../../script/parser/Lexer.h"

#include<lang/log/LogLevel.h>

#include <commonlib/commonlib.h>
#include "lang/tools/parser/LexerIStreamWrapper.h"

using namespace yy;

namespace IAS {
namespace Lang {
namespace Script {
namespace Parser {

/*************************************************************************/
Lexer::Lexer(Tools::Parser::LexerIStreamFactory* pLexerIStreamFactory,
		     Tools::Parser::ISourceLocationStore *pSourceLocationStore):
		LexerBase(pLexerIStreamFactory, pSourceLocationStore){
	IAS_TRACER;

	init();
}
/*************************************************************************/
Lexer::~Lexer() throw(){
	IAS_TRACER;
}
/*************************************************************************/
const ::IAS::Lang::Tools::Parser::LexerLocation* Lexer::getLocation(){
	IAS_TRACER;
	return getActiveWrapper();
}
/*************************************************************************/
void Lexer::init(){

	IAS_TRACER;
	hmKeywords["PROGRAM"]=Token::T_PROGRAM;
	hmKeywords["IMPORT"]=Token::T_IMPORT;
	hmKeywords["BEGIN"]=Token::T_BEGIN;
	hmKeywords["END"]=Token::T_END;

	hmKeywords["CALL"]=Token::T_CALL;

	hmKeywords["FOR"]=Token::T_FOR;
	hmKeywords["TO"]=Token::T_TO;
	hmKeywords["STEP"]=Token::T_STEP;

	hmKeywords["WHILE"]=Token::T_WHILE;
	hmKeywords["DO"]=Token::T_DO;

	hmKeywords["WITH"]=Token::T_WITH;

	hmKeywords["SORT"]=Token::T_SORT;
	hmKeywords["USING"]=Token::T_USING;
	hmKeywords["MERGE"]=Token::T_MERGE;
	hmKeywords["INDEX"]=Token::T_INDEX;

	hmKeywords["AS"]=Token::T_AS;
	hmKeywords["OF"]=Token::T_OF;
	hmKeywords["ARRAY"]=Token::T_ARRAY;
	hmKeywords["RETURNS"]=Token::T_RETURNS;
	hmKeywords["VAR"]=Token::T_VAR;

	hmKeywords["IF"]=Token::T_IF;
	hmKeywords["THEN"]=Token::T_THEN;
	hmKeywords["ELSE"]=Token::T_ELSE;

	hmKeywords["AND"]=Token::T_AND;
	hmKeywords["OR"]=Token::T_OR;
	hmKeywords["NOT"]=Token::T_NOT;

	hmKeywords["NEW"]=Token::T_NEW;
	hmKeywords["COPYOF"]=Token::T_COPYOF;
	hmKeywords["DETACH"]=Token::T_DETACH;
	hmKeywords["SIZEOF"]=Token::T_SIZEOF;
	hmKeywords["CREATE"]=Token::T_CREATE;
	hmKeywords["DELETE"]=Token::T_DELETE;
	hmKeywords["TYPE"]=Token::T_TYPE;
	hmKeywords["TYPENS"]=Token::T_TYPENS;

	hmKeywords["ISSET"]=Token::T_ISSET;
	hmKeywords["ISNULL"]=Token::T_ISNULL;
	hmKeywords["ISTYPE"]=Token::T_ISTYPE;
	hmKeywords["ISINSTANCE"]=Token::T_ISINSTANCE;

	hmKeywords["STRLEN"]=Token::T_STRLEN;

	hmKeywords["EXTERNAL"]=Token::T_EXTERNAL;

	hmKeywords["RETURN"]=Token::T_RETURN;

	hmKeywords["TRY"]=Token::T_TRY;
	hmKeywords["CATCH"]=Token::T_CATCH;
	hmKeywords["THROW"]=Token::T_THROW;

	hmKeywords["DEFINE"]=Token::T_DEFINE;
	hmKeywords["EXTENSION"]=Token::T_EXTENSION;
	hmKeywords["ALIAS"]=Token::T_ALIAS;

	hmConstants["TRUE"]=Token::T_BOOLEAN;
	hmConstants["FALSE"]=Token::T_BOOLEAN;

	hmConstants["NULL"]=Token::T_NULL;

}

/*************************************************************************/
const Lexer::TokenInfo& Lexer::nextToken(){
	IAS_TRACER;

	iCurrentState=S_Start;
	aTokenInfo.setToken(Token::T_NONE);
	aTokenInfo.clearInfo();

	while(iCurrentState != S_End)
		handleStep();

	IAS_LOG(::IAS::Lang::LogLevel::INSTANCE.isDetailedInfo(),"Token:"<<aTokenInfo.getToken());
	return aTokenInfo;

}
/*************************************************************************/
void Lexer::handleStep(){
	IAS_TRACER;

	unsigned char c = getActiveWrapper()->getChar();

	if(getActiveWrapper()->isEOF()){

		if(iCurrentState==S_BlockComment)
			IAS_THROW(ParseErrorException("Block comment was not closed",getActiveWrapper()));

		if(iCurrentState==S_LineComment)
			iCurrentState=S_Start;

		if(iCurrentState==S_Start){

			while(getActiveWrapper()->isEOF() && getStackSize() > 1)
				popIStreamWrapper();

			if(getActiveWrapper()->isEOF()){
				iCurrentState=S_End;
				aTokenInfo.setToken(Token::T_EOF);
				return;
			}else
				c = getActiveWrapper()->getChar();
		}else{
			c=0;
		}
	}

	//TODO (M) map char -> function
	switch(iCurrentState){

		case S_Start:      handleState_Start(c); break;
		case S_String:     handleState_String(c); break;
		case S_StringEsc:  handleState_StringEsc(c); break;

		case S_Symbol:      handleState_Symbol(c); break;
		case S_SpecSymbol:  handleState_SpecSymbol(c); break;
		case S_OpenSquare:  handleState_OpenSquare(c); break;
		case S_CloseSquare: handleState_CloseSquare(c); break;
		case S_Integer:     handleState_Integer(c); break;
		case S_Float:       handleState_Float(c); break;
		case S_Greater:     handleState_Greater(c); break;
		case S_Less:        handleState_Less(c); break;
		case S_Eq:          handleState_Eq(c); break;
		case S_Colon:       handleState_Colon(c); break;
		case S_Slash:          handleState_Slash(c); break;
		case S_QuestionMark:   handleState_QuestionMark(c); break;
		case S_LineComment:    handleState_LineComment(c); break;
		case S_BlockComment:   handleState_BlockComment(c); break;

		default:
			IAS_THROW(InternalException(String("CurrentState not handled: ")+TypeTools::IntToString(iCurrentState)));
	}
}
/*************************************************************************/
void Lexer::handleState_Start(unsigned char c){
	IAS_TRACER;

	if(isspace(c))
		return;

	//TODO (M) map char -> function - or struct ( token, state)
	switch(c){
		case '(': aTokenInfo.setToken(Token::T_OPEN_PAR); iCurrentState=S_End; return;
		case ')': aTokenInfo.setToken(Token::T_CLOSE_PAR); iCurrentState=S_End; return;

		case '+': aTokenInfo.setToken(Token::T_PLUS); iCurrentState=S_End; return;
		case '-': aTokenInfo.setToken(Token::T_MINUS); iCurrentState=S_End; return;

		case '*': aTokenInfo.setToken(Token::T_ASTERISK); iCurrentState=S_End; return;
		case '%': aTokenInfo.setToken(Token::T_PERCENT); iCurrentState=S_End; return;

		case ',': aTokenInfo.setToken(Token::T_COMMA); iCurrentState=S_End; return;
		case '.': aTokenInfo.setToken(Token::T_DOT); iCurrentState=S_End; return;
		case ';': aTokenInfo.setToken(Token::T_SEMICOLON); iCurrentState=S_End; return;

		case '[': iCurrentState=S_OpenSquare; return;
		case ']': iCurrentState=S_CloseSquare; return;

		case '/': iCurrentState=S_Slash; return;
		case ':': iCurrentState=S_Colon; return;
		case '=': iCurrentState=S_Eq; return;
		case '<': iCurrentState=S_Less; return;
		case '>': iCurrentState=S_Greater; return;
		case '"': iCurrentState=S_String; return;
		case '{': iCurrentState=S_SpecSymbol; return;
		case '?': iCurrentState=S_QuestionMark; return;
	}

	if(isdigit(c)){
		aTokenInfo.addChar(c);
		iCurrentState=S_Integer;
		return;
	}

	if(isalnum(c) || c == '_'){
		aTokenInfo.addChar(c);
		iCurrentState=S_Symbol;
		return;
	}

	IAS_LOG(::IAS::Lang::LogLevel::INSTANCE.isError(),"Unknown char:"<<(c)<<":"<<(int)c<<"\n");
	IAS_THROW(ParseErrorException(String("Unknown character: ")
			+(char)(c>' '?c:'_')+" ("+TypeTools::IntToString(c)+") ",
			getActiveWrapper()));
}
/*************************************************************************/
void Lexer::handleState_String(unsigned char c){
	IAS_TRACER;

	if(c == '"'){

		iCurrentState=S_End;
		aTokenInfo.setToken(Token::T_STRING,true);

	}else if(c == '\\'){
		iCurrentState=S_StringEsc;

		iEscCharLen   = 0;
		iEscCharValue = 0;

	}else{
		aTokenInfo.addChar(c);
	}

}
/*************************************************************************/
void Lexer::handleState_SpecSymbol(unsigned char c){
	IAS_TRACER;

	if(c == '}'){

		iCurrentState=S_End;
		aTokenInfo.setToken(Token::T_SYMBOL,true);

	}else{
		aTokenInfo.addChar(c);
	}

}
/*************************************************************************/
void Lexer::handleState_OpenSquare(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == '['){
		aTokenInfo.setToken(Token::T_DOUBLE_OPEN_SQUARE);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_OPEN_SQUARE);
	}

}
/*************************************************************************/
void Lexer::handleState_CloseSquare(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == ']'){
		aTokenInfo.setToken(Token::T_DOUBLE_CLOSE_SQUARE);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_CLOSE_SQUARE);
	}

}
/*************************************************************************/
void Lexer::handleState_StringEsc(unsigned char c){
	IAS_TRACER;

	if(iEscCharLen){

		if('0' <= c && c <= '7'){

			iEscCharValue =  (iEscCharValue << 3) + (c - '0');

			if(++iEscCharLen < 3)
				return;

			aTokenInfo.addChar(iEscCharValue);

		}else{
			IAS_THROW(ParseErrorException(String("Bad octed number after \\")));
		}

	}else {

		if('0' <= c && c <= '7'){

			iEscCharValue = (iEscCharValue << 3) + (c - '0');
			iEscCharLen++;

			return;

		}else
			switch(c){

			case '"' : aTokenInfo.addChar(c); break;

			case 'n' : aTokenInfo.addChar('\n'); break;
			case 't' : aTokenInfo.addChar('\t'); break;
			case '\\': aTokenInfo.addChar('\\'); break;

		default:
			aTokenInfo.addChar(c);
		}
	};

	iCurrentState=S_String;
}
/*************************************************************************/
void Lexer::handleState_Symbol(unsigned char c){
	IAS_TRACER;

	if(isalpha(c) || isdigit(c) || c=='_'){
		aTokenInfo.addChar(c);
	}else{

		getActiveWrapper()->ungetChar();
		iCurrentState=S_End;

		KeywordsMap::const_iterator it = hmKeywords.find(aTokenInfo.getInfo());

		if(it != hmKeywords.end()){
			aTokenInfo.setToken(it->second,false);
		}else{

			it = hmConstants.find(aTokenInfo.getInfo());

			if(it != hmConstants.end()){
				aTokenInfo.setToken(it->second,true);
			}else{
				aTokenInfo.setToken(Token::T_SYMBOL,true);
			};

		}
	}
}
/*************************************************************************/
void Lexer::handleState_Integer(unsigned char c){
	IAS_TRACER;
	if(isdigit(c)){
		aTokenInfo.addChar(c);
	}else if(c == '.'){
		iCurrentState=S_Float;
		aTokenInfo.addChar(c);
	}else{
		getActiveWrapper()->ungetChar();
		iCurrentState=S_End;
		aTokenInfo.setToken(Token::T_INTEGER,true);
	}

}
/*************************************************************************/
void Lexer::handleState_Float(unsigned char c){
	IAS_TRACER;
	if(isdigit(c)){
		aTokenInfo.addChar(c);
	}else{
		getActiveWrapper()->ungetChar();
		iCurrentState=S_End;
		aTokenInfo.setToken(Token::T_FLOAT,true);
	}

}
/*************************************************************************/
void Lexer::handleState_Greater(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == '='){
		aTokenInfo.setToken(Token::T_GREATER_EQ);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_GREATER);
	}

}
/*************************************************************************/
void Lexer::handleState_Less(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == '='){
		aTokenInfo.setToken(Token::T_LESS_EQ);
	}else if(c == '>'){
		aTokenInfo.setToken(Token::T_DIFF);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_LESS);
	}

}
/*************************************************************************/
void Lexer::handleState_Eq(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == '='){
		aTokenInfo.setToken(Token::T_EQ);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_ASSIGN);
	}

}
/*************************************************************************/
void Lexer::handleState_Colon(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == ':'){
		aTokenInfo.setToken(Token::T_DOUBLECOLON);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_COLON);
	}

}
/*************************************************************************/
void Lexer::handleState_QuestionMark(unsigned char c){
	IAS_TRACER;

	iCurrentState=S_End;

	if(c == '='){
		aTokenInfo.setToken(Token::T_CONDASSIGN);
	}else{
		getActiveWrapper()->ungetChar();
		aTokenInfo.setToken(Token::T_QMARK);
	}

}
/*************************************************************************/
void Lexer::handleState_Slash(unsigned char c){
	IAS_TRACER;

	if(c == '/'){
		iCurrentState=S_LineComment;
	}else if(c == '*'){
		iCurrentState=S_BlockComment;
	}else{
		aTokenInfo.setToken(Token::T_SLASH);
		iCurrentState=S_End;
		getActiveWrapper()->ungetChar();
	}
}
/*************************************************************************/
void Lexer::handleState_BlockComment(unsigned char c){
	IAS_TRACER;

	if(c == '*'){

		c = getActiveWrapper()->getChar();

		if(c == '/'){
			iCurrentState=S_Start;
		}else{
			getActiveWrapper()->ungetChar();
		}
	}
}
/*************************************************************************/
void Lexer::handleState_LineComment(unsigned char c){
	IAS_TRACER;

	if(c == '\n')
		iCurrentState=S_Start;
}
/*************************************************************************/
}
}
}
}


text: echo This file is executable by everyone.


text:
% Check if figure has been closed
if ishandle(hFigs{2}) == 0 % If figure has been closed
    button = questdlg(['You closed Figure 2: plotPower. Reopen?']);
    if strcmp(button,'Yes')
        disp(['You closed Figure 2: plotPower. Reopening for further use.'])
        hFigs{2} = figure;
    else
        postProcOptions.plotPower = false;
        disp(['You closed Figure 2: plotPower. Disabling for further use.'])
    end
end

% Plot figure, if applicable
if postProcOptions.plotPower
    % Format all power predictions and measurements as a vector
    time    = [sol_array.time];
    pwWFSim = [sol_array.PEst];
    pwLES   = [sol_array.PTrue];

    % if postProcOptions.powerForecast > 0
    %     disp(['Forecasting currently disabled. This is especially difficult since' ...
    %           ' typically you do not know the control settings of the turbines a priori.']);
    %     k_end = postProcOptions.powerForecast+sol.k;
    %     disp(['Forecasting power for k = ' num2str(sol.k+1) ' until k = ' num2str(k_end) '.']);
    %     sol_tmp    = sol;  % Copy current sol
    %     sol_tmp.uu = sol.u;
    %     sol_tmp.vv = sol.v;
    %     sol_tmp.pp = sol.p;
    %     timeFC = []; pwFC = [];
    %     while sol_tmp.k < k_end
    %         [ sol_tmp,~ ] = WFSim_timestepping( sol_tmp, sys, Wp, postProcOptions );
    %         pwFC(:,sol_tmp.k-sol.k) = sol_tmp.turbine.power; % Extract power
    %         timeFC(sol_tmp.k-sol.k) = sol_tmp.time;
    %     end
    %     pwFC = movmean(pwFC',[10 0])'; % Low-pass filter power forecast
    %     t_st = min([postProcOptions.powerForecast, 60]); % t-shortterm
    %     try
    %         RMSE_FC_shortterm = sqrt(mean((pwLES(:,timeFC(1:t_st))-pwFC(:,1:t_st)).^2,2));
    %         RMSE_FC_longterm  = sqrt(mean((pwLES(:,timeFC)-pwFC).^2,2));
    %         %             RMSE_FC_shortterm = mean(abs(pwLES(:,timeFC(1:t_st))-pwFC(:,1:t_st)),2);
    %         %             RMSE_FC_longterm  = mean(abs(pwLES(:,timeFC)-pwFC),2);
    %         disp(['Short-term Mean RMSE forecasted vs. true power for k = ' num2str(sol.k+1) ':' num2str(sol.k+t_st) ' is ' num2str(mean(RMSE_FC_shortterm),'%10.2e\n') '.']);
    %         disp(['Long-term  Mean RMSE forecasted vs. true power for k = ' num2str(sol.k+1) ':' num2str(k_end) ' is ' num2str(mean(RMSE_FC_longterm),'%10.2e\n') '.']);
    %     end
    % end

    % Plot results
    set(0,'CurrentFigure',hFigs{2}); clf;
    subplotDim = numSubplots(Wp.turbine.N); % Determine optimal layout for subplots
    for j = 1:Wp.turbine.N
        subplot(subplotDim(1),subplotDim(2),j);
        plot(time,pwLES(j,:),'k-','lineWidth',0.25,'DisplayName', ['LES']); hold on
        plot(time,pwWFSim(j,:),'-','lineWidth',1.0,'DisplayName', ['WFObs: ' strucObs.filtertype]); hold on;
        %     if postProcOptions.powerForecast > 0 && length(timeFC) > 0
        %         plot(timeFC,pwFC(j,:),'-','lineWidth',0.75,'DisplayName',['WFObs: ' strucObs.filtertype ' (FC)']); hold on;
        %     end
        legend('-DynamicLegend');
        xlabel('Time (s)');
        %     xlim([0 Wp.sim.NN]);
        ylim([0 1e6*ceil(max([pwWFSim(:); pwLES(:)])/1e6)]);
        grid on;
        ylabel('Power (W)');
        title(['Turbine ' num2str(j) '']);
    end;
end


text:
package au.com.scds.chats.dom.module.general.codes;

import java.util.ArrayList;
import java.util.List;

import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.DomainServiceLayout;
import org.apache.isis.applib.annotation.DomainServiceLayout.MenuBar;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.ParameterLayout;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.query.QueryDefault;

import au.com.scds.chats.dom.module.participant.Participant;

@DomainService(repositoryFor = Region.class)
@DomainServiceLayout(menuBar = MenuBar.SECONDARY, named = "Administration", menuOrder = "100.8")
public class Regions {

	@Action(semantics = SemanticsOf.SAFE)
	@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
	@MemberOrder(sequence = "1")
	public List<Region> listAllRegions() {
		List<Region> list = container.allMatches(new QueryDefault<>(Region.class, "findAll"));
		return list;
	}

	@MemberOrder(sequence = "2")
	public List<Region> createRegion(final @ParameterLayout(named = "Region Name") String name) {
		final Region obj = container.newTransientInstance(Region.class);
		obj.setName(name);
		container.persistIfNotAlready(obj);
		container.flush();
		return listAllRegions();
	}

	@Programmatic
	public String nameForRegion(Region region) {
		return (region != null) ? region.getName() : null;
	}

	@Programmatic
	public List<String> allNames() {
		List<Region> regions = listAllRegions();
		List<String> names = new ArrayList<String>();
		for (Region r : regions) {
			names.add(r.getName());
		}
		return names;
	}

	@Programmatic
	public Region regionForName(String name) {
		if (name == null)
			return null;
		else
			return container.firstMatch(new QueryDefault<>(Region.class, "findByName", "name", name));
	}

	@javax.inject.Inject
	DomainObjectContainer container;
}


text:
package com.android.browser;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import android.webkit.WebSettingsClassic.AutoFillProfile;

public class AutoFillProfileDatabase {

    static final String LOGTAG = "AutoFillProfileDatabase";

    static final String DATABASE_NAME = "autofill.db";
    static final int DATABASE_VERSION = 2;
    static final String PROFILES_TABLE_NAME = "profiles";
    private AutoFillProfileDatabaseHelper mOpenHelper;
    private static AutoFillProfileDatabase sInstance;

    public static final class Profiles implements BaseColumns {
        private Profiles() { }

        static final String FULL_NAME = "fullname";
        static final String EMAIL_ADDRESS = "email";
        static final String COMPANY_NAME = "companyname";
        static final String ADDRESS_LINE_1 = "addressline1";
        static final String ADDRESS_LINE_2 = "addressline2";
        static final String CITY = "city";
        static final String STATE = "state";
        static final String ZIP_CODE = "zipcode";
        static final String COUNTRY = "country";
        static final String PHONE_NUMBER = "phone";
    }

    private static class AutoFillProfileDatabaseHelper extends SQLiteOpenHelper {
        AutoFillProfileDatabaseHelper(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + PROFILES_TABLE_NAME + " ("
                    + Profiles._ID + " INTEGER PRIMARY KEY,"
                    + Profiles.FULL_NAME + " TEXT,"
                    + Profiles.EMAIL_ADDRESS + " TEXT,"
                    + Profiles.COMPANY_NAME + " TEXT,"
                    + Profiles.ADDRESS_LINE_1 + " TEXT,"
                    + Profiles.ADDRESS_LINE_2 + " TEXT,"
                    + Profiles.CITY + " TEXT,"
                    + Profiles.STATE + " TEXT,"
                    + Profiles.ZIP_CODE + " TEXT,"
                    + Profiles.COUNTRY + " TEXT,"
                    + Profiles.PHONE_NUMBER + " TEXT"
                    + " );");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(LOGTAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + PROFILES_TABLE_NAME);
            onCreate(db);
        }
    }

    private AutoFillProfileDatabase(Context context) {
        mOpenHelper = new AutoFillProfileDatabaseHelper(context);
    }

    public static AutoFillProfileDatabase getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new AutoFillProfileDatabase(context);
        }
        return sInstance;
    }

    private SQLiteDatabase getDatabase(boolean writable) {
        return writable ? mOpenHelper.getWritableDatabase() : mOpenHelper.getReadableDatabase();
    }

    public void addOrUpdateProfile(final int id, AutoFillProfile profile) {
        final String sql = "INSERT OR REPLACE INTO " + PROFILES_TABLE_NAME + " ("
                + Profiles._ID + ","
                + Profiles.FULL_NAME + ","
                + Profiles.EMAIL_ADDRESS + ","
                + Profiles.COMPANY_NAME + ","
                + Profiles.ADDRESS_LINE_1 + ","
                + Profiles.ADDRESS_LINE_2 + ","
                + Profiles.CITY + ","
                + Profiles.STATE + ","
                + Profiles.ZIP_CODE + ","
                + Profiles.COUNTRY + ","
                + Profiles.PHONE_NUMBER
                + ") VALUES (?,?,?,?,?,?,?,?,?,?,?);";
        final Object[] params = { id,
                profile.getFullName(),
                profile.getEmailAddress(),
                profile.getCompanyName(),
                profile.getAddressLine1(),
                profile.getAddressLine2(),
                profile.getCity(),
                profile.getState(),
                profile.getZipCode(),
                profile.getCountry(),
                profile.getPhoneNumber() };
        getDatabase(true).execSQL(sql, params);
    }

    public Cursor getProfile(int id) {
        final String[] cols = {
                Profiles.FULL_NAME,
                Profiles.EMAIL_ADDRESS,
                Profiles.COMPANY_NAME,
                Profiles.ADDRESS_LINE_1,
                Profiles.ADDRESS_LINE_2,
                Profiles.CITY,
                Profiles.STATE,
                Profiles.ZIP_CODE,
                Profiles.COUNTRY,
                Profiles.PHONE_NUMBER
        };

        final String[] selectArgs = { Integer.toString(id) };
        return getDatabase(false).query(PROFILES_TABLE_NAME, cols, Profiles._ID + "=?", selectArgs,
                null, null, null, "1");
    }

    public void dropProfile(int id) {
        final String sql = "DELETE FROM " + PROFILES_TABLE_NAME +" WHERE " + Profiles._ID + " = ?;";
        final Object[] params = { id };
        getDatabase(true).execSQL(sql, params);
    }

    public void close() {
        mOpenHelper.close();
    }
}


text:
package com.google.sitebricks.mail.imap;

import com.google.common.collect.Sets;

import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Parse STORE_LABELS response, including new flags as echoed by server.
 * TODO: time allowing, generify and merge with StoreFlagsResponseExtractor.
 * TODO: replace "STORE_FLAGS RESPONSE" with an error code or string for easy classification.
 *
 * @author jochen@pedesis.org (Jochen Bekmann)
 */
public class StoreLabelsResponseExtractor implements Extractor<Set<String>> {
  private static final Pattern FETCH_LABEL_PATT = Pattern.compile(".* FETCH *\\(X-GM-LABELS( *\\(.*\\))" +
      ".*\\)");
  private static final Pattern BAD_PATT = Pattern.compile("\\d+ +BAD (.*)");
  private static final Pattern NO_PATT = Pattern.compile("\\d+ +NO (.*)");
  private static final Pattern OK_PATT = Pattern.compile("\\d+ +OK (.*)");

  /**
   * Parse the response, which includes label settings and command status.
   * We expect only one FETCH response as we only set labels on one msg.
   *
   * http://code.google.com/apis/gmail/imap/#x-gm-labels
   *  C: a011 STORE_FLAGS 1 +X-GM-LABELS (foo)
   *  S: * 1 FETCH (X-GM-LABELS (\Inbox \Sent Important "Muy Importante" foo))
   *  S: a011 OK STORE_FLAGS (Success)
   */
  @Override
  public Set<String> extract(List<String> messages) throws ExtractionException {
    boolean gotFetch = false;
    Set<String> result = null;

    // Find FETCH, throw error if none or more than one, or if we receive an error response.
    String fetchStr = null;
    for (int i = 0, messagesSize = messages.size(); i < messagesSize; i++) {
      String message = messages.get(i);
      if (null == message || message.isEmpty())
        continue;

      fetchStr = matchAndGetGroup1(FETCH_LABEL_PATT, message);
      if(fetchStr != null) {
        if (gotFetch) {
          throw new ExtractionException("STORE_LABELS RESPONSE: Got more than one FETCH " +
              "response " + message);
        }
        gotFetch = true;
        result = Sets.<String>newHashSet();
        result.addAll(Parsing.tokenize(fetchStr));
        result.remove("(");
        result.remove(")");
      } else {
        if(matchAndGetGroup1(OK_PATT, message) != null) {
          if (!gotFetch) {
            throw new ExtractionException("STORE_LABELS RESPONSE: no LABELS received." +
                message);
          }
          // All Good.
        } else if (matchAndGetGroup1(BAD_PATT, message) != null || matchAndGetGroup1(NO_PATT,
            message) != null) {
          throw new ExtractionException("STORE_LABELS RESPONSE: " + message);
        }
      }
    }
    return result;
  }

  private String matchAndGetGroup1(Pattern p, String s) {
    Matcher m = p.matcher(s);

    if (m.matches() && m.groupCount() > 0) {
      return m.group(1);
    }
    return null;
  }
}


text:
var _ = require('lodash');
var vumigo = require('vumigo_v02');
var JsonApi = vumigo.http.api.JsonApi;
var Choice = vumigo.states.Choice;

go.utils = {
    // Shared utils lib

    get_today: function(config) {
        var today;
        if (config.testing_today) {
            today = new Date(config.testing_today);
        } else {
            today = new Date();
        }
        return today;
    },

    check_valid_number: function(input){
        // an attempt to solve the insanity of JavaScript numbers
        var numbers_only = new RegExp('^\\d+$');
        if (input !== '' && numbers_only.test(input) && !Number.isNaN(Number(input))){
            return true;
        } else {
            return false;
        }
    },

    check_number_in_range: function(input, start, end){
        return go.utils.check_valid_number(input) && (parseInt(input, 10) >= start) && (parseInt(input, 10) <= end);
    },

    is_true: function(bool) {
        //If is is not undefined and boolean is true
        return (!_.isUndefined(bool) && (bool==='true' || bool===true));
    },

    incr_user_extra: function(data_to_increment, amount_to_increment) {
        if (_.isUndefined(data_to_increment)) {
            new_data_amount = 1;
        } else {
            new_data_amount = parseInt(data_to_increment, 10) + amount_to_increment;
        }
        return new_data_amount.toString();
    },

    incr_kv: function(im, name) {
        return im.api_request('kv.incr', {key: name, amount: 1})
            .then(function(result){
                return result.value;
            });
    },

    decr_kv: function(im, name) {
        return im.api_request('kv.incr', {key: name, amount: -1})
            .then(function(result){
                return result.value;
            });
    },

    set_kv: function(im, name, value) {
        return im.api_request('kv.set',  {key: name, value: value})
            .then(function(result){
                return result.value;
            });
    },

    get_kv: function(im, name, default_value) {
        // returns the default if null/undefined
        return im.api_request('kv.get',  {key: name})
            .then(function(result){
                if(result.value === null) return default_value;
                return result.value;
            });
    },

    get_snappy_faqs: function (im) {
        var http = new JsonApi(im, {
            auth: {
                username: im.config.snappy.username,
                password: 'x'
            }
        });
        return http.get(im.config.snappy.endpoint + 'account/'+im.config.snappy.account_id+'/faqs', {
            data: JSON.stringify(),
            headers: {
                'Content-Type': ['application/json']
            },
        });
    },

    get_snappy_topics: function (im, faq_id) {
        var http = new JsonApi(im, {
          auth: {
            username: im.config.snappy.username,
            password: 'x'
          }
        });
        return http.get(im.config.snappy.endpoint + 'account/'+im.config.snappy.account_id+'/faqs/'+faq_id+'/topics', {
          data: JSON.stringify(),
          headers: {
            'Content-Type': ['application/json']
          },
        });
    },

    get_snappy_topic_content: function(im, faq_id, topic_id) {
        var http = new JsonApi(im, {
          auth: {
            username: im.config.snappy.username,
            password: 'x'
          }
        });
        return http.get(im.config.snappy.endpoint + 'account/'+im.config.snappy.account_id+'/faqs/'+faq_id+'/topics/'+topic_id+'/questions', {

          headers: {
            'Content-Type': ['application/json']
          },
        });
    },

    //search function -->
    get_snappy_search: function(im, query) {
        var http = new JsonApi(im, {
          auth: {
            username: im.config.snappy.username,
            password: 'x'
          }
        });
        return http.get(im.config.snappy.endpoint + 'account/'+im.config.snappy.account_id+'/faqs/search', {
          params: {
                    "query": query,
                    "page": 1
                }
        }).then(function(result) {
                return result.data.data;
        });
    },

    make_search_result_choices: function(results) {
        var choices = [new Choice('restart', ('Restart'))];
        results.forEach(function(question) {
            choices.push(new Choice(question.id, question.question));
        });
        return choices;
    },

    make_search_result_answer: function(results, answer_id) {
        for (var i = 0; i < results.length; i += 1) {
            if (results[i].id === answer_id) {
                return results[i].answer;
            }
        }
    }
    //<---
};


text:
import abc

from oslo_log import log
import six

from atrope import exception

LOG = log.getLogger(__name__)

@six.add_metaclass(abc.ABCMeta)
class BaseImageListSource(object):
    """An image list."""

    def __init__(self, name, url="", enabled=True, subscribed_images=[],
                 prefix="", project="", **kwargs):
        self.name = name
        self.url = url
        self.enabled = enabled
        self.prefix = prefix
        self.subscribed_images = subscribed_images

        self.project = project

    def __repr__(self):
        return "<%s: %s>" % (
            self.__class__.__name__,
            self.name
        )

    @abc.abstractmethod
    def fetch(self):
        """Fetch the image list."""

    def get_valid_subscribed_images(self):
        return [i for i in self.get_subscribed_images() if i.verified]

    def get_subscribed_images(self):
        """Get the subscribed images from the fetched image list."""
        if not self.enabled:
            return []

        if self.image_list is None:
            LOG.error(f"Image list {self.name} has not been fetched!")
            return []

        if not self.subscribed_images:
            return self.image_list.get_images()
        else:
            return [img for img in self.image_list.get_images()
                    if img.identifier in self.subscribed_images]

    def get_images(self):
        """Get the images defined in the fetched image list."""
        if not self.enabled:
            return []

        if self.image_list is None:
            raise exception.ImageListNotFetched(id=self.name)

        return self.image_list.get_images()

    def print_list(self):
        pass


text:
import os
import MySQLdb

from flask import Flask
from flask import request, redirect, render_template, url_for
from flask import Response

app = Flask(__name__)

IP_ADDRESS = os.environ['CLOUDSQL_IP']
PASSWORD = os.environ['CLOUDSQL_PWD']
ZONE = os.environ['HOST_ZONE']

@app.route('/', methods=['GET', 'POST'])
def main_page():
    db = MySQLdb.connect(host=IP_ADDRESS, port=3306, db='guestbook', user='root', passwd=PASSWORD)
    cursor = db.cursor()
    if request.method == 'POST':
        cursor.execute('INSERT INTO entries (entry) VALUES (%s)', (request.form['entry'],))
        db.commit()
        db.close()
        return redirect(url_for('main_page'))
    else:
        cursor.execute('SELECT * FROM entries')
        entries = [row[1] for row in cursor.fetchall()]
        db.close()
        return render_template('main.html', entries=entries, zone=ZONE)

@app.route('/clear', methods=['POST'])
def clear_entries():
    db = MySQLdb.connect(host=IP_ADDRESS, port=3306, db='guestbook', user='root', passwd=PASSWORD)
    cursor = db.cursor()
    cursor.execute('DELETE from entries')
    db.commit()
    db.close()
    return redirect(url_for('main_page'))

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=80)


text:
package com.optimizely.ab.odp.serializer.impl;

import com.optimizely.ab.odp.ODPEvent;
import com.optimizely.ab.odp.serializer.ODPJsonSerializer;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

public class JsonSerializer implements ODPJsonSerializer {
    @Override
    public String serializeEvents(List<ODPEvent> events) {
        JSONArray jsonArray = new JSONArray();
        for (ODPEvent event: events) {
            JSONObject eventObject = new JSONObject();
            eventObject.put("type", event.getType());
            eventObject.put("action", event.getAction());

            if (event.getIdentifiers() != null) {
                JSONObject identifiers = new JSONObject();
                for (Map.Entry<String, String> identifier : event.getIdentifiers().entrySet()) {
                    identifiers.put(identifier.getKey(), identifier.getValue());
                }
                eventObject.put("identifiers", identifiers);
            }

            if (event.getData() != null) {
                JSONObject data = new JSONObject();
                for (Map.Entry<String, Object> dataEntry : event.getData().entrySet()) {
                    data.put(dataEntry.getKey(), getJSONObjectValue(dataEntry.getValue()));
                }
                eventObject.put("data", data);
            }

            jsonArray.put(eventObject);
        }
        return jsonArray.toString();
    }

    private static Object getJSONObjectValue(Object value)  {
        return value == null ? JSONObject.NULL : value;
    }
}


text:
package br.com.oficinatablet.login.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.Arrays;

import br.com.oficinatablet.R;
import br.com.oficinatablet.chats.ChatsSwipeActivity;
import br.com.oficinatablet.model.User;
import br.com.oficinatablet.service.UserService;

/**
 * Created by Mateus Emanuel Araújo on 9/10/16.
 * MA Solutions
 * teusemanuel@gmail.com
 */
public class LoginFragment extends Fragment {

    private static final String TAG = "LoginFragment";

    private UserService service;

    //FIREBASE
    private FirebaseAuth mFirebaseAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    private CallbackManager callbackManager;
    private LoginButton loginButton;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mFirebaseAuth = FirebaseAuth.getInstance();

        this.service = new UserService();

        /**
         * Listner para ouvir alterações do login do usuário.
         */
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
                if (firebaseUser != null) {
                    Log.d(TAG, getString(R.string.firebase_on_auth_state_changed_signed_in, firebaseUser.getUid()));

                    //SALVA OU ATUALIZA USUARIO
                    ////////////
                    User user  = new User(firebaseUser);
                    service.saveUser(user.getId(), user);

                    startActivity(new Intent(getActivity(), ChatsSwipeActivity.class));
                    getActivity().finish();

                } else {
                    Log.d(TAG, getString(R.string.firebase_on_auth_state_changed_signed_out));
                }
            }
        };

    }

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

        //FACEBOOK LOGIN
        ////////////////////
        callbackManager = CallbackManager.Factory.create();

        loginButton = (LoginButton) view.findViewById(R.id.login_button);

        final String[] permissions = getResources().getStringArray(R.array.login_permissions);

        loginButton.setReadPermissions( Arrays.asList(permissions) );
        loginButton.setFragment(this);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                moldarTokenAcessoFacebook(loginResult.getAccessToken());

            }

            @Override
            public void onCancel() {
                Log.d(TAG, getString(R.string.facebook_on_cancel));
            }

            @Override
            public void onError(FacebookException error) {
                Log.e(TAG, getString(R.string.facebook_on_error));
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        mFirebaseAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mFirebaseAuth.removeAuthStateListener(mAuthListener);
        }
    }

    public void onBackPressed() {
        getActivity().finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void moldarTokenAcessoFacebook(AccessToken token) {

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mFirebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            Log.e(TAG, getString(R.string.sign_in_with_facebook), task.getException());
                            Toast.makeText(getActivity(), R.string.authentication_failed, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }
}


text:
using System.Collections.Generic;

namespace Settings.Common.Models
{
    public interface IHierarchicalItem<T>
    {
        int Id { get; set; }
        int? ParentId { get; set; }
        ICollection<T> Children { get; set; }
        string Name { get; set; }
    }
}


text:
var $window = $(window);
var didScroll;
var lastScrollTop = 0;
var scrollAmount = 10;          // Value of scroll amount
var navbarHeight = $('.slideUp').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {

    "use strict";

    var sup = $(window).scrollTop();

    if(Math.abs(lastScrollTop - sup) <= scrollAmount) return;

    if (sup > lastScrollTop && sup > navbarHeight){
        // On Scroll Down
        $('.slideUp').css({top: -$(window).outerHeight()});
    } else {
        // On Scroll Up
        if(sup + $(window).height() < $(document).height()) {
            $('.slideUp').css({top: 0});
        }
    }

    lastScrollTop = sup;

}


text:
package ch.unibe.scg.ese2017.fullintegration.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
	DataSource dataSource;

	@Bean
	public UserDetailsManager userDetailsManager(DataSource dataSource) {
		JdbcUserDetailsManager userDetailsManager = new JdbcUserDetailsManager();
		userDetailsManager.setDataSource(dataSource);
		return userDetailsManager;
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/", "/user/create").permitAll().and().authorizeRequests()
				.regexMatchers(HttpMethod.POST, "/user").permitAll().and().authorizeRequests().anyRequest()
				.authenticated().and().formLogin().and().httpBasic();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.jdbcAuthentication().dataSource(dataSource);
	}

}


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

namespace Medidata.RWS.Core.Requests.ODM_Adapter
{

    /// <summary>
    /// All folders in use in a study.
    /// </summary>
    /// <seealso cref="Medidata.RWS.Core.Requests.QueryOptionGetRequest" />
    public class VersionFoldersRequest : QueryOptionGetRequest
    {
        private readonly string Environment;
        private readonly string ProjectName;

        /// <summary>
        /// The study name and environment, for example: "Mediflex(Prod)"
        /// </summary>
        public string studyoid => string.IsNullOrWhiteSpace(Environment) ? $"{ProjectName}" : $"{ProjectName}({Environment})";

        /// <summary>
        /// Initializes a new instance of the <see cref="VersionFoldersRequest"/> class.
        /// </summary>
        /// <param name="ProjectName">Name of the project.</param>
        /// <param name="Environment">The environment.</param>
        public VersionFoldersRequest(string ProjectName, string Environment)
        {
            this.ProjectName = ProjectName;
            this.Environment = Environment;
        }

        /// <summary>
        /// The list of query string parameters that can be supplied for this request.
        /// </summary>
        public override List<string> KnownQueryOptions
        {
            get
            {
                return new List<string> { "studyoid" };
            }
        }

        /// <summary>
        /// The request URL path.
        /// </summary>
        /// <returns></returns>
        public override string UrlPath()
        {
            return RequestHelpers.MakeUrl("/", QueryString(), new string[] { "datasets", "VersionFolders.odm" });
        }
    }
}


text:
package com.bitgirder.mingle;

import com.bitgirder.validation.Inputs;
import com.bitgirder.validation.State;

public
final
class MingleEnum
implements MingleValue
{
    private final static Inputs inputs = new Inputs();
    private final static State state = new State();

    private final QualifiedTypeName type;
    private final MingleIdentifier value;

    MingleEnum( QualifiedTypeName type,
                MingleIdentifier value )
    {
        this.type = type;
        this.value = value;
    }

    public QualifiedTypeName getType() { return type; }
    public MingleIdentifier getValue() { return value; }

    public
    AtomicTypeReference
    getAtomicType()
    {
        return new AtomicTypeReference( type, null );
    }

    public int hashCode() { return type.hashCode() | value.hashCode(); }

    public
    boolean
    equals( Object o )
    {
        if ( o == this ) return true;

        if ( o instanceof MingleEnum )
        {
            MingleEnum e = (MingleEnum) o;

            return type.equals( e.type ) && value.equals( e.value );
        }

        return false;
    }

    public
    static
    MingleEnum
    create( QualifiedTypeName name,
            MingleIdentifier value )
    {
        inputs.notNull( name, "name" );
        inputs.notNull( value, "value" );

        return new MingleEnum( name, value );
    }
}


text:
module RuboCop
  module Cop
    module Naming
      # This cop checks for class and module names with
      # an underscore in them.
      #
      # @example
      #   # bad
      #   class My_Class
      #   end
      #   module My_Module
      #   end
      #
      #   # good
      #   class MyClass
      #   end
      #   module MyModule
      #   end
      class ClassAndModuleCamelCase < Cop
        MSG = 'Use CamelCase for classes and modules.'.freeze

        def on_class(node)
          return unless node.loc.name.source =~ /_/

          add_offense(node, location: :name)
        end
        alias on_module on_class
      end
    end
  end
end


text:
jvm.VMLCircleElement = function(config, style){
  jvm.VMLCircleElement.parentClass.call(this, 'oval', config, style);
};

jvm.inherits(jvm.VMLCircleElement, jvm.VMLShapeElement);

jvm.VMLCircleElement.prototype.applyAttr = function(attr, value){
  switch (attr) {
    case 'r':
      this.node.style.width = value*2+'px';
      this.node.style.height = value*2+'px';
      this.applyAttr('cx', this.get('cx') || 0);
      this.applyAttr('cy', this.get('cy') || 0);
      break;
    case 'cx':
      if (!value) return;
      this.node.style.left = value - (this.get('r') || 0) + 'px';
      break;
    case 'cy':
      if (!value) return;
      this.node.style.top = value - (this.get('r') || 0) + 'px';
      break;
    default:
      jvm.VMLCircleElement.parentClass.prototype.applyAttr.call(this, attr, value);
  }
};


text:
# Adding an custom Type

By adding an custom type you can influence how the model handles certain values.

First you have to create an type class that implements the TypeInterface, like this:

```php
class YourType implements TypeInterface {

    /**
     * executes an certain parsing part
     * @param AbstractModel $model
     * @param $data
     * @param $field
     */
    public static function execute(AbstractModel &$model, $data, $field) {
        //todo code
    }

    /**
     * asks for the params according to the type and return an array with the field information
     * @param OutputInterface $output
     * @param InputInterface $input
     * @param $helper
     * @return array
     */
    public static function generateTypeWithConsole(OutputInterface $output, InputInterface $input, $helper) {
        //todo code
    }

    /**
     * return name of the type
     * @return string
     */
    public static function getName() {
        //todo code
    }

    /**
     * return type of the Type Class
     * @return string
     */
    public static function getType() {
        //todo code
    }
}
```

The execute() method takes a model, data and field properties. With that information the method() sets an model value with the right value from the data array, these relations between the data array and the model are defined in the yml configuration.

The generateTypeWithConsole() returns an array that resembles your yml configuration for that type, it will be used to autogenerate Models.

getName() and getType() returns the type f.e \DateTime::class and the name f.e. 'date'.

To add the type to the existing one you have to add it to the certain yml configuration of the model like this:

```yml
Webuntis\Models\Classes:
    repositoryClass: null
    fields:
        name:
            type: string
            api:
                name: name
        fullName:
            type: string
            api:
                name: longName
    additionalTypes:
        yourtypename: Your\Namespace\To\The\Class
```

after this you can start using that custom Type


text:
package com.voxeo.tropo.actions;

import com.voxeo.tropo.Key;
import com.voxeo.tropo.Tropo;
import com.voxeo.tropo.TropoException;
import com.voxeo.tropo.annotations.RequiredKeys;
import com.voxeo.tropo.annotations.ValidKeys;

@ValidKeys(keys={"to","from","name","required"})
@RequiredKeys(keys={"to"})
public class RedirectAction extends JsonAction {

	public RedirectAction() {

		super();
		setName("redirect");
	}

	public RedirectAction(Key... keys) {

		super(keys);
		setName("redirect");
	}

	@Override
	protected void validate() throws TropoException {

		super.validate();
		if (getParent() != null) {
			if (!(getParent() instanceof Tropo)) {
				throw new TropoException("Redirect should only be used alone and before the session is answered, use transfer instead");
			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/android/workspace/jenkins/workspace/fabric-android-deploy-to-staging/sdk/digits/digits/src/main/res/values-nb/strings.xml -->
    <eat-comment/>
    <string name="dgts__cancel">Avbryt</string>
    <string name="dgts__communication_error">Kommunikasjonsfeil</string>
    <string name="dgts__confirmation_code">Bekreftelseskode</string>
    <string name="dgts__confirmation_edit_hint">Skriv inn bekreftelseskoden</string>
    <string name="dgts__confirmation_error">Fikk ikke bekreftet telefonnummeret ditt</string>
    <string name="dgts__confirmation_error_alternative">Beklager, vi har problemer med å sende deg en bekreftelseskode.</string>
    <string name="dgts__confirmation_expired">Denne koden har utløpt. Send bekreftelseskoden på nytt.</string>
    <string name="dgts__confirmation_send_text">Send bekreftelseskode</string>
    <string name="dgts__confirmation_sending_text">Sender bekreftelseskode</string>
    <string name="dgts__confirmation_sent_text">Sendt bekreftelseskode</string>
    <string name="dgts__confirmation_sms">Bekreftelseskode: %1$s. Skriv den inn i %2$s</string>
    <string name="dgts__create_account_text">Opprett konto</string>
    <string name="dgts__creating_account_text">Oppretter kontoen</string>
    <string name="dgts__digits_logo_desc">digits-logo-ikon</string>
    <string name="dgts__digits_logo_name_desc">digits-logo-navn</string>
    <string name="dgts__dismiss">Forkast</string>
    <string name="dgts__find_your_friends">Finn vennene dine</string>
    <string name="dgts__image_header_description">Toppbilde for innlogging</string>
    <string name="dgts__login_digits_text">Bruk telefonnummeret mitt</string>
    <string name="dgts__network_error">Sjekk nettverket ditt, og prøv igjen.</string>
    <string name="dgts__not_now">Ikke nå</string>
    <string name="dgts__okay">OK</string>
    <string name="dgts__phone_number_edit_hint">Nummeret ditt</string>
    <string name="dgts__phone_number_text">Skriv inn telefonnummeret ditt</string>
    <string name="dgts__pin_code_verification_title">Skriv inn koden for 2-trinnsbekreftelse</string>
    <string name="dgts__resend">Send på nytt</string>
    <string name="dgts__resend_confirmation_text">Send bekreftelseskoden på nytt</string>
    <string name="dgts__sign_in">Logg inn</string>
    <string name="dgts__sign_in_error">Vi kunne ikke logge deg inn via Twitter akkurat nå. Prøv igjen senere.</string>
    <string name="dgts__sign_in_twitter">Logg inn med Twitter</string>
    <string name="dgts__signing_in">Logger inn</string>
    <string name="dgts__success_desc">Suksess-ikon</string>
    <string name="dgts__terms_text">Når du trykker på %1$sSend bekreftelseskode%1$s ovenfor, vil Digits by Twitter sende deg en tekstmelding for å bekrefte telefonnummeret ditt. Meldings- og datakostnader kan påløpe.</string>
    <string name="dgts__terms_text_create">Ved å trykke på %1$sOpprett konto%1$s ovenfor samtykker du i Digits by Twitters bruksvilkår, personvernpolicy og bruk av informasjonskapsler. Du samtykker også i at brukere av denne applikasjonen kan finne deg ved hjelp av telefonnummer og/eller e-postadresse.</string>
    <string name="dgts__terms_text_sign_in">Ved å trykke på %1$sLogg inn%1$s samtykker du i de oppdaterte bruksvilkårene, personvernpolicyen og Digits by Twitters policy vedr. informasjonskapsler. Du samtykker også i at brukerne av %1$s kan finne deg ved hjelp av telefonnummer og/eller e-postadresse.</string>
    <string name="dgts__try_again">Prøv igjen</string>
    <string name="dgts__try_again_confirmation">Sjekk koden din, og prøv igjen.</string>
    <string name="dgts__try_again_phone_number">Sjekk nummeret ditt, og prøv igjen.</string>
    <string name="dgts__try_another_phone">Prøv med et annet telefonnummer</string>
    <string name="dgts__upload_contacts">Vi benytter Digits by Twitter til å finne venner av deg som bruker denne appen. Når du trykker på OK, laster vi opp adresseboken din til Digits by Twitter, så vi kan hjelpe deg å finne brukere av %1$s som du kjenner eller hjelpe brukere av %1$s til å finne deg.</string>
    <string name="dgts__verification_code">Verifiseringskode</string>
    <string name="dgts_pin_code_terms">Du har angitt en kode for 2-trinnsbekreftelse på digits.com</string>
    <string name="dgts_verify">Verifiser</string>
    <string name="dgts_verifying">Verifiserer</string>
</resources>


text:
.. _refreeze:

==============================
Re-freezing the 32-bit server
==============================

If you want to make your own 32-bit server you will need

1) a 32-bit version of Python 2.7 or 3.5+ (whatever version you want)
2) `PyInstaller <https://www.pyinstaller.org/>`_

Using pip from the 32-bit Python interpreter run

.. code-block:: console

   pip install msl-loadlib pyinstaller

.. note::

   If you want to include additional packages, for example,
   pythonnet, comtypes, numpy, etc. run

    .. code-block:: console

       pip install pythonnet comtypes numpy

Using the API
-------------

Launch an Interactive Console using the 32-bit Python interpreter

.. code-block:: console

   python

and enter

.. code-block:: pycon

   >>> from msl.loadlib import freeze_server32
   >>> freeze_server32.main()  # doctest: +SKIP
   ... PyInstaller logging messages ...
   Server saved to: ...

Specify the appropriate keyword arguments to the
:func:`~msl.loadlib.freeze_server32.main` function.

Copy the ``server32-*`` file to the folder where you have MSL-LoadLib installed
in your 64-bit version of Python to replace the existing server file.

Using the CLI
-------------

In this example we will clone the GitHub repository and create the server from
the command line. Make sure that invoking `python` on your terminal uses the
32-bit Python interpreter or specify the full path to the 32-bit Python interpreter
that you want to use.

.. code-block:: console

   git clone https://github.com/MSLNZ/msl-loadlib.git
   cd msl-loadlib/msl/loadlib
   python freeze_server32.py

Copy the ``server32-*`` file to the folder where you have MSL-LoadLib installed
in your 64-bit version of Python to replace the existing server file.

To see the help for the `freeze_server32.py` module run

.. code-block:: console

   python freeze_server32.py --help

For example, if you wanted to bypass the error that pythonnet is not installed run

.. code-block:: console

   python freeze_server32.py --ignore-pythonnet


text:
from __future__ import absolute_import
from __future__ import division
# Copyright (c) 2010-2016 openpyxl

import math

from openpyxl.compat import deprecated

from openpyxl.styles.colors import Color, BLACK, WHITE
from openpyxl.utils.units import (
    pixels_to_EMU,
    EMU_to_pixels,
    short_color,
)

class Drawing(object):
    """ a drawing object - eg container for shapes or charts
        we assume user specifies dimensions in pixels; units are
        converted to EMU in the drawing part
    """

    count = 0

    def __init__(self):

        self.name = ''
        self.description = ''
        self.coordinates = ((1, 2), (16, 8))
        self.left = 0
        self.top = 0
        self._width = 21 # default in px
        self._height = 192 #default in px
        self.resize_proportional = False
        self.rotation = 0
        self.anchortype = "absolute"
        self.anchorcol = 0 # left cell
        self.anchorrow = 0 # top row

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, w):
        if self.resize_proportional and w:
            ratio = self._height / self._width
            self._height = round(ratio * w)
        self._width = w

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, h):
        if self.resize_proportional and h:
            ratio = self._width / self._height
            self._width = round(ratio * h)
        self._height = h

    def set_dimension(self, w=0, h=0):

        xratio = w / self._width
        yratio = h / self._height

        if self.resize_proportional and w and h:
            if (xratio * self._height) < h:
                self._height = math.ceil(xratio * self._height)
                self._width = w
            else:
                self._width = math.ceil(yratio * self._width)
                self._height = h

    @deprecated("Private method used when serialising")
    def get_emu_dimensions(self):
        """ return (x, y, w, h) in EMU """

        return (pixels_to_EMU(self.left), pixels_to_EMU(self.top),
            pixels_to_EMU(self._width), pixels_to_EMU(self._height))

    @property
    def anchor(self):
        from .spreadsheet_drawing import (
            OneCellAnchor,
            TwoCellAnchor,
            AbsoluteAnchor)
        if self.anchortype == "absolute":
            anchor = AbsoluteAnchor()
            anchor.pos.x = pixels_to_EMU(self.left)
            anchor.pos.y = pixels_to_EMU(self.top)

        elif self.anchortype == "oneCell":
            anchor = OneCellAnchor()
            anchor._from.col = self.anchorcol
            anchor._from.row = self.anchorrow

        anchor.ext.width = pixels_to_EMU(self._width)
        anchor.ext.height = pixels_to_EMU(self._height)

        return anchor


text:
using System;

namespace com.riotgames.platform.game
{
    public class PlatformGameLifecycleDTO : VersionedObject
    {
        public string gameName;

        public DateTime? lastModifiedDate;

        public int reconnectDelay;
        public string connectivityStateEnum;
        public object gameSpecificLoyaltyRewards;

        public GameDTO game;
        public PlayerCredentialsDto playerCredentials;
    }
}


text:
/* *
 *
 *  License: www.highcharts.com/license
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 * */
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/* *
 *
 *  Imports
 *
 * */
import Point from '../../../Core/Series/Point.js';
import SeriesRegistry from '../../../Core/Series/SeriesRegistry.js';
var SMAIndicator = SeriesRegistry.seriesTypes.sma;
var VBPPoint = /** @class */ (function (_super) {
    __extends(VBPPoint, _super);
    function VBPPoint() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    // Required for destroying negative part of volume
    VBPPoint.prototype.destroy = function () {
        // @todo: this.negativeGraphic doesn't seem to be used anywhere
        if (this.negativeGraphic) {
            this.negativeGraphic = this.negativeGraphic.destroy();
        }
        return Point.prototype.destroy.apply(this, arguments);
    };
    return VBPPoint;
}(SMAIndicator.prototype.pointClass));
/* *
 *
 *  Default Export
 *
 * */
export default VBPPoint;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

                            <apiman-activity model="auditEntries" next="getNextPage"/>


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'dynamic_class'


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the MIT license.  See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
    Microsoft.NetCore.Analyzers.Security.JsonNetTypeNameHandling,
    Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
    Microsoft.NetCore.Analyzers.Security.JsonNetTypeNameHandling,
    Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;

namespace Microsoft.NetCore.Analyzers.Security.UnitTests
{
    public class JsonNetTypeNameHandlingTests
    {
        private static readonly DiagnosticDescriptor Rule = JsonNetTypeNameHandling.Rule;

        [Theory]
        [CombinatorialData]
        public async Task DocSample1_CSharp_Violation_DiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using Newtonsoft.Json;

public class ExampleClass
{
    public JsonSerializerSettings Settings { get; }

    public ExampleClass()
    {
        Settings = new JsonSerializerSettings();
        Settings.TypeNameHandling = TypeNameHandling.All;    // CA2326 violation.
    }
}",
                GetCSharpResultAt(11, 37, Rule));
        }

        [Theory]
        [CombinatorialData]
        public async Task DocSample1_VB_Violation_DiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyBasicWithJsonNetAsync(version, @"
Imports Newtonsoft.Json

Public Class ExampleClass
    Public ReadOnly Property Settings() As JsonSerializerSettings

    Public Sub New()
        Settings = New JsonSerializerSettings()
        Settings.TypeNameHandling = TypeNameHandling.All    ' CA2326 violation.
    End Sub
End Class",
                GetBasicResultAt(9, 37, Rule));
        }

        [Theory]
        [CombinatorialData]
        public async Task DocSample1_CSharp_Solution_NoDiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using Newtonsoft.Json;

public class ExampleClass
{
    public JsonSerializerSettings Settings { get; }

    public ExampleClass()
    {
        Settings = new JsonSerializerSettings();

        // The default value of Settings.TypeNameHandling is TypeNameHandling.None.
    }
}");
        }

        [Theory]
        [CombinatorialData]
        public async Task DocSample1_VB_Solution_NoDiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyBasicWithJsonNetAsync(version, @"
Imports Newtonsoft.Json

Public Class ExampleClass
    Public ReadOnly Property Settings() As JsonSerializerSettings

    Public Sub New()
        Settings = New JsonSerializerSettings()

        ' The default value of Settings.TypeNameHandling is TypeNameHandling.None.
    End Sub
End Class");
        }

        [Theory]
        [CombinatorialData]
        public async Task Reference_TypeNameHandling_None_NoDiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        Console.WriteLine(TypeNameHandling.None);
    }
}");
        }

        [Theory]
        [CombinatorialData]
        public async Task Reference_TypeNameHandling_All_DiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        Console.WriteLine(TypeNameHandling.All);
    }
}",
                GetCSharpResultAt(9, 27, Rule));
        }

        [Theory]
        [CombinatorialData]
        public async Task Reference_AttributeTargets_All_NoDiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        Console.WriteLine(AttributeTargets.All);
    }
}");
        }

        [Theory]
        [CombinatorialData]
        public async Task Assign_TypeNameHandling_Objects_DiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        TypeNameHandling tnh = TypeNameHandling.Objects;
    }
}",
                GetCSharpResultAt(9, 32, Rule));
        }

        [Theory]
        [CombinatorialData]
        public async Task Assign_TypeNameHandling_1_Or_Arrays_DiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        TypeNameHandling tnh = (TypeNameHandling) 1 | TypeNameHandling.Arrays;
    }
}",
                GetCSharpResultAt(9, 55, Rule));
        }

        [Theory]
        [CombinatorialData]
        public async Task Assign_TypeNameHandling_0_NoDiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        TypeNameHandling tnh = (TypeNameHandling) 0;
    }
}");
        }

        [Theory]
        [CombinatorialData]
        public async Task Assign_TypeNameHandling_None_NoDiagnosticAsync(NewtonsoftJsonVersion version)
        {
            await VerifyCSharpWithJsonNetAsync(version, @"
using System;
using Newtonsoft.Json;

class Blah
{
    public static void Main(string[] args)
    {
        TypeNameHandling tnh = TypeNameHandling.None;
    }
}");
        }

        private async Task VerifyCSharpWithJsonNetAsync(NewtonsoftJsonVersion version, string source, params DiagnosticResult[] expected)
        {
            var csharpTest = new VerifyCS.Test
            {
                ReferenceAssemblies = version switch
                {
                    NewtonsoftJsonVersion.Version10 => AdditionalMetadataReferences.DefaultWithNewtonsoftJson10,
                    NewtonsoftJsonVersion.Version12 => AdditionalMetadataReferences.DefaultWithNewtonsoftJson12,
                    _ => throw new NotSupportedException(),
                },
                TestState =
                {
                    Sources = { source },
                },
            };

            csharpTest.ExpectedDiagnostics.AddRange(expected);

            await csharpTest.RunAsync();
        }

        private async Task VerifyBasicWithJsonNetAsync(NewtonsoftJsonVersion version, string source, params DiagnosticResult[] expected)
        {
            var vbTest = new VerifyVB.Test
            {
                ReferenceAssemblies = version switch
                {
                    NewtonsoftJsonVersion.Version10 => AdditionalMetadataReferences.DefaultWithNewtonsoftJson10,
                    NewtonsoftJsonVersion.Version12 => AdditionalMetadataReferences.DefaultWithNewtonsoftJson12,
                    _ => throw new NotSupportedException(),
                },
                TestState =
                {
                    Sources = { source },
                },
            };

            vbTest.ExpectedDiagnostics.AddRange(expected);

            await vbTest.RunAsync();
        }

        private static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule)
#pragma warning disable RS0030 // Do not used banned APIs
           => VerifyCS.Diagnostic(rule)
               .WithLocation(line, column);
#pragma warning restore RS0030 // Do not used banned APIs

        private static DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule)
#pragma warning disable RS0030 // Do not used banned APIs
           => VerifyVB.Diagnostic(rule)
               .WithLocation(line, column);
#pragma warning restore RS0030 // Do not used banned APIs
    }
}


text:
package com.cilogi.shiro.googlegae;

import org.apache.shiro.authc.HostAuthenticationToken;
import org.apache.shiro.authc.RememberMeAuthenticationToken;

public class GoogleGAEAuthenticationToken implements HostAuthenticationToken, RememberMeAuthenticationToken {

    private final String principal;
    private final String host;

    public GoogleGAEAuthenticationToken(String principal, String host) {
        this.principal = principal;
        this.host = host;
    }

    @Override
    public Object getPrincipal() {
        return principal;
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public boolean isRememberMe() {
        return true;
    }

    @Override
    public String getHost() {
        return host;
    }
}


text:
layout: post
date: 2016-07-02 01:45
---
There's a local Dixieland brass band playing on the front steps of a historical hotel down the street from me. I love this neighborhood.


text:
require_relative '../../automated_init'

context "Handle" do
  context "Configure" do
    context "Session and Settings" do
      handler_class = Class.new do
        include Messaging::Handle

        attr_accessor :session
        attr_accessor :settings

        def configure(session: nil, settings: nil)
          self.session = session
          self.settings = settings
        end
      end

      session = Object.new
      settings = Object.new

      context "Passed to configure method" do
        handler = handler_class.build(session: session, settings: settings)

        test "Session" do
          assert(handler.session.equal?(session))
        end

        test "Settings" do
          assert(handler.settings.equal?(settings))
        end
      end
    end
  end
end