text:
"""Tests for haiku._src.moving_averages."""

from absl.testing import absltest
from absl.testing import parameterized
from haiku._src import basic
from haiku._src import moving_averages
from haiku._src import multi_transform
from haiku._src import test_utils
from haiku._src import transform
import jax
import jax.numpy as jnp
import jax.random as random
import numpy as np
import tree

class MovingAveragesTest(parameterized.TestCase):

  @test_utils.transform_and_run
  def test_zero_decay(self):
    ema = moving_averages.ExponentialMovingAverage(0.)
    random_input = jax.random.uniform(jax.random.PRNGKey(428), shape=(2, 3, 4))

    # The ema should be equal to the input with decay=0.
    np.testing.assert_allclose(random_input[0], ema(random_input[0]))
    np.testing.assert_allclose(random_input[1], ema(random_input[1]))

  @test_utils.transform_and_run
  def test_warmup(self):
    ema = moving_averages.ExponentialMovingAverage(
        0.5, warmup_length=2, zero_debias=False)
    random_input = jax.random.uniform(jax.random.PRNGKey(428), shape=(2, 3, 4))

    # The ema should be equal to the input for the first two calls.
    np.testing.assert_allclose(random_input[0], ema(random_input[0]))
    np.testing.assert_allclose(random_input[0], ema(random_input[0]))

    # After the warmup period, with decay = 0.5 it should be halfway between the
    # first two inputs and the new input.
    np.testing.assert_allclose(
        (random_input[0] + random_input[1]) / 2, ema(random_input[1]))

  @test_utils.transform_and_run
  def test_invalid_warmup_length(self):
    with self.assertRaises(ValueError):
      moving_averages.ExponentialMovingAverage(
          0.5, warmup_length=-1, zero_debias=False)

  @test_utils.transform_and_run
  def test_warmup_length_and_zero_debias(self):
    with self.assertRaises(ValueError):
      moving_averages.ExponentialMovingAverage(
          0.5, warmup_length=2, zero_debias=True)

  @test_utils.transform_and_run
  def test_call(self):
    ema = moving_averages.ExponentialMovingAverage(0.5)
    self.assertAlmostEqual(ema(3.), 3.)
    self.assertAlmostEqual(ema(6.), 5.)

  @test_utils.transform_and_run
  def test_fast_slow_decay(self):
    ema_fast = moving_averages.ExponentialMovingAverage(0.2)
    ema_slow = moving_averages.ExponentialMovingAverage(0.8)
    np.testing.assert_allclose(ema_fast(1.), ema_slow(1.), rtol=1e-4)
    # Expect fast decay to increase more quickly than slow.
    self.assertGreater(ema_fast(2.), ema_slow(2.))

  @test_utils.transform_and_run
  def test_fast_slow_decay_without_update(self):
    ema_fast = moving_averages.ExponentialMovingAverage(0.5)
    ema_slow = moving_averages.ExponentialMovingAverage(0.8)
    # This shouldn't have an effect.
    np.testing.assert_allclose(
        ema_fast(1., update_stats=False),
        ema_slow(1., update_stats=False),
        rtol=1e-4)
    np.testing.assert_allclose(ema_fast(1.), ema_slow(1.), rtol=1e-4)
    self.assertGreater(ema_fast(2.), ema_slow(2.))

  def test_ema_is_identity_on_unchanged_data(self):
    def f(x):
      return moving_averages.ExponentialMovingAverage(0.5)(x)

    inp_value = 1.0
    init_fn, apply_fn = multi_transform.without_apply_rng(
        transform.transform_with_state(f))
    _, params_state = init_fn(None, inp_value)

    # The output should never change as long as the input doesn't.
    value = inp_value
    for _ in range(10):
      value, params_state = apply_fn(None, params_state, value)
      # Floating point error creeps up to 1e-7 (the default).
      np.testing.assert_allclose(inp_value, value, rtol=1e-6)

  @parameterized.parameters(True, False)
  @test_utils.transform_and_run
  def test_initialize(self, legacy_initialize):
    ema = moving_averages.ExponentialMovingAverage(0.99)
    if legacy_initialize:
      ema.initialize(jnp.ones([]))
    else:
      ema.initialize([])
    self.assertEqual(ema.average, 0.)
    ema(jnp.array(100.))

    # Matching the behavior of Sonnet 2 initialize only sets the value to zero
    # if the EMA has not already been initialized.
    if legacy_initialize:
      ema.initialize(jnp.ones([]))
    else:
      ema.initialize([])
    self.assertNotEqual(ema.average, 0.)

class EMAParamsTreeTest(absltest.TestCase):

  def test_ema_naming_scheme(self):
    ema_name = "this_is_a_wacky_but_valid_name"
    linear_name = "so_is_this"

    def f():
      return basic.Linear(output_size=2, name=linear_name)(jnp.zeros([6]))

    init_fn, _ = transform.transform(f)
    params = init_fn(random.PRNGKey(428))

    def g(x):
      return moving_averages.EMAParamsTree(0.2, name=ema_name)(x)
    init_fn, _ = transform.transform_with_state(g)
    _, params_state = init_fn(None, params)

    expected_ema_states = [
        "{}/{}__{}".format(ema_name, linear_name, s) for s in ["w", "b"]]
    self.assertEqual(set(expected_ema_states), set(params_state.keys()))

  def test_ema_on_changing_data(self):
    def f():
      return basic.Linear(output_size=2, b_init=jnp.ones)(jnp.zeros([6]))

    init_fn, _ = transform.transform(f)
    params = init_fn(random.PRNGKey(428))

    def g(x):
      return moving_averages.EMAParamsTree(0.2)(x)
    init_fn, apply_fn = multi_transform.without_apply_rng(
        transform.transform_with_state(g))
    _, params_state = init_fn(None, params)
    params, params_state = apply_fn(None, params_state, params)
    # Let's modify our params.
    changed_params = tree.map_structure(lambda t: 2. * t, params)
    ema_params, params_state = apply_fn(None, params_state, changed_params)

    # ema_params should be different from changed params!
    tree.assert_same_structure(changed_params, ema_params)
    for p1, p2 in zip(tree.flatten(params), tree.flatten(ema_params)):
      self.assertEqual(p1.shape, p2.shape)
      with self.assertRaisesRegex(AssertionError, "Not equal to tolerance"):
        np.testing.assert_allclose(p1, p2, atol=1e-6)

  def test_ignore_regex(self):
    def f():
      return basic.Linear(output_size=2, b_init=jnp.ones)(jnp.zeros([6]))

    init_fn, _ = transform.transform(f)
    params = init_fn(random.PRNGKey(428))

    def g(x):
      return moving_averages.EMAParamsTree(0.2, ignore_regex=".*w")(x)
    init_fn, apply_fn = multi_transform.without_apply_rng(
        transform.transform_with_state(g))
    _, params_state = init_fn(None, params)
    params, params_state = apply_fn(None, params_state, params)
    # Let's modify our params.
    changed_params = tree.map_structure(lambda t: 2. * t, params)
    ema_params, params_state = apply_fn(None, params_state, changed_params)

    # W should be the same!
    # ... but b should have changed!
    self.assertTrue(
        (changed_params["linear"]["b"] != ema_params["linear"]["b"]).all())
    self.assertTrue(
        (changed_params["linear"]["w"] == ema_params["linear"]["w"]).all())

  def test_tree_update_stats(self):
    def f():
      return basic.Linear(output_size=2, b_init=jnp.ones)(jnp.zeros([6]))

    init_fn, _ = transform.transform(f)
    params = init_fn(random.PRNGKey(428))

    def g(x):
      """This should never update internal stats."""
      return moving_averages.EMAParamsTree(0.2)(x, update_stats=False)
    init_fn, apply_fn_g = multi_transform.without_apply_rng(
        transform.transform_with_state(g))
    _, params_state = init_fn(None, params)

    # Let's modify our params.
    changed_params = tree.map_structure(lambda t: 2. * t, params)
    ema_params, params_state = apply_fn_g(None, params_state, changed_params)
    ema_params2, params_state = apply_fn_g(None, params_state, changed_params)

    # ema_params should be the same as ema_params2 with update_stats=False!
    for p1, p2 in zip(tree.flatten(ema_params2), tree.flatten(ema_params)):
      self.assertEqual(p1.shape, p2.shape)
      np.testing.assert_allclose(p1, p2)

    def h(x):
      """This will behave like normal."""
      return moving_averages.EMAParamsTree(0.2)(x, update_stats=True)
    init_fn, apply_fn_h = multi_transform.without_apply_rng(
        transform.transform_with_state(h))
    _, params_state = init_fn(None, params)
    params, params_state = apply_fn_h(None, params_state, params)

    # Let's modify our params.
    changed_params = tree.map_structure(lambda t: 2. * t, params)
    ema_params, params_state = apply_fn_h(None, params_state, changed_params)
    ema_params2, params_state = apply_fn_h(None, params_state, changed_params)

    # ema_params should be different as ema_params2 with update_stats=False!
    for p1, p2 in zip(tree.flatten(ema_params2), tree.flatten(ema_params)):
      self.assertEqual(p1.shape, p2.shape)
      with self.assertRaisesRegex(AssertionError, "Not equal to tolerance"):
        np.testing.assert_allclose(p1, p2, atol=1e-6)

if __name__ == "__main__":
  absltest.main()


text:
package com.ikuuy.locale.provider;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.spi.NumberFormatProvider;
import java.util.Locale;

import com.ikuuy.locale.util.ExtLocalesUtil;

/**
 * An implementation class for {@link NumberFormatProvider} which provides a
 * localized {@link NumberFormat}.
 *
 * @author Yuki Yamada
 *
 */
public class NumberFormatProviderImpl extends NumberFormatProvider {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Locale[] getAvailableLocales() {
		return ExtLocalesUtil.getAvailableLocales();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public NumberFormat getCurrencyInstance(final Locale locale) throws IllegalArgumentException, NullPointerException {
		return getInstance("CurrencyPattern", locale);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public NumberFormat getIntegerInstance(final Locale locale) throws IllegalArgumentException, NullPointerException {
		NumberFormat format = getInstance("IntegerPattern", locale);
		format.setParseIntegerOnly(true);
		return format;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public NumberFormat getNumberInstance(final Locale locale) throws IllegalArgumentException, NullPointerException {
		return getInstance("NumberPattern", locale);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public NumberFormat getPercentInstance(final Locale locale) throws IllegalArgumentException, NullPointerException {
		return getInstance("PercentPattern", locale);
	}

	/**
	 * Returns a new NumberFormat instance for the specified key and locale.
	 *
	 * @param key the property key.
	 * @param locale the desired locale.
	 * @return a number formatter.
	 * @throws IllegalArgumentException if locale isn't available.
	 * @throws NullPointerException if locale is null.
	 */
	protected NumberFormat getInstance(final String key, final Locale locale) throws IllegalArgumentException,
			NullPointerException {
		if (locale == null) {
			throw new NullPointerException("locale:null");
		} else if (!ExtLocalesUtil.isAvailableLocale(locale, getAvailableLocales())) {
			throw new IllegalArgumentException("locale:" + locale.toString());
		}

		DecimalFormat format = new DecimalFormat();
		format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(locale));

		String pattern = ExtLocalesUtil.getString(key, locale);
		format.applyPattern(pattern);

		return format;
	}
}

redpajama_set_name: RedPajamaGithub


text:
exports.defineTags = function(dictionary) {
  function hasUrlPrefix(text) {
    return (/^(http|ftp)s?:\/\//).test(text);
  }

  dictionary.defineTag('ngdoc', {
    mustHaveValue: true,
    onTagged : function(doclet, tag) {
      if (tag.value == "method") {
        doclet.addTag('kind', 'function');
      } else {
        doclet.addTag('kind', 'class');
      }
      doclet.ngdoc = tag.value;
    }
  });

  dictionary.defineTag('attribute', {
    mustHaveValue: true,
    canHaveType: true,
    canHaveName: true,
    onTagged: function(doclet, tag) {
      if (!doclet.attributes) { doclet.attributes = []; }
      doclet.attributes.push(tag.value);
    }
  })
  .synonym('attr');

  dictionary.defineTag('restrict', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      var restricts={
          'A': 'Attribute',
          'E': 'Element',
          'C': 'Class'
      }
      var s = tag.value.split('').map(function(aec) {
        return restricts[aec];
      })
      doclet.restrict = s;
    }
  });

  dictionary.defineTag('priority', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.priority = tag.value;
    }
  });

  dictionary.defineTag('eventType', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.eventType = tag.value;
    }
  });

  dictionary.defineTag('animations', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      doclet.animations = tag.value;
    }
  });

  dictionary.defineTag('scope', {
    onTagged: function(doclet, tag) {
      var scopeType={
        'object': '\'isolate\' scope',
        '{}': '\'isolate\' scope',
        'true': 'scope which prototypically inherits from its parent',
        'false': 'shared scope'
      }
      var s = function() {
        return scopeType[tag.value];
      }();
      if (!tag.value || !s) {
        doclet.scopeType = 'scope';
      } else {
        doclet.scopeType = s;
      }
      doclet.newScope = !(s == 'shared scope');
    }
  });

  dictionary.defineTag('description', {
    mustHaveValue: true,
    onTagged: function(doclet, tag) {
      var helper = require('jsdoc/util/templateHelper');

      // replace inline link tags
      tag.value = require('jsdoc/tag/inline').replaceInlineTag(tag.value, 'link', function(string, matchedTag) {
        var match;
        var longname;
        var text;
        var fragmentId;
        var link;

        if ( hasUrlPrefix(matchedTag.text) ) {
          match = /(\S+)\s(\S+)/.exec(matchedTag.text);
          if (match) {
            longname = match[1];
            text = match[2] || match[1];
          }
        }
        else {
          match = /(\S+)#(methods|properties|events)_(\S+)\s(\S+)/.exec(matchedTag.text);
          if (match) {
            longname = match[1];
            text = match[4] || match[3];
            fragmentId = match[3];
            helper.registerLink(longname, longname + '.html');
          }
        }

        link = helper.linkto(longname, helper.htmlsafe(text), null, fragmentId);
        return tag.value.replace(new RegExp(require('escape-string-regexp')(matchedTag.completeTag), 'g'), link);
      }).newString;
    },
    synonyms: ['desc']
  });
};


text:
package mobileoak.volleyballtracker.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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

import mobileoak.volleyballtracker.R;
import mobileoak.volleyballtracker.model.Card;
import mobileoak.volleyballtracker.model.Player;

public class StartActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        Button rosterButton = (Button) findViewById(R.id.manage_button);
        rosterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                startActivity(new Intent(StartActivity.this, RosterActivity.class));
            }
        });

        Button runGames = (Button) findViewById(R.id.run_games);
        runGames.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                startActivity(new Intent(StartActivity.this, CheckinActivity.class));
            }
        });

        Button sendScores = (Button) findViewById(R.id.email_scores);
        sendScores.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                startActivity(new Intent(StartActivity.this, EmailScoresActivity.class));
            }
        });

        Button createDatabase = (Button) findViewById(R.id.create_players);
        createDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                List<Player> mPlayers = new ArrayList<Player>();
                mPlayers.add(new Player("Carl Anderson", new Card(Card.CLUB, "2")));
                mPlayers.add(new Player("Andrew Kaiser", new Card(Card.SPADE, "A")));
                mPlayers.add(new Player("Wade Fasano", new Card(Card.SPADE, "K")));
                mPlayers.add(new Player("Courtney Fasano", new Card(Card.DIAMOND, "Q")));
                mPlayers.add(new Player("Devon Crawford", new Card(Card.HEART, "5")));
                mPlayers.add(new Player("Jennifer Clack", new Card(Card.HEART, "7")));
                mPlayers.add(new Player("Julia Clack", new Card(Card.HEART, "6")));
                mPlayers.add(new Player("Bogdan Fetsek", new Card(Card.CLUB, "A")));
                mPlayers.add(new Player("Ian Lee", new Card(Card.CLUB, "7")));
                mPlayers.add(new Player("Kyle May", new Card(Card.SPADE, "10")));
                mPlayers.add(new Player("Tom Knight", new Card(Card.SPADE, "J")));

            }
        });

        Button deleteDatabase = (Button) findViewById(R.id.delete_database);
        deleteDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

}


text:
package policy

// Transformations defines a structure for a collection of transformations to be applied.
type Transformations struct {
	Tmpl Transformation
	Mtch Transformation
	Rslt Transformation
}

// NewTransformations creates a collection of transformations to be applied.
// NewTransformations returns a pointer to a collection if exactly 3 types of transformations are specified, otherwise nil is returned.
func NewTransformations(tr ...*Transformation) (trs *Transformations) {
	if len(tr) != 3 {
		trs = nil
	} else {
		trc := make([]Transformation, len(tr))

		// Make a copy of the transformations.
		for i := range tr {
			if tr[i] != nil {
				trans := tr[i]
				function := trans.Function()
				params := trans.Parameters()
				ntr := NewTransformation(function, params...)
				trc[i] = ntr
			} else {
				trc[i] = Transformation{}
			}
		}

		trs = &Transformations{Tmpl: trc[0], Mtch: trc[1], Rslt: trc[2]}
	}

	return trs
}

// Template returns a transformation that can be applied to template entities.
func (trs *Transformations) Template() (trans *Transformation) {
	trans = nil

	if trs != nil {
		trans = &trs.Tmpl
	}

	return trans
}

// Match returns an transformation that can be applied to matched entities.
func (trs *Transformations) Match() (match *Transformation) {
	match = nil

	if trs != nil {
		match = &trs.Mtch
	}

	return match
}

// Result returns an transformation that can be applied to result entities.
func (trs *Transformations) Result() (rslt *Transformation) {
	rslt = nil

	if trs != nil {
		rslt = &trs.Rslt
	}

	return rslt
}


text:
/* line 2, /Users/yamadanaoki/Documents/workspace/dev.cm/middleman/source/assets/stylesheets/18/colorpalette.scss */
.well .page-header {
  margin-top: 0; }


text:
FROM jlawton/ubuntu-dev:latest
MAINTAINER Jim Lawton

RUN apt-get -y update

RUN apt-get -y install python
RUN apt-get -y install python-dev
RUN apt-get -y install python-pip

RUN pip install virtualenv


text:
package com.ggj.java.rpc.demo.first;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author gaoguangjin
 */
@Slf4j
public class RPCClient {
    public static void main(String[] args) {
        client();
    }

    public static void client() {
        Socket socket = null;
        try {
            socket = new Socket("localhost", 8081);
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            printWriter.println(JSONObject.toJSON(new RpcBean("com.ggj.java.rpc.demo.first.TestServiceImpl", "testMethod", "ddd")));
            printWriter.flush();
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String readLine = null;
            while ((readLine = bufferedInputStream.readLine()) != null) {
                log.info("get client message {}", readLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


text:
package com.google.cloud.runtimes.jetty9;

import com.google.cloud.ServiceOptions;
import com.google.cloud.logging.TraceLoggingEnhancer;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.handler.ContextHandler.ContextScopeListener;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A Jetty {@link ContextScopeListener} that is called whenever a container managed thread enters or
 * exits the scope of a context and/or request. Used to maintain {@link ThreadLocal} references to
 * the current request and Google traceID, primarily for logging.
 *
 * @see TraceLoggingEnhancer
 */
public class RequestContextScope implements ContextHandler.ContextScopeListener {

  static final Logger logger = Logger.getLogger(RequestContextScope.class.getName());

  private static final String X_CLOUD_TRACE = "x-cloud-trace-context";
  private static final ThreadLocal<Integer> contextDepth = new ThreadLocal<>();

  private final String projectId = ServiceOptions.getDefaultProjectId();

  @Override
  public void enterScope(Context context, Request request, Object reason) {
    if (logger.isLoggable(Level.FINE)) {
      logger.fine("enterScope " + context);
    }
    if (request != null) {
      Integer depth = contextDepth.get();
      if (depth == null || depth.intValue() == 0) {
        contextDepth.set(1);
        String currentTraceId = (String) request.getAttribute(X_CLOUD_TRACE);
        if (currentTraceId == null) {
          // extract xCloud Trace in format: TRACE_ID/SPAN_ID;o=TRACE_TRUE
          String cloudTrace = request.getHeader(X_CLOUD_TRACE);
          if (cloudTrace != null) {
            int split = cloudTrace.indexOf('/');
            if (split < 0) {
              split = cloudTrace.indexOf(';');
            }
            String traceId = split >= 0 ? cloudTrace.substring(0, split) : cloudTrace;
            if (traceId != null) {
              currentTraceId = String.format("projects/%s/traces/%s", projectId, traceId);
              request.setAttribute(X_CLOUD_TRACE, currentTraceId);
              TraceLoggingEnhancer.setCurrentTraceId(currentTraceId);
            }
          }
        }
      } else {
        contextDepth.set(depth + 1);
      }
    }
  }

  @Override
  public void exitScope(Context context, Request request) {
    if (logger.isLoggable(Level.FINE)) {
      logger.fine("exitScope " + context);
    }
    Integer depth = contextDepth.get();
    if (depth != null) {
      if (depth > 1) {
        contextDepth.set(depth - 1);
      } else {
        contextDepth.remove();
        TraceLoggingEnhancer.setCurrentTraceId(null);
      }
    }
  }
}


text:
TopStackMetricSearch
====================

TopStack service to search metrics (AWS CloudWatch compatible).


text:
<?php
namespace FW\Log;

class Log implements \Psr\Log\LoggerInterface
{
	private $backtrace = '';
	public function __construct()
	{
		$i = 1;
		$tmp = debug_backtrace();
		foreach($tmp as $v) {
			$this->backtrace .= $i++.') '.$v['file'].'('.$v['line'].'): '.($v['class'] ?? '').($v['type'] ?? '').($v['function'] ?? '')."\r\n";
		}
	}

	private function mail($error)
	{
		$res = \q("SELECT `timer` FROM `fw_log_timer` WHERE `timer` < NOW() - INTERVAL 10 MINUTE");
		if($res->num_rows) {
			\q("UPDATE `fw_log_timer` SET `timer` = NOW()");

			try {
				$mail = new \MailProxy(true);

				$mail->Subject = \Core::$DOMAIN.': произошла критическая ошибка!';
				$mail->msgHTML('
'.$error.'

Backtrace:
'.nl2br(htmlspecialchars($this->backtrace)).'
');

				foreach(\Core::$ALARMMAIL as $v) {
					$mail->addAddress(\Core::$ALARMMAIL);
					$mail->send();
				}
			} catch(\Exception $e) {
				(new Log())->error('Mail notification not working: '.$e->getMessage());
			}
		}
	}

	private function file($error)
	{
		$error = $error."\r\n".
			'--date: '.date("Y-m-d H:i:s")."\r\n".
			"Trace:\r\n".
			$this->backtrace.
			"\r\n===================================";

		file_put_contents('./logs/mysql.log',$error."\r\n\r\n",FILE_APPEND);

	}

	private function mysql($error)
	{
		\q("
			INSERT INTO `fw_log` SET
			`page` = '".\es($_GET['route'] ?? '')."',
			`text` = '".\es($error)."',
			`ip` = '".\es($_SERVER['REMOTE_ADDR'] ?? '')."'
		");
	}

	private function notification($error)
	{
		\q("
			INSERT INTO `fw_log_notification` SET
			`title` = 'Ошибка на сервере',
			`text` = '".\es($error)."\r\nTrace:\r\n".\es($this->backtrace)."',
			`key` = 'role',
			`value` = 'admin'
		");
	}

	private function sms($error)
	{
		if(!count(\Core::$ERRORS['sms_phone'])) {
			(new Log)->alert('SMS PHONE not insered');
		} elseif(empty(\Core::$ERRORS['sms_login']) || empty(\Core::$ERRORS['sms_pass'])) {
			(new Log)->alert('SMS LOGIN or PASS not insered');
		}

		file_get_contents('https://smsc.ru/sys/send.php?login='.\Core::$ERRORS['sms_login'].'&psw='.mb_strtolower(md5(\Core::$ERRORS['sms_pass'])).'&phones='.implode(',', \Core::$ERRORS['sms_phone']).'&mes='.mb_substr($error,0,60));
	}

	public function emergency($message, array $context = array())
	{
		return $this->alert($message, $context);
	}

	public function alert($message, array $context = array())
	{
		if(\Core::$ERRORS['sms']) {
			$this->sms($message);
		}

		if(\Core::$ERRORS['mail']) {
			$this->mail($message);
		}

		return $this->critical($message, $context);
	}

	public function critical($message, array $context = array())
	{
		return $this->error($message, $context);
	}

	public function error($message, array $context = array())
	{
		if(\Core::$ERRORS['file']) {
			$this->file($message);
		}

		if(\Core::$ERRORS['mysql']) {
			$this->mysql($message);
		}

		if(\Core::$ERRORS['notification']) {
			$this->notification($message);
		}

		return $this->warning($message, $context);
	}

	public function warning($message, array $context = array())
	{
		return $this->notice($message, $context);
	}

	public function notice($message, array $context = array())
	{
		return $this->info($message, $context);
	}

	public function info($message, array $context = array())
	{
		return $this->debug($message, $context);
	}

	public function debug($message, array $context = array())
	{
		if(\Core::$ERRORS['show']) {

		}

		return $this->log($message, $context);
	}

	public function log($level, $message, array $context = array())
	{
		return true;
	}
}


text:
namespace dragon {

#ifdef WITH_MPI

template <class Context>
class CollectiveUpdateOp : public Operator<Context> {
 public:
     CollectiveUpdateOp(const OperatorDef& op_def, Workspace* ws)
        : Operator<Context>(op_def, ws),
          mode(OperatorBase::GetSingleArg<string>("mode", "UNKNOWN")) {
         InitMPI();
         if (mode.find("NCCL") != string::npos) InitNCCL();
     }

    void InitMPI();
    void InitNCCL();

    void RunOnDevice() override;
    void MPIAllReduceWithFloat();
    void NCCLAllReduceWithFloat();
    void MPIBcastWithFloat();
    void NCCLBcastWithFloat();

 protected:
    int comm_size, comm_rank, comm_root;
    int world_size, world_rank;
    Tensor* buffer;
    string  mode;

    MPI_Comm comm;
    MPI_Group group;

#ifdef WITH_MPI_NCCL
    ncclComm_t nccl_comm;
    cudaStream_t stream;
#endif
};

#endif    // WITH_MPI

}    // namespace dragon

#endif    // DRAGON_OPERATORS_UPDATE_COLLECTIVE_UPDATE_OP_H_


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.ui.modeler.model;

public class FormFieldSummaryRepresentation {

    protected String id;
    protected String name;
    protected String type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


text:
function Usage() {
	set +ex
	echo >&2 "
Runs GTest executables created by scons in alljoyn_core, common, or services/about.

Usage: $(basename -- "$0") [ -s -d alljoyn_dist ] [ -t alljoyn_test ] [-c configfile ] [ ajtest ] [ cmtest ] ...
where
	-s              # start and stop our own AllJoyn-Daemon (default internal transport address, --no-bt)

	-d alljoyn_dist # path to the build/.../dist tree, used to find cpp/bin/alljoyn-daemon exe, if used

	-t alljoyn_test # path to the build/.../test tree, used to find cpp/bin/cmtest exe, ajtest exe, ...
				# Note: do not include the 'cpp/bin' subpath in alljoyn_dist or alljoyn_test

	-c configfile   # name of config file(s) (an embedded wildcard is replaced by the gtest test name)
				#  default '*.conf'

	ajtest, cmtest, and/or abouttest
				# simple file name(s) of the gtest exe(s) to be run (found in -t path/cpp/bin)
				#  default runs ajtest and cmtest
"
	exit 2
}

: read commandline options

set -e

start_daemon=false
alljoyn_dist=''
alljoyn_test=''
configfile='*.conf'

while getopts sSc:d:t: option
do
	case "$option" in
	( c ) configfile="$OPTARG" ;;
	( d ) alljoyn_dist="$OPTARG" ;;
	( t ) alljoyn_test=$OPTARG ;;
	( s ) start_daemon=true ;;
	( S ) start_daemon=false ;;
	( \? ) Usage ;;
	esac
done

gtests=''
if test "$OPTIND" -gt 0 -a "$OPTIND" -le $#
then
	shift ` expr $OPTIND - 1 `
	while test $# -ge 1
	do
		case "$1" in
		( *[!a-zA-Z0-9_-]* | '' ) echo >&2 "error, $1:  allowed characters are [a-zA-Z0-9_-]" ; Usage ;;
		( * ) gtests="$gtests $1" ;;
		esac
		shift
	done
fi

if test -z "$gtests"
then
	gtests="ajtest cmtest"
fi

: check commandline options

# alljoyn_dist, alljoyn_test paths
if test -z "$alljoyn_dist" -a -z "$alljoyn_test"
then
	echo >&2 "error, -d and/or -t path is required"
	Usage
elif test -z "$alljoyn_dist"
then
	alljoyn_dist="$alljoyn_test/../dist"
elif test -z "$alljoyn_test"
then
	alljoyn_test="$alljoyn_dist/../test"
fi

ckbin() {
	ckvar=$1
	binvar=$2
	eval ckval="\$$1"
	binval=` cd "$ckval/cpp/bin" > /dev/null && pwd ` || : ok
	if test -z "$binval"
	then
		echo >&2 "error, could not find 'cpp/bin' subdirectory in $ckvar=$ckval"
		exit 2
	fi
	eval $binvar="'$binval'"
}

ckbin alljoyn_dist daemon_bin
ckbin alljoyn_test gtest_bin

if cygpath -wa . > /dev/null 2>&1
then
	# found Cygwin, which means Windows

	if $start_daemon; then
		echo >&2 "error, start_daemon=true but this is Windows and daemon is not supported"
		exit 2
	fi

	# gtest_bin needs to be Windows-style because we use pure Windows Python, not Cygwin Python
	gtest_bin_p="$( cygpath -wa "$gtest_bin" )"
	# sometimes Windows "home" does not work for keystore tests
	export USERPROFILE="$( cygpath -wa . )"
	export LOCALAPPDATA="$USERPROFILE"
elif pwd -W > /dev/null 2>&1
then
	# found MSysGit, which also means Windows

	if $start_daemon; then
		echo >&2 "error, start_daemon=true but this is Windows and daemon is not supported"
		exit 2
	fi

	# MSysGit will handle the *nix path
	gtest_bin_p=$gtest_bin
	# sometimes Windows "home" does not work for keystore tests
	export USERPROFILE="$( pwd -W )"
	export LOCALAPPDATA="$USERPROFILE"
else
	options='--internal --no-bt --verbosity=5'
	gtest_bin_p="$gtest_bin"
	# MBUS-1589: remove .alljoyn_keystore, if any
	export HOME="$PWD"
fi
# MBUS-1589: remove .alljoyn_keystore, if any
rm -rf .alljoyn_keystore

echo "# runall test plan:"
if $start_daemon
then
	ls >/dev/null -ld "$daemon_bin/alljoyn-daemon" || ls >/dev/null -ld "$daemon_bin/alljoyn-daemon.exe" || {
		echo >&2 "error, alljoyn-daemon exe not found"
		exit 2
	}
	echo "# $daemon_bin/alljoyn-daemon $options > alljoyn-daemon.log &"
fi

for i in $gtests
do
	ls >/dev/null -ld "$gtest_bin/$i" || ls >/dev/null -ld "$gtest_bin/$i.exe" || {
		echo >&2 "error, $i exe not found"
		exit 2
	}
	c="$( echo "$configfile" | sed -e 's,\*,'$i',g' )"
	ls >/dev/null -ld "$c" || {
		echo >&2 "error, configfile $c not found"
		exit 2
	}
	echo "# python test_harness.py -c $c -t $i -p $gtest_bin_p > $i.log"
done

: begin

export ER_DEBUG_ALL=0

if $start_daemon
then

	: start alljoyn-daemon

	rm -f alljoyn-daemon.log

	killall -9 -v alljoyn-daemon || : ok
	(
		set -ex
		cd "$daemon_bin"
		pwd
		date

		./alljoyn-daemon $options; xit=$?

		date
		set +x
		echo exit status $xit
	) > alljoyn-daemon.log 2>&1 </dev/null &

	sleep 5
fi

: run gtest executables

xit=0
for i in $gtests
do
	# configfile for gtest $i
	c="$( echo "$configfile" | sed -e 's,\*,'$i',g' )"

	rm -f "$i.log"

	sleep 5
	set -x
	: run $i

	date
	python -u test_harness.py -c $c -t $i -p "$gtest_bin_p" > "$i.log" 2>&1 < /dev/null || : exit status is $? / IGNORE IT
	date
	set +x
	tail -10 "$i.log" | grep "exiting with status 0" || xit=1

	case "$xit" in
	0 ) echo $i PASSED ;;
	* ) echo $i FAILED, see $i.log for info ;;
	esac

	sleep 5
done

if $start_daemon
then
	sleep 5
	killall -9 -v alljoyn-daemon || : ok
	sleep 5
fi

echo exit status $xit
exit $xit


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE123_Write_What_Where_Condition__listen_socket_84_goodG2B.cpp
Label Definition File: CWE123_Write_What_Where_Condition.label.xml
Template File: sources-sink-84_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 123 Write-What-Where Condition
 * BadSource: listen_socket Overwrite linked list pointers using a listen socket (server side)
 * GoodSource: Don't overwrite linked list pointers
 * Sinks:
 *    BadSink : Remove element from list
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE123_Write_What_Where_Condition__listen_socket_84.h"

namespace CWE123_Write_What_Where_Condition__listen_socket_84
{
CWE123_Write_What_Where_Condition__listen_socket_84_goodG2B::CWE123_Write_What_Where_Condition__listen_socket_84_goodG2B(badStruct dataCopy)
{
    data = dataCopy;
    /* FIX: don't overwrite linked list pointers */
    ; /* empty statement needed by some flow variants */
}

CWE123_Write_What_Where_Condition__listen_socket_84_goodG2B::~CWE123_Write_What_Where_Condition__listen_socket_84_goodG2B()
{
    /* POTENTIAL FLAW: The following removes 'a' from the list.  Because of the possible overflow this
     * causes a "write-what-where" aka "write4".  It does another write as
     * well.  But this is the prototypical "write-what-where" at least from
     * the Windows perspective.
     *
     * linkedListPrev = a->list->prev  WHAT
     * linkedListNext = a->list->next  WHERE
     * linkedListPrev->next = linkedListNext  "at the address that prev/WHERE points, write
     *                    next/WHAT"
     *                    aka "write-what-where"
     * linkedListNext->prev = linkedListPrev  "at the address that next/WHAT points plus 4
     *                    (because prev is the second field in 'list' hence
     *                    4 bytes away on 32b machines), write prev/WHERE"
     */
    linkedListPrev = data.list.prev;
    linkedListNext = data.list.next;
    linkedListPrev->next = linkedListNext;
    linkedListNext->prev = linkedListPrev;
}
}
#endif /* OMITGOOD */


text:
<?php

class LS_ImportUtil {

	/**
	 * The managed ZipArchieve instance.
	 */
	private $zip;

	/**
	 * Target folders
	 */
	private $targetDir, $targetURL, $tmpDir;

	// Imported images
	private $imported = array();

	// Accepts $_FILES
	public function __construct($archive, $name = null) {

		if(empty($name)) {
			$name = $archive;
		}

		// TODO: check file extension to support old import method
		$type = wp_check_filetype(basename($name), array(
			'zip' => 'application/zip',
			'json' => 'application/json'
		));

		// Check for ZIP
		if(!empty($type['ext']) && $type['ext'] == 'zip') {
			if(class_exists('ZipArchive')) {

				$this->zip = new ZipArchive;
				if($this->zip->open($archive)) {
					if($this->unpack($archive)) {

						// Uploaded folders
						foreach(glob($this->tmpDir.'/*', GLOB_ONLYDIR) as $key => $dir) {

							$this->imported = array();
							$this->uploadMedia($dir);

							if(file_exists($dir.'/settings.json')) {
								$this->addSlider($dir.'/settings.json');
							}
						}

						// Finishing up
						$this->cleanup();
						return true;
					}

					// Close ZIP
					$this->zip->close();
				}
			} else {
				header('Location: admin.php?page=layerslider&error=1&message=exportZipError');
				die();
			}

		// Check for JSON
		} elseif(!empty($type['ext']) && $type['ext'] == 'json') {

			// Get decoded file data
			$data = base64_decode(file_get_contents($archive));

			// Parsing JSON or PHP object
			if(!$parsed = json_decode($data, true)) {
				$parsed = unserialize($data);
			}

			// Iterate over imported sliders
			if(is_array($parsed)) {

				// Import sliders
				foreach($parsed as $item) {

					// Fix for export issue in v4.6.4
					if(is_string($item)) { $item = json_decode($item, true); }

					LS_Sliders::add($item['properties']['title'], $item);
				}
			}
		}

		// Return false otherwise
		return false;
	}

	public function unpack($archive) {

		// Get uploads folder
		$uploads = wp_upload_dir();

		// Check if /uploads dir is writable
		if(is_writable($uploads['basedir'])) {

			// Get target folders
			$this->targetDir = $targetDir = $uploads['basedir'].'/layerslider';
			$this->targetURL = $uploads['baseurl'].'/layerslider';
			$this->tmpDir = $tmpDir = $uploads['basedir'].'/layerslider/tmp';

			// Create necessary folders under /uploads
			if(!file_exists($targetDir)) { mkdir($targetDir, 0755); }
			if(!file_exists($targetDir)) { mkdir($targetDir, 0755); }

			// Unpack archive
			if($this->zip->extractTo($tmpDir)) {
				return true;
			}
		}

		return false;
	}

	public function uploadMedia($dir = null) {

		// Check provided data
		if(empty($dir) || !is_string($dir) || !file_exists($dir.'/uploads')) {
			return false;
		}

		// Create folder if it isn't exists already
		$targetDir = $this->targetDir . '/' . basename($dir);
		if(!file_exists($targetDir)) { mkdir($targetDir, 0755); }

		// Include image.php for media library upload
		require_once(ABSPATH.'wp-admin/includes/image.php');

		// Iterate through directory
		foreach(glob($dir.'/uploads/*') as $filePath) {

			$fileName = sanitize_file_name(basename($filePath));
			$targetFile = $targetDir.'/'.$fileName;

			// Validate media
			$filetype = wp_check_filetype($fileName, null);
			if(!empty($filetype['ext']) && $filetype['ext'] != 'php') {

				// Move item to place
				rename($filePath, $targetFile);

				// Upload to media library
				$attachment = array(
					'guid' => $targetFile,
					'post_mime_type' => $filetype['type'],
					'post_title' => preg_replace( '/\.[^.]+$/', '', $fileName),
					'post_content' => '',
					'post_status' => 'inherit'
				);

				$attach_id = wp_insert_attachment($attachment, $targetFile, 37);
				if($attach_data = wp_generate_attachment_metadata($attach_id, $targetFile)) {
					wp_update_attachment_metadata($attach_id, $attach_data);
				}

				$this->imported[$fileName] = array(
					'id' => $attach_id,
					'url' => $this->targetURL.'/'.basename($dir).'/'.$fileName
				);
			}
		}

		return true;
	}

	public function deleteDir($dirPath) {

		if(!is_dir($dirPath)) {
			return false;
		}
		if(substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
			$dirPath .= '/';
		}
		$files = glob($dirPath . '*', GLOB_MARK);
		foreach($files as $file) {
			if(is_dir($file)) {
				$this->deleteDir($file);
			} else {
				unlink($file);
			}
		}
		rmdir($dirPath);
	}

	public function addSlider($file) {

		// Get slider data and title
		$data = json_decode(file_get_contents($file), true);
		$title = $data['properties']['title'];

		// Slider settings
		if(!empty($data['properties']['backgroundimage'])) {
			$data['properties']['backgroundimage'] = $this->attachURLForImage(
				$data['properties']['backgroundimage']
			);
		}

		if(!empty($data['properties']['yourlogo'])) {
			$data['properties']['yourlogoId'] = '';
			$data['properties']['yourlogo'] = $this->attachURLForImage(
				$data['properties']['yourlogo']
			);
		}

		// Slides
		if(!empty($data['layers']) && is_array($data['layers'])) {
		foreach($data['layers'] as &$slide) {

			if(!empty($slide['properties']['background'])) {
				$slide['properties']['backgroundId'] = '';
				$slide['properties']['background'] = $this->attachURLForImage(
					$slide['properties']['background']
				);
			}

			if(!empty($slide['properties']['thumbnail'])) {
				$slide['properties']['thumbnailId'] = '';
				$slide['properties']['thumbnail'] = $this->attachURLForImage(
					$slide['properties']['thumbnail']
				);
			}

			// Layers
			if(!empty($slide['sublayers']) && is_array($slide['sublayers'])) {
			foreach($slide['sublayers'] as &$layer) {

				if(!empty($layer['image'])) {
					$layer['imageId'] = '';
					$layer['image'] = $this->attachURLForImage($layer['image']);
				}
			}}
		}}

		// Add slider
		LS_Sliders::add($title, $data);
	}

	public function attachURLForImage($file = '#') {

		if(isset($this->imported[basename($file)])) {
			return $this->imported[basename($file)]['url'];
		}

		return $file;
	}

	public function cleanup() {
		$this->deleteDir($this->tmpDir);
	}
}
?>


text:
<?php

// PDO socket
// Or using socket would be even faster then 127.0.0.1 :3
define('POMF_DB_CONN', 'mysql:host=127.0.0.1;dbname=madokami');
// MySQL user and password
define('POMF_DB_USER', getenv('POMF_DB_USER'));
define('POMF_DB_PASS', getenv('POMF_DB_PASS'));

// Root location of files
define('POMF_FILES_ROOT', '/srv/http/madokami_com/data/');
// Maximum number of iterations while generating a new name
define('POMF_FILES_RETRIES', 15);
// URL to prepend to output (include trailing slash)
define('POMF_URL', 'https://madokami.com/');

$doubledots = array_map('strrev', array(
	'tar.gz',
	'tar.bz',
	'tar.bz2',
	'tar.xz',
	'user.js'
));

?>


text:
TCP Output Plugin for FluentBit

Info on FluentBit: https://github.com/fluent/fluent-bit

Info on Golang Output Plugins for FluentBit: https://github.com/fluent/fluent-bit-go


text:
package org.elasticsearch.xpack.transform.action.compat;

import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.transform.action.compat.GetTransformActionDeprecated;
import org.elasticsearch.xpack.transform.action.TransportGetTransformAction;

public class TransportGetTransformActionDeprecated extends TransportGetTransformAction {

    @Inject
    public TransportGetTransformActionDeprecated(TransportService transportService, ActionFilters actionFilters, Client client,
            NamedXContentRegistry xContentRegistry) {
        super(GetTransformActionDeprecated.NAME, transportService, actionFilters, client, xContentRegistry);
    }

}


text:
FROM java:8
ADD todomanager.jar app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-Dspring.profiles.active=container","-jar","/app.jar"]


text:
<!DOCTYPE html><meta charset="UTF-8" /><title>Source Code</title>
<%--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--%>
<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
<html>
  <head>
    <title>JSP 2.0 Examples - Hello World SimpleTag Handler</title>
  </head>
  <body>
    <h1>JSP 2.0 Examples - Hello World SimpleTag Handler</h1>
    <hr>
    <p>This tag handler simply echos "Hello, World!"  It's an example of
    a very basic SimpleTag handler with no body.</p>
    <br>
    <b><u>Result:</u></b>
    <mytag:helloWorld/>
  </body>
</html>


text:
using System;
using Haven;
using Haven.Net;
using NLog;
using OpenTK.Input;
using SharpHaven.Graphics;
using SharpHaven.Graphics.Text;
using SharpHaven.Input;
using SharpHaven.UI;
using SharpHaven.UI.Widgets;

namespace SharpHaven.Login
{
	public class LoginScreen : BaseScreen
	{
		private static readonly Logger Log = LogManager.GetCurrentClassLogger();

		private const int MinWidth = 800;
		private const int MinHeight = 600;

		private readonly Login login;

		private Container cntPassword;
		private TextBox tbUserName;
		private TextBox tbPassword;
		private CheckBox chkRemember;
		private Label lblErrorMessage;

		private Container cntToken;
		private Label lblUserName;
		private Button btnForget;

		private Label lbProgress;
		private ImageButton btnLogin;

		public LoginScreen(GameClient client)
		{
			login = new Login(client);
			login.Finished += Finish;

			InitWidgets();
			GotoInitialPage();
			RootWidget.KeyDown += OnKeyDown;
		}

		public event Action LoginCompleted;

		private void InitWidgets()
		{
			var background = new Image(RootWidget);
			background.Drawable = App.Resources.Get<Drawable>("gfx/loginscr");
			background.Move(0, 0);
			background.Resize(background.Drawable.Size);

			var logo = new Image(RootWidget);
			logo.Drawable = App.Resources.Get<Drawable>("gfx/logo");
			logo.Move(420 - logo.Drawable.Width / 2, 215 - logo.Drawable.Height / 2);
			logo.Resize(logo.Size);

			btnLogin = new ImageButton(RootWidget);
			btnLogin.Image = App.Resources.Get<Drawable>("gfx/hud/buttons/loginu");
			btnLogin.PressedImage = App.Resources.Get<Drawable>("gfx/hud/buttons/logind");
			btnLogin.Click += Login;
			btnLogin.Move(373, 460);
			btnLogin.Resize(btnLogin.Image.Size);

			cntPassword = new Container(RootWidget);
			cntPassword.Move(345, 310).Resize(150, 100);

			var lbUserName = new Label(cntPassword);
			lbUserName.Text = "User Name";
			lbUserName.TextColor = Color.White;
			lbUserName.Move(0, 0).Resize(150, 20);

			tbUserName = new TextBox(cntPassword);
			tbUserName.Text = "ken_tower";
			tbUserName.Move(0, 20).Resize(150, 23);

			var lbPassword = new Label(cntPassword);
			lbPassword.Text = "Password";
			lbPassword.TextColor = Color.White;
			lbPassword.Move(0, 60).Resize(150, 20);

			tbPassword = new TextBox(cntPassword);
			tbPassword.PasswordChar = '*';
			tbPassword.Move(0, 80).Resize(150, 23);

			chkRemember = new CheckBox(cntPassword);
			chkRemember.Move(0, 110);
			chkRemember.Text = "Remember me";

			cntToken = new Container(RootWidget);
			cntToken.Move(295, 310).Resize(250, 100);

			lblUserName = new Label(cntToken);
			lblUserName.Resize(cntToken.Width, cntToken.Height);
			lblUserName.TextAlign = TextAlign.Center;

			btnForget = new Button(cntToken, 100);
			btnForget.Text = "Forget me";
			btnForget.Move(75, 23);
			btnForget.Click += ForgetToken;

			lblErrorMessage = new Label(RootWidget);
			lblErrorMessage.TextColor = Color.Red;
			lblErrorMessage.TextAlign = TextAlign.Center;
			lblErrorMessage.Visible = false;
			lblErrorMessage.Move(0, 500).Resize(840, 20);

			lbProgress = new Label(RootWidget);
			lbProgress.TextColor = Color.White;
			lbProgress.TextAlign = TextAlign.Center;
			lbProgress.Visible = false;
			lbProgress.Move(0, 350).Resize(840, 20);
		}

		protected override void OnResize(int newWidth, int newHeight)
		{
			var w = newWidth > MinWidth ? newWidth : MinWidth;
			var h = newHeight > MinHeight ? newHeight : MinHeight;
			RootWidget.Move((w - MinWidth) / 2, (h - MinHeight) / 2);
		}

		private void OnKeyDown(KeyEvent args)
		{
			switch (args.Key)
			{
				case Key.Enter:
					if (string.IsNullOrEmpty(tbUserName.Text))
						SetKeyboardFocus(tbUserName);
					else if (tbUserName.IsFocused || string.IsNullOrEmpty(tbPassword.Text))
						SetKeyboardFocus(tbPassword);
					else
						Login();
					break;
				case Key.Tab:
					if (tbPassword.IsFocused)
						SetKeyboardFocus(tbUserName);
					else if (tbUserName.IsFocused)
						SetKeyboardFocus(tbPassword);
					break;
			}
		}

		private void Login()
		{
			GotoProgressPage();

			if (!login.HasToken)
			{
				login.UserName = tbUserName.Text;
				login.Password = tbPassword.Text;
				login.Remember = chkRemember.IsChecked;
				// clear password
				tbPassword.Text = "";
			}

			UpdateProgress("Authenticating...");

			login.LoginAsync();
		}

		private void GotoInitialPage(string errorMessage = null)
		{
			lbProgress.Visible = false;

			cntPassword.Visible = !login.HasToken;
			cntToken.Visible = login.HasToken;
			btnLogin.Visible = true;

			lblErrorMessage.Visible = !string.IsNullOrEmpty(errorMessage);
			lblErrorMessage.Text = errorMessage;

			tbUserName.Text = login.UserName;
			lblUserName.Text = $"Identity is saved for {login.UserName}";

			if (string.IsNullOrEmpty(tbUserName.Text))
				SetKeyboardFocus(tbUserName);
			else
				SetKeyboardFocus(tbPassword);
		}

		private void GotoProgressPage()
		{
			lbProgress.Text = "";
			lbProgress.Visible = true;

			cntPassword.Visible = false;
			cntToken.Visible = false;
			btnLogin.Visible = false;

			lblErrorMessage.Visible = false;
		}

		private void UpdateProgress(string status)
		{
			lbProgress.Text = status;
		}

		private void Finish(LoginResult authResult)
		{
			if (authResult.IsSuccessful)
			{
				try
				{
					UpdateProgress("Connecting...");
					LoginCompleted.Raise();
					GotoInitialPage();
				}
				catch (NetworkException ex)
				{
					GotoInitialPage(ex.Message);
				}
				catch (Exception ex)
				{
					Log.Error(ex, "Unexpected connection error");
					GotoInitialPage("Unexpected connection error");
				}
			}
			else
				GotoInitialPage(authResult.ErrorMessage);
		}

		private void ForgetToken()
		{
			login.ForgetToken();
			GotoInitialPage();
		}
	}
}


text:
<?php

namespace Oro\Component\Layout\Form\RendererEngine;

use Symfony\Component\Form\FormRendererEngineInterface as BaseFormRendererEngineInterfaceInterface;
use Symfony\Component\Form\FormView;

/**
 * {@inheritdoc}
 */
interface FormRendererEngineInterface extends BaseFormRendererEngineInterfaceInterface
{
    /**
     * Sets the theme(s) to be used for rendering a view and its children.
     *
     * @param string|string[] $themes The theme(s). The type of these themes
     * is open to the implementation.
     */
    public function addDefaultThemes($themes);

    /**
     * Switches to the next parent resource for a block hierarchy. This method
     * is invoked to find next parent resource when invoking "parent_block_widget"
     *
     * A block hierarchy is an array which starts with the root of the hierarchy
     * and continues with the child of that root, the child of that child etc.
     * The following is an example for a block hierarchy:
     *
     * <code>
     * form_widget
     * text_widget
     * url_widget
     * </code>
     *
     * In this example, "url_widget" is the most specific block, while the other
     * blocks are its ancestors in the hierarchy.
     *
     * The type of the resource is decided by the implementation. The resource
     * is later passed to {@link renderBlock()} by the rendering algorithm.
     *
     * @param FormView $view               The view for determining the used themes
     *                                     First the themes  attached directly to
     *                                     the view with {@link setTheme()} are
     *                                     considered, then the ones of its parent etc.
     * @param array    $blockNameHierarchy The block name hierarchy, with the root block
     *                                     at the beginning.
     *
     * @return mixed The renderer resource or false, if none was found
     */
    public function switchToNextParentResource(FormView $view, array $blockNameHierarchy);
}


text:
<?php

namespace Tests\Services;

use App\Services\Logger;
use Tests\TestCase;

class LoggerTest extends TestCase
{
    public function testFileLogger()
    {
        $this->assertEquals(true, Logger::debug('debug'));
        $this->assertEquals(true, Logger::error('error'));
        $this->assertEquals(true, Logger::warning('error'));
        $this->assertEquals(true, Logger::info('error'));
    }

    public function testDbLogger()
    {
        $this->assertEquals(true, Logger::newDbLog('error', 'msg'));
    }
}


text:
package org.hoteia.qalingo.core.dao;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hoteia.qalingo.core.domain.Dictionary;
import org.hoteia.qalingo.core.domain.Tag;
import org.hoteia.qalingo.core.fetchplan.FetchPlan;
import org.hoteia.qalingo.core.fetchplan.common.FetchPlanGraphCommon;
import org.hoteia.qalingo.core.util.CoreUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

@Repository("referentialDataDao")
public class ReferentialDataDao extends AbstractGenericDao {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    // TAG

    public Tag getTagById(final Long tagId, Object... params) {
        Criteria criteria = createDefaultCriteria(Tag.class);

        FetchPlan fetchPlan = handleSpecificTagFetchMode(criteria, params);

        criteria.add(Restrictions.eq("id", tagId));

        Tag tag = (Tag) criteria.uniqueResult();
        if (tag != null) {
            tag.setFetchPlan(fetchPlan);
        }
        return tag;
    }

    public Tag getTagByCode(final String tagCode, Object... params) {
        Criteria criteria = createDefaultCriteria(Tag.class);

        FetchPlan fetchPlan = handleSpecificTagFetchMode(criteria, params);

        criteria.add(Restrictions.eq("code", handleCodeValue(tagCode)));

        Tag tag = (Tag) criteria.uniqueResult();
        if (tag != null) {
            tag.setFetchPlan(fetchPlan);
        }
        return tag;
    }

    public Long getMaxTagId() {
        Criteria criteria = createDefaultCriteria(Tag.class);
        criteria.setProjection(Projections.max("id"));
        Long maxId = (Long) criteria.uniqueResult();
        return (maxId == null) ? new Long(0) : maxId;
    }

    public List<Tag> findAllTags(Object... params) {
        Criteria criteria = createDefaultCriteria(Tag.class);

        handleSpecificTagFetchMode(criteria, params);

        criteria.addOrder(Order.asc("code"));

        @SuppressWarnings("unchecked")
        List<Tag> tags = criteria.list();
        return tags;
    }

    public Tag saveOrUpdateTag(final Tag tag) {
        if (tag.getDateCreate() == null) {
            tag.setDateCreate(new Date());
        }
        if (StringUtils.isEmpty(tag.getCode())) {
            tag.setCode(CoreUtil.generateEntityCode());
        }
        tag.setDateUpdate(new Date());
        if (tag.getId() != null) {
            if (em.contains(tag)) {
                em.refresh(tag);
            }
            Tag mergedTag = em.merge(tag);
            em.flush();
            return mergedTag;
        } else {
            em.persist(tag);
            return tag;
        }
    }

    public void deleteTag(final Tag tag) {
        em.remove(em.contains(tag) ? tag : em.merge(tag));
    }

    protected FetchPlan handleSpecificTagFetchMode(Criteria criteria, Object... params) {
        if (params != null && params.length > 0) {
            return super.handleSpecificFetchMode(criteria, params);
        } else {
            return super.handleSpecificFetchMode(criteria, FetchPlanGraphCommon.defaultTagFetchPlan());
        }
    }

    // DICTIONARY

    public Dictionary getDictionaryById(final Long dictionaryId, Object... params) {
        Criteria criteria = createDefaultCriteria(Dictionary.class);

        criteria.add(Restrictions.eq("id", dictionaryId));

        Dictionary dictionary = (Dictionary) criteria.uniqueResult();
        return dictionary;
    }

    public Dictionary getDictionaryByCodeAndLocalizationId(final String dictionaryCode, final Long localizationId, Object... params) {
        Criteria criteria = createDefaultCriteria(Dictionary.class);

        criteria.add(Restrictions.eq("code", handleCodeValue(dictionaryCode)));

        criteria.add(Restrictions.eq("localization.id", localizationId));

        Dictionary dictionary = (Dictionary) criteria.uniqueResult();
        return dictionary;
    }

    public Long getMaxDictionaryId() {
        Criteria criteria = createDefaultCriteria(Dictionary.class);
        criteria.setProjection(Projections.max("id"));
        Long maxId = (Long) criteria.uniqueResult();
        return (maxId == null) ? new Long(0) : maxId;
    }

    public List<Dictionary> findAllDictionarys(Object... params) {
        Criteria criteria = createDefaultCriteria(Dictionary.class);

        criteria.addOrder(Order.asc("code"));

        @SuppressWarnings("unchecked")
        List<Dictionary> dictionarys = criteria.list();
        return dictionarys;
    }

    public Dictionary saveOrUpdateDictionary(final Dictionary dictionary) {
        if (dictionary.getDateCreate() == null) {
            dictionary.setDateCreate(new Date());
        }
        if (StringUtils.isEmpty(dictionary.getCode())) {
            dictionary.setCode(CoreUtil.generateEntityCode());
        }
        dictionary.setDateUpdate(new Date());
        if (dictionary.getId() != null) {
            if (em.contains(dictionary)) {
                em.refresh(dictionary);
            }
            Dictionary mergedDictionary = em.merge(dictionary);
            em.flush();
            return mergedDictionary;
        } else {
            em.persist(dictionary);
            return dictionary;
        }
    }

    public void deleteDictionary(final Dictionary dictionary) {
        em.remove(em.contains(dictionary) ? dictionary : em.merge(dictionary));
    }

}


text:
package org.apache.causeway.testdomain.persistence.jpa.springdata;

import java.util.Optional;

import javax.inject.Inject;

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.apache.causeway.applib.services.repository.RepositoryService;
import org.apache.causeway.core.config.presets.CausewayPresets;
import org.apache.causeway.core.metamodel.specloader.SpecificationLoader;
import org.apache.causeway.testdomain.conf.Configuration_usingSpringDataJpa;
import org.apache.causeway.testdomain.jpa.springdata.Employee;
import org.apache.causeway.testdomain.jpa.springdata.EmployeeRepository;
import org.apache.causeway.testdomain.jpa.springdata.SpringDataJpaTestModule;
import org.apache.causeway.testing.fixtures.applib.fixturescripts.ExecutionParametersServiceAutoConfiguration;
import org.apache.causeway.testing.fixtures.applib.fixturescripts.FixtureScriptsSpecificationProviderAutoConfiguration;
import org.apache.causeway.testing.integtestsupport.applib.CausewayIntegrationTestAbstract;

import lombok.val;

@DataJpaTest
@ContextConfiguration(classes = {
        Configuration_usingSpringDataJpa.class,
        FixtureScriptsSpecificationProviderAutoConfiguration.class, // because @DataJpaTest disables autoconfiguration
        ExecutionParametersServiceAutoConfiguration.class           // because @DataJpaTest disables autoconfiguration
})
@TestPropertySource(CausewayPresets.UseLog4j2Test)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DirtiesContext
// @Disabled // CAUSEWAY-2789 revert
class SpringDataJpaBootstrappingTest extends CausewayIntegrationTestAbstract {

    @Inject private Optional<PlatformTransactionManager> platformTransactionManager;
    @Inject private RepositoryService repository;
    @Inject private SpecificationLoader specLoader;

    @Inject private EmployeeRepository employeeRepository;

    void cleanUp() {
        employeeRepository.deleteAllInBatch();
    }

    void setUp() {
        SpringDataJpaTestModule.setupEmployeeFixture(employeeRepository);
    }

    @Inject
    ConfigurableBeanFactory configurableBeanFactory;

    @Test @Order(0)
    void platformTransactionManager_shouldBeAvailable() {
        assertTrue(platformTransactionManager.isPresent());
        platformTransactionManager.ifPresent(ptm->{
            assertEquals("JpaTransactionManager", ptm.getClass().getSimpleName());
        });
    }

    @Test @Order(0)
    void transactionalAnnotation_shouldBeSupported() {
        assertTrue(platformTransactionManager.isPresent());
        platformTransactionManager.ifPresent(ptm->{

            val txDef = new DefaultTransactionDefinition();
            txDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_MANDATORY);

            val txStatus = ptm.getTransaction(txDef);

            assertNotNull(txStatus);
            assertFalse(txStatus.isCompleted());

        });
    }

    @Test @Order(0)
    void jpaEntities_shouldBeRecognisedAsSuch() {
        val productSpec = specLoader.loadSpecification(Employee.class);
        assertTrue(productSpec.isEntity());
        assertNotNull(productSpec.entityFacetElseFail());
    }

    @Test @Order(1) @Rollback(false)
    void sampleEmployeesShouldBeSetUp() {

        // given - expected pre condition: no inventories

        cleanUp();
        assertEquals(0, repository.allInstances(Employee.class).size());

        // when

        setUp();

        // then - expected post condition: 4 employees

        val employees = repository.allInstances(Employee.class);
        assertEquals(4, employees.size());

        val employee = employees.get(0);
        assertNotNull(employee);
        assertNotNull(employee.getLastName());

    }

    @Test @Order(2) @Rollback(false)
    void aSecondRunShouldWorkAsWell() {
        sampleEmployeesShouldBeSetUp();
    }

}


text:
"""Specifications for different types of input/output domains."""

import abc
import collections
from collections.abc import Iterable

import gin
import numpy as np
import six
from six.moves import range

from amortized_bo import utils

BOS_TOKEN = '<'  # Beginning of sequence token.
EOS_TOKEN = '>'  # End of sequence token.
PAD_TOKEN = '_'  # End of sequence token.
MASK_TOKEN = '*'  # End of sequence token.
SEP_TOKEN = '|'  # A special token for separating tokens for serialization.

@gin.configurable
class Vocabulary(object):
  """Basic vocabulary used to represent output tokens for domains."""

  def __init__(self,
               tokens,
               include_bos=False,
               include_eos=False,
               include_pad=False,
               include_mask=False,
               bos_token=BOS_TOKEN,
               eos_token=EOS_TOKEN,
               pad_token=PAD_TOKEN,
               mask_token=MASK_TOKEN):
    """A token vocabulary.

    Args:
      tokens: An list of tokens to put in the vocab. If an int, will be
        interpreted as the number of tokens and '0', ..., 'tokens-1' will be
        used as tokens.
      include_bos: Whether to append `bos_token` to `tokens` that marks the
        beginning of a sequence.
      include_eos: Whether to append `eos_token` to `tokens` that marks the
        end of a sequence.
      include_pad: Whether to append `pad_token` to `tokens` to marks past end
        of sequence.
      include_mask: Whether to append `mask_token` to `tokens` to mark masked
        positions.
      bos_token: A special token than marks the beginning of sequence.
        Ignored if `include_bos == False`.
      eos_token: A special token than marks the end of sequence.
        Ignored if `include_eos == False`.
      pad_token: A special token than marks past the end of sequence.
        Ignored if `include_pad == False`.
      mask_token: A special token than marks MASKED positions for e.g. BERT.
        Ignored if `include_mask == False`.
    """
    if not isinstance(tokens, Iterable):
      tokens = range(tokens)
    tokens = [str(token) for token in tokens]
    if include_bos:
      tokens.append(bos_token)
    if include_eos:
      tokens.append(eos_token)
    if include_pad:
      tokens.append(pad_token)
    if include_mask:
      tokens.append(mask_token)
    if len(set(tokens)) != len(tokens):
      raise ValueError('tokens not unique!')
    special_tokens = sorted(set(tokens) & set([SEP_TOKEN]))
    if special_tokens:
      raise ValueError(
          f'tokens contains reserved special tokens: {special_tokens}!')

    self._tokens = tokens
    self._token_ids = list(range(len(self._tokens)))
    self._id_to_token = collections.OrderedDict(
        zip(self._token_ids, self._tokens))
    self._token_to_id = collections.OrderedDict(
        zip(self._tokens, self._token_ids))
    self._bos_token = bos_token if include_bos else None
    self._eos_token = eos_token if include_eos else None
    self._mask_token = mask_token if include_mask else None
    self._pad_token = pad_token if include_pad else None

  def __len__(self):
    return len(self._tokens)

  @property
  def tokens(self):
    """Return the tokens of the vocabulary."""
    return list(self._tokens)

  @property
  def token_ids(self):
    """Return the tokens ids of the vocabulary."""
    return list(self._token_ids)

  @property
  def bos(self):
    """Returns the index of the BOS token or None if unspecified."""
    return (None if self._bos_token is None else
            self._token_to_id[self._bos_token])

  @property
  def eos(self):
    """Returns the index of the EOS token or None if unspecified."""
    return (None if self._eos_token is None else
            self._token_to_id[self._eos_token])

  @property
  def mask(self):
    """Returns the index of the MASK token or None if unspecified."""
    return (None if self._mask_token is None else
            self._token_to_id[self._mask_token])

  @property
  def pad(self):
    """Returns the index of the PAD token or None if unspecified."""
    return (None
            if self._pad_token is None else self._token_to_id[self._pad_token])

  def is_valid(self, value):
    """Tests if a value is a valid token id and returns a bool."""
    return value in self._token_ids

  def are_valid(self, values):
    """Tests if values are valid token ids and returns an array of bools."""
    return np.array([self.is_valid(value) for value in values])

  def encode(self, tokens):
    """Maps an iterable of string tokens to a list of integer token ids."""
    if six.PY3 and isinstance(tokens, bytes):
      # Always use Unicode in Python 3.
      tokens = tokens.decode('utf-8')
    return [self._token_to_id[token] for token in tokens]

  def decode(self, values, stop_at_eos=False, as_str=True):
    """Maps an iterable of integer token ids to string tokens.

    Args:
      values: An iterable of token ids.
      stop_at_eos: Whether to ignore all values after the first EOS token id.
      as_str: Whether to return a list of tokens or a concatenated string.

    Returns:
      A string of tokens or a list of tokens if `as_str == False`.
    """
    if stop_at_eos and self.eos is None:
      raise ValueError('EOS unspecified!')
    tokens = []
    for value in values:
      value = int(value)  # Requires if value is a scalar tensor.
      if stop_at_eos and value == self.eos:
        break
      tokens.append(self._id_to_token[value])
    return ''.join(tokens) if as_str else tokens

@six.add_metaclass(abc.ABCMeta)
class Domain(object):
  """Base class of problem domains, which specifies the set of valid objects."""

  @property
  def mask_fn(self):
    """Returns a masking function or None."""

  @abc.abstractmethod
  def is_valid(self, sample):
    """Tests if the given sample is valid for this domain."""

  def are_valid(self, samples):
    """Tests if the given samples are valid for this domain."""
    return np.array([self.is_valid(sample) for sample in samples])

class DiscreteDomain(Domain):
  """Base class for discrete domains: sequences of categorical variables."""

  def __init__(self, vocab):
    self._vocab = vocab

  @property
  def vocab_size(self):
    return len(self.vocab)

  @property
  def vocab(self):
    return self._vocab  # pytype: disable=attribute-error  # trace-all-classes

  def encode(self, samples, **kwargs):
    """Maps a list of string tokens to a list of lists of integer token ids."""
    return [self.vocab.encode(sample, **kwargs) for sample in samples]

  def decode(self, samples, **kwargs):
    """Maps list of lists of integer token ids to list of strings."""
    return [self.vocab.decode(sample, **kwargs) for sample in samples]

@gin.configurable
class FixedLengthDiscreteDomain(DiscreteDomain):
  """Output is a fixed length discrete sequence."""

  def __init__(self, vocab_size=None, length=None, vocab=None):
    """Creates an instance of this class.

    Args:
      vocab_size: An optional integer for constructing a vocab of this size.
        If provided, `vocab` must be `None`.
      length: The length of the domain (required).
      vocab: The `Vocabulary` of the domain. If provided, `vocab_size` must be
        `None`.

    Raises:
      ValueError: If neither `vocab_size` nor `vocab` is provided.
      ValueError: If `length` if not provided.
    """
    if length is None:
      raise ValueError('length must be provided!')
    if not (vocab_size is None) ^ (vocab is None):
      raise ValueError('Exactly one of vocab_size of vocab must be specified!')
    self._length = length
    if vocab is None:
      vocab = Vocabulary(vocab_size)
    super(FixedLengthDiscreteDomain, self).__init__(vocab)

  @property
  def length(self):
    return self._length

  @property
  def size(self):
    """The number of structures in the Domain."""
    return self.vocab_size**self.length

  def is_valid(self, sequence):
    return len(sequence) == self.length and self.vocab.are_valid(sequence).all()

  def sample_uniformly(self, num_samples, seed=None):
    random_state = utils.get_random_state(seed)
    return np.int32(
        random_state.randint(
            size=[num_samples, self.length], low=0, high=self.vocab_size))

  def index_to_structure(self, index):
    """Given an integer and target length, encode into structure."""
    structure = np.zeros(self.length, dtype=np.int32)
    tokens = [int(token, base=len(self.vocab))
              for token in np.base_repr(index, base=len(self.vocab))]
    structure[-len(tokens):] = tokens
    return structure

  def structure_to_index(self, structure):
    """Returns the index of a sequence over a vocabulary of size `vocab_size`."""
    structure = np.asarray(structure)[::-1]
    return np.sum(structure * np.power(len(self.vocab), range(len(structure))))


text:
// ExplorerBar.cpp: implementation of the CToolboxBar class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "DevInc.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CToolboxBar::CToolboxBar()
{
}

CToolboxBar::~CToolboxBar()
{
}

BEGIN_MESSAGE_MAP(CToolboxBar, CSizingControlBar)
    //{{AFX_MSG_MAP(CToolboxBar)
    ON_WM_CREATE()
    ON_WM_SIZE()
	ON_WM_DESTROY()
	ON_WM_NCHITTEST()
	ON_WM_NCCALCSIZE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPropertyBar message handlers
int CToolboxBar::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CSizingControlBar::OnCreate(lpCreateStruct) == -1)
        return -1;

	/*CRect rect;
	rect.SetRectEmpty();
	if (!m_wndExplorerTree.Create(WS_VISIBLE | WS_CHILD/* | WS_BORDER*//*,
			rect, this, AFX_IDW_PANE_FIRST))
		return -1;*/

	CRect rect(0, 0, lpCreateStruct->cx, lpCreateStruct->cy);

	if (!m_wndBoxCtrl.Create(NULL, NULL, 0, rect, this, 0, NULL))
		return -1;
	m_wndBoxCtrl.InitWindow();

    return 0;
}

CSize CToolboxBar::CalcDynamicLayout(int nLength, DWORD dwMode)
{
    if (dwMode & (LM_HORZDOCK | LM_VERTDOCK)) //docked
    {
        if (nLength == -1)
            m_bParentSizing = TRUE;
		CSize size;

        size = baseCSizingControlBar::CalcDynamicLayout(nLength, dwMode);
		if (dwMode & LM_VERTDOCK)
		{
			int nWidth;
			if (::IsWindow(m_wndBoxCtrl.m_hWnd))
			{
				m_wndBoxCtrl.CalcParentWndWidth(size.cx, nWidth);
				size.cx = nWidth;
			}
		}
		return size;
    }

    if (dwMode & LM_MRUWIDTH) return m_szFloat;
    if (dwMode & LM_COMMIT) return m_szFloat; // already committed

    //((dwMode & LM_LENGTHY) ? m_szFloat.cy : m_szFloat.cx) = nLength - 30;
	if (dwMode & LM_LENGTHY)
	{
		m_szFloat.cy = nLength;
	}
	else
	{	//ˮƽsizeing
		int nWidth;
		if (::IsWindow(m_wndBoxCtrl.m_hWnd))
			m_wndBoxCtrl.CalcParentWndWidth(nLength, nWidth);
		else
			nWidth = nLength;
		m_szFloat.cx = nWidth;
	}

    m_szFloat.cx = max(m_szFloat.cx, m_szMin.cx);
    m_szFloat.cy = max(m_szFloat.cy, m_szMin.cy);

    return m_szFloat;
}

void CToolboxBar::NcPaintGripper(CDC* pDC, CRect rcClient)
{
	// paints a simple "two raised lines" gripper
    // override this if you want a more sophisticated gripper
    CRect gripper = rcClient;
    BOOL bHorz = IsHorzDocked();

    gripper.DeflateRect(1, 1);
    if (bHorz)
    {   // gripper at left
        gripper.left -= m_cyGripper - 5;
        gripper.right = gripper.left + 3;
    }
    else
    {   // gripper at top
        gripper.top -= m_cyGripper - 5;
        gripper.bottom = gripper.top + 3;
    }
    pDC->Draw3dRect(gripper, ::GetSysColor(COLOR_BTNHIGHLIGHT),
        ::GetSysColor(COLOR_BTNSHADOW));
}

UINT CToolboxBar::OnNcHitTest(CPoint point)
{
    if (IsFloating())
        return baseCSizingControlBar::OnNcHitTest(point);

    CRect rcBar, rcEdge;
    GetWindowRect(rcBar);

    for (int i = 0; i < 4; i++)
        if (GetEdgeRect(rcBar, GetEdgeHTCode(i), rcEdge))
            if (rcEdge.PtInRect(point)) return GetEdgeHTCode(i);
    return HTCLIENT;
}

void CToolboxBar::OnNcCalcSize(BOOL bCalcValidRects,
                                     NCCALCSIZE_PARAMS FAR* lpncsp)
{
    // compute the the client area
    CRect rcClient = lpncsp->rgrc[0];
    rcClient.DeflateRect(5, 5);

    m_dwSCBStyle &= ~SCBS_EDGEALL;

    switch(m_nDockBarID)
    {
    case AFX_IDW_DOCKBAR_TOP:
        m_dwSCBStyle |= SCBS_EDGEBOTTOM;
        rcClient.DeflateRect(m_cyGripper - m_cyGripper/2, 0, 0, 0);
        break;
    case AFX_IDW_DOCKBAR_BOTTOM:
        m_dwSCBStyle |= SCBS_EDGETOP;
        rcClient.DeflateRect(m_cyGripper - m_cyGripper/2, 0, 0, 0);
        break;
    case AFX_IDW_DOCKBAR_LEFT:
        m_dwSCBStyle |= SCBS_EDGERIGHT;
        rcClient.DeflateRect(0, m_cyGripper - m_cyGripper/2, 0, 0);
        break;
    case AFX_IDW_DOCKBAR_RIGHT:
        m_dwSCBStyle |= SCBS_EDGELEFT;
        rcClient.DeflateRect(0, m_cyGripper - m_cyGripper/2, 0, 0);
        break;
    default:
        break;
    }

    if (!IsFloating() && m_pDockBar != NULL)
    {
        CSCBArray arrSCBars;
        GetRowSizingBars(arrSCBars);

        for (int i = 0; i < arrSCBars.GetSize(); i++)
            if (arrSCBars[i] == this)
            {
                if (i > 0)
                    m_dwSCBStyle |= IsHorzDocked() ?
                        SCBS_EDGELEFT : SCBS_EDGETOP;
                if (i < arrSCBars.GetSize() - 1)
                    m_dwSCBStyle |= IsHorzDocked() ?
                        SCBS_EDGERIGHT : SCBS_EDGEBOTTOM;
            }
    }

    // make room for edges only if they will be painted
    if (m_dwSCBStyle & SCBS_SHOWEDGES)
        rcClient.DeflateRect(
            (m_dwSCBStyle & SCBS_EDGELEFT) ? m_cxEdge : 0,
            (m_dwSCBStyle & SCBS_EDGETOP) ? m_cxEdge : 0,
            (m_dwSCBStyle & SCBS_EDGERIGHT) ? m_cxEdge : 0,
            (m_dwSCBStyle & SCBS_EDGEBOTTOM) ? m_cxEdge : 0);

    lpncsp->rgrc[0] = rcClient;
}

void CToolboxBar::OnSize(UINT nType, int cx, int cy)
{
    CSizingControlBar::OnSize(nType, cx, cy);
	if (::IsWindow(m_wndBoxCtrl.m_hWnd))
	{
		CRect rect;
		GetClientRect(rect);
		rect.DeflateRect(2, 2);

		// need to push non-client borders out of the client area
		::AdjustWindowRectEx(rect,
			m_wndBoxCtrl.GetStyle(), FALSE, WS_EX_CLIENTEDGE);
		m_wndBoxCtrl.SetWindowPos(NULL, rect.left, rect.top,
			rect.Width(), rect.Height(), SWP_NOACTIVATE | SWP_NOZORDER);
	}
}

void CToolboxBar::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler)
{
    CSizingControlBar::OnUpdateCmdUI(pTarget, bDisableIfNoHndler);

	if (m_wndBoxCtrl.GetSelFolder() == 0 && CDevTool::c_drawShape >= DRAW_SELECTION  && CDevTool::c_drawShape <= DRAW_ALMSUM)
	{
		if (m_wndBoxCtrl.GetSelFolder() == 0 && m_wndBoxCtrl.GetSelItem() != CDevTool::c_drawShape - DRAW_SELECTION)
			m_wndBoxCtrl.SetSelItem(CDevTool::c_drawShape - DRAW_SELECTION);
	}
	else
	{
		if (CDevTool::c_drawShape == DRAW_SELECTION  && m_wndBoxCtrl.GetSelItem() > 0)
			m_wndBoxCtrl.SetSelItem(0);

//		if (CDevTool::c_drawShape == DRAW_RECTITEM &&
//			m_wndBoxCtrl.GetSelFolder() == 0 &&
//			CRectItemTool::c_bInterior == TRUE &&
//			IsEqualCLSID(CRectItemTool::c_clsid, CLSID_CxRunCtrl))
//		{
//			m_wndBoxCtrl.SetSelItem(18);
//		}
	}
}

void CToolboxBar::OnDestroy()
{
	if (m_wndBoxCtrl.GetSafeHwnd())
	{
		m_wndBoxCtrl.SaveWindow();
	}
}


text:
package com.github.anba.es6draft;

/**
 *
15 ECMAScript Language: Scripts and Modules

 *

 *
15.1 Scripts
 *
15.2 Modules
 *

 */
public interface Program extends Executable {
}


text:
@implementation UIImage (HHKit)
+ (UIImage *)imageFromMainBundleFile:(NSString *)filename {
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", bundlePath, filename]];
}

@end


text:
import signal

def ctrlc_handler(signum, frm):
    print "Haha! you cannot kill me!"

print "Installing signal handler ....."

signal.signal(signal.SIGINT, ctrlc_handler)
print "Done!"

while True:
    pass


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

   <title>Inventory statements</title>
   <meta name="generator" content="Help & Manual" />
   <meta name="keywords" content="" />
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <meta http-equiv="Content-Style-Type" content="text/css" />
   <link type="text/css" href="default.css" rel="stylesheet" />

Inventory statements

     Top
     Previous
     Next

Check "Auto-numbering" in case you wish to use auto numbering for your stock balances.

For better traceability of stock balance documents and to help users quickly identify this kind of documents, you may specify a prefix and/or suffix for such statements. You may enter them into "prefix" or "suffix" fields. For example, you may enter  "INVST" for "Inventory Statement". Current ID number of the document is entered in the "Current number" field. Next document will be assigned a sequence number starting from the current number

Check "create document as posted" if you wish to automatically post the stock balances after they are created. In this case you won't need to use a posting option after you create this document.


text:
'use strict';
module.exports = function(sequelize, DataTypes) {
  var ProductOrder = sequelize.define('ProductOrder', {
    'status': DataTypes.STRING,
    'orderDetails': DataTypes.TEXT,
    'productDetails': DataTypes.JSONB,
    'orderTotal': DataTypes.INTEGER,
    'customerFullName': DataTypes.STRING,
    'customerEmail': DataTypes.STRING,
    'phone': DataTypes.STRING,
    'shippingStreet': DataTypes.STRING,
    'shippingApartment': DataTypes.STRING,
    'shippingCity': DataTypes.STRING,
    'shippingState': DataTypes.STRING,
    'shippingZip': DataTypes.STRING,
    'shippingCountry': DataTypes.STRING
  }, {
    'classMethods': {
        associate: function(models) {
            ProductOrder.belongsTo(models.User);
        }
    }
  });
  return ProductOrder;
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.azure.spring.messaging.config;

import com.microsoft.azure.spring.messaging.annotation.AzureMessageListener;
import com.microsoft.azure.spring.messaging.annotation.EnableAzureMessaging;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;

/**
 * {@code @Configuration} class that registers a {@link AzureListenerAnnotationBeanPostProcessor}
 * bean capable of processing Spring's @{@link AzureMessageListener} annotation. Also register
 * a default {@link AzureListenerEndpointRegistry}.
 *
 * <p>This configuration class is automatically imported when using the @{@link EnableAzureMessaging}
 * annotation. See the {@link EnableAzureMessaging} javadocs for complete usage details.
 *
 * @author Warren Zhu
 * @see AzureListenerAnnotationBeanPostProcessor
 * @see AzureListenerEndpointRegistry
 * @see EnableAzureMessaging
 */
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class AzureBootstrapConfiguration {

    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @Bean
    public AzureListenerAnnotationBeanPostProcessor azureListenerAnnotationProcessor() {
        return new AzureListenerAnnotationBeanPostProcessor();
    }

    @Bean(name = AzureListenerAnnotationBeanPostProcessor.DEFAULT_AZURE_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)
    public AzureListenerEndpointRegistry azureListenerEndpointRegistry() {
        return new AzureListenerEndpointRegistry();
    }

}


text:
package router

import (
	"bytes"
	"sync"
	"testing"
	"time"

	"github.com/go-redis/redis"
	"github.com/tsuru/planb/log"
	"github.com/tsuru/planb/reverseproxy"
	"gopkg.in/check.v1"
)

type S struct {
	redis *redis.Client
}

var _ = check.Suite(&S{})

func Test(t *testing.T) {
	check.TestingT(t)
}

func clearKeys(r *redis.Client) error {
	val := r.Keys("frontend:*").Val()
	val = append(val, r.Keys("dead:*").Val()...)
	if len(val) > 0 {
		return r.Del(val...).Err()
	}
	return nil
}

func redisConn() (*redis.Client, error) {
	return redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379", DB: 0}), nil
}

func (s *S) SetUpTest(c *check.C) {
	var err error
	s.redis, err = redisConn()
	c.Assert(err, check.IsNil)
	err = clearKeys(s.redis)
	c.Assert(err, check.IsNil)
}

func (s *S) TearDownTest(c *check.C) {
	s.redis.Close()
}

func (s *S) TestInit(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	c.Assert(router.roundRobin, check.DeepEquals, map[string]*uint32{})
	c.Assert(router.logger, check.IsNil)
	c.Assert(router.cache, check.IsNil)
	c.Assert(router.Backend, check.NotNil)
}

func (s *S) TestInitCacheEnabled(c *check.C) {
	router := Router{CacheEnabled: true}
	err := router.Init()
	c.Assert(err, check.IsNil)
	c.Assert(router.roundRobin, check.DeepEquals, map[string]*uint32{})
	c.Assert(router.logger, check.IsNil)
	c.Assert(router.cache, check.NotNil)
	c.Assert(router.Backend, check.NotNil)
}

func (s *S) TestChooseBackend(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "http://url1:123",
		BackendIdx: 0,
		BackendKey: "myfrontend.com",
		BackendLen: 1,
		Host:       "myfrontend.com",
	})
}

func (s *S) TestChooseBackendConsiderPort(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com:1234", "myfrontend", "http://url1:123").Err()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend", "http://url2:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com:1234")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "http://url1:123",
		BackendIdx: 0,
		BackendKey: "myfrontend.com:1234",
		BackendLen: 1,
		Host:       "myfrontend.com:1234",
	})
	reqData, err = router.ChooseBackend("myfrontend.com:9999")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "http://url2:123",
		BackendIdx: 0,
		BackendKey: "myfrontend.com",
		BackendLen: 1,
		Host:       "myfrontend.com",
	})
}

func (s *S) TestChooseBackendIgnorePort(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com:80")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "http://url1:123",
		BackendIdx: 0,
		BackendKey: "myfrontend.com",
		BackendLen: 1,
		Host:       "myfrontend.com",
	})
}

func (s *S) TestChooseBackendNotFound(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.Equals, reverseproxy.ErrNoRegisteredBackends)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "",
		BackendIdx: 0,
		BackendLen: 0,
		BackendKey: "",
		Host:       "myfrontend.com",
	})
}

func (s *S) TestChooseBackendNoBackends(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.Equals, reverseproxy.ErrNoRegisteredBackends)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "",
		BackendIdx: 0,
		BackendLen: 0,
		BackendKey: "",
		Host:       "myfrontend.com",
	})
}

func (s *S) TestChooseBackendAllDead(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123").Err()
	c.Assert(err, check.IsNil)
	err = s.redis.SAdd("dead:myfrontend.com", "0").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.Equals, reverseproxy.ErrAllBackendsDead)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "",
		BackendIdx: 0,
		BackendLen: 1,
		BackendKey: "myfrontend.com",
		Host:       "myfrontend.com",
	})
}

func (s *S) TestChooseBackendRoundRobin(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123", "http://url2:123", "http://url3:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.StartTime.IsZero(), check.Equals, false)
	reqData.StartTime = time.Time{}
	c.Assert(reqData, check.DeepEquals, &reverseproxy.RequestData{
		Backend:    "http://url1:123",
		BackendIdx: 0,
		BackendKey: "myfrontend.com",
		BackendLen: 3,
		Host:       "myfrontend.com",
	})
	err = s.redis.RPush("frontend:myfrontend.com", "http://url4:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url2:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url3:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url4:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url1:123")
}

func (s *S) TestChooseBackendRoundRobinWithCache(c *check.C) {
	router := Router{CacheEnabled: true}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123", "http://url2:123", "http://url3:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err := router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url1:123")
	err = s.redis.RPush("frontend:myfrontend.com", "http://url4:123").Err()
	c.Assert(err, check.IsNil)
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url2:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url3:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url1:123")
	time.Sleep(cacheTTLExpires)
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url1:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url2:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url3:123")
	reqData, err = router.ChooseBackend("myfrontend.com")
	c.Assert(err, check.IsNil)
	c.Assert(reqData.Backend, check.Equals, "http://url4:123")
}

func (s *S) TestChooseBackendRoundRobinStress(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend",
		"http://url1",
		"http://url2",
		"http://url3",
		"http://url4",
		"http://url5").Err()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend2.com", "myfrontend",
		"http://url1",
		"http://url2").Err()
	c.Assert(err, check.IsNil)
	freq1 := map[int]int{}
	freq2 := map[int]int{}
	mu := sync.Mutex{}
	wg := sync.WaitGroup{}
	nParallel := 10
	nSeq := 1000
	for i := 0; i < nParallel; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < nSeq; j++ {
				reqData1, err := router.ChooseBackend("myfrontend.com")
				c.Assert(err, check.IsNil)
				reqData2, err := router.ChooseBackend("myfrontend2.com")
				c.Assert(err, check.IsNil)
				mu.Lock()
				freq1[reqData1.BackendIdx]++
				freq2[reqData2.BackendIdx]++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	expected1 := (nParallel * nSeq) / 5
	expected2 := (nParallel * nSeq) / 2
	c.Assert(freq1, check.DeepEquals, map[int]int{
		0: expected1,
		1: expected1,
		2: expected1,
		3: expected1,
		4: expected1,
	})
	c.Assert(freq2, check.DeepEquals, map[int]int{
		0: expected2,
		1: expected2,
	})
}

func (s *S) TestChooseBackendRoundRobinStressOverflow(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	err = s.redis.RPush("frontend:myfrontend.com", "myfrontend",
		"http://url1",
		"http://url2",
		"http://url3",
		"http://url4",
		"http://url5").Err()
	c.Assert(err, check.IsNil)
	freq := map[int]int{}
	mu := sync.Mutex{}
	wg := sync.WaitGroup{}
	nParallel := 10
	nSeq := 1000
	initialNumber := uint32(1<<32 - 2)
	router.roundRobin["myfrontend.com"] = &initialNumber
	for i := 0; i < nParallel; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < nSeq; j++ {
				reqData, err := router.ChooseBackend("myfrontend.com")
				c.Assert(err, check.IsNil)
				mu.Lock()
				freq[reqData.BackendIdx]++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	expected := (nParallel * nSeq) / 5
	c.Assert(freq, check.DeepEquals, map[int]int{
		0: expected + 1,
		1: expected,
		2: expected,
		3: expected - 1,
		4: expected,
	})
}

type bufferCloser struct {
	bytes.Buffer
}

func (b *bufferCloser) Close() error {
	return nil
}

func (s *S) TestEndRequest(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	buf := bufferCloser{}
	router.logger = log.NewWriterLogger(&buf)
	data := &reverseproxy.RequestData{
		Host: "myfe.com",
	}
	err = router.EndRequest(data, false, nil)
	c.Assert(err, check.IsNil)
	members := s.redis.SMembers("dead:myfe.com").Val()
	c.Assert(members, check.DeepEquals, []string{})
	router.Stop()
	c.Assert(buf.String(), check.Equals, "")
}

func (s *S) TestEndRequestWithLogFunc(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	buf := bufferCloser{}
	router.logger = log.NewWriterLogger(&buf)
	data := &reverseproxy.RequestData{
		Host: "myfe.com",
	}
	err = router.EndRequest(data, false, func() *log.LogEntry { return &log.LogEntry{} })
	c.Assert(err, check.IsNil)
	members := s.redis.SMembers("dead:myfe.com").Val()
	c.Assert(members, check.DeepEquals, []string{})
	router.Stop()
	c.Assert(buf.String(), check.Equals, "::ffff: - - [01/Jan/0001:00:00:00 +0000] \"  \" 0 0 \"\" \"\" \":\" \"\" \"\" 0.000 0.000\n")
}

func (s *S) TestEndRequestWithError(c *check.C) {
	router := Router{}
	err := router.Init()
	c.Assert(err, check.IsNil)
	data := &reverseproxy.RequestData{
		Host: "myfe.com",
	}
	err = router.EndRequest(data, true, nil)
	c.Assert(err, check.IsNil)
	members := s.redis.SMembers("dead:myfe.com").Val()
	c.Assert(members, check.DeepEquals, []string{"0"})
}

func BenchmarkChooseBackend(b *testing.B) {
	r, err := redisConn()
	if err != nil {
		b.Fatal(err)
	}
	defer clearKeys(r)
	err = r.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123", "http://url2:123", "http://url3:123").Err()
	if err != nil {
		b.Fatal(err)
	}
	router := Router{
		CacheEnabled: true,
	}
	err = router.Init()
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			router.ChooseBackend("myfrontend.com")
		}
	})
	b.StopTimer()
}

func BenchmarkChooseBackendNoCache(b *testing.B) {
	r, err := redisConn()
	if err != nil {
		b.Fatal(err)
	}
	defer clearKeys(r)
	err = r.RPush("frontend:myfrontend.com", "myfrontend", "http://url1:123", "http://url2:123", "http://url3:123").Err()
	if err != nil {
		b.Fatal(err)
	}
	router := Router{}
	err = router.Init()
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			router.ChooseBackend("myfrontend.com")
		}
	})
	b.StopTimer()
}

func BenchmarkChooseBackendManyNoCache(b *testing.B) {
	r, err := redisConn()
	if err != nil {
		b.Fatal(err)
	}
	defer clearKeys(r)
	backends := make([]interface{}, 100)
	for i := range backends {
		backends[i] = "http://urlx:123"
	}
	backends = append([]interface{}{"benchfrontend"}, backends...)
	err = r.RPush("frontend:myfrontend.com", backends...).Err()
	if err != nil {
		b.Fatal(err)
	}
	router := Router{}
	err = router.Init()
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			router.ChooseBackend("myfrontend.com")
		}
	})
	b.StopTimer()
}


text:
<?php

namespace IRY\AppliBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;

class PilotType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text')
            ->add('isCalling', 'checkbox')
            // ->add('dateCalling', 'date')->addViewTransformer(new DateTimeToStringTransformer())
            ->add('serie', 'entity', array(
                'class' => 'IRYAppliBundle:Serie',
                'property' => 'name',
            ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
	{
	    $resolver->setDefaults(array(
	        'data_class' => 'IRY\AppliBundle\Entity\Pilot',
            'csrf_protection' => false,
	    ));
	}

    public function getName()
    {
        return 'pilot';
    }
}