text:
@implementation HLURLDataSource

@synthesize context=context_;
@synthesize responseData=responseData_;

+ (HLURLDataSource *) postToURL: (NSURL *)url
                       withBody: (NSString *)body
{
    return [[[HLURLDataSource alloc] initWithContext: [NSDictionary dictionaryWithObjectsAndKeys:
                                                       @"POST", @"requestMethod",
                                                       url, @"requestURL",
                                                       body, @"requestBody", nil]] autorelease];
}

- (id) initWithContext: (NSDictionary *)aContext
{
    self = [super init];
    if (self) {
        conn_ = nil;
        response_ = nil;
        responseData_ = nil;
        context_ = [aContext retain];
    }
    return self;
}

- (id) initWithURL: (NSURL *)url
{
	self = [self initWithContext: [NSDictionary dictionaryWithObject: url forKey: @"requestURL"]];
	return self;
}

- (id) initWithURLString: (NSString *)urlString
{
	self = [self initWithContext: [NSDictionary dictionaryWithObject: urlString forKey: @"requestURL"]];
	return self;
}

- (void) dealloc
{
    [conn_ release]; conn_ = nil;
    [response_ release]; response_ = nil;
    [responseData_ release]; responseData_ = nil;
    [context_ release]; context_ = nil;
    [super dealloc];
}

#pragma mark -
#pragma mark Public API: template methods, override these to customize behaviour

- (NSMutableURLRequest *) urlRequest
{
    NSMutableURLRequest *result = nil;
    id requestURL = [context_ objectForKey: @"requestURL"];
    if (requestURL) {
        if ([requestURL isKindOfClass: [NSString class]]) {
            requestURL = [NSURL URLWithString: requestURL];
        }
        result = [NSMutableURLRequest requestWithURL: requestURL
                                         cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
                                     timeoutInterval: 240.0];
        // allow response to be gzip compressed
        [result setValue: @"gzip" forHTTPHeaderField: @"Accept-Encoding"];
        NSString *requestMethod = [context_ objectForKey: @"requestMethod"];
        [result setHTTPMethod: requestMethod ? requestMethod : @"GET"];
        NSData *requestBody = [context_ objectForKey: @"requestBody"];
        if (requestBody) {
            [result setHTTPBody: requestBody];
            [result setValue: [NSString stringWithFormat: @"%d", [requestBody length]] forHTTPHeaderField: @"Content-Length"];
        }
        NSString *requestBodyContentType = [context_ objectForKey: @"requestBodyContentType"];
        if (requestBodyContentType) [result setValue: requestBodyContentType forHTTPHeaderField: @"content-type"];
        NSString *lastModified = [context_ objectForKey: @"requestIfModifiedSince"];
		if (lastModified) [result setValue: lastModified forHTTPHeaderField: @"If-Modified-Since"];
    }
    return result;
}

- (void) execute
{
	[conn_ release];
    conn_ = [[NSURLConnection alloc] initWithRequest: [self urlRequest]
                                            delegate: self];
}

- (void) cancelOnRunLoopThread
{
    [conn_ cancel];
    [super cancelOnRunLoopThread];
}

- (void) responseFailed
{
    [self asyncCompleteOperationError];
}

- (BOOL) responseBegan
{
    BOOL result = NO;
    if ([response_ isKindOfClass: [NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response_;
		NSInteger statusCode = [httpResponse statusCode];
        if ((statusCode >= 200) && (statusCode < 300)) {
			[responseData_ release];
            responseData_ = [[NSMutableData alloc] init]; // YAY!
            result = YES;
        }
    } else {
		[responseData_ release];
        responseData_ = [[NSMutableData alloc] init]; // YAY!
        result = YES;
    }
    return result;
}

- (void) responseReceivedData: (NSData *)data
{
    if (responseData_) {
        [responseData_ appendData: data];
    }
}

- (void) responseFinished
{
	[self asyncCompleteOperationResult];
}

#pragma mark -
#pragma mark Private API

- (void) connection: (NSURLConnection *)connection didFailWithError: (NSError *)anError
{
    [self setError: anError];
    [self responseFailed];
}

- (void) connection: (NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)aResponse
{
	[response_ release];
    response_ = [aResponse retain];
    [self responseBegan];
}

- (void) connection: (NSURLConnection *)connection didReceiveData: (NSData *)data
{
    [self responseReceivedData: data];
}

- (void) connectionDidFinishLoading: (NSURLConnection *)connection
{
    [self setResult: responseData_];
    [self responseFinished];
}

#pragma mark -
#pragma mark Public API

- (NSString *) responseHeaderValueForKey: (NSString *)key
{
    if ([response_ isKindOfClass: [NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *r = (NSHTTPURLResponse *)response_;
        return [[r allHeaderFields] objectForKey: key];
    }
    return nil;
}

- (NSInteger) responseStatusCode
{
    NSInteger result = 0;
    if ([response_ isKindOfClass: [NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response_;
        result = [httpResponse statusCode];
    }
    return result;
}

- (BOOL) entityWasOK
{
    return [self responseStatusCode] == 200;
}

- (BOOL) entityWasNotModified
{
    return [self responseStatusCode] == 304;
}

- (BOOL) entityWasNotFound
{
    return [self responseStatusCode] == 404;
}

@end


text:
package com.netflix.spectator.api;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

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

@RunWith(JUnit4.class)
public class NoopDynamicIdTest {
  @Test
  public void testTags() {
    Assert.assertFalse(NoopDynamicId.INSTANCE.tags().iterator().hasNext());
  }

  @Test
  public void testWithKeyValueTag() {
    Assert.assertSame(NoopDynamicId.INSTANCE.withTag("k", "v"), NoopDynamicId.INSTANCE);
  }

  @Test
  public void testWithTag() {
    Assert.assertSame(NoopDynamicId.INSTANCE.withTag(new TagList("k", "v")), NoopDynamicId.INSTANCE);
  }

  @Test
  public void testWithTags() {
    Assert.assertSame(NoopDynamicId.INSTANCE.withTags(new TagList("k", "v")), NoopDynamicId.INSTANCE);
  }

  @Test
  public void testWithTagsMap() {
    Map<String, String> tags = new HashMap<>();

    tags.put("key", "value");
    Assert.assertSame(NoopDynamicId.INSTANCE.withTags(tags), NoopDynamicId.INSTANCE);
  }

  @Test
  public void testWithTagFactory() {
    Assert.assertSame(NoopDynamicId.INSTANCE.withTagFactory(new ConstantTagFactory("k", "v")), NoopDynamicId.INSTANCE);
  }

  @Test
  public void testWithTagFactories() {
    Assert.assertSame(NoopDynamicId.INSTANCE.withTagFactories(Arrays.asList(new ConstantTagFactory("k", "v"))), NoopDynamicId.INSTANCE);
  }

  @Test
  public void testResolveToId() {
    Assert.assertSame(NoopId.INSTANCE, NoopDynamicId.INSTANCE.resolveToId());
  }

  @Test
  public void testToString() {
    Assert.assertEquals(NoopDynamicId.INSTANCE.toString(), "noop");
  }
}

redpajama_set_name: RedPajamaGithub


text:
@interface UIColor (FFMoreColors)

+ (UIColor *)lighterGrayCustom;
+ (UIColor *)lightGrayCustom;

@end


text:
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.utils import six
from django.db.models import Model
from django.db import IntegrityError

from random import randrange

from fuzzy import ast, sym_eq, sym_not, sym_or, sym_and, sym_gt, sym_lt, concolic_int

import fuzzy
import traceback
import base64
import string

class SymMixin():
  def _old_get(self, cls, *args, **kwargs):
    return super(cls, self).get(*args, **kwargs)

# SymQuerySet that creates concolic variables from DB object fields. Example:
# - user = User.objects.get(username='alice') will return an object
# where user.person.zoobars and the other fields are concolic
# - z3 solves constraints and finds concrete values to test
# - Concrete values are then included in the query:
#   user = User.objects.get(username='alice', person.zoobars=1)
# - If no such user exists, create it
# This makes it possible to test branches that would not otherwise be covered
# when there are no objects in the DB with the required fields. But it makes it
# more difficult to test invariants since the DB will change
class SQLSymQuerySet(QuerySet, SymMixin):
  cache = {},
  _id = 0

  def get(self, *args, **kwargs):
    import django.contrib.sessions.models
    if self.model is django.contrib.sessions.models.Session or len(kwargs) != 1:
      return self._old_get(SQLSymQuerySet, *args, **kwargs)

    # If this query has already been called, some or all of its object's
    # properties may be symbolic and have constraints
    query_id = self._create_query_id()

    # Get any concrete values that are available for this query
    index = len(query_id)
    concrete = {}
    for id in fuzzy.concrete_values:
      if not id.startswith(query_id):
        continue

      concrete[id[index:]] = fuzzy.concrete_values[id]

    if len(concrete) > 0:
      for field in concrete:
        kwargs[field] = concrete[field]

    unique = self._get_unique_fields()

    try:
      obj = self._old_get(SQLSymQuerySet, *args, **kwargs)
    except self.model.DoesNotExist:
      # Django does not allow empty strings in 'unique' fields
      for field in unique:
        if field.name in kwargs and kwargs[field.name] == '':
          raise self.model.DoesNotExist()

      # If searching by primary key and a row exists, update the row
      # to avoid errors with duplicate primary keys
      obj = None
      for field in unique:
        if field.name in kwargs:
          newkwargs = {field.name: kwargs[field.name]}
          try:
            obj = self._old_get(SQLSymQuerySet, *args, **newkwargs)
            break
          except self.model.DoesNotExist:
            pass

      if obj is None:
        obj = self.model()
        setattr(obj, self.model._meta.pk.name, hash(str(self._id)))
        self._id = self._id + 1
        obj.save()

      for arg in kwargs:
        if arg != self.model._meta.pk.name:
          obj = self._set_attr(obj, arg, kwargs[arg])

      try:
        obj.save()
        print obj
        print self.all()
      except IntegrityError:
        raise self.model.DoesNotExist()

    obj = self._make_fields_concolic(query_id, obj)
    return obj

  def _set_attr(self, obj, key, value):
    if not isinstance(key, str) or not '__' in key:
      setattr(obj, key, value)
      return obj

    keys = str.split(key, '__', 1)
    setattr(obj, keys[0], self._set_attr(getattr(obj, keys[0]), keys[1], value))
    return obj

  def _get_unique_fields(self):
    return [f for f in self.model._meta.fields if f.unique]

  def _make_fields_concolic(self, query_id, obj, blacklist = set(), prefix = ''):
    blacklist.add('_' + type(obj)._meta.model_name + '_cache')
    for prop in vars(obj):
      # Ignore private fields
      if (prop.startswith('_') and not prop.endswith('_cache')) or prop in blacklist:
        continue

      value = getattr(obj, prop)
      if isinstance(value, fuzzy.concolic_int) or isinstance(value, fuzzy.concolic_str):
        continue

      if hasattr(value, '__dict__'):
        setattr(obj, prop, self._make_fields_concolic(query_id, value, blacklist, type(value)._meta.model_name))

      if isinstance(value, int):
        setattr(obj, prop, fuzzy.mk_int(query_id + prefix + '__' + prop, value))
      elif isinstance(value, str) or isinstance(value, unicode):
        setattr(obj, prop, fuzzy.mk_str(query_id + prefix + '__' + prop, value))

    return obj

  # Each SymQuerySet has a unique ID based on where it was created (i.e. call
  # stack contents when it was created)
  def _create_query_id(self):
    return base64.b64encode(str(hash(''.join(traceback.format_stack()))))

  # If the query returns DoesNotExist, then it is probably the case that we are
  # looking up the DB with an empty key (e.g. at the beginning of testing when
  # 'username' has a default value of ''), so we create a synthetic branch to
  # ensure that on a subsequent iteration we actually get a real object
  def _create_synthetic_branch(self, **kwargs):
    obj = self._get_random_object()
    for obj in self.model.objects.all():
      if len(kwargs) == 1:
        key = kwargs.keys()[0]

        if key == 'pk':
          key = self.model._meta.pk.name
          kwargs[key] = kwargs['pk']
          del kwargs['pk']

        value = kwargs[key]

        if isinstance(value, Model) and hasattr(value, key):
          value = getattr(value, key)

        if getattr(obj, key) == value:
          pass

  def _get_random_object(self):
    return self.model.objects.all()[randrange(self.count())]

  def _exists(self, query_id):
    return query_id in self.cache

  def _add_query_constraints(self):
    pass

# SymQuerySet that just iterates through every row in the DB
class AllSymQuerySet(QuerySet, SymMixin):
  def _convert_pk(self, **kwargs):
    for key in kwargs:
      if key != 'pk':
        continue

      newkey = self.model._meta.pk.name
      kwargs[newkey] = kwargs['pk']
      del kwargs['pk']

    return kwargs

  def _is_match(self, real, obj, **kwargs):
    for key in kwargs:
      value = kwargs[key]

      lookups, parts, reffed_aggregate = self.query.solve_lookup_type(key)

      self._create_branch(value, obj, lookups, parts)

    if obj == real:
      return True

    return False

  def _create_branch(self, value, obj, lookup, props):
    if len(lookup) != 1:
      return

    obj_attr = self._get_attr(obj, props)

    op = lookup[0]
    if op == 'gt' and obj_attr > value:
      pass
    if op == 'gte' and obj_attr >= value:
      pass
    if op == 'lt' and obj_attr < value:
      pass
    if op == 'lte' and obj_attr <= value:
      pass
    if op == 'exact' and obj_attr == value:
      pass

  def _get_attr(self, obj, props):
    result = obj
    for prop in props:
      if hasattr(obj, prop):
        result = getattr(obj, prop)
    return result

  def get(self, *args, **kwargs):
    import django.contrib.sessions.models
    if self.model is django.contrib.sessions.models.Session:
      return self._old_get(AllSymQuerySet, *args, **kwargs)

    kwargs = self._convert_pk(**kwargs)

    real = None
    try:
      real = self._old_get(AllSymQuerySet, *args, **kwargs)
    except self.model.DoesNotExist:
      pass

    for m in self.model.objects.all():
      if self._is_match(real, m, **kwargs):
        return m

    return self._old_get(AllSymQuerySet, *args, **kwargs)

# SymQuerySet that creates mutations based on ConSMutate
class MutationSymQuerySet(AllSymQuerySet, SymMixin):
  operators = ['lte', 'gte', 'gt', 'lt', 'exact']
  condition_cache = set()

  def filter(self, *args, **kwargs):
    (op, value, mutations) = self._mutate(*args, **kwargs)

    actual = self._apply_filter(*args, **kwargs)
    if not isinstance(value, concolic_int):
      return actual

    mutations = self._remove_dead_mutations(actual, mutations)
    self._create_constraints(op, value, mutations)
    return actual

  def _apply_filter(self, *args, **kwargs):
    from django.core.exceptions import FieldError
    try:
      return super(MutationSymQuerySet, self).filter(*args, **kwargs)
    except FieldError:
      return None

  #
  # Based on ConSMutate: SQL mutants for guiding concolic testing of database
  # applications (T. Sarkar, S. Basu, and J.S. Wong, 2012)
  #
  # Mutate the current queryset when it is filtered
  #
  # Suppose the filter is Transfer.objects.filter(zoobars__gt=10) (all
  # transfers of more than 10 zoobars)
  #
  # 1. Split the input string: filter_column = zoobars, operator = gt,
  # filter_value = 10
  # 2. Create possible mutations:
  #   i. Create mutated querysets by varying the 'operator', e.g. create
  #      querysets with operator = 'lt' (less than), 'gte' (greater than or
  #      equal), etc.
  #   ii.Should end up with several mutations: e.g.
  #      Transfer.objects.filter(zoobars__lt=10),
  #      Transfer.objects.filter(zoobars__gte=10), etc.
  # 3. Run original filter
  # 4. For each mutation:
  #   i. Run it and compare with original
  #   ii.If result is different (called 'dead' mutations in the paper): discard
  #   iii.If result is the same: Add the symmetric difference of the original
  #       and the mutation to the path constraints
  #
  def _mutate(self, *args, **kwargs):
    mutations = {}
    for arg in kwargs:
      lookups, parts, reffed_aggregate = self.query.solve_lookup_type(arg)

      if len(lookups) != 1:
        continue

      mutated_filters = {}
      operator = lookups[0]
      filter_column = '_'.join(parts)
      filter_value = kwargs[arg]

      mutate_operators = [op for op in self.operators if op != operator]
      for op in mutate_operators:
        mutated_filters[op] = {filter_column + '__' + op: filter_value}

      # TODO: currently only handles filters with single column queries
      # e.g. username='alice'. Ideally, this would handle filters over
      # multiple columns e.g. find the transfers of more than 10 zoobars
      # to alice recipient='alice' && zoobars > 10
      #break
      return (operator, filter_value, self._create_mutated_querysets(mutated_filters, *args))

    #mutations.append(mutation_set)

    return mutations

  def _create_mutated_querysets(self, mutated_filters, *args):
    mutations = {}
    for op in mutated_filters:
      filter_kv = mutated_filters[op]
      mutated_queryset = self._apply_filter(*args, **filter_kv)
      mutations[op] = mutated_queryset
    return mutations

  def _remove_dead_mutations(self, original_queryset, mutations):
    unique_mutations = {}
    items = list(six.moves.map(repr, original_queryset))
    for op in mutations:
      mutation = mutations[op]
      if self._is_equal(items, mutation):
        unique_mutations[op] = mutation
    return unique_mutations

  def _is_equal(self, values, other_queryset):
    items = list(six.moves.map(repr, other_queryset))
    return items == values

  def _create_constraints(self, original_op, sym, mutations):
    original = self._create_condition(original_op, sym)
    t_original = sym_eq(original, ast(True))
    f_original = sym_eq(original, ast(False))

    for op in mutations:
      mutant = self._create_condition(op, sym)
      if mutant is None:
        return None

      t_mutant = sym_eq(mutant, ast(True))
      f_mutant = sym_eq(mutant, ast(False))

      condition = sym_not(sym_or(sym_and(t_original, f_mutant), sym_and(f_original, t_mutant)))

      if self._in_cache(condition):
        continue

      fuzzy.cur_path_constr = []
      fuzzy.cur_path_constr_callers = []
      fuzzy.add_constr(sym_and(sym_not(fuzzy.path_condition), condition))
      self._add_to_cache(condition)
      return

  def _hash_condition(self, condition):
    return str(condition)

  def _add_to_cache(self, condition):
    return self.condition_cache.add(self._hash_condition(condition))

  def _in_cache(self, condition):
    return self._hash_condition(condition) in self.condition_cache

  def _create_condition(self, op, sym):
    sym_type = None

    if op == 'gt':
      sym_type = sym_gt
    elif op == 'lt':
      sym_type = sym_lt
    elif op == 'exact':
      sym_type = sym_eq
    elif op == 'gte':
      sym_type = sym_gte
    elif op == 'lte':
      sym_type = sym_lte

    if sym_type is None:
      return None

    return sym_type(ast(sym), ast(sym.concrete_value()))

class SymManager(Manager, SymMixin):
  def __init__(self, manager, queryset_cls):
    self.manager = manager
    self.queryset_cls = queryset_cls

  def __getattr__(self, attr):
    #print 'getattr' + attr
    return getattr(self.manager, attr)

  def get_queryset(self):
    #import pdb; pdb.set_trace()
    if self.queryset_cls == AllSymQuerySet:
      return AllSymQuerySet(self.model, using=self._db, hints=self._hints)

    if self.queryset_cls == SQLSymQuerySet:
      return SQLSymQuerySet(self.model, using=self._db, hints=self._hints)

    if self.queryset_cls == MutationSymQuerySet:
      return MutationSymQuerySet(self.model, using=self._db, hints=self._hints)

    print 'No SymQuerySet selected'
    return QuerySet(self.model, using=self._db, hints=self._hints)


text:
<?php

namespace frontend\controllers;

use source\core\base\BaseController;
use source\LuLu;
use source\models\Content;

class BaseContentController extends BaseController
{
    //首页页面大小
    public $pageSize_index = 10;

    //内容类型
    public $content_type;

    //内容body的class
    public $bodyClass;

    /**
     * 首页
     * @return string
     */
    public function actionIndex() {
        $query = Content::find()->published()->andWhere(['content_type' => $this->content_type]);

        $locals = LuLu::getPagedRows($query, [
            'orderBy' => 'created_at desc', 'pageSize' => $this->pageSize_index,
        ]);

        return $this->render('index_default', $locals);
    }

    /**
     * 列表页
     * @param integer $taxonomy
     * @return string
     */
    public function actionList($taxonomy = -1) {
        $query = Content::find()->published()->andWhere(['content_type' => $this->content_type]);
        if (intval($taxonomy) > 0) {
            $query->andFilterWhere(['taxonomy_id' => intval($taxonomy)]);
        }

        $taxonomyModel = app()->taxonomy->getTaxonomyById($taxonomy);
        LuLu::setViewParam(['taxonomyModel' => $taxonomyModel]);

        $vars = $this->getListVars($taxonomyModel);

        $locals = LuLu::getPagedRows($query, [
            'orderBy' => 'created_at desc', 'pageSize' => $vars['pageSize'],
        ]);
        $locals['taxonomyModel'] = $taxonomyModel;

        $this->layout = $vars['layout'];

        return $this->render($vars['view'], $locals);
    }

    /**
     * 内容页
     * @param $id
     * @return string
     */
    public function actionDetail($id) {
        Content::updateAllCounters(['view_count' => 1], ['id' => $id]);

        $locals = $this->getDetail($id);

        $taxonomyModel = app()->taxonomy->getTaxonomyById($locals['model']['taxonomy_id']);
        LuLu::setViewParam(['taxonomyModel' => $taxonomyModel]);

        $locals['taxonomyModel'] = $taxonomyModel;

        $vars = $this->getDetailVars($locals['taxonomyModel'], $locals['model']);

        $this->layout = $vars['layout'];

        return $this->render($vars['view'], $locals);
    }

    public function getDetail($id) {
        $model = Content::find()->with(['body'])->where(['id'=>$id])->one();
        $array = $model->toArray();
        if($model->body){
            $array['created_at'] = $model->createdAt;
            $array['updated_at'] = $model->updatedAt;
            $array['body_id'] = $model->body->id;
            $array['body_content_id'] = $model->body->content_id;
            $array['body_body'] = $model->body->body;
        }

        return [
            'model' => $array,
        ];
    }

    /**
     *
     * @param array $taxonomyModel
     * @return array ['view','layout','pageSize]
     */
    public function getListVars($taxonomyModel) {
        $vars = [];

        $vars['view'] = empty($taxonomyModel['list_view']) ? 'list_default' : $taxonomyModel['list_view'];
        $vars['layout'] = empty($taxonomyModel['list_layout']) ? NULL : $taxonomyModel['list_layout'];
        $vars['pageSize'] = empty($taxonomyModel['page_size']) ? 10 : $taxonomyModel['page_size'];

        return $vars;
    }

    /**
     *
     * @param array $taxonomyModel
     * @param array $detailModel
     * @return array ['view','layout']
     */
    public function getDetailVars($taxonomyModel, $detailModel) {
        $vars = [];

        if (!empty($detailModel['view'])) {
            $vars['view'] = $detailModel['view'];
        } else {
            $vars['view'] = empty($taxonomyModel['detail_view']) ? 'detail_default' : $taxonomyModel['detail_view'];
        }

        if (!empty($detailModel['layout'])) {
            $vars['layout'] = $detailModel['layout'];
        } else {
            $vars['layout'] = empty($taxonomyModel['detail_layout']) ? NULL : $taxonomyModel['detail_layout'];
        }

        return $vars;
    }
}


text:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import

import tempfile

from scalyr_agent import compat
from tests.utils.compat import Path

import six
from io import open

TEMP_PREFIX = "scalyr-test-"

def get_env(name):
    try:
        return compat.os_environ_unicode[name]
    except KeyError:
        raise KeyError("Environment variable: '{0}' not set.".format(name))

def create_tmp_directory(suffix=""):
    # type: (six.text_type) -> Path
    path = Path(tempfile.mkdtemp(prefix=TEMP_PREFIX, suffix="-" + suffix))
    return path

def create_tmp_file(suffix=""):
    # type: (six.text_type) -> Path
    tmp_file = tempfile.NamedTemporaryFile(prefix=TEMP_PREFIX, suffix="-" + suffix)
    tmp_file.close()
    return Path(tmp_file.name)

def get_shebang_from_file(file_path):
    # type: (six.text_type) -> six.text_type
    """
    Return shebang (first line) from a specific file path.
    """
    with open(file_path, "r") as fp:
        shebang_line = fp.readline().strip()

    return shebang_line


text:
"""
This module implements a Monte-Carlo Tree Search (MCTS), enriched with UCB1 and
 techniques from PROST to handle stochastic effects of actions (notably, from sparse UCT).

Intuitively, MCTS works by (1) selecting a node to expand, (2) expanding the node,
 (3) simulating one of the rollouts from that node to a final state/horizon limit, and
 (4) backpropagating the results to guide the search in selecting the next node.

Intuitively, UCB1 works by balancing the exploration/exploitation tradeoff.
 It minimises regret by ensuring that we do explore less promising branches
 to ensure we don't miss out, while ensuring that we sufficiently explore
 more promising branches to achieve the best possible results.

Intuitively, PROST works by dividing the tree in layers, where one of the
 alternating layers consists of states, in which we can select the next action
 to take, and the other layer consists of actions, from which we transition to
 other states pending on the stochastic effect that occurs (which affects (3-4)).
"""
import logging as log
from random import choice
from collections import namedtuple
from search_structure import Node

__author__ = "Kim Bauters"

# provide a named tuple for easy access to all information relevant to available actions after the search finishes
ActInfo = namedtuple('ActInfo', 'action reward visits')

def mcts(root_state, problem, budget, horizon,
         select_action=lambda node: choice(list(node.tried_actions.keys())),
         expand_action=lambda node: choice(node.untried_actions),
         rollout_action=lambda node: choice(node.untried_actions),
         select_best=lambda acts: sorted(acts, key=lambda act: act.reward/act.visits, reverse=True)[0].action,
         *, discounting=0.9, verbose=False, graphviz=False):
    """
    :param root_state: the initial state from which to start the search
    :param problem: a description of the problem in the form of a Problem instance data structure
    :param budget: a function that is called after each cycle to determine
                     whether we should stop (return False) or continue (return True)
    :param horizon: the maximum depth up to which to explore the search tree
    :param select_action:  heuristic used to select an action during step 1 of each MCTS iteration
                           the function should select one argument, which is a list of actions we already tried
    :param expand_action:  heuristic used to select an action to expand to a new node during step 2 of an MCTS iteration
                           the function should accept two arguments: the current node and the untried actions
    :param rollout_action: heuristic used to select which action to simulate during each step of the rollout phase
    :param discounting: can only be given as named parameter; alters the default discounting value
    :param verbose: can only be given as named parameter; provides (very) verbose output while searching
    :param graphviz: can only be given as named parameter; return the DOT graphviz contents associated with the search
    :return: the next best action to take
    """

    log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG if verbose else log.ERROR)
    root = Node(problem, None, None, None, root_state)  # each episode starts from the root node
    iterations = 0  # so far, no iterations as we still have to start

    while budget(iterations):  # continue exploring for as long as we have the computational budget

        node = root  # the node to start from is the root node
        depth = 1  # we are at the start, so a depth of 1

        # (1) select: descend through the search tree to find a node to expand
        log.info("Monte-Carlo Tree Search iteration starting from " + str(node.state))
        log.info("  step (1): selecting node")

        # find a node with untried actions by recursing through the children
        while not node.untried_actions and node.children and depth <= horizon:
            action = select_action(node)  # use heuristics to select the best action to follow
            log.info("  -> " + action.name)
            node = node.simulate_action(action)  # simulate the action to determine its stochastic outcome
            depth += 1
        # stop once we find a node with untried actions, or when the node does not have any children
        log.info("  selected node with the state " + str(node.state))

        # (2) expand: expand the node we just found
        log.info("  step (2): expanding node on depth " + str(depth))
        # check that the node we ended up with has actions we still have to try
        if node.untried_actions and depth <= horizon and not node.is_goal:
            action = expand_action(node)  # use heuristics to pick one of the actions to try
            log.info("  -> " + action.name)
            node = node.perform_action(action)  # execute this action; set the node to the generated child
            log.info("  the new state became " + str(node.state))
            depth += 1

        # (3) rollout: simulate a full run from the expanded node
        log.info("  step (3): performing rollout")
        # perform a rollout from the current node; return final node, and total descend depth
        node, depth = node.rollout_actions(rollout_action, depth, horizon)
        log.info("  ended up in the state " + str(node.state))

        # (4) backpropagate: update the search tree to reflect the results from the rollout
        log.info("  step (4): backpropagating from depth " + str(depth) + " with " +
                 ("success" if node.is_goal else "no success"))

        node.update(discounting)  # perform the update of the values

        iterations += 1

    log.info("search completed\n")
    if graphviz:
        location = root.create_graphviz()
        print("The Graphviz DOT file has been saved in " + str(location) + ".")

    # collect all the actions available in the root along with any information used for choosing
    actions = [ActInfo(action, reward, visits) for
               action, (reward, visits) in root.tried_actions.items()]

    return select_best(actions)


text:
Game
====
This is a game. It is currently being developed.


text:
package ru.histone.v2.evaluator.node;

import ru.histone.v2.rtti.HistoneType;

/**
 * @author Alexey Nevinsky
 */
public class LongEvalNode extends EvalNode<Long> {
    public LongEvalNode(Integer value) {
        this(value.longValue());
    }

    public LongEvalNode(Long value) {
        super(value);
        if (value == null) {
            throw new NullPointerException();
        }
    }

    @Override
    public HistoneType getType() {
        return HistoneType.T_NUMBER;
    }
}


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

namespace Plugin.BLE.Abstractions.Contracts
{
    /// <summary>
    /// A bluetooth LE device.
    /// </summary>
    public interface IDevice : IDisposable
    {
        /// <summary>
        /// Id of the device.
        /// </summary>
        Guid Id { get; }

        /// <summary>
        /// Advertised Name of the Device.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Last known rssi value in decibals.
        /// Can be updated via <see cref="UpdateRssiAsync()"/>.
        /// </summary>
        int Rssi { get; }

        /// <summary>
        /// Gets the native device object reference. Should be cast to the
        /// appropriate type on each platform.
        /// </summary>
        /// <value>The native device.</value>
        object NativeDevice { get; }

        /// <summary>
        /// State of the device.
        /// </summary>
        DeviceState State { get; }

        /// <summary>
        /// All the advertisment records
        /// For example:
        /// - Advertised Service UUIDS
        /// - Manufacturer Specifc data
        /// - ...
        /// </summary>
        IList<AdvertisementRecord> AdvertisementRecords { get; }

        /// <summary>
        /// Gets all services of the device.
        /// </summary>
        /// <returns>A task that represents the asynchronous read operation. The Result property will contain a list of all available services.</returns>
        Task<IList<IService>> GetServicesAsync();

        /// <summary>
        /// Gets the first service with the Id <paramref name="id"/>.
        /// </summary>
        /// <param name="id">The id of the searched service.</param>
        /// <returns>
        /// A task that represents the asynchronous read operation.
        /// The Result property will contain the service with the specified <paramref name="id"/>.
        /// If the service doesn't exist, the Result will be null.
        /// </returns>
        Task<IService> GetServiceAsync(Guid id);

        /// <summary>
        /// Updates the rssi value.
        ///
        /// Important:
        /// On Android: This function will only work if the device is connected. The Rssi value will be determined once on the discovery of the device.
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous read operation. The Result property will contain a boolean that inticates if the update was successful.
        /// The Task will finish after Rssi has been updated.
        /// </returns>
        Task<bool> UpdateRssiAsync();

        /// <summary>
        /// Requests a MTU update and fires an "Exchange MTU Request" on the ble stack. Be aware that the resulting MTU value will be negotiated between master and slave using your requested value for the negotiation.
        ///
        /// Important:
        /// On Android: This function will only work with API level 21 and higher. Other API level will get an default value as function result.
        /// On iOS: Requesting MTU sizes is not supported by iOS. The function will return the current negotiated MTU between master / slave.
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation. The result contains the negotiated MTU size between master and slave</returns>
        /// <param name="requestValue">The requested MTU</param>
        Task<int> RequestMtuAsync(int requestValue);
    }
}


text:
#ifndef _ASM_X86_PCI_H
#define _ASM_X86_PCI_H

#include <linux/mm.h> /* for struct page */
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <asm/scatterlist.h>
#include <asm/io.h>
#include <asm/x86_init.h>

#ifdef __KERNEL__

struct pci_sysdata {
	int		domain;		/* PCI domain */
	int		node;		/* NUMA node */
#ifdef CONFIG_X86_64
	void		*iommu;		/* IOMMU private data */
#endif
};

extern int pci_routeirq;
extern int noioapicquirk;
extern int noioapicreroute;

/* scan a bus after allocating a pci_sysdata for it */
extern struct pci_bus *pci_scan_bus_on_node(int busno, struct pci_ops *ops,
					    int node);
extern struct pci_bus *pci_scan_bus_with_sysdata(int busno);

#ifdef CONFIG_PCI

#ifdef CONFIG_PCI_DOMAINS
static inline int pci_domain_nr(struct pci_bus *bus)
{
	struct pci_sysdata *sd = bus->sysdata;
	return sd->domain;
}

static inline int pci_proc_domain(struct pci_bus *bus)
{
	return pci_domain_nr(bus);
}
#endif

/* Can be used to override the logic in pci_scan_bus for skipping
   already-configured bus numbers - to be used for buggy BIOSes
   or architectures with incomplete PCI setup by the loader */

extern unsigned int pcibios_assign_all_busses(void);
extern int pci_legacy_init(void);
# ifdef CONFIG_ACPI
#  define x86_default_pci_init pci_acpi_init
# else
#  define x86_default_pci_init pci_legacy_init
# endif
#else
# define pcibios_assign_all_busses()	0
# define x86_default_pci_init		NULL
#endif

extern unsigned long pci_mem_start;
#define PCIBIOS_MIN_IO		0x1000
#define PCIBIOS_MIN_MEM		(pci_mem_start)

#define PCIBIOS_MIN_CARDBUS_IO	0x4000

extern int pcibios_enabled;
void pcibios_config_init(void);
struct pci_bus *pcibios_scan_root(int bus);

void pcibios_set_master(struct pci_dev *dev);
void pcibios_penalize_isa_irq(int irq, int active);
struct irq_routing_table *pcibios_get_irq_routing_table(void);
int pcibios_set_irq_routing(struct pci_dev *dev, int pin, int irq);

#define HAVE_PCI_MMAP
extern int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
			       enum pci_mmap_state mmap_state,
			       int write_combine);

#ifdef CONFIG_PCI
extern void early_quirks(void);
static inline void pci_dma_burst_advice(struct pci_dev *pdev,
					enum pci_dma_burst_strategy *strat,
					unsigned long *strategy_parameter)
{
	*strat = PCI_DMA_BURST_INFINITY;
	*strategy_parameter = ~0UL;
}
#else
static inline void early_quirks(void) { }
#endif

extern void pci_iommu_alloc(void);

#ifdef CONFIG_PCI_MSI
/* MSI arch specific hooks */
static inline int x86_setup_msi_irqs(struct pci_dev *dev, int nvec, int type)
{
	return x86_msi.setup_msi_irqs(dev, nvec, type);
}

static inline void x86_teardown_msi_irqs(struct pci_dev *dev)
{
	x86_msi.teardown_msi_irqs(dev);
}

static inline void x86_teardown_msi_irq(unsigned int irq)
{
	x86_msi.teardown_msi_irq(irq);
}
#define arch_setup_msi_irqs x86_setup_msi_irqs
#define arch_teardown_msi_irqs x86_teardown_msi_irqs
#define arch_teardown_msi_irq x86_teardown_msi_irq
/* implemented in arch/x86/kernel/apic/io_apic. */
int native_setup_msi_irqs(struct pci_dev *dev, int nvec, int type);
void native_teardown_msi_irq(unsigned int irq);
/* default to the implementation in drivers/lib/msi.c */
#define HAVE_DEFAULT_MSI_TEARDOWN_IRQS
void default_teardown_msi_irqs(struct pci_dev *dev);
#else
#define native_setup_msi_irqs		NULL
#define native_teardown_msi_irq		NULL
#define default_teardown_msi_irqs	NULL
#endif

#define PCI_DMA_BUS_IS_PHYS (dma_ops->is_phys)

#endif  /* __KERNEL__ */

#ifdef CONFIG_X86_64
#include "pci_64.h"
#endif

/* implement the pci_ DMA API in terms of the generic device dma_ one */
#include <asm-generic/pci-dma-compat.h>

/* generic pci stuff */
#include <asm-generic/pci.h>
#define PCIBIOS_MAX_MEM_32 0xffffffff

#ifdef CONFIG_NUMA
/* Returns the node based on pci bus */
static inline int __pcibus_to_node(const struct pci_bus *bus)
{
	const struct pci_sysdata *sd = bus->sysdata;

	return sd->node;
}

static inline const struct cpumask *
cpumask_of_pcibus(const struct pci_bus *bus)
{
	int node;

	node = __pcibus_to_node(bus);
	return (node == -1) ? cpu_online_mask :
			      cpumask_of_node(node);
}
#endif

#endif /* _ASM_X86_PCI_H */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE components PUBLIC "-//DBFLUTE//DTD LastaDi 1.0//EN"
	"http://dbflute.org/meta/lastadi10.dtd">
<components namespace="dbflute_readonly">
	<include condition="#exists('#path')" path="my_included_dbflute.xml"/>
	<include path="rdb.xml"/>

	<!-- The components of DBFlute Runtime. -->
	<component name="royIntroduction" class="org.docksidestage.sqlite.dbflute.readonly.allcommon.RoyDBFluteInitializer"/>
	<component name="royInvokerAssistant" class="org.docksidestage.sqlite.dbflute.readonly.allcommon.RoyImplementedInvokerAssistant"/>
	<component name="royBehaviorCommandInvoker" class="org.dbflute.bhv.core.BehaviorCommandInvoker"/>
	<component name="royBehaviorSelector" class="org.docksidestage.sqlite.dbflute.readonly.allcommon.RoyImplementedBehaviorSelector"/>
	<component name="royCommonColumnAutoSetupper" class="org.docksidestage.sqlite.dbflute.readonly.allcommon.RoyImplementedCommonColumnAutoSetupper"/>

	<!-- The components of Behavior. -->
	<component name="royMemberBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberBhv"/>
	<component name="royMemberAddressBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberAddressBhv"/>
	<component name="royMemberLoginBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberLoginBhv"/>
	<component name="royMemberSecurityBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberSecurityBhv"/>
	<component name="royMemberServiceBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberServiceBhv"/>
	<component name="royMemberStatusBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberStatusBhv"/>
	<component name="royMemberWithdrawalBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyMemberWithdrawalBhv"/>
	<component name="royProductBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyProductBhv"/>
	<component name="royProductCategoryBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyProductCategoryBhv"/>
	<component name="royProductStatusBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyProductStatusBhv"/>
	<component name="royPurchaseBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyPurchaseBhv"/>
	<component name="royPurchasePaymentBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyPurchasePaymentBhv"/>
	<component name="royRegionBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyRegionBhv"/>
	<component name="royServiceRankBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyServiceRankBhv"/>
	<component name="roySummaryProductBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoySummaryProductBhv"/>
	<component name="royVendorCheckBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyVendorCheckBhv"/>
	<component name="royWithdrawalReasonBhv" class="org.docksidestage.sqlite.dbflute.readonly.exbhv.RoyWithdrawalReasonBhv"/>
</components>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edacc.manageDB;

/**
 *
 * @author dgall
 */
class SolverAlreadyInDBException extends Exception {

    public SolverAlreadyInDBException() {
        super ("You are trying to add a duplicate solver!");
    }

}


text:
namespace WordPressRestApi.QueryModel
{
    public class Context
    {
        public static string View = "view";
        public static string Embed = "embed";
        public static string Edit = "edit";

    }
}


text:
```cpp
// (1)
template<typename InputType>
static basic_json from_bson(InputType&& i,
                            const bool strict = true,
                            const bool allow_exceptions = true);
// (2)
template<typename IteratorType>
static basic_json from_bson(IteratorType first, IteratorType last,
                            const bool strict = true,
                            const bool allow_exceptions = true);
```

Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.

1. Reads from a compatible input.
2. Reads from an iterator range.

The exact mapping and its limitations is described on a [dedicated page](../../features/binary_formats/bson.md).

## Template parameters

`InputType`
:   A compatible input, for instance:

    - an `std::istream` object
    - a `FILE` pointer
    - a C-style array of characters
    - a pointer to a null-terminated string of single byte characters
    - an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators.

`IteratorType`
:   a compatible iterator type

## Parameters

`i` (in)
:   an input in BSON format convertible to an input adapter

`first` (in)
:   iterator to start of the input

`last` (in)
:   iterator to end of the input

`strict` (in)
:   whether to expect the input to be consumed until EOF (`#!cpp true` by default)

`allow_exceptions` (in)
:   whether to throw exceptions in case of a parse error (optional, `#!cpp true` by default)

## Return value

deserialized JSON value; in case of a parse error and `allow_exceptions` set to `#!cpp false`, the return value will be
`value_t::discarded`.  The latter can be checked with [`is_discarded`](is_discarded.md).

## Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

## Exceptions

Throws [`parse_error.114`](../../home/exceptions.md#jsonexceptionparse_error114) if an unsupported BSON record type is
encountered.

## Complexity

Linear in the size of the input.

## Examples

??? example

    The example shows the deserialization of a byte vector in BSON format to a JSON value.

    ```cpp
    --8<-- "examples/from_bson.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/from_bson.output"
    ```

## See also

- [BSON specification](http://bsonspec.org/spec.html)
- [to_bson](to_bson.md) for the analogous serialization
- [from_cbor](from_cbor.md) for the related CBOR format
- [from_msgpack](from_msgpack.md) for the related MessagePack format
- [from_ubjson](from_ubjson.md) for the related UBJSON format

## Version history

- Added in version 3.4.0.

!!! warning "Deprecation"

    - Overload (2) replaces calls to `from_bson` with a pointer and a length as first two parameters, which has been
      deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like
      `#!cpp from_bson(ptr, len, ...);` with `#!cpp from_bson(ptr, ptr+len, ...);`.
    - Overload (2) replaces calls to `from_bson` with a pair of iterators as their first parameter, which has been
      deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like
      `#!cpp from_bson({ptr, ptr+len}, ...);` with `#!cpp from_bson(ptr, ptr+len, ...);`.

    You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
    function.


text:
A Kotlin client with Wasabi HTTP framework

## Dependencies
- gradle
- JDK 8
- Kotlin 1.0.4

## Code
The game server will post orders on `/order` endpoint.
`orderHandler` route handler in `MyServer.kt` file will handle this so this is where to start coding.

## Run
You don't need any application server. The server is embedded. Just execute the main method in the MyServer.kt file

The server listens on port 9000: [http://localhost:9000/ping](http://localhost:9000/ping)


text:
module Azure::CognitiveServices::CustomSearch::V1_0
  module Models
    #
    # Defines values for TextFormat
    #
    module TextFormat
      Raw = "Raw"
      Html = "Html"
    end
  end
end


text:
import config
from cloudconsole import app

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


text:
/*jslint browser: true*/
/*global $, define, rangy, _, prompt, alert, Detector, WebSyncData, ace, JST*/

//= require templates/edit-ribbon
//= require templates/edit-body
//= require templates/edit-wordcount

// WebSync: Text Editing Plugin
define('edit', ['websync'], function(WS) {
  /**
   * The primary text editor for WebSync
   * @exports edit
   * @module edit
   */

  'use strict';
  var exports = {};
  // Plugins should use a jQuery namespace for ease of use.
  // Bind Example: $(document).bind("click.Tables", clickHandler);
  // Unbind Example: $("*").unbind(".Tables");

  // Add Text menu to the ribbon.
  $('.ribbon').append(JST['templates/edit-ribbon']({}));
  $('body').append(JST['templates/edit-body']({}));

  /** List of buttons that can be clicked in the Text menu. */
  exports.textButtons = ['bold', 'italic', 'strikethrough', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'removeFormat', 'insertorderedlist', 'insertunorderedlist', 'superscript', 'subscript', 'insertHorizontalRule', 'indent', 'outdent'];

  // Bind the basic text editing commands to the buttons.
  exports.textButtons.forEach(function(elem) {
    $('button#' + elem).bind('click.TextEdit', function() {
      document.execCommand(elem);
      //$(this).toggleClass("active");
      $(document).trigger('selectionchange');
    });
  });
  // Button and code to handle word/character counting.
  $('#view_mode').after(' <button id="word_count" class="Text btn btn-default"> Word Count</button>');
  var updateText = function() {
    var table = $('#word_count_info');
    table.parents('.popover').css({
      'max-width': 500,
      'z-index': 10000
    });
    var text = $('.content_container').text();
    var seltext = rangy.getSelection().toString();
    table.parents('.popover-content').css({
      padding: 0
    }).html(JST['templates/edit-wordcount']({
      wordsDocument: text.split(/\s+/).length,
      wordsSelection: seltext === '' ? 0 : seltext.split(/\s+/).length,
      characterDocument: text.length,
      characterSelection: seltext.length,
      characterDocumentNoSpaces: text.replace(/\s+/g, '').length,
      characterSelectionNoSpaces: seltext.replace(/\s+/g, '').length
    }));
  };
  var liveUpdate = false;
  $(document).on('selectionchange.Text', function() {
    if (liveUpdate) {
      updateText();
    }
  });
  $('#word_count').on('shown.bs.popover', function() {
    updateText();
    liveUpdate = true;
  }).on('hide.bs.popover', function() {
    liveUpdate = false;
  }).popover({
    placement: 'bottom',
    html: true,
    container: 'body',
    content: JST['templates/edit-wordcount']({
      wordsDocument: 0,
      wordsSelection: 0,
      characterDocument: 0,
      characterSelection: 0,
      characterDocumentNoSpaces: 0,
      characterSelectionNoSpaces: 0
    })
  }).popover('show').popover('hide');

  // Text styling handlers
  $('#fontColor').change(function() {
    document.execCommand('foreColor', false, this.value);
  });
  $('#hilightColor').change(function() {
    document.execCommand('hiliteColor', false, this.value);
  });
  // Reflects text in menu at top
  $(document).bind('selectionchange.TextEdit', function() {
    if (!exports._selectTimeout) {
      exports._selectTimeout = setTimeout(exports.selectHandler, 200);
    }
  });
  // List indentation
  $('.content_well').bind('keydown.TextEdit', function(e) {
    if (e.keyCode === 9) {
      var node = $(document.getSelection().anchorNode);
      var parent = node.parent();
      if ($(document.getSelection().baseNode).closest('li').length === 1) {
        if (e.shiftKey) {
          document.execCommand('outdent');
        } else {
          document.execCommand('indent');
        }
      } else {
        if (e.shiftKey) {
          if (parent.css('text-indent') !== '0px') {
            parent.css({
              'text-indent': ''
            });
          } else {
            document.execCommand('outdent');
          }
          // No indentation inside a table.
        } else if (!parent.is('td, th')) {
          if (parent.css('text-indent') === '0px') {
            if (parent.attr('contenteditable') === 'true') {
              node.wrap("

");
            } else {
              parent.css({
                'text-indent': 40
              });
            }
          } else {
            document.execCommand('indent');
          }
        }
      }
      e.preventDefault();
    }
    if (e.shiftKey && e.ctrlKey) {
      var command = true;
      if (e.keyCode === 54) { // Key 6
        document.execCommand('superscript');
      } else if (e.keyCode === 55) { // Key 7
        document.execCommand('insertunorderedlist');
      } else if (e.keyCode === 56) { // Key 8
        document.execCommand('insertorderedlist');
      } else if (e.keyCode === 69) { // E
        document.execCommand('justifycenter');
      } else if (e.keyCode === 74) { // J
        document.execCommand('justifyfull');
      } else if (e.keyCode === 76) { // L
        document.execCommand('justifyleft');
      } else if (e.keyCode === 82) { // R
        document.execCommand('justifyright');
      } else if (e.keyCode === 189) { // -
        document.execCommand('subscript');
      } else if (e.keyCode === 220) { // \
        document.execCommand('removeFormat');
      } else {
        command = false;
      }
      if (command) {
        e.preventDefault();
      }
    }
    if (e.ctrlKey && e.keyCode === 83) { // S
      WS.info('Saved WebSync automatically saves your changes.');
      $('#ribbon_buttons a:contains(File)').click();
      $('#File .btn-group button').click();
      e.preventDefault();
    }
  });
  $('#font ul').on('click.TextEdit', 'a', function(e) {
    var font = $(e.currentTarget).find('.fname').text();
    console.log(e, font);
    document.execCommand('fontname', false, font);
  });
  $('#font_size').change(function() {
    var size = $('#font_size').val();
    console.log(size);
    WS.applyCssToSelection({
      'font-size': size
    });
  });
  // Picture, video and link insertion.
  $('#picture').click(function() {
    exports.selection = WS.selectionSave();
    console.log(exports.selection);
    $('#image_modal').modal();
  });
  $('#insert_image').click(function() {
    var url = $('#image_modal input[type=text]').val();
    if (url.length > 0) {
      $('#image_modal').modal('hide');
      WS.selectionRestore(exports.selection);
      delete exports.selection;
      $('#image_modal input[type=text]').val('');
      document.execCommand('insertImage', false, url);
    } else {
      var files = $('#image_modal input[type=file]')[0].files;
      if (files.length > 0) {
        $('#image_modal .progress').slideDown();
        var name = files[0].name;
        WS.uploadResource(files[0], function(e) {
          var pc = parseInt(100 - (e.loaded / e.total * 100), 10);
          $('#image_modal .progress-bar').css('width', pc + '%');
        }, function(xhr) {
          if (xhr.readyState === 4) {
            $('#image_modal .progress-bar').css('width', '100%');
            $('#image_modal .progress').slideUp();
            if (xhr.status === 200) {
              WS.success('Success! File uploaded successfully.');
            } else {
              WS.error('Error! File failed to upload.');
            }
            $('#image_modal input[type=file]').val('');
            $('#image_modal').modal('hide');
            WS.selectionRestore(exports.selection);
            document.execCommand('insertImage', false, 'assets/' + name);
          }
        });
      } else {
        WS.error('Error! You need to input a file or URL.');
      }
    }
  });
  $('#createLink').click(function() {
    var url = prompt('Hyperlink URL');
    document.execCommand('createLink', false, url);
  });
  $('#line_spacing a').click(function() {
    var width = $(this).text();
    WS.applyCssToSelection({
      'line-height': width + 'em'
    });
  });
  $('#video').click(function() {
    /** The temporarily saved selection */
    exports.selection = WS.selectionSave();
    $('#youtube_modal').modal();
  });
  $('#youtube_modal input').change(function() {
    var url = $('#youtube_modal input').val();
    var youtubeId = exports.youtubeParser(url);
    var html = '';
    $('#youtube_modal #youtube-preview').html(html);
  });
  $('#insert_video').click(function() {
    $('#youtube_modal').modal('hide');
    var url = $('#youtube_modal input').val();
    $('#youtube_modal input').val('');
    var youtubeId = exports.youtubeParser(url);
    var html = '';
    WS.selectionRestore(exports.selection);
    delete exports.selection;
    document.execCommand('insertHTML', false, html);
  });

  if (window.webkitSpeechRecognition) {
    $('#voice_input').show();

    var voiceInputActive = false;
    var lastResults = [];
    var nodes = [];
    var recognition;

    var stopVoice = function() {
      $('#voice_input').removeClass('active')
        .find('i').removeClass('fa-microphone-slash').addClass('fa-microphone');
      $('.content_well .voice-intermin').removeClass('voice-intermin');
      voiceInputActive = false;
      if (recognition) {
        recognition.stop();
      }
    };
    var startVoice = function() {
      lastResults = [];
      nodes = [];

      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;

      recognition.onstart = function() {
        $('#voice_input').addClass('active')
          .find('i').addClass('fa-microphone-slash').removeClass('fa-microphone');
        voiceInputActive = true;
      };
      recognition.onresult = function(event) {
        console.log('VOICE', event);
        _.each(event.results, function(result, i) {
          var text = result[0].transcript;

          var lastResult = lastResults[i];
          if (!lastResult) {
            var node = $('').text(text);
            nodes.push(node);

            var sel = rangy.getSelection().getRangeAt(0);
            sel.insertNode(node[0]);
          } else {
            nodes[i].text(text);
            if (result.isFinal) {
              nodes[i].removeClass('voice-intermin');
            }
          }
        });
        lastResults = event.results;
      };
      recognition.onerror = function(event) {
        console.log('VOICE ERROR', event);
        if (event.error !== 'not-allowed') {
          startVoice();
        }
      };
      recognition.onend = function() {
        console.log('VOICE END');
        stopVoice();
      };
      recognition.start();
    };
    $('#voice_input').click(function() {
      if (voiceInputActive) {
        stopVoice();
      } else {
        startVoice();
      }
    });
  }

  /**
   * Youtube REGEX from http://stackoverflow.com/a/8260383 by Lasnv
   * @param {String} url - The url to parse.
   * @return {String} The youtube video ID.
   */
  exports.youtubeParser = function(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match && match[2].length === 11) {
      return match[2];
    }
    alert('Invalid URL');
    return '';
  };

  /**
   * Helper function to convert rgba(r, g, b, a) to #RRGGBB
   * @param {String} rgb - The RGBA string. Ex: 'rgb(255,128,0)'
   * @return {String}
   */
  exports.rgbToHex = function(rgb) {
    if (rgb === 'rgba(0, 0, 0, 0)') {
      return '#FFFFFF';
    }
    var parts = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0|0?\.d+))?\)$/);
    if (!parts) {
      return '#000000';
    }
    var i;
    for (i = 1; i <= 3; ++i) {
      if (parts[i]) {
        parts[i] = parseInt(parts[i], 10).toString(16);
        if (parts[i].length === 1) {
          parts[i] = '0' + parts[i];
        }
      }
    }
    return '#' + parts.slice(1, 4).join('').toUpperCase();
  };

  /** Disables the TextEdit plugin. */
  exports.disable = function() {
    $('.Text').remove();
    WS.updateRibbon();
    $('*').unbind('.TextEdit');
    $('*').undelegate('.TextEdit');
  };

  /** Handling function for displaying accurate information about text in ribbon. */
  exports.selectHandler = function() {
    var style = WS.getCss();
    $('#fontColor')[0].value = exports.rgbToHex(style.color);
    $('#hilightColor')[0].value = exports.rgbToHex(style.backgroundColor);
    var fontSizePt = Math.floor(parseInt(style.fontSize, 10) * 0.75);
    $('#font_size').val(fontSizePt + 'pt');

    exports.textButtons.forEach(function(elem) {
      var button = $('button#' + elem);
      if (document.queryCommandState(elem)) {
        button.addClass('active');
      } else {
        button.removeClass('active');
      }
    });
    var font = document.queryCommandValue('fontname').
    split(',')[0].split("'").join('').capitalize();
    $('#font .name').text(font).css({
      'font-family': font
    });
    clearTimeout(exports._selectTimeout);
    exports._selectTimeout = null;
  };
  // Sets up the list of fonts
  var fonts = ['Cursive', 'Monospace', 'Serif', 'Sans-serif', 'Fantasy', 'Arial', 'Arial Black', 'Arial Narrow', 'Arial Rounded MT Bold', 'Bookman Old Style', 'Bradley Hand ITC', 'Century', 'Century Gothic', 'Comic Sans MS', 'Droid Sans', 'Courier', 'Courier New', 'Georgia', 'Gentium', 'Impact', 'King', 'Lucida Console', 'Lalit', 'Modena', 'Monotype Corsiva', 'Papyrus', 'TeX', 'Times', 'Times New Roman', 'Trebuchet MS', 'Tahoma', 'Verdana', 'Verona', 'Helvetica', 'Segoe', 'Open Sans'];
  var d = new Detector();
  var fontList = [];
  fonts = fonts.sort(function(a, b) {
    if (a  b) {
      return 1;
    }
    return 0;
  });

  /** The available fonts on the clients system. */
  exports.availableFonts = [];
  var i, result;
  for (i = 0; i < fonts.length; i++) {
    result = d.detect(fonts[i]);
    if (result) {
      exports.availableFonts.push({
        name: fonts[i],
        source: 'local'
      });
    }
  }

  var webfonts = ['Ubuntu', 'Ubuntu Mono', 'Roboto', 'Oswald', 'Lato', 'Droid Sans', 'Droid Serif'];
  $('head').append("<link href='https://fonts.googleapis.com/css?family=" +
    webfonts.join('|').replace(/\s+/g, '+') + "' rel='stylesheet' type='text/css'>");
  _.each(webfonts, function(font) {
    if (exports.availableFonts.indexOf(font) === -1) {
      exports.availableFonts.push({
        name: font,
        source: 'google'
      });
    }
  });

  _.each(exports.availableFonts, function(font) {
    var fontEntry = '
';
    fontEntry += '';
    fontEntry += '' + font.name + '';
    if (font.source === 'google') {
      //fontEntry += '';
      fontEntry += 'G';
    }
    fontEntry += '
';
    fontList.push(fontEntry);
  });

  /**
   * A function to update the styles on the page from the custom css.
   * TODO: Not sure if this should be here.
   */
  exports.updateStyles = function() {
    exports.stylesheet.innerHTML = (WebSyncData.custom_css || []).join('\n');
  };

  /** The Ace editor used for custom css. */
  exports.editor = null;

  /** The custom stylesheet element */
  exports.stylesheet = document.createElement('style');

  // WebKit hack :(
  exports.stylesheet.appendChild(document.createTextNode(''));

  // Add the


text:
import com.google.gson.Gson;
import org.json.JSONObject;
import java.sql.*;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.text.SimpleDateFormat;

import java.net.URI;
import java.net.URISyntaxException;

import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;

import com.heroku.sdk.jdbc.DatabaseUrl;
import spark.Request;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) {

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    get("/hello", (req, res) -> "Hello World");

    //index.ftl
    get("/index", (req, res) -> {
            Map<String, Object> attributes = new HashMap<>();

            ArrayList<String> oddtopics = new ArrayList<String>();
            oddtopics.add("Animal");
            oddtopics.add("Beauty");
            oddtopics.add("Books");
            oddtopics.add("Television");
            ArrayList<String> eventopics = new ArrayList<String>();
            eventopics.add("Culture");
            eventopics.add("Music");
            eventopics.add("Technology");
            ArrayList<String> weektopics = new ArrayList<String>();
            weektopics.add("Cooking");
            weektopics.add("Movies");
            weektopics.add("Sports");
            weektopics.add("Travel");

            SimpleDateFormat formatter = new SimpleDateFormat("EEEE");
            String dayOfWeek = formatter.format(new Date());
            //Testing
            System.out.println(dayOfWeek);
            System.out.println(weektopics);

            attributes.put("oddtopics", oddtopics);
            attributes.put("eventopics", eventopics);
            attributes.put("weektopics", weektopics);
            attributes.put("dayOfWeek", dayOfWeek);

            return new ModelAndView(attributes, "index.ftl");
          } , new FreeMarkerEngine());

    //get("/", (request, response) -> {
    //        Map<String, Object> attributes = new HashMap<>();
    //        attributes.put("message", "Hello World!");
    //
    //        return new ModelAndView(attributes, "index.ftl");
    //    }, new FreeMarkerEngine());

    Gson gson = new Gson();
    //GET Mthod using JSON--match.html, find.js
    get("api/find", (req, res) -> {
        Connection connection = null;
        Map<String, Object> attributes = new HashMap<>();
        try {
        //Connect to Database and execute SQL Query
          connection = DatabaseUrl.extract().getConnection();
          Statement stmt = connection.createStatement();
          ResultSet rs = stmt.executeQuery("SELECT username, nlanguage, planguage FROM users");

          List<Object> data = new ArrayList<>();
          while (rs.next()) {
            Map<String, Object> member = new HashMap<>();
            member.put("username", rs.getString("username"));
            member.put("nlanguage", rs.getString("nlanguage"));
            member.put("planguage", rs.getString("planguage"));
            data.add(member);
          }
          return data;
        } catch (Exception e) {
          attributes.put("message", "There was an error: " + e);
          return new ModelAndView(attributes, "error.ftl");
        } finally {
          if (connection != null) try{connection.close();} catch(SQLException e){}
        }
      }, gson::toJson);

    //POST Method using JSON --registration.html,registration.js
    post("api/register", (req, res) -> {
          Connection connection = null;
          System.out.println(req.body());
        try {
          connection = DatabaseUrl.extract().getConnection();
          JSONObject obj = new JSONObject(req.body());
          String username = obj.getString("username");
          String password = obj.getString("password");
          String email = obj.getString("email");
          String fname = obj.getString("fname");
          String lname = obj.getString("lname");
          String gender = obj.getString("gender");
          String language = obj.getString("language");
          String planguage = obj.getString("planguage");
          String topic = obj.getString("topic");

          String sql = "INSERT INTO users VALUES ('"+ username + "','" + password + "','" + email + "','" + fname + "','"+ lname + "','" + gender + "','" + language + "','" + planguage + "','" + topic + "')";
          ///Connect to Database and execute SQL Query
          connection = DatabaseUrl.extract().getConnection();
          Statement stmt = connection.createStatement();
          stmt.executeUpdate(sql);

          ResultSet rs = stmt.executeQuery("SELECT * FROM users where username ='" + username + "'");
          Map<String, Object> currentuser = new HashMap<>();

					currentuser.put("username", rs.getString("username"));
					currentuser.put("email", rs.getString("email"));

          return currentuser;
        } catch (Exception e) {
          return e.getMessage();
        } finally {
          if (connection != null) try{connection.close();} catch(SQLException e){}
        }
      });

      //GET Method using XML-forum.html,forum.js
      get("api/forum", (req, res) -> {

          Connection connection = null;

          Map<String, Object> attributes = new HashMap<>();
          try {
              //Connect to Database and execute SQL Query
              connection = DatabaseUrl.extract().getConnection();
              Statement stmt = connection.createStatement();
              ResultSet rs = stmt.executeQuery("SELECT title,username,threads.planguage,threads.topic,description FROM users,threads WHERE users.email=threads.email");

              String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
              xml += "<forum xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:SchemaLocation=\"https://still-brushlands-7620.herokuapp.com/forum.xsd\">";
              while (rs.next()) {
              xml += "<thread>";
						  xml += "<title>"+rs.getString("title")+"</title>";
						  xml += "<username>"+rs.getString("username")+"</username>";
						  xml += "<language>"+rs.getString("planguage")+"</language>";
						  xml += "<topic>"+rs.getString("topic")+"</topic>";
						  xml += "<description>"+rs.getString("description")+"</description>";
					    xml += "</thread>";
              }
              xml += "</forum>";
              res.type("text/xml");
              return xml;

          } catch (Exception e) {
              attributes.put("message", "There was an error: " + e);
              return attributes;
          } finally {
              if (connection != null) try{connection.close();} catch(SQLException e){}
          }
        });//End api/forum

    get("/db", (req, res) -> {
      Connection connection = null;
      Map<String, Object> attributes = new HashMap<>();
      try {
        connection = DatabaseUrl.extract().getConnection();

        Statement stmt = connection.createStatement();
        stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
        stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
        ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");

        ArrayList<String> output = new ArrayList<String>();
        while (rs.next()) {
          output.add( "Read from DB: " + rs.getTimestamp("tick"));
        }

        attributes.put("results", output);
        return new ModelAndView(attributes, "db.ftl");
      } catch (Exception e) {
        attributes.put("message", "There was an error: " + e);
        return new ModelAndView(attributes, "error.ftl");
      } finally {
        if (connection != null) try{connection.close();} catch(SQLException e){}
      }
    }, new FreeMarkerEngine());

  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/play" android:state_checked="false"/>
    <item android:drawable="@mipmap/pause" android:state_checked="true"/>

</selector>


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Chicago 2014
 -  Proposal</title>
  <meta name="author" content="Jacob Tomaw" >
  <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

Chicago 2014
 -  Proposal

Gold sponsors

    welcome

    program
    location

    contact
    conduct

Back to proposals overview - program

Roll Forward, Roll Back, Cancel The Release

Abstract

As an evangelist for Continuous Delivery at Orbitz, I have been able to see many of the struggles and there to see how we have over come them. None of these struggles are purely development struggles. These changes are building stronger DevTestOps teams.

Over the last year, Orbitz has started the transition from deploying our 175 applications at most once every 2 week to being able to deploy them at will, daily or more often. This is creating cultural change that is not always easy to bear. Our history has built a culture where a failed release is shameful and not just a learning opportunity. As the deployment of the Orbitz Global Platform's applications become more frequent we are entering a new level of maturity. As releases become more frequent the value of them changes. The value of many of our practices are changing also to the point of abandoning some of them, automating others, and refactoring the rest.

As we simplify, automate, and speed up the deployment pipeline, the feedback of a release candidate's production worthiness becomes more important and clearer. In the past, there was a fuzzy gray area between Go and No-Go. We are learning to kill off a bad release sooner because another release is already on deck. Trying to salvage a release is an effort in fighting stupid and blinds you from an opportunity to make more awesome.

There is a lot to learn from our mistakes such as:

made heroic efforts to deploy apps when procedures didn't work

kept releases in production that should have been rolled back

put undue pressure on teams to resolve an issue in the next days release

begged our Product partners to give us business justification for an additional off-cycle release in an effort to cover up our mistake

As we are just entering the new maturity, I am sure there will be much more by October. We believe the community at the conference will benefit from hearing what we've learned, how we're changing, where we are still struggling, and how awesome it's going to continue to be as we head down this path.

Speaker Jacob Tomaw

Slides

Video

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

Silver sponsors

Bronze sponsors

Media sponsors

Wifi sponsors


text:
from __future__ import annotations

import logging

from xia2.Driver.DriverFactory import DriverFactory

logger = logging.getLogger("xia2.Wrappers.Dials.ExportXDSASCII")

def ExportXDSASCII(DriverType=None):
    """A factory for ExportXDSASCIISWrapper classes."""

    DriverInstance = DriverFactory.Driver(DriverType)

    class ExportXDSASCIISWrapper(DriverInstance.__class__):
        def __init__(self):
            DriverInstance.__class__.__init__(self)
            self.set_executable("dials.export")

            self._experiments_filename = None
            self._reflections_filename = None
            self._hkl_filename = "DIALS.HKL"

        def set_experiments_filename(self, experiments_filename):
            self._experiments_filename = experiments_filename

        def set_reflections_filename(self, reflections_filename):
            self._reflections_filename = reflections_filename

        def set_hkl_filename(self, hkl_filename):
            self._hkl_filename = hkl_filename

        def get_hkl_filename(self):
            return self._hkl_filename

        def run(self):
            logger.debug("Running dials.export")

            assert self._experiments_filename is not None
            assert self._reflections_filename is not None

            self.clear_command_line()
            self.add_command_line(self._experiments_filename)
            self.add_command_line(self._reflections_filename)
            if self._hkl_filename is not None:
                self.add_command_line("xds_ascii.hklout=%s" % self._hkl_filename)
            self.add_command_line("format=xds_ascii")
            self.start()
            self.close_wait()
            self.check_for_errors()

    return ExportXDSASCIISWrapper()


text:
var express = require('express'),
    router = express.Router(),
    User = require('../models').User,
    ensureAuthenticated = require('../lib/middleware').ensureAuthenticated;

router.get('/foundation', function(req, res, next){
    res.render('foundation');
});

router.get('/login', function(req, res, next){
    res.render('login');
});

router.get('/logout', function(req, res, next){
    req.logout();
    req.session.destroy();
    res.redirect('/');
});

router.route('/account')
    .all(ensureAuthenticated)
    .get(function(req, res, next){
        res.render('account');
    })
    .put(function(req, res, next){
        User.findById(req.user._id, function(err, user){
            if (err) {
                return res.json(404, {
                    error: 'Could not find user'
                });
            }

            req.assert('username', 'username is required').notEmpty();
            req.assert('name', 'name is required').notEmpty();
            req.assert('email', 'valid email required').isEmail();

            var errors = req.validationErrors();
            if (errors) {
                return res.json('200', {
                    errors: errors
                });
            }

            user.username = req.body.username;
            user.name = req.body.name;
            user.email = req.body.email;
            return user.save(function(err){
                if (err) { next(err); }

                return res.json(200, {
                    message: 'Changes saved'
                });
            });
        });
    });

module.exports = router;


text:
package com.yirendai.infra.cicada.entity;

import com.alibaba.fastjson.JSON;

import lombok.AllArgsConstructor;
import lombok.Data;

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

@Data
@AllArgsConstructor
public class Job {
  private long id;
  private long startTimestamp;
  private long endTimestamp;
  private Map<String, Fragment> infos;

  public Job() {
    this.infos  = new HashMap<String, Fragment>();
  }

  public void addJobFragment(final String key, final Fragment fragment) {
    infos.put(key, fragment);
  }

  public Fragment getJobFragment(final String key) {
    return infos.get(key);
  }

  public void incrJodId() {
    ++this.id;
  }

  @Override
  public String toString() {
    return JSON.toJSONString(this);
  }
}


text:
@interface LGNotificationsViewController ()
#pragma mark - Email
#pragma mark-- Outlets --

@property (weak) IBOutlet NSTextField *smtpServer;
@property (weak) IBOutlet NSTextField *smtpPort;

@property (weak) IBOutlet NSTextField *smtpUsername;
@property (weak) IBOutlet NSSecureTextField *smtpPassword;

// Status icons
@property (weak) IBOutlet NSImageView *testSmtpServerStatus;

// Spinners
@property (weak) IBOutlet NSProgressIndicator *sendTestEmailSpinner;
@property (weak) IBOutlet NSProgressIndicator *testSmtpServerSpinner;

#pragma mark-- IBActions --
- (IBAction)sendTestEmail:(id)sender;
- (IBAction)testServerPort:(id)sender;

- (IBAction)getKeychainPassword:(NSTextField *)sender;
- (IBAction)updateKeychainPassword:(id)sender;

#pragma mark Other Services
#pragma mark-- Outletes ---

@property (weak) IBOutlet NSButton *configureSlackButton;
@property (weak) IBOutlet NSButton *configureHipChatButton;
@property (weak) IBOutlet NSButton *configureMicrosoftTeamsButton;
@property (weak) IBOutlet NSButton *configureGoogleHangoutsButton;

#pragma mark-- IBActions
- (IBAction)configure:(NSButton *)sender;

@end

#pragma mark - LGNotificationsViewController
@implementation LGNotificationsViewController {
    LGNotificationServiceWindowController *_serviceWindow;
    LGTemplateRenderWindowController *_templateRenderWindow;
    LGSelectNotificationsWindowController *_flagConfigureWindow;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do view setup here.
}

- (void)awakeFromNib
{
    self.configureHipChatButton.action = @selector(configure:);
    self.configureHipChatButton.target = self;
    self.configureHipChatButton.identifier = NSStringFromClass([LGHipChatNotification class]);

    self.configureSlackButton.action = @selector(configure:);
    self.configureSlackButton.target = self;
    self.configureSlackButton.identifier = NSStringFromClass([LGSlackNotification class]);

    self.configureMicrosoftTeamsButton.action = @selector(configure:);
    self.configureMicrosoftTeamsButton.target = self;
    self.configureMicrosoftTeamsButton.identifier = NSStringFromClass([LGMicrosoftTeamsNotification class]);

    self.configureGoogleHangoutsButton.action = @selector(configure:);
    self.configureGoogleHangoutsButton.target = self;
    self.configureGoogleHangoutsButton.identifier = NSStringFromClass([LGGoogleHangoutsNotification class]);

    self.configureSlackButton.wantsLayer = YES;
    self.configureSlackButton.animator.alphaValue = 1.0;

    [LGPasswords migrateKeychainIfNeeded:^(NSString *password, NSError *error) {
        if (error) {
            [NSApp presentError:error];
        }

        if (password) {
            _smtpPassword.stringValue = password;
        }
    }];

    [self getKeychainPassword:_smtpPassword];
}

- (NSString *)tabLabel
{
    return NSLocalizedString(@"Notifications", @"Tab label");
}

#pragma mark - Open Config Panel
- (IBAction)configure:(NSButton *)sender
{
    // Handle first time checkboxes.
    if (sender.state) {
        BOOL configured = NO;
        if ([sender.identifier isEqualToString:@"enableSlackCheckBox"]) {
            configured = [[LGDefaults standardUserDefaults] boolForKey:@"SlackConfigured"];
            if (!configured) {
                [self configure:self.configureSlackButton];
                [[LGDefaults standardUserDefaults] setBool:YES forKey:@"SlackConfigured"];
            }
        }
        else if ([sender.identifier isEqualToString:@"enableHipChatCheckBox"]) {
            configured = [[LGDefaults standardUserDefaults] boolForKey:@"HipChatConfigured"];
            if (!configured) {
                [self configure:self.configureHipChatButton];
                [[LGDefaults standardUserDefaults] setBool:YES forKey:@"HipChatConfigured"];
            }
        }
        else if ([sender.identifier isEqualToString:@"enableMicrosoftTeamsCheckBox"]) {
            configured = [[LGDefaults standardUserDefaults] boolForKey:@"MicrosoftTeamsConfigured"];
            if(!configured) {
                [self configure:self.configureMicrosoftTeamsButton];
                [[LGDefaults standardUserDefaults] setBool:YES forKey:@"MicrosoftTeamsConfigured"];
            }
        }
        else if ([sender.identifier isEqualToString:@"enableGoogleHangoutsCheckBox"]) {
            configured = [[LGDefaults standardUserDefaults] boolForKey:@"GoogleHangoutsConfigured"];
            if(!configured) {
                [self configure:self.configureGoogleHangoutsButton];
                [[LGDefaults standardUserDefaults] setBool:YES forKey:@"GoogleHangoutsConfigured"];
            }
        }
    }

    Class viewClass = NSClassFromString([sender.identifier stringByAppendingString:@"View"]);
    Class serviceClass = NSClassFromString(sender.identifier);

    if (serviceClass && viewClass) {
        id<LGNotificationServiceProtocol> service = [[serviceClass alloc] init];
        LGBaseNotificationServiceViewController *serviceView = [[viewClass alloc] initWithNotificationService:service];

        _serviceWindow = [[LGNotificationServiceWindowController alloc] initWithViewController:serviceView];

        [_serviceWindow openSheetOnWindow:self.modalWindow complete:^(LGWindowController *windowController) {
            NSString *enabledKey = nil;
            if (serviceClass == [LGSlackNotification class]) {
                enabledKey = @"Slack";
            }
            else if (serviceClass == [LGHipChatNotification class]) {
                enabledKey = @"HipChat";
            }
            else if (serviceClass == [LGMicrosoftTeamsNotification class]) {
                enabledKey = @"MicrosoftTeams";
            }
            else if (serviceClass == [LGGoogleHangoutsNotification class]) {
                enabledKey = @"GoogleHangouts";
            }
            if (enabledKey.length) {
                id controller = (LGBaseNotificationServiceViewController *)_serviceWindow.viewController;
                if ([controller respondsToSelector:@selector(didConfigure)] && ![controller didConfigure]) {
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:[enabledKey stringByAppendingString:@"NotificationsEnabled"]];
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:[enabledKey stringByAppendingString:@"Configured"]];
                }
            }
            _serviceWindow = nil;
        }];
    }
}

- (IBAction)configureNotificationsFlags:(id)sender
{
    _flagConfigureWindow = [[LGSelectNotificationsWindowController alloc] init];
    [_flagConfigureWindow openSheetOnWindow:self.modalWindow complete:^(LGWindowController *windowController) {
        _flagConfigureWindow = nil;
    }];
}

- (IBAction)openTemplateEditor:(id)sender
{
    _templateRenderWindow = [[LGTemplateRenderWindowController alloc] init];
    [_templateRenderWindow open:^(LGWindowController *renderer) {
        _templateRenderWindow = nil;
    }];
}

#pragma mark - Keychain Actions
- (void)getKeychainPassword:(NSTextField *)sender
{
    [LGEmailNotification infoFromKeychain:^(NSString *infoOrPassword, NSError *error) {
        if (error) {
            NSLog(@"Error getting password for %@ [%ld]: %@", [LGEmailNotification account], error.code, error.localizedDescription);
        }
        else {
            _smtpPassword.safe_stringValue = infoOrPassword;
        }
    }];
}

- (IBAction)updateKeychainPassword:(id)sender
{
    [self savePassword:nil];
}

- (void)savePassword:(void (^)(NSError *error))reply
{
    NSString *account = _smtpUsername.safe_stringValue;
    NSString *password = _smtpPassword.safe_stringValue;

    if (account && [LGEmailNotification storesInfoInKeychain]) {
        [LGEmailNotification saveInfoToKeychain:password reply:^(NSError *error) {
            if (reply) {
                reply(error);
            }
            if (error) {
                if (error.code == errSecAuthFailed || error.code == errSecDuplicateKeychain) {
                    [LGPasswords resetKeychainPrompt:^(NSError *error) {
                        if (!error) {
                            [self updateKeychainPassword:nil];
                        }
                        else {
                            NSLog(@"Error resetting password [%ld]: %@", error.code, error.localizedDescription);
                        }
                    }];
                }
                else {
                    NSLog(@"Error setting password [%ld]: %@", error.code, error.localizedDescription);
                }
            }
        }];
    }
    else {
        if (reply) {
            reply(nil);
        }
    }
}

#pragma mark - Email Actions
- (void)testServerPort:(id)sender
{
    if (![[_smtpServer stringValue] isEqualToString:@""] && [_smtpPort integerValue] > 0) {

        DLog(@"Testing SMTP server and port settings.");
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

        // Set up the UI.
        [_testSmtpServerStatus setHidden:YES];
        [_testSmtpServerSpinner setHidden:NO];
        [_testSmtpServerSpinner startAnimation:self];

        LGTestPort *tester = [[LGTestPort alloc] init];

        [center addObserver:self
                   selector:@selector(testSmtpServerPortNotificationReceived:)
                       name:kLGNotificationTestSmtpServerPort
                     object:nil];

        [tester testHost:[NSHost hostWithName:[_smtpServer stringValue]]
                withPort:[_smtpPort integerValue]];
    }
    else {
        NSLog(@"Cannot test SMTP. Either host is blank or port is unreadable.");
    }
}

- (void)sendTestEmail:(id)sender
{
    // Send a test email notification when the user clicks "Send Test Email".

    DevLog(@"'Send Test Email' button clicked.");

    // Handle UI.
    [sender setEnabled:NO]; // disable button
    [_sendTestEmailSpinner setHidden:NO]; // show spinner
    [_sendTestEmailSpinner startAnimation:self]; // animate spinner

    // Set up a completion block.
    void (^didComplete)(NSError *) = ^void(NSError *error) {
        [sender setEnabled:YES]; // enable button
        [_sendTestEmailSpinner setHidden:YES]; // hide spinner
        [_sendTestEmailSpinner stopAnimation:self]; // stop animation

        [self.progressDelegate stopProgress:error];
    };

    [self savePassword:^(NSError *error) {
        // If the save password method has an error, stop emailing. The emailer would get the same error.
        if (error) {
            return didComplete(error);
        }

        // Create an instance of the LGEmailer class.
        LGEmailNotification *emailer = [[LGEmailNotification alloc] init];
        [emailer sendTest:didComplete];
    }];
}

- (void)testSmtpServerPortNotificationReceived:(NSNotification *)notification
{
    // Set up the spinner and show the status image.
    [_testSmtpServerSpinner setHidden:YES];
    [_testSmtpServerSpinner stopAnimation:self];
    [_testSmtpServerStatus setHidden:NO];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kLGNotificationTestSmtpServerPort
                                                  object:nil];

    NSString *status = notification.userInfo[kLGNotificationUserInfoSuccess];
    if ([status isEqualTo:@NO]) {
        [_testSmtpServerStatus setImage:[NSImage LGStatusUnavailable]];
    }
    else if ([status isEqualTo:@YES]) {
        [_testSmtpServerStatus setImage:[NSImage LGStatusAvailable]];
    }
    else {
        NSLog(@"Unexpected result for received from port test.");
        [_testSmtpServerStatus setImage:[NSImage LGStatusPartiallyAvailable]];
    }
}

@end


text:
package parsers

import (
	"bufio"
	"strconv"
	"strings"
	"sync"

	m "github.com/AntoineAugusti/wordsegmentation/models"
)

// Parse unigrams from a given TSV file.
func Unigrams(path string) m.Unigrams {
	jobs := make(chan string, 5000)
	results := make(chan m.Unigram, 5000)

	wg := new(sync.WaitGroup)
	for w := 1; w <= 2; w++ {
		wg.Add(1)
		go parseUnigram(jobs, results, wg)
	}

	go func() {
		readFile(path, jobs)
	}()

	// Now collect all the results
	go func() {
		wg.Wait()
		// Make sure we close the result channel when everything was processed
		close(results)
	}()

	// Add up the unigrams
	unigrams := m.NewUnigrams()
	for b := range results {
		unigrams.Add(b)
	}

	return unigrams
}

// Parse bigrams from a given TSV file.
func Bigrams(path string) m.Bigrams {
	jobs := make(chan string, 5000)
	results := make(chan m.Bigram, 5000)

	wg := new(sync.WaitGroup)
	for w := 1; w <= 2; w++ {
		wg.Add(1)
		go parseBigram(jobs, results, wg)
	}

	go func() {
		readFile(path, jobs)
	}()

	// Now collect all the results
	go func() {
		wg.Wait()
		// Make sure we close the result channel when everything was processed
		close(results)
	}()

	// Add up the bigrams
	bigrams := m.NewBigrams()
	for b := range results {
		bigrams.Add(b)
	}

	return bigrams
}

// Parse a unigram.
func parseUnigram(jobs <-chan string, results chan<- m.Unigram, wg *sync.WaitGroup) {
	defer wg.Done()
	var fields []string

	for line := range jobs {
		fields = nil
		fields = strings.Split(line, "\t")
		rating, _ := strconv.ParseFloat(fields[1], 64)

		results <- m.Unigram{fields[0], rating}
	}
}

// Parse a bigram.
func parseBigram(jobs <-chan string, results chan<- m.Bigram, wg *sync.WaitGroup) {
	defer wg.Done()
	var fields []string

	for line := range jobs {
		fields = nil
		fields = strings.Split(line, "\t")
		rating, _ := strconv.ParseFloat(fields[2], 64)

		results <- m.Bigram{fields[0], fields[1], rating}
	}
}

// Read a file and put the content in a channel.
func readFile(path string, jobs chan<- string) chan<- string {
	scanner := bufio.NewScanner(strings.NewReader(path))
	for scanner.Scan() {
		jobs <- scanner.Text()
	}
	close(jobs)

	return jobs
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Processor\Subresource\Shared;

use Oro\Bundle\ApiBundle\Processor\GetConfig\CompleteDefinition\UnidirectionalAssociationCompleter;
use Oro\Bundle\ApiBundle\Processor\Subresource\SubresourceContext;
use Oro\Bundle\ApiBundle\Util\DoctrineHelper;
use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;

/**
 * Builds ORM QueryBuilder object that will be used to get a list of entities
 * for an unidirectional association for "get_relationship" and "get_subresource" actions.
 */
class BuildUnidirectionalAssociationSubresourceQuery implements ProcessorInterface
{
    /** @var DoctrineHelper */
    private $doctrineHelper;

    /**
     * @param DoctrineHelper $doctrineHelper
     */
    public function __construct(DoctrineHelper $doctrineHelper)
    {
        $this->doctrineHelper = $doctrineHelper;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContextInterface $context)
    {
        /** @var SubresourceContext $context */

        if ($context->hasQuery()) {
            // a query is already built
            return;
        }

        $parentConfig = $context->getParentConfig();
        if (null === $parentConfig) {
            // not supported API resource
            return;
        }

        $associationName = $context->getAssociationName();
        $unidirectionalAssociations = $parentConfig->get(
            UnidirectionalAssociationCompleter::UNIDIRECTIONAL_ASSOCIATIONS
        );
        if (!isset($unidirectionalAssociations[$associationName])) {
            // not unidirectional association
            return;
        }

        $targetEntityClass = $parentConfig->getField($associationName)->getTargetClass();
        $targetAssociationName = $unidirectionalAssociations[$associationName];
        $query = $this->doctrineHelper
            ->createQueryBuilder($targetEntityClass, 'e')
            ->innerJoin('e.' . $targetAssociationName, 'p')
            ->where('p = :' . AddParentEntityIdToQuery::PARENT_ENTITY_ID_QUERY_PARAM_NAME)
            ->setParameter(AddParentEntityIdToQuery::PARENT_ENTITY_ID_QUERY_PARAM_NAME, $context->getParentId());

        $context->setQuery($query);
    }
}


text:
#include "tensorflow/compiler/tf2xla/xla_context.h"

#include <memory>
#include <utility>
#include <vector>

#include "absl/types/span.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

const char XlaContext::kXlaContextResourceName[] = "_xla_context";

// Looks up the context associated with the current step. It is stored
// in a resource container managed by the device.
/* static */ XlaContext& XlaContext::Get(const OpKernelContext* ctx) {
  // When an Op kernel wants to use an XLA JIT context, the
  // per-step context is looked up in the resource manager. The
  // JIT will prepopulate the JITContext.
  XlaContext* context;
  TF_CHECK_OK(ctx->step_container()->Lookup(ctx->resource_manager(),
                                            kXlaContextResourceName, &context));
  // The resource manager handed us a fresh reference to 'context', but retains
  // a reference itself so the context won't be freed. The resource manager will
  // outlive the JIT compilation.
  context->Unref();
  return *context;
}

void XlaContext::set_args(std::vector<XlaExpression> args) {
  args_ = std::move(args);
}

XlaContext::XlaContext(XlaCompiler* compiler, xla::XlaBuilder* builder)
    : compiler_(compiler), builder_(builder) {}

string XlaContext::DebugString() const { return "XLA JIT context"; }

void XlaContext::SetRetval(int index, const XlaExpression& expression) {
  if (retvals_.size() <= index) {
    retvals_.resize(index + 1);
  }
  retvals_[index] = expression;
}

XlaResource* XlaContext::AddResource(std::unique_ptr<XlaResource> resource) {
  resources_.push_back(std::move(resource));
  return resources_.back().get();
}

const xla::XlaComputation* XlaContext::GetOrCreateMax(const DataType type) {
  return LookupOrCreate(type, &max_func_, [type] {
    const string type_string = DataTypeString(type);
    VLOG(1) << "Building Max() for " << type_string;
    xla::XlaBuilder b("max<" + type_string + ">");
    xla::PrimitiveType xla_type;
    TF_CHECK_OK(DataTypeToPrimitiveType(type, &xla_type));
    auto x =
        xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x");
    auto y =
        xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y");
    xla::Max(x, y);
    return b.Build().ConsumeValueOrDie();
  });
}

const xla::XlaComputation* XlaContext::GetOrCreateMin(const DataType type) {
  return LookupOrCreate(type, &min_func_, [type] {
    const string type_string = DataTypeString(type);
    VLOG(1) << "Building Min() for " << type_string;
    xla::XlaBuilder b("min<" + type_string + ">");
    xla::PrimitiveType xla_type;
    TF_CHECK_OK(DataTypeToPrimitiveType(type, &xla_type));
    auto x =
        xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x");
    auto y =
        xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y");
    xla::Min(x, y);
    return b.Build().ConsumeValueOrDie();
  });
}

const xla::XlaComputation* XlaContext::GetOrCreateAdd(const DataType type) {
  return LookupOrCreate(type, &add_func_, [type] {
    const string type_string = DataTypeString(type);
    VLOG(1) << "Building Add() for " << type_string;
    xla::XlaBuilder b("add<" + type_string + ">");
    xla::PrimitiveType xla_type;
    TF_CHECK_OK(DataTypeToPrimitiveType(type, &xla_type));
    auto x =
        xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x");
    auto y =
        xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y");
    xla::Add(x, y);
    return b.Build().ConsumeValueOrDie();
  });
}

const xla::XlaComputation* XlaContext::GetOrCreateMul(const DataType type) {
  return LookupOrCreate(type, &mul_func_, [type] {
    const string type_string = DataTypeString(type);
    VLOG(1) << "Building Mul() for " << type_string;
    xla::XlaBuilder b("mul<" + type_string + ">");
    xla::PrimitiveType xla_type;
    TF_CHECK_OK(DataTypeToPrimitiveType(type, &xla_type));
    auto x =
        xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x");
    auto y =
        xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y");
    xla::Mul(x, y);
    return b.Build().ConsumeValueOrDie();
  });
}

const xla::XlaComputation* XlaContext::LookupOrCreate(
    DataType type, ComputationMap* out,
    const std::function<xla::XlaComputation()>& create) {
  {
    const auto& entry = (*out)[type];
    if (!entry.IsNull()) {
      return &entry;
    }
  }
  auto new_entry = create();
  {
    // Somebody else might have made one concurrently.
    auto& entry = (*out)[type];
    if (entry.IsNull()) {
      entry = std::move(new_entry);
    }
    return &entry;
  }
}

}  // namespace tensorflow