text:
require "edition"
require "attachable"

class ReportEdition < Edition
  include AttachableWithMetadata

  field    :date, type: DateTime

  attaches :report

  GOVSPEAK_FIELDS = Edition::GOVSPEAK_FIELDS + [:description]

  clone_fields :date

  def rendering_app
    "www"
  end

  def whole_body
    ""
  end

  def rendering_path
    "/reports/#{slug}"
  end

end


text:
          {% if page.permalink != '/' -%}

            {%- if site.title == "blank" -%}
              {%- if site.first_name -%}
                {{- site.first_name -}}
              {%- endif -%}
              {%- if site.middle_name -%}
                {{- site.middle_name -}}
              {%- endif -%}
              {%- if site.last_name -%}
                {{- site.last_name -}}
              {%- endif -%}
            {%- else -%}
              {{- site.title -}}
            {%- endif -%}

          {%- elsif site.enable_navbar_social -%}

            {% include social.html %}

          {% endif %}

          <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            Toggle navigation

          </button>

              {%- for page in site.pages -%}
                {% if page.permalink == '/' %}
                  {% assign about_title = page.title %}
                {% endif %}
              {% endfor %}

                {{ about_title }}
                  {%- if page.permalink == '/' -%}
                  (current)
                  {%- endif -%}

              {% if site.blog_nav_title %}

                {{ site.blog_nav_title }}
                  {%- if page.url contains 'blog' -%}
                  (current)
                  {%- endif -%}

              {%- endif %}

              {%- assign sorted_pages = site.pages | sort: "nav_order" -%}
              {%- for p in sorted_pages -%}
              {%- if p.nav and p.autogen == nil -%}
              {%- if p.dropdown %}

                {{ p.title }}
                  {%- if page.title == p.title -%}
                  (current)
                  {%- endif -%}

                  {%- for child in p.children -%}
                  {%- if child.title == 'divider' %}

                  {%- else %}
                  {{ child.title }}
                  {%- endif -%}
                  {% endfor %}

              {%- else %}

                {{ p.title }}
                  {%- if page.title == p.title -%}
                  (current)
                  {%- endif -%}

              {%- endif -%}
              {%- endif -%}
              {% endfor -%}
              {%- if site.enable_darkmode %}

                <button id="light-toggle" title="Change theme">

                </button>

              {%- endif %}

redpajama_set_name: RedPajamaGithub


text:
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% if page.title == "Home" %}{{ site.title }}{% else %}{{ site.acronym }} · {{ page.title }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.subtitle }}{% endif %}">
  <link rel="stylesheet" href="{{ base }}/css/main.css">
  <link rel="canonical" href="{{ site.url }}{{ site.baseurl }}{{ page.url | replace:'index.html', '' }}">
  <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ site.url }}{{ site.baseurl }}/feed.xml">
  <link rel="icon" type="image/x-icon" href="{{ "/favicon.ico" | prepend: base }}">


text:
package com.yetu.oauth2provider.services.data

import com.yetu.oauth2provider.base.DataServiceBaseSpec
import com.yetu.oauth2provider.registry.{ TestRegistry, IntegrationTestRegistry }
import com.yetu.oauth2provider.signature.models.YetuPublicKey
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import securesocial.core.services.SaveMode

import scala.concurrent.ExecutionContext.Implicits.global

abstract class BaseKeyServiceSpec extends DataServiceBaseSpec with ScalaFutures {

  s"The [$databaseImplementationName] Public Key Service" must {

    val testKey = YetuPublicKey("rsa-ssh ASDFDGHEGWEAFSASDFDGHEGWEAFSASDFDGHEGWEAFSASDFDGHEGWEAFS...")

    "store and retrieve a key" in {

      val result = for {
        delete <- personService.deleteUser(testUser.userId)
        user <- personService.save(testUser, SaveMode.SignUp)
        store <- publicKeyService.storeKeyF(testUser.userId, testKey)
        retrieve <- publicKeyService.getKeyF(testUser.userId)
      } yield retrieve

      whenReady(result, timeout(Span(5, Seconds))) {
        response =>
          response mustEqual Some(testKey)
          personService.deleteUser(testUser.userId)
      }
    }

  }
}

class APIKeyServiceITSpec extends BaseKeyServiceSpec with IntegrationTestRegistry

class MemoryKeyServiceSpec extends BaseKeyServiceSpec with TestRegistry


text:
<?php
use F3\Commuter\Application;
use Pimple\Container;

return function (Container $container, array $config) {
    $container['pdo'] = function () use ($config) {
        return new PDO($config['storage']['dsn'], null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    };
    $container['application'] = function ($app) {
        return new Application($app['pdo'], new DateTimeImmutable());
    };
};


text:
package org.reasm.m68k.messages;

import org.reasm.AssemblyErrorMessage;

/**
 * An error message that is generated during an assembly when a MOVEM instruction is encountered in which either no
 * operand can be parsed as a register list or both operands can be parsed as a register list.
 *
 * @author Francis Gagné
 */
public class MovemRequiresARegisterListInExactlyOneOperandErrorMessage extends AssemblyErrorMessage {

    /**
     * Initializes a new MovemRequiresARegisterListInExactlyOneOperandErrorMessage.
     */
    public MovemRequiresARegisterListInExactlyOneOperandErrorMessage() {
        super("MOVEM requires a register list in exactly one operand");
    }

}


text:
@echo off
echo Linking Utils...

mklink /J "H:\GitHub\SAssemblies\SPackages\STimers\Utils\" "H:\Visual Studio 2012\Projects\SAwareness\SAwareness\Utils\"

echo Creating Resource folder...

mkdir "H:\GitHub\SAssemblies\SPackages\STimers\Resources"

echo Linking Dll's...

mklink /J "H:\GitHub\SAssemblies\SPackages\STimers\Resources\DLL\" "H:\Visual Studio 2012\Projects\SAwareness\SAwareness\Resources\DLL\"

echo Linking Translations...

mklink /J "H:\GitHub\SAssemblies\SPackages\STimers\Resources\TRANSLATIONS\" "H:\Visual Studio 2012\Projects\SAwareness\SAwareness\Resources\TRANSLATIONS\"

echo Linking Miscs...

mklink /J "H:\GitHub\SAssemblies\SPackages\STimers\Timers\" "H:\Visual Studio 2012\Projects\SAwareness\SAwareness\Timers\"

echo Finished
Pause


text:
package org.instantlogic.fabric.deduction;

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

import org.instantlogic.fabric.util.DeductionContext;
import org.instantlogic.fabric.util.ValueAndLevel;

public class SumDeduction<V extends Number> extends Deduction<V> {

	private List<Deduction<? extends Number>> operands = new ArrayList<Deduction<? extends Number>>();

	public void addToOperands(Deduction<? extends Number> operand) {
		operands.add(operand);
	}

	@SuppressWarnings("unchecked")
	@Override
	public ValueAndLevel<V> execute(DeductionContext context) {
		Number result = Integer.valueOf(0);
		for(Deduction<? extends Number> input: operands) {
			Number term = input.deduce(context).getValue();
			if (term==null) return ValueAndLevel.inconclusive();
			if (term instanceof Double || result instanceof Double) {
				result = result.doubleValue()+term.doubleValue();
			} else if (term instanceof Long || result instanceof Long) {
				result = result.longValue()+term.longValue();
			} else {
				result = result.intValue()+term.intValue();
			}
		}
		return ValueAndLevel.rule((V)result);
	}
}


text:
//
//  UIFont+DTCoreText.h
//  DTCoreText
//
//  Created by Oliver Drobnik on 11.12.12.
//  Copyright (c) 2012 Drobnik.com. All rights reserved.
//

@interface UIFont (DTCoreText)

/**
 Creates a UIFont that matches the provided CTFont.
 @param ctFont a `CTFontRef`
 @returns The matching UIFont
 */
+ (UIFont *)fontWithCTFont:(CTFontRef)ctFont;

@end


text:
#pragma once

#include <react/renderer/core/EventQueue.h>

namespace facebook {
namespace react {

/*
 * Event Queue that dispatches event in batches synchronizing them with
 * an Event Beat.
 */
class BatchedEventQueue final : public EventQueue {
 public:
  BatchedEventQueue(
      EventPipe eventPipe,
      StatePipe statePipe,
      std::unique_ptr<EventBeat> eventBeat);

  void onEnqueue() const override;

  /*
   * Enqueues and (probably later) dispatches a given event.
   * Deletes last RawEvent from the queue if it has the same type and target.
   * Can be called on any thread.
   */
  void enqueueUniqueEvent(const RawEvent &rawEvent) const;
};

} // namespace react
} // namespace facebook


text:
import ModalService from "./services/modal-service";
import { RPGPlayerSession } from "./services/rpg-player-session"

export class MainController{

    static $inject = ["modalService",  "rpgPlayerSession"];
    constructor(private modalService:ModalService, private rpgPlayerSession:RPGPlayerSession){
    }

    forceSidebar = false;
    toggleSidebar():void{
        this.forceSidebar = !this.forceSidebar;
    }

    shouldRemoveScrollFromBody():boolean {
        if(!this.modalService){
            return false;
        }
        return this.modalService.modalActive;
    }

    get usernameText():string {
        if(!this.rpgPlayerSession.isAuthenticated) {
            return "Sign In";
        }
        return this.rpgPlayerSession.playerName;
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="ah">
        <note>
            Frames file for 'ah' based on sentences in ectb 2.  No Verbnet entry.
        </note>

        <roleset id="ah.01" name="express admiration or pleasure" vncls="-">
            <roles>
                <role descr="ah-er" n="0"/>
                <role descr="cause of awe (ah?)" n="1"/>
            </roles>

            <example name="transitive">
                <text>
                    Caucasians like * to ooh and ah over a product 's finer points, while
                    the Chinese do nothing but comment on flaws.
                </text>
                <arg n="0">*-9</arg>
                <rel>ooh</rel>
                <arg n="1">over a product 's finer points</arg>
            </example>

            <note>
                Frame created by Arrick
            </note>

        </roleset>
    </predicate>
</frameset>


text:
pub mod karma;
mod karma_def;
mod karma_token;
mod tokenizer;

#[cfg(feature = "arbitrary")]
pub mod test_all_token {
    use nom::IResult;
    pub use crate::bot::parser::karma_token::KarmaToken;

    pub fn all_token(input: &str) -> IResult<&str, Vec<KarmaToken>> {
        crate::bot::parser::karma_token::all_token(input)
    }
}

pub fn reacji_to_karma(input: &str) -> Option<karma::Karma> {
    karma_def::reacji_to_karma(input)
}


text:
package postprocessing;

import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import fluentSolver.Fluent;
import fluentSolver.FluentNetworkSolver;
import htn.HTNMetaConstraint;
import htn.HTNOperator;
import htn.HTNPlanner;
import htn.PlanReportroryItem;
import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.Variable;
import org.metacsp.multi.allenInterval.AllenIntervalNetworkSolver;
import org.metacsp.time.APSPSolver;
import org.metacsp.time.SimpleDistanceConstraint;
import org.metacsp.time.TimePoint;
import planner.CHIMP;
import postprocessing.estereltypes.*;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.Writer;
import java.util.*;

public class EsterelGenerator {

    public static void generateEsterelGraph(CHIMP chimp, Writer writer) {

        FluentNetworkSolver fluentSolver = chimp.getFluentSolver();
        List<SimpleDistanceConstraint> additionalConsList = calcAdditionalConstraints(fluentSolver);

        // Add new constraints to apspSolver
        APSPSolver apspSolver = getApspSolver(fluentSolver);
        boolean success = apspSolver.addConstraints(
                additionalConsList.toArray(new SimpleDistanceConstraint[additionalConsList.size()]));

        // Create Esterel Graph:

        Map<TimePoint, Fluent> timePointActivityMap = getTimePointActivityMap(fluentSolver);

        // create ActionDispatch messages
        Map<Fluent, ActionDispatch> fluentActionDispatchMap = getFluentActionDispatchMap(timePointActivityMap, chimp);

        // Create and sort array of timepoints
        TimePoint[] tps = createSortedActivityTimepoints(apspSolver, timePointActivityMap);

        EsterelPlan esterelPlan = new EsterelPlan();
        // add nodes to esterel plan
        for (int i = 0; i < tps.length - 1; i++) {
            TimePoint tp = tps[i];
            if (tp.getID() == 0) {
                EsterelPlanNode node = new EsterelPlanNode();
                node.name = "plan_start";
                node.node_id = 0;
                node.node_type = 2;
                node.action = new ActionDispatch(0, "");
                esterelPlan.nodes.add(node);
            } else {
                Fluent fl = timePointActivityMap.get(tp);
                EsterelPlanNode node = new EsterelPlanNode();
                node.name = fl.getCompoundSymbolicVariable().getPredicateName();
                if (isEndpoint(tp)) {
                    node.name += "_end";
                } else {
                    node.name += "_start";
                }
                node.node_type = isEndpoint(tp) ? 1 : 0;
                node.node_id = i;
                node.action = fluentActionDispatchMap.get(fl);
                esterelPlan.nodes.add(node);
            }
        }
        // the index of nodes in the esterel plan is the same as that of the corresponding timepoint in tps

        // Add edges: for two nodes check if an edge exist and add it to the plan
        int edgeIdCnt = 0;
        for (int i = 0; i < tps.length - 1; i++) {
            for (int j = 0; j < tps.length - 1; j++) {  // horizon tp is last in tps and can be ignored
                SimpleDistanceConstraint sdc = apspSolver.getConstraint(tps[i], tps[j]);
                if (sdc != null) {
                    // create edge
                    int edgeId = edgeIdCnt++;
                    EsterelPlanEdge edge = new EsterelPlanEdge(edgeId, "edge" + edgeId, i, j,
                            sdc.getMinimum() / 1000, sdc.getMaximum() / 1000);
                    esterelPlan.addEdge(edge);
                }
            }
        }

        // export esterel
        ObjectMapper objectMapper = new ObjectMapper(
                new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));
        try {
            objectMapper.writeValue(writer, esterelPlan);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static TimePoint[] createSortedActivityTimepoints(APSPSolver apspSolver, Map<TimePoint, Fluent> timePointActivityMap) {
        TimePoint[] tps = new TimePoint[timePointActivityMap.keySet().size() + 2];
        tps[0] = apspSolver.getSource();
        tps[tps.length-1] = apspSolver.getSink();
        int pos = 1;
        for (TimePoint tp : timePointActivityMap.keySet()) {
            tps[pos++] = tp;
        }
        Arrays.sort(tps, new Comparator<TimePoint>() {
            @Override
            public int compare(TimePoint t0, TimePoint t1) {
                return Long.compare(t0.getLowerBound(), t1.getLowerBound());
            }
        });
        return tps;
    }

    public static Map<Fluent, ActionDispatch> getFluentActionDispatchMap(Map<TimePoint, Fluent> timePointActivityMap,
                                                                         CHIMP chimp) {
        // we need the operators to get the names of the actions' arguments
        List<PlanReportroryItem> operators = chimp.getPlanner().getHTNMetaConstraint().getOperators();
        Map<String, PlanReportroryItem> nameOperatorMap = new HashMap<>();
        for (PlanReportroryItem op : operators) {
            nameOperatorMap.put(op.getName(), op);
        }

        Map<Fluent, ActionDispatch> fluentActionDispatchMap = new HashMap<>();
        for (Fluent fl : timePointActivityMap.values()) {
            String actionName= fl.getCompoundSymbolicVariable().getPredicateName();
            ActionDispatch actionDispatch = new ActionDispatch(fl.getID(), actionName);
            actionDispatch.duration = (fl.getAllenInterval().getEET() - fl.getAllenInterval().getEST()) / 1000;
            String[] opArgNames = nameOperatorMap.get(actionName).getStringArgumentNames();
            String[] flArgs = fl.getCompoundSymbolicVariable().getArgs();
            for (int i = 0; i < flArgs.length; i++) {
                String key = opArgNames[i];
                // remove leading '?'
                if (key.length() > 0 && key.charAt(0) == '?') {
                    key = key.substring(1);
                }
                actionDispatch.parameters.add(new KeyValue(key, flArgs[i]));
            }
            actionDispatch.dispatch_time = fl.getAllenInterval().getEST() / 1000;
            fluentActionDispatchMap.put(fl, actionDispatch);
        }
        return fluentActionDispatchMap;
    }

    public static Map<TimePoint, Fluent> getTimePointActivityMap(FluentNetworkSolver fluentSolver) {
        Map<TimePoint, Fluent> timePointActivityMap = new HashMap<>();
        for (Variable activityVar : fluentSolver.getVariables(Fluent.ACTIVITY_TYPE_STR))  {
            Fluent activity = (Fluent) activityVar;
            timePointActivityMap.put(activity.getAllenInterval().getStart(), activity);
            timePointActivityMap.put(activity.getAllenInterval().getEnd(), activity);
        }
        return timePointActivityMap;
    }

    public static APSPSolver getApspSolver(FluentNetworkSolver fluentSolver) {
        AllenIntervalNetworkSolver aiSolver =
                (AllenIntervalNetworkSolver) fluentSolver.getConstraintSolvers()[1];
        APSPSolver apspSolver = (APSPSolver) aiSolver.getConstraintSolvers()[0];
        return apspSolver;
    }

    /**
     * Compute implicit constraints in between activities for between which a path exists.
     * @param fluentSolver
     * @return List of implicit constraints between activities.
     */
    public static List<SimpleDistanceConstraint> calcAdditionalConstraints(FluentNetworkSolver fluentSolver) {
        APSPSolver apspSolver = getApspSolver(fluentSolver);
        // Copy temporal constraint network to dummy cn
        ConstraintNetwork cn = (ConstraintNetwork) apspSolver.getConstraintNetwork().clone();

        List<SimpleDistanceConstraint> additionalConsList = new ArrayList<>();
        // [0,0]-constraints are relevant in both directions, therefore we also need edges in both directions
        // Add reverse constraints for constraints [0,0]-constraints from end-timepoint to end-timepoint
        for (Constraint con : cn.getConstraints()) {
            SimpleDistanceConstraint dst = (SimpleDistanceConstraint) con;
            if (isEndpoint(dst.getFrom()) && isEndpoint(dst.getTo()) &&
                    dst.getMinimum() == 0 && dst.getMaximum() == 0) {
                additionalConsList.add(createReverseConstraint(dst));
            }
        }
        cn.addConstraints(additionalConsList.toArray(new SimpleDistanceConstraint[additionalConsList.size()]));

        // Replace fluents that are not activities
        for (Variable v : fluentSolver.getVariables()) {
            Fluent fl = (Fluent) v;
            if (!fl.isActivity()) {
                TimePoint start = fl.getAllenInterval().getStart();
                additionalConsList.addAll(replaceNode(cn, start));
                TimePoint end = fl.getAllenInterval().getEnd();
                additionalConsList.addAll(replaceNode(cn, end));
            }
        }
        return additionalConsList;
    }

    //

    /**
     * Check if the temporal variable represents a start or end point.
     *
     * Assumes that ids of endpoints are odd.
     * @return true if the temporal variable is a endpoint, false if it as startpoint
     */
    private static boolean isEndpoint(Variable var) {
        return (var.getID() % 2) == 1;
    }

    private static SimpleDistanceConstraint createReverseConstraint(SimpleDistanceConstraint con) {
        SimpleDistanceConstraint reverseCon = new SimpleDistanceConstraint();
        reverseCon.setMinimum(con.getMinimum());
        reverseCon.setMaximum(con.getMaximum());
        reverseCon.setFrom(con.getTo());
        reverseCon.setTo(con.getFrom());
        return reverseCon;
    }

    public static List<SimpleDistanceConstraint> replaceNode(ConstraintNetwork cn, TimePoint tp) {
        List<SimpleDistanceConstraint> newConstraints = new ArrayList<>();
        for (Constraint inConstraint : cn.getIngoingEdges(tp)) {
            SimpleDistanceConstraint inDistCon = (SimpleDistanceConstraint) inConstraint;
            if (inDistCon.getFrom().getID() < tp.getID())
                continue; // skip node that has already been processed
            for (Constraint outConstraint : cn.getOutgoingEdges(tp)) {
                SimpleDistanceConstraint outDistCon = (SimpleDistanceConstraint) outConstraint;
                if (outDistCon.getTo().getID() < tp.getID())
                    continue; // skip node that has already been processed
                SimpleDistanceConstraint sumDistCon = new SimpleDistanceConstraint();
                if (inDistCon.getMinimum() == APSPSolver.INF || outDistCon.getMinimum() == APSPSolver.INF) {
                    sumDistCon.setMinimum(APSPSolver.INF);
                } else {
                    sumDistCon.setMinimum(inDistCon.getMinimum() + outDistCon.getMinimum());
                }
                if (inDistCon.getMaximum() == APSPSolver.INF || outDistCon.getMaximum() == APSPSolver.INF) {
                    sumDistCon.setMaximum(APSPSolver.INF);
                } else {
                    sumDistCon.setMaximum(inDistCon.getMaximum() + outDistCon.getMaximum());
                }
                sumDistCon.setFrom(inDistCon.getFrom());
                sumDistCon.setTo(outDistCon.getTo());
                if(sumDistCon.getFrom().getID() == sumDistCon.getTo().getID()) {
//                    System.out.println("Found self-constraint: " + sumDistCon.toString());
                } else {
                    newConstraints.add(sumDistCon);
                    cn.addConstraint(sumDistCon);
                }

//                System.out.println("Replacement for " + inDistCon.toString() + " and " + outDistCon.toString() + ":");
//                System.out.println("   -> " + sumDistCon.toString());
            }
        }
        return newConstraints;
    }
}


text:
from datetime import datetime
from corehq.apps.products.models import SQLProduct
from dimagi.utils.dates import force_to_date
import fluff
import re
import logging
from custom.intrahealth import get_location_by_type, PRODUCT_MAPPING, get_domain, PRODUCT_NAMES, get_loc_from_case

def form_date(form):
    return form.received_on

def real_date(form):
    return form.form['real_date']

def numeric_value(val):
    number = 0
    try:
        number = int(val)
    except ValueError:
        logging.info('Bad value type: %s' % val)
    return number

def get_product_code(product_name, domain):
    try:
        return SQLProduct.objects.get(name=product_name, domain=domain).code
    except SQLProduct.DoesNotExist:
        for k, v in PRODUCT_NAMES.iteritems():
            if product_name.lower() in v:
                return SQLProduct.objects.get(name__iexact=k,
                                              domain=domain).code

def _locations_per_type(domain, loc_type, location):
    return (location.sql_location.get_descendants(include_self=True)
            .filter(domain=domain, location_type__name=loc_type, is_archived=False).count())

class PPSRegistered(fluff.Calculator):
    @fluff.date_emitter
    def total_for_region(self, form):
        loc = get_location_by_type(form=form, type=u'r\xe9gion')
        count = _locations_per_type(form.domain, 'PPS', loc)
        yield {
            'date': form_date(form),
            'value': count
        }

    @fluff.date_emitter
    def total_for_district(self, form):
        loc = get_location_by_type(form=form, type=u'district')
        count = _locations_per_type(form.domain, 'PPS', loc)
        yield {
            'date': form_date(form),
            'value': count
        }

class PPSPlaned(fluff.Calculator):
    @fluff.date_emitter
    def total(self, form):
        yield {
            'date': form_date(form),
            'value': 0
        }

class Commandes(fluff.Calculator):
    @fluff.date_emitter
    def total(self, form):
        if 'num_products' in form.form and form.form['num_products'] > 1:
            products = form.form['products']
            for product in products:
                if 'productName' in product and 'receivedMonthInner' in product and product['receivedMonthInner']:
                    yield {
                        'date': product['receivedMonthInner'],
                        'value': product['amountOrdered'],
                        'group_by': [product['productName'],
                                     get_product_code(product['productName'], get_domain(form))]
                    }
        elif 'productName' in form.form['products'] and 'receivedMonthInner' in form.form['products']\
             and form.form['products']['receivedMonthInner']:
            yield {
                'date': form.form['products']['receivedMonthInner'],
                'value': form.form['products']['amountOrdered'],
                'group_by': [form.form['products']['productName'],
                             get_product_code(form.form['products']['productName'], get_domain(form))]
            }

class Recus(fluff.Calculator):
    @fluff.date_emitter
    def total(self, form):
        if 'num_products' in form.form and form.form['num_products'] > 1:
            products = form.form['products']
            for product in products:
                if 'productName' in product and 'receivedMonthInner' in product and product['receivedMonthInner']:
                    yield {
                        'date': product['receivedMonthInner'],
                        'value': product['amountReceived'],
                        'group_by': [product['productName'],
                                     get_product_code(product['productName'], get_domain(form))]
                    }
        elif 'productName' in form.form['products'] and \
             'receivedMonthInner' in form.form['products'] and \
             form.form['products']['receivedMonthInner']:
            yield {
                'date': form.form['products']['receivedMonthInner'],
                'value': form.form['products']['amountOrdered'],
                'group_by': [form.form['products']['productName'],
                             get_product_code(form.form['products']['productName'], get_domain(form))]
            }

class PPSConsumption(fluff.Calculator):

    def __init__(self, field='actual_consumption'):
        super(PPSConsumption, self).__init__()
        self.field = field

    @fluff.date_emitter
    def total(self, form):
        if 'num_products' in form.form and form.form['num_products'] > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    yield {
                        'date': real_date(form),
                        'value': product[self.field],
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products'][self.field],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

class RupturesDeStocks(fluff.Calculator):

    def __init__(self, field='pps_stocked_out'):
        super(RupturesDeStocks, self).__init__()
        self.field = field

    @fluff.date_emitter
    def total(self, form):
        for k, v in form.form.iteritems():
            if re.match("^rupture.*hv$", k):
                if 'date_rapportage' in form.form and form.form['date_rapportage']:
                    product_name = PRODUCT_NAMES.get(PRODUCT_MAPPING[k[8:-3]].lower())
                    if product_name is not None:
                        try:
                            prd = SQLProduct.objects.get(name__iexact=product_name,
                                                         domain=get_domain(form))
                            yield {
                                'date': form.form['date_rapportage'],
                                'value': v,
                                'group_by': [PRODUCT_MAPPING[k[8:-3]], prd.code]
                            }
                        except SQLProduct.DoesNotExist:
                            pass

class RecapPassage(fluff.Calculator):

    @fluff.date_emitter
    def old_stock_total(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['old_stock_total'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        "group_by": [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['old_stock_total'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def total_stock(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['total_stock'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['total_stock'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def livraison(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['top_up']['transfer']['entry']['value']['@quantity'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            val = numeric_value(form.form['products']['top_up']['transfer']['entry']['value']['@quantity'])
            yield {
                'date': real_date(form),
                'value': val,
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def display_total_stock(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['display_total_stock'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['display_total_stock'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def old_stock_pps(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['old_stock_pps'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['old_stock_pps'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def outside_receipts_amount(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['outside_receipts_amt'])
                    yield {
                        "date": real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['outside_receipts_amt'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def actual_consumption(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['actual_consumption'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['actual_consumption'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def billed_consumption(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['billed_consumption'])
                    yield {
                        'date': real_date(form),
                        "value": val,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['billed_consumption'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def pps_restant(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product:
                    val = numeric_value(product['pps_stock'])
                    yield {
                        'date': real_date(form),
                        "value": val if val >= 0 else 0,
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['pps_stock'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

    @fluff.date_emitter
    def loss_amt(self, form):
        if 'num_products' in form.form and int(form.form['num_products']) > 1:
            for product in form.form['products']:
                if 'real_date' in form.form and form.form['real_date'] and 'product_name' in product\
                        and product['loss_amt']:
                    yield {
                        'date': real_date(form),
                        "value": int(product['loss_amt']),
                        'group_by': [product['product_name'],
                                     get_product_code(product['product_name'], get_domain(form))]
                    }
        elif 'real_date' in form.form and form.form['real_date'] and 'product_name' in form.form['products']:
            yield {
                'date': real_date(form),
                'value': form.form['products']['loss_amt'],
                'group_by': [form.form['products']['product_name'],
                             get_product_code(form.form['products']['product_name'], get_domain(form))]
            }

class DureeMoyenneLivraison(fluff.Calculator):

    @fluff.date_emitter
    def total(self, form):
        value = form.form['duree_moyenne_livraison'] if form.form['duree_moyenne_livraison'] else 0
        yield {
            'date': form.form['mois_visite'],
            'value': value
        }

def check_prop(prop, case):
    return case.get_case_property(prop) and case.get_case_property('date_du')

def get_district_name(case):
    return get_loc_from_case(case).name

def get_date_du(case):
    date = case.get_case_property('date_du')
    if type(date) is not datetime:
        return force_to_date(date)
    return date

class Recouvrement(fluff.Calculator):

    @fluff.date_emitter
    def amount_to_pay(self, case):
        if check_prop('quantite_reale_a_payer', case):
            value = case.get_case_property('quantite_reale_a_payer')

            yield {
                'date': get_date_du(case),
                'value': int(value),
                'group_by': [get_district_name(case),
                             case.get_case_property('domain')]
            }

    @fluff.date_emitter
    def amount_paid(self, case):
        if check_prop('montant_paye', case):
            value = case.get_case_property('montant_paye')

            yield {
                'date': get_date_du(case),
                'value': int(value),
                'group_by': [get_district_name(case),
                             case.get_case_property('domain')]
            }

    @fluff.date_emitter
    def in_30_days(self, case):
        if check_prop('payee_trent_jour', case):
            value = case.get_case_property('payee_trent_jour')

            yield {
                'date': get_date_du(case),
                'value': int(value),
                'group_by': [get_district_name(case),
                             case.get_case_property('domain')]
            }

    @fluff.date_emitter
    def in_3_months(self, case):
        if check_prop('payee_trois_mois', case):
            value = case.get_case_property('payee_trois_mois')

            yield {
                'date': get_date_du(case),
                'value': int(value),
                'group_by': [get_district_name(case),
                             case.get_case_property('domain')]
            }

    @fluff.date_emitter
    def in_year(self, case):
        if check_prop('payee_un_an', case):
            value = case.get_case_property('payee_un_an')

            yield {
                'date': get_date_du(case),
                'value': int(value),
                'group_by': [get_district_name(case),
                             case.get_case_property('domain')]
            }


text:
<?php

namespace Surfnet\StepupMiddleware\ManagementBundle\Tests\Validator;

use Mockery as m;
use PHPUnit\Framework\TestCase as TestCase;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\ConfigurationStructureValidator;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Constraints\HasValidConfigurationStructure;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\EmailTemplatesConfigurationValidator;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\GatewayConfigurationValidator;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\IdentityProviderConfigurationValidator;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\ServiceProviderConfigurationValidator;

final class ConfigurationValidationTest extends TestCase
{
    public function invalidConfigurations()
    {
        $dataSet = [];

        foreach (glob(__DIR__ . '/Fixtures/invalid_configuration/*.php') as $invalidConfiguration) {
            $fixture = include $invalidConfiguration;
            $dataSet[basename($invalidConfiguration)] = [
                $fixture['configuration'],
                $fixture['expectedPropertyPath']
            ];
        };

        return $dataSet;
    }

    /**
     * @test
     * @group command-handler
     * @dataProvider invalidConfigurations
     * @param array $configuration
     * @param string $expectedPropertyPath
     */
    public function it_rejects_invalid_configuration($configuration, $expectedPropertyPath)
    {
        $builder = m::mock('Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface');
        $builder->shouldReceive('addViolation')->with()->once();
        $builder->shouldReceive('atPath')->with(self::spy($actualPropertyPath))->once();

        $context = m::mock('Symfony\Component\Validator\Context\ExecutionContextInterface');
        $context->shouldReceive('buildViolation')->with(self::spy($errorMessage))->once()->andReturn($builder);

        $validator = new ConfigurationStructureValidator(
            new GatewayConfigurationValidator(
                new IdentityProviderConfigurationValidator(),
                new ServiceProviderConfigurationValidator()
            ),
            new EmailTemplatesConfigurationValidator('en_GB')
        );
        $validator->initialize($context);
        $validator->validate(json_encode($configuration), new HasValidConfigurationStructure());

        // PHPUnit assertions are more informative than Mockery's method-should-be-called-1-times-but-called-0-times.
        $this->assertEquals(
            $expectedPropertyPath,
            $actualPropertyPath,
            sprintf("Actual path to erroneous property doesn't match expected path (%s)", $errorMessage)
        );
    }

    /**
     * @param mixed &$spy
     * @return \Mockery\Matcher\MatcherAbstract
     */
    private static function spy(&$spy)
    {
        return m::on(
            function ($value) use (&$spy) {
                $spy = $value;

                return true;
            }
        );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/Toolbar"
        app:navigationIcon="@drawable/ic_arrow_back_white_24dp"
        app:title="关于"
        app:titleTextColor="@android:color/white"></android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="40dp">

        <ImageView
            android:id="@+id/iv_logo"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="16dp"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/iv_logo"
            android:layout_centerHorizontal="true"
            android:padding="8dp"
            android:text="单纯的只是个日历 orz" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tv_cp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="16dp"
            android:text="Copyright© 2017 米小饭" />

        <Button
            android:id="@+id/btn_os"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@id/tv_cp"
            android:layout_centerHorizontal="true"
            android:autoLink="all"
            android:background="?selectableItemBackgroundBorderless"
            android:text="开源相关" />

        <Button
            android:id="@+id/btn_donate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@id/btn_os"
            android:layout_centerHorizontal="true"
            android:background="?selectableItemBackgroundBorderless"
            android:drawableLeft="@drawable/ic_favorite_border"
            android:drawablePadding="8dp"
            android:gravity="left|center_vertical"
            android:minWidth="0dp"
            android:text="@string/donate" />
    </RelativeLayout>
</LinearLayout>


text:
<?php
require_once('modules/interface/interfaceobjects/base/BaseBlockHtmlInterfaceObject.class.php');

function moduleTechnicalManual() {
    $objResponse = new xajaxResponse();
    if (PamApplication::hasValidSession($objResponse)) {
        ApplicationNavigationService::setCurrentApplicationModule(MODULE_TECH_MANUAL);

        $technicalManualTitle       =  TXT_UCF('TECHNICAL_MANUAL') ;
        $technicalManualContentHtml = '

                        ' . TXT_UCF("APPLICATION_REQUIREMENTS") . ':

' . TXT_UCF("BEST_VIEWED_IN_IE")    . '

' . TXT_UCF("BEST_VIEWED_IN_OTHER") . '

';

        $technicalManualBlock = BaseBlockHtmlInterfaceObject::create($technicalManualTitle, 700);
        $technicalManualBlock->setContentHtml($technicalManualContentHtml);

        $getgt_data = '

                                ' . $technicalManualBlock->fetchHtml() . '

';

        $objResponse->assign('module_main_panel', 'innerHTML', $getgt_data);
        $objResponse->assign('modules_menu_panel', 'innerHTML', ApplicationNavigationInterfaceBuilder::buildMenuForModule(MODULE_TECH_MANUAL));
    }

    return $objResponse;
}

?>


text:
<head>
  <title>
    Webshop
  </title>
</head>

<body>
  <link rel="stylesheet" href="stylesheet.css">
  <script src="webshop.js"></script>
</body>


text:
tests=[
  ("python","test_list.py",{'dir':'RDGeneral'}),
  ("python","test_list.py",{'dir':'Geometry'}),
  ("python","test_list.py",{'dir':'Geometry/Wrap'}),
  ("python","test_list.py",{'dir':'DataStructs'}),
  ("python","test_list.py",{'dir':'DataStructs/Wrap'}),
  ("python","test_list.py",{'dir':'Query'}),
  ("python","test_list.py",{'dir':'DataManip/MetricMatrixCalc'}),
  ("python","test_list.py",{'dir':'DataManip/MetricMatrixCalc/Wrap'}),
  ("python","test_list.py",{'dir':'ML/InfoTheory/Wrap'}),
  ("python","test_list.py",{'dir':'Numerics'}),
  ("python","test_list.py",{'dir':'ForceField'}),
  ("python","test_list.py",{'dir':'DistGeom'}),
  ("python","test_list.py",{'dir':'ChemicalFeatures'}),
  ("python","test_list.py",{'dir':'ChemicalFeatures/Wrap'}),
  #("python","test_list.py",{'dir':'PgSQL/RDLib'}),
  ("python","test_list.py",{'dir':'SimDivPickers/Wrap'}),
  ("python","test_list.py",{'dir':'ML'}),
  ("python","test_list.py",{'dir':'GraphMol'}),
  ]

longTests = [
  ]

if __name__=='__main__':
  import sys
  from rdkit import TestRunner
  failed,tests = TestRunner.RunScript('test_list.py',0,1)
  sys.exit(len(failed))


text:
package com.jeanchampemont.wtfdyum.utils;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

public class EnumRedisSerializer<T extends Enum<T>> implements RedisSerializer<T> {

    public EnumRedisSerializer(final Class<T> enumType) {
        charset = Charset.forName("UTF8");
        this.enumType = enumType;
    }

    private final Charset charset;

    private final Class<T> enumType;

    @Override
    public T deserialize(final byte[] bytes) throws SerializationException {
        return (bytes == null ? null : Enum.valueOf(enumType, new String(bytes, charset)));
    }

    @Override
    public byte[] serialize(final T val) throws SerializationException {
        return (val == null ? null : val.name().getBytes(charset));
    }
}


text:
<!DOCTYPE html>

	<link href="http://gmpg.org/xfn/11" rel="profile">
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<title>404 · Ankit</title>
	<meta name="mobile-web-app-capable" content="yes">
	<meta name="HandheldFriendly" content="True" />
	<meta name="MobileOptimized" content="320" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<link rel="stylesheet" type="text/css" media="only screen and (min-width: 1001px)" href="/assets/css/desktop.css" />
	<link rel="stylesheet" type="text/css" media="only screen and (max-width: 1000px)" href="/assets/css/mobile.css" />
	<link href="/assets/css/genericons.css" type="text/css" rel="stylesheet" />
	<link href="/assets/css/syntax.css" type="text/css" rel="stylesheet" />
	<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700|PT+Sans:400">
	<link rel="apple-touch-icon" href="http://codeankit.me/assets/images/icon.png">
	<link rel="shortcut icon" href="http://codeankit.me/assets/images/favicon.ico">
	<link rel="alternate" type="application/rss+xml" title="RSS" href="http://codeankit.me/atom.xml">

<input id="_1" type="checkbox">

	Home

	About

404

This page has just discovered that Darth Vader is his father and ran away to not be found. Go back to the homepage.

©2015, Ankit. .


text:
//
//  AppReloader.m
//  RNPlayNative
//
//  Created by Dave Sibiski on 6/2/15.
//  Copyright (c) 2015 Facebook. All rights reserved.
//

#import "AppReloader.h"
#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppReloader

RCT_EXPORT_MODULE()

-(dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

/**
 *  var AppReloader = require('NativeModules').AppReloader;
 *  AppReloader.reloadAppWithURLString('https://example.com/index.ios.bundle', 'App')
 */
RCT_EXPORT_METHOD(reloadAppWithURLString:(NSString *)URLString moduleNamed:(NSString *)moduleName)
{
  AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSURL *JSBundleURL = [NSURL URLWithString:URLString];

  @try {
    ViewController *appViewController = [[ViewController alloc] init];
    [appViewController reloadWithJSBundleURL:JSBundleURL moduleNamed:moduleName];

    delegate.appViewController = appViewController;
    delegate.shouldRotate = YES;

    [UIView transitionWithView:delegate.window
                      duration:kFlipTransitionDuration
                       options:kFlipTransitionType
                    animations:^{
                      delegate.window.rootViewController = appViewController;
                    }
                    completion:NULL];
  }
  @catch (NSException *exception) {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                    message:@"Sorry, this app doesn't work! Looks like someone needs to brush up on their JavaScript! :p"
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"OK", nil];

    [alert show];
  }
}

@end


text:
local Optim = torch.class('Optim')

local options = {
  {
    '-max_batch_size', 160,
    [[Maximum batch size.]],
    {
      valid = onmt.utils.ExtendedCmdLine.isUInt()
    }
  },
  {
    '-max_tokens', 1800,
    [[Maximum tokens in a batch.]],
    {
      valid = onmt.utils.ExtendedCmdLine.isUInt()
    }
  },
  {
    '-uneven_batches', false,
    [[If set, batches are filled up to `-max_batch_size` even if the source lengths are different.
      Slower but needed for some tasks.]]
  },
  {
    '-optim', 'sgd',
    [[Optimization method.]],
    {
      enum = {'sgd', 'adagrad', 'adadelta', 'adam'},
      train_state = true
    }
  },
  {
    '-learning_rate', 1,
    [[Initial learning rate. If `adagrad` or `adam` is used, then this is the global learning rate.
      Recommended settings are: `sgd` = 1, `adagrad` = 0.1, `adam` = 0.0002.]],
    {
      train_state = true
    }
  },
  {
    '-min_learning_rate', 0,
    [[Do not continue the training past this learning rate value.]],
    {
      train_state = true
    }
  },
  {
    '-max_grad_norm', 5,
    [[Clip the gradients L2-norm to this value. Set to 0 to disable.]],
    {
      train_state = true
    }
  },
  {
    '-learning_rate_decay', 0.7,
    [[Learning rate decay factor: `learning_rate = learning_rate * learning_rate_decay`.]],
    {
      train_state = true
    }
  },
  {
    '-start_decay_at', 9,
    [[In "default" decay mode, start decay after this epoch.]],
    {
      valid = onmt.utils.ExtendedCmdLine.isUInt(),
      train_state = true
    }
  },
  {
    '-start_decay_score_delta', 0,
    [[Start decay when validation score improvement is lower than this value.]],
    {
      train_state = true
    }
  },
  {
    '-decay', 'default',
    [[When to apply learning rate decay.
      `default`: decay after each epoch past `-start_decay_at` or as soon as the
      validation score is not improving more than `-start_decay_score_delta`,
      `epoch_only`: only decay after each epoch past `-start_decay_at`,
      `score_only`: only decay when validation score is not improving more than
      `-start_decay_score_delta`.]],
    {
      enum = {'default', 'epoch_only', 'score_only'},
      train_state = true
    }
  },
  {
    '-decay_method', 'default',
    [[If `restart` is set, the optimizer states (if any) will be reset when the
      decay condition is met.]],
    {
      enum = {'default', 'restart'},
      train_state = true
    }
  }
}

function Optim.declareOpts(cmd)
  cmd:setCmdLineOptions(options, 'Optimization')
end

function Optim:__init(args)
  self.args = onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)
  self.valPerf = {}
end

function Optim:setOptimStates(states)
  self.optimStates = states
end

--[[ Sets optimization states to zero. ]]
function Optim:resetOptimStates()
  if self.optimStates == nil then
    return
  end

  for i = 1, #self.optimStates do
    for key, state in pairs(self.optimStates[i]) do
      if torch.isTensor(state) then
        state:zero()
      elseif key == 't' then
        self.optimStates[i].t = 0
      end
    end
  end
end

function Optim:zeroGrad(gradParams)
  for j = 1, #gradParams do
    gradParams[j]:zero()
  end
end

function Optim:prepareGrad(gradParams)
  if self.args.optim ~= 'sgd' and not self.optimStates then
    self.optimStates = {}
    for _ = 1, #gradParams do
      table.insert(self.optimStates, {})
    end
  end

  if self.args.max_grad_norm > 0 then
    Optim.clipGradByNorm(gradParams, self.args.max_grad_norm)
  end

  for j = 1, #gradParams do
    -- Prepare gradients params according to the optimization method.
    if self.args.optim == 'adagrad' then
      Optim.adagradStep(gradParams[j], self.args.learning_rate, self.optimStates[j])
    elseif self.args.optim == 'adadelta' then
      Optim.adadeltaStep(gradParams[j], self.optimStates[j])
    elseif self.args.optim == 'adam' then
      Optim.adamStep(gradParams[j], self.args.learning_rate, self.optimStates[j])
    else
      gradParams[j]:mul(-self.args.learning_rate)
    end
  end
end

function Optim:status()
  local status = 'Optim ' .. self.args.optim:upper()
  if self.args.optim ~= 'adadelta' then
    status = status .. ' LR '.. string.format("%.6f", self.args.learning_rate)
  end
  return status
end

function Optim:updateParams(params, gradParams)
  for j = 1, #params do
    params[j]:add(gradParams[j])
  end
end

--[[ Update the learning rate if conditions are met (see the documentation).

Parameters:

  * `score` - the last validation score.
  * `èpoch` - the current epoch number.
  * `evaluator` - the `Evaluator` used to compute `score`.

Returns: the new learning rate.

]]
function Optim:updateLearningRate(score, epoch, evaluator)
  local function decayLr()
    self.args.learning_rate = self.args.learning_rate * self.args.learning_rate_decay

    if self.args.decay_method == 'restart' then
      self:resetOptimStates()
    end
  end

  evaluator = evaluator or onmt.evaluators.PerplexityEvaluator.new()

  if self.args.optim == 'sgd' or self.args.optim == 'adam' then
    self.valPerf[#self.valPerf + 1] = score

    local epochCondMet = (epoch >= self.args.start_decay_at)
    local scoreCondMet = false

    if self.valPerf[#self.valPerf] ~= nil and self.valPerf[#self.valPerf-1] ~= nil then
      local currScore = self.valPerf[#self.valPerf]
      local prevScore = self.valPerf[#self.valPerf-1]
      scoreCondMet = not evaluator:compare(currScore, prevScore, self.args.start_decay_score_delta)
    end

    if self.args.decay == 'default' and (epochCondMet or scoreCondMet or self.startDecay) then
      self.startDecay = true
      decayLr()
    elseif self.args.decay == 'epoch_only' and epochCondMet then
      decayLr()
    elseif self.args.decay == 'score_only' and scoreCondMet then
      decayLr()
    end
  end

  return self.args.learning_rate
end

function Optim:isFinished()
  if self.args.optim == 'sgd' or self.args.optim == 'adam' then
    return self.args.learning_rate < self.args.min_learning_rate
  else
    return false
  end
end

function Optim:getLearningRate()
  return self.args.learning_rate
end

function Optim:getStates()
  return self.optimStates
end

--[[ Clips gradients to a maximum L2-norm.

Parameters:

  * `gradParams` - a table of Tensor.
  * `maxNorm` - the maximum L2-norm.

]]
function Optim.clipGradByNorm(gradParams, maxNorm)
  local gradNorm = 0
  for j = 1, #gradParams do
    gradNorm = gradNorm + gradParams[j]:norm()^2
  end
  gradNorm = math.sqrt(gradNorm)

  local clipCoef = maxNorm / gradNorm

  if clipCoef < 1 then
    for j = 1, #gradParams do
      gradParams[j]:mul(clipCoef)
    end
  end
end

function Optim.adagradStep(dfdx, lr, state)
  state.var = state.var or dfdx.new(dfdx:size()):zero()

  local std = dfdx.new(dfdx:size())

  state.var:addcmul(1, dfdx, dfdx)
  std:sqrt(state.var)
  dfdx:cdiv(std:add(1e-10)):mul(-lr)
end

function Optim.adamStep(dfdx, lr, state)
  local beta1 = state.beta1 or 0.9
  local beta2 = state.beta2 or 0.999
  local eps = state.eps or 1e-8

  state.t = state.t or 0
  state.m = state.m or dfdx.new(dfdx:size()):zero()
  state.v = state.v or dfdx.new(dfdx:size()):zero()

  local denom = dfdx.new(dfdx:size())

  state.t = state.t + 1
  state.m:mul(beta1):add(1-beta1, dfdx)
  state.v:mul(beta2):addcmul(1-beta2, dfdx, dfdx)
  denom:copy(state.v):sqrt():add(eps)

  local bias1 = 1-beta1^state.t
  local bias2 = 1-beta2^state.t
  local stepSize = lr * math.sqrt(bias2)/bias1

  dfdx:copy(state.m):cdiv(denom):mul(-stepSize)
end

function Optim.adadeltaStep(dfdx, state)
  local rho = state.rho or 0.9
  local eps = state.eps or 1e-6
  state.var = state.var or dfdx.new(dfdx:size()):zero()
  state.accDelta = state.accDelta or dfdx.new(dfdx:size()):zero()

  local std = dfdx.new(dfdx:size())
  local delta = dfdx.new(dfdx:size())

  state.var:mul(rho):addcmul(1-rho, dfdx, dfdx)
  std:copy(state.var):add(eps):sqrt()
  delta:copy(state.accDelta):add(eps):sqrt():cdiv(std):cmul(dfdx)
  dfdx:copy(delta):mul(-1)
  state.accDelta:mul(rho):addcmul(1-rho, delta, delta)
end

return Optim


text:
/*
 * Map.h
 *
 *  Created on: Apr 22, 2014
 *      Author: user
 */

#ifndef MAP_H_
#define MAP_H_

#define MAP_STATE_UNKNOWN 0
#define MAP_STATE_OBSTACLE 1
#define MAP_STATE_CLEAR 2
#define MAP_STATE_ROBOT 3

#include "Matrix.h"
#include "Robot.h"
#include "Point.h"
#include "Laser.h"
#include <math.h>
#include <iostream>

using namespace std;

class Robot;
class Laser;

class Map
{
	float _resolution;
	int _rows;
	int _columns;
	Matrix<int> _matrix;
	Point _prev;

public:
	Map & operator =(const Map& m);
	Map(int rows = MAP_ROWS, int columns = MAP_COLUMNS, double resolution = MAP_RESOLUTION);

	int convertYToRow(double y) const;
	int convertXToColumn(double x) const;

	Map(unsigned int rows, unsigned int columns, double resolution);

	// By x, y of world
	int get(double x, double y) const;
	void set(double x, double y, int value);
	void set(const Point& point, int value);

	// By row and column
	int get(int row, int column) const;
	void set(int row, int column, int value);

	// Tells if there is a mismatch between the new value and the existing value
	bool isMismatch(const Point& point, int value, bool & isUnknown);
	bool isMismatch(int row, int column, int value, bool & isUnknown);

	// Returns match percentage
	double handleObstacles(const Point& initalPoint, const vector<Point>& obstacles);
	double handleObstacles(Robot& robot, const vector<Point>& obstacles);

	// Returns match percentage
	double update(double x, double y, double yaw, const Laser& laser);

	friend std::ostream& operator<< (std::ostream& stream, const Map& matrix);
};

#endif /* MAP_H_ */


text:
package org.drools.mvel;

import org.drools.core.base.evaluators.Operator;
import org.drools.core.common.SingleBetaConstraints;
import org.drools.core.test.model.Cheese;

import org.drools.core.reteoo.NodeTypeEnums;
import org.drools.core.spi.BetaNodeFieldConstraint;
import org.junit.Test;

public class SingleBetaConstraintsTest extends BaseBetaConstraintsTest {

    @Test
    public void testIndexed() {
        BetaNodeFieldConstraint constraint0 = getConstraint( "cheeseType0", Operator.EQUAL, "type", Cheese.class );
        BetaNodeFieldConstraint [] constraints = new BetaNodeFieldConstraint [] { constraint0 };
        checkBetaConstraints( constraints, SingleBetaConstraints.class );
    }

    @Test
    public void testNotIndexed() {
        BetaNodeFieldConstraint  constraint0 = getConstraint( "cheeseType0", Operator.NOT_EQUAL, "type", Cheese.class );
        BetaNodeFieldConstraint [] constraints = new BetaNodeFieldConstraint [] { constraint0 };
        checkBetaConstraints( constraints, SingleBetaConstraints.class );
    }

    @Test
    public void testIndexedForComparison() {
        BetaNodeFieldConstraint  constraint0 = getConstraint( "cheeseType0", Operator.LESS, "type", Cheese.class );
        BetaNodeFieldConstraint [] constraints = new BetaNodeFieldConstraint [] { constraint0 };
        checkBetaConstraints( constraints, SingleBetaConstraints.class, NodeTypeEnums.ExistsNode );
    }

    @Test
    public void testNotIndexedForComparison() {
        BetaNodeFieldConstraint  constraint0 = getConstraint( "cheeseType0", Operator.LESS, "type", Cheese.class );
        BetaNodeFieldConstraint [] constraints = new BetaNodeFieldConstraint [] { constraint0 };
        checkBetaConstraints( constraints, SingleBetaConstraints.class, NodeTypeEnums.JoinNode );
    }
}


text:
import history from 'focus-core/history';

//TODO : à revoir avec Pierre et Nicolas => comment je connais le type de ligne ???
export default function onLineClick(data) {
    let url = '#';

    const {name} = data;
    //console.log(data, '\n', isMovie,'\n', isPerson,'\n', code);
    url = `#definitions/${name}`;

    history.navigate(url, true);
    window.scrollTo(0, 0);
}


text:
package org.usfirst.frc.team340.robot.commands;

import org.usfirst.frc.team340.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class DriveTurn extends Command {

	private double speed = 0;
	private double turn = 0;

    public DriveTurn(double speed, double turn) {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    	this.speed = speed;
    	this.turn = turn;
    	requires(Robot.drive);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.drive.arcadeDrive(speed, turn);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.drive.stopBothDrive();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}


text:
import random
import hashlib
import logging

from Crypto.PublicKey import RSA
from Crypto import Random

logger = logging.getLogger(__name__)

def generate_key_pair(username=None):
    random_generator = Random.new().read
    key = RSA.generate(2048, random_generator)
    if username is None:
        end = "chemtools-webapp"
    else:
        end = username + "@chemtools-webapp"
    a = {
        "public": " ".join([key.publickey().exportKey("OpenSSH"), end]),
        "private": key.exportKey('PEM'),
    }
    return a

def update_all_ssh_keys(user, new_public):
    for cred in user.credentials.filter(use_password=False):
        with cred.get_ssh_connection() as ssh, cred.get_sftp_connection() as sftp:
            s = "cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys.bak"
            _, _, err = ssh.exec_command(s)
            a = err.readlines()
            if a:
                logger.warn("Unable to update ssh key: %s - %s" % (cred, a))
                raise Exception(str(a))

            _, out, err = ssh.exec_command('echo $HOME')
            base = out.read().strip()

            with sftp.open("%s/.ssh/authorized_keys.bak" % base, 'r') as f1:
                with sftp.open("%s/.ssh/authorized_keys" % base, 'w') as f2:
                    for line in f1:
                        if "chemtools-webapp" in line:
                            line = new_public
                        f2.write(line)

def generate_key(text):
    salt = hashlib.sha1(str(random.random())).hexdigest()[:10]
    return hashlib.sha1(salt + text).hexdigest()

class Pages(object):

    def __init__(self):
        self.__registry = dict()

    def __getitem__(self, name):
        return self.__registry[name]

    def __setitem__(self, name, value):
        self.__registry[name] = value

    def __iter__(self):
        return iter(sorted(self.__registry.keys()))

PAGES = Pages()

def add_account_page(url):
    def decorator(f):
        PAGES[url] = f
        return f
    return decorator


text:
package org.bbop.apollo.gwt.client.dto;

import com.google.gwt.json.client.JSONObject;

/**
 * Created by ndunn on 4/17/15.
 * TODO: switch the name . .  horrible
 */
public interface HasJSON {

    JSONObject toJSON()  ;

}


text:
<?php
// Include the connect.php file
include ('connect.php');

// Connect to the database
// connection String
$mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno())
	{
	printf("Connect failed: %s\n", mysqli_connect_error());
	exit();
	}
$pagenum = $_GET['pagenum'];
$pagesize = $_GET['pagesize'];
$start = $pagenum * $pagesize;
$query = "SELECT SQL_CALC_FOUND_ROWS OrderDate, ShippedDate, ShipName, ShipAddress, ShipCity, ShipCountry FROM Orders LIMIT ?, ?";
$result = $mysqli->prepare($query);
$result->bind_param('ii', $start, $pagesize);
// filter data.
if (isset($_GET['filterscount']))
	{
	$filterscount = $_GET['filterscount'];
	if ($filterscount > 0)
		{
		$where = " WHERE (";
		$tmpdatafield = "";
		$tmpfilteroperator = "";
		$valuesPrep = "";
		$values = [];
		for ($i = 0; $i < $filterscount; $i++)
			{
			// get the filter's value.
			$filtervalue = $_GET["filtervalue" . $i];
			// get the filter's condition.
			$filtercondition = $_GET["filtercondition" . $i];
			// get the filter's column.
			$filterdatafield = $_GET["filterdatafield" . $i];
			// get the filter's operator.
			$filteroperator = $_GET["filteroperator" . $i];
			if ($tmpdatafield == "")
				{
				$tmpdatafield = $filterdatafield;
				}
			  else if ($tmpdatafield <> $filterdatafield)
				{
				$where.= ")AND(";
				}
			  else if ($tmpdatafield == $filterdatafield)
				{
				if ($tmpfilteroperator == 0)
					{
					$where.= " AND ";
					}
				  else $where.= " OR ";
				}
			// build the "WHERE" clause depending on the filter's condition, value and datafield.
			switch ($filtercondition)
				{
			case "CONTAINS":
				$condition = " LIKE ";
				$value = "%{$filtervalue}%";
				break;

			case "DOES_NOT_CONTAIN":
				$condition = " NOT LIKE ";
				$value = "%{$filtervalue}%";
				break;

			case "EQUAL":
				$condition = " = ";
				$value = $filtervalue;
				break;

			case "NOT_EQUAL":
				$condition = " <> ";
				$value = $filtervalue;
				break;

			case "GREATER_THAN":
				$condition = " > ";
				$value = $filtervalue;
				break;

			case "LESS_THAN":
				$condition = " < ";
				$value = $filtervalue;
				break;

			case "GREATER_THAN_OR_EQUAL":
				$condition = " >= ";
				$value = $filtervalue;
				break;

			case "LESS_THAN_OR_EQUAL":
				$condition = " <= ";
				$value = $filtervalue;
				break;

			case "STARTS_WITH":
				$condition = " LIKE ";
				$value = "{$filtervalue}%";
				break;

			case "ENDS_WITH":
				$condition = " LIKE ";
				$value = "%{$filtervalue}";
				break;

			case "NULL":
				$condition = " IS NULL ";
				$value = "%{$filtervalue}%";
				break;

			case "NOT_NULL":
				$condition = " IS NOT NULL ";
				$value = "%{$filtervalue}%";
				break;
				}
			$where.= " " . $filterdatafield . $condition . "? ";
			$valuesPrep = $valuesPrep . "s";
			$values[] = & $value;
			if ($i == $filterscount - 1)
				{
				$where.= ")";
				}
			$tmpfilteroperator = $filteroperator;
			$tmpdatafield = $filterdatafield;
			}
		$valuesPrep = $valuesPrep . "ii";
		$values[] = & $start;
		$values[] = & $pagesize;
		// build the query.
		$query = "SELECT SQL_CALC_FOUND_ROWS OrderDate, ShippedDate, ShipName, ShipAddress, ShipCity, ShipCountry FROM orders" . $where . " LIMIT ?, ?";
		$result = $mysqli->prepare($query);
		call_user_func_array(array(
			$result,
			"bind_param"
		) , array_merge(array(
			$valuesPrep
		) , $values));
		}
	}
$result->execute();
/* bind result variables */
$result->bind_result($OrderDate, $ShippedDate, $ShipName, $ShipAddress, $ShipCity, $ShipCountry);
/* fetch values */
while ($result->fetch())
	{
	$orders[] = array(
		'OrderDate' => $OrderDate,
		'ShippedDate' => $ShippedDate,
		'ShipName' => $ShipName,
		'ShipAddress' => $ShipAddress,
		'ShipCity' => $ShipCity,
		'ShipCountry' => $ShipCountry
	);
	}
$result = $mysqli->prepare("SELECT FOUND_ROWS()");
$result->execute();
$result->bind_result($total_rows);
$result->fetch();
$data[] = array(
	'TotalRows' => $total_rows,
	'Rows' => $orders
);
echo json_encode($data);
/* close statement */
$result->close();
/* close connection */
$mysqli->close();
?>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.partnet</groupId>
    <artifactId>seauto</artifactId>
    <version>0.9.2-SNAPSHOT</version>
  </parent>
  <artifactId>seauto-driver-manager</artifactId>
  <packaging>maven-plugin</packaging>

  <name>seauto-driver-manager</name>
  <description>SeAuto Driver Manager</description>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>2.0</version>
    </dependency>

    <!-- dependencies to annotations -->
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <version>3.4</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.partnet</groupId>
      <artifactId>seauto-core</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <version>3.4</version>
        <configuration>
          <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
        </configuration>
        <executions>
          <execution>
            <id>mojo-descriptor</id>
            <phase>process-classes</phase>
            <goals>
              <goal>descriptor</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
package shiver.me.timbers.retrying;

import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static shiver.me.timbers.data.random.RandomEnums.someEnum;
import static shiver.me.timbers.data.random.RandomIntegers.someNegativeInteger;
import static shiver.me.timbers.data.random.RandomIntegers.somePositiveInteger;
import static shiver.me.timbers.data.random.RandomLongs.someLongs;

public class OptionsServiceConfigurerTest {

    private OptionsServiceConfigurer configurer;

    @Before
    public void setUp() {
        configurer = new OptionsServiceConfigurer();
    }

    @Test
    @SuppressWarnings("unchecked")
    public void Can_configure_an_options_service() {

        final OptionsService optionsService = mock(OptionsService.class);
        final Retry retry = mock(Retry.class);

        final Integer retries = somePositiveInteger();
        final Interval interval = mock(Interval.class);
        final Long[] intervalDurations = someLongs().array();
        final TimeUnit intervalUnit = someEnum(TimeUnit.class);
        final Class[] includes = {RuntimeException.class, IllegalArgumentException.class, Error.class};
        final Class[] excludes = {IllegalStateException.class, ClassCastException.class, IllegalAccessError.class};

        // Given
        given(retry.value()).willReturn(retries);
        given(retry.interval()).willReturn(interval);
        given(interval.durations()).willReturn(toPrimitives(intervalDurations));
        given(interval.unit()).willReturn(intervalUnit);
        given(retry.includes()).willReturn(includes);
        given(retry.excludes()).willReturn(excludes);

        // When
        configurer.configure(optionsService, retry);

        // Then
        verify(optionsService).withRetries(retries);
        verify(optionsService).withIntervals(intervalUnit, intervalDurations);
        verify(optionsService).includes(includes);
        verify(optionsService).excludes(excludes);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void Will_not_configure_default_options() {

        final OptionsService optionsService = mock(OptionsService.class);
        final Retry retry = mock(Retry.class);

        final Interval interval = mock(Interval.class);

        // Given
        given(retry.value()).willReturn(someNegativeInteger());
        given(retry.interval()).willReturn(interval);
        given(interval.durations()).willReturn(new long[0]);
        given(interval.unit()).willReturn(someEnum(TimeUnit.class));
        given(retry.includes()).willReturn(new Class[0]);
        given(retry.excludes()).willReturn(new Class[0]);

        // When
        configurer.configure(optionsService, retry);

        // Then
        verifyZeroInteractions(optionsService);
    }

    private static long[] toPrimitives(Long[] longs) {
        final long[] primitives = new long[longs.length];
        for (int i = 0; i < longs.length; i++) {
            primitives[i] = longs[i];
        }
        return primitives;
    }
}


text:
svn-to-git
==========

A Subversion to Git migration tool for repositories with complex layouts.

By complex layouts, I mean:

1.  You have multi-level tags and branches like tags/2.0/2.0.1 and
    branches/2.2/2.2.1

2.  You have multiple sub-projects in your repo and have copied code
    from other areas of the repo into your project of interest.

3.  You may have, at some point, checked in code against a tag.

Installation
------------

You need:

1.  PHP 5.2 or later, preferably a 64-bit build, as 32-bit PHP cannot seek
    around in Subversion dump files larger than 2GB in size.

2.  A Subversion repository dumped via "svnadmin dump"

3.  Enough disk space; potentially up to 3 time the size of the dump file,
    depending on how much of the repo you want to pull into Git.

Operation
---------

For help, run svn-to-git --help.

You'll typically run in two stages; analysis while you figure out what you
want, and then complete the run when you're happy.

### Analysis ###

    ./svn-to-git --svn-dump my.dump --analyze

This will examine your repo and tell what it's going to do.  It may ask you
to add --branch or --exclude-branch hints and re-run.

### Completion ###

Once you're happy with the plan, you can run it to completion:

    ./svn-to-git --svn-dump my.dump --complete --git-repo /path/to/target/git

You'll almost certainly want to use the --authors option to set up an
author map.

Check out the --help output for more information.

Background Information
======================

Subversion has a somewhat strange notion of branches.  People (or perhaps just
us) abuse or extend the branches/branchname and tags/tagname convention and use
hierarchical schemes.  Sometimes people commit to tags because it is convenient
to do so.

All of the existing migration tools I have found assume that you're using
subversion 100% according to the conventions suggested (but not mandated) by
the subversion documentation.  This can lead to a broken conversion.

How svn-to-git works:

First obtain an svndump of your Subversion repository.  svn-to-git will only
process dump files; it cannot work with a repository URL.

Second, tell svn-to-git which is the mainline for your repository.  The default
is trunk, but any location in the repo is acceptable.

svn-to-git will then analyze the dump file to determine branches created from
your main line; these branches will be followed, and branches created from
those branches will be followed recursively.

If svn-to-git finds merge activity coming in to any of the tracked branches
from non-tracked branches, the analysis will bail out and ask you to re-try,
but this time with a hint on whether you want to exclude or include the
non-tracked branch.

At the end of the analysis, svn-to-git has information on all the branches that
will take part in the Git migration.

Tags:

Subversion has tags-by-convention.  They're really branches.  These are not
compatible with the immutable nature of tags in Git.  If svn-to-git detects a
tag in the svn repo, it checks the commit activity against the tag; if there is
no activity beyond the initial create (or final delete) then the tag is deemed
to be a pure tag and will be created as a annotated tag in the Git repository.
If the tag is impure (it has any other changes applied against it) then
svn-to-git will create a branch instead, and will create a tag for the final
commit against that branch.

With the analysis complete, svn-to-git generates a data file to feed into the
Git fast-import tool.


text:
local bit = require "bgcrypto.private.bit"

local sbyte = string.byte
local schar = string.char
local sgsub = string.gsub
local ssub  = string.sub
local srep  = string.rep
local bxor  = bit.bxor

local function hmac_xor(str, b)
  return sgsub(str, '.', function(ch)
    return schar(bxor(sbyte(ch), b))
  end)
end

local function hmac_key(hash, key)
  if #key > hash.BLOCK_SIZE then key = hash.digest(key) end
  key = key .. srep('\0', hash.BLOCK_SIZE - #key)
  return key, hmac_xor(key, 54), hmac_xor(key, 92)
end

local function hmac_hash(hash, key, value, i, size, text)
  local key, ipad, opad = hmac_key(hash, key)

  if type(i) ~= 'number' then text = not not i
  else
    if type(size) ~= 'number' then
      size, text = #value, not not size
    end
    value = ssub(value, i, i + size - 1)
  end

  return hash.digest( opad .. hash.digest(ipad .. value), text)
end

local hmac = {} do
hmac.__index = hmac

function hmac:new(hash, key)
  assert(type(key) == 'string')
  local o = setmetatable({
    private_ = {
      hash = hash;
      hctx = hash.new();
    }
  },self)
  o:reset(key)
  return o
end

function hmac:clone()
  local o = setmetatable({
    private_ = {
      hash = self.private_.hash;
      hctx = self.private_.hctx:clone();
      ipad = self.private_.ipad;
      opad = self.private_.opad;
    }
  },hmac)

  return o
end

function hmac:reset(key)
  local hash = self.private_.hash
  local hctx = self.private_.hctx

  if key then
    key, self.private_.ipad, self.private_.opad = hmac_key(hash, key)
  end

  hctx:reset()
  hctx:update(assert(self.private_.ipad))

  return self
end

function hmac:update(chunk, i, size)
  self.private_.hctx:update(chunk, i, size)
  return self
end

function hmac:digest(chunk, text)
  if type(chunk) ~= 'string' then text, chunk = chunk end
  if chunk then self:update(chunk) end

  local hash = self.private_.hash
  local hctx = self.private_.hctx
  local opad = self.private_.opad
  return hash.digest(opad .. hctx:digest(), text)
end

function hmac:destroy()
  if not self.private_ then return end
  self.private_.hctx:destroy()
  self.private_ = nil
end

function hmac:destroyed()
  return not not self.private_
end

end

return {
  new    = function(...) return hmac:new(...) end;
  digest = hmac_hash;
}


text:
package controlapi

import (
	"context"

	"github.com/sirupsen/logrus"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/moby/swarmkit/v2/api"
	"github.com/moby/swarmkit/v2/identity"
	"github.com/moby/swarmkit/v2/log"
	"github.com/moby/swarmkit/v2/manager/state/store"
)

// CreateResource returns a `CreateResourceResponse` after creating a `Resource` based
// on the provided `CreateResourceRequest.Resource`.
//   - Returns `InvalidArgument` if the `CreateResourceRequest.Resource` is malformed,
//     or if the config data is too long or contains invalid characters.
//   - Returns an error if the creation fails.
func (s *Server) CreateResource(ctx context.Context, request *api.CreateResourceRequest) (*api.CreateResourceResponse, error) {
	if request.Annotations == nil || request.Annotations.Name == "" {
		return nil, status.Errorf(codes.InvalidArgument, "Resource must have a name")
	}

	// finally, validate that Kind is not an emptystring. We know that creating
	// with Kind as empty string should fail at the store level, but to make
	// errors clearer, special case this.
	if request.Kind == "" {
		return nil, status.Errorf(codes.InvalidArgument, "Resource must belong to an Extension")
	}
	r := &api.Resource{
		ID:          identity.NewID(),
		Annotations: *request.Annotations,
		Kind:        request.Kind,
		Payload:     request.Payload,
	}

	err := s.store.Update(func(tx store.Tx) error {
		return store.CreateResource(tx, r)
	})

	switch err {
	case store.ErrNoKind:
		return nil, status.Errorf(codes.InvalidArgument, "Kind %v is not registered", r.Kind)
	case store.ErrNameConflict:
		return nil, status.Errorf(
			codes.AlreadyExists,
			"A resource with name %v already exists",
			r.Annotations.Name,
		)
	case nil:
		log.G(ctx).WithFields(logrus.Fields{
			"resource.Name": r.Annotations.Name,
			"method":        "CreateResource",
		}).Debugf("resource created")
		return &api.CreateResourceResponse{Resource: r}, nil
	default:
		return nil, err
	}
}

// GetResource returns a `GetResourceResponse` with a `Resource` with the same
// id as `GetResourceRequest.Resource`
// - Returns `NotFound` if the Resource with the given id is not found.
// - Returns `InvalidArgument` if the `GetResourceRequest.Resource` is empty.
// - Returns an error if getting fails.
func (s *Server) GetResource(ctx context.Context, request *api.GetResourceRequest) (*api.GetResourceResponse, error) {
	if request.ResourceID == "" {
		return nil, status.Errorf(codes.InvalidArgument, "resource ID must be present")
	}
	var resource *api.Resource
	s.store.View(func(tx store.ReadTx) {
		resource = store.GetResource(tx, request.ResourceID)
	})

	if resource == nil {
		return nil, status.Errorf(codes.NotFound, "resource %s not found", request.ResourceID)
	}

	return &api.GetResourceResponse{Resource: resource}, nil
}

// RemoveResource removes the `Resource` referenced by `RemoveResourceRequest.ResourceID`.
// - Returns `InvalidArgument` if `RemoveResourceRequest.ResourceID` is empty.
// - Returns `NotFound` if the a resource named `RemoveResourceRequest.ResourceID` is not found.
// - Returns an error if the deletion fails.
func (s *Server) RemoveResource(ctx context.Context, request *api.RemoveResourceRequest) (*api.RemoveResourceResponse, error) {
	if request.ResourceID == "" {
		return nil, status.Errorf(codes.InvalidArgument, "resource ID must be present")
	}
	err := s.store.Update(func(tx store.Tx) error {
		return store.DeleteResource(tx, request.ResourceID)
	})
	switch err {
	case store.ErrNotExist:
		return nil, status.Errorf(codes.NotFound, "resource %s not found", request.ResourceID)
	case nil:
		return &api.RemoveResourceResponse{}, nil
	default:
		return nil, err
	}
}

// ListResources returns a `ListResourcesResponse` with a list of `Resource`s stored in the raft store,
// or all resources matching any name in `ListConfigsRequest.Names`, any
// name prefix in `ListResourcesRequest.NamePrefixes`, any id in
// `ListResourcesRequest.ResourceIDs`, or any id prefix in `ListResourcesRequest.IDPrefixes`.
// - Returns an error if listing fails.
func (s *Server) ListResources(ctx context.Context, request *api.ListResourcesRequest) (*api.ListResourcesResponse, error) {
	var (
		resources     []*api.Resource
		respResources []*api.Resource
		err           error
		byFilters     []store.By
		by            store.By
		labels        map[string]string
	)

	// andKind is set to true if the Extension filter is not the only filter
	// being used. If this is the case, we do not have to compare by strings,
	// which could be slow.
	var andKind bool

	if request.Filters != nil {
		for _, name := range request.Filters.Names {
			byFilters = append(byFilters, store.ByName(name))
		}
		for _, prefix := range request.Filters.NamePrefixes {
			byFilters = append(byFilters, store.ByNamePrefix(prefix))
		}
		for _, prefix := range request.Filters.IDPrefixes {
			byFilters = append(byFilters, store.ByIDPrefix(prefix))
		}
		labels = request.Filters.Labels
		if request.Filters.Kind != "" {
			// if we're filtering on Extensions, then set this to true. If Kind is
			// the _only_ kind of filter, we'll set this to false below.
			andKind = true
		}
	}

	switch len(byFilters) {
	case 0:
		// NOTE(dperny): currently, filtering using store.ByKind would apply an
		// Or operation, which means that filtering by kind would return a
		// union. However, for Kind filters, we actually want the
		// _intersection_; that is, _only_ objects of the specified kind. we
		// could dig into the db code to figure out how to write and use an
		// efficient And combinator, but I don't have the time nor expertise to
		// do so at the moment. instead, we'll filter by kind after the fact.
		// however, if there are no other kinds of filters, and we're ONLY
		// listing by Kind, we can set that to be the only filter.
		if andKind {
			by = store.ByKind(request.Filters.Kind)
			andKind = false
		} else {
			by = store.All
		}
	case 1:
		by = byFilters[0]
	default:
		by = store.Or(byFilters...)
	}

	s.store.View(func(tx store.ReadTx) {
		resources, err = store.FindResources(tx, by)
	})
	if err != nil {
		return nil, err
	}

	// filter by label and extension
	for _, resource := range resources {
		if !filterMatchLabels(resource.Annotations.Labels, labels) {
			continue
		}
		if andKind && resource.Kind != request.Filters.Kind {
			continue
		}
		respResources = append(respResources, resource)
	}

	return &api.ListResourcesResponse{Resources: respResources}, nil
}

// UpdateResource updates the resource with the given `UpdateResourceRequest.Resource.Id` using the given `UpdateResourceRequest.Resource` and returns a `UpdateResourceResponse`.
// - Returns `NotFound` if the Resource with the given `UpdateResourceRequest.Resource.Id` is not found.
// - Returns `InvalidArgument` if the UpdateResourceRequest.Resource.Id` is empty.
// - Returns an error if updating fails.
func (s *Server) UpdateResource(ctx context.Context, request *api.UpdateResourceRequest) (*api.UpdateResourceResponse, error) {
	if request.ResourceID == "" || request.ResourceVersion == nil {
		return nil, status.Errorf(codes.InvalidArgument, "must include ID and version")
	}
	var r *api.Resource
	err := s.store.Update(func(tx store.Tx) error {
		r = store.GetResource(tx, request.ResourceID)
		if r == nil {
			return status.Errorf(codes.NotFound, "resource %v not found", request.ResourceID)
		}

		if request.Annotations != nil {
			if r.Annotations.Name != request.Annotations.Name {
				return status.Errorf(codes.InvalidArgument, "cannot change resource name")
			}
			r.Annotations = *request.Annotations
		}
		r.Meta.Version = *request.ResourceVersion
		// only alter the payload if the
		if request.Payload != nil {
			r.Payload = request.Payload
		}

		return store.UpdateResource(tx, r)
	})
	switch err {
	case store.ErrSequenceConflict:
		return nil, status.Errorf(codes.InvalidArgument, "update out of sequence")
	case nil:
		return &api.UpdateResourceResponse{
			Resource: r,
		}, nil
	default:
		return nil, err
	}
}


text:
var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
  userName: String,
  userId: Number,
  location: [{type: mongoose.Schema.Types.ObjectId, ref: 'Location'}]
});

module.exports = mongoose.model('User', userSchema );


text:
package com.garmin.fit;

public interface FileCapabilitiesMesgListener {
   public void onMesg(FileCapabilitiesMesg mesg);
}


text:
module Landable
  module Traffic
    class Device < ActiveRecord::Base
      include Landable::TableName

      lookup_by :device, cache: 50, find_or_create: true

      has_many :user_agents
    end
  end
end