text:
============================
 Fourfront Metadata Database
============================

|Build status|_

.. |Build status| image:: https://travis-ci.org/4dn-dcic/fourfront.png?branch=master
.. _Build status: https://travis-ci.org/4dn-dcic/fourfront

|Coverage|_

.. |Coverage| image:: https://coveralls.io/repos/github/4dn-dcic/fourfront/badge.svg?branch=master
.. _Coverage: https://coveralls.io/github/4dn-dcic/fourfront?branch=master

|Quality|_

.. |Quality| image:: https://api.codacy.com/project/badge/Grade/f5fc54006b4740b5800e83eb2aeeeb43
.. _Quality: https://www.codacy.com/app/4dn/fourfront?utm_source=github.com&utm_medium=referral&utm_content=4dn-dcic/fourfront&utm_campaign=Badge_Grade

Overview
========

This is a fork from `ENCODE-DCC/encoded <https://github.com/ENCODE-DCC/encoded>`_ .  We are working to modularize the project and adapted to our needs for the 4D Nucleome project.

Installation
============

Fourfront is known to work with Python 3.6.x and 3.7.x and will not work with Python 3.8 or greater.
If part of the HMS team, it is recommended to use a high patch version, such as Python 3.7.12,
since that's what we try to do with our servers, but any version of 3.7 should work if you
find you are unable to install that particular patch version.
It is best practice to create a fresh Python
virtualenv using one of these versions before proceeding to the following steps.

Step 0: Obtain Credentials
--------------------------

Obtain AWS keys. These will need to added to your environment variables or through the AWS CLI (installed later in this process).

Step 1: Verify Homebrew Itself
------------------------------

Verify that homebrew is working properly::

    $ brew doctor

Step 2: Install Homebrewed Dependencies
---------------------------------------

Install or update dependencies::

    $ brew install libevent libmagic libxml2 libxslt openssl postgresql graphviz nginx python3
    $ brew install freetype libjpeg libtiff littlecms webp  # Required by Pillow
    $ brew cask install adoptopenjdk8
    $ brew install elasticsearch@6.8 node@10

NOTES:

* To migrate from ES5 to ES6 (--force option may be needed)::

    $ brew unlink elasticsearch@5.6
    $ brew install elasticsearch@6.8
    $ brew link elasticsearch@6.8

* If installation of adtopopenjdk8 fails due to an ambiguity, it should work to do this instead::

    $ brew cask install homebrew/cask-versions/adoptopenjdk8

* If you need to update dependencies::

    $ brew update
    $ rm -rf encoded/eggs

* If you need to upgrade brew-installed packages that don't have pinned versions,
  you can use the following. However, take care because there is no command to directly
  undo this effect::

    $ brew update
    $ brew upgrade
    $ rm -rf encoded/eggs

Step 3: Running Make
------------------------

Run make::

    $ make build-dev  # for all dependencies
    OR
    $ make build      # for only application level dependencies

NOTES:

* If you have issues with postgres or the python interface to it (psycogpg2)
  you probably need to install postgresql via homebrew (as above)

* If you have issues with Pillow you may need to install new xcode command line tools.

  - First update Xcode from AppStore (reboot)::

      $ xcode-select --install

  - If you are running macOS Mojave (though this is fixed in Catalina), you may need to run this command as well::

      $ sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /

  - If you have trouble with zlib, especially in Catalina, it is probably because brew installed it
    in a different location. In that case, you'll want to do the following
    in place of the regular call to buildout::

      $ CFLAGS="-I$(brew --prefix zlib)/include" LDFLAGS="-L$(brew --prefix zlib)/lib" bin/buildout

* If you wish to completely rebuild the application, or have updated dependencies,
  before you go ahead, you'll probably want to do::

    $ make clean

  Then goto Step 3.

Step 4: Running the Application Locally
---------------------------------------

Start the application locally

In one terminal startup the database servers and nginx proxy with::

    $ make deploy1

This will first clear any existing data in /tmp/encoded.
Then postgres and elasticsearch servers will be initiated within /tmp/encoded.
An nginx proxy running on port 8000 will be started.
The servers are started, and finally the test set will be loaded.

In a second terminal, run the app with::

    $ make deploy2

Indexing will then proceed in a background thread similar to the production setup.

Running the app with the `--reload` flag will cause the app to restart when changes to the Python source files are detected::

    $ bin/pserve development.ini --reload

If doing this, it is highly recommended to set the following environment variable to override the default file monitor used. The default monitor on Unix systems is watchman, which can cause problems due too tracking too many files and degrade performance. Use the following environment variable::

    $ HUPPER_DEFAULT_MONITOR=hupper.polling.PollingFileMonitor

Browse to the interface at http://localhost:8000/.

Running tests
=============

Python Testing
--------------

To run specific tests locally::

    $ bin/test -k test_name

To run with a debugger::

    $ bin/test --pdb

Specific tests to run locally for schema changes::

    $ bin/test -k test_load_workbook
    $ bin/test -k test_edw_sync

Run the Pyramid tests with::

    $ bin/test

Note: to run against chrome you should first::

    $ brew install chromedriver

Javascript Testing
------------------

Run the Javascript tests with::

    $ npm test

Or if you need to supply command line arguments::

    $ ./node_modules/.bin/jest

Building Javascript
===================

Our Javascript is written using ES6 and JSX, so needs to be compiled
using babel and webpack.

To build production-ready bundles, do::

    $ npm run build

(This is also done as part of running buildout.)

To build development bundles and continue updating them as you edit source files, run::

    $ npm run dev

The development bundles are not minified, to speed up building.

Notes on SASS/SCSS
==================

We use the `SASS <http://sass-lang.com/>`_ and `node-sass <https://github.com/sass/node-sass/>`_ CSS preprocessors.
The buildout installs the SASS utilities and compiles the CSS.
When changing the SCSS source files you must recompile the CSS using one of the following methods:

Compiling "on the fly"
----------------------

Node-sass can watch for any changes made to .scss files and instantly compile them to .css.
To start this, from the root of the project do::

    $ npm run watch-scss

Force compiling
---------------

::

    $ npm run build-scss


text:
<?php namespace Models;

use Illuminate\Database\Eloquent\Model;

use Models\TestUser;

class TestPayment extends Model{

	protected $guarded = [];
    public $timestamps = false;

    public function testUser(){
        return $this -> belongsTo(TestUser::class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Xml.Serialization;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// KoubeiMarketingDataMemberReportQueryResponse.
    /// </summary>
    public class KoubeiMarketingDataMemberReportQueryResponse : AopResponse
    {
        /// <summary>
        /// 查询成功时返回json格式数据
        /// </summary>
        [XmlElement("report_data")]
        public string ReportData { get; set; }
    }
}


text:
package com.hp.ov.sdk.adaptors;

import java.lang.reflect.Type;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.hp.ov.sdk.dto.Patch;

public class PatchSerializer implements JsonSerializer<Patch> {

    @Override
    public JsonElement serialize(Patch src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject patch = new JsonObject();

        patch.addProperty("from", src.getFrom());
        patch.addProperty("op", src.getOp().toString());
        patch.addProperty("path", src.getPath());
        patch.add("value", context.serialize(src.getValue()));

        JsonArray array = new JsonArray();

        array.add(patch);

        return array;
    }
}


text:
using namespace graphlab::extension;

int main(int argc, char** argv) {
  extension_graph graph;
  if (argc < 2) {
    std::cout << argv[0] << " [input prefix] optional:[output prefix]\n";
    return 0;
  }
  graph.load_structure(argv[1], "snap");
  pagerank(graph, "pr", 0.01);
  if (argc > 2) {
    graph.save_vertices(argv[2], "pr");
  }
}


text:
import requests
import logging
import time
import ratelim

# Local imports
from utils.common.db_utils import read_all_results
from utils.common.datapipeline import DataPipeline
# from retrying import retry

RATELIM_DUR = 50 * 60
RATELIM_QUERIES = 8500

# @retry(wait_random_min=2000, wait_random_max=60000, stop_max_attempt_number=10)
@ratelim.patient(RATELIM_QUERIES, RATELIM_DUR)
def get_events(urlname, params):
    # Set the offset parameter and make the request
    r = requests.get("https://api.meetup.com/{}/events".format(urlname),
                     params=params)
    #if r.status_code in (410, 404):
    #    return []
    try:
        r.raise_for_status()
    except Exception as err:
        return str(err)
    # If no response is found
    if len(r.text) == 0:
        time.sleep(5)
        return get_events(urlname, params)
    return r.json()

def filter_groups(groups, config):
    '''Filter groups matching target country/category'''
    groups = [row for row in groups
              if row['country_name'] == config['parameters']['country']]
    groups = [row for row in groups
              if row['category_id'] == int(config['parameters']['category'])]
    return groups

def run(config):
    # Get already collected groups
    done_groups = read_all_results(config, 'output_db', 'table_name')
    done_groups = set(row['group_id'] for row in done_groups)
    # Get all possible input groups
    groups = read_all_results(config, 'input_db', 'input_table')
    groups = filter_groups(groups, config)
    groups = set((row['id'], row['urlname'])
                 for row in groups
                 if row['id'] not in done_groups)

    # Collect group info
    logging.info("Got %s distinct groups from database", len(groups))

    # Collect events
    api_key = config["Meetup"]["api-key"]
    max_results = 200
    output = []
    failed = []
    for group_id, group_urlname in groups:
        events = []
        for desc in (True, False):
            params = dict(page=max_results, key=api_key,
                          desc=desc, status="past")
            result = get_events(group_urlname, params)
            if type(result) == str:
                print(result)
                print(group_urlname)
                failed.append([group_urlname, desc])
                continue
            events += result
        # Consolidate required info into output
        for info in events:
            attendance = None
            if "manual_attendance_count" in info:
                attendance = info["manual_attendance_count"]
            yes_rsvp_count = info["yes_rsvp_count"]
            row = dict(event_id=info["id"],
                       group_urlname=group_urlname,
                       group_id=group_id,
                       event_time=info["time"],
                       event_manual_attendance_count=attendance,
                       event_yes_rsvp_count=yes_rsvp_count)
            output.append(row)

    logging.info("Warning: %s events failed:\n%s", len(failed), failed)
    # Write to output
    logging.info("Got %s rows of data", len(output))
    with DataPipeline(config) as dp:
        for row in output:
            dp.insert(row)


text: export { default } from './PasswordRequirementsList';


text:
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================

#ifndef CHCONTACTDVI_H
#define CHCONTACTDVI_H

#include "chrono/core/ChFrame.h"
#include "chrono/core/ChVectorDynamic.h"
#include "chrono/solver/ChConstraintTwoTuplesContactN.h"
#include "chrono/solver/ChSystemDescriptor.h"
#include "chrono/collision/ChCCollisionModel.h"
#include "chrono/physics/ChContactTuple.h"
#include "chrono/physics/ChContactContainerBase.h"
#include "chrono/physics/ChSystem.h"

namespace chrono {

/// Class for DVI contact between two generic ChContactable objects.
/// Ta and Tb are of ChContactable sub classes.

template <class Ta, class Tb>
class ChContactDVI : public ChContactTuple<Ta, Tb> {
  public:
    typedef typename ChContactTuple<Ta, Tb>::typecarr_a typecarr_a;
    typedef typename ChContactTuple<Ta, Tb>::typecarr_b typecarr_b;

  protected:
    float* reactions_cache;  ///< N,U,V reactions which might be stored in a persistent contact manifold

    /// The three scalar constraints, to be fed into the system solver.
    /// They contain jacobians data and special functions.
    ChConstraintTwoTuplesContactN<typecarr_a, typecarr_b> Nx;
    ChConstraintTwoTuplesFrictionT<typecarr_a, typecarr_b> Tu;
    ChConstraintTwoTuplesFrictionT<typecarr_a, typecarr_b> Tv;

    ChVector<> react_force;

    double compliance;
    double complianceT;
    double restitution;
    double dampingf;

  public:
    //
    // CONSTRUCTORS
    //

    ChContactDVI() {
        Nx.SetTangentialConstraintU(&Tu);
        Nx.SetTangentialConstraintV(&Tv);
    }

    ChContactDVI(ChContactContainerBase* mcontainer,      ///< contact container
                 Ta* mobjA,                               ///< collidable object A
                 Tb* mobjB,                               ///< collidable object B
                 const collision::ChCollisionInfo& cinfo  ///< data for the contact pair
                 )
        : ChContactTuple<Ta, Tb>(mcontainer, mobjA, mobjB, cinfo) {
        Nx.SetTangentialConstraintU(&Tu);
        Nx.SetTangentialConstraintV(&Tv);

        Reset(mobjA, mobjB, cinfo);
    }

    ~ChContactDVI() {}

    //
    // FUNCTIONS
    //

    /// Initialize again this constraint.
    virtual void Reset(Ta* mobjA,                               ///< collidable object A
                       Tb* mobjB,                               ///< collidable object B
                       const collision::ChCollisionInfo& cinfo  ///< data for the contact pair
                       ) override {
        // inherit base class:
        ChContactTuple<Ta, Tb>::Reset(mobjA, mobjB, cinfo);

        Nx.Get_tuple_a().SetVariables(*this->objA);
        Nx.Get_tuple_b().SetVariables(*this->objB);
        Tu.Get_tuple_a().SetVariables(*this->objA);
        Tu.Get_tuple_b().SetVariables(*this->objB);
        Tv.Get_tuple_a().SetVariables(*this->objA);
        Tv.Get_tuple_b().SetVariables(*this->objB);

        // Compute the 'average' material

        // just low level casting, now, since we are sure that this contact was created only if dynamic casting was fine
        ChMaterialSurface* mmatA = (ChMaterialSurface*)(this->objA->GetMaterialSurfaceBase().get());
        ChMaterialSurface* mmatB = (ChMaterialSurface*)(this->objB->GetMaterialSurfaceBase().get());

        ChMaterialCouple mat;
        mat.static_friction = (float)ChMin(mmatA->static_friction, mmatB->static_friction);
        mat.restitution = (float)ChMin(mmatA->restitution, mmatB->restitution);
        mat.cohesion = (float)ChMin(mmatA->cohesion, mmatB->cohesion);
        mat.dampingf = (float)ChMin(mmatA->dampingf, mmatB->dampingf);
        mat.compliance = (float)(mmatA->compliance + mmatB->compliance);
        mat.complianceT = (float)(mmatA->complianceT + mmatB->complianceT);
        // mat.complianceRoll = (float)(mmatA->complianceRoll + mmatB->complianceRoll);
        // mat.complianceSpin = (float)(mmatA->complianceSpin + mmatB->complianceSpin);
        // mat.rolling_friction = (float)ChMin(mmatA->rolling_friction, mmatB->rolling_friction);
        // mat.spinning_friction = (float)ChMin(mmatA->spinning_friction, mmatB->spinning_friction);

        // see if the user wants to modify the material via a callback:
        if (this->container->GetAddContactCallback()) {
            this->container->GetAddContactCallback()->ContactCallback(cinfo, mat);
        }

        Nx.SetFrictionCoefficient(mat.static_friction);
        Nx.SetCohesion(mat.cohesion);

        this->restitution = mat.restitution;
        this->dampingf = mat.dampingf;
        this->compliance = mat.compliance;
        this->complianceT = mat.complianceT;

        this->reactions_cache = cinfo.reaction_cache;

        // COMPUTE JACOBIANS

        // delegate objA to compute its half of jacobian
        this->objA->ComputeJacobianForContactPart(this->p1, this->contact_plane, Nx.Get_tuple_a(), Tu.Get_tuple_a(),
                                                  Tv.Get_tuple_a(), false);

        // delegate objB to compute its half of jacobian
        this->objB->ComputeJacobianForContactPart(this->p2, this->contact_plane, Nx.Get_tuple_b(), Tu.Get_tuple_b(),
                                                  Tv.Get_tuple_b(), true);

        react_force = VNULL;
    }

    /// Get the contact force, if computed, in contact coordinate system
    virtual ChVector<> GetContactForce() const override { return react_force; }

    /// Get the contact friction coefficient
    virtual double GetFriction() { return Nx.GetFrictionCoefficient(); }

    /// Set the contact friction coefficient
    virtual void SetFriction(double mf) { Nx.SetFrictionCoefficient(mf); }

    //
    // UPDATING FUNCTIONS
    //

    virtual void ContIntStateGatherReactions(const unsigned int off_L, ChVectorDynamic<>& L) override {
        L(off_L) = react_force.x();
        L(off_L + 1) = react_force.y();
        L(off_L + 2) = react_force.z();
    }

    virtual void ContIntStateScatterReactions(const unsigned int off_L, const ChVectorDynamic<>& L) override {
        react_force.x() = L(off_L);
        react_force.y() = L(off_L + 1);
        react_force.z() = L(off_L + 2);
    }

    virtual void ContIntLoadResidual_CqL(const unsigned int off_L,    ///< offset in L multipliers
                                         ChVectorDynamic<>& R,        ///< result: the R residual, R += c*Cq'*L
                                         const ChVectorDynamic<>& L,  ///< the L vector
                                         const double c               ///< a scaling factor
                                         ) override {
        this->Nx.MultiplyTandAdd(R, L(off_L) * c);
        this->Tu.MultiplyTandAdd(R, L(off_L + 1) * c);
        this->Tv.MultiplyTandAdd(R, L(off_L + 2) * c);
    }

    virtual void ContIntLoadConstraint_C(const unsigned int off_L,  ///< offset in Qc residual
                                         ChVectorDynamic<>& Qc,     ///< result: the Qc residual, Qc += c*C
                                         const double c,            ///< a scaling factor
                                         bool do_clamp,             ///< apply clamping to c*C?
                                         double recovery_clamp      ///< value for min/max clamping of c*C
                                         ) override {
        bool bounced = false;

        // Elastic Restitution model (use simple Newton model with coeffcient e=v(+)/v(-))
        // Note that this works only if the two connected items are two ChBody.

        if (this->objA && this->objB) {
            if (this->restitution) {
                // compute normal rebounce speed
                Vector V1_w = this->objA->GetContactPointSpeed(this->p1);
                Vector V2_w = this->objB->GetContactPointSpeed(this->p2);
                Vector Vrel_w = V2_w - V1_w;
                Vector Vrel_cplane = this->contact_plane.MatrT_x_Vect(Vrel_w);

                double h = this->container->GetSystem()->GetStep();  // = 1.0 / c;  // not all steppers have c = 1/h

                double neg_rebounce_speed = Vrel_cplane.x() * this->restitution;
                if (neg_rebounce_speed < -this->container->GetSystem()->GetMinBounceSpeed())
                    if (this->norm_dist + neg_rebounce_speed * h < 0) {
                        // CASE: BOUNCE
                        bounced = true;
                        Qc(off_L) += neg_rebounce_speed;
                    }
            }
        }

        if (!bounced) {
            // CASE: SETTLE (most often, and also default if two colliding items are not two ChBody)

            if (this->compliance) {
                double h = 1.0 / c;  // was: this->container->GetSystem()->GetStep(); note not all steppers have c = 1/h

                double alpha = this->dampingf;              // [R]=alpha*[K]
                double inv_hpa = 1.0 / (h + alpha);         // 1/(h+a)
                double inv_hhpa = 1.0 / (h * (h + alpha));  // 1/(h*(h+a))

                //***TODO*** move to KRMmatricesLoad() the following, and only for !bounced case
                Nx.Set_cfm_i((inv_hhpa) * this->compliance);
                Tu.Set_cfm_i((inv_hhpa) * this->complianceT);
                Tv.Set_cfm_i((inv_hhpa) * this->complianceT);

                double qc = inv_hpa * this->norm_dist; //***TODO*** see how to move this in KRMmatricesLoad()

                // Note: clamping of Qc in case of compliance is questionable: it does not limit only the outgoing speed, but
                // also the reaction, so it might allow more 'sinking'.
                //if (do_clamp)
                //    qc = ChMax(qc, -recovery_clamp);

                Qc(off_L) += qc;

            } else {
                if (do_clamp)
                    if (this->Nx.GetCohesion())
                        Qc(off_L) += ChMin(0.0, ChMax(c * this->norm_dist, -recovery_clamp));
                    else
                        Qc(off_L) += ChMax(c * this->norm_dist, -recovery_clamp);
                else
                    Qc(off_L) += c * this->norm_dist;
            }
        }
    }

    virtual void ContIntToDescriptor(const unsigned int off_L,    ///< offset in L, Qc
                                     const ChVectorDynamic<>& L,  ///<
                                     const ChVectorDynamic<>& Qc  ///<
                                     ) override {
        // only for solver warm start
        Nx.Set_l_i(L(off_L));
        Tu.Set_l_i(L(off_L + 1));
        Tv.Set_l_i(L(off_L + 2));

        // solver known terms
        Nx.Set_b_i(Qc(off_L));
        Tu.Set_b_i(Qc(off_L + 1));
        Tv.Set_b_i(Qc(off_L + 2));
    }

    virtual void ContIntFromDescriptor(const unsigned int off_L,  ///< offset in L
                                       ChVectorDynamic<>& L       ///<
                                       ) override {
        L(off_L) = Nx.Get_l_i();
        L(off_L + 1) = Tu.Get_l_i();
        L(off_L + 2) = Tv.Get_l_i();
    }

    virtual void InjectConstraints(ChSystemDescriptor& mdescriptor) override {
        mdescriptor.InsertConstraint(&Nx);
        mdescriptor.InsertConstraint(&Tu);
        mdescriptor.InsertConstraint(&Tv);
    }

    virtual void ConstraintsBiReset() override {
        Nx.Set_b_i(0.);
        Tu.Set_b_i(0.);
        Tv.Set_b_i(0.);
    }

    virtual void ConstraintsBiLoad_C(double factor = 1., double recovery_clamp = 0.1, bool do_clamp = false) override {
        bool bounced = false;

        // Elastic Restitution model (use simple Newton model with coeffcient e=v(+)/v(-))
        // Note that this works only if the two connected items are two ChBody.

        if (this->objA && this->objB) {
            if (this->restitution) {
                // compute normal rebounce speed
                Vector V1_w = this->objA->GetContactPointSpeed(this->p1);
                Vector V2_w = this->objB->GetContactPointSpeed(this->p2);
                Vector Vrel_w = V2_w - V1_w;
                Vector Vrel_cplane = this->contact_plane.MatrT_x_Vect(Vrel_w);

                double h = 1.0 / factor;  // inverse timestep is factor

                double neg_rebounce_speed = Vrel_cplane.x() * this->restitution;
                if (neg_rebounce_speed < -this->container->GetSystem()->GetMinBounceSpeed())
                    if (this->norm_dist + neg_rebounce_speed * h < 0) {
                        // CASE: BOUNCE
                        bounced = true;
                        Nx.Set_b_i(Nx.Get_b_i() + neg_rebounce_speed);
                    }
            }
        }

        if (!bounced) {
            // CASE: SETTLE (most often, and also default if two colliding items are not two ChBody)

            if (this->compliance) {
                //  inverse timestep is factor
                double h = 1.0 / factor;

                double alpha = this->dampingf;              // [R]=alpha*[K]
                double inv_hpa = 1.0 / (h + alpha);         // 1/(h+a)
                double inv_hhpa = 1.0 / (h * (h + alpha));  // 1/(h*(h+a))

                Nx.Set_cfm_i((inv_hhpa) * this->compliance);  // was (inv_hh)* ...   //***TEST DAMPING***//
                Tu.Set_cfm_i((inv_hhpa) * this->complianceT);
                Tv.Set_cfm_i((inv_hhpa) * this->complianceT);

                // GetLog()<< "compliance " << (int)this << "  compl=" << this->compliance << "  damping=" <<
                // this->dampingf
                // << "  h=" << h << "\n";

                // no clamping of residual
                Nx.Set_b_i(Nx.Get_b_i() + inv_hpa * this->norm_dist);  // was (inv_h)* ...   //***TEST DAMPING***//
            } else {
                // GetLog()<< "rigid " << (int)this << "  recov_clamp=" << recovery_clamp << "\n";
                if (do_clamp)
                    if (this->Nx.GetCohesion())
                        Nx.Set_b_i(Nx.Get_b_i() + ChMin(0.0, ChMax(factor * this->norm_dist, -recovery_clamp)));
                    else
                        Nx.Set_b_i(Nx.Get_b_i() + ChMax(factor * this->norm_dist, -recovery_clamp));
                else
                    Nx.Set_b_i(Nx.Get_b_i() + factor * this->norm_dist);
            }
        }
    }

    virtual void ConstraintsFetch_react(double factor) override {
        // From constraints to react vector:
        react_force.x() = Nx.Get_l_i() * factor;
        react_force.y() = Tu.Get_l_i() * factor;
        react_force.z() = Tv.Get_l_i() * factor;
    }
};

}  // end namespace chrono

#endif


text:
package org.libx4j.maven.plugin.cert;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;

public class KeyStoreImport {
  public static void main(final String args[]) throws Exception {
    // Meaningful variable names for the arguments
    final String keyStoreFileName = args[0];
    final String certificateChainFileName = args[1];
    final String privateKeyFileName = args[2];
    final String entryAlias = args[3];
    final String keyStorePassword = args[4];
    final String privateKeyEntryPassword = args[5];

    final File keyFile = new File(privateKeyFileName);
    try (
      final FileInputStream certificateStream = new FileInputStream(certificateChainFileName);
      final FileInputStream keyInputStream = new FileInputStream(keyFile);
    ) {
      final byte[] key = new byte[(int)keyFile.length()];
      keyInputStream.read(key);

      final KeyStore keyStore;
      if (keyStoreFileName != null) {
        keyStore = KeyStore.getInstance("jks");
        try (final FileInputStream keyStoreInputStream = new FileInputStream(keyStoreFileName)) {
          keyStore.load(keyStoreInputStream, keyStorePassword.toCharArray());
        }

        makeKeystore(keyStore, certificateStream, key, entryAlias, privateKeyEntryPassword);

        try (final FileOutputStream keyStoreOutputStream = new FileOutputStream(keyStoreFileName)) {
          keyStore.store(keyStoreOutputStream, keyStorePassword.toCharArray());
        }
      }
      else {
        keyStore = makeKeystore(null, certificateStream, key, entryAlias, privateKeyEntryPassword);
      }
    }
  }

  public static KeyStore makeKeystore(final KeyStore defaultKeystore, final InputStream certificateChainInputStream, final byte[] key, final String entryAlias, final String privateKeyEntryPassword) throws Exception {
    final KeyStore keyStore = defaultKeystore != null ? defaultKeystore : KeyStore.getInstance("jks");

    // Load the certificate chain (in X.509 DER encoding).
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    // Required because Java is STUPID. You can't just cast the result
    // of toArray to Certificate[].
    Certificate[] chain = {};
    chain = certificateFactory.generateCertificates(certificateChainInputStream).toArray(chain);

    // Load the private key (in PKCS#8 DER encoding).
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    final PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(key));

    // Add the new entry
    keyStore.setEntry(entryAlias, new KeyStore.PrivateKeyEntry(privateKey, chain), new KeyStore.PasswordProtection(privateKeyEntryPassword.toCharArray()));
    return keyStore;
  }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Twits" do
  it "fails" do
    fail "hey buddy, you should probably rename this file and start specing for real"
  end
end

=begin
link to the oneclick DevKit instructions:

https://github.com/oneclick/rubyinstaller/wiki/Development-Kit

C:\cygwin\usr\local\bin\Ruby192\bin\ruby.exe -e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift) C:\cygwin\usr\local\bin\Ruby192\bin/bundle install
Fetching source index for http://rubygems.org/
Using rake (0.9.2)
Using bundler (1.0.15)
Using diff-lcs (1.1.2)
Using git (1.2.5)
Using jeweler (1.5.2)
Installing rcov (0.9.9) C:/cygwin/usr/local/bin/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/defaults/operating_system.rb:9:in `block in <top (required)>': The 'rcov' native gem requires installed build tools. (Gem::InstallError)

Please update your PATH to include build tools or download the DevKit
from 'http://rubyinstaller.org/downloads' and follow the instructions
at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/installer.rb:141:in `call'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/installer.rb:141:in `block in install'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/installer.rb:140:in `each'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/installer.rb:140:in `install'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/source.rb:101:in `block in install'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/rubygems_integration.rb:78:in `preserve_paths'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/source.rb:91:in `install'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/installer.rb:58:in `block (2 levels) in run'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/rubygems_integration.rb:93:in `with_build_args'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/installer.rb:57:in `block in run'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/spec_set.rb:12:in `block in each'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/spec_set.rb:12:in `each'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/spec_set.rb:12:in `each'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/installer.rb:49:in `run'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/installer.rb:8:in `install'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/cli.rb:222:in `install'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/vendor/thor/task.rb:22:in `run'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/vendor/thor.rb:246:in `dispatch'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/lib/bundler/vendor/thor/base.rb:389:in `start'
	from C:/cygwin/usr/local/bin/Ruby192/lib/ruby/gems/1.9.1/gems/bundler-1.0.15/bin/bundle:13:in `<top (required)>'
	from C:/cygwin/usr/local/bin/Ruby192/bin/bundle:19:in `load'
	from C:/cygwin/usr/local/bin/Ruby192/bin/bundle:19:in `<top (required)>'
	from -e:1:in `load'
	from -e:1:in `<main>'

Process finished with exit code 1
=end


text:
""" This test will repeatedly launch and switch apps, which serve
as a stress test for the life cycle methods of the main activity of
the app being tested.
"""

import os, sys, inspect

def module_path():
    ''' returns the module path without the use of __file__.
    from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'''
    return os.path.abspath(os.path.dirname(inspect.getsourcefile(module_path)))

sys.path.append(module_path())
sys.path.append(os.path.join(module_path(), '..', 'src'))

import DeviceManager
from Agents import LogcatAgent
import time

def main():
    """ This test launches a series of apps (with given package and main activity names)
    and repeats this for a given number of times. After that, the scripts dumps the error
    messages printed to logcat during the test.
    """
    # constants
    APP_CLOCK = 'com.android.deskclock/com.android.deskclock.DeskClock'
    APP_SETTINGS = 'com.android.settings/com.android.settings.Settings'
    # configurations
    packages = [APP_SETTINGS, APP_CLOCK]
    sleep_interval = 2
    repeats = 2
    app_tag = 'ActivityManager'
    device = DeviceManager.getDevice()
    agent = LogcatAgent(device)
    agent.clear()
    print 'Start launching stress test'
    for _ in range(repeats):
        for p in packages:
            device.startActivity(component=p)
            time.sleep(sleep_interval)
    err = agent.dump(fmt=None, filterTuples=[(app_tag, 'E'), ('*', 'S')])
    print 'Finishing test, dumping error messages:'
    print err

main()


text:
from .voteutils import VoteUtils

def setup(bot):
    bot.add_cog(VoteUtils(bot))


text: Libri Diario Conta


text:
package edu.uci.ics.hyracks.algebricks.core.algebra.properties;

import java.util.Collection;

import edu.uci.ics.hyracks.algebricks.core.algebra.base.LogicalVariable;

public interface IStructuralProperty {
    public void getColumns(Collection<LogicalVariable> columns);
}


text:
layout: post
title: 363 - Max Sum Of Rectangle No Larger Than K
date: 2020-02-05
tags:
- Leetcode
categories:
- Matrix
author: Jason
---
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.

```python
from bisect import bisect_left, insort
class Solution:
    def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
        for row in matrix:
            for i in range(1, len(row)):
                row[i] += row[i - 1]

        ret = -float("inf")
        for j in range(len(matrix[0])):
            for l in range(j, len(matrix[0])):
                sums, curr = [0], 0
                for i in range(len(matrix)):
                    curr += matrix[i][l] - (matrix[i][j - 1] if j > 0 else 0)
                    i = bisect_left(sums, curr - k)
                    if i < len(sums):
                        ret = max(ret, curr - sums[i])
                    insort(sums, curr)
        return ret
```


text:
.. _ref_migration_backlink:

================
Adding backlinks
================

This example shows how to handle a schema that makes use of a
backlink. We'll use a linked-list structure to represent a sequence of
events.

We'll start with this schema:

.. code-block:: sdl

    type Event {
      required property name -> str;
      link prev -> Event;

      # ... more properties and links
    }

We specify a ``prev`` link because that will make adding a new
``Event`` at the end of the chain easier, since we'll be able to
specify the payload and the chain the ``Event`` should be appended to
in a single :eql:stmt:`insert`. Once we've updated the schema
file we proceed with our first migration:

.. code-block:: bash

    $ edgedb migration create
    did you create object type 'default::Event'? [y,n,l,c,b,s,q,?]
    > y
    Created ./dbschema/migrations/00001.edgeql, id:
    m1v3ahcx5f43y6mlsdmlz2agnf6msbc7rt3zstiqmezaqx4ev2qovq
    $ edgedb migrate
    Applied m1v3ahcx5f43y6mlsdmlz2agnf6msbc7rt3zstiqmezaqx4ev2qovq
    (00001.edgeql)

We now have a way of chaining events together. We might create a few
events like these:

.. code-block:: edgeql-repl

    db> select Event {
    ...     name,
    ...     prev: { name },
    ... };
    {
      default::Event {name: 'setup', prev: {}},
      default::Event {name: 'work', prev: default::Event {name: 'setup'}},
      default::Event {name: 'cleanup', prev: default::Event {name: 'work'}},
    }

It seems like having a ``next`` link would be useful, too. So we can
define it as a computed link by using :ref:`backlink
<ref_datamodel_links>` notation:

.. code-block:: sdl

    type Event {
      required property name -> str;

      link prev -> Event;
      link next := .<prev[is Event];
    }

The migration is straightforward enough:

.. code-block:: bash

    $ edgedb migration create
    did you create link 'next' of object type 'default::Event'?
    [y,n,l,c,b,s,q,?]
    > y
    Created ./dbschema/migrations/00002.edgeql, id:
    m1qpukyvw2m4lmomoseni7vdmevk4wzgsbviojacyrqgiyqjp5sdsa
    $ edgedb migrate
    Applied m1qpukyvw2m4lmomoseni7vdmevk4wzgsbviojacyrqgiyqjp5sdsa
    (00002.edgeql)

Trying out the new link on our existing data gives us:

.. code-block:: edgeql-repl

    db> select Event {
    ...     name,
    ...     prev_name := .prev.name,
    ...     next_name := .next.name,
    ... };
    {
      default::Event {
        name: 'setup',
        prev_name: {},
        next_name: {'work'},
      },
      default::Event {
        name: 'work',
        prev_name: 'setup',
        next_name: {'cleanup'},
      },
      default::Event {
        name: 'cleanup',
        prev_name: 'work',
        next_name: {},
      },
    }

That's not quite right. The value of ``next_name`` appears to be a set
rather than a singleton. This is because the link ``prev`` is
many-to-one and so ``next`` is one-to-many, making it a *multi* link.
Let's fix that by making the link ``prev`` a one-to-one, after all
we're interested in building event chains, not trees.

.. code-block:: sdl

    type Event {
      required property name -> str;

      link prev -> Event {
        constraint exclusive;
      };
      link next := .<prev[is Event];
    }

Since the ``next`` link is computed, the migration should not need any
additional user input even though we're reducing the link's
cardinality:

.. code-block:: bash

    $ edgedb migration create
    did you create constraint 'std::exclusive' of link 'prev'?
    [y,n,l,c,b,s,q,?]
    > y
    Created ./dbschema/migrations/00003.edgeql, id:
    m17or2bfywuckdqeornjmjh7c2voxgatspcewyefcd4p2vbdepimoa
    $ edgedb migrate
    Applied m17or2bfywuckdqeornjmjh7c2voxgatspcewyefcd4p2vbdepimoa
    (00003.edgeql)

The new ``next`` computed link is now inferred as a ``single`` link
and so the query results for ``next_name`` and ``prev_name`` are
symmetrical:

.. code-block:: edgeql-repl

    db> select Event {
    ...     name,
    ...     prev_name := .prev.name,
    ...     next_name := .next.name,
    ... };
    {
      default::Event {name: 'setup', prev_name: {}, next_name: 'work'},
      default::Event {name: 'work', prev_name: 'setup', next_name: 'cleanup'},
      default::Event {name: 'cleanup', prev_name: 'work', next_name: {}},
    }


text:
<!DOCTYPE html>

    <title>Home</title>
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Nunito:700,900|Open+Sans:300,400,600,600i,700">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="assets/css/style.css">

Home

About Us

Services

Blog

Classic blog

Grid blog

Blog Line

Masonry Blog

Blog post

Pages

Gallery

Grid gallery

Masonry gallery

Cobbles gallery

Gallery item

Pages

Make an Appointment

Clients

Clients testimonials

Our team

Team member profile

Careers

Pricing

FAQ

Extras

Extras

404 Page

503 Page

Maintenance

Coming soon

Login

Register

Search results

Terms of use

Components

Accordion

Buttons

Grid

Forms

Icons

Icon lists

Progress bars

Tabs

Table styles

Typography

Contacts

Privacy/ Sitemap

©  Thrive Refugee Enterprise Ltd - ABN 50 612 682 381

            <button title="Close (Esc)" class="pswp__button pswp__button--close"></button>
            <button title="Share" class="pswp__button pswp__button--share"></button>
            <button title="Toggle fullscreen" class="pswp__button pswp__button--fs"></button>
            <button title="Zoom in/out" class="pswp__button pswp__button--zoom"></button>

          <button title="Previous (arrow left)" class="pswp__button pswp__button--arrow--left"></button>
          <button title="Next (arrow right)" class="pswp__button pswp__button--arrow--right"></button>


text:
require 'spec_helper'

describe 'nodejs', :type => :class do

  describe 'input validation' do
    let :facts  do { :operatingsystem => 'Debian' } end
    let :params do {} end
    it 'when deploying on an unsupported os' do
      facts.merge!({:operatingsystem => 'SparklePony'})
      params.merge!({:dev_package => true, :manage_repo => true })
       expect { subject }.to raise_error(Puppet::Error, /Class nodejs does not support SparklePony/)
    end
    ['dev_package','manage_repo'].each do |boolz|
      it "should fail when #{boolz} is not a boolean" do
        facts.merge!({:osfamily => 'Debian'})
        params.merge!({boolz => 'BOGON'})
        expect { subject }.to raise_error(Puppet::Error, /"BOGON" is not a boolean.  It looks to be a String/)
      end
    end
  end
  describe 'when deploying on debian' do
    let :facts do
      {
        :osfamily => 'Debian',
        :operatingsystem => 'Debian',
        :lsbdistcodename => 'wheezy',
        :lsbdistid => 'Debian',
      }
    end
    let :params do
      { :dev_package => true, :manage_repo => true }
    end
    context 'when manage_repo is true' do
      it { should contain_class('apt') }
      it 'should contain the apt source' do
        should contain_apt__source('sid').with({
          'location' => 'http://ftp.us.debian.org/debian/',
        })
      end
    end
    context 'when manage_repo is false' do
      it 'should not contain the apt source' do
        params.merge!({:manage_repo => false})
        should_not contain_apt__source('sid')
      end
    end
    it { should contain_package('nodejs').with({
      'name'    => 'nodejs',
      'require' => 'Anchor[nodejs::repo]',
      'ensure'  => 'present',
    }) }
    it { should contain_package('npm').with({
      'name'    => 'npm',
      'require' => 'Anchor[nodejs::repo]',
    }) }
    it { should_not contain_package('nodejs-stable-release') }
  end

  describe 'when deploying on ubuntu' do
    let :facts do
      {
        :operatingsystem => 'Ubuntu',
        :osfamily        => 'Debian',
        :lsbdistcodename => 'trusty',
        :lsbdistid       => 'Ubuntu',
      }
    end

    let :params do
      { :dev_package => true, :manage_repo => true }
    end
    context 'when manage_repo is true' do
      it { should contain_class('apt') }
      it { should contain_apt__source('nodesource') }
    end
    context 'when manage_repo is false' do
      it 'should not create the ppa' do
        params.merge!({:manage_repo => false})
        should_not contain_class('apt')
        should_not contain_apt__source('nodesource')
      end
    end

    it { should contain_class('apt') }
    it { should contain_apt__source('nodesource') }
    it { should contain_apt__source('nodesource-devel') }
    it { should contain_package('nodejs') }
    it { should contain_package('nodejs').with({
      'name'    => 'nodejs',
      'require' => 'Anchor[nodejs::repo]',
    }) }
    it { should contain_package('nodejs-dev') }
    it { should_not contain_package('npm') }
    it { should_not contain_package('nodejs-stable-release') }
  end

  { 'Redhat' => 'el$releasever',
    'Scientific' => 'el$releasever',
    'CentOS' => 'el$releasever'
  }.each do |os, repo|
    { '5' => 'nodejs-compat-symlinks',
      '6' => 'nodejs'
    }.each do |major, package|
      describe "when deploying on (#{os}) #{major}" do
        let :facts do
          { :operatingsystem => os,
            :operatingsystemrelease => "#{major}.4",
            :lsbmajdisrelease => major
          }
        end

        let :params do
          { :manage_repo => true}
        end

        context 'when manage_repo is true' do
          it 'should remove the node-js-stable-release package' do
            should contain_package('nodejs-stable-release').with({
              'ensure' => 'absent',
            })
          end
          it 'should add the nodejs-stable yumrepo' do
            should contain_yumrepo('nodejs-stable').with({
              'baseurl'  => "http://patches.fedorapeople.org/oldnode/stable/#{repo}/$basearch/",
              'before'   => 'Anchor[nodejs::repo]',
            })
          end
          it 'should add the yumrepo file resource' do
            should contain_file('nodejs_repofile')
          end
        end
        context 'when manage_repo is false' do
          let (:params) {{:manage_repo => false}}
          it 'should not remove the nodejs-stable-release package if present' do
            should_not contain_package('nodejs-stable-release')
          end
          it 'should not contain the yumrepo' do
            should_not contain_yumrepo('nodejs-stable')
          end
          it 'should not contain the yumrepo file' do
            should_not contain_file('nodejs_repofile')
          end
        end

        context 'when dev_package is true' do
          let (:params) {{:dev_package => true}}
          it { should contain_package('nodejs-dev') }
        end

        context 'when node_pkg is set' do
          let (:params) {{:node_pkg => 'nodejs010'}}
          it { should contain_package('nodejs').with({
            'name' => 'nodejs010',
            'require' => 'Anchor[nodejs::repo]',
          }) }
        end

        context 'when node_pkg and npm_pkg are set' do
          let (:params) {{:node_pkg => 'nodejs010',:npm_pkg => 'nodejs010-npm'}}
          it { should contain_package('nodejs').with({
            'name' => 'nodejs010',
            'require' => 'Anchor[nodejs::repo]',
          }) }
          it { should contain_package('npm').with({
            'name' => 'nodejs010-npm',
            'require' => 'Anchor[nodejs::repo]',
          }) }
        end

        it { should contain_package('nodejs').with({
          'name'    => package,
          'require' => 'Anchor[nodejs::repo]',
        }) }
        it { should contain_package('npm').with({
          'name'    => 'npm',
          'require' => 'Anchor[nodejs::repo]',
        }) }
        it { should_not contain_package('nodejs-dev') }
      end
    end
  end
  { 'Fedora' => 'f$releasever',
    'Amazon' => 'amzn1'
  }.each do |os, repo|
    describe "when deploying on (#{os})" do
      let :facts do
        { :operatingsystem => os,
        }
      end
      let :params do
        { :manage_repo => true }
      end
      context 'when manage_repo is true' do
        it 'should remove the node-js-stable-release package' do
          should contain_package('nodejs-stable-release').with({
            'ensure' => 'absent',
          })
        end
        it 'should add the nodejs-stable yumrepo' do
          should contain_yumrepo('nodejs-stable').with({
            'baseurl'  => "http://patches.fedorapeople.org/oldnode/stable/#{repo}/$basearch/",
            'before'   => 'Anchor[nodejs::repo]',
          })
        end
        it 'should contain the yumrepo file' do
          should contain_file('nodejs_repofile')
        end
      end

      context 'when manage_repo is false' do
        let (:params) {{:manage_repo => false}}
        it 'should not remove the nodejs-stable-release package if present' do
          should_not contain_package('nodejs-stable-release')
        end
        it 'should not contain the yumrepo' do
          should_not contain_yumrepo('nodejs-stable')
        end
        it 'should not contain the yumrepo file' do
          should_not contain_file('nodejs_repofile')
        end
      end

      context 'when dev_package is true' do
        let (:params) {{:dev_package => true}}
        it { should contain_package('nodejs-dev') }
      end
      it { should contain_package('nodejs').with({
        'require' => 'Anchor[nodejs::repo]',
      }) }
      it { should contain_package('npm').with({
        'name'    => 'npm',
        'require' => 'Anchor[nodejs::repo]',
      }) }
      it { should_not contain_package('nodejs-dev') }
    end
  end

  describe 'when deploying with proxy on CentOS' do
    let :facts do
      {
        :operatingsystem => 'CentOS',
        :lsbdistcodename => 'Final',
        :lsbdistid       => 'CentOS',
      }
    end

    let :params do
      { :proxy => 'http://proxy.puppetlabs.lan:80/' }
    end

    it { should contain_exec('npm_proxy').with({
      'command' => 'npm config set proxy http://proxy.puppetlabs.lan:80/',
      'require' => 'Package[npm]',
    }) }
    it { should_not contain_package('nodejs-stable-release') }
  end

  describe 'when deploying with proxy on Ubuntu' do
    let :facts do
      {
        :operatingsystem => 'Ubuntu',
        :lsbdistcodename => 'edgy',
        :lsbdistid       => 'Ubuntu',
      }
    end

    let :params do
      { :proxy => 'http://proxy.puppetlabs.lan:80/' }
    end

    it { should_not contain_package('npm') }
    it { should contain_exec('npm_proxy').with({
      'command' => 'npm config set proxy http://proxy.puppetlabs.lan:80/',
      'require' => 'Package[nodejs]',
    }) }
    it { should_not contain_package('nodejs-stable-release') }
  end

  describe 'when deploying with version' do
    let :facts do
      {
        :operatingsystem => 'Ubuntu',
        :lsbdistcodename => 'edgy',
        :lsbdistid       => 'Ubuntu',
      }
    end

    let :params do
      { :version => '0.8.16-1chl1~precise1' }
    end

    it { should contain_package('nodejs').with({
      'name'    => 'nodejs',
      'ensure' => '0.8.16-1chl1~precise1',
    }) }

  end

  describe 'when deploying on gentoo' do
    let :facts do
      {
        :operatingsystem => 'Gentoo',
      }
    end

    it { should contain_package_use('net-libs/nodejs').with({
      'ensure'  => 'present',
      'use'     => 'npm',
      'require' => 'Anchor[nodejs::repo]',
    }) }
    it { should contain_package('nodejs').with({
      'ensure'  => 'present',
      'name'    => 'net-libs/nodejs',
      'require' => 'Anchor[nodejs::repo]',
    }) }
  end

  describe 'when deploying on Archlinux' do
    let :facts do
      {
        :operatingsystem => 'Archlinux',
      }
    end

    it { should contain_package('nodejs') }
    it { should_not contain_package('npm') }
  end
end


text:
//___________________________________________________________________________________
//
//  Copyright (C) 2018, Mariusz Postol LODZ POLAND.
//
//  To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI
//___________________________________________________________________________________

using System;
using System.Runtime.Serialization;
using System.Xml;

namespace UAOOI.Configuration.Networking.Serialization
{
  /// <summary>
  /// Class UATypeInfo - stores information about an OPC UA Type.
  /// </summary>
  [DataContractAttribute(Name = "UATypeInfo", Namespace = CommonDefinitions.Namespace)]
  [SerializableAttribute()]
  public class UATypeInfo
  {

    #region constructor
    /// <summary>
    /// Initializes a new instance of the <see cref="UATypeInfo"/> class representing an unknown type.
    /// </summary>
    [Obsolete("Shall be used only by the serializer")]
    public UATypeInfo()
    {
      m_builtInType = BuiltInType.Null;
      m_valueRank = ValueRanks.Any;
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="UATypeInfo"/> class representing <see cref="BuiltInType"/> and value rank.
    /// </summary>
    /// <param name="builtInType">Type of the an OPC UA entity.</param>
    public UATypeInfo(BuiltInType builtInType) : this(builtInType, ValueRanks.Scalar) { }
    /// <summary>
    /// Initializes a new instance of the <see cref="UATypeInfo"/> class representing <see cref="BuiltInType"/> and value rank.
    /// </summary>
    /// <param name="builtInType">Type of the an OPC UA entity.</param>
    /// <param name="valueRank">The value rank.</param>
    public UATypeInfo(BuiltInType builtInType, int valueRank) : this(builtInType, valueRank, null) { }
    /// <summary>
    /// Initializes a new instance of the <see cref="UATypeInfo"/> class.
    /// </summary>
    /// <param name="builtInType">Type of the built in.</param>
    /// <param name="valueRank">The value rank.</param>
    /// <param name="arrayDimensions">The array dimensions.</param>
    /// <exception cref="System.ArgumentOutOfRangeException">$for {nameof(valueRank)} == {valueRank} {nameof(ArrayDimensions)} must be provided.</exception>
    public UATypeInfo(BuiltInType builtInType, int valueRank, int[] arrayDimensions)
    {
      if ((valueRank == 0 || valueRank > 1) && (arrayDimensions == null || arrayDimensions.Length == 0))
        throw new ArgumentOutOfRangeException(nameof(valueRank), $"for {nameof(valueRank)} == {valueRank} {nameof(ArrayDimensions)} must be provided.");
      m_builtInType = builtInType;
      m_valueRank = valueRank;
      m_ArrayDimensionsField = (arrayDimensions == null || arrayDimensions.Length == 0) ? null : (int[])arrayDimensions.Clone();
    }
    #endregion

    #region properties
    /// <summary>
    /// The built-in type.
    /// </summary>
    /// <value>The type of any value represented by this instance.</value>
    [DataMemberAttribute(EmitDefaultValue = true, IsRequired = true)]
    public BuiltInType BuiltInType
    {
      get { return m_builtInType; }
      set { m_builtInType = value; }
    }
    /// <summary>
    /// Gets or sets the array range. Indicates whether the dataType is an array and how many dimensions the array has.
    /// It may have the following values:
    /// n > 1: the dataType is an array with the specified number of dimensions.
    /// OneDimension(1): The dataType is an array with one dimension.
    /// OneOrMoreDimensions (0): The dataType is an array with one or more dimensions.
    /// Scalar (−1): The dataType is not an array.
    /// Any (−2): The dataType can be a scalar or an array with any number of dimensions.
    /// ScalarOrOneDimension(−3): The dataType can be a scalar or a one dimensional array.
    /// </summary>
    /// <remarks>
    /// <note>
    /// NOTE All DataTypes are considered to be scalar, even if they have array-like semantics like ByteString and String.
    /// </note>
    /// </remarks>
    /// <value>The array dimensions.</value>
    [DataMemberAttribute(IsRequired = true)]
    public int ValueRank
    {
      get { return m_valueRank; }
      set { m_valueRank = value; }
    }
    /// <summary>
    /// Gets or sets the array dimensions - Specifies the length of each dimension for an array dataType.
    /// It is intended to describe the capability of the dataType, not the current size.
    /// The number of elements shall be equal to the value of the valueRank.Shall be null if valueRank ≤ 0.
    /// A value of 0 for an individual dimension indicates that the dimension has a variable length.
    /// </summary>
    /// <value>The array dimensions.</value>
    [DataMemberAttribute(EmitDefaultValue = false)]
    public int[] ArrayDimensions
    {
      get { return m_ArrayDimensionsField; }
      set { m_ArrayDimensionsField = value; }
    }
    /// <summary>
    /// Gets or sets the name of the type.
    /// </summary>
    /// <value>The instance of <see cref="XmlQualifiedName"/> representing globally unique name of the type.</value>
    [DataMemberAttribute(EmitDefaultValue = true, IsRequired = false)]
    public XmlQualifiedName TypeName
    {
      get { return TypeNameField; }
      set { TypeNameField = value; }
    }
    #endregion

    #region private
    private BuiltInType m_builtInType;
    private int m_valueRank;
    private int[] m_ArrayDimensionsField;
    private System.Xml.XmlQualifiedName TypeNameField;
    #endregion

  }
}


text:
<!DOCTYPE HTML>
<?php
if (!isset($pageTitle))
	$pageTitle = "Flares that Care";
?>

		<title><?php echo $pageTitle; ?></title>
		<meta charset="UTF-8" />

		<meta property="og:title" content="<?php echo $pageTitle; ?>" />
		<meta property="og:url" content="http://<?php echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />
		<meta property="og:site_name" content="Flares that Care" />
		<meta property="og:description" content="
			Flares that Care is a quarterly charity livestream event supporting Child's Play Charity.
			Our second event is set to take place from Friday, March 13th at 12 PM PST until Sunday, March 15th at 12 AM PST.
		" />
		<meta property="og:image" content="http://<?php echo $_SERVER['HTTP_HOST']; ?>/img/flare.png" />
		<meta property="og:type" content="website" />
		<meta property="og:locale" content="en_US" />

		<link rel="stylesheet" type="text/css" href="/styles.css">
		<link rel="icon" type="image/icon" href="/favicon.ico">
		<link rel="stylesheet"	type="text/css" href="http://fonts.googleapis.com/css?family=Source+Sans+Pro%7CMontserrat">

					%COUNTDOWN%

					<?php
					if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") <= -1) {
						if ($_COOKIE['sparks'] == "off")
							echo "Want flames again? Click here!";
						else
							echo "Flames too slow? Turn 'em off!";
					}
					?>


text:
import { h, Component } from 'preact';
import PropTypes from 'prop-types';

import { applyTheme } from '../ThemeProvider/';

import './style.css';

/**
 * Header
 *
 */
class Header extends Component {
  propTypes = {
    toggleChat: PropTypes.func,
    style: PropTypes.string,
    theme: PropTypes.shape({
      primary_colour: PropTypes.string.isRequired,
    }),
    chatOpen: PropTypes.boolean,
  };

  renderToggleChatButton = () => (this.props.chatOpen ? × : ...);

  render () {
    const { toggleChat, style, theme } = this.props;

    return (
      <header
        style={{ backgroundColor: theme.primary_colour }}
        role="button"
        tabIndex={0}
        className={`Header--${style}`}
        onClick={() => toggleChat(true)}
        onKeyPress={event => {
          // Ensure event is not null
          const e = event || window.event;

          if ((e.which === 72 || e.keyCode === 72) && e.ctrlKey) {
            toggleChat(true);
          }
        }}
      >
        <span className={`Header__title--${style}`}>Chat with John
        <button className={`Header__closeBtn--${style}`} onClick={() => toggleChat(true)}>
          {this.renderToggleChatButton()}
        </button>

    );
  }
}

export default applyTheme(Header);


text:
package script.promotion;

import java.text.MessageFormat;
import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xinqihd.sns.gameserver.db.mongo.MailMessageManager;
import com.xinqihd.sns.gameserver.entity.user.User;
import com.xinqihd.sns.gameserver.reward.Reward;
import com.xinqihd.sns.gameserver.reward.RewardManager;
import com.xinqihd.sns.gameserver.script.ScriptManager;
import com.xinqihd.sns.gameserver.script.ScriptResult;
import com.xinqihd.sns.gameserver.util.DateUtil;
import com.xinqihd.sns.gameserver.util.MessageFormatter;

/**
 * 开展充值赠送活动
		【活动时间】 2012.10.16 至 2012.11.23

		【活动奖励】

		一次性充值5000元宝 返赠1000元宝
		一次性充值2000元宝 返赠500元宝
		一次性充值1000元宝 返赠200元宝

 *
 * @author wangqi
 *
 */
public class ChargePromotion {

	private static final Logger logger = LoggerFactory.getLogger(ChargePromotion.class);
	//开始日期
	private static final Calendar startCal = Calendar.getInstance();
	//结束日期
	private static final Calendar endCal = Calendar.getInstance();

	private static final String subject = "新年充值大酬宾";
	private static final String content =
			"为了回馈广大玩家,我们开启新年充值大返利活动,活动时间从{}到{},详情如下:\n" +
			"一次性充值满10000元宝,返赠10000元宝; \n" +
			"一次性充值满8000元宝,返赠6000元宝; \n" +
			"一次性充值满5000元宝,返赠2500元宝;\n" +
			"一次性充值满3000元宝,返赠1000元宝;\n" +
			"一次性充值满1000元宝,返赠200元宝。\n" +
			"您本次充值了{}元宝,将获得额外赠送的{}元宝,祝您游戏愉快";

	static {
		startCal.set(Calendar.YEAR, 2013);
		/**
		 * 新年酬宾
		 * 2013-2-9 到 2013-2-15日
		 */
		startCal.set(Calendar.MONTH, 1);
		startCal.set(Calendar.DAY_OF_MONTH, 9);
		startCal.set(Calendar.HOUR_OF_DAY, 0);
		startCal.set(Calendar.MINUTE, 0);
		startCal.set(Calendar.SECOND, 0);

		endCal.set(Calendar.YEAR, 2013);
		endCal.set(Calendar.MONTH, 1);
		endCal.set(Calendar.DAY_OF_MONTH, 15);
		endCal.set(Calendar.HOUR_OF_DAY, 23);
		endCal.set(Calendar.MINUTE, 59);
		endCal.set(Calendar.SECOND, 59);

	}

	public static ScriptResult func(Object[] parameters) {
		ScriptResult result = ScriptManager.checkParameters(parameters, 2);
		if ( result != null ) {
			return result;
		}
		User user = (User)parameters[0];
		Integer chargedYuanbao = (Integer)parameters[1];
		boolean available = false;
		long currentTimeMillis = System.currentTimeMillis();
		if ( currentTimeMillis >= startCal.getTimeInMillis() &&
				currentTimeMillis <= endCal.getTimeInMillis() ) {
			//logger.debug("The charge promotion is in date:{} to {}", startCal.getTime(), endCal.getTime());
			available = true;
		}
		if ( available ) {
			String startDateStr = DateUtil.formatDateTime(startCal.getTime());
			String endDateStr = DateUtil.formatDateTime(endCal.getTime());
			if ( chargedYuanbao.intValue() >= 10000 ) {
				sendMail(user, chargedYuanbao, 10000, startDateStr, endDateStr);
			} else if ( chargedYuanbao.intValue() >= 8000 ) {
				sendMail(user, chargedYuanbao, 6000, startDateStr, endDateStr);
			} else if ( chargedYuanbao.intValue() >= 5000 ) {
				sendMail(user, chargedYuanbao, 2500, startDateStr, endDateStr);
			} else if ( chargedYuanbao >= 3000 ) {
				sendMail(user, chargedYuanbao, 1000, startDateStr, endDateStr);
			} else if ( chargedYuanbao >= 1000 ) {
				sendMail(user, chargedYuanbao, 200, startDateStr, endDateStr);
			}
		}
		result = new ScriptResult();
		result.setType(ScriptResult.Type.SUCCESS);
		result.setResult(null);
		return result;
	}

	private static void sendMail(User user, Integer chargedYuanbao, int yuanbao,
			String startDateStr, String endDateStr) {
		Reward reward = RewardManager.getInstance().getRewardYuanbao(yuanbao);
		String message = MessageFormatter.arrayFormat(content,
				new Object[]{startDateStr, endDateStr, chargedYuanbao, yuanbao}).getMessage();
		MailMessageManager.getInstance().sendAdminMail(user.get_id(), subject, message, reward);
	}
}


text:
package com.samsistemas.todoapp;

import android.os.Bundle;

import com.facebook.react.ReactActivity;

public final class MainActivity extends ReactActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
    }

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "todoApp";
    }
}


text:
package ru.job4j.pseudo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

public class PaintTest {
    //Получаем ссылку на стандартный вывод в консоль.
    private final PrintStream stdout = System.out;
    //Создаем буфeр для хранения вывода.
    private final ByteArrayOutputStream out = new ByteArrayOutputStream();

    //Заменяем стандартный вывод на вывод в пямять для тестирования.
    @Before
    public void loadOutput() {
        System.setOut(new PrintStream(this.out));
    }

    //Возвращаем обратно стандартный вывод в консоль.
    @After
    public void backOutput() {
        System.setOut(this.stdout);
    }

    @Test
    public void whenUserDrawSquare() {
        new Paint().draw(new Square());
        assertThat(
                new String(out.toByteArray()),
                is(
                        new StringBuilder()
                                .append("****\n")
                                .append("****\n")
                                .append("****\n")
                                .append("****\n")
                                .append(System.lineSeparator())
                                .toString())
        );
    }

    @Test
    public void whenUserDrawTriangle() {
        new Paint().draw(new Triangle());
        assertThat(
                new String(out.toByteArray()),
                is(
                        new StringBuilder()
                                .append("   *\n")
                                .append("  ***  \n")
                                .append(" ***** \n")
                                .append("******* \n")
                                .append(System.lineSeparator())
                                .toString())
        );
    }
}


text:
package org.osc.core.broker.service.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.osc.core.broker.model.entities.virtualization.openstack.HostAggregate;
import org.osc.core.broker.service.dto.openstack.HostAggregateDto;

public class HostAggregateEntityMgr {

    public static void fromEntity(HostAggregate entity, HostAggregateDto dto) {
        dto.setId(entity.getId());
        dto.setOpenstackId(entity.getOpenstackId());
    }

    public static void toEntity(HostAggregate entity, HostAggregateDto dto) {
        entity.setName(dto.getName());
    }

    public static List<HostAggregate> listByOpenstackId(EntityManager em, String openstackId) {
        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<HostAggregate> query = cb.createQuery(HostAggregate.class);

        Root<HostAggregate> root = query.from(HostAggregate.class);

        query = query.select(root).distinct(true)
            .where(cb.equal(root.get("openstackId"), openstackId));

        return em.createQuery(query).getResultList();
    }
}


text:
#if UNITY_IOS
using System;
using GetSocialSdk.Core;

namespace GetSocialSdk.Ui
{
    internal delegate void ActionListenerDelegate(IntPtr actionListenerPtr, string serializedAction);

    public static class ActionListenerCallback
    {
        [AOT.MonoPInvokeCallback(typeof(ActionListenerDelegate))]
        public static void OnAction(IntPtr actionListenerPtr, string serializedAction)
        {
            GetSocialDebugLogger.D(string.Format("OnActionReceived: {0}", serializedAction));

            if (actionListenerPtr != IntPtr.Zero)
            {
                var action = GetSocialJsonBridge.FromJson<GetSocialAction>(serializedAction);
                actionListenerPtr.Cast<ActionListener>().Invoke(action);
            }
        }
    }
}

#endif


text:
'use strict'

var request = require('request')

module.exports = (app, text) => {

  const dataSeparator = '|'
  const defaultCharacterColor = '#006666'

  let slapp = app.slapp
  let helpText = text
  let kv = app.dataStore

  // Slash Command: ...
  slapp.command('/char_add', (msg) => {

    var userID = msg.body.user_id
    console.info(`user: ${userID}`)
    /** [TO DO] restrict access to this command to the channel owner and those authorized
     *
     * will need to setup ROLES and store that data in the persist storage
     */

    var characterData = msg.body.text.split(dataSeparator)
    var characterName = ''
    var characterThumb = ''
    var characterColor = defaultCharacterColor
    var characterSheetUrl = ''

    if (characterData) {
      if (characterData[0] != '' && characterData.length > 0) { characterName = characterData[0]}
      if (characterData[1] != '' && characterData.length > 1) { characterThumb = characterData[1]}
      if (characterData[2] != '' && characterData.length > 2) { characterColor = characterData[2]}
      if (characterData[3] != '' && characterData.length > 3) { characterSheetUrl = characterData[3]}
    } else {
      // [TO DO] handle error
    }

    // [DEBUG]
    console.info(`character data: ${characterData}`)

    if (characterName != '') {
      kv.set(`${userID}::NPC::${characterName}`, { name: characterName, thumb: characterThumb, color: characterColor, sheet_url: characterSheetUrl }, function (err) {
        //[TO DO] handle error
      })
    } else {
      // [TO DO] handle error
    }
  })
}
//'https://u8921732.dl.dropboxusercontent.com/u/8921732/slack/thumbs/ar_jenkins.png'


text:
// <copyright file="ContactProperty.cs" company="Quamotion">
// Copyright (c) Quamotion. All rights reserved.
// </copyright>

namespace AgileAPI.Models
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    /// <summary>
    /// Represents a property of the contact
    /// </summary>
    public class ContactProperty
    {
        /// <summary>
        /// Gets or sets the name of the property.
        /// </summary>
        [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the type of the property.
        /// </summary>
        [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
        [JsonConverter(typeof(StringEnumConverter))]
        public PropertyType Type { get; set; }

        /// <summary>
        /// Gets or sets the sub type of the property. Sub type of the field. Only system properties like email will have the sub types.
        /// </summary>
        [JsonProperty("subtype", NullValueHandling = NullValueHandling.Ignore)]
        public string SubType { get; set; }

        /// <summary>
        /// Gets or sets the value of the property.
        /// </summary>
        [JsonProperty("value")]
        public string Value { get; set; }
    }
}


text:
schema

      namespace
      <input name="namespace" id="{{id:namespace}}" type="text"/>

      root element
      <input name="root" id="{{id:root}}" type="text"/>

      elements


text:
<?php

namespace CherryBomb\Gunp\Setup;

use CherryBomb\Gunp\Assets;

/**
 * Remove unnecesary stuff to get clean html
 */
function cleanup() {
  // Some unnecesary data
  remove_action('wp_head', 'wp_generator');
  remove_action('wp_head', 'wlwmanifest_link');
  remove_action('wp_head', 'rsd_link');
  remove_action('wp_head', 'rest_output_link_wp_head', 10);
  remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);

  // All actions related to emojis
  remove_action('admin_print_styles', 'print_emoji_styles');
  remove_action('wp_head', 'print_emoji_detection_script', 7);
  remove_action('admin_print_scripts', 'print_emoji_detection_script');
  remove_action('wp_print_styles', 'print_emoji_styles');
  remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
  remove_filter('the_content_feed', 'wp_staticize_emoji');
  remove_filter('comment_text_rss', 'wp_staticize_emoji');

  add_filter('emoji_svg_url', '__return_false');

  // Filter to remove TinyMCE emojis
  add_filter('tiny_mce_plugins', function ($plugins) {
    return is_array($plugins) ? array_diff($plugins, ['wpemoji']) : [];
  });

  // Remove the REST API endpoint.
  remove_action('rest_api_init', 'wp_oembed_register_route');

  // Turn off oEmbed auto discovery.
  // Don't filter oEmbed results.
  remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);

  // Remove oEmbed discovery links.
  remove_action('wp_head', 'wp_oembed_add_discovery_links');

  // Remove oEmbed-specific JavaScript from the front-end and back-end.
  remove_action('wp_head', 'wp_oembed_add_host_js');
}
add_action('init', __NAMESPACE__ . '\\cleanup');

/**
 * Theme setup
 */
function setup() {
  // Enable features from Soil when plugin is activated
  // https://roots.io/plugins/soil/
  // TODO might be good a plugin only to enable these
  add_theme_support('soil-clean-up');
  add_theme_support('soil-nav-walker');
  add_theme_support('soil-nice-search');
  add_theme_support('soil-jquery-cdn');

  // Make theme available for translation
  load_theme_textdomain('gunp', get_template_directory() . '/lang');

  // Enable plugins to manage the document title
  // http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag
  add_theme_support('title-tag');

  // Register wp_nav_menu() menus
  // http://codex.wordpress.org/Function_Reference/register_nav_menus
  register_nav_menus([
    'primary_navigation' => __('Primary Navigation', 'gunp')
  ]);

  // Enable post thumbnails
  // http://codex.wordpress.org/Post_Thumbnails
  // http://codex.wordpress.org/Function_Reference/set_post_thumbnail_size
  // http://codex.wordpress.org/Function_Reference/add_image_size
  add_theme_support('post-thumbnails');

  // Enable post formats
  // http://codex.wordpress.org/Post_Formats
  add_theme_support('post-formats', ['aside', 'gallery', 'link', 'image', 'quote', 'video', 'audio']);

  // Enable HTML5 markup support
  // http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5
  add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);

  // Use main stylesheet for visual editor
  // To add custom styles edit /assets/styles/layouts/_tinymce.scss
  add_editor_style(Assets\asset_path('styles/main.css'));
}
add_action('after_setup_theme', __NAMESPACE__ . '\\setup');

/**
 * Register sidebars
 */
function widgets_init() {
  register_sidebar([
    'name'          => __('Primary', 'gunp'),
    'id'            => 'sidebar-primary',
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '
',
    'after_title'   => '
'
  ]);

  register_sidebar([
    'name'          => __('Footer', 'gunp'),
    'id'            => 'sidebar-footer',
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '
',
    'after_title'   => '
'
  ]);
}
add_action('widgets_init', __NAMESPACE__ . '\\widgets_init');

/**
 * Determine which pages should NOT display the sidebar
 */
function display_sidebar() {
  static $display;

  isset($display) || $display = !in_array(true, [
    // The sidebar will NOT be displayed if ANY of the following return true.
    // @link https://codex.wordpress.org/Conditional_Tags
    is_404(),
    is_front_page(),
    is_page_template('template-custom.php'),
  ]);

  return apply_filters('gunp/display_sidebar', $display);
}

/**
 * Theme assets
 */
function assets() {
  wp_enqueue_style('gunp/style', Assets\asset_path('styles/main.css'), false, null);

  if (is_single() && comments_open() && get_option('thread_comments')) {
    wp_enqueue_script('comment-reply');
  }

  wp_enqueue_script('gunp/script', Assets\asset_path('scripts/main.js'), ['jquery'], null, true);
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\assets', 100);


text:
import { Transform, TransformOptions, Writable, Readable } from "stream";
import JSON2CSVBase = require("./JSON2CSVBase");
import JSON2CSVTransform = require("./JSON2CSVTransform");

declare class JSON2CSVAsyncParser<T> extends JSON2CSVBase<T> {
    input: Transform;
    processor: Writable;
    transform: JSON2CSVTransform<T>;

    constructor(opts?: json2csv.Options<T>, transformOpts?: TransformOptions);

    fromInput(input: Readable): JSON2CSVAsyncParser<T>;

    throughTransform(transform: Transform): JSON2CSVAsyncParser<T>;

    toOutput(output: Writable): JSON2CSVAsyncParser<T>;

    promise(returnCSV?: boolean): Promise<undefined | string>;
}

export = JSON2CSVAsyncParser;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Mém. Acad. Sci. (Paris) 67:14. 1949

#### Original name
null

### Remarks
null


text:
#ifndef __SORTER_HPP__
#define __SORTER_HPP__

#include <list>

namespace mesos {
namespace internal {
namespace master {

// Sorters implement the logic for determining the
// order in which users or frameworks should receive
// resource allocations.
class Sorter
{
public:
  virtual ~Sorter() {}

  // Adds a client to allocate resources to. A client
  // may be a user or a framework.
  virtual void add(const std::string& client) = 0;

  // Removes a client.
  virtual void remove(const std::string& client) = 0;

  // Readds a client to the sort after deactivate.
  virtual void activate(const std::string& client) = 0;

  // Removes a client from the sort, so it won't get allocated to.
  virtual void deactivate(const std::string& client) = 0;

  // Specify that resources have been allocated to the given client.
  virtual void allocated(const std::string& client,
                         const Resources& resources) = 0;

  // Specify that resources have been unallocated from the given client.
  virtual void unallocated(const std::string& client,
                           const Resources& resources) = 0;

  // Returns the resources that have been allocated to this client.
  virtual Resources allocation(const std::string& client) = 0;

  // Add resources to the total pool of resources this
  // Sorter should consider.
  virtual void add(const Resources& resources) = 0;

  // Remove resources from the total pool.
  virtual void remove(const Resources& resources) = 0;

  // Returns a list of all clients, in the order that they
  // should be allocated to, according to this Sorter's policy.
  virtual std::list<std::string> sort() = 0;

  // Returns true if this Sorter contains the specified client,
  // either active or deactivated.
  virtual bool contains(const std::string& client) = 0;

  // Returns the number of clients this Sorter contains,
  // either active or deactivated.
  virtual int count() = 0;
};

} // namespace master {
} // namespace internal {
} // namespace mesos {

#endif // __SORTER_HPP__


text:
module main.nav {
    import State = services.State;
    'use strict';

    import WrappedUser = models.WrappedUser;
    import WrappedFriend = models.WrappedFriend;

    export class NavController {
        private $scope: NavModel;
        private frontEndService: services.FrontEndService;
        private userService: services.UserService;
        private errorService: services.ErrorService;

        constructor(
            $scope: NavModel,
            $uibModal: ng.ui.bootstrap.IModalService,
            $locale: ng.ILocaleService,
            frontEndService: services.FrontEndService,
            userService: services.UserService,
            stateService: services.StateService,
            errorService: services.ErrorService) {

            this.$scope = $scope;
            this.frontEndService = frontEndService;
            this.userService = userService;
            this.errorService = errorService;

            this.userService.userSetEvent(user => this.$scope.user = user);

            this.$scope.locale = $locale.id;
            this.$scope.confirmFriendRequest = (friend) => this.confirmFriendRequest(friend);
            this.$scope.ignoreFriendRequest = (friend) => this.ignoreFriendRequest(friend);

            this.$scope.logout = () => {
                this.frontEndService.logout();
            };

            this.$scope.viewFriend = (friend: WrappedFriend) => {
                console.log("Changing to friend", friend);
                stateService.changeState((s) => { s.selectedUserId = friend.userId; return s; });
            };

            this.$scope.viewUser = () => {
                console.log("Changing to user");
                stateService.changeState((s) => { s.selectedUserId = this.userService.User.userId; return s; });
            };

            stateService.stateChangedEvent((state: State) => {
                console.log("State changed", state);
                if (this.userService.User) {
                    if (state.selectedUserId == this.userService.User.userId) {
                        this.userService.Friend = null;
                    } else {
                        for(let i = 0; i < this.userService.User.friends.length; i++) {
                            if (this.userService.User.friends[i].userId == state.selectedUserId) {
                                this.userService.Friend = this.userService.User.friends[i];
                            }
                        }
                    }
                }
            });

            this.$scope.isUserSelected = () => this.userService.Friend == null;
            this.$scope.isFriendSelected = (friend: WrappedFriend) => this.userService.Friend == friend;

            this.$scope.addFriend = () => {
                $uibModal.open({
                    animation: true,
                    templateUrl: '/scripts/main/share/share.view.html',
                    controller: main.share.ShareController,
                    controllerAs: 'vm',
                    size: 'lg',
                });
            };

            // Pop-up the account settings screen
            this.$scope.updateAccountSettings = () => {
                $uibModal.open({
                    animation: true,
                    templateUrl: '/scripts/main/account/account.view.html',
                    controller: main.account.AccountController,
                    controllerAs: 'vm',
                    size: 'lg',
                });
            };
        }

        private confirmFriendRequest(friend: WrappedFriend) {
            this.frontEndService.addFriend(friend.email)
                .error((error) => this.errorService.raiseError('Failed to confirm friend', error))
                .success(() => {
                   this.frontEndService.getUser()
                       .error((error) => this.errorService.raiseError('Failed to fetch user after friend confirmation', error))
                       .success((user: WrappedUser) => this.userService.User = user)
                });
        }

        private ignoreFriendRequest(friend: WrappedFriend) {
            this.frontEndService.deleteFriend(friend.userId)
                .error((error) => this.errorService.raiseError('Failed to ignore friend', error))
                .success(() => {
                    this.frontEndService.getUser()
                        .error((error) => this.errorService.raiseError('Failed to fetch user after ignoring friend', error))
                        .success((user: WrappedUser) => this.userService.User = user)
                });
        }
    }
}


text:
using ILspect.Syntax.Expressions;
using Mono.Cecil.Cil;

namespace ILspect.Syntax.Statements
{
    public class AssignmentStatement : Statement
    {
        public VariableReference Variable { get; }
        public Expression Value { get; }

        public AssignmentStatement(VariableReference variable, Expression value)
            : this(variable, value, instruction: null) { }

        public AssignmentStatement(VariableReference variable, Expression value, Instruction instruction) : base(instruction)
        {
            Variable = variable;
            Value = value;
        }

        public override string ToString()
        {
            return $"_{Variable.Index} = {Value}";
        }
    }
}


text:
import React from 'react';
import { assert } from 'chai';
import { createShallow, createMount, getClasses } from '@material-ui/core/test-utils';
import TabScrollButton from './TabScrollButton';
import ButtonBase from '../ButtonBase';

describe('<TabScrollButton />', () => {
  const props = {
    direction: 'left',
  };
  let shallow;
  let mount;
  let classes;

  before(() => {
    shallow = createShallow({ dive: true });
    classes = getClasses(<TabScrollButton {...props} />);
    // StrictModeViolation: uses ButtonBase
    mount = createMount({ strict: false });
  });

  after(() => {
    mount.cleanUp();
  });

  describe('prop: visible', () => {
    it('should render as a button with the root class', () => {
      const wrapper = shallow(<TabScrollButton {...props} visible />);

      assert.strictEqual(wrapper.type(), ButtonBase);
      assert.strictEqual(wrapper.hasClass(classes.root), true);
    });
  });

  describe('prop: !visible', () => {
    it('should render as a div with root class', () => {
      const wrapper = shallow(<TabScrollButton {...props} visible={false} />);

      assert.strictEqual(wrapper.name(), 'div');
      assert.strictEqual(wrapper.hasClass(classes.root), true);
    });
  });

  describe('prop: className', () => {
    it('should render with the user and root classes', () => {
      const wrapper = shallow(<TabScrollButton {...props} className="woofTabScrollButton" />);
      assert.strictEqual(wrapper.hasClass(classes.root), true);
      assert.strictEqual(wrapper.hasClass('woofTabScrollButton'), true);
    });
  });

  describe('prop: direction', () => {
    it('should render with the left icon', () => {
      const wrapper = mount(<TabScrollButton {...props} direction="left" visible />);
      assert.strictEqual(wrapper.find('svg[data-mui-test="KeyboardArrowLeftIcon"]').length, 1);
    });

    it('should render with the right icon', () => {
      const wrapper = mount(<TabScrollButton {...props} direction="right" visible />);
      assert.strictEqual(wrapper.find('svg[data-mui-test="KeyboardArrowRightIcon"]').length, 1);
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace KitKatPrintDemo
{
    [Activity (Label = "MainActivity", MainLauncher = true, Theme = "@android:style/Theme.Holo.Light")]
    public class MainActivity : Activity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.Main);

            var showPrint = FindViewById<Button> (Resource.Id.showPrintButton);

            showPrint.Click += (object sender, EventArgs e) => StartActivity (typeof(PrintActivity));

            var showHybrid = FindViewById<Button> (Resource.Id.showHybridButton);

            showHybrid.Click += (object sender, EventArgs e) => StartActivity (typeof(HybridActivity));
        }
    }
}