text:
package org.oscm.validator;

import org.oscm.logging.Log4jLogger;
import org.oscm.logging.LoggerFactory;
import org.oscm.converter.TimeStampUtil;
import org.oscm.types.enumtypes.LogMessageIdentifier;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.exception.ServiceStateException;

/**
 * Contains utility methods for validating Product domain model objects.
 *
 * @author barzu
 */
public class ProductValidator {

    private static final Log4jLogger logger = LoggerFactory
            .getLogger(ProductValidator.class);

    /**
     * Checks if the given product state is {@link ServiceStatus#INACTIVE} or
     * {@link ServiceStatus#SUSPENDED} or {@link ServiceStatus#ACTIVE}
     *
     * @param productId
     *            the ID of the product to be validated
     * @param status
     *            the product state to be checked
     * @throws ServiceStateException
     *             in case the state is not {@link ServiceStatus#INACTIVE} or
     *             {@link ServiceStatus#SUSPENDED} or
     *             {@link ServiceStatus#ACTIVE}
     */
    public static void validateActiveOrInactiveOrSuspended(String productId,
            ServiceStatus status) throws ServiceStateException {
        if (status != ServiceStatus.INACTIVE
                && status != ServiceStatus.SUSPENDED
                && status != ServiceStatus.ACTIVE) {
            String expected = "[" + ServiceStatus.ACTIVE.name()
                    + ServiceStatus.INACTIVE.name() + ", "
                    + ServiceStatus.SUSPENDED.name() + "]";
            ServiceStateException e = new ServiceStateException(status,
                    expected,
                    TimeStampUtil.removeTimestampFromId(productId));
            logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.WARN_INVALID_SERVICE_STATUS, expected,
                    status.name(), productId);
            throw e;
        }
    }

    /**
     * Checks if the given product state is {@link ServiceStatus#INACTIVE} or
     * {@link ServiceStatus#SUSPENDED}
     *
     * @param productId
     *            the ID of the product to be validated
     * @param status
     *            the product state to be checked
     * @throws ServiceStateException
     *             in case the state is not {@link ServiceStatus#INACTIVE} or
     *             {@link ServiceStatus#SUSPENDED}
     */
    public static void validateInactiveOrSuspended(String productId,
            ServiceStatus status) throws ServiceStateException {
        if (status != ServiceStatus.INACTIVE
                && status != ServiceStatus.SUSPENDED) {
            String expected = "[" + ServiceStatus.INACTIVE.name() + ", "
                    + ServiceStatus.SUSPENDED.name() + "]";
            ServiceStateException e = new ServiceStateException(status,
                    expected,
                    TimeStampUtil.removeTimestampFromId(productId));
            logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.WARN_INVALID_SERVICE_STATUS, expected,
                    status.name(), productId);
            throw e;
        }
    }

    /**
     * Checks if the resale permission was removed for the given product.
     *
     * @param productId
     *            the ID of the product to be validated
     * @param status
     *            the product state to be checked
     * @throws ServiceStateException
     *             in case the resale permission was removed for the specified
     *             product.
     */
    public static void validateResalePermission(String productId,
            ServiceStatus status) throws ServiceStateException {
        if (status == null) {
            throw new NullPointerException("status is not allowed to be null");
        }
        if (status == ServiceStatus.DELETED) {
            String expected = "[" + ServiceStatus.INACTIVE.name() + ", "
                    + ServiceStatus.SUSPENDED.name() + "]";
            ServiceStateException e = new ServiceStateException(status,
                    expected, productId);
            logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.WARN_INVALID_SERVICE_STATUS, expected,
                    status.name(), productId);
            throw e;
        }
    }

    /**
     * Checks if the given product state is {@link ServiceStatus#INACTIVE} or
     * {@link ServiceStatus#ACTIVE}
     *
     * @param productId
     *            the ID of the product to be validated
     * @param status
     *            the product state to be checked
     * @throws ServiceStateException
     *             in case the state is not {@link ServiceStatus#INACTIVE} or
     *             {@link ServiceStatus#ACTIVE}
     */
    public static void validateInactiveOrActive(String productId,
            ServiceStatus status) throws ServiceStateException {
        if (status != ServiceStatus.INACTIVE && status != ServiceStatus.ACTIVE) {
            String expected = "[" + ServiceStatus.INACTIVE.name() + ", "
                    + ServiceStatus.ACTIVE.name() + "]";
            ServiceStateException e = new ServiceStateException(status,
                    expected, productId);
            logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.WARN_INVALID_SERVICE_STATUS, expected,
                    status.name(), productId);
            throw e;
        }
    }

}


text:
define(["iweb/CoreModule", "./ColorController"], function(Core) {

	var color = Ext.define(null, {
	       extend: 'Ext.SplitButton',

	       controller: "drawmenu.colorbutton",

			cls: 'color-btn',
			scale: 'medium',
			colspan: 3,
			tooltip: 'Color',
			arrowAlign: 'bottom',

		    style: {
		        width: '100%'
		    },

		    listeners: {
		    	afterRender : "afterRender"
		    },

			menu: {
				xtype: 'colormenu',
				handler: "onColorSelect"
			}

	    });

	return color;
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Release 8.2.5</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Release Notes"
HREF="release.html"><LINK
REL="PREVIOUS"
TITLE="Release 8.2.6"
HREF="release-8-2-6.html"><LINK
REL="NEXT"
TITLE="Release 8.2.4"
HREF="release-8-2-4.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29">

PostgreSQL 9.2.8 Documentation

Prev	Up	Appendix E. Release Notes	Next

E.106. Release 8.2.5

Release Date: 2007-09-17

   This release contains a variety of fixes from 8.2.4.
   For information about new features in the 8.2 major release, see
   Section E.111.

E.106.1. Migration to Version 8.2.5

    A dump/restore is not required for those running 8.2.X.

E.106.2. Changes

      Prevent index corruption when a transaction inserts rows and
      then aborts close to the end of a concurrent <TT
CLASS="COMMAND"
>VACUUM</TT
>
      on the same table (Tom)

      Fix <TT
CLASS="LITERAL"
>ALTER DOMAIN ADD CONSTRAINT</TT
> for cases involving
      domains over domains (Tom)

      Make <TT
CLASS="COMMAND"
>CREATE DOMAIN ... DEFAULT NULL</TT
> work properly (Tom)

      Fix some planner problems with outer joins, notably poor
      size estimation for <TT
CLASS="LITERAL"
>t1 LEFT JOIN t2 WHERE t2.col IS NULL</TT
>
      (Tom)

      Allow the <TT
CLASS="TYPE"
>interval</TT
> data type to accept input consisting only of
      milliseconds or microseconds (Neil)

      Allow timezone name to appear before the year in <TT
CLASS="TYPE"
>timestamp</TT
> input (Tom)

      Fixes for <ACRONYM
CLASS="ACRONYM"
>GIN</ACRONYM
> indexes used by <TT
CLASS="FILENAME"
>/contrib/tsearch2</TT
> (Teodor)

      Speed up rtree index insertion (Teodor)

      Fix excessive logging of <ACRONYM
CLASS="ACRONYM"
>SSL</ACRONYM
> error messages (Tom)

      Fix logging so that log messages are never interleaved when using
      the syslogger process (Andrew)

      Fix crash when <TT
CLASS="VARNAME"
>log_min_error_statement</TT
> logging runs out
      of memory (Tom)

      Fix incorrect handling of some foreign-key corner cases (Tom)

      Fix stddev_pop(numeric) and var_pop(numeric) (Tom)

      Prevent <TT
CLASS="COMMAND"
>REINDEX</TT
> and <TT
CLASS="COMMAND"
>CLUSTER</TT
> from failing
      due to attempting to process temporary tables of other sessions (Alvaro)

      Update the time zone database rules, particularly New Zealand's upcoming changes (Tom)

      Windows socket and semaphore improvements (Magnus)

      Make <TT
CLASS="COMMAND"
>pg_ctl -w</TT
> work properly in Windows service mode (Dave Page)

      Fix memory allocation bug when using MIT Kerberos on Windows (Magnus)

      Suppress timezone name (<TT
CLASS="LITERAL"
>%Z</TT
>) in log timestamps on Windows
      because of possible encoding mismatches (Tom)

      Require non-superusers who use <TT
CLASS="FILENAME"
>/contrib/dblink</TT
> to use only
      password authentication, as a security measure (Joe)

      Restrict <TT
CLASS="FILENAME"
>/contrib/pgstattuple</TT
> functions to superusers, for security reasons (Tom)

      Do not let <TT
CLASS="FILENAME"
>/contrib/intarray</TT
> try to make its GIN opclass
      the default (this caused problems at dump/restore) (Tom)

Prev	Home	Next

Release 8.2.6	Up	Release 8.2.4


text:
<?php

namespace frontend\controllers;

use Yii;
use frontend\models\AntiReply;
use frontend\models\AntireplySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AntireplyController implements the CRUD actions for AntiReply model.
 */
class AntireplyController extends Controller
{
    public $layout= 'user';
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all AntiReply models.
     * @return mixed
     */
    public function actionIndex()
    {
        $role=Yii::$app->user->identity->role;
        if ($role<50){return $this->goBack(['user/anti']);}
        $searchModel = new AntireplySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single AntiReply model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new AntiReply model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AntiReply();
        $uid=Yii::$app->user->id;
        $model->uid=$uid;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    public function  actionOnereply()
    {

        $uid=Yii::$app->user->id;
        $antireply = AntiReply::find()->where(['uid' => $uid])->all();

        if ($antireply == null) {
            $model = new AntiReply();
            $model->uid = $uid;
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }
        $model=$antireply[0];
        $model->uid = $uid;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }

    }

    /**
     * Updates an existing AntiReply model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing AntiReply model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the AntiReply model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AntiReply the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AntiReply::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
Parser::Parser(Engine& engine) : engine(engine), includeFile(0), readBufferPos(0), readBufferEnd(0), currentLine(1), currentChar(' ') {}

Statement* Parser::parse(const String& file, Engine::ErrorHandler errorHandler, void* userData)
{
  this->errorHandler = errorHandler;
  this->errorHandlerUserData = userData;
  this->filePath = file;

  try
  {
    if(!this->file.open(file))
    {
      errorHandler(errorHandlerUserData, file, 0, Error::getString());
      throw false;
    }
    includeFile = new IncludeFile(engine);
    includeFile->fileDir = File::getDirname(file);
    nextChar(); // read first character
    nextToken(); // read first symbol
    return readFile();
  }
  catch(...)
  {
    return 0;
  }
}

void Parser::nextChar()
{
  if(readBufferPos == readBufferEnd)
  {
    if(currentChar == '\0')
      return;
    size_t i = file.read(readBuffer, sizeof(readBuffer));
    if(i == 0)
    {
      currentChar = '\0';
      return;
    }
    else
    {
      readBufferPos = readBuffer;
      readBufferEnd = readBufferPos + i;
    }
  }
  currentChar = *(readBufferPos++);
}

void Parser::nextToken()
{
  for(;;)
  {
    char c = currentChar;
    nextChar();
    switch(c)
    {
    case '\0': currentToken.id = Token::eof; return;
    case '(': currentToken.id = Token::leftParenthesis; return;
    case ')': currentToken.id = Token::rightParenthesis; return;
    case '{': currentToken.id = Token::leftBrace; return;
    case '}': currentToken.id = Token::rightBrace; return;
    case ',': currentToken.id = Token::comma; return;
    case ';': currentToken.id = Token::comma; return;
    case '?': currentToken.id = Token::interrogation; return;
    case ':': currentToken.id = Token::colon; return;

    case '&':
      if(currentChar == '&')
      {
        nextChar();
        currentToken.id = Token::and_;
      }
      else
        unexpectedChar(c);
      return;

    case '|':
      if(currentChar == '|')
      {
        nextChar();
        currentToken.id = Token::or_;
      }
      else
        unexpectedChar(c);
      return;

    case '=':
      if(currentChar == '=')
      {
        nextChar();
        currentToken.id = Token::equal;
      }
      else
        currentToken.id = Token::assignment;
      return;

    case '+':
      if(currentChar == '=')
      {
        nextChar();
        currentToken.id = Token::plusAssignment;
      }
      else
        currentToken.id = Token::plus;
      return;

    case '-':
      if(currentChar == '=')
      {
        nextChar();
        currentToken.id = Token::minusAssignment;
      }
      else
        currentToken.id = Token::minus;
      return;

    case '!':
      if(currentChar == '=')
      {
        nextChar();
        currentToken.id = Token::notEqual;
      }
      else
        currentToken.id = Token::not_;
      return;

    case '>':
      if(currentChar == '=')
      {
        nextChar();
        currentToken.id = Token::greaterEqualThan;
      }
      else
        currentToken.id = Token::greaterThan;
      return;

    case '<':
      if(currentChar == '=')
      {
        nextChar();
        currentToken.id = Token::lowerEqualThan;
      }
      else
        currentToken.id = Token::lowerThan;
      return;

    case '/': // comment ?
      switch(currentChar)
      {
      case '*': // "/*"
        for(;;)
        {
          nextChar();
          if(currentChar == '\0')
            goto handleNextChar;
          if(currentChar == '*')
          {
            nextChar();
            if(currentChar == '/')
            {
              nextChar();
              goto handleNextChar;
            }
          }
        }

      case '/': // "//"
        for(;;)
        {
          nextChar();
          if(currentChar == '\0' || currentChar == '\r' || currentChar == '\n')
            goto handleNextChar;
        }

      default:
        unexpectedChar(c);
        goto handleNextChar;
      }

    case '\r':
      ++currentLine;
      if(currentChar == '\n')
        nextChar();
      goto handleNextChar;
    case '\n':
      ++currentLine;
      goto handleNextChar;

    case '"': // string
      {
        currentToken.id = Token::quotedString;
        String& value = currentToken.value;
        value.clear();
        while(currentChar != '"')
        {
          if(currentChar == '\\')
          {
            nextChar();
            if(currentChar == '\0')
              goto handleNextChar;
            static const char backslashChars[] = "rnt\"\\";
            static const char backslashTranslation[] = "\r\n\t\"\\";
            const char* str = strchr(backslashChars, currentChar);
            if(str)
              value.append(backslashTranslation[str - backslashChars]);
            else
            {
              value.append('\\');
              value.append(currentChar);
            }
          }
          else
            value.append(currentChar);
          nextChar();
          if(currentChar == '\0')
            goto handleNextChar;
        }
        nextChar(); // skip closing "
        return;
      }

    default: // space, keyword or identifier

      if(isspace(*(unsigned char*)&c))
        goto handleNextChar;

      if(isalpha(c) || c == '_')
      {
        currentToken.id = Token::string;
        String& value = currentToken.value;
        value.clear();
        value.append(c);
        while(isalnum(currentChar) || currentChar == '_')
        {
          value.append(currentChar);
          nextChar();
        }
        return;
      }

      unexpectedChar(c);
      goto handleNextChar;
    }
handleNextChar: ;
  }
}

void Parser::unexpectedChar(char c)
{
  String message;
  message.format(256, "unexpected character \"%c\"", c);
  errorHandler(errorHandlerUserData, filePath, currentLine, message);
  throw false;
}

void Parser::expectToken(Token::Id id)
{
  if(currentToken.id != id)
  {
    String message;
    message.format(256, "expected \"%s\" instead of \"%s\"", currentToken.getName(id), currentToken.getName());
    errorHandler(errorHandlerUserData, filePath, currentLine, message);
    throw false;
  }
  nextToken();
}

void Parser::readString(String& string)
{
  switch(currentToken.id)
  {
  case Token::string:
  case Token::quotedString:
    string = currentToken.value;
    nextToken();
    return;
  default:
    {
      String message;
      message.format(256, "expected string instead of \"%s\"", currentToken.getName());
      errorHandler(errorHandlerUserData, filePath, currentLine, message);
      throw false;
    }
  }
}

Statement* Parser::readFile()
{
  BlockStatement* statement = new BlockStatement(*includeFile);
  while(currentToken.id != Token::eof)
    statement->statements.append(readStatement());
  return statement;
}

Statement* Parser::readStatements()
{
  if(currentToken.id == Token::leftBrace)
  {
    nextToken();
    BlockStatement* blockStatement = new BlockStatement(*includeFile);
    while(currentToken.id != Token::rightBrace)
      blockStatement->statements.append(readStatement());
    nextToken();
    return blockStatement;
  }
  else
    return readStatement();
}

Statement* Parser::readStatement()
{
  Statement* statement;
  if(currentToken.id == Token::string && currentToken.value == "if")
  {
    nextToken();
    IfStatement* ifStatement = new IfStatement(*includeFile);
    ifStatement->condition = readExpression();
    ifStatement->thenStatements = readStatements();
    if(currentToken.id == Token::string && currentToken.value == "else")
    {
      nextToken();
      ifStatement->elseStatements = readStatements();
    }
    statement = ifStatement;
  }
  else if(currentToken.id == Token::string && currentToken.value == "include")
  {
    nextToken();

    String fileName;
    readString(fileName);
    if(!File::isPathAbsolute(fileName))
    {
      String parentDir = includeFile->fileDir;
      if(parentDir != ".")
        fileName = parentDir + "/" + fileName;
    }

    Parser parser(engine);
    WrapperStatement* statement = new WrapperStatement(*includeFile);
    statement->statement = parser.parse(fileName, errorHandler, errorHandlerUserData);
    if(!statement->statement)
      throw false;
    return statement;
  }
  else
    statement = readAssignment();
  while(currentToken.id == Token::comma)
    nextToken();
  return statement;
}

Statement* Parser::readAssignment()
{
  if(currentToken.id == Token::minus)
  {
    nextToken();
    RemoveStatement* statement = new RemoveStatement(*includeFile);
    readString(statement->variable);
    return statement;
  }
  else
  {
    AssignStatement* statement = new AssignStatement(*includeFile);
    readString(statement->variable);
    switch(currentToken.id)
    {
    case Token::plusAssignment:
    case Token::minusAssignment:
      statement->operation = currentToken.id;
      // no break
    case Token::assignment:
      nextToken();
      statement->value = readConcatination();
      break;
    default:
      break;
    }
    return statement;
  }
}

Statement* Parser::readExpression()
{
  Statement* statement = readOrForumla();
  if(currentToken.id == Token::interrogation)
  {
    nextToken();
    IfStatement* ifStatement = new IfStatement(*includeFile);
    ifStatement->condition = statement;
    ifStatement->thenStatements = readExpression();
    if(currentToken.id == Token::colon)
    {
      nextToken();
      ifStatement->elseStatements = readExpression();
    }
    return ifStatement;
  }
  return statement;
}

Statement* Parser::readOrForumla()
{
  Statement* statement = readAndFormula();
  while(currentToken.id == Token::or_)
  {
    BinaryStatement* binaryStatement = new BinaryStatement(*includeFile);
    binaryStatement->operation = currentToken.id;
    nextToken();
    binaryStatement->leftOperand = statement;
    binaryStatement->rightOperand = readAndFormula();
    statement = binaryStatement;
  }
  return statement;
}

Statement* Parser::readAndFormula()
{
  Statement* statement = readComparison();
  while(currentToken.id == Token::and_)
  {
    BinaryStatement* binaryStatement = new BinaryStatement(*includeFile);
    binaryStatement->operation = currentToken.id;
    nextToken();
    binaryStatement->leftOperand = statement;
    binaryStatement->rightOperand = readComparison();
    statement = binaryStatement;
  }
  return statement;
}

Statement* Parser::readComparison()
{
  Statement* statement = readRelation();
  while(currentToken.id == Token::equal || currentToken.id == Token::notEqual)
  {
    BinaryStatement* binaryStatement = new BinaryStatement(*includeFile);
    binaryStatement->operation = currentToken.id;
    nextToken();
    binaryStatement->leftOperand = statement;
    binaryStatement->rightOperand = readRelation();
    statement = binaryStatement;
  }
  return statement;
}

Statement* Parser::readRelation()
{
  Statement* statement = readValue();
  while(currentToken.id == Token::greaterThan || currentToken.id == Token::lowerThan ||
    currentToken.id == Token::greaterEqualThan || currentToken.id == Token::lowerEqualThan)
  {
    BinaryStatement* binaryStatement = new BinaryStatement(*includeFile);
    binaryStatement->operation = currentToken.id;
    nextToken();
    binaryStatement->leftOperand = statement;
    binaryStatement->rightOperand = readValue();
    statement = binaryStatement;
  }
  return statement;
}

Statement* Parser::readConcatination()
{
  Statement* statement = readValue();
  while(currentToken.id == Token::plus || currentToken.id == Token::minus)
  {
    BinaryStatement* binaryStatement = new BinaryStatement(*includeFile);
    binaryStatement->operation = currentToken.id;
    nextToken();
    binaryStatement->leftOperand = statement;
    binaryStatement->rightOperand = readValue();
    statement = binaryStatement;
  }
  return statement;
}

Statement* Parser::readValue()
{
  switch(currentToken.id)
  {
  case Token::not_:
    {
      UnaryStatement* statement = new UnaryStatement(*includeFile);
      statement->operation = currentToken.id;
      nextToken();
      statement->operand = readValue();
      return statement;
    }
  case Token::leftParenthesis:
    {
      nextToken();
      Statement* statement = readExpression();
      expectToken(Token::rightParenthesis);
      return statement;
    }
  case Token::leftBrace:
    {
      nextToken();
      BlockStatement* statements = new BlockStatement(*includeFile);
      while(currentToken.id != Token::rightBrace)
      {
        if(currentToken.id == Token::eof)
          expectToken(Token::rightBrace);
        statements->statements.append(readStatement());
      }
      nextToken();
      return statements;
    }
  case Token::string:
    if(currentToken.value == "true")
    {
      nextToken();
      StringStatement* statement = new StringStatement(*includeFile);
      statement->value = "true";
      return statement;
    }
    else if(currentToken.value == "false")
    {
      nextToken();
      return new StringStatement(*includeFile);
    }
    else
    {
      ReferenceStatement* statement = new ReferenceStatement(*includeFile);
      readString(statement->variable);
      return statement;
    }
  default: // quotedString
    {
      StringStatement* statement = new StringStatement(*includeFile);
      readString(statement->value);
      return statement;
    }
  }
}


text:
import sys
import serial
import cgi, cgitb
import json

#-----------------------------------------------------------------------------
# Buscar puertos series disposibles.
# ENTRADAS:
#   -num_ports : Numero de puertos a escanear. Por defecto 20
#   -verbose   : Modo verboso True/False. Si esta activado se va
#                imprimiendo todo lo que va ocurriendo
# DEVUELVE:
#    Una lista con todos los puertos encontrados. Cada elemento de la lista
#    es una tupla con el numero del puerto y el del dispositivo
#-----------------------------------------------------------------------------
def scan(num_ports = 20, verbose=True):
	#-- Lista de los dispositivos serie. Inicialmente vacia
	dispositivos_serie = []
	#if verbose:
		#print "Escanenado %d puertos serie:" % num_ports
	#-- Escanear num_port posibles puertos serie
	for i in range(num_ports):
		if verbose:
			sys.stdout.write("puerto %d: " % i)
			sys.stdout.flush()
		try:
			#-- Abrir puerto serie
			s = serial.Serial(i)
			#if verbose: print "OK --> %s" % s.portstr
			#-- Si no hay errores, anadir el numero y nombre a la lista
			dispositivos_serie.append( (i, s.portstr))
			#-- Cerrar puerto
			s.close()
		#-- Si hay un error se ignora
		except:
			#if verbose: print "NO"
			pass
	#-- Devolver la lista de los dispositivos serie encontrados
	return dispositivos_serie

#--------------------------
# Pruebas del modulo Scan
#--------------------------
if __name__=='__main__':

	form = cgi.FieldStorage() # instantiate only once!
	auto = form.getvalue('id')

	#-- Escanear los puertos.
	#-- Se puede indicar el numero de puertos a escaner
	#-- El modo "verbose" esta activado por defecto. Se desactiva con False
	puertos_disponibles=scan(num_ports=33,verbose=False)

	#-- Recorrer la lista mostrando los que se han podido abrir
	print ("Content-Type: application/json\n")
	if (auto == "1"):
		if len(puertos_disponibles)!=0:
			jsondata = []
			for n,nombre in puertos_disponibles:
				#print "  (%d) %s" % (n,nombre)
				#jsondata = [jsondata + [n, nombre]]
				#aux = {n, nombre}
				aux = { 'optionValue':nombre, 'optionDisplay':nombre }
				jsondata.append(aux)
			print (json.dumps( jsondata ))
		else:
			print ("0")
	else:
		jsondata = [ {"optionValue": "COM1", "optionDisplay": "COM 1"}, {"optionValue": "COM2", "optionDisplay": "COM 2"}, {"optionValue": "COM3", "optionDisplay": "COM 3"}, {"optionValue": "COM4", "optionDisplay": "COM 4"}, {"optionValue": "COM5", "optionDisplay": "COM 5"}, {"optionValue": "COM6", "optionDisplay": "COM 6"}, {"optionValue": "COM7", "optionDisplay": "COM 7"}, {"optionValue": "COM8", "optionDisplay": "COM 8"}, {"optionValue": "COM9", "optionDisplay": "COM 9"}, {"optionValue": "COM33", "optionDisplay": "COM 33"}, {"optionValue": "COM34", "optionDisplay": "COM 34"}, {"optionValue": "COM35", "optionDisplay": "COM 35"}, {"optionValue": "CNCA0", "optionDisplay": "CNCA0"}, {"optionValue": "CNCB0", "optionDisplay": "CNCB0"}]
		print (json.dumps( jsondata ))


text:
Ext.define('Densa.mvc.ViewController', {
    extend: 'Deft.mvc.ViewController',
    optionalControl: null,

    mixins: {
        observable: 'Ext.util.Observable'
    },

    constructor: function(config) {
        this.callParent(arguments);
        this.mixins.observable.constructor.call(this, config);
    },
    onViewInitialize: function()
    {
        if (this.optionalControl) {
            this.control = Ext.clone(this.control || {});
            for (var id in this.optionalControl) {
                if (typeof this.control[id] != 'undefined') continue;
                var config = this.optionalControl[id];
                var selector = null;
                if (id !== 'view') {
                    if (Ext.isString(config)) {
                        selector = config;
                    } else if (config.selector != null) {
                        selector = config.selector;
                    } else {
                        selector = '#' + id;
                    }
                }
                if (this.getViewComponent(selector)) {
                    this.control[id] = config;
                }
            }
        }
        this.callParent(arguments);
    },

    /**
     * Fires an event on the view. See {@link Ext.Component#fireEvent}.
     * @param {String} eventName The name of the event to fire.
     * @param {Object...} args Variable number of parameters are passed to handlers.
     * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
     * @protected
     */
    fireViewEvent: function(eventName) {
        var view = this.view,
            result = false;

        if (view) {
            result = view.fireEvent.apply(view, arguments);
        }
        return result;
    }
});


text:
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;

namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages
{
    [Guid(Guids.RoslynOptionPagePerformanceFunctionIdIdString)]
    internal class PerformanceFunctionIdPage : AbstractOptionPage
    {
        protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider)
        {
            return new InternalOptionsControl(PerformanceFunctionIdOptionsProvider.Name, serviceProvider);
        }
    }
}


text:
package ru.job4j;

/** javadoc comment for class. */
public class Calculate {

    /** javadoc comment for method.
     @param args you can leave empty */
    public static void main(String[] args) {
        System.out.println("Hello World");
    }

    /**
     * Method echo.
     * @param name Your name.
     * @return Echo plus your name.
     */
    public String echo(String name) {
        return "Echo, echo, echo : " + name;
    }

}


text:
function check_root {
    if [ "$EUID" -eq "0" ]; then
	    echo "running as root."
    else
	    echo "Root authentication required. (Rerun with sudo)." 1>&2
	    exit 1
    fi
}
check_root

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

rm -rf /opt/homebrew*

sudo -u _brew -g _brew getconf DARWIN_USER_TEMP_DIR | xargs dirname | xargs -I {} rm -rf '{}'
sysadminctl -deleteUser _brew -keepHome
bashrc='/etc/bashrc'
if [ -n "$(grep "alias brew=" ${bashrc})" ]; then
    sed -i '' -e '/^alias brew/ d' ${bashrc}
fi

if [ -n "$(grep "alias pip=" ${bashrc})" ]; then
    sed -i '' -e '/^alias pip/ d' ${bashrc}
fi

if [ -n "$(grep "alias gem=" ${bashrc})" ]; then
    sed -i '' -e '/^alias gem/ d' ${bashrc}
fi


text:
package org.r358.poolnetty.test.simpleserver;

import io.netty.channel.ChannelHandlerContext;

/**
 *
 */
public interface SimpleServerListener
{

    void newValue(ChannelHandlerContext ctx, String val);

    void newConnection(ChannelHandlerContext ctx);

}


text:
using System.Reflection;
using Abp.Modules;
using Abp.Reflection.Extensions;
using poolprobase.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace poolprobase.Web.Startup
{
    [DependsOn(typeof(poolprobaseWebCoreModule))]
    public class poolprobaseWebMvcModule : AbpModule
    {
        private readonly IHostingEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        public poolprobaseWebMvcModule(IHostingEnvironment env)
        {
            _env = env;
            _appConfiguration = env.GetAppConfiguration();
        }

        public override void PreInitialize()
        {
            Configuration.Navigation.Providers.Add<poolprobaseNavigationProvider>();
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(poolprobaseWebMvcModule).GetAssembly());
        }
    }
}


text:
package com.colmcoughlan.colm.alchemy.repository;

import com.colmcoughlan.colm.alchemy.model.Donation;

import androidx.room.Database;
import androidx.room.RoomDatabase;

/**
 * Created by colmc on 30/12/2018.
 */

@Database(entities = {Donation.class}, version = 1, exportSchema = false)
public abstract class DonationDatabase extends RoomDatabase {
    public abstract DonationDao donationDao();
}


text:
#include <stdio.h>
#include <string.h>
#include "common.h"
#include "object.h"
#include "vect.h"
#include "list.h"
#include "env.h"
#include "sb.h"
#include "stdarg.h"
#include "stdarg.h"
#include "listo.h"

List* tempRoots = NULL;
Object* rootObject = NULL;
uint32_t numObjects = 0;
uint32_t maxObjects = 32;

void listoPushRoot(Object* object) {
    listAddFirst(tempRoots, object);
}
void listoPopRoot(void) {
    listPopFirst(tempRoots);
}

static void mark(Object* obj) {
    obj->marked = 1;
    if (obj->type == OBJ_LIST) {
        ListNode* curr = obj->data.list->head;
        while(curr != NULL) {
            mark(curr->data);
            curr = curr->next;
        }
    } else if (obj->type == OBJ_VECTOR) {
        for (int ix = 0; ix < vectSize(obj->data.vector); ix++) {
            mark(vectGet(obj->data.vector, ix));
        }
    }
}

static void gc() {
    int nobjs = numObjects;
    Env* env =  getGlobalEnv();
    Entry* curr = getBindingsHead(env);
    while (curr != NULL) {
        mark(curr->symbol);
        mark(curr->variable);
        curr = curr->next;
    }
    Object** object = &rootObject;
    while (*object) {
        if (!(*object)->marked) {
            Object* unreached = *object;
            *object = unreached->next;
            freeObject(unreached);
            numObjects--;
        } else {
            (*object)->marked = 0;
            object = &(*object)->next;
        }
    }
    maxObjects *= 2;
    printf("Collected: %d, Remaining: %d\n", nobjs - numObjects, numObjects);
}

/*Object*/
Object* newObject(ObjectType type) {
    if (tempRoots == NULL) {
        tempRoots = newList();
    }

    if (numObjects == maxObjects) {
        gc();
    }

    Object* object = malloc(sizeof(Object));
    if (object == NULL) {
        error("Out of memory");
    }
    object->type = type;
    object->next = rootObject;
    rootObject = object;
    object->marked = 0;
    numObjects++;
    return object;
}

void freeObject(Object* object) {
    switch (object->type) {
        case OBJ_LIST: {
            ListNode* curr = object->data.list->head;
            while(curr != NULL) {
                freeObject(curr->data);
                curr = curr->next;
            }
            break;
        }
        case OBJ_VECTOR: {
            for (int ix = 0; ix < vectSize(object->data.vector); ix++) {
                freeObject(vectGet(object->data.vector, ix));
            }
            break;
        }
    }
}

Object* newNumber(double value) {
    Object* object = newObject(OBJ_NUMBER);
    object->data.number = value;
    return object;
}

Object* newBoolean(bool value) {
    Object* object = newObject(OBJ_BOOLEAN);
    object->data.boolean = value;
    return object;
}

Object* newString(const char* value) {
    return newStringWithLength(value, (uint32_t) strlen(value));
}

Object* newStringWithLength(const char* value, uint32_t length) {
    char* chars = malloc(sizeof(char) * (length + 1));
    Object* object = newObject(OBJ_STRING);
    memcpy(chars, value, length);
    chars[length] = '\0';
    object->data.chars = chars;
    return object;
}

Object* newSymbol(const char* value) {
    return newSymbolWithLength(value, (uint32_t) strlen(value));
}

Object* newSymbolWithLength(const char* value, uint32_t length) {
    char* chars = malloc(sizeof(char) * (length + 1));
    Object* object = newObject(OBJ_SYMBOL);
    memcpy(chars, value, length);
    chars[length] = '\0';
    object->data.chars = chars;
    return object;
}

Object* newError(const char* fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    char* str;
    vasprintf(&str, fmt, ap);
    va_end(ap);

    unsigned long length = strlen(str);
    char* chars = malloc(sizeof(char) * (length + 1));
    Object* object = newObject(OBJ_ERROR);
    memcpy(chars, str, length);
    chars[length] = '\0';
    object->data.chars = chars;
    return object;
}

Object* newFunction(Object* (*function)(List* args)) {
    Object* object = newObject(OBJ_FUNCTION);
    object->data.function = function;
    return object;
}

Object* newClosure(Object* (*eval)(Object*, Env*),
                   Object* args, Object* body, Env* env) {
    Object* obj = newObject(OBJ_CLOSURE);
    obj->data.closure.eval = eval;
    obj->data.closure.args = args;
    obj->data.closure.body = body;
    obj->data.closure.env = env;
    return obj;
}

bool objectEquals(Object* first, Object* second) {
    if (first->type != second->type) {
        return false;
    }
    switch(first->type) {
        case OBJ_BOOLEAN:
            return objectAsBool(first) == objectAsBool(second);
        case OBJ_NUMBER:
            return asNumber(first) == asNumber(second);
        case OBJ_SYMBOL:
        case OBJ_STRING:
            return strcmp(first->data.chars, second->data.chars) == 0;
        case OBJ_NIL:
                return true;
        default:
            return false;
    }
}

static void objectToStringInternal(StringBuffer* sb, Object* object, bool readable) {
    switch (object->type) {
        case OBJ_NIL:
            stringBufferAdd(sb, "nil");
            break;
        case OBJ_BOOLEAN:
            stringBufferAdd(sb, object->data.boolean ? "true" : "false");
            break;
        case OBJ_STRING:
            if (readable) {
                stringBufferAddFormat(sb, "\"%s\"", object->data.chars);
            } else {
                stringBufferAdd(sb, object->data.chars);
            }
            break;
        case OBJ_NUMBER:
            stringBufferAddFormat(sb, "%.14g", object->data.number);
            break;
        case OBJ_SYMBOL:
            stringBufferAddFormat(sb, "%s", object->data.chars);
            break;
        case OBJ_ERROR:
            stringBufferAddFormat(sb, "Error> %s", object->data.chars);
            break;
        case OBJ_VECTOR:
            stringBufferAdd(sb, "[");
            uint32_t vsize = vectSize(object->data.vector);
            for (uint32_t i = 0; i < vsize; i++) {
                objectToStringInternal(sb, vectGet(object->data.vector, i), readable);
                if (i < vsize -1) {
                    stringBufferAdd(sb, " ");
                }
            }
            stringBufferAdd(sb, "]");
            break;
        case OBJ_LIST:
            stringBufferAdd(sb, "(");
            ListNode* curr = object->data.list->head;
            while(curr != NULL) {
                objectToStringInternal(sb, curr->data, readable);
                curr = curr->next;
                if (curr != NULL) {
                    stringBufferAdd(sb, " ");
                }
            }
            stringBufferAdd(sb, ")");
            break;
        case OBJ_CLOSURE:
            stringBufferAddFormat(sb, "<#fn>");
            break;
        case OBJ_FUNCTION:
            stringBufferAddFormat(sb, "<#procedure>");
            break;
        default:
            break;
    }
}

const char* objectToString(Object* object, bool readable) {
    StringBuffer* sb = newStringBuffer();
    objectToStringInternal(sb, object, readable);
    const char* result = stringBufferGetString(sb);
    freeStringBuffer(sb);
    return result;
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\cf\PersonsSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'ID') ?>

    <?= $form->field($model, 'FirstName') ?>

    <?= $form->field($model, 'LastName') ?>

    <?= $form->field($model, 'MidName') ?>

    <?php // echo $form->field($model, 'City') ?>

    <?php // echo $form->field($model, 'Address') ?>

    <?php // echo $form->field($model, 'Email1') ?>

    <?php // echo $form->field($model, 'Phone1') ?>

    <?php // echo $form->field($model, 'Phone2') ?>

    <?php // echo $form->field($model, 'Phone3') ?>

    <?php // echo $form->field($model, 'Additional') ?>

    <?php // echo $form->field($model, 'CardID') ?>

    <?php // echo $form->field($model, 'RegisterDate') ?>

    <?php // echo $form->field($model, 'AccountID') ?>

    <?php // echo $form->field($model, 'Blocked') ?>

    <?php // echo $form->field($model, 'GroupID') ?>

    <?php // echo $form->field($model, 'Login') ?>

    <?php // echo $form->field($model, 'Password') ?>

    <?php // echo $form->field($model, 'MustChangePass') ?>

    <?php // echo $form->field($model, 'Spend') ?>

    <?php // echo $form->field($model, 'Deleted') ?>

    <?php // echo $form->field($model, 'ServiceCard') ?>

        <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
title: Localization
layout: usermanual-page.hbs
position: 9
---

This page describes how to localize your Text Elements to different languages.

## Localization Files

For each language you want to support you will need to add a JSON asset that contains the translated phrases for that language. PlayCanvas supports a specific format for the JSON asset. Open the Editor Settings and under LOCALIZATION click CREATE NEW ASSET to generate a new JSON asset in the expected format.

The JSON asset looks like so:

```javascript
{
    "header": {
        "version": 1
    },
    "data": [
        {
            "info": {
                "locale": "en-US"
            },
            "messages": {
                "key": "Single key translation",
                "key plural": [
                    "One key translation",
                    "Translation for {number} keys"
                ]
            }
        }
    ]
}
```

You can specify a different locale in the `info` part of the JSON file. The `messages` section contains key - value pairs for each localized phrase. The key is the identifier for that phrase and the text is the translated text for that key.

PlayCanvas also supports plural forms for each locale. To specify plural forms for each phrase you need to pass an array of strings for each plural form instead of a single string. Each language has different plural forms which you can find [here][1]. Each array element corresponds to a plural form for that language. For example for English:

```javascript
"key plural": [
    "One item", // plural form ONE
    "Not one" // plural form OTHER
]
```

For Arabic:

```javascript
"key plural": [
    "Zero items", // plural form ZERO
    "One item", // plural form ONE
    "Two items", // plural form TWO
    "Few items", // plural form FEW
    "Many items", // plural form MANY
    "Rest", // plural form OTHER
]
```

Refer to the language tables [here][1] to determine the rules for each language.

After you have created your localization JSON assets you need to add them to the Editor Settings under LOCALIZATION.

## Localizing Text Elements

Enable the `Localized` checkbox for a Text Element in order to use the Localization Files to translate its text. The text you enter in the `Key` field of the Text Element should match the key in the localization file.

To test your localization you can change the `Locale` field under the Editor Settings. That should update your Editor viewport to that locale and also this will update the locale used when you launch your application. This field is not used when you publish or download a build.

## Localizing Numbers

Different locales will have different rules on how numbers should be formatted. For example, English (UK and US) would format `1000000` as `1,000,000` and Dutch would format with a decimal instead `1.000.000`.

JavaScript provides a built in function to do this formatting based on the locale code, [`Number.protoype.toLocaleString()`][5].

An example of usage:

```javascript
var numberOfItems = 1000;
var currentLocale = this.app.i18n.locale;
var localeNumberString = numberOfItems.toLocaleString(currentLocale);

console.log(localeNumberString);
// expected output assuming currentLocale is en-US: "1,000"
```

## Localized Fonts

Often you will find that different languages might require different fonts to be used. In order to define a different font for a specific language select the primary font Asset you are using for your Text Element and towards the bottom of the Asset Attributes you will find the Localization section for that font Asset. Type the desired locale and assign a new font Asset for that locale.

At runtime when the application switches to a different locale it will load the font Asset you defined for that locale.

## Language Notes

There are some languages that require specific workflows or considerations that are listed below.

### Thai

For word wrapping to work correctly in UI Text Elements with Thai text, [zero width characters (Unicode U+200B)][7] need be added between words by the translators.

The Thai language has no spaces between words and the same run of glyphs can be split into different combinations of words depending on the context of the sentence.

Being able to split Thai text correctly computationally is still an [unsolved problem][6] and usually done via a dictionary based approach which can be expensive to do at runtime.

The [thai-language.com site also has a separate tool][8] to add the zero width characters between words using a dictionary based approach if you have existing text.

## Engine

To retrieve the text from a key in script, use the APIs:

* [pc.I18n#getText][3] To retrieve the a non-plural or first text string in a plural list
* [pc.I18n#getPluralText][4] To retrieve a plural text string based on the number

For the complete engine API reference for localization see [this page][2].

[1]: https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html
[2]: /api/pc.I18n.html
[3]: /api/pc.I18n.html#getText
[4]: /api/pc.I18n.html#getPluralText
[5]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
[6]: http://www.thai-language.com/ref/breaking-words
[7]: https://en.wikipedia.org/wiki/Zero-width_space
[8]: http://www.thai-language.com/?nav=zwsp


text:
"""Blockly Games: Turtle/Movie to Reddit Submission

Copyright 2014 Google Inc.
https://github.com/google/blockly-games

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

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

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

"""Store XML with App Engine.  Store thumbnail with Memcache.  Send to Reddit.
"""

__author__ = "fraser@google.com (Neil Fraser)"

import base64
import re
import storage
from google.appengine.api import images
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class Reddit(webapp.RequestHandler):
    def get(self):
      url = re.sub(r"\w+-reddit\?", "thumb?", self.request.url)
      app = re.search(r"(\w+)-reddit\?", self.request.url).group(1)
      uuid = self.request.query_string
      self.response.out.write("""

          <meta property="og:image" content="%s" />
          <meta http-equiv="refresh" content="0; url=/%s?level=10#%s">

Loading Blockly Games : %s : %s...

      """ % (url, app, uuid, app.title(), uuid))

    def post(self):
      xml = str(self.request.get("xml"))
      thumb = str(self.request.get("thumb"))
      uuid = storage.xmlToKey(xml)
      memcache.add("THUMB_" + uuid, thumb, 3600)
      self.redirect("https://www.reddit.com/r/BlocklyGames/submit?url=%s?%s"
                    % (self.request.url, uuid))

class Thumb(webapp.RequestHandler):
    def get(self):
      uuid = self.request.query_string
      thumbnail = memcache.get("THUMB_" + uuid)
      if not thumbnail:
        raise Exception("Thumbnail not found: %s" % uuid)
      header = "data:image/png;base64,"
      if not thumbnail.startswith(header):
        raise Exception("Bad header: %s" % thumbnail[:len(header)])
      thumbnail = base64.b64decode(thumbnail[len(header):])
      # Resize image to prove that this is an image, not random content.
      # Tested to verify that this throws BadImageError if not a valid PNG.
      thumbnail = images.resize(thumbnail, 100, 100)

      self.response.headers["Content-Type"] = "image/png"
      self.response.out.write(thumbnail)

application = webapp.WSGIApplication([(r"/\w+-reddit", Reddit),
                                      ("/thumb", Thumb),
                                     ],
                                     debug=True)

run_wsgi_app(application)


text:
#include <modules/qtwidgets/properties/buttongrouppropertywidgetqt.h>

#include <inviwo/core/properties/buttongroupproperty.h>     // for ButtonGroupProperty, ButtonGr...
#include <modules/qtwidgets/inviwoqtutils.h>                // for toQString
#include <modules/qtwidgets/properties/propertywidgetqt.h>  // for PropertyWidgetQt

#include <cstddef>   // for size_t
#include <optional>  // for optional

#include <QHBoxLayout>  // for QHBoxLayout
#include <QIcon>        // for QIcon
#include <QLayoutItem>  // for QLayoutItem
#include <QPushButton>  // for QPushButton
#include <QWidget>      // for QWidget

class QHBoxLayout;

namespace inviwo {

ButtonGroupPropertyWidgetQt::ButtonGroupPropertyWidgetQt(ButtonGroupProperty* property)
    : PropertyWidgetQt(property), property_(property) {

    setObjectName("ButtonGroupPropertyWidgetQt");

    QHBoxLayout* hLayout = new QHBoxLayout();
    hLayout->setContentsMargins(0, 0, 0, 0);
    hLayout->setSpacing(0);

    for (size_t i = 0; i < property->size(); ++i) {
        const auto& button = property->getButton(i);

        auto buttonWidget = new QPushButton(this);
        if (button.icon) {
            buttonWidget->setIcon(QIcon(utilqt::toQString(*button.icon)));
        }
        if (button.name) {
            buttonWidget->setText(utilqt::toQString(*button.name));
        }
        if (button.tooltip) {
            buttonWidget->setToolTip(utilqt::toQString(*button.tooltip));
        }

        connect(buttonWidget, &QPushButton::released, this, [this, i]() {
            if (!property_->getReadOnly()) property_->pressButton(i);
        });
        hLayout->addWidget(buttonWidget);
    }
    if (property->size() > 0) {
        setFocusPolicy(hLayout->itemAt(0)->widget()->focusPolicy());
        setFocusProxy(hLayout->itemAt(0)->widget());
    }

    setLayout(hLayout);
}

void ButtonGroupPropertyWidgetQt::updateFromProperty() {}

}  // namespace inviwo


text:
require 'spec_helper'

describe Aiss::CcSignature do
	before :each do
		@cc_signature = Aiss::CcSignature.new
		@nonce_path = "./files/testes/nonce.txt"
		@cyphered_nonce_path = "./files/testes/nonce_cyphered_64.txt"
		@cert = "./files/testes/bern.cert"

		@cc_signature.cert_path_in = @cert
		@cc_signature.nonce_cyphered_path_in = @cyphered_nonce_path
		@cc_signature.nonce_path_in = @nonce_path
	end

	describe "#call_cc_sign" do
		it 'should create a cert file, nonce and signed nonce file encoded in base 64' do
			File.delete(@cyphered_nonce_path) if File.exist?(@cyphered_nonce_path)
			File.delete(@cert) if File.exist?(@cert)

			@cc_signature.call_cc_sign

			File.exist?(@nonce_path).should be_true
			File.exist?(@cyphered_nonce_path).should be_true
			File.exist?(@cert).should be_true
		end
	end

	describe '#call_cc_verify_sign' do
		before :each do
			File.delete(@cyphered_nonce_path) if File.exist?(@cyphered_nonce_path)
			File.delete(@cert) if File.exist?(@cert)

			@cc_signature.cert_path_out = @cert
			@cc_signature.nonce_cyphered_path_out = @cyphered_nonce_path
			@cc_signature.nonce_path_out = @nonce_path

			@cc_signature.call_cc_sign
		end

		it 'should be able to verify the signatures' do
			@cc_signature.call_cc_verify_sign.should match(/Assinatura verificada com sucesso/)
		end

		after :each do
			File.delete(@cyphered_nonce_path) if File.exist?(@cyphered_nonce_path)
			File.delete(@cert) if File.exist?(@cert)
		end

	end

end


text:
#include <cydevice_trm.h>
#include <CyLib.h>
#include <ISR_WATCHDOG.h>

#if !defined(ISR_WATCHDOG__REMOVED) /* Check for removal by optimization */

/*******************************************************************************
*  Place your includes, defines and code here
********************************************************************************/
/* `#START ISR_WATCHDOG_intc` */

/* `#END` */

/*******************************************************************************
* Function Name: ISR_WATCHDOG_Start
********************************************************************************
*
* Summary:
*  Set up the interrupt and enable it. This function disables the interrupt,
*  sets the default interrupt vector, sets the priority from the value in the
*  Design Wide Resources Interrupt Editor, then enables the interrupt to the
*  interrupt controller.
*
* Parameters:
*   None
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_Start(void)
{
    /* For all we know the interrupt is active. */
    ISR_WATCHDOG_Disable();

    /* Set the ISR to point to the ISR_WATCHDOG Interrupt. */
    ISR_WATCHDOG_SetVector(&ISR_WATCHDOG_Interrupt);

    /* Set the priority. */
    ISR_WATCHDOG_SetPriority((uint8)ISR_WATCHDOG_INTC_PRIOR_NUMBER);

    /* Enable it. */
    ISR_WATCHDOG_Enable();
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_StartEx
********************************************************************************
*
* Summary:
*  Sets up the interrupt and enables it. This function disables the interrupt,
*  sets the interrupt vector based on the address passed in, sets the priority
*  from the value in the Design Wide Resources Interrupt Editor, then enables
*  the interrupt to the interrupt controller.
*
*  When defining ISR functions, the CY_ISR and CY_ISR_PROTO macros should be
*  used to provide consistent definition across compilers:
*
*  Function definition example:
*   CY_ISR(MyISR)
*   {
*   }
*   Function prototype example:
*   CY_ISR_PROTO(MyISR);
*
* Parameters:
*   address: Address of the ISR to set in the interrupt vector table.
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_StartEx(cyisraddress address)
{
    /* For all we know the interrupt is active. */
    ISR_WATCHDOG_Disable();

    /* Set the ISR to point to the ISR_WATCHDOG Interrupt. */
    ISR_WATCHDOG_SetVector(address);

    /* Set the priority. */
    ISR_WATCHDOG_SetPriority((uint8)ISR_WATCHDOG_INTC_PRIOR_NUMBER);

    /* Enable it. */
    ISR_WATCHDOG_Enable();
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_Stop
********************************************************************************
*
* Summary:
*   Disables and removes the interrupt.
*
* Parameters:
*   None
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_Stop(void)
{
    /* Disable this interrupt. */
    ISR_WATCHDOG_Disable();
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_Interrupt
********************************************************************************
*
* Summary:
*   The default Interrupt Service Routine for ISR_WATCHDOG.
*
*   Add custom code between the START and END comments to keep the next version
*   of this file from over-writing your code.
*
*   Note You may use either the default ISR by using this API, or you may define
*   your own separate ISR through ISR_StartEx().
*
* Parameters:
*   None
*
* Return:
*   None
*
*******************************************************************************/
CY_ISR(ISR_WATCHDOG_Interrupt)
{
    #ifdef ISR_WATCHDOG_INTERRUPT_INTERRUPT_CALLBACK
        ISR_WATCHDOG_Interrupt_InterruptCallback();
    #endif /* ISR_WATCHDOG_INTERRUPT_INTERRUPT_CALLBACK */

    /*  Place your Interrupt code here. */
    /* `#START ISR_WATCHDOG_Interrupt` */

    /* `#END` */

    /* PSoC3 ES1, ES2 RTC ISR PATCH  */
    #if(CYDEV_CHIP_FAMILY_USED == CYDEV_CHIP_FAMILY_PSOC3)
        #if((CYDEV_CHIP_REVISION_USED <= CYDEV_CHIP_REVISION_3A_ES2) && (ISR_WATCHDOG__ES2_PATCH ))
            ISR_WATCHDOG_ISR_PATCH();
        #endif /* CYDEV_CHIP_REVISION_USED */
    #endif /* (CYDEV_CHIP_FAMILY_USED == CYDEV_CHIP_FAMILY_PSOC3) */
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_SetVector
********************************************************************************
*
* Summary:
*   Change the ISR vector for the Interrupt. Note calling ISR_WATCHDOG_Start
*   will override any effect this method would have had. To set the vector
*   before the component has been started use ISR_WATCHDOG_StartEx instead.
*
*   When defining ISR functions, the CY_ISR and CY_ISR_PROTO macros should be
*   used to provide consistent definition across compilers:
*
*   Function definition example:
*   CY_ISR(MyISR)
*   {
*   }
*
*   Function prototype example:
*     CY_ISR_PROTO(MyISR);
*
* Parameters:
*   address: Address of the ISR to set in the interrupt vector table.
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_SetVector(cyisraddress address)
{
    CY_SET_REG16(ISR_WATCHDOG_INTC_VECTOR, (uint16) address);
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_GetVector
********************************************************************************
*
* Summary:
*   Gets the "address" of the current ISR vector for the Interrupt.
*
* Parameters:
*   None
*
* Return:
*   Address of the ISR in the interrupt vector table.
*
*******************************************************************************/
cyisraddress ISR_WATCHDOG_GetVector(void)
{
    return (cyisraddress) CY_GET_REG16(ISR_WATCHDOG_INTC_VECTOR);
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_SetPriority
********************************************************************************
*
* Summary:
*   Sets the Priority of the Interrupt.
*
*   Note calling ISR_WATCHDOG_Start or ISR_WATCHDOG_StartEx will
*   override any effect this API would have had. This API should only be called
*   after ISR_WATCHDOG_Start or ISR_WATCHDOG_StartEx has been called.
*   To set the initial priority for the component, use the Design-Wide Resources
*   Interrupt Editor.
*
*   Note This API has no effect on Non-maskable interrupt NMI).
*
* Parameters:
*   priority: Priority of the interrupt, 0 being the highest priority
*             PSoC 3 and PSoC 5LP: Priority is from 0 to 7.
*             PSoC 4: Priority is from 0 to 3.
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_SetPriority(uint8 priority)
{
    *ISR_WATCHDOG_INTC_PRIOR = priority << 5;
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_GetPriority
********************************************************************************
*
* Summary:
*   Gets the Priority of the Interrupt.
*
* Parameters:
*   None
*
* Return:
*   Priority of the interrupt, 0 being the highest priority
*    PSoC 3 and PSoC 5LP: Priority is from 0 to 7.
*    PSoC 4: Priority is from 0 to 3.
*
*******************************************************************************/
uint8 ISR_WATCHDOG_GetPriority(void)
{
    uint8 priority;

    priority = *ISR_WATCHDOG_INTC_PRIOR >> 5;

    return priority;
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_Enable
********************************************************************************
*
* Summary:
*   Enables the interrupt to the interrupt controller. Do not call this function
*   unless ISR_Start() has been called or the functionality of the ISR_Start()
*   function, which sets the vector and the priority, has been called.
*
* Parameters:
*   None
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_Enable(void)
{
    /* Enable the general interrupt. */
    *ISR_WATCHDOG_INTC_SET_EN = ISR_WATCHDOG__INTC_MASK;
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_GetState
********************************************************************************
*
* Summary:
*   Gets the state (enabled, disabled) of the Interrupt.
*
* Parameters:
*   None
*
* Return:
*   1 if enabled, 0 if disabled.
*
*******************************************************************************/
uint8 ISR_WATCHDOG_GetState(void)
{
    /* Get the state of the general interrupt. */
    return ((*ISR_WATCHDOG_INTC_SET_EN & (uint8)ISR_WATCHDOG__INTC_MASK) != 0u) ? 1u:0u;
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_Disable
********************************************************************************
*
* Summary:
*   Disables the Interrupt in the interrupt controller.
*
* Parameters:
*   None
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_Disable(void)
{
    /* Disable the general interrupt. */
    *ISR_WATCHDOG_INTC_CLR_EN = ISR_WATCHDOG__INTC_MASK;
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_SetPending
********************************************************************************
*
* Summary:
*   Causes the Interrupt to enter the pending state, a software method of
*   generating the interrupt.
*
* Parameters:
*   None
*
* Return:
*   None
*
* Side Effects:
*   If interrupts are enabled and the interrupt is set up properly, the ISR is
*   entered (depending on the priority of this interrupt and other pending
*   interrupts).
*
*******************************************************************************/
void ISR_WATCHDOG_SetPending(void)
{
    *ISR_WATCHDOG_INTC_SET_PD = ISR_WATCHDOG__INTC_MASK;
}

/*******************************************************************************
* Function Name: ISR_WATCHDOG_ClearPending
********************************************************************************
*
* Summary:
*   Clears a pending interrupt in the interrupt controller.
*
*   Note Some interrupt sources are clear-on-read and require the block
*   interrupt/status register to be read/cleared with the appropriate block API
*   (GPIO, UART, and so on). Otherwise the ISR will continue to remain in
*   pending state even though the interrupt itself is cleared using this API.
*
* Parameters:
*   None
*
* Return:
*   None
*
*******************************************************************************/
void ISR_WATCHDOG_ClearPending(void)
{
    *ISR_WATCHDOG_INTC_CLR_PD = ISR_WATCHDOG__INTC_MASK;
}

#endif /* End check for removal by optimization */

/* [] END OF FILE */


text: TRANSLOADIT_URL = 'http://api2.transloadit.com/assemblies'


text:
'''
    This file holds all of the forms for the cleaning and validation of
    the parameters being used for friend requests.

    Created on Dec 20, 2013

    @author: Andrew Oberlin, Jake Gregg
'''
from django import forms
from rememerme.games.models import Game, GameMember
from rememerme.games.rest.exceptions import InvalidWinningScore, GameNotFound,\
    BadRequestException
from rememerme.games.serializers import GameSerializer, GameMemberSerializer
from uuid import UUID
import uuid
from pycassa.cassandra.ttypes import NotFoundException as CassaNotFoundException
import datetime
import json
from rememerme.games.permissions import GamePermissions
from rememerme.users.client import UserClient, UserClientError

class GamesListGetForm(forms.Form):

    def submit(self, request):
        try:
            game_memberships = GameMember.filterByUser(request.user.pk)
            games = [Game.getByID(mem.game_id) for mem in game_memberships]
        except CassaNotFoundException:
            raise GameNotFound()
        return GameSerializer(games, many=True).data

'''
    Creates a new game instance.
'''
class GamesPostForm(forms.Form):
    game_members = forms.CharField(required=True)
    winning_score = forms.IntegerField(required=True)

    def clean(self):
        '''
            Overriding the clean method to add the default offset and limiting information.
        '''
        now = datetime.datetime.now()
        self.cleaned_data['date_created'] = now
        self.cleaned_data['last_modified'] = now

        if self.cleaned_data['winning_score'] <= 0:
            raise InvalidWinningScore()

        try:
            self.cleaned_data['game_members'] = json.loads(self.cleaned_data['game_members'])
            if not isinstance(self.cleaned_data['game_members'], list):
                raise BadRequestException()
        except ValueError:
            raise BadRequestException()

        return self.cleaned_data

    def submit(self, request):
        '''
            Submits this form to create the given game.
        '''
        game_members = self.cleaned_data['game_members']
        del self.cleaned_data['game_members']
        self.cleaned_data['leader_id'] = UUID(request.user.pk)
        game = Game.fromMap(self.cleaned_data)
        game.save()

        members_added = {}

        for mem in game_members:
            try:
                mem = str(UUID(mem))
                UserClient(request.auth).get(mem)
                # user exists so let's add him/her
                now = datetime.datetime.now()
                member = GameMember(game_member_id=str(uuid.uuid1()), game_id=UUID(game.game_id), user_id=UUID(mem), status=1, date_created=now, last_modified=now)
                member.save()
                members_added[member.game_member_id] = now
            except ValueError, UserClientError:
                continue

        member = GameMember(game_member_id=str(uuid.uuid1()), score=0, game_id=UUID(game.game_id), user_id=UUID(request.user.pk), status=2, date_created=now, last_modified=now)
        member.save()
        members_added[member.game_member_id] = now

        serialized = GameSerializer(game).data
        serialized['game_members'] = members_added
        return serialized

class GamesSingleGetForm(forms.Form):
    game_id = forms.CharField()

    def clean(self):
        try:
            self.cleaned_data['game_id'] = str(UUID(self.cleaned_data['game_id']))
        except ValueError:
            raise GameNotFound()
        return self.cleaned_data

    def submit(self, request):
        try:
            game = Game.getByID(self.cleaned_data['game_id'])
            if not GamePermissions.has_object_permission(request, game):
                raise BadRequestException()
        except CassaNotFoundException:
            raise GameNotFound()
        return GameSerializer(game).data

class GameRequestsForm(forms.Form):
    def submit(self, request):
        requests = [gm for gm in GameMember.filterByUser(request.user.pk) if gm.status == 1]
        return GameMemberSerializer(requests, many=True).data


text:
<resources>

    <!--Customize here the subject of your application-->
    <style name="myTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/materialblueprimary</item>
        <item name="colorPrimaryDark">@color/materialbluedark</item>
        <item name="colorAccent">@color/materialbluealpha</item>
    </style>

    <!--Here will be the theme of the class that will extends NavigationLiveo-->
    <style name="nLiveoDrawer" parent="nLiveo.Theme.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/materialblueprimary</item>
        <item name="colorPrimaryDark">@color/materialbluedark</item>
        <item name="colorAccent">@color/materialbluealpha</item>
    </style>

</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.teradata.prestomanager</groupId>
        <artifactId>presto-manager</artifactId>
        <version>0.1-SNAPSHOT</version>
    </parent>
    <artifactId>presto-manager-controller</artifactId>

    <properties>
        <project.root>${project.parent.basedir}</project.root>

        <main-class>com.teradata.prestomanager.controller.ControllerServer</main-class>
        <executable-name>ControllerServer</executable-name>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.teradata.prestomanager</groupId>
            <artifactId>presto-manager-common</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>io.airlift.discovery</groupId>
            <artifactId>discovery-server</artifactId>
            <version>1.28</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${shade-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>${executable-name}</finalName>
                            <shadedArtifactAttached>true</shadedArtifactAttached>
                            <shadedClassifierName>executable</shadedClassifierName>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>${main-class}</Main-Class>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>com.github.kongchen</groupId>
                <artifactId>swagger-maven-plugin</artifactId>
                <version>3.1.5</version>
                <configuration>
                    <apiSources>
                        <apiSource>
                            <info>
                                <title>Presto Manager Controller</title>
                                <version>v1</version>
                                <description>Swagger specification for REST API</description>
                                <license>
                                    <name>Apache License 2.0</name>
                                    <url>http://www.apache.org/licenses/LICENSE-2.0</url>
                                </license>
                            </info>
                            <springmvc>false</springmvc>
                            <basePath>/v1</basePath>
                            <swaggerDirectory>${project.build.directory}/swagger</swaggerDirectory>
                            <swaggerFileName>Controller.swagger</swaggerFileName>
                            <outputFormats>yaml</outputFormats>
                            <locations>
                                <location>com.teradata.prestomanager.controller.api</location>
                            </locations>
                        </apiSource>
                    </apiSources>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>io.github.swagger2markup</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>1.3.1</version>
                <configuration>
                    <swaggerInput>${project.build.directory}/swagger/Controller.swagger.yaml</swaggerInput>
                    <outputDir>${project.build.directory}/swagger/asciidoc</outputDir>
                    <config>
                        <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                    </config>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
namespace tizen_webview {

ContextMenuController::~ContextMenuController() {
}

} // namespace tizen_webview


text:
/* jshint node: true  */
'use strict';

const util = require('util'),
      defaults = require('../defaults'),
      options = require('../options');

var descriptor = defaults.defaultDescriptor({
  'productName': {
    name: 'Product Name',
    required: true
  },
  'displayName': {
    name: 'Display Name'
  },
  'productDesc': {
        name: 'Description'
  },
  'proxies': {
    name: 'API Proxies',
    required: true
  },
  'environments':{
        name: 'Environments',
        required: true
  },
  'approvalType': {
        name: 'Approval Type',
        required: true
  },
  'quota' : {
        name: 'Quota',
  },
  'quotaInterval':{
        name: 'Quota Interval'
  },
  'quotaTimeUnit': {
        name:'Quota Time Unit'
  },
  'scopes': {
        name: "Scope",
  }
});

module.exports.descriptor = descriptor;

module.exports.run = function(opts, cb) {
  options.validateSync(opts, descriptor);
  if (opts.debug) {
    console.log('createProduct: %j', opts);
  }
  var request = defaults.defaultRequest(opts);
  createProduct(opts, request, function(err, results) {
      if (err) {
        cb(err);
      } else {
        if (opts.debug) {
          console.log('results: %j', results);
        }
        cb(undefined, results);
      }
    });
};

function createProduct(opts,request,done){
        var product = {
          "approvalType": "auto",
          "attributes":
            [ {"name": "access", "value": "public"} ],
          "scopes": []
        }

        product.name = opts.productName
        if(opts.displayName){
                product.displayName = opts.displayName
        }else{
                product.displayName = opts.productName
        }
        product.description = opts.productDesc
        if(opts.approvalType){
                product.approvalType = opts.approvalType
        }
        product.proxies = []
        if(opts.proxies){
                var split = opts.proxies.split(',')
                split.forEach(function(s){
                        if(s && s.trim()!= '') {
                                product.proxies.push(s.trim())
                        }
                })
        }
        product.apiResources = []
        if(opts.apiResources){
                var split = opts.apiResources.split(',')
                split.forEach(function(s){
                        if(s && s.trim()!= '') {
                                product.apiResources.push(s.trim())
                        }
                })
        }
        if(opts.attributes) {
                product.attributes = opts.attributes;
        }
        if(opts.scopes){
                var split = opts.scopes.split(',')
                split.forEach(function(s){
                        if(s && s.trim()!= '') {
                                product.scopes.push(s.trim())
                        }
                })
        }
        product.environments = []
        if(opts.environments){
                var split = opts.environments.split(',')
                split.forEach(function(s){
                        if(s && s.trim()!= '') {
                                product.environments.push(s.trim())
                        }
                })
        }
        if(opts.quota && opts.quotaInterval && opts.quotaTimeUnit){
                product.quota = opts.quota
                product.quotaInterval = opts.quotaInterval
                product.quotaTimeUnit = opts.quotaTimeUnit
        }

        var uri = util.format('%s/v1/o/%s/apiproducts', opts.baseuri, opts.organization);
        request({
                uri: uri,
                method:'POST',
                body: product,
                json:true
        },function(err,res,body){
                var jsonBody = body
                if(err){
                        if (opts.debug) {
                       console.log('Error occured %s', err);
                    }
                        done(err)
                }else if (res.statusCode === 201) {
                        if (opts.verbose) {
                 console.log('Create successful');
                }
                    if (opts.debug) {
                       console.log('%s', body);
                    }
                done(undefined, jsonBody);
                }else {
              if (opts.verbose) {
                console.error('Create Product result: %j', body);
              }
              var errMsg;
              if (jsonBody && (jsonBody.message)) {
                errMsg = jsonBody.message;
              } else {
                errMsg = util.format('Create Product failed with status code %d', res.statusCode);
              }
              done(new Error(errMsg));
        }
        })
}


text:
package com.gp.solutions.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;

    @Value("${authorization.expiration}")
    private int expiration;

    @Value("${authorization.client}")
    private String client;

    @Value("${authorization.secret}")
    private String secret;

    @Value("${authorization.resourceIds}")
    private String getResourceId;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient(client)
                .authorizedGrantTypes("password", "refresh-token")
                .accessTokenValiditySeconds(expiration)
                .scopes("read", "write")
                .secret(secret)
                .resourceIds(getResourceId)
                .and()
                .withClient("swagger-ui")
                .authorizedGrantTypes("implicit")
                .scopes("read", "write"/*, "vendorExtensions"*/)
                .resourceIds(getResourceId)
                .autoApprove(true);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}


text:
set -euo pipefail

# Call koji hello in a loop until it succeeds.
#
# Use in containers that depend on koji-hub and koji-db being ready.

attempts=0

while true; do
    (( attempts+=1 ))
    echo "koji hello attempt #$attempts"

    if timeout 2 koji hello; then
        echo "Success!"
        break
    elif [ $? = 124 ]; then
        echo "Timed out, the hub or database pods are likely still starting."
    fi

    sleep 3
done


text:
Contents
--------

- [Intro](#intro)
- [Setup](#setup)
- [Modules](#modules)
- [Sandboxes](#sandboxes)
  - [Extending the Sandbox](#extending-the-sandbox)
- [Working with Modules](#working-with-modules)
  - [Passing Options to Modules](#passing-options-to-modules)
  - [Events](#events)
  - [Deferred initialization](#deferred-initialization)
  - [Mixins](#mixins)
  - [Event Clean Up](#event-clean-up)
- [Debugging](#debugging)
- [Testing](#testing)

Intro
-----

A light framework designed to solve three common problems when writing JavaScript for web pages.

1. Initialization: Only executing JavaScript code when the relevant HTML is available on the page.
2. Isolation: Portions of code, especially event handlers, updating elements all over a given page.
3. Testability: Passing dependancies into the code to make it easy to stub when testing.

Setup
-----

All **m** requires to function is the *m.js* script included on the page after the [jQuery](http://jquery.com) and [Underscore](http://underscorejs.org) libraries. Then modules should be defined. Finally, the `m.module.initialize()` method should be called once everything is loaded, it might look something like this:

```html
<script src="vendor/jquery.js"></script>
<script src="vendor/underscore.js"></script>
<script src="vendor/m.js"></script>
<script src="modules/like-button.js"></script>
<script src="modules/comment-box.js"></script>
<script>
  // Initialize modules in the document.body element.
  m.module.initialize(document.body);
</script>
```

Modules
-------

The core part of **m** is creating modules. These can be thought of as distinct portions of a web page that are ideally responsible for one thing. Think a like button, a comment box, a popup menu etc.

A module can be defined using `m.module()`:

```js
m.module('like-button', {
  initialize: function () {
    this.el; // <div data-like-button />
  }
});
```

When an element with a `data-like-button` attribute is found on a page. An instance of the `like-button` module will be created and the element set to the `this.el` property (a jQuery wrapped `this.$el` is also available). The `initialize()` method is then called allowing you to set up the element with event listeners and other logic.

The API for a module is very similar to a [Backbone.View][#backbone] as it supports a subset of the methods such as `.el`, `.$el`, `.$()` and `.events`.

There are three guidelines to keep in mind when creating modules:

1. A module should primarily do one thing.
2. A module should not interact directly with any element outside of it's children.
3. A module should not interact directly with any other modules.

[#backbone]: http://backbonejs.org/#View

Sandboxes
---------

Each module is also given it's own sandbox, this is how it interacts with the rest of the page. By default the sandbox only has an event hub with `.publish()` and `.subscribe()` methods but it's also possible to add additional methods via the `m.sandbox.mixin()` API.

The idea is to keep all dependancies separate from the module and the global namespace by accessing them through the sandbox. This way a mock sandbox can be passed into a module for testing.

```js
// One module can trigger events that others react to.
m.module('like-button', {
  events: {click: '_onClick'}, // DOM events can be bound here.
  _onClick: function () {
    this.sandbox.publish('like');
  }
});

// A counter can update.
m.module('like-counter', {
  initialise: function () {
    this.sandbox.subscribe('like', this._onLike, this);
  },
  ...
  _onLike: function () {
    this.el.innerHTML = this.el.innerHTML + 1;
  }
});

// External library code can also listen to these events.
m.events.subscribe('like', function () {
  jQuery.post('/like');
});
```

__NOTE:__ A sandbox can also be created for testing by calling `m.sandbox()`.

### Extending the Sandbox

The sandbox should be extended to include site specific methods and helpers. Use this to do all your global DOM manipulation. A client for making http requests is also a good example:

```js
// Used to add methods to the Sandbox prototype. Don't add
// objects here they will be shared across all instances :)
m.sandbox.mixin({
  template: function (name) {
    return jQuery('[data-template-' + name + ']').html();
  },
  createElement: function (html) {
    return jQuery(html);
  }
});

// Called when a sandbox is created, receives the sandbox
// instance. Use this to add objects to the sandbox.
m.sandbox.setup(function (instance) {
  instance.client = new WebClient();
});
```

Check out *sandbox.js* for code, documentation and examples.
Working with Modules
--------------------

While modules are pretty basic in themselves, there are a few extra methods that extend them.

### Passing in options to modules

Data attributes can be added to elements following the style `#{module_name}-#{option_key}=#{option_value}`. These will be extracted from the element and set on the `this.options` property. Defaults can be provided by using the `.options()` method.

Hyphenated names will be converted to camelCase and JSON inside values will be evaluated allowing complex data structures to be passed in.

```html
<!-- html -->
<div data-truncate data-truncate-lines="5">...</div>
```

```js
// JavaScript
m.module('truncate', {
  initialize: function () {
    this.options.likes === 5;
  }
}).options({likes: 2});
```

See `ModuleFactory#extract()` in *module.js* for more documentation and examples.

### Events

DOM events such as click and key press handlers can easily be added by using the `.events` property. These follow the style `#{event} #{selector}: #{method}`. If no selector is provided the root module element (`this.el`) will be used.

```js
m.module('comment-field', {
  events: {
    'keypress textarea': '_onKeypress',
    'blur textarea': '_onBlur'
  },
  _onKeypress: function () {
    // `this` is scoped to the module.
  },
  _onBlur: function () {
  }
});
```

See `Module#delegateEvents()` in *module.js* for more documentation and examples.

### Deferred initialization

Sometimes an element doesn't need to do anything on a page until the user interacts with it. In these cases it's wasteful to use the `.initialize()` method to set the whole object up on page load.

The `.defer()` method can be used to wait until a DOM event is triggered before running the `.initialize()` code. A separate method `.run()` will be called each time the event is subsequently triggered.

```js
m.module('alert-button', {
  initialize: function () {
    // Put any expensive setup in here. It will be run once.
  },
  run: function (event) {
    // This will be run once per click. The event object is
    // the click event. prevetntDefault is called by default.
    alert('clicked');
  }
}).defer({on: 'click'});
```

See `ModuleFactory#defer()` in *module.js* for more documentation and examples.

### Mixins

If you find you have modules sharing a lot of the same code, you can use the `.mixin()` method to share it between modules.

```js
var toggle = {
  show: function () { this.$el.show(); },
  hide: function () { this.$el.hide(); },
  isVisible: function () { this.$el.is(':visible'); }
};

m.module('faq-entry', {
  events: {'click button': '_onToggle'},
  _onToggle: function () {
    this.isVisible() ? this.hide() : this.show();
  }
}).mixin(toggle);
```

### Event clean up

A module can be removed from the page at any time by calling the `.remove()` method. **m** manages DOM event handlers and sandbox subscriptions for you so you don't need to unbind these yourself. But should anything else need to be cleaned up this should be done in the `.teardown()` method.

```js
m.module('timer', {
  initialize: function () {
    this.timer = setInterval(this.runLots, 300);
  },
  teardown: function () {
    clearTimeout(this.timer);
  }
});
```

Debugging
---------

Sometimes it's often desirable to interact with a module when it's loaded on the page for debugging. The `m.module.lookup()` function will take an element and return all modules associated with it.

```js
// In the browser console the selected element === $0.
var modules = m.module.lookup($0); // [Module1, Module2]
var module  = m.module.lookup($0, 'toggle') // ToggleModule
module.show();
module.isVisible();
```

Testing
-------

To create an instance of a module for testing the following pattern can be used:

```js
// Find the module factory used to create instances.
var factory = m.module.find('like-button');

// Create an instance, the `force` flag ignores the cache.
var LikeButtonModule = factory.build({ force: true });

var instance = new LikeButtonModule({
  el: fixtureElement,
  sandbox: fixtureSandbox,
  option1: 'an option',
  option2: 'another option'
});
```


text:
declare class C {
    get foo(): typeof this.foo;
}


text:
import copy
import json
import re
from urllib.parse import unquote_plus

from svtplay_dl.error import ServiceError
from svtplay_dl.fetcher.http import HTTP
from svtplay_dl.service import OpenGraphThumbMixin
from svtplay_dl.service import Service

class Youplay(Service, OpenGraphThumbMixin):
    supported_domains = ["www.affarsvarlden.se"]

    def get(self):
        data = self.get_urldata()
        match = re.search(r'script async defer src="(//content.youplay.se[^"]+)"', data)
        if not match:
            yield ServiceError("Cant find video info for {}".format(self.url))
            return

        data = self.http.request("get", "http:{}".format(match.group(1)).content)
        match = re.search(r'decodeURIComponent\("([^"]+)"\)\)', data)
        if not match:
            yield ServiceError("Can't decode video info")
            return
        data = unquote_plus(match.group(1))
        match = re.search(r"videoData = ({[^;]+});", data)
        if not match:
            yield ServiceError("Cant find video info for {}".format(self.url))
            return
        # fix broken json.
        regex = re.compile(r"\s(\w+):")
        data = regex.sub(r"'\1':", match.group(1))
        data = data.replace("'", '"')
        j = re.sub(r"{\s*(\w)", r'{"\1', data)
        j = j.replace("\n", "")
        j = re.sub(r'",\s*}', '"}', j)
        jsondata = json.loads(j)
        for i in jsondata["episode"]["sources"]:
            match = re.search(r"mp4_(\d+)", i)
            if match:
                yield HTTP(copy.copy(self.config), jsondata["episode"]["sources"][i], match.group(1), output=self.output)


text:
using System;
using System.Collections.Generic;
using Our.Umbraco.NestedContent.Extensions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;

namespace Our.Umbraco.NestedContent.Converters
{
    public class NestedContentValueConverter : PropertyValueConverterBase, IPropertyValueConverterMeta
    {
        public override bool IsConverter(PublishedPropertyType propertyType)
        {
            return propertyType.IsNestedContentProperty() && !propertyType.IsSingleNestedContentProperty();
        }

        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            try
            {
                return propertyType.ConvertPropertyToNestedContent(source, preview);
            }
            catch (Exception e)
            {
                LogHelper.Error<NestedContentValueConverter>("Error converting value", e);
            }

            return null;
        }

        public virtual Type GetPropertyValueType(PublishedPropertyType propertyType)
        {
            return typeof (IEnumerable<IPublishedContent>);
        }

        public virtual PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType, PropertyCacheValue cacheValue)
        {
            return PropertyCacheLevel.Content;
        }
    }
}


text:
```shell
docker build -t hub.opshub.sh/containerops/dependence-nodejs-jscs:latest .
```

## Run

```shell
docker run --env CO_DATA="git_url=https://github.com/spyl94/react-brunch-demo.git path=brunch-config.js preset=airbnb" hub.opshub.sh/containerops/dependence-nodejs-jscs:latest
```

## Options

Required:

- git-url
- path
- preset


text:
package com.cl.xlp.core.impl.common.crypt;

import org.junit.Assert;
import org.junit.Test;

public class ConfigurableCipherFactoryTest {

    @Test
    public void testConfiguration() {
        ConfigurableCipherFactory f = new ConfigurableCipherFactory();
        f.setAlgorithm("alg");
        f.setPadding("pad");
        Assert.assertEquals("alg", f.getAlgorithm());
        Assert.assertEquals("pad", f.getPadding());
    }

}


text:
#ifndef DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H
#define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H

// INTERNAL INCLUDES
#include <dali/internal/imaging/common/native-image-source-factory.h>

namespace Dali
{
namespace Internal
{
namespace Adaptor
{
class NativeImageSourceFactoryX : public NativeImageSourceFactory
{
public:
  std::unique_ptr<NativeImageSource> CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) override;

  std::unique_ptr<NativeImageSourceQueue> CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorFormat colorFormat, Any nativeImageSourceQueue) override;
};

} // namespace Adaptor
} // namespace Internal
} // namespace Dali

#endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H


text:
<?php

namespace Iluminar\Fluent\Core;

use Illuminate\Support\Facades\Auth;

class Fluent
{
    public $user;

    public function __construct()
    {
        $this->user = Auth::user();
    }

    public function __call($method, $parameters)
    {
        return $this->createClass($method, $parameters[0]);
    }

    public function createClass($name, $params)
    {
        return NodeFactory::create($name, [$this->user->token, $params]);
    }
}