text:
/*using System.Reflection;
using MetX.Standard.Generators;
using MetX.Standard.Library;
using MetX.Standard.Library.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MetX.Tests.Standard.Generation
{
    [TestClass]
    public class ShadowRunContextTests
    {
        [TestMethod][Ignore("Never finished line of code that will not be used but who's code may be re-purposed")]
        public void Initialize_AddStaticCodeActual()
        {
            var data = new AddStaticCode();
            var actual = data.InitializeShadowRunContext();
            Assert.IsTrue(actual);

            Assert.IsTrue(data.FullNameOfActual.IsNotEmpty());
            Assert.IsNotNull(data.ShadowRunContext);
            Assert.IsTrue(data.PathToActual.IsNotEmpty());
            Assert.IsTrue(data.ShadowDomainName.IsNotEmpty());
        }
    }
}*/

redpajama_set_name: RedPajamaGithub


text:
import requests
import json
import datetime
from flask import flash
import os, re
from bs4 import BeautifulSoup
import urllib

badList = [
    u'Pagina_principale',
    u'Special:',
    u'File:',
    u'Speciale:',
    u'Categoria:',
    u'Especial:',
    u'Wikipedia:',
    u'Spezial:',
    u'Main_Page',
    u'Portada',
    u'Hauptseite',
    u'Spezial:',
    u'Wikip\xe9dia:',
    u'Sp\xe9cial'
]

def getViews(query):
    try:
        data = []
        for q in query['query']:
            for lang in query['langs']:

                base = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/' + lang + '.wikipedia/all-access/all-agents'

                url = "/".join([base, q, 'daily', query['start']+'00', query['end']+'00'])

                response = requests.get(url)
                if response.json().has_key('items'):
                    stats = response.json()['items']
                    for s in stats:
                        if s.has_key('views'):
                            replace = ''.join(e for e in s['article'] if e.isalnum())
                            s[replace + 'views'] = s['views']
                    data += stats

        if data == []: data = None

        return data, response.content

    except(KeyError):
        print "No data"
        return None, response.content

def getTrends(day=datetime.date.today()-datetime.timedelta(days=1), langs=['en']):

    try:
        data = []

        for lang in langs:
            url = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/top/'+str(lang)+'.wikipedia/all-access/'+str('%02d' % day.year)+'/'+str('%02d' % day.month)+'/'+str('%02d' % day.day)
            response = requests.get(url)
            if response.json().has_key('items'):
                stats = response.json()['items']
                for s in stats[0]['articles']:
                    s['project'] = stats[0]['project']
                data += stats[0]['articles']
            else:
                day=datetime.date.today()-datetime.timedelta(days=2)
                url = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/top/'+str(lang)+'.wikipedia/all-access/'+str('%02d' % day.year)+'/'+str('%02d' % day.month)+'/'+str('%02d' % day.day)
                response = requests.get(url)
                if response.json().has_key('items'):
                    stats = response.json()['items']
                    for s in stats[0]['articles']:
                        s['project'] = stats[0]['project']
                    data += stats[0]['articles']

            toremove = []
            for d in data:
                for b in badList:
                    if b in d['article']:
                        d['lang'] = lang
                        if d not in toremove: toremove.append(d)
                    else:
                        d['lang'] = lang
            for t in toremove:
                data.remove(t)

        return data, day, response.content

    except(KeyError):
        print "No data"
        return None, day ,response.content

def launchQuery(query, start, end, langs):

    # start = "20161101"
    # end = "20161114"
    # query = 'Donald Trump'

    query = query.split(",")

    for i in range(0, len(query)):
        if query[i][0] == ' ':
            query[i] = query[i][1:]
        if query[i][-1] == ' ':
            query[i] = query[i][:-1]

    q = {'query': query,
         'start': str(start),
         'end': str(end),
         'langs': langs
         }

    data, errors = getViews(q)
    return data, errors

def acquireTrends(langs=['en']):
    trends, day, errors = getTrends(langs=langs)
    query_list = ''
    query_title = ''
    timestamp = str('%02d' % day.year) + str('%02d' % day.month) + str('%02d' % day.day) + '00'
    toappend = []

    i = 0

    for d in trends:

        query_list += ((d['article'])+',')
        query_title += ((d['article'])+' - ')
        article = ''.join(e for e in d['article'] if e.isalnum())

        toappend += [{u'access': u'all-access', u'views': d['views'], u'timestamp': timestamp, u'agent': u'all-agents', u'project': d['lang']+'.wikipedia', article+'views': d['views'], u'granularity': u'daily', u'article': d['article']}]

        i += 1
        if i > 4: break

    query_list = query_list[:-1]
    query_title = query_title[:-2]
    end = datetime.datetime.today()
    start = end - datetime.timedelta(days=7)

    startDate = str('%02d' % start.year)+str('%02d' % start.month)+str('%02d' % start.day)
    endDate =  str('%02d' % end.year)+str('%02d' % end.month)+str('%02d' % end.day)

    data, errors = launchQuery(query_list, startDate, endDate, langs)
    if not data:
        flash("No data, retry")
        flash(errors)
    data += toappend
    return data, query_list, query_title

def enrichArticles(articles, lang):
    object_articles = []
    for article in articles:
        url = ('https://'+lang+'.wikipedia.org/wiki/'+article).encode('utf8')
        content = urllib.urlopen(url).read()
        page = BeautifulSoup(content, "html.parser")
        title = page.find('h1', id="firstHeading").text
        description = page.find('div', id="bodyContent").find('p').text
        image = page.find('div', id="bodyContent").find('img')['src']
        object_articles.append({'title':title, 'url':url, 'image':image, 'description':description})
    return object_articles


text:
<?php

namespace LooplineSystems\CloseIoApiWrapper\Model;

use LooplineSystems\CloseIoApiWrapper\Library\Exception\InvalidParamException;
use LooplineSystems\CloseIoApiWrapper\Library\JsonSerializableHelperTrait;
use LooplineSystems\CloseIoApiWrapper\Library\ObjectHydrateHelperTrait;

class Url implements \JsonSerializable
{
    const URL_TYPE_URL = 'url';

    use ObjectHydrateHelperTrait;
    use JsonSerializableHelperTrait;

    /**
     * @var string
     */
    private $url;

    /**
     * @var string
     */
    private $type;

    /**
     * @param array $data
     *
     * @throws InvalidParamException
     */
    public function __construct(array $data = null)
    {
        if ($data) {
            $this->hydrate($data);
        }
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param string $type
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @param string $url
     * @return $this
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }
}


text:
<!DOCTYPE html>

	<link rel="stylesheet" href="../pagebase.css" />
	<link rel="stylesheet" href="../../ext/font-awesome-4.4.0/css/font-awesome.min.css" />

		<button id="ta-button">Try Again</button>


text:
<div md-color-picker
    ng-model="configVals[cp.targetProperty]"
    label="{{ cp.label }}"
    open-on-input="false"
    md-color-material-palette="false"
    md-color-generic-palette="true"
    md-color-history="false"
    md-color-rgb="false"
    md-color-hsl="false"
    md-color-clear-button="false"
    style="margin-left: 10px;"
></div>


text:
title: Center Text with Bootstrap
localeTitle: Текст центра с бутстрапом
---
## Текст центра с бутстрапом

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/center-text-with-bootstrap/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
package org.scalaide.core.internal.project

import java.io.File.separator
import org.eclipse.core.runtime.IPath
import org.eclipse.core.runtime.Path

/**
 * Used to carry information about scope of sources compilation in given project.
 *
 * Compilation scope is a set of sources which are compiled together and
 * a product of compilation is usually stored in scope specific output folder.<br/>
 *
 * There are defined (as a convention) 3 scopes (can be changed in future so following
 * can be treated as example in scopes defining):
 *  - macros with default source path: <project root>/src/macros* and
 *    especially for Play projects <project root>/conf*
 *  - tests with default source path: <project root>/src/test* and (because of
 *    Play projects) <project root>/test*
 *  - main which gets all source paths which don't match macros and tests scopes
 *    (* is a wildcard so for example to tests scope are assigned sources from
 *    folders src/test, src/test-my-special)
 *
 * The scopes are compiled in order: macros, main, tests. The compilation is
 * conditional so if any scope compilation fails then further scopes are not
 * compiled. So when macros compilation fails then neither main nor tests is
 * compiles. When macros compiles successfully and main fails then tests scope is not compiled.
 *
 * When given eclipse project (let name it B) depends on other project (let
 * call it A) then there are introduced additional dependencies between
 * projects' scopes:
 *  - macros of B depends on macros and main of A. So macros of B requires the
 *    correct compilations of macros and main scopes in project A
 *  - main of B depends on macros and main of A
 *  - tests of B depends on macros, main and tests of A
 *
 * Refer to [[SbtScopesBuildManager]] implementation for
 * implementation details.
 *
 * The feature is controlled by 'useScopesCompiler' exposed on 'build manager' tab in
 * Scala->Compiler preferences menu. If this flag is not set then compilation process
 * falls to old approach implemented in [[ProjectsDependentSbtBuildManager]].
 */
trait CompileScope {

  /** Can be human readable name. */
  def name: String

  /** Says about what scopes kinds in upstream projects have impact on this one. */
  def dependentScopesInUpstreamProjects: Seq[CompileScope]

  /** `true` if source belongs to this compilation scope. */
  def isValidSourcePath(projectRelativePath: IPath): Boolean
  protected def isInPath(that: IPath, pathPatterns: IPath*): Boolean =
    pathPatterns.exists { _.isPrefixOf(that) }
  protected def toIPath(path: String): IPath = new Path(path)
}

case object CompileMacrosScope extends CompileScope {
  override def name: String = "macros"
  override def dependentScopesInUpstreamProjects: Seq[CompileScope] = Seq(CompileMacrosScope, CompileMainScope)
  override def isValidSourcePath(path: IPath): Boolean = isInPath(path, default, play)
  private val default = toIPath(s"src${separator}macros")
  private val play = toIPath("conf")
}

case object CompileMainScope extends CompileScope {
  override def name: String = "main"
  override def dependentScopesInUpstreamProjects: Seq[CompileScope] = Seq(CompileMacrosScope, CompileMainScope)
  override def isValidSourcePath(path: IPath): Boolean =
    !CompileMacrosScope.isValidSourcePath(path) && !CompileTestsScope.isValidSourcePath(path)
}

case object CompileTestsScope extends CompileScope {
  override def name: String = "tests"
  override def dependentScopesInUpstreamProjects: Seq[CompileScope] =
    Seq(CompileMacrosScope, CompileMainScope, CompileTestsScope)
  override def isValidSourcePath(path: IPath): Boolean = isInPath(path, default, play)
  private val default = toIPath(s"src${separator}test")
  private val play = toIPath("test")
}


text:
use std::ffi::OsStr;
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, Stdio};

use sys::abilities;

use hcore::os;

use error::{Error, Result};
use manager::service::Pkg;

static LOGKEY: &'static str = "EX";

pub fn run<T, S>(path: S, pkg: &Pkg, _: Option<T>) -> Result<Child>
where
    T: ToString,
    S: AsRef<OsStr>,
{
    let mut cmd = Command::new(path.as_ref());
    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    for (key, val) in pkg.env.iter() {
        cmd.env(key, val);
    }

    if abilities::can_run_services_as_svc_user() {
        // If we can SETUID/SETGID, then run the script as the service
        // user; otherwise, we'll just run it as ourselves.

        let uid =
            os::users::get_uid_by_name(&pkg.svc_user).ok_or(sup_error!(Error::Permissions(
                format!("No uid for user '{}' could be found", &pkg.svc_user)
            )))?;
        let gid =
            os::users::get_gid_by_name(&pkg.svc_group).ok_or(sup_error!(Error::Permissions(
                format!("No gid for group '{}' could be found", &pkg.svc_group)
            )))?;

        cmd.uid(uid).gid(gid);
    } else {
        debug!(
            "Current user lacks sufficient capabilites to run {:?} as \"{}\"; running as self!",
            path.as_ref(),
            &pkg.svc_user
        );
    }

    Ok(cmd.spawn()?)
}


text:
package com.asofdate.utils;

import com.asofdate.hauth.authentication.JwtService;
import com.asofdate.hauth.dto.RequestUserDto;
import com.asofdate.hauth.sql.SqlText;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hzwy23 on 2017/6/19.
 */
@Component
public class LoggerHandlerInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(LoggerHandlerInterceptor.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SqlText sqlText;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        RequestUserDto httpConn = JwtService.getConnUser(httpServletRequest);
        String userId = httpConn.getUserId();
        String domainId = httpConn.getDomainID();
        String clientIp = httpServletRequest.getRemoteAddr();
        Integer statuCd = httpServletResponse.getStatus();
        String method = httpServletRequest.getMethod();
        String uri = httpServletRequest.getRequestURI();
        Map<String, String[]> map = httpServletRequest.getParameterMap();
        Map<String, String> dt = parseJSON(map);
        String dtvalue = new GsonBuilder().create().toJson(dt);
        jdbcTemplate.update(sqlText.getSql("sys207"), userId, clientIp, statuCd, method, uri, dtvalue, domainId);
    }

    private Map<String, String> parseJSON(Map<String, String[]> map) {
        Map<String, String> dt = new HashMap<>();
        for (Map.Entry<String, String[]> m : map.entrySet()) {
            if ("_".equals(m.getKey())) {
                continue;
            }
            String val = "";
            for (int i = 0; i < m.getValue().length; i++) {
                if (i == 0) {
                    val += m.getValue()[i];
                } else {
                    val += "," + m.getValue()[i];
                }
            }
            dt.put(m.getKey(), val);
        }
        return dt;
    }
}


text:
"""Test TBR Matched Markets greedy search.
"""
import itertools

from matched_markets.methodology import geoeligibility
from matched_markets.methodology import tbrmatchedmarkets
from matched_markets.methodology import tbrmmdata
from matched_markets.methodology import tbrmmdesignparameters
from matched_markets.methodology import tbrmmdiagnostics
import pandas as pd

import unittest

TBRMatchedMarkets = tbrmatchedmarkets.TBRMatchedMarkets
TBRMMDiagnostics = tbrmmdiagnostics.TBRMMDiagnostics
TBRMMDesignParameters = tbrmmdesignparameters.TBRMMDesignParameters
TBRMMData = tbrmmdata.TBRMMData

class DesignWithinConstraints(unittest.TestCase):
  """Test method 'design_within_constraints'."""

  def setUp(self):
    super().setUp()
    n_geos = 5
    n_days = 21
    geos = {str(geo) for geo in range(n_geos)}
    dates = pd.date_range('2020-03-01', periods=n_days)
    df_data = [{'date': date, 'geo': geo} for geo, date in
               itertools.product(geos, dates)]
    df = pd.DataFrame(df_data)
    response_column = 'sales'

    # Create sales data.
    def day_geo_sales(geo, n_days):
      # Larger geos have different means and variances.
      return [100 * geo + 10 * geo * day + day for day in range(n_days)]

    par = TBRMMDesignParameters(n_test=14, iroas=3.0)

    df[response_column] = 0.0
    sales = {}
    impact = {}
    for geo in geos:
      sales_time_series = day_geo_sales(int(geo), n_days)
      df.loc[df.geo == geo, response_column] = sales_time_series
      sales[geo] = sales_time_series
      dg = TBRMMDiagnostics(sales_time_series, par)
      impact[geo] = dg.estimate_required_impact(par.rho_max)

    self.impact = impact
    self.geos = geos
    self.par = par
    self.data = TBRMMData(df, response_column)
    self.response = response_column
    self.default_geo_eligibility_data = self.data.geo_eligibility.data
    self.data.geo_index = ['0', '1', '2', '3', '4']

  def testWithinConstraint(self):
    """check that _constraint_not_satisfied returns False when it's ok."""
    mm = TBRMatchedMarkets(self.data, self.par)
    self.assertFalse(mm._constraint_not_satisfied(0.5, 0, 1))

  def testNotWithinConstraint(self):
    """check that _constraint_not_satisfied returns False."""
    mm = TBRMatchedMarkets(self.data, self.par)
    self.assertTrue(mm._constraint_not_satisfied(0.5, 0, 0.4))
    self.assertTrue(mm._constraint_not_satisfied(0.5, 0.6, 1))

  def testVolumeRatioBetweenBounds(self):
    """Volume ratio between the two groups is not within 1/2 and 2."""
    self.par.volume_ratio_tolerance = 1
    mm = TBRMatchedMarkets(self.data, self.par)
    treatment_group = set([0])
    control_group = set([4])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))
    treatment_group = set([4])
    control_group = set([0])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))

  def testGeoRatioBetweenBounds(self):
    """Number of geos ratio between the two groups is not within 1/2 and 2."""
    self.par.geo_ratio_tolerance = 1
    mm = TBRMatchedMarkets(self.data, self.par)
    treatment_group = set([0])
    control_group = set([2, 3, 4])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))
    treatment_group = set([2, 3, 4])
    control_group = set([0])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))

  def testTreatmentShareBetweenBounds(self):
    """Treatment response share between the two groups is not within (0.4,0.7)."""
    self.par.treatment_share_range = (0.4, 0.7)
    mm = TBRMatchedMarkets(self.data, self.par)
    treatment_group = set([0])
    control_group = set([2, 3, 4])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))
    treatment_group = set([2, 3, 4])
    control_group = set([0])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))

  def testNumberTreatmentGeosBetweenBounds(self):
    """Treatment group size is not within (2,3)."""
    self.par.treatment_geos_range = (2, 3)
    mm = TBRMatchedMarkets(self.data, self.par)
    treatment_group = set([0])
    control_group = set([2, 3, 4])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))
    treatment_group = set([1, 2, 3, 4])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))

  def testNumberControlGeosBetweenBounds(self):
    """Treatment group size is not within (2,3)."""
    self.par.control_geos_range = (2, 3)
    mm = TBRMatchedMarkets(self.data, self.par)
    treatment_group = set([0])
    control_group = set([1])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))
    control_group = set([1, 2, 3, 4])
    self.assertFalse(
        mm.design_within_constraints(treatment_group, control_group))

class GreedySearch(unittest.TestCase):
  """Test method 'greedy_search'."""

  def setUp(self):
    super().setUp()
    response_geo1 = [
        255.2, 165.8, 186.0, 160.9, 218.1, 165.7, 212.9, 207.7, 224.4, 205.0,
        247.2, 145.1, 191.1, 173.6
    ]
    response_geo2 = [
        132.5, 87.8, 89.4, 78.5, 117.3, 54.0, 134.9, 84.8, 106.4, 95.0, 129.2,
        58.8, 93.6, 92.3
    ]
    response_geo3 = [10 + 1 * i for i in range(len(response_geo1))]
    dates = pd.date_range('2020-03-01', periods=len(response_geo1))
    df = pd.DataFrame({
        'date': list(dates) * 3,
        'geo': sorted([1, 2, 3] * len(dates)),
        'response': response_geo1 + response_geo2 + response_geo3
    })
    self.dataframe = df
    self.data = TBRMMData(df, 'response')
    self.par = TBRMMDesignParameters(
        n_test=7, iroas=3.0)
    self.default_geo_eligibility_data = self.data.geo_eligibility.data

  def testGreedySearch(self):
    """Search finds a design with 1 and 2 geos in treatment."""
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.greedy_search()
    treatment_groups = [{'1'}, {'1', '3'}]
    control_groups = [{'2'}, {'2'}]
    treatment_index = [[0], [0, 2]]
    control_index = [[1], [1]]
    for ind in range(len(designs)):
      diag = TBRMMDiagnostics(
          self.data.aggregate_time_series(set(treatment_index[ind])), self.par)
      diag.x = self.data.aggregate_time_series(set(control_index[ind]))
      corr = diag.corr
      required_impact = diag.estimate_required_impact(corr)
      self.assertSetEqual(designs[ind].treatment_geos, treatment_groups[ind])
      self.assertSetEqual(designs[ind].control_geos, control_groups[ind])
      self.assertTupleEqual(designs[ind].score.score,
                            (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
      self.assertEqual(designs[ind].score.diag.corr, designs[ind].diag.corr)
      self.assertEqual(designs[ind].score.score.corr,
                       round(designs[ind].diag.corr, 2))

  def testGreedySearchScoreWithIroas(self):
    """Tests the optimal design is found based on correlation and iROAS."""
    self.par.budget_range = (0.01, 1000)
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.exhaustive_search()

    tmp_diag = TBRMMDiagnostics(
        self.data.aggregate_time_series(set([0])), self.par)
    tmp_diag.x = self.data.aggregate_time_series(set([1]))
    corr = tmp_diag.corr
    required_impact = tmp_diag.required_impact
    iroas = required_impact / self.par.budget_range[1]

    self.assertSetEqual(designs[0].treatment_geos, {'1'})
    self.assertSetEqual(designs[0].control_geos, {'2'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / iroas))

  def testGreedySearchFailsToFindDesignWithinConstraints(self):
    """Search does not find a valid design since correlation is too low."""
    self.par.min_corr = 0.9
    mm = TBRMatchedMarkets(self.data, self.par)

    designs = mm.greedy_search()
    treatment_groups = [{'1'}, {'1', '3'}]
    control_groups = [{'2'}, {'2'}]
    treatment_index = [[0], [0, 2]]
    control_index = [[1], [1]]
    for ind in range(len(designs)):
      diag = TBRMMDiagnostics(
          self.data.aggregate_time_series(set(treatment_index[ind])), self.par)
      diag.x = self.data.aggregate_time_series(set(control_index[ind]))
      corr = diag.corr
      required_impact = diag.estimate_required_impact(corr)
      self.assertSetEqual(designs[ind].treatment_geos, treatment_groups[ind])
      self.assertSetEqual(designs[ind].control_geos, control_groups[ind])
      self.assertTupleEqual(designs[ind].score.score,
                            (0, 1, 1, 1, round(corr, 2), 1 / required_impact))
      self.assertEqual(designs[ind].score.diag.corr, designs[ind].diag.corr)
      self.assertEqual(designs[ind].score.score.corr,
                       round(designs[ind].diag.corr, 2))

  def testGreedySearchFixedTreatmentGeo(self):
    """Search finds a design with geos fixed treatment group."""
    df_geo_elig = self.default_geo_eligibility_data
    df_geo_elig.loc['1'] = [0, 1, 0]  # geo 1 (index 0) is fixed to Treatment.
    geo_elig = geoeligibility.GeoEligibility(df_geo_elig)
    data = TBRMMData(self.dataframe, 'response', geo_elig)
    self.par.treatment_geos_range = (1, 1)
    mm = TBRMatchedMarkets(data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(data.aggregate_time_series(set([0])), self.par)
    diag.x = data.aggregate_time_series(set([1]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'1'})
    self.assertSetEqual(designs[0].control_geos, {'2'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

  def testGreedySearchFixedTreatmentGeoFail(self):
    """Search fails with fixed treatment group as all design do not pass dwtest."""
    df_geo_elig = self.default_geo_eligibility_data
    df_geo_elig.loc['2'] = [0, 1, 0]  # geo 2 (index 1) is fixed to Treatment.
    geo_elig = geoeligibility.GeoEligibility(df_geo_elig)
    data = TBRMMData(self.dataframe, 'response', geo_elig)
    self.par.treatment_geos_range = (1, 1)
    mm = TBRMatchedMarkets(data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(data.aggregate_time_series(set([1])), self.par)
    diag.x = data.aggregate_time_series(set([0]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'2'})
    self.assertSetEqual(designs[0].control_geos, {'1'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 0, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

  def testGreedySearchTreatmentSizeRange(self):
    """Search succeed with constrained treatment group size."""
    # limit the search to treatment groups of size 2
    self.par.treatment_geos_range = (2, 2)
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(
        self.data.aggregate_time_series(set([0, 2])), self.par)
    diag.x = self.data.aggregate_time_series(set([1]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'1', '3'})
    self.assertSetEqual(designs[0].control_geos, {'2'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

  def testGreedySearchControlSizeRange(self):
    """Search succeed with constrained treatment group size."""
    # limit the search to control groups of size 2
    self.par.control_geos_range = (2, 2)
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(
        self.data.aggregate_time_series(set([0])), self.par)
    diag.x = self.data.aggregate_time_series(set([1, 2]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'1'})
    self.assertSetEqual(designs[0].control_geos, {'2', '3'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

  def testGreedySearchTreatmentGeoShare(self):
    """Search succeed with constrained treatment group revenue share."""
    # limit the search to treatment groups with a revenue share >0.65
    # note that the largest single geos only has a share of 0.635031, so we
    # need at least two geos in treatment
    self.par.treatment_share_range = (0.65, 0.99)
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(
        self.data.aggregate_time_series(set([0, 2])), self.par)
    diag.x = self.data.aggregate_time_series(set([1]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'1', '3'})
    self.assertSetEqual(designs[0].control_geos, {'2'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

  def testGreedySearchVolumeRatioTolerance(self):
    """Search succeed with constrained volume ratio tolerance."""
    # limit the search to groups with a volume ratio >0.5.
    # note that the best design (Treatment=geo1, Control=geo2) has a ratio of
    # 0.4909, so we need at least two geos in control
    self.par.volume_ratio_tolerance = 1
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(self.data.aggregate_time_series(set([0])), self.par)
    diag.x = self.data.aggregate_time_series(set([1, 2]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'1'})
    self.assertSetEqual(designs[0].control_geos, {'2', '3'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

  def testGreedySearchGeoRatioTolerance(self):
    """Search succeed with constrained geo ratio tolerance."""
    # limit the search to groups with a geo ratio >0.52 and <1.9. The constraint
    # would raise an error (division by zero) since the search starts with
    # all geos in control and 0 geos in treatment
    self.par.geo_ratio_tolerance = 0.9
    mm = TBRMatchedMarkets(self.data, self.par)
    designs = mm.greedy_search()
    diag = TBRMMDiagnostics(self.data.aggregate_time_series(set([0])), self.par)
    diag.x = self.data.aggregate_time_series(set([1]))
    corr = diag.corr
    required_impact = diag.estimate_required_impact(corr)
    self.assertTrue(len(designs) == 1)  # pylint: disable=g-generic-assert
    self.assertSetEqual(designs[0].treatment_geos, {'1'})
    self.assertSetEqual(designs[0].control_geos, {'2'})
    self.assertTupleEqual(designs[0].score.score,
                          (1, 1, 1, 1, round(corr, 2), 1 / required_impact))
    self.assertEqual(designs[0].score.diag.corr, designs[0].diag.corr)
    self.assertEqual(designs[0].score.score.corr, round(designs[0].diag.corr,
                                                        2))

if __name__ == '__main__':
  unittest.main()


text:
package android.github.thiagonascimento.com.menucake;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by Thiago on 02/11/2016.
 */

public class Rocambole extends AppCompatActivity {

    ImageView imageViewRocambole;
    TextView txtrocambole;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rocambole);
        imageViewRocambole = (ImageView) findViewById(R.id.imagerocambole);
        txtrocambole = (TextView) findViewById(R.id.textViewrocambole);
    }
}


text:
package connector

import (
	"encoding/binary"
	"errors"
	"net"
	"time"

	"github.com/kyf/klein/message"
)

var (
	ErrCodehandshakeInvalidSize = 101
	ErrCodehandshakeInvalidBody = 102

	SuccessCodehandshake = 200
)

const (
	SessionRegisterTimeout   = time.Second * 10
	SessionUnRegisterTimeout = time.Second * 10
)

type MessagePackage struct {
	ch chan string
	m  *MessageRequest
}

type Client struct {
	conn       net.Conn
	ConnId     ID
	UserId     [32]byte
	DeviceInfo []byte
	ReqCh      chan *MessageRequest
	ReplyCh    chan *ReceiveAck
}

func NewClient(c net.Conn) *Client {
	return &Client{conn: c, ConnId: GeneralId()}
}

func (this *Client) Read(p []byte) (int, error) {
	return this.conn.Read(p)
}

func (this *Client) Write(p []byte) (int, error) {
	return this.conn.Write(p)
}

func (this *Client) ReadFull(p []byte) error {
	num, err := this.conn.Read(p)
	if err != nil {
		return err
	}

	if num != len(p) {
		return errors.New("client.ReadFull: not full")
	}

	return nil
}

func (this *Client) ReadMessageHeader(p []byte) error {
	err := this.ReadFull(p)
	if err != nil {
		return errors.New("message header is invalid")
	}
	return nil
}

func (this *Client) WriteError(err error) {
	this.Write([]byte(err.Error()))
}

func (this *Client) Id() ID {
	return this.ConnId
}

func (this *Client) handshake() error {
	length := make([]byte, 4)
	err := this.ReadFull(length)
	if err != nil {
		this.Write([]byte{byte(ErrCodehandshakeInvalidSize)})
		return err
	}

	_len := binary.BigEndian.Uint64(length)
	buf := make([]byte, _len)
	err = this.ReadFull(buf)
	if err != nil {
		this.Write([]byte{byte(ErrCodehandshakeInvalidBody)})
		return err
	}

	userid, deviceInfo := buf[:32], buf[32:]
	copy(this.UserId[:], userid)
	this.DeviceInfo = deviceInfo

	this.Write([]byte{byte(SuccessCodehandshake)})
	return nil
}

func (this *Client) Wait() {
	waitReplyChs := make(map[seq]chan int)

	go func() {
		for rp := range this.ReplyCh {

		}
	}()

	for m := range this.ReqCh {
		msg := &message.Message{
			Type:       m.MsgType,
			SequenceId: m.SequenceId,
			ConnId:     m.ConnId,
			Sender:     m.Sender,
			Receiver:   m.Receiver,
			Body:       m.Body,
		}

		data, err := msg.Encode()
		_, err := this.Write(data)
		if err != nil {

		}
	}
}


text:
(function(){

  var app = angular.module('nrzLightifyApp',[
    'ngRoute',
    'nrzLightify'
  ]);

  app.config(function($routeProvider, $locationProvider) {
    $routeProvider
    .when('/page1', {
      templateUrl: 'page1.html',
      controller: 'nrzLightifyPageCtrl'
    })
    .when('/page2', {
      templateUrl: 'page2.html',
      controller: 'nrzLightifyPageCtrl'
    })
    .otherwise({
      redirectTo: '/page1'
    });
  });

  app.controller('nrzLightifyCtrl', function($scope){
    $scope.heading = "Angularjs Bootstrap Lightify";
  });

  app.controller('nrzLightifyPageCtrl', function($scope, nrzLightify){
    $scope.lightifyMe = function(type, delaySeconds) {
      nrzLightify({
        type: type,
        text: 'A notification!'
      }, delaySeconds);
    };

    $scope.lightifyMeFlash = function(type, delaySeconds) {
      nrzLightify({
        type: 'info',
        text: 'Flash notification will appear when you change the route.'
      });

      nrzLightify.flash({
        type: type,
        text: 'A flash notification!'
      }, delaySeconds);
    };
  });

})();


text:
package org.apache.derbyTesting.functionTests.tests.compatibility;

import junit.framework.Test;

/**
 * Tests all available versions of Derby against each other.
 */
public class _SuiteOldFull
        extends _Suite {

    public _SuiteOldFull(String name) {
        super(name);
        throw new IllegalStateException("invoke suite() instead");
    }

    /**
     * Returns an extended suite of compatibility tests.
     *
     * @return A test suite.
     */
    public static Test suite() {
        configurator = VersionCombinationConfigurator.getInstanceOldFull();
        return _Suite.suite();
    }
}


text:
/**
 *    @file
 *          Provides an implementation of the BLEManager singleton object
 *          for the MW320 platforms.
 */

/* this file behaves like a config.h, comes first */


text:
package com.gmail.entityreborn.extensionloader;

import java.io.File;

import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.gmail.entityreborn.extensionloader.api.ExtensionAnnotation;
import com.gmail.entityreborn.extensionloader.api.BaseExtensionType;

@SuppressWarnings("rawtypes")
public abstract class ExtensionManager {
    protected List<Class> annotated;
    protected List<File> dirs;
    protected final Map<String, ExtensionClassLoader> loaders = new LinkedHashMap<String, ExtensionClassLoader>();
    protected List<BaseExtensionType> subclassed;

    public ExtensionManager() {
        this.subclassed = new ArrayList<BaseExtensionType>();
        this.annotated = new ArrayList<Class>();
        this.dirs = new ArrayList<File>();
    }

    public boolean addDirectory(String dir) {
        if (!dirs.contains(dir)) {
            File d = new File(dir);

            if (d.isDirectory()) {
                dirs.add(d);
                return true;
            }
        }

        return false;
    }

    public List<Class> getAnnotated() {
        return new ArrayList<Class>(annotated);
    }

    @SuppressWarnings("unchecked")
    public List<Class> getAnnotated(Class type) {
        List<Class> retn = new ArrayList<Class>();

        for (Class c : annotated) {
            if (c.isAnnotationPresent(type)) {
                retn.add(c);
            }
        }

        return retn;
    }

    public List<BaseExtensionType> getInterfaced() {
        return new ArrayList<BaseExtensionType>(subclassed);
    }

    @SuppressWarnings("unchecked")
    public List<BaseExtensionType> getInterfaced(Class iface) {
        List<BaseExtensionType> retn = new ArrayList<BaseExtensionType>();

        for (BaseExtensionType c : subclassed) {
            if (iface.isAssignableFrom(c.getClass())) {
                retn.add(c);
            }
        }

        return retn;
    }

    public ExtensionClassLoader getLoader(String klass) {
        return loaders.get(klass);
    }

    public boolean loadFor(Class type) {
        // Using BaseExtensionType to load extensions is
        // pointless. Also, we only want to load from types
        // that inherit BaseExtensionType.
        if ((type == BaseExtensionType.class) || (!type.isAnnotation()
                && !BaseExtensionType.class.isAssignableFrom(type))) {
            return false;
        }

        boolean retn = false;

        for (File dir : dirs) {
            if (!dir.isDirectory()) {
                continue;
            }

            File[] files = dir.listFiles();

            for (File file : files) {
                if (file.getName().endsWith(".jar") && file.isFile()) {
                    if (loadExtensionsInFile(file, type)) {
                        retn = true;
                    }
                }
            }
        }

        return retn;
    }

    protected abstract List<String> getClassPaths(File file);

    @SuppressWarnings("unchecked")
    protected boolean loadExtensionsInFile(File file, Class type) {
        ExtensionClassLoader loader;
        URL[] source;

        boolean retn = false;

        try {
            source = new URL[] { file.toURI().toURL() };
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return false;
        }

        loader = new ExtensionClassLoader(source, getClass().getClassLoader());

        for (String name : getClassPaths(file)) {
            Class<?> klass;
            try {
                klass = Class.forName(name, true, loader);

                if (klass == type) {
                    continue;
                }
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
                continue;
            }

            if (!loaders.containsKey(klass.toString())) {
                loaders.put(klass.getName(), loader);
            } else {
                // Already loaded!
                continue;
            }

            if (type.isAnnotation() && klass.isAnnotationPresent(type)) {
                annotated.add(klass);
                retn = true;
            } else if (type.isAssignableFrom(klass)) {
                BaseExtensionType inst;

                try {
                    Class<? extends BaseExtensionType> extension = klass
                            .asSubclass(type);
                    Constructor<? extends BaseExtensionType> constructor = extension
                            .getConstructor();

                    inst = constructor.newInstance();
                    inst.instantiate(this, loader);
                    retn = true;

                } catch (Throwable e) {
                    e.printStackTrace();
                    continue;
                }

                subclassed.add(inst);
            }
        }

        return retn;
    }
}


text:
@interface PATag : NSObject

- (instancetype)initWithName:(NSString *)name andValue:(BOOL)value;

- (NSString *)getName;
- (id)getValue;
- (NSString *)getType;

- (NSDictionary *)toDictionary;

@end


text:
//
// Copyright 2014 SandRock
//
// 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.
//

namespace SrkToolkit.Mvvm
{
    /// <summary>
    /// Navigation states for a Windows Phone 7 application.
    /// </summary>
    public enum PhoneAppNavigationState
    {
        /// <summary>
        /// Before the first navigation of the application lifetime (ephemeral state).
        /// </summary>
        Starting,

        /// <summary>
        /// First navigation of the application lifetime.
        /// </summary>
        Started,

        /// <summary>
        /// Internal navigation.
        /// </summary>
        Internal,

        /// <summary>
        /// Before the application is activated (ephemeral state).
        /// </summary>
        Activated,

        /// <summary>
        /// Application is activated.
        /// </summary>
        Activating,

        /// <summary>
        /// The application is deactivated.
        /// </summary>
        Deactivated,

        /// <summary>
        /// The application is closed.
        /// </summary>
        Closed,
    }
}


text:
define(['lib/angular'], function(angular) {
    return angular.module('controllers', [])
})


text:
    This music phrase is currently empty.

      <[$index + 1]>

      <select ng-model="localValue[$index].label" ng-options="readableNoteName as readableNoteName for readableNoteName in choices" required>
      </select>

      <button type="button" class="pull-right" ng-click="deleteItem($index)">Delete</button>

    <button type="button" ng-click="addItem()" class="pull-right">
      <[getAddItemText()]>
    </button>


text:
set -x

USAGE() {
cat << EOF
Usage: ${0##*/} <-i ident.p12> [-p password] <-m profile.mobileprovision> [-a com.example.app] [-n NewName] [-I Info.plist]
     -i ident.p12                  The signing identity file.
     -p password                   The password of signing identity file.
     -m profile.mobileprovision    Signing provision profile
     -a com.example.app            Override CFBundleIdentifier
     -n NewName                    Override CFBundleName
     -I Info.plist                 Override plist file target
     -h help
EOF
exit 1
}

while getopts "i:p::m:a::n::I::h" opt ; do
    case "$opt" in
        i) SIGNFILE=$OPTARG ;;
        p) SIGNPASS=$OPTARG ;;
        m) PROVFILE=$OPTARG ;;
        a) OVER_APPID=$OPTARG ;;
        n) OVER_NAME=$OPTARG ;;
        I) OVER_FILE=$OPTARG ;;
        h|*) USAGE ;;
    esac
done

if [ ! -f "$SIGNFILE" ]
then
    echo "signing identity file not exists"
    exit 1
fi
if [ ! -f "$PROVFILE" ]
then
    echo "signing provision profile not exists"
    exit 1
fi

if [ "$OVER_APPID" != "" ]
then
    if [ ! -f "$OVER_FILE" ]
    then
        echo "Use -I Info.plist to find plist"
        exit 7
    fi
    /usr/libexec/PlistBuddy -c "set :CFBundleIdentifier $OVER_APPID" "$OVER_FILE"
fi
if [ "$OVER_NAME" != "" ]
then
    if [ ! -f "$OVER_FILE" ]
    then
        echo "Use -I Info.plist to find plist"
        exit 7
    fi
    /usr/libexec/PlistBuddy -c "set :CFBundleName $OVER_NAME" "$OVER_FILE"
fi

RAND_KEYCHAIN=cmdbuild$$.keychain
security create-keychain -p $$ $RAND_KEYCHAIN || exit 2
security default-keychain -s $RAND_KEYCHAIN || exit 2
security list-keychains -s $RAND_KEYCHAIN || exit 2

trap "{
    security delete-keychain $RAND_KEYCHAIN || echo Cannot delete keychain $RAND_KEYCHAIN
}" EXIT

if [ "$OVER_NAME" != "" ]
then
    if [ -f "$OVER_FILE" ]
    then
        trap "{
            git checkout \"$OVER_FILE\"
            security delete-keychain $RAND_KEYCHAIN || echo Cannot delete keychain $RAND_KEYCHAIN
        }" EXIT
    fi
fi

if [ "$SIGNPASS" == "" ]
then
security import "$SIGNFILE" -k $RAND_KEYCHAIN -T /usr/bin/codesign || exit 3
else
security import "$SIGNFILE" -k $RAND_KEYCHAIN -P "$SIGNPASS" -T /usr/bin/codesign || exit 3
fi
security unlock-keychain -p $$ $HOME/Library/Keychains/$RAND_KEYCHAIN || exit 4
security set-keychain-settings -u $RAND_KEYCHAIN || exit 5
#security show-keychain-info $RAND_KEYCHAIN

SIGN_IDEN=$(security find-identity -p codesigning -v $RAND_KEYCHAIN|head -n1|cut -d "\"" -f 2)
if [ "$SIGN_IDEN" == "" ]
then
    exit 5
fi
#echo $SIGN_IDEN

# For macOS 10.12+, new security enforcement need following command.
security set-key-partition-list -S apple: -k $$ -D "$SIGN_IDEN" -t private

PROV_UUID=$(/usr/libexec/PlistBuddy -c "Print UUID" /dev/stdin <<< `security cms -D -i "$PROVFILE"`)
if [ "$PROV_UUID" == "" ]
then
    exit 6
fi
if [ ! -d "$HOME/Library/MobileDevice/Provisioning Profiles/" ]
then
    mkdir -p "$HOME/Library/MobileDevice/Provisioning Profiles/"
fi
cp "$PROVFILE" "$HOME/Library/MobileDevice/Provisioning Profiles/$PROV_UUID.mobileprovision"
#echo $PROV_UUID

xcodebuild $CMDBUILD_ARGS CODE_SIGN_IDENTITY="$SIGN_IDEN" PROVISIONING_PROFILE="$PROV_UUID" OTHER_CODE_SIGN_FLAGS="--keychain '$HOME/Library/Keychains/$RAND_KEYCHAIN'"

exit 0


text:
package com.cloudbees.simplediskusage;

import hudson.*;
import hudson.init.InitMilestone;
import hudson.model.Job;
import hudson.model.TopLevelItem;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.NamingThreadFactory;
import jenkins.model.Jenkins;
import jenkins.util.Timer;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;

import javax.inject.Singleton;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

@Extension
@Singleton
public class QuickDiskUsagePlugin extends Plugin {

    public static final int QUIET_PERIOD = 15 * 60 * 1000;

    private static final Executor singleExecutorService = Executors.newSingleThreadExecutor(
            new NamingThreadFactory(Executors.defaultThreadFactory(),"Simple disk usage computation"));

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

    private final CopyOnWriteArrayList<DiskItem> directoriesUsages = new CopyOnWriteArrayList<>();

    private final CopyOnWriteArrayList<JobDiskItem> jobsUsages = new CopyOnWriteArrayList<>();

    private long lastRunStart = 0;

    private long lastRunEnd = 0;

    private transient final AtomicInteger progress = new AtomicInteger();

    private transient final AtomicInteger total = new AtomicInteger();

    @Override
    public void start() throws Exception {
        try {
            load();
        } catch (IOException e) {
            logger.log(Level.WARNING, "Failed to load " + getConfigXml(), e);
        }
        if (isRunning()) {
            // It's impossible, the plugin was just loaded. Let's reset end date
            lastRunEnd = lastRunStart;
        }
    }

    public void refreshData() {
        if (!isRunning()) {
            singleExecutorService.execute(computeDiskUsage);
        }
    }

    public void refreshDataOnStartup() {
         singleExecutorService.execute(computeDiskUsageOnStartup);
    }

    public CopyOnWriteArrayList<DiskItem> getDirectoriesUsages() throws IOException {
        if (System.currentTimeMillis() - lastRunEnd >= QUIET_PERIOD) {
            refreshData();
        }
        return directoriesUsages;
    }

    public CopyOnWriteArrayList<JobDiskItem> getJobsUsages() throws IOException {
        if (System.currentTimeMillis() - lastRunEnd >= QUIET_PERIOD) {
            refreshData();
        }
        return jobsUsages;
    }

    public long getLastRunStart() {
        return lastRunStart;
    }

    public long getLastRunEnd() {
        return lastRunEnd;
    }

    public String getSince() {
        return Util.getPastTimeString(System.currentTimeMillis() - lastRunEnd);
    }

    public String getDuration() {
        return Util.getTimeSpanString(lastRunEnd - lastRunStart);
    }

    public boolean isRunning() {
        return lastRunEnd < lastRunStart;
    }

    @RequirePOST
    public void doRefresh(StaplerRequest req, StaplerResponse res) throws IOException, ServletException {
        refreshData();
        res.forwardToPreviousPage(req);
    }

    @RequirePOST
    public void doClean(StaplerRequest req, StaplerResponse res) throws IOException, ServletException {
        Jenkins jenkins = Jenkins.get();
        final Job job = jenkins.getItemByFullName(req.getParameter("job"), Job.class);
        Timer.get().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    job.logRotate();
                } catch (Exception e) {
                    logger.log(Level.WARNING, "logRotate failed", e);
                }
            }
        });
        res.forwardToPreviousPage(req);
    }

    class JobUsageListener implements UsageComputation.CompletionListener {
        final Job<?, ?> job;

        JobUsageListener(Job<?, ?> job) {
            this.job = job;
        }

        @Override
        public void onCompleted(Path dir, long usage) {
            JobDiskItem jobDiskItem = new JobDiskItem(job, usage / 1024);
            jobsUsages.remove(jobDiskItem);
            jobsUsages.add(jobDiskItem);
            progress.incrementAndGet();
        }
    }

    class DirectoryUsageListener implements UsageComputation.CompletionListener {
        final String displayName;

        DirectoryUsageListener(String displayName) {
            this.displayName = displayName;
        }

        @Override
        public void onCompleted(Path dir, long usage) {
            DiskItem diskItem = new DiskItem(displayName, dir.toFile(), usage / 1024);
            directoriesUsages.remove(diskItem);
            directoriesUsages.add(diskItem);
            progress.incrementAndGet();
        }
    }

    private void registerJobs(UsageComputation uc) throws IOException, InterruptedException {
        Jenkins jenkins = Jenkins.get();

        // Remove useless entries for jobs
        for (JobDiskItem item : jobsUsages) {
            if (!item.getPath().exists() || jenkins.getItemByFullName(item.getFullName(), Job.class) == null) {
                jobsUsages.remove(item);
            }
        }

        // Add or update entries for jobs
        for (Job job : jenkins.getAllItems(Job.class)) {
            if (job instanceof TopLevelItem) {
                uc.addListener(job.getRootDir().toPath(), new JobUsageListener(job));
            }
        }
    }

    private File getJenkinsBaseDirectory() throws NullPointerException {
        // finds the lowest non-null value of parent.
        // for example, would return "/" for "/var/jenkins_home"
        Jenkins jenkins = Jenkins.get();
        Path basePath = jenkins.getRootDir().toPath();
        try {
            while (basePath.getParent() != null) {
                basePath = basePath.getParent();
            }
        }
        catch (NullPointerException e){
            logger.log(Level.WARNING, "cloudbees-disk-usage-plugin: Could not find Jenkins Base Directory");
        }
        return basePath.toFile();
    }

    private void registerDirectoriesFS(UsageComputation uc) throws IOException, InterruptedException {
        Map<File, String> directoriesToProcess = new HashMap<>();
        // Display JENKINS_FS size
        File rootPath = getJenkinsBaseDirectory();
        directoriesToProcess.put(rootPath, "JENKINS_FS");

        // Add or update entries for directories
        for (Map.Entry<File, String> item : directoriesToProcess.entrySet()) {
            uc.addListener(item.getKey().toPath(), new DirectoryUsageListener(item.getValue()));
        }
    }

    private void registerDirectories(UsageComputation uc) throws IOException, InterruptedException {
        Jenkins jenkins = Jenkins.get();
        Map<File, String> directoriesToProcess = new HashMap<>();
        // Display JENKINS_HOME size
        directoriesToProcess.put(jenkins.getRootDir(), "JENKINS_HOME");
        // Display JENKINS_HOME first level sub-directories
        File[] jenkinsHomeRootDirectories = jenkins.getRootDir().listFiles();
        if (jenkinsHomeRootDirectories != null) {
            for (File child : jenkinsHomeRootDirectories) {
                if (child.isDirectory()) {
                    directoriesToProcess.put(child, "JENKINS_HOME/" + child.getName());
                }
            }
        }
        // Display java.io.tmpdir size
        directoriesToProcess.put(new File(System.getProperty("java.io.tmpdir")), "java.io.tmpdir");

        // Remove useless entries for directories
        for (DiskItem item : directoriesUsages) {
            if (!item.getPath().exists() || !directoriesToProcess.containsKey(item.getPath())) {
                directoriesUsages.remove(item);
            }
        }

        // Add or update entries for directories
        for (Map.Entry<File, String> item : directoriesToProcess.entrySet()) {
            uc.addListener(item.getKey().toPath(), new DirectoryUsageListener(item.getValue()));
        }
    }

    public int getItemsCount() {
        return total.intValue();
    }

    public int getProgress() {
        return progress.intValue();
    }

    private transient final Runnable computeDiskUsage = new Runnable() {

        public void run() {
            logger.fine("Re-estimating disk usage");
            progress.set(0);
            lastRunStart = System.currentTimeMillis();
            Jenkins jenkins = Jenkins.get();
            try (ACLContext old = ACL.as(ACL.SYSTEM)) {
                UsageComputation uc = new UsageComputation(Arrays.asList(Paths.get(System.getProperty("java.io.tmpdir")), jenkins.getRootDir().toPath()));
                registerJobs(uc);
                registerDirectories(uc);
                total.set(uc.getItemsCount());
                uc.compute();

                // Adds JENKINS_FS section with relevant disk usage info
                File rootPath = getJenkinsBaseDirectory();
                UsageComputation ucfs = new UsageComputation(Arrays.asList(rootPath.toPath()));
                registerJobs(ucfs);
                registerDirectoriesFS(ucfs);
                total.set(ucfs.getItemsCount());
                ucfs.computeFS();

                logger.fine("Finished re-estimating disk usage.");

                lastRunEnd = System.currentTimeMillis();
            } catch (IOException | InterruptedException e) {
                logger.log(Level.WARNING, "Unable to run disk usage check", e);
                lastRunEnd = lastRunStart;
            }
            try {
                // Save data
                save();
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed to save " + getConfigXml(), e);
            }
        }
    };

    private transient final Runnable computeDiskUsageOnStartup = new Runnable() {
        public void run() {
            Jenkins jenkins = Jenkins.get();
            while (jenkins.getInitLevel() != InitMilestone.COMPLETED) {
                try {
                    logger.log(Level.FINE, "Waiting for Jenkins to be up before computing disk usage");
                    Thread.sleep(3 * 60 * 1000);
                } catch (InterruptedException e) {
                    return;
                }
            }
            refreshData();
        }
    };
}


text:
package user

import (
	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/models/errors"
	"github.com/gogits/gogs/pkg/api"
	"github.com/gogits/gogs/pkg/context"
	"github.com/gogits/gogs/pkg/form"
	"github.com/gogits/gogs/pkg/setting"
)

func Search(c *context.APIContext) {

}

func GetInfo(c *context.APIContext) {
	u, err := models.GetUserByName(c.Params(":username"))
	if err != nil {
		if errors.IsUserNotExist(err) {
			c.Status(404)
		} else {
			c.Error(500, "GetUserByName", err)
		}
		return
	}

	// Hide user e-mail when API caller isn't signed in.
	if !c.IsLogged {
		u.Email = ""
	}
	c.JSON(200, api.ConvertUserToAPI(u))
}

func afterLogin(c *context.Context, u *models.User, remember bool) {
	if remember {
		days := 86400 * setting.LoginRememberDays
		c.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL, "", setting.CookieSecure, true)
		c.SetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName, u.Name, days, setting.AppSubURL, "", setting.CookieSecure, true)
	}

	c.Session.Set("uid", u.ID)
	c.Session.Set("uname", u.Name)
	c.Session.Delete("twoFactorRemember")
	c.Session.Delete("twoFactorUserID")

	// Clear whatever CSRF has right now, force to generate a new one
	c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
	if setting.EnableLoginStatusCookie {
		c.SetCookie(setting.LoginStatusCookieName, "true", 0, setting.AppSubURL)
	}
	//redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to"))
	//c.SetCookie("redirect_to", "", -1, setting.AppSubURL)

}

func AuthenticatePost(c *context.Context, f form.SignIn) {

	u, err := models.UserSignIn(f.UserName, f.Password)
	if err != nil {
		if errors.IsUserNotExist(err) {
			c.JSON(500, nil)
		} else {
			c.ServerError("UserSignIn", err)
		}
		return
	}

	if !u.IsEnabledTwoFactor() {
		afterLogin(c, u, f.Remember)
		return
	}

	c.Session.Set("twoFactorRemember", f.Remember)
	c.Session.Set("twoFactorUserID", u.ID)
	c.Redirect(setting.AppSubURL + "/user/login/two_factor")
}

func AuthenticateGet(c *context.APIContext) {
	if c.IsLogged {
		c.JSONString(c.User.FullName)
	} else {
		c.JSONString("")
	}
}

func GetAccount(c *context.APIContext) {
	if c.IsLogged {
		user := api.ConvertUserToAPI(c.User)
		c.JSONSuccess(user)
	} else {
		c.JSON(500, nil)
	}
}


text:
from openstack import resource

class RoleDomainUserAssignment(resource.Resource):
    resource_key = 'role'
    resources_key = 'roles'
    base_path = '/domains/%(domain_id)s/users/%(user_id)s/roles'

    # capabilities
    allow_list = True

    # Properties
    #: name of the role *Type: string*
    name = resource.Body('name')
    #: The links for the service resource.
    links = resource.Body('links')
    #: The ID of the domain to list assignment from. *Type: string*
    domain_id = resource.URI('domain_id')
    #: The ID of the user to list assignment from. *Type: string*
    user_id = resource.URI('user_id')


text:
import cacheManager from 'cache-manager';
import { noop, isString } from 'lodash';
import { createLogger } from 'pot-logger';
import createProxyObject from '../utils/createProxyObject';
import ms from 'ms';

const logger = createLogger('cache', 'magentaBright');
let stores = {};
let cache;
let defaultCacheKey;

export function resolveCacheStore(appConfig) {
	const { dbs } = appConfig;
	const cacheStoresMap = new Map();

	stores = {};
	cache = null;
	defaultCacheKey = null;

	Object.keys(dbs).forEach((key) => {
		const db = dbs[key];
		if (db.cache) {
			const { cache: options, ...other } = db;
			const descriptor = {
				...other,
				...options,
			};
			if (isString(descriptor.ttl)) {
				descriptor.ttl = ~~(ms(descriptor.ttl) / 1000);
			}
			if (!defaultCacheKey || options.default) {
				defaultCacheKey = key;
			}
			cacheStoresMap.set(key, descriptor);
		}
	});

	if (!cacheStoresMap.size) {
		const defaultKey = 'default';
		cacheStoresMap.set(defaultKey, {
			store: 'memory',
			max: 100,
			ttl: 60,
		});
		defaultCacheKey = defaultKey;
	}

	return cacheStoresMap;
}

export function createCacheStores(cacheStoresMap) {
	for (const [key, descriptor] of cacheStoresMap) {
		if (!descriptor.store) {
			logger.warn(`"${key}" has NOT "store"`);
			continue;
		}
		const cacheStore = cacheManager.caching(descriptor);
		stores[key] = cacheStore;
		logger.trace(`"${key}" created`);
	}
	cache = stores[defaultCacheKey];
	return { cacheStores: stores, cache };
}

export function getCache() {
	return cache;
}

export function getCacheStores() {
	return stores;
}

export default new Proxy(
	{},
	{
		get(target, key) {
			if (!cache) {
				logger.error('cache is NOT ready');
				return noop;
			}
			return cache[key];
		},
	},
);

export const cacheStores = createProxyObject(() => stores, 'CacheStores');


text:
package backends

import (
	"fmt"
	"strings"

	"github.com/docker/libswarm/beam"
)

func Debug() beam.Sender {
	backend := beam.NewServer()
	backend.OnSpawn(beam.Handler(func(ctx *beam.Message) error {
		instance := beam.Task(func(in beam.Receiver, out beam.Sender) {
			for {
				msg, err := in.Receive(beam.Ret)
				if err != nil {
					fmt.Printf("debug receive: %v", err)
					return
				}
				fmt.Printf("[DEBUG] %s %s\n", msg.Verb, strings.Join(msg.Args, " "))
				if _, err := out.Send(msg); err != nil {
					fmt.Printf("debug send: %v", err)
					return
				}
			}
		})
		_, err := ctx.Ret.Send(&beam.Message{Verb: beam.Ack, Ret: instance})
		return err
	}))
	return backend
}


text:
@interface MUKitDemoNetworkingController ()

@property (nonatomic,strong) MUKitDemoNetworkingHeaderViews *headerView;
@end

@implementation MUKitDemoNetworkingController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"MUNetworking";
    self.navigationBarTintColor = [UIColor whiteColor];
    self.navigationBarBackgroundImageMu = [UIImage imageFromColorMu:[UIColor colorWithHexString:@"#767F90"]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = [MUKitDemoNetworkingHeaderViews viewForXibNOMargainMuWithRetainObject:self];
    self.tableView.backgroundColor = [UIColor colorWithRed:242./255. green:242./255. blue:242./255. alpha:1.];
    [MUModel GlobalStatus:nil networkingStatus:^(NSUInteger status) {
        if (status == 404) {//

        }
    }];
    [MUModel GlobalConfigurationWithModelName:@"MUModel" parameterModel:@"MUParaModel" domain:@"http://room.api.zp365.com/" Certificates:nil dataFormat:@{@"Success":@"Success",@"Status":@"ret",@"Data":@"Content",@"Message":@"Result"}];
   [MUModel requestHeader:@{@"UserType":@"0"}];
}
//模型数据
Click_MUSignal(button1){
    [MUModel GET:@"api/OpenActivity/GetOpenActivityInfo" parameters:^(MUParaModel *parameter) {
        parameter.ID = @"17";
    } success:^(MUModel *model, NSArray<MUModel *> *modelArray, id responseObject) {

        self.headerView.textView1.text = [NSString stringWithFormat:@"id:%@\n\nNewHouseName:%@\n\nNewHouseAddr:%@\n\nActivityName:%@\n\nStartTime:%@\n\nEndTime:%@\n",model.id,model.NewHouseName,model.NewHouseAddr,model.ActivityName,model.StartTime,model.EndTime];
        self.headerView.textview2.text = [NSString dictionaryToJson:responseObject];

    } failure:^(NSURLSessionDataTask *task, NSError *error, NSString *errorMsg) {

    }];
}
//模型数组
Click_MUSignal(button2){
    [MUModel GET:@"api/OpenActivity/GetOpenActivityListByApp" parameters:^(MUParaModel *parameter) {

    } success:^(MUModel *model, NSArray<MUModel *> *modelArray, id responseObject) {

        NSString *resultString = @"";
        for (MUModel *tempModel in modelArray) {
            resultString = [NSString stringWithFormat:@"%@aid:%@\nActivityName:%@\n\n",resultString,tempModel.aid,tempModel.ActivityName];
        }
       self.headerView.textView1.text = resultString;
       self.headerView.textview2.text = [NSString dictionaryToJson:responseObject];

    } failure:^(NSURLSessionDataTask *task, NSError *error, NSString *errorMsg) {
    }];
}
@end


text:
package net.tridentsdk.world;

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

public class DimensionTest {

    @Test
    public void testToByte() throws Exception {
        Assert.assertEquals(Dimension.NETHER.asByte(), (byte) -1);
        Assert.assertEquals(Dimension.OVERWORLD.asByte(), (byte) 0);
        Assert.assertEquals(Dimension.END.asByte(), (byte) 1);
    }

    @Test
    public void testGetDimension() throws Exception {
        Assert.assertEquals(Dimension.dimension(-1), Dimension.NETHER);
        Assert.assertEquals(Dimension.dimension(0), Dimension.OVERWORLD);
        Assert.assertEquals(Dimension.dimension(1), Dimension.END);
        Assert.assertEquals(Dimension.dimension(5), null);
    }
}


text:
////
//// A little fun driving a view with cytoscape.
////

// Let jshint pass over over our external globals (browserify takes
// care of it all).
/* global jQuery */
/* global global_id */
/* global global_golr_server */
/* global global_barista_location */
/* global global_minerva_definition_name */
/* global global_golr_neo_server */
/* global jsPlumb */
/* global global_barista_token */
/* global global_collapsible_relations */
/* global global_barista_token */

// Code here will be ignored by JSHint, as we are technically
// "redefining" jQuery (although we are not).
/* jshint ignore:start */
var jQuery = require('jquery');
/* jshint ignore:end */
var selectize = require('selectize');

var us = require('underscore');
var bbop = require('bbop-core');

var amigo = require('amigo2');
var golr_manager = require('bbop-manager-golr');
var golr_conf = require('golr-conf');
var golr_response = require('bbop-response-golr');

// // Help with strings and colors--configured separately.
// var aid = new bbop_legacy.context(amigo.data.context);

var model = require('bbop-graph-noctua');
var minerva_requests = require('minerva-requests');
var class_expression = require('class-expression');

var widgetry = require('noctua-widgetry');

// Aliases
var each = us.each;
var noctua_graph = model.graph;
var noctua_node = model.node;
var noctua_annotation = model.annotation;
var edge = model.edge;
var is_defined = bbop.is_defined;
var what_is = bbop.what_is;
var uuid = bbop.uuid;

var barista_response = require('bbop-response-barista');

//
var jquery_engine = require('bbop-rest-manager').jquery;
var minerva_manager = require('bbop-manager-minerva');

///
/// ...
///

var createNEOBioAC = function(element_id){

    // GOlr manager.
    var engine = new jquery_engine(golr_response);
    engine.use_jsonp(true);
    var gconf = new golr_conf.conf(amigo.data.golr);
    var manager =
	    new golr_manager(global_golr_neo_server, gconf, engine, 'async');
    manager.set_personality('ontology');
    manager.add_query_filter('document_category', 'ontology_class', ['*']);
    manager.add_query_filter('regulates_closure', 'CHEBI:23367', ['*']);

    var items = {};

    var selectized = jQuery('#' + element_id).selectize({
	valueField: 'annotation_class',
	labelField: 'annotation_class_label',
	searchField: 'annotation_class_label',
	create: false,
	render: {
            option: function(item, escape) {
		return '
' +
		    escape(item['annotation_class_label']) + ' (' +
		    escape(item['annotation_class']) + ')' +
		    '
';
            }
	},

	load: function(query, callback) {
	    // At least a length of 3 to operate.
            if( ! query.length ){
	    	return callback();
	    }

	    manager.set_comfy_query(query);
            manager.search().then(function(resp){
		callback(resp.documents() || []);
            }).done();
	},
	// onType: function(){
	//     selectized[0].selectize.clearCache("option");
	//     selectized[0].selectize.clearOptions();
	// },
	onItemAdd: function(value, $item){
	    items[value] = true;
	},
	onItemRemove: function(value){
	    delete items[value];
	},
	onInitialize: function(){
	    if( jQuery('#' + element_id).val() ){
		items[jQuery('#' + element_id).val()] = true;
	    }
	}
    });

    this.values = function(){
	return us.keys(items);
    };

};

var createComplexAC = function(element_id){

    // GOlr manager.
    var engine = new jquery_engine(golr_response);
    engine.use_jsonp(true);
    var gconf = new golr_conf.conf(amigo.data.golr);
    var manager =
	    new golr_manager(global_golr_server, gconf, engine, 'async');
    manager.set_personality('ontology');
    manager.add_query_filter('document_category', 'ontology_class', ['*']);
    // macromolecular complex
    manager.add_query_filter('regulates_closure', 'GO:0032991', ['*']);
    // protein complex
    //manager.add_query_filter('regulates_closure', 'GO:0043234', ['*']);

    var items = {};

    var selectized = jQuery('#' + element_id).selectize({
	valueField: 'annotation_class',
	labelField: 'annotation_class_label',
	searchField: 'annotation_class_label',
	create: false,
	render: {
            option: function(item, escape) {
		return '
' +
		    escape(item['annotation_class_label']) + ' (' +
		    escape(item['annotation_class']) + ')' +
		    '
';
            }
	},
	load: function(query, callback) {
	    // At least a length of 3 to operate.
            if( ! query.length ){
	    	return callback();
	    }

	    manager.set_comfy_query(query);
            manager.search().then(function(resp){
		callback(resp.documents() || []);
            }).done();
	},
	onItemAdd: function(value, $item){
	    items[value] = true;
	},
	onItemRemove: function(value){
	    delete items[value];
	},
	onInitialize: function(){
	    if( jQuery('#' + element_id).val() ){
		items[jQuery('#' + element_id).val()] = true;
	    }
	}
    });

    this.values = function(){
	return us.keys(items);
    };

};

// Start the day the jQuery way.
jQuery(document).ready(function(){
    //jQuery('#select').selectize({});

    console.log('mmcc ready');

    var bioac = new createNEOBioAC('select-bio');
    var compac = new createComplexAC('select-term');

    jQuery('#submit').click(function(){

	if( compac.values().length !== 1 ){
	    alert('You must enter and select *one* macromolecular complex.');
	}else if( bioac.values().length === 0 ){
	    alert('You must enter and select one or more bioentities.');
	}else{

	    // We know we have just one, convert it if it is the
	    // default value.
	    var cp = compac.values()[0];
	    if( cp === 'macromolecular complex' ){
		cp = 'GO:0032991';
		//cp = 'GO:0043234';
	    }

	    var reqs = new minerva_requests.request_set(global_barista_token,
							global_id);

	    // All as link in to complex.
	    //var ce = new class_expression();
	    //ce.as_set('intersection', [cp].concat(bio_svfs));
	    var complex_ind_id = reqs.add_individual(cp);

	    // Collect as has_parts.
	    each(bioac.values(), function(bid){
		var bind = reqs.add_individual(bid);
		reqs.add_fact([complex_ind_id, bind, 'BFO:0000051']);
	    });

	    sendRequestToMinerva(reqs);

	    //alert('submitted:' + bioac.values().join(', '));
	}
    });

    // When all is said and done, let's also fillout the user name
    // just for niceness. This is also a test of CORS in express.
    if( global_barista_token ){
	widgetry.user_check(global_barista_location,
			    global_barista_token, 'user_name_info', false);
    }
});

///
function sendRequestToMinerva(request_set){

    var logger = new bbop.logger('noctua mmcc');
    logger.DEBUG = true;
    function ll(str){ logger.kvetch(str); }

    // Events registry.
    // Add manager and default callbacks to repl.
    var engine = new jquery_engine(barista_response);
    var manager = new minerva_manager(global_barista_location,
				      global_minerva_definition_name,
				      global_barista_token, engine, 'async');

    // GOlr location and conf setup.
    var gserv = global_golr_server;
    var gconf = new golr_conf.conf(amigo.data.golr);

    ///
    /// Helpers.
    ///

    var compute_shield_modal = null;

    // Block interface from taking user input while
    // operating.
    function _shields_up(){
	if( compute_shield_modal ){
	    // Already have one.
	}else{
	    ll('shield up');
	    compute_shield_modal = widgetry.compute_shield();
	    compute_shield_modal.show();
	}
    }
    // Release interface when transaction done.
    function _shields_down(){
	if( compute_shield_modal ){
	    ll('shield down');
	    compute_shield_modal.destroy();
	    compute_shield_modal = null;
	}else{
	    // None to begin with.
	}
    }

    ///
    /// Management.
    ///

    // Internal registrations.
    manager.register('prerun', _shields_up);
    manager.register('postrun', _shields_down, 9);
    manager.register('manager_error', function(resp, man){
	alert('There was a manager error (' +
	      resp.message_type() + '): ' + resp.message());
    }, 10);

    // Likely the result of unhappiness on Minerva.
    manager.register('warning', function(resp, man){
	alert('Warning: ' + resp.message() + '; ' +
	      'your operation was likely not performed');
    }, 10);

    // Likely the result of serious unhappiness on Minerva.
    manager.register('error', function(resp, man){

	// Do something different if we think that this is a
	// permissions issue.
	var perm_flag = "InsufficientPermissionsException";
	var token_flag = "token";
	if( resp.message() && resp.message().indexOf(perm_flag) !== -1 ){
	    alert('Error: it seems like you do not have permission to ' +
		  'perform that operation. Did you remember to login?');
	}else if( resp.message() && resp.message().indexOf(token_flag) !== -1 ){
	    alert("Error: it seems like you have a bad token...");
	}else{
	    // Generic error.
	    alert('Error (' +
		  resp.message_type() + '): ' +
		  resp.message() + '; ' +
		  'your operation was likely not performed.');
	}
    }, 10);

    // ???
    manager.register('meta', function(resp, man){
	ll('a meta callback?');
    });

    // Likely result of a new model being built on Minerva.
    manager.register('rebuild', function(resp, man){
	ll('rebuild callback');

    }, 10);

    manager.request_with(request_set);
}


text:
import java.util.List;

public class SudokuChecker {

    /*
    6.16
    */

    public static boolean isValidSudoku(List<List<Integer>> partialAssignment) {

        return true;
    }
}


text:
import cronjobs
from datetime import datetime, timedelta

from rest_framework.authtoken.models import Token

from django.conf import settings

from kitsune.questions.models import Answer
from kitsune.search.models import generate_tasks
from kitsune.search.tasks import index_task
from kitsune.users.models import RegistrationProfile, UserMappingType
from kitsune.wiki.models import Revision

@cronjobs.register
def remove_expired_registration_profiles():
    """"Cleanup expired registration profiles and users that not activated."""
    RegistrationProfile.objects.delete_expired_users()
    generate_tasks()

@cronjobs.register
def reindex_users_that_contributed_yesterday():
    """Update the users (in ES) that contributed yesterday.

    The idea is to update the last_contribution_date field.
    """
    if settings.STAGE:
        return

    today = datetime.now()
    yesterday = today - timedelta(days=1)

    # Support Forum answers
    user_ids = list(Answer.objects.filter(
        created__gte=yesterday,
        created__lt=today).values_list('creator_id', flat=True))

    # KB Edits
    user_ids += list(Revision.objects.filter(
        created__gte=yesterday,
        created__lt=today).values_list('creator_id', flat=True))

    # KB Reviews
    user_ids += list(Revision.objects.filter(
        reviewed__gte=yesterday,
        reviewed__lt=today).values_list('reviewer_id', flat=True))

    # Note:
    # Army of Awesome replies are live indexed. No need to do anything here.

    index_task.delay(UserMappingType, list(set(user_ids)))

@cronjobs.register
def clear_expired_auth_tokens():
    too_old = datetime.now() - timedelta(days=30)
    Token.objects.filter(created__lt=too_old).delete()


text: What I want to acheive in 2015.


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

using Orchard.ContentManagement.Records;

namespace MTBSmallCTA.Models
{
    public class MTBSmallCTAPartRecord : ContentPartRecord
    {
        public virtual string Item1Title { get; set; }
        public virtual string Item1CSSClass { get; set; }

        public virtual string Item2Title { get; set; }
        public virtual string Item2CSSClass { get; set; }

        public virtual string Item3Title { get; set; }
        public virtual string Item3CSSClass { get; set; }
    }
}


text:
//
//  LoanModel.m
//  AWBTCChinaAPIDemo
//
//  Created by mafengwo on 15/3/18.
//  Copyright (c) 2015年 Aldaron. All rights reserved.
//

#import "LoanModel.h"

@interface LoanModel ()

/** 货币代码 **/
@property (nonatomic, strong) NSString *currency;
/** 货币符号 **/
@property (nonatomic, strong) NSString *symbol;
/** 账户冻结金额 (小数精度) **/
@property (nonatomic, strong) NSNumber *amount;
/** 账户冻结金额 (整数精度) **/
@property (nonatomic, strong) NSString *amount_integer;
/** 在使用"amount_integer"时小数点的位置 **/
@property (nonatomic, assign) NSInteger amount_decimal;

@end

@implementation LoanModel

- (void)parseJSONData:(NSDictionary *)responseObject{
    self.amount = [NSNumber numberWithDouble:[[responseObject objectForKey:@"amount"] doubleValue]];
    self.amount_decimal = [[responseObject objectForKey:@"amount_decimal"] integerValue];
    self.amount_integer = [responseObject objectForKey:@"amount_integer"];
    self.currency = [responseObject objectForKey:@"currency"];
    self.symbol = [responseObject objectForKey:@"symbol"];
}

@end


text:
/* ----------------------------------------------------------------------
 * Project:      CMSIS DSP Library
 * Title:        arm_fir_lattice_f32.c
 * Description:  Processing function for floating-point FIR Lattice filter
 *
 * $Date:        23 April 2021
 * $Revision:    V1.9.0
 *
 * Target Processor: Cortex-M and Cortex-A cores
 * -------------------------------------------------------------------- */
/*
 * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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
 *
 * 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.
 */

#include "dsp/filtering_functions.h"

/**
  @ingroup groupFilters
 */

/**
  @defgroup FIR_Lattice Finite Impulse Response (FIR) Lattice Filters

  This set of functions implements Finite Impulse Response (FIR) lattice filters
  for Q15, Q31 and floating-point data types.  Lattice filters are used in a
  variety of adaptive filter applications. The filter structure is feedforward and
  the net impulse response is finite length.
  The functions operate on blocks
  of input and output data and each call to the function processes
  blockSize samples through the filter.  pSrc and
  pDst point to input and output arrays containing blockSize values.

  @par           Algorithm
                   \image html FIRLattice.gif "Finite Impulse Response Lattice filter"
                   The following difference equation is implemented:
  @par

      f0[n] = g0[n] = x[n]
      fm[n] = fm-1[n] + km * gm-1[n-1] for m = 1, 2, ...M
      gm[n] = km * fm-1[n] + gm-1[n-1] for m = 1, 2, ...M
      y[n] = fM[n]

  @par
                   pCoeffs points to tha array of reflection coefficients of size numStages.
                   Reflection Coefficients are stored in the following order.
  @par

      {k1, k2, ..., kM}

                   where M is number of stages
  @par
                   pState points to a state array of size numStages.
                   The state variables (g values) hold previous inputs and are stored in the following order.

    {g0[n], g1[n], g2[n] ...gM-1[n]}

                   The state variables are updated after each block of data is processed; the coefficients are untouched.

  @par           Instance Structure
                   The coefficients and state variables for a filter are stored together in an instance data structure.
                   A separate instance structure must be defined for each filter.
                   Coefficient arrays may be shared among several instances while state variable arrays cannot be shared.
                   There are separate instance structure declarations for each of the 3 supported data types.

  @par           Initialization Functions
                   There is also an associated initialization function for each data type.
                   The initialization function performs the following operations:
                   - Sets the values of the internal structure fields.
                   - Zeros out the values in the state buffer.
                   To do this manually without calling the init function, assign the follow subfields of the instance structure:
                   numStages, pCoeffs, pState. Also set all of the values in pState to zero.
  @par
                   Use of the initialization function is optional.
                   However, if the initialization function is used, then the instance structure cannot be placed into a const data section.
                   To place an instance structure into a const data section, the instance structure must be manually initialized.
                   Set the values in the state buffer to zeros and then manually initialize the instance structure as follows:

      arm_fir_lattice_instance_f32 S = {numStages, pState, pCoeffs};
      arm_fir_lattice_instance_q31 S = {numStages, pState, pCoeffs};
      arm_fir_lattice_instance_q15 S = {numStages, pState, pCoeffs};

  @par
                   where numStages is the number of stages in the filter;
                   pState is the address of the state buffer;
                   pCoeffs is the address of the coefficient buffer.

  @par           Fixed-Point Behavior
                   Care must be taken when using the fixed-point versions of the FIR Lattice filter functions.
                   In particular, the overflow and saturation behavior of the accumulator used in each function must be considered.
                   Refer to the function specific documentation below for usage guidelines.
 */

/**
  @addtogroup FIR_Lattice
  @{
 */

/**
  @brief         Processing function for the floating-point FIR lattice filter.
  @param[in]     S          points to an instance of the floating-point FIR lattice structure
  @param[in]     pSrc       points to the block of input data
  @param[out]    pDst       points to the block of output data
  @param[in]     blockSize  number of samples to process
  @return        none
 */

void arm_fir_lattice_f32(
  const arm_fir_lattice_instance_f32 * S,
  const float32_t * pSrc,
        float32_t * pDst,
        uint32_t blockSize)
{
        float32_t *pState = S->pState;                 /* State pointer */
  const float32_t *pCoeffs = S->pCoeffs;               /* Coefficient pointer */
        float32_t *px;                                 /* Temporary state pointer */
  const float32_t *pk;                                 /* Temporary coefficient pointer */
        uint32_t numStages = S->numStages;             /* Number of stages in the filter */
        uint32_t blkCnt, stageCnt;                     /* Loop counters */
        float32_t fcurr0, fnext0, gnext0, gcurr0;      /* Temporary variables */

#if defined (ARM_MATH_LOOPUNROLL)
        float32_t fcurr1, fnext1, gnext1;              /* Temporary variables for second sample in loop unrolling */
        float32_t fcurr2, fnext2, gnext2;              /* Temporary variables for third sample in loop unrolling */
        float32_t fcurr3, fnext3, gnext3;              /* Temporary variables for fourth sample in loop unrolling */
#endif

  gcurr0 = 0.0f;

#if defined (ARM_MATH_LOOPUNROLL)

  /* Loop unrolling: Compute 4 outputs at a time */
  blkCnt = blockSize >> 2U;

  while (blkCnt > 0U)
  {
    /* Read two samples from input buffer */
    /* f0(n) = x(n) */
    fcurr0 = *pSrc++;
    fcurr1 = *pSrc++;

    /* Initialize state pointer */
    px = pState;

    /* Initialize coeff pointer */
    pk = pCoeffs;

    /* Read g0(n-1) from state buffer */
    gcurr0 = *px;

    /* Process first sample for first tap */
    /* f1(n) = f0(n) +  K1 * g0(n-1) */
    fnext0 = (gcurr0 * (*pk)) + fcurr0;

    /* g1(n) = f0(n) * K1  +  g0(n-1) */
    gnext0 = (fcurr0 * (*pk)) + gcurr0;

    /* Process second sample for first tap */
    fnext1 = (fcurr0 * (*pk)) + fcurr1;
    gnext1 = (fcurr1 * (*pk)) + fcurr0;

    /* Read next two samples from input buffer */
    /* f0(n+2) = x(n+2) */
    fcurr2 = *pSrc++;
    fcurr3 = *pSrc++;

    /* Process third sample for first tap */
    fnext2 = (fcurr1 * (*pk)) + fcurr2;
    gnext2 = (fcurr2 * (*pk)) + fcurr1;

    /* Process fourth sample for first tap */
    fnext3 = (fcurr2 * (*pk  )) + fcurr3;
    gnext3 = (fcurr3 * (*pk++)) + fcurr2;

    /* Copy only last input sample into the state buffer
       which will be used for next samples processing */
    *px++ = fcurr3;

    /* Update of f values for next coefficient set processing */
    fcurr0 = fnext0;
    fcurr1 = fnext1;
    fcurr2 = fnext2;
    fcurr3 = fnext3;

    /* Loop unrolling.  Process 4 taps at a time . */
    stageCnt = (numStages - 1U) >> 2U;

    /* Loop over the number of taps.  Unroll by a factor of 4.
       Repeat until we've computed numStages-3 coefficients. */

    /* Process 2nd, 3rd, 4th and 5th taps ... here */
    while (stageCnt > 0U)
    {
      /* Read g1(n-1), g3(n-1) .... from state */
      gcurr0 = *px;

      /* save g1(n) in state buffer */
      *px++ = gnext3;

      /* Process first sample for 2nd, 6th .. tap */
      /* Sample processing for K2, K6.... */
      /* f2(n) = f1(n) +  K2 * g1(n-1) */
      fnext0 = (gcurr0 * (*pk)) + fcurr0;

      /* Process second sample for 2nd, 6th .. tap */
      /* for sample 2 processing */
      fnext1 = (gnext0 * (*pk)) + fcurr1;

      /* Process third sample for 2nd, 6th .. tap */
      fnext2 = (gnext1 * (*pk)) + fcurr2;

      /* Process fourth sample for 2nd, 6th .. tap */
      fnext3 = (gnext2 * (*pk)) + fcurr3;

      /* g2(n) = f1(n) * K2  +  g1(n-1) */
      /* Calculation of state values for next stage */
      gnext3 = (fcurr3 * (*pk)) + gnext2;

      gnext2 = (fcurr2 * (*pk)) + gnext1;

      gnext1 = (fcurr1 * (*pk)) + gnext0;

      gnext0 = (fcurr0 * (*pk++)) + gcurr0;

      /* Read g2(n-1), g4(n-1) .... from state */
      gcurr0 = *px;

      /* save g2(n) in state buffer */
      *px++ = gnext3;

      /* Sample processing for K3, K7.... */
      /* Process first sample for 3rd, 7th .. tap */
      /* f3(n) = f2(n) +  K3 * g2(n-1) */
      fcurr0 = (gcurr0 * (*pk)) + fnext0;

      /* Process second sample for 3rd, 7th .. tap */
      fcurr1 = (gnext0 * (*pk)) + fnext1;

      /* Process third sample for 3rd, 7th .. tap */
      fcurr2 = (gnext1 * (*pk)) + fnext2;

      /* Process fourth sample for 3rd, 7th .. tap */
      fcurr3 = (gnext2 * (*pk)) + fnext3;

      /* Calculation of state values for next stage */
      /* g3(n) = f2(n) * K3  +  g2(n-1) */
      gnext3 = (fnext3 * (*pk)) + gnext2;

      gnext2 = (fnext2 * (*pk)) + gnext1;

      gnext1 = (fnext1 * (*pk)) + gnext0;

      gnext0 = (fnext0 * (*pk++)) + gcurr0;

      /* Read g1(n-1), g3(n-1) .... from state */
      gcurr0 = *px;

      /* save g3(n) in state buffer */
      *px++ = gnext3;

      /* Sample processing for K4, K8.... */
      /* Process first sample for 4th, 8th .. tap */
      /* f4(n) = f3(n) +  K4 * g3(n-1) */
      fnext0 = (gcurr0 * (*pk)) + fcurr0;

      /* Process second sample for 4th, 8th .. tap */
      /* for sample 2 processing */
      fnext1 = (gnext0 * (*pk)) + fcurr1;

      /* Process third sample for 4th, 8th .. tap */
      fnext2 = (gnext1 * (*pk)) + fcurr2;

      /* Process fourth sample for 4th, 8th .. tap */
      fnext3 = (gnext2 * (*pk)) + fcurr3;

      /* g4(n) = f3(n) * K4  +  g3(n-1) */
      /* Calculation of state values for next stage */
      gnext3 = (fcurr3 * (*pk)) + gnext2;

      gnext2 = (fcurr2 * (*pk)) + gnext1;

      gnext1 = (fcurr1 * (*pk)) + gnext0;

      gnext0 = (fcurr0 * (*pk++)) + gcurr0;

      /* Read g2(n-1), g4(n-1) .... from state */
      gcurr0 = *px;

      /* save g4(n) in state buffer */
      *px++ = gnext3;

      /* Sample processing for K5, K9.... */
      /* Process first sample for 5th, 9th .. tap */
      /* f5(n) = f4(n) +  K5 * g4(n-1) */
      fcurr0 = (gcurr0 * (*pk)) + fnext0;

      /* Process second sample for 5th, 9th .. tap */
      fcurr1 = (gnext0 * (*pk)) + fnext1;

      /* Process third sample for 5th, 9th .. tap */
      fcurr2 = (gnext1 * (*pk)) + fnext2;

      /* Process fourth sample for 5th, 9th .. tap */
      fcurr3 = (gnext2 * (*pk)) + fnext3;

      /* Calculation of state values for next stage */
      /* g5(n) = f4(n) * K5  +  g4(n-1) */
      gnext3 = (fnext3 * (*pk)) + gnext2;

      gnext2 = (fnext2 * (*pk)) + gnext1;

      gnext1 = (fnext1 * (*pk)) + gnext0;

      gnext0 = (fnext0 * (*pk++)) + gcurr0;

      stageCnt--;
    }

    /* If the (filter length -1) is not a multiple of 4, compute the remaining filter taps */
    stageCnt = (numStages - 1U) % 0x4U;

    while (stageCnt > 0U)
    {
      gcurr0 = *px;

      /* save g value in state buffer */
      *px++ = gnext3;

      /* Process four samples for last three taps here */
      fnext0 = (gcurr0 * (*pk)) + fcurr0;

      fnext1 = (gnext0 * (*pk)) + fcurr1;

      fnext2 = (gnext1 * (*pk)) + fcurr2;

      fnext3 = (gnext2 * (*pk)) + fcurr3;

      /* g1(n) = f0(n) * K1  +  g0(n-1) */
      gnext3 = (fcurr3 * (*pk)) + gnext2;

      gnext2 = (fcurr2 * (*pk)) + gnext1;

      gnext1 = (fcurr1 * (*pk)) + gnext0;

      gnext0 = (fcurr0 * (*pk++)) + gcurr0;

      /* Update of f values for next coefficient set processing */
      fcurr0 = fnext0;
      fcurr1 = fnext1;
      fcurr2 = fnext2;
      fcurr3 = fnext3;

      stageCnt--;
    }

    /* The results in the 4 accumulators, store in the destination buffer. */
    /* y(n) = fN(n) */
    *pDst++ = fcurr0;
    *pDst++ = fcurr1;
    *pDst++ = fcurr2;
    *pDst++ = fcurr3;

    blkCnt--;
  }

  /* Loop unrolling: Compute remaining outputs */
  blkCnt = blockSize % 0x4U;

#else

  /* Initialize blkCnt with number of samples */
  blkCnt = blockSize;

#endif /* #if defined (ARM_MATH_LOOPUNROLL) */

  while (blkCnt > 0U)
  {
    /* f0(n) = x(n) */
    fcurr0 = *pSrc++;

    /* Initialize state pointer */
    px = pState;

    /* Initialize coeff pointer */
    pk = pCoeffs;

    /* read g2(n) from state buffer */
    gcurr0 = *px;

    /* for sample 1 processing */
    /* f1(n) = f0(n) +  K1 * g0(n-1) */
    fnext0 = (gcurr0 * (*pk)) + fcurr0;

    /* g1(n) = f0(n) * K1  +  g0(n-1) */
    gnext0 = (fcurr0 * (*pk++)) + gcurr0;

    /* save g1(n) in state buffer */
    *px++ = fcurr0;

    /* f1(n) is saved in fcurr0 for next stage processing */
    fcurr0 = fnext0;

    stageCnt = (numStages - 1U);

    /* stage loop */
    while (stageCnt > 0U)
    {
      /* read g2(n) from state buffer */
      gcurr0 = *px;

      /* save g1(n) in state buffer */
      *px++ = gnext0;

      /* Sample processing for K2, K3.... */
      /* f2(n) = f1(n) +  K2 * g1(n-1) */
      fnext0 = (gcurr0 * (*pk)) + fcurr0;

      /* g2(n) = f1(n) * K2  +  g1(n-1) */
      gnext0 = (fcurr0 * (*pk++)) + gcurr0;

      /* f1(n) is saved in fcurr0 for next stage processing */
      fcurr0 = fnext0;

      stageCnt--;
    }

    /* y(n) = fN(n) */
    *pDst++ = fcurr0;

    blkCnt--;
  }

}

/**
  @} end of FIR_Lattice group
 */