text:
package com.amazonaws.services.xray.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.xray.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * SamplingRule JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SamplingRuleJsonUnmarshaller implements Unmarshaller<SamplingRule, JsonUnmarshallerContext> {

    public SamplingRule unmarshall(JsonUnmarshallerContext context) throws Exception {
        SamplingRule samplingRule = new SamplingRule();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("RuleName", targetDepth)) {
                    context.nextToken();
                    samplingRule.setRuleName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("RuleARN", targetDepth)) {
                    context.nextToken();
                    samplingRule.setRuleARN(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ResourceARN", targetDepth)) {
                    context.nextToken();
                    samplingRule.setResourceARN(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Priority", targetDepth)) {
                    context.nextToken();
                    samplingRule.setPriority(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("FixedRate", targetDepth)) {
                    context.nextToken();
                    samplingRule.setFixedRate(context.getUnmarshaller(Double.class).unmarshall(context));
                }
                if (context.testExpression("ReservoirSize", targetDepth)) {
                    context.nextToken();
                    samplingRule.setReservoirSize(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("ServiceName", targetDepth)) {
                    context.nextToken();
                    samplingRule.setServiceName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ServiceType", targetDepth)) {
                    context.nextToken();
                    samplingRule.setServiceType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Host", targetDepth)) {
                    context.nextToken();
                    samplingRule.setHost(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("HTTPMethod", targetDepth)) {
                    context.nextToken();
                    samplingRule.setHTTPMethod(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("URLPath", targetDepth)) {
                    context.nextToken();
                    samplingRule.setURLPath(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Version", targetDepth)) {
                    context.nextToken();
                    samplingRule.setVersion(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("Attributes", targetDepth)) {
                    context.nextToken();
                    samplingRule
                            .setAttributes(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context.getUnmarshaller(String.class))
                                    .unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return samplingRule;
    }

    private static SamplingRuleJsonUnmarshaller instance;

    public static SamplingRuleJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new SamplingRuleJsonUnmarshaller();
        return instance;
    }
}


text:
import sys
from setuptools import setup

# Support for building on mac & linux, and installation
# on Unix
if sys.platform == 'darwin':
    extra_options = dict(
        setup_requires=['py2app'],
        app=['slingshotsms.py'],
        )
elif sys.platform  == 'win32':
    from distutils.core import setup
    import py2exe
    extra_options = dict(
        setup_requires=['py2exe'],
		console=['slingshotsms.py'],
        excludes=['javax.comm']
        )
else:
    extra_options = dict(
        # Normally unix-like platforms will use "setup.py install"
        # and install the main script as such
        scripts=['slingshotsms.py'],
        )

setup(
    name="SlingshotSMS",
    data_files=['README.md'],
    **extra_options
    )

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.builder.xml;

import javax.xml.transform.Source;

import org.apache.camel.CamelContext;
import org.apache.camel.component.xslt.XsltUriResolver;
import org.apache.camel.impl.DefaultCamelContext;
import org.junit.Assert;
import org.junit.Test;

public class XsltUriResolverTest extends Assert {

    @Test
    public void testResolveUri() throws Exception {
        CamelContext context = new DefaultCamelContext();
        XsltUriResolver xsltUriResolver = new XsltUriResolver(context, "classpath:xslt/staff/staff.xsl");
        Source source = xsltUriResolver.resolve("../../xslt/common/staff_template.xsl", "classpath:xslt/staff/staff.xsl");
        assertNotNull(source);
        assertEquals("classpath:xslt/common/staff_template.xsl", source.getSystemId());
    }
}


text:
angular.module('casinocoin.controllers')

.controller('HomeCtrl', function ($scope, $rootScope, publicAPI, $log, $ionicSideMenuDelegate, insight) {
    // set application version
    $log.debug("### App Version: " + $rootScope.appVersion);
    $log.debug("### Security: " + angular.toJson($rootScope.security));
    $ionicSideMenuDelegate.canDragContent(true);
    // get api info on page show
    $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        if (toState.name == 'app.home') {
            // get the last Blocks from Insight
            insight.getBlocks().then(function (apiResult) {
                if (apiResult.status == 200) {
                    $rootScope.blocks = apiResult.data.blocks;
                    if ($rootScope.blocks.length > 0) {
                        $rootScope.blockheight = $rootScope.blocks[0].height;
                    }
                }
            })
            // get CoinInfo from API
            publicAPI.getCoinInfo().then(function (apiResult) {
                $log.debug("### CoinInfo: " + angular.toJson(apiResult));
                if (apiResult.status == 200) {
                    $rootScope.coinInfo = apiResult.data.Result.CoinInfo;
                    $rootScope.blockheight = $scope.coinInfo.Blockheight;
                }
            });
            // get new exchanges info data
            publicAPI.getActiveExchanges().then(function (apiResult) {
                if (apiResult.status == 200) {
                    $rootScope.activeExchanges = apiResult.data.Result.ActiveExchanges;
                }
            });
            $log.debug("### Security: " + JSON.stringify($scope.security));
        }
    });
});


text:
function [net, IMAGES]=ini(numhid,SYNAPSE_COST,RATE_COST)
% Simply sets up the neural network and some parameters
%
%
%
% =============== THIS CODE WAS WRITTEN BY BENJAMIN VINCENT ===============
% IF YOU DO ANYTHING COOL WITH THIS CODE, FEEL FREE TO EMAIL ME AT:
% B.T.VINCENT@DUNDEE.AC.UK
%
% IF YOU USE IT, PLEASE CITE THE FOLLOWING WORK:
%
% - Vincent B, Troscianko T, Gilchrist I, (2007) Investigating a
% space-variant weighted salience account of visual selection,
% Vision Research, 47(13): 1809-1820.
%
% - Vincent B, Baddeley R, Troscianko T, Gilchrist I, (2005) Is the early
% visual system optimised to be energy efficient, Network: Computation in
% Neural Systems, 16(2/3): 175-190.
% =========================================================================

figure(1),clf,colormap(gray)
figure(2),clf,colormap(gray)

load DATA

input_image_size    =size(IMAGES,1);

% ======================================================
% Initialise network
net.numin   =input_image_size;
net.numhid  =numhid;
net.wcon	=0;	% weight decay parameter

% Create Gaussian distributed random weights
net.w      =(randn(net.numhid,net.numin)*0.1);
%net.w=generate_correlated_random_patches( sqrt(net.numin), net.numhid);

% DEFINE OTHER THINGS
net.display			=1;
net.SYNAPSE_COST    =SYNAPSE_COST;
net.RATE_COST       =RATE_COST;
net.batch_size		=100;
net.lr_schedule		=1;
net.epoch			=1;

% Set L2 of each filter to 1
net.lr				=0.8;
[net]				=set_l2_to_1(net);

% parameters to play around with, but these work just fine
net.display_interval	=1000;	% just determines how frequency of replotting

% plot the initial random receptive fields
see_matrix(net.w);
drawnow

fprintf('\nTraining model: %d %1.3f %1.3f\n',net.numhid,net.SYNAPSE_COST,net.RATE_COST)


text:
layout: post
date: 2021-08-20 15:59:00-0400
inline: true
---

 Come join the [CaMLSys](https://mlsys.cst.cam.ac.uk/) group as a new postdoc studying Federated Learning! Help us invent the next generation of FL methods and contribute to the evolution of our open-source FL framework [Flower](http://flower.dev).


text:
Add Board Cost

{{msg}}
<form name="cost_form" method="post" action="/cost_action" >
    Board Cost :

    <input type="text" name="cost" value=""  required/>

    <input type="submit" name="add_cost" value="Add" />
</form>


text:
<?php

namespace Birgit\Component\Task\Exception;

/**
 * Exception
 */
abstract class Exception extends \Exception
{
}


text:
import React from 'react';
import IconBase from './../components/IconBase/IconBase';

export default class AndroidArrowDropdown extends React.Component {
	render() {
if(this.props.bare) {
			return <g>

<g>
	<polygon points="128,192 256,320 384,192 	"></polygon>
</g>

			</g>;
		}		return <IconBase>
<g>
	<polygon points="128,192 256,320 384,192 	"></polygon>
</g>
</IconBase>;
	}
};AndroidArrowDropdown.defaultProps = {bare: false}


text:
<?xml version="1.0" encoding="UTF-8"?>
<layout>
    <VSNode splits="0.3 0.7">

        <CNode>
            <Component label="Asserted hierarchy">
                <Property id="pluginId" value="org.protege.editor.owl.OWLAssertedClassHierarchy"/>
            </Component>
        </CNode>

        <CNode>
            <Component label="Integrativo CBR">
                <Property id="pluginId" value="br.ufpe.integrativocbr.plugin.OWLClassExpressionEditorViewComponent"/>
            </Component>
        </CNode>

    </VSNode>

</layout>


text:
package org.zstack.simulator;

import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.core.Completion;
import org.zstack.header.host.HypervisorType;
import org.zstack.header.network.l2.*;
import org.zstack.header.simulator.SimulatorConstant;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

public class L2VlanNetworkRealizer implements L2NetworkRealizationExtensionPoint {
    private static CLogger logger = Utils.getLogger(L2VlanNetworkRealizer.class);

    @Autowired
    private DatabaseFacade dbf;

    @Override
    public void realize(L2NetworkInventory l2Network, String hostUuid, Completion completion) {
        L2VlanNetworkVO vo = dbf.findByUuid(l2Network.getUuid(), L2VlanNetworkVO.class);
        logger.debug(String.format("simulator successfully realized l2network[uuid:%s, vlan:%s]", l2Network.getUuid(), vo.getVlan()));
        completion.success();
    }

    @Override
    public void check(L2NetworkInventory l2Network, String hostUuid, Completion completion) {
        completion.success();
    }

    @Override
    public L2NetworkType getSupportedL2NetworkType() {
        return L2NetworkType.valueOf(L2NetworkConstant.L2_VLAN_NETWORK_TYPE);
    }

    @Override
    public HypervisorType getSupportedHypervisorType() {
        return HypervisorType.valueOf(SimulatorConstant.SIMULATOR_HYPERVISOR_TYPE);
    }

    public void delete(L2NetworkInventory l2Network, String hostUuid, Completion completion) {
        completion.success();
    }

}


text:
({
    /**
     * verify client action exist in Child only get called.
     */
    testClientSideActionInChildOnly : {
        test : [function(component) {
            var clientAction = component.get("c.clientSideActionInChildOnly");
            $A.enqueueAction(clientAction);

            $A.test.addWaitFor(true, function() {
                return (component.get("v.WhichControllerWasCalledChild") === "clientSideActionInChildOnly")
            });
        }]
    },

    /**
     * both Child and Parent has client action: clientSideActionInBoth
     * This verify the one in Child get called.
     */
    testClientSideActionInBoth : {
        test : function(component) {
            var clientAction = component.get("c.clientSideActionInBoth");
            $A.enqueueAction(clientAction);

            $A.test.addWaitFor(true, function() {
                return (component.get("v.WhichControllerWasCalledChild") === "clientSideActionInBoth from Child")
            });
        }
    },

    /**
     * Parent has server controller: JavaTestController, Child has a no server controller
     * This verify when Child can call parent's server action directly, and it go through the correct one
     */
    testServerSideActionInParentOnly : {
        test : function(component) {
            var clientAction = component.get("c.serverSideActionInParentOnly");
            $A.enqueueAction(clientAction);

            $A.test.addWaitFor(true, function() {
                return (component.get("v.WhichControllerWasCalledChild") === "getString called from Child's serverSideActionInParentOnly")
            });
        }
    },

    /**
     * Parent has attribute of type Aura.Action, Child set that attribute to its client
     * action: setAttributeAuraActionChild.
     * This verify when client get the action through that attribute, it go through what
     * we set it to : setAttributeAuraActionChild
     */
    testAttributeAuraAction : {
        test : function(component) {
            var clientAction = component.get("c.fireAttributeAuraAction");
            $A.enqueueAction(clientAction);

            $A.test.addWaitFor(true, function() {
                return (component.get("v.WhichControllerWasCalledChild") === "setAttributeAuraAction in Child")
            });
        }
    },

    /**
     * Parent has attribute of type Aura.Action
     * by default it's set to its client action: setAttributeAuraAction
     * Child set that attribute to its client action: setAttributeAuraActionChild
     * This verify when client get the action through Parent's attribute, it still go through Child's client action
     */
    testAttributeAuraActionInParentCmp : {
        test : [function(component) {
            var clientAction = component.getSuper().get("c.fireAttributeAuraAction");
            $A.enqueueAction(clientAction);
            //verify Child's client controller was called.
            $A.test.addWaitFor(true, function() {
                return (component.get("v.WhichControllerWasCalledChild") === "setAttributeAuraAction in Child");
            });
        }, function(component) {
            //verify we didn't call Parent's client controller
            $A.test.assertEquals("no one", component.getSuper().get("v.WhichControllerWasCalledParent"));
        }]
    }

})


text:
using std::optional;

struct X
{
private:
    ~X() {}
};

int main()
{
    using std::optional;
    {
        // expected-error@optional:* 2 {{static_assert failed "instantiation of optional with a reference type is ill-formed}}
        optional<int&> opt1;
        optional<int&&> opt2;
    }
    {
        // expected-error@optional:* {{static_assert failed "instantiation of optional with a non-destructible type is ill-formed"}}
        optional<X> opt3;
    }
    {
        // expected-error@optional:* {{static_assert failed "instantiation of optional with a non-object type is undefined behavior"}}
        // expected-error@optional:* {{static_assert failed "instantiation of optional with a non-destructible type is ill-formed}}
        optional<void()> opt4;
    }
    {
        // expected-error@optional:* {{static_assert failed "instantiation of optional with a non-object type is undefined behavior"}}
        // expected-error@optional:* {{static_assert failed "instantiation of optional with a non-destructible type is ill-formed}}
        // expected-error@optional:* 1+ {{cannot form a reference to 'void'}}
        optional<const void> opt4;
    }
    // FIXME these are garbage diagnostics that Clang should not produce
    // expected-error@optional:* 0+ {{is not a base class}}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.github.shiraji.butai.sample.MainActivity">

    <Button
        android:text="Next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gotoNextButton"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>


text:
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>pork</title>

  <link href="{{ url_for('static', filename='common.css') }}" rel="stylesheet" />

  <link href="{{ url_for('static', filename='bootstrap.css') }}" rel="stylesheet" />

      {% with msgs = get_flashed_messages() %}
      {% if msgs %}

        {% for msg in msgs %}

{{msg}}

        {% endfor %}

      {% endif %}
      {% endwith %}

Berkeley RND

      {% block content %}{% endblock %}

      <form id="cmd" action="">
        <input id="cmdi" type="text">
        <input type="submit" style="position: absolute; left: -9999px;">
      </form>


text:
//** Introduction
// This file contains constant definition shared by CryptUtil and the parts
// of the Crypto Engine.
//

#ifndef _CRYPT_RAND_H
#define _CRYPT_RAND_H

//** DRBG Structures and Defines

// Values and structures for the random number generator. These values are defined
// in this header file so that the size of the RNG state can be known to TPM.lib.
// This allows the allocation of some space in NV memory for the state to
// be stored on an orderly shutdown.

// The DRBG based on a symmetric block cipher is defined by three values,
// 1) the key size
// 2) the block size (the IV size)
// 3) the symmetric algorithm

#define DRBG_KEY_SIZE_BITS      AES_MAX_KEY_SIZE_BITS
#define DRBG_IV_SIZE_BITS       (AES_MAX_BLOCK_SIZE * 8)
#define DRBG_ALGORITHM          TPM_ALG_AES

typedef tpmKeyScheduleAES     DRBG_KEY_SCHEDULE;
#define DRBG_ENCRYPT_SETUP(key, keySizeInBits, schedule)        \
            TpmCryptSetEncryptKeyAES(key, keySizeInBits, schedule)
#define DRBG_ENCRYPT(keySchedule, in, out)                      \
            TpmCryptEncryptAES(SWIZZLE(keySchedule, in, out))

#if     ((DRBG_KEY_SIZE_BITS % RADIX_BITS) != 0) \
    || ((DRBG_IV_SIZE_BITS % RADIX_BITS) != 0)
#error "Key size and IV for DRBG must be even multiples of the radix"
#endif
#if (DRBG_KEY_SIZE_BITS % DRBG_IV_SIZE_BITS) != 0
#error "Key size for DRBG must be even multiple of the cypher block size"
#endif

// Derived values
#define DRBG_MAX_REQUESTS_PER_RESEED (1 << 48)
#define DRBG_MAX_REQEST_SIZE (1 << 32)

#define pDRBG_KEY(seed)    ((DRBG_KEY *)&(((BYTE *)(seed))[0]))
#define pDRBG_IV(seed)     ((DRBG_IV *)&(((BYTE *)(seed))[DRBG_KEY_SIZE_BYTES]))

#define DRBG_KEY_SIZE_WORDS     (BITS_TO_CRYPT_WORDS(DRBG_KEY_SIZE_BITS))
#define DRBG_KEY_SIZE_BYTES     (DRBG_KEY_SIZE_WORDS * RADIX_BYTES)

#define DRBG_IV_SIZE_WORDS      (BITS_TO_CRYPT_WORDS(DRBG_IV_SIZE_BITS))
#define DRBG_IV_SIZE_BYTES      (DRBG_IV_SIZE_WORDS * RADIX_BYTES)

#define DRBG_SEED_SIZE_WORDS    (DRBG_KEY_SIZE_WORDS + DRBG_IV_SIZE_WORDS)
#define DRBG_SEED_SIZE_BYTES    (DRBG_KEY_SIZE_BYTES + DRBG_IV_SIZE_BYTES)

typedef union
{
    BYTE            bytes[DRBG_KEY_SIZE_BYTES];
    crypt_uword_t   words[DRBG_KEY_SIZE_WORDS];
} DRBG_KEY;

typedef union
{
    BYTE            bytes[DRBG_IV_SIZE_BYTES];
    crypt_uword_t   words[DRBG_IV_SIZE_WORDS];
} DRBG_IV;

typedef union
{
    BYTE            bytes[DRBG_SEED_SIZE_BYTES];
    crypt_uword_t   words[DRBG_SEED_SIZE_WORDS];
} DRBG_SEED;

#define CTR_DRBG_MAX_REQUESTS_PER_RESEED        ((UINT64)1 << 20)
#define CTR_DRBG_MAX_BYTES_PER_REQUEST          (1 << 16)

#   define CTR_DRBG_MIN_ENTROPY_INPUT_LENGTH    DRBG_SEED_SIZE_BYTES
#   define CTR_DRBG_MAX_ENTROPY_INPUT_LENGTH    DRBG_SEED_SIZE_BYTES
#   define CTR_DRBG_MAX_ADDITIONAL_INPUT_LENGTH DRBG_SEED_SIZE_BYTES

#define     TESTING         (1 << 0)
#define     ENTROPY         (1 << 1)
#define     TESTED          (1 << 2)

#define     IsTestStateSet(BIT)    ((g_cryptoSelfTestState.rng & BIT) != 0)
#define     SetTestStateBit(BIT)   (g_cryptoSelfTestState.rng |= BIT)
#define     ClearTestStateBit(BIT) (g_cryptoSelfTestState.rng &= ~BIT)

#define     IsSelfTest()    IsTestStateSet(TESTING)
#define     SetSelfTest()   SetTestStateBit(TESTING)
#define     ClearSelfTest() ClearTestStateBit(TESTING)

#define     IsEntropyBad()      IsTestStateSet(ENTROPY)
#define     SetEntropyBad()     SetTestStateBit(ENTROPY)
#define     ClearEntropyBad()   ClearTestStateBit(ENTROPY)

#define     IsDrbgTested()      IsTestStateSet(TESTED)
#define     SetDrbgTested()     SetTestStateBit(TESTED)
#define     ClearDrbgTested()   ClearTestStateBit(TESTED)

typedef struct
{
    UINT64      reseedCounter;
    UINT32      magic;
    DRBG_SEED   seed; // contains the key and IV for the counter mode DRBG
    UINT32      lastValue[4];   // used when the TPM does continuous self-test
                                // for FIPS compliance of DRBG
} DRBG_STATE, *pDRBG_STATE;
#define DRBG_MAGIC   ((UINT32) 0x47425244) // "DRBG" backwards so that it displays

typedef struct
{
    UINT64               counter;
    UINT32               magic;
    UINT32               limit;
    TPM2B               *seed;
    const TPM2B         *label;
    TPM2B               *context;
    TPM_ALG_ID           hash;
    TPM_ALG_ID           kdf;
    UINT16               digestSize;
    TPM2B_DIGEST         residual;
} KDF_STATE, *pKDR_STATE;
#define KDF_MAGIC    ((UINT32) 0x4048444a) // "KDF " backwards

// Make sure that any other structures added to this union start with a 64-bit
// counter and a 32-bit magic number
typedef union
{
    DRBG_STATE      drbg;
    KDF_STATE       kdf;
} RAND_STATE;

// This is the state used when the library uses a random number generator.
// A special function is installed for the library to call. That function
// picks up the state from this location and uses it for the generation
// of the random number.
extern RAND_STATE           *s_random;

// When instrumenting RSA key sieve
#if  RSA_INSTRUMENT
#define PRIME_INDEX(x)  ((x) == 512 ? 0 : (x) == 1024 ? 1 : 2)
#   define INSTRUMENT_SET(a, b) ((a) = (b))
#   define INSTRUMENT_ADD(a, b) (a) = (a) + (b)
#   define INSTRUMENT_INC(a)    (a) = (a) + 1

extern UINT32  PrimeIndex;
extern UINT32  failedAtIteration[10];
extern UINT32  PrimeCounts[3];
extern UINT32  MillerRabinTrials[3];
extern UINT32  totalFieldsSieved[3];
extern UINT32  bitsInFieldAfterSieve[3];
extern UINT32  emptyFieldsSieved[3];
extern UINT32  noPrimeFields[3];
extern UINT32  primesChecked[3];
extern UINT16  lastSievePrime;
#else
#   define INSTRUMENT_SET(a, b)
#   define INSTRUMENT_ADD(a, b)
#   define INSTRUMENT_INC(a)
#endif

#endif // _CRYPT_RAND_H


text:
import { version } from "../version";
import { AnyAudioContext, hasAudioContext, theWindow } from "./context/AudioContext";
import { Context } from "./context/Context";
import { DummyContext } from "./context/DummyContext";
import { BaseContext } from "./context/BaseContext";
import { OfflineContext } from "./context/OfflineContext";
import { isAudioContext, isOfflineAudioContext } from "./util/AdvancedTypeCheck";

/**
 * This dummy context is used to avoid throwing immediate errors when importing in Node.js
 */
const dummyContext = new DummyContext();

/**
 * The global audio context which is getable and assignable through
 * getContext and setContext
 */
let globalContext: BaseContext = dummyContext;

/**
 * Returns the default system-wide [[Context]]
 * @category Core
 */
export function getContext(): BaseContext {
	if (globalContext === dummyContext && hasAudioContext) {
		setContext(new Context());
	}
	return globalContext;
}

/**
 * Set the default audio context
 * @category Core
 */
export function setContext(context: BaseContext | AnyAudioContext): void {
	if (isAudioContext(context)) {
		globalContext = new Context(context);
	} else if (isOfflineAudioContext(context)) {
		globalContext = new OfflineContext(context);
	} else {
		globalContext = context;
	}
}

/**
 * Most browsers will not play _any_ audio until a user
 * clicks something (like a play button). Invoke this method
 * on a click or keypress event handler to start the audio context.
 * More about the Autoplay policy
 * [here](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio)
 * @example
 * document.querySelector("button").addEventListener("click", async () => {
 * 	await Tone.start();
 * 	console.log("context started");
 * });
 * @category Core
 */
export function start(): Promise<void> {
	return globalContext.resume();
}

/**
 * Log Tone.js + version in the console.
 */
if (theWindow && !theWindow.TONE_SILENCE_LOGGING) {
	let prefix = "v";
	if (version === "dev") {
		prefix = "";
	}
	const printString = ` * Tone.js ${prefix}${version} * `;
	// eslint-disable-next-line no-console
	console.log(`%c${printString}`, "background: #000; color: #fff");
}


text:
using System;
using System.Collections.Generic;
using UnityEngine;

namespace TenPN.DecisionFlex.Demos
{
    public class GraphParameters
    {
        public Rect ScreenBounds;
        public Vector2 YValuesMinMax = Vector2.zero;
        public IList<IList<float>> YValuesList;
        public IList<float> XValues;
        public IEnumerator<Color> Cols;

        // x is min, y is max
        public Vector2 GetYValuesMinMax()
        {
            Vector2 minMax = new Vector2(float.MaxValue, -float.MaxValue);
            for(int listIndex = 0; listIndex < YValuesList.Count; ++listIndex)
            {
                var values = YValuesList[listIndex];
                for(int yIndex = 0; yIndex < values.Count; ++yIndex)
                {
                    float yValue = values[yIndex];
                    minMax.x = Mathf.Min(minMax.x, yValue);
                    minMax.y = Mathf.Max(minMax.y, yValue);
                }
            }
            return minMax;
        }
    }

    [AddComponentMenu("TenPN/DecisionFlex/Demos/iPerson/GraphRenderer")]
    public class GraphRenderer : MonoBehaviour
    {
        public static GraphRenderer Instance;

        public void RenderGraph(GraphParameters graph)
        {
            m_graphs.Enqueue(graph);
        }

        //////////////////////////////////////////////////

        Queue<GraphParameters> m_graphs = new Queue<GraphParameters>();

        [SerializeField]
        Material graphMat;

        //////////////////////////////////////////////////

        void Awake()
        {
            Instance = this;
        }

        void OnPostRender()
        {
            while(m_graphs.Count > 0)
            {
                var graph = m_graphs.Dequeue();
                PostRenderGraph(graph);
            }
        }

        void PostRenderGraph(GraphParameters graph)
        {
            if (graph.XValues.Count <= 1)
            {
                // not enough to render
                return;
            }

            GL.PushMatrix();
            graphMat.SetPass(0);
            GL.LoadOrtho();

            float normScreenGraphXMin = graph.ScreenBounds.x/Screen.width;
            float normScreenGraphYMin = (Screen.height - graph.ScreenBounds.y)/Screen.height;
            float normScreenGraphWidth = graph.ScreenBounds.width/Screen.width;
            float normScreenGraphHeight = graph.ScreenBounds.height/Screen.height;

            Rect normalizedGraphScreenRect =
                new Rect(normScreenGraphXMin, normScreenGraphYMin,
                         normScreenGraphWidth, normScreenGraphHeight);

            bool isYRangeManuallySet = graph.YValuesMinMax != Vector2.zero;
            var graphMinMax = graph.GetYValuesMinMax();
            float minYValue = isYRangeManuallySet ? graph.YValuesMinMax.x : graphMinMax.x;
            float maxYValue = isYRangeManuallySet ? graph.YValuesMinMax.y : graphMinMax.y;
            float yScale = normalizedGraphScreenRect.height/(maxYValue - minYValue);

            float lastX = graph.XValues[graph.XValues.Count-1];
            float xScale = normalizedGraphScreenRect.width
                /(lastX- graph.XValues[0]);

            Func<float,float,Vector2> graphToGLCoord = (xValue, yValue) =>
                new Vector2(normalizedGraphScreenRect.x + xValue * xScale,
                            normalizedGraphScreenRect.y - normalizedGraphScreenRect.height
                            + yValue * yScale);

            // horizontal bars
            GL.Begin(GL.LINES);
            GL.Color(new Color(0.1f, 0.1f, 0.1f, 0.2f));

            GL.Vertex(graphToGLCoord(graph.XValues[0], minYValue));
            GL.Vertex(graphToGLCoord(lastX, minYValue));
            GL.Vertex(graphToGLCoord(graph.XValues[0], maxYValue));
            GL.Vertex(graphToGLCoord(lastX, maxYValue));
            GL.End();

            // vertical bars
            GL.Begin(GL.LINES);
            GL.Color(new Color(0.1f, 0.1f, 0.1f, 0.2f));
            foreach(var xValue in graph.XValues)
            {
                GL.Vertex(graphToGLCoord(xValue, minYValue));
                GL.Vertex(graphToGLCoord(xValue, maxYValue));
            }
            GL.End();

            foreach(var yValues in graph.YValuesList)
            {
                if (yValues.Count <= 1)
                {
                    continue;
                }

                GL.Begin(GL.LINES);

                int xIndexOffset =
                    graph.XValues.Count - Mathf.Min(graph.XValues.Count, yValues.Count);

                var prevPoint = graphToGLCoord(graph.XValues[xIndexOffset], yValues[0]);

                graph.Cols.MoveNext();
                var graphColor = graph.Cols.Current;

                for(int valueIndex = 1; valueIndex < yValues.Count; ++valueIndex)
                {
                    GL.Color(graphColor);

                    float xValue = graph.XValues[valueIndex + xIndexOffset];
                    float yValue = yValues[valueIndex];

                    GL.Vertex(prevPoint);
                    var currentPoint = graphToGLCoord(xValue, yValue);
                    GL.Vertex(currentPoint);

                    prevPoint = currentPoint;
                }

                GL.End();
            }

            GL.PopMatrix();
        }

    }
}


text:
// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2018 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#pragma once

#include "SchedulerStatus.h"
#include "Scheduler.h"
#include <functional>
#include <vector>
#include <memory>

class Backend;
class Scheduler;
struct RequestNotes;

/**
 * Manages a set of backends of one role.
 *
 * \see BackendRole
 * \see Director
 */
class BackendCluster {
 public:
  typedef std::vector<Backend*> List;

  BackendCluster();
  ~BackendCluster();

  template <typename T>
  void setScheduler() {
    auto old = scheduler_;
    scheduler_ = new T(&cluster_);
    delete old;
  }
  Scheduler* scheduler() const { return scheduler_; }

  SchedulerStatus schedule(RequestNotes* rn);

  bool empty() const { return cluster_.empty(); }
  size_t size() const { return cluster_.size(); }
  size_t capacity() const;

  void push_back(Backend* backend);
  void remove(Backend* backend);

  void each(const std::function<void(Backend*)>& cb);
  void each(const std::function<void(const Backend*)>& cb) const;
  bool find(const std::string& name, const std::function<void(Backend*)>& cb);
  Backend* find(const std::string& name);

 protected:
  List cluster_;
  Scheduler* scheduler_;
};


text:
import React from 'react';
import { Link } from 'react-router';
import SearchListContainer from '../containers/search-list-container';

const Page2Layout = React.createClass({
  render: function() {
    return (

Page 2

        <SearchListContainer>
          {this.props.children}
        </SearchListContainer>

    );
  }
});

export default Page2Layout;


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

import {DeleteResourceController} from './deleteresource_controller';

/**
 * @param {!md.$dialog} mdDialog
 * @param {string} resourceKindName
 * @param {string} resourceUrl
 * @param {!backendApi.ObjectMeta} objectMeta
 * @return {!angular.$q.Promise}
 */
export default function showDeleteDialog(mdDialog, resourceKindName, resourceUrl, objectMeta) {
  return mdDialog.show({
    controller: DeleteResourceController,
    controllerAs: '$ctrl',
    clickOutsideToClose: true,
    templateUrl: 'common/resource/deleteresource.html',
    locals: {
      'resourceUrl': resourceUrl,
      'objectMeta': objectMeta,
      'resourceKindName': resourceKindName,
    },
  });
}


text:
package cars.infra.response;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import lombok.Data;

/**
 * Car Rental Data
 * Created by claudio on 07/07/17.
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CarRentalData {

  Provider provider;

  String airport;

  List<VehicleOffer> cars;

}


text:
layout: default
title: Building a Twitter App
---

This is a tutorial that will introduce the basic functionality of the
social library for Bittorrent Apps, specifically how to manage Twitter
authentication and interaction with Twitter's APIs.

For a basic introduction to Bittorrent Apps development, see the
[introduction](http://btapps-sdk.bittorrent.com/).
A tutorial introducing the bascs of the Bittorrent API can be found at:
[Media Downloader](http://github.com/bittorrent/apps-sdk/blob/master/doc/tutorials/media_downloader.md).

A complete version of the app from this tutorial can be found at:
[Twitter Example](http://github.com/bittorrent/social/tree/master/examples/twitter/).

Setup
-----
Create a new app and add the social package to the app as a dependency:

    % apps setup --name=twitter
    % cd twitter
    % apps add --file=http://staging.apps.bittorrent.com/pkgs/social.pkg

Add the following to `html/index.html` to set up all the page elements we'll need:

    <form id="login" class="out">

Log in to Twitter

        Username: <input type="text" name="username">
        Password: <input type="password" name="password">
        <button type="submit">Submit</button>
    </form>

        Log out

        <form id="update">
          <input type="text" name="status">
          <button type="submit">Post</button>
        </form>

        <form id="search">
          <input type="text" name="query">
          <button type="submit">Search</button>
        </form>

Home

Login and Logout
----------------
Front the HTML, it's easy to see how display the right page elements to the
user based on their login state; we just need to instantiate a Twitter object
to handle the actual authentication.

In `lib/index.js`, change your code to the following:

    $(document).ready(function() {
      $(".out").show();
      $(".in").hide();
      var twt = new Twitter();

      $("#login").submit(function() {
        twt.login(
          $("input[name=username]").val(),
          $("input[name=password]").val(),
          function (error) {
            if(!error){
              $("#status").html("Logged in as: " + twt.screen_name);
              $(".in").show();
              $(".out").hide();
            }
          }
        );
        return false;
      });

      $("#logout").click(function() {
        twt.logout();
        $(".in").hide();
        $(".out").show();
        return false;
      });
    });

User interaction with the login form and the logout link calls the respective
twitter login and logout functions. The login function takes the form values
as parameters, as well as a callback function. This callback will be passed a
LoginError if login is unsuccessful for any reason.

The twitter object can also automatically log a user in when we instantiate
it; it can use the same callback function as the login method:

    function show_login (error) {
      if(!error) {
        $("#status").html("Logged in as: " + twt.screen_name);
        $(".in").show();
        $(".out").hide();
        twt.timeline(1, function(statuses){
          _.each(statuses, function(status){
            $("#feed").append(status.from_user + ": " + status.text + "
");
          });
        });
      }
    }
    var twt = new Twitter(show_login);
    $("#login").submit(function() {
      twt.login(
        $("input[name=username]").val(),
        $("input[name=password]").val(),
        show_login
      );
      return false;
    });

The the timeline method in the common callback function fetches
the home timeline of the authenticated user and prints out each item; this
timeline is the same as a user would see when logged into twitter.com.

You should now be able to run the app (either via the serve or package
commands) and log in to Twitter! If you refresh the page after successfully
logging in, the app should automatically re-login to the same account for you.
You may also try generating a few LoginErrors and take a look at the
information the error provides.

Search
------
Interacting with the Twitter Search API is a simple next step. Since the event
handlers for searching and posting tweets are similar, add them both:

    $("#update").submit(function() {
      twt.post($("input[name=status]").val());
      return false;
    });
    $("#search").submit(function() {
      twt.search($("input[name=query]").val());
      return false;
    });

In order to do anything with the search results, we need to add a callback function.

    twt.search($("input[name=query]").val(), function (data) {
      $("#feed").html("");
      $("div.in h2").text("Search: " + $("input[name=query]").val());
      _.each(data.results, function(tweet){
        $("#feed").append(tweet.from_user + ": " + tweet.text + "
");
      });
    });

Try out the new search functionality; you might also take a look at the JSON
object which the search function returns as well as the result objects.

The search function can also take as a parameter an object containing
additional search options; for more information on these and the Twitter
search API in general, see the Twitter API page on
[the search method](http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-search)
(http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-search)

Post
----
By adding the event handler for the 'update' form above, we've actually fully
enabled the user to post a tweet, but it would be nice to add a callback to
show the user that their action was successful:

    $("#update").submit(function() {
      twt.post($("input[name=status]").val(), function(error){
        var msg = "A error occurred.";
        if(!error){
          msg = "Post successful.";
          if ($("div.in h2").text() === "Home") {
            $("#feed").prepend(
              twt.screen_name + ": " +
              $("input[name=status]").val() + "
"
            );
          }
          $("input[name=status]").val("");
        }
        $("#msg").text(msg).show().fadeOut(2000);
      });
      return false;
    });

The function chooses the message to display based on the existence of a
PostError; if the post was successful, the form field is cleared for the next
tweet. Additionally, if the user is looking at their home timeline, the new
tweet is prepended to it.


text:
'use strict';

angular
  .module('somafmPlayerApp', [
    //'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'config',
    'LocalStorageModule',
    'ui.router',
    'somafm.tpls',
    'jtt_aping'
  ])
  .constant('USE_HTML_AUDIO', (function () {
    var elem = document.createElement("audio");

    if( typeof elem.canPlayType == 'function' ) {
      var playable = elem.canPlayType('audio/mpeg');
      if( (playable.toLowerCase() == 'maybe') || (playable.toLowerCase() == 'probably') ) {
        return true;
      }
    }
    return false;
  })())
  .constant('POLL_INT', 30000)
  .constant('SHOP_URI', 'http://somafm.com/buy/appbuy.cgi?mode=amazon&title={SONG}&artist={ARTIST}')
  .constant('X2JS', window.X2JS)
  .constant('Audio', window.Audio)
  .constant('AudioContext', window.AudioContext)
  .config(['localStorageServiceProvider', function(localStorageServiceProvider){
    localStorageServiceProvider.setPrefix('somafm');
  }])
  .config([
    '$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
      $stateProvider
        .state('all-stations', {
          url: '/all-stations',
          data: {
            largeHeader: true
          },
          views: {
            header: {
              template: '<sf-all-stations-header></sf-all-stations-header>'
            },
            body: {
              template: '<sf-all-stations-body></sf-all-stations-body>'

            }
          }
        })
        .state('fav-stations', {
          url: '/fav-stations',
          data: {
            largeHeader: true
          },
          views: {
            header: {
              template: '<sf-fav-stations-header></sf-fav-stations-header>'
            },
            body: {
              template: '<sf-fav-stations-body></sf-fav-stations-body>'
            }
          }
        })
        .state('fav-songs', {
          url: '/fav-songs',
          data: {
            largeHeader: false
          },
          views: {
            header: {
              template: '<sf-fav-songs-header></sf-fav-songs-header>'
            },
            body: {
              template: '<sf-fav-songs-body></sf-fav-songs-body>'
            }
          }
        })
        .state('community', {
          url: '/community',
          data: {
            largeHeader: false
          },
          views: {
            header: {
              template: '<sf-community-header></sf-community-header>'
            },
            body: {
              template: '<sf-community-body></sf-community-body>'
            }
          }
        })
        .state('now-playing', {
          url: '/now-playing/:stationID',
          data: {
            largeHeader: false
          },
          views: {
            header: {
              template: '<sf-now-playing-header></sf-now-playing-header>'
            },
            body: {
              template: '<sf-now-playing-body></sf-now-playing-body>'
            }
          }
        });

      $urlRouterProvider.otherwise('/all-stations');
    }
  ]);


text:
::Chef::Recipe.send(:include, Opscode::OpenSSL::Password)
node.set_unless['mariadb']['root_password'] = secure_password
node.save

package 'mariadb-server'
package 'mariadb-devel'
resources('package[mariadb-devel]').run_action(:install)
chef_gem 'mysql'

include_recipe 'mariadb::storage'

service 'mysqld' do
	supports :status => true, :restart => true, :reload => true
	action [:enable, :start]
end

execute 'assign-root-password' do
	command "/usr/bin/mysqladmin -u root password \"#{node['mariadb']['root_password']}\""
	action :run
	notifies :restart, 'service[mysqld]'
	only_if "/usr/bin/mysql -u root -e 'show databases;'"
end

mysql_connection_info = {:host => 'localhost',
												 :username => 'root',
												 :password => node['mariadb']['root_password']}

mysql_database 'remove remote root' do
	connection mysql_connection_info
	database_name 'mysql'
	sql "DELETE FROM user WHERE user='root' AND host NOT IN ('localhost', '127.0.0.1', '::1')"
	action :query
end

mysql_database 'remove anonymous users' do
	connection mysql_connection_info
	database_name 'mysql'
	sql "DELETE FROM user WHERE user=''"
	action :query
end

mysql_database 'drop test database' do
	connection mysql_connection_info
	database_name 'mysql'
	sql "DROP DATABASE IF EXISTS test"
	action :query
end

mysql_database 'remove test database' do
	connection mysql_connection_info
	database_name 'mysql'
	sql "DELETE FROM db WHERE db='test' OR db='test\\_%'"
	action :query
end

mysql_database 'flush_privileges' do
	connection mysql_connection_info
	database_name 'mysql'
	sql 'flush privileges'
	action :query
end


text:
<?php

namespace app\models;

use dektrium\user\models\User as BaseUser;

class User extends BaseUser
{
    public function register()
    {
        // do your magic
        var_dump($this);
    }
}


text:
<?php
namespace UnitTest\Lib;
class Mockery
{
    public static function arrayInAnyOrder($expected)
    {
        $return = new Mockery\Matcher\InAnyOrderMatcher($expected);
        return $return;
    }
    public static function stringContains($expected)
    {
        $return = new Mockery\Matcher\SubstringMatcher($expected);
        return $return;
    }
}


text:
describe Agent::NodePlugger do
  let(:grid) { Grid.create!(name: 'test-grid') }
  let(:subject) { described_class.new(node) }
  let(:rpc_client) { instance_double(RpcClient) }
  let(:connected_at) { Time.now }

  before do
    allow(subject).to receive(:rpc_client).and_return(rpc_client)
  end

  context 'for an initializing node' do
    let(:node) {
      grid.create_node!('test-node', node_id: 'xyz')
    }

    before do
      expect(node.status).to eq :offline
    end

    describe '#plugin!' do
      it 'marks node as connected' do
        expect(subject).to receive(:send_node_info)

        expect {
          subject.plugin! connected_at
        }.to change{ node.reload.connected? }.to be_truthy

        expect(node.status).to eq :connecting
        expect(node.websocket_connection).to_not be_nil
        expect(node.websocket_connection.opened).to be true
        expect(node.websocket_connection.close_code).to be_nil
        expect(node.websocket_connection.close_reason).to be_nil
      end
    end

    describe '#reject!' do
      it 'marks node websocket connection as non-opened' do
        subject.reject! connected_at, 1006, "asdf"

        node.reload

        expect(node.status).to eq :offline
        expect(node.connected).to be false
        expect(node.websocket_connection).to_not be_nil
        expect(node.websocket_connection.opened).to be false
        expect(node.websocket_connection.close_code).to eq 1006
        expect(node.websocket_connection.close_reason).to eq "asdf"
      end
    end
  end

  context 'for an existing node' do
    let(:node) {
      grid.create_node!('test-node',
        node_id: 'xyz',
        labels: ['region=ams2'],
        connected: false, updated: true,
        websocket_connection: {close_code: 1337, close_reason: "fail!" },
        private_ip: '10.12.1.2', public_ip: '80.240.128.3',
      )
    }

    describe '#plugin!' do
      it 'marks node as connected and clears connection error' do
        expect(subject).to receive(:publish_update_event)
        expect(subject).to receive(:send_node_info)
        expect {
          subject.plugin! connected_at
        }.to change{ node.reload.connected? }.to be_truthy
        expect(node.status).to eq :connecting

        expect(node.websocket_connection).to_not be_nil
        expect(node.websocket_connection.close_code).to be_nil
        expect(node.websocket_connection.close_reason).to be_nil
      end
    end

    describe '#send_node_info' do
      it "sends node info" do
        expect(rpc_client).to receive(:notify).with('/agent/node_info', hash_including(
          name: 'test-node',
          grid: hash_including(
            name: 'test-grid',
          ),
        ))

        subject.send_node_info
      end
    end
  end

  context 'for a reconnected node' do
    let(:reconnected_at) { 2.seconds.ago }
    let(:connected_at) { 10.seconds.ago }
    let(:node) {
      grid.create_node!('test-node',
        node_id: 'xyz',
        labels: ['region=ams2'],
        connected: true, connected_at: reconnected_at, updated: true,
        private_ip: '10.12.1.2', public_ip: '80.240.128.3',
      )
    }

    describe '#plugin!' do
      it 'does not update node' do
        expect(subject).to_not receive(:publish_update_event)
        expect(subject).to_not receive(:send_master_info)
        expect(subject).to_not receive(:send_node_info)

        expect {
          subject.plugin! connected_at
        }.to_not change{ node.reload.connected_at }
      end
    end

    describe '#reject!' do
      it 'does not update node' do
        expect {
          subject.reject! connected_at, 1006, "asdf"
        }.to_not change{ node.reload }
      end
    end
  end
end


text:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <stdlib.h>

static void serve1(int socket_fd, struct sockaddr* to, socklen_t to_len) {
    char buf[128];
    memset(buf, 0, sizeof(buf));
    ssize_t ret = recv(socket_fd, buf, sizeof(buf)-1, 0);

    if (ret == -1) {
        if (errno == EAGAIN) {
            // Timeout, need to peck
            sendto(socket_fd, "", 0, 0, to, to_len);
        }
        return;
    }

    int fdnum=-1, val=-1, len;
    if (sscanf(buf, "%d%d", &fdnum, &val) != 2) return;

    int fd_allowed = 0;
    if (fdnum == 1) fd_allowed = 1;
    if (fdnum >= 3 && fdnum <= 1000) fd_allowed = 1;
    if (!fd_allowed) return;

    len = snprintf(buf, sizeof(buf), "%d\n", val);

    if (len <= 0 || len > sizeof(buf)) return;

    write(fdnum, buf, len);
}

int main(int argc, char* argv[]) {
    if (argc != 6) {
        fprintf(stderr, "Usage: udpfilepecker listen_addr listen_port peck_addr peck_port peck_period_sec\n");
        fprintf(stderr, "Listens UDP port, periodically pings peck_addr:peck_port, for for each incoming UDP packet of the format of two integer values 'fd_num value' it writes value to the specified FD.\n");
        fprintf(stderr, "Sample: udpfilepecker 0.0.0.0 5599 104.131.203.210 5598 30 3> /sys/class/backlight/intel_backlight/brightness\n");
        return 1;
    }

    const char* listen_addr = argv[1];
    const char* listen_port = argv[2];
    const char* peck_addr = argv[3];
    const char* peck_port = argv[4];
    const char* peck_period = argv[5];

    struct addrinfo hints;
    struct addrinfo *recv_addr;
    struct addrinfo *send_addr;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
    hints.ai_flags = AI_PASSIVE;

    int gai_error;
    gai_error=getaddrinfo(listen_addr,listen_port, &hints, &recv_addr);
    if (gai_error) { fprintf(stderr, "getaddrinfo 1: %s\n",gai_strerror(gai_error)); return 4; }
    if (!recv_addr) { fprintf(stderr, "getaddrinfo returned no addresses\n");   return 6;  }
    if (recv_addr->ai_next) {
        fprintf(stderr, "Warning: using only one of addresses retuned by getaddrinfo\n");
    }

    hints.ai_flags &= !AI_PASSIVE;
    gai_error=getaddrinfo(peck_addr, peck_port, &hints, &send_addr);
    if (gai_error) { fprintf(stderr, "getaddrinfo 2: %s\n",gai_strerror(gai_error));   return 13;  }
    if (!send_addr) { fprintf(stderr, "getaddrinfo 2 returned no addresses\n");  return 15;  }
    if (send_addr->ai_next) {
        fprintf(stderr, "Warning: using only one of addresses retuned by getaddrinfo 2\n");
    }

    int s;
    s = socket(recv_addr->ai_family, recv_addr->ai_socktype, recv_addr->ai_protocol);
    if (s == -1) { perror("socket"); return 7; }
    {
        int one = 1;
        setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
    }
    if (bind(s, recv_addr->ai_addr, recv_addr->ai_addrlen)) {  perror("bind");  return 5;  }

    struct timeval tv;
    tv.tv_sec = atoi(peck_period);
    tv.tv_usec = 0;
    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

    mlockall(MCL_CURRENT|MCL_FUTURE);
    nice(-19);

    for(;;) {
        serve1(s, send_addr->ai_addr, send_addr->ai_addrlen);
    }

    return 0;
}


text:
**Go to:**      [**Root TOC**](CM-Well.RootTOC.md)      [**Topic TOC**](API.TOC.md)      [**Previous Topic**](API.UsingTheWith-dataFlag.md)     [**Next Topic**](API.UsingTheWith-deletedFlag.md)

----

Each time a CM-Well infoton is updated, a "historical" copy of it is saved, and its URL (which serves as a "virtual link") is updated to point to the most recent version.

Each version of the infoton has a "point in time URL", which is a unique URL pointing to that particular version.

For example, this is what we see when retrieving the default (latest) version of an infoton:

And this is what we see when retrieving the same infoton, using the with-history flag:

Note that the infoton has 12 historical versions (the image shows only one page of results).

----

**Go to:**      [**Root TOC**](CM-Well.RootTOC.md)      [**Topic TOC**](API.TOC.md)      [**Previous Topic**](API.UsingTheWith-dataFlag.md)     [**Next Topic**](API.UsingTheWith-deletedFlag.md)

----


text:
package org.apache.spark.examples.mllib

import scala.collection.mutable

import org.apache.log4j.{Level, Logger}
import scopt.OptionParser

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.SparkContext._
import org.apache.spark.mllib.recommendation.{ALS, MatrixFactorizationModel, Rating}
import org.apache.spark.rdd.RDD

/**
 * An example app for ALS on MovieLens data (http://grouplens.org/datasets/movielens/).
 * Run with
 * {{{
 * bin/run-example org.apache.spark.examples.mllib.MovieLensALS
 * }}}
 * A synthetic dataset in MovieLens format can be found at `data/mllib/sample_movielens_data.txt`.
 * If you use it as a template to create your own app, please use `spark-submit` to submit your app.
 */
object MovieLensALS {

  case class Params(
      input: String = null,
      kryo: Boolean = false,
      numIterations: Int = 20,
      lambda: Double = 1.0,
      rank: Int = 10,
      numUserBlocks: Int = -1,
      numProductBlocks: Int = -1,
      implicitPrefs: Boolean = false) extends AbstractParams[Params]

  def main(args: Array[String]) {
    val defaultParams = Params()

    val parser = new OptionParser[Params]("MovieLensALS") {
      head("MovieLensALS: an example app for ALS on MovieLens data.")
      opt[Int]("rank")
        .text(s"rank, default: ${defaultParams.rank}}")
        .action((x, c) => c.copy(rank = x))
      opt[Int]("numIterations")
        .text(s"number of iterations, default: ${defaultParams.numIterations}")
        .action((x, c) => c.copy(numIterations = x))
      opt[Double]("lambda")
        .text(s"lambda (smoothing constant), default: ${defaultParams.lambda}")
        .action((x, c) => c.copy(lambda = x))
      opt[Unit]("kryo")
        .text("use Kryo serialization")
        .action((_, c) => c.copy(kryo = true))
      opt[Int]("numUserBlocks")
        .text(s"number of user blocks, default: ${defaultParams.numUserBlocks} (auto)")
        .action((x, c) => c.copy(numUserBlocks = x))
      opt[Int]("numProductBlocks")
        .text(s"number of product blocks, default: ${defaultParams.numProductBlocks} (auto)")
        .action((x, c) => c.copy(numProductBlocks = x))
      opt[Unit]("implicitPrefs")
        .text("use implicit preference")
        .action((_, c) => c.copy(implicitPrefs = true))
      arg[String]("<input>")
        .required()
        .text("input paths to a MovieLens dataset of ratings")
        .action((x, c) => c.copy(input = x))
      note(
        """
          |For example, the following command runs this app on a synthetic dataset:
          |
          | bin/spark-submit --class org.apache.spark.examples.mllib.MovieLensALS \
          |  examples/target/scala-*/spark-examples-*.jar \
          |  --rank 5 --numIterations 20 --lambda 1.0 --kryo \
          |  data/mllib/sample_movielens_data.txt
        """.stripMargin)
    }

    parser.parse(args, defaultParams).map { params =>
      run(params)
    } getOrElse {
      System.exit(1)
    }
  }

  def run(params: Params) {
    val conf = new SparkConf().setAppName(s"MovieLensALS with $params")
    if (params.kryo) {
      conf.registerKryoClasses(Array(classOf[mutable.BitSet], classOf[Rating]))
        .set("spark.kryoserializer.buffer", "8m")
    }
    val sc = new SparkContext(conf)

    Logger.getRootLogger.setLevel(Level.WARN)

    val implicitPrefs = params.implicitPrefs

    val ratings = sc.textFile(params.input).map { line =>
      val fields = line.split("::")
      if (implicitPrefs) {
        /*
         * MovieLens ratings are on a scale of 1-5:
         * 5: Must see
         * 4: Will enjoy
         * 3: It's okay
         * 2: Fairly bad
         * 1: Awful
         * So we should not recommend a movie if the predicted rating is less than 3.
         * To map ratings to confidence scores, we use
         * 5 -> 2.5, 4 -> 1.5, 3 -> 0.5, 2 -> -0.5, 1 -> -1.5. This mappings means unobserved
         * entries are generally between It's okay and Fairly bad.
         * The semantics of 0 in this expanded world of non-positive weights
         * are "the same as never having interacted at all".
         */
        Rating(fields(0).toInt, fields(1).toInt, fields(2).toDouble - 2.5)
      } else {
        Rating(fields(0).toInt, fields(1).toInt, fields(2).toDouble)
      }
    }.cache()

    val numRatings = ratings.count()
    val numUsers = ratings.map(_.user).distinct().count()
    val numMovies = ratings.map(_.product).distinct().count()

    println(s"Got $numRatings ratings from $numUsers users on $numMovies movies.")

    val splits = ratings.randomSplit(Array(0.8, 0.2))
    val training = splits(0).cache()
    val test = if (params.implicitPrefs) {
      /*
       * 0 means "don't know" and positive values mean "confident that the prediction should be 1".
       * Negative values means "confident that the prediction should be 0".
       * We have in this case used some kind of weighted RMSE. The weight is the absolute value of
       * the confidence. The error is the difference between prediction and either 1 or 0,
       * depending on whether r is positive or negative.
       */
      splits(1).map(x => Rating(x.user, x.product, if (x.rating > 0) 1.0 else 0.0))
    } else {
      splits(1)
    }.cache()

    val numTraining = training.count()
    val numTest = test.count()
    println(s"Training: $numTraining, test: $numTest.")

    ratings.unpersist(blocking = false)

    val model = new ALS()
      .setRank(params.rank)
      .setIterations(params.numIterations)
      .setLambda(params.lambda)
      .setImplicitPrefs(params.implicitPrefs)
      .setUserBlocks(params.numUserBlocks)
      .setProductBlocks(params.numProductBlocks)
      .run(training)

    val rmse = computeRmse(model, test, params.implicitPrefs)

    println(s"Test RMSE = $rmse.")

    sc.stop()
  }

  /** Compute RMSE (Root Mean Squared Error). */
  def computeRmse(model: MatrixFactorizationModel, data: RDD[Rating], implicitPrefs: Boolean)
    : Double = {

    def mapPredictedRating(r: Double): Double = {
      if (implicitPrefs) math.max(math.min(r, 1.0), 0.0) else r
    }

    val predictions: RDD[Rating] = model.predict(data.map(x => (x.user, x.product)))
    val predictionsAndRatings = predictions.map{ x =>
      ((x.user, x.product), mapPredictedRating(x.rating))
    }.join(data.map(x => ((x.user, x.product), x.rating))).values
    math.sqrt(predictionsAndRatings.map(x => (x._1 - x._2) * (x._1 - x._2)).mean())
  }
}


text:
package ch.ethz.globis.phtree.v8;

/**
 * Interface for PhIterator checkers. A checker is continuously checked
 * during navigation to see whether subnodes or postfixes should be traversed.
 *
 *
 * @author Tilmann Zäschke
 *
 * @param <T> The value type of the tree
 *
 */
public interface PhTraversalChecker<T> {

	boolean isValid(long[] key);

	boolean isValid(Node<T> node, long[] prefix);

}


text:
author: elliott
layout: post
title: Updating your Repo by Merging on Github.com
categories: how-to exercise
---

{% include ghmerging %}


text:
/**
 * Define the Tabber internal types and classes which are not exposed to the
 * popup UI, but still need to be name-protected or type checked inside Tabber.
 * @fileoverview
 */

/**
 * Define the TabberInt object which defines the internal types and methods.
 * @interface
 */
function TabberInt() {}

/**
 * Define Tab object fields we care about. The only required fields are the
 * url and the index (which are also the only ones that can be specified to
 * chrome when creating a new tab).
 * @typedef {{
 *  url: string,
 *  index: string,
 *  id: (string|undefined),
 *  windowId: (number|undefined),
 *  active: (boolean|undefined),
 *  title: (string|undefined)
 * }}
 */
TabberInt.type.Tab;

/**
 * Define tabdiff object fields.
 * @typedef {{
 *   major: string,
 *   minor: string,
 *   err: boolean
 * }}
 */
TabberInt.type.TabDiff;

/**
 * Define the TabberSession object which holds saved tabs data.
 * @interface
 */
TabberInt.TabberSession = function() {};

/** @type {string} */
TabberInt.TabberSession.prototype.description;

/** @type {number} */
TabberInt.TabberSession.prototype.generation;

/** @type {Object|number} */
TabberInt.TabberSession.prototype.numtabs;

/** @type {Array<TabberInt.type.Tab>} */
TabberInt.TabberSession.prototype.tabs;

/** @type {number|boolean} */
TabberInt.TabberSession.prototype.updateTime;

/**
 * Helper to print session info to console.
 * @param {string} label - Label to tag the output with.
 */
TabberInt.TabberSession.prototype.printSession = function(label) {};

/**
 * Return the last touch time as a user string. If this session has not yet
 * been initialized, it returns an empty string.
 * @return {string}
 */
TabberInt.TabberSession.prototype.getTimeString = function() {};


text:
//
//  MainViewController.m
//  RongCloudDemo
//
//  Created by 秦启飞 on 2016/12/25.
//  Copyright © 2016年 dlz. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //隐藏返回按钮navigationController的navigationBar
    self.navigationController.navigationBarHidden=YES;
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewDidAppear:(BOOL)animated{

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
@class PublicModel;

@interface ShowPicVC : UIViewController

@property (nonatomic, weak) PublicModel * model;

@end


text:
require 'mock_web_service'

include MockWebService

host_name = '0.0.0.0'
port = 1925
endpoint = '/endpoint/to/test'
response_body = 'OK!!!'

url = "http://#{host_name}:#{port}"
full_path = "#{url}#{endpoint}"
test_path = "#{full_path}?query=test"

describe MockWebService do
  before :each do
    mock.start host_name, port
  end

  after :each do
    mock.stop
  end

  it 'should match a url without specifying a querystring while requesting with one' do
    # set up mock endpoint
    mock.get endpoint do |request|
      expect(request.query).to eql 'query' => 'test'
      [200, response_body]
    end

    # make HTTP request to API
    response = HTTParty.get test_path

    # assert response code 200
    expect(response.code).to be 200

    request = mock.log(:get, endpoint).last

    # assert query is equal to expected
    expect(request.query).to eql 'query' => 'test'

    # assert response body is equal to expected
    expect(response.body).to eql 'OK!!!'
  end
end


text:
package org.uncertml.distribution.continuous;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;

import org.uncertml.util.Validate;

/**
 * Class representing a log-normal distribution with log-scale and shape parameters.
 *
 * {@URL https://wiki.aston.ac.uk/foswiki/bin/view/UncertWeb/LogNormal}
 *
 * @author Matthew Williams
 * @version 2.0
 */
public class LogNormalDistribution implements IContinuousDistribution {

    private List<Double> logScale;
    private List<Double> shape;

    /**
     * Constructor that takes a single log-scale and shape parameter.
     *
     * @param logScale the log-scale parameter.
     * @param shape the shape parameter.
     */
    public LogNormalDistribution(double logScale, double shape) {
        this(new double[]{logScale}, new double[]{shape});
    }

    /**
     * Constructor that takes an array of doubles for the log-scale and shape parameters.
     * Each log-scale and scale pair represents a unique log-normal distribution.
     * This is in line with the UncertML syntax whereby a collection of types can
     * be represented by a single entity. The arrays must be of equal length.
     *
     * @param logScale an array of doubles representing the log-scale parameter of n
     * log-normal distributions.
     * @param shape an array of doubles representing the shape parameter of n
     * log-normal distributions.
     */
    public LogNormalDistribution(double[] logScale, double[] shape) {
        this(Arrays.asList(ArrayUtils.toObject(logScale)), Arrays.asList(ArrayUtils.toObject(shape)));
    }

    /**
     * Constructor that takes a list of doubles for the log-scale and shape parameters.
     * Each log-scale and scale pair represents a unique log-normal distribution.
     * This is in line with the UncertML syntax whereby a collection of types can
     * be represented by a single entity. The lists must be of equal length and
     * must not contain any null elements.
     *
     * @param logScale a list of doubles representing the log-scale parameter of n
     * log-normal distributions.
     * @param shape a list of doubles representing the shape parameter of n
     * log-normal distributions.
     */
    public LogNormalDistribution(List<Double> logScale, List<Double> shape) {
        Validate.notNull(logScale);
        Validate.notNull(shape);
        Validate.noNullElements(logScale);
        Validate.noNullElements(shape);
        Validate.allElementsGreaterThan(shape, 0.0);
        Validate.allListsEqualLength(new List<?>[]{logScale, shape});
        this.logScale = new ArrayList<Double>(logScale);
        this.shape = new ArrayList<Double>(shape);
    }

    /**
     *
     * @return the log-scale parameter of each log-normal distribution represented
     * by this object.
     */
    public List<Double> getLogScale() {
        return this.logScale;
    }

    /**
     *
     * @return the shape parameter of each log-normal distribution represented
     * by this object.
     */
    public List<Double> getShape() {
        return this.shape;
    }

}


text:
<?php

################################################################################
#                                                                              #
#		Filename:	allocate_products.php			       #
#		Author:		Martin Settle				       #
#               Created:	21 September 2006			       #
#		Description:	allocate deliveries to customers	       #
#		Calls:		config.php.inc				       #
#		Called by:	nothing					       #
#									       #
#   Copyright 2010 Trellis Ltd
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
################################################################################

/*
MODIFICATION HISTORY
	- 2006.09.21 file created
	- 2008-04-04 make redundant entry in product_calendar

*/

if(empty($CoopName))
{
	session_start();

	if(empty($_SESSION['member_id']))
	{
		header ("Location:../index.php");
		exit();
		}
	elseif(empty($_SESSION['admin']))
	{
		header ("Location:index.php");
		exit();
		}

	header ("Cache-control: private");

	$Secure = 1;
	include '../config.php';
	}

if(empty($_POST['PROCESS']))
{
	// get confirmation of delivery numbers
	$smarty->assign('pagetitle','Confirm Delivery');
	$smarty->assign('products',$_POST['products']);
	include ("../header.php");
	include ("../footer.php");
	$smarty->display('confirm_delivery.tpl');

/*	foreach($_POST['products'] as $key => $value)
	{
		foreach($value as $k => $v)
		{
			print ($k . ": ");
	        	print ($v . "
");
			}
		}
*/
	exit();
}

foreach($_POST['delivered'] as $product_id => $delivered)
{
	//get current stock
	if(empty($delivered)) $delivered = 0;
	$stocklookup = mysql_query("SELECT IFNULL(product_current_stock,0) as product_current_stock, product_case_size FROM product WHERE product_id = $product_id");
	$currentstock = mysql_result($stocklookup,0,'product_current_stock');
	$case_size = mysql_result($stocklookup,0,'product_case_size');
	$delivery = $delivered * $case_size;
	//rough check for rounding errors:
	$round_check = mysql_query("SELECT IF(ABS({$delivery} - purchase_quantity) < 0.1, purchase_quantity,{$delivery}) AS delivered
					FROM product_calendar WHERE product_id = {$product_id}
					AND order_date = '{$_SESSION['admin_date']}'");
	$delivery = mysql_result($round_check,0,'delivered');
	$unallocated = $delivery + $currentstock;

	// get the orders
	$orders_query = mysql_query("SELECT order_id, order_quantity_requested FROM orders WHERE order_product_id = $product_id AND order_date = '$_SESSION[admin_date]' ORDER BY order_time ASC");
	while($orders = mysql_fetch_array($orders_query))
	{
		if($orders['order_quantity_requested'] <= $unallocated)
		{
			mysql_query("UPDATE orders SET order_quantity_delivered = order_quantity_requested WHERE order_id = $orders[order_id]");
			$unallocated = $unallocated - $orders['order_quantity_requested'];
			}
		else
		{
			mysql_query("UPDATE orders SET order_quantity_delivered = $unallocated WHERE order_id = $orders[order_id]");
			$unallocated = 0;
			}
		}
	// set up or update the supplier_accounts transaction
	$details_lookup = mysql_query("SELECT current_price, product_VAT_rate FROM product, product_calendar
									WHERE product.product_id = product_calendar.product_id
									AND order_date = '{$_SESSION['admin_date']}'
									AND product.product_id = {$product_id}");
	$VAT_rate = mysql_result($details_lookup,0,'product_VAT_rate');
	$current_price = mysql_result($details_lookup,0,'current_price');
	$transaction_id_lookup = mysql_query("SELECT transaction_id FROM supplier_accounts
										WHERE supplier_id = (SELECT product_supplier_id FROM product WHERE product_id = {$product_id})
										AND transaction_date = '{$_SESSION['admin_date']}'
										AND transaction_reference LIKE 'Goods Delivered'");
	if(mysql_num_rows($transaction_id_lookup) != 0)
	{
		$transaction_id = mysql_result($transaction_id_lookup,0,'transaction_id');
		mysql_query("UPDATE supplier_accounts SET transaction_value = IFNULL(transaction_value,0) + {$delivered} * {$case_size} * {$current_price},
					transaction_VAT = IFNULL(transaction_VAT,0) + {$delivered} * {$case_size} * {$current_price} * {$VAT_rate}
					WHERE transaction_id = {$transaction_id}");
		}
	else
	{
		mysql_query("INSERT INTO supplier_accounts
					SET supplier_id = (SELECT product_supplier_id FROM product WHERE product_id = {$product_id}),
					transaction_date = '{$_SESSION['admin_date']}',
					transaction_reference = 'Goods Delivered',
					transaction_value = {$delivered} * {$case_size} * {$current_price},
					transaction_VAT = {$delivered} * {$case_size} * {$current_price} * {$VAT_rate}");
		print mysql_error();
		$transaction_id = mysql_insert_id();

		}

	// update the product_calendar delivered field
	mysql_query("UPDATE product_calendar SET delivered_quantity = {$delivery}, transaction_id = {$transaction_id} WHERE product_id = {$product_id} AND order_date = '{$_SESSION['admin_date']}'");
	mysql_query("UPDATE product SET product_current_stock = $unallocated WHERE product_id = $product_id");
	}

include '../header.php';
$smarty->assign('pagetitle','Delivery Allocated');
$smarty->assign('body_text','The delivery has been allocated to customer orders.
If deliveries from all suppliers have been received you may now process sorting data');
include '../footer.php';

$smarty->display('index.tpl');

?>


text:
const lp_Integral = 1;					// solve using integers?
const lp_Fraction = lp_Integral+1;		// using fractions?
const lp_Decimal = lp_Fraction+1;		// using decimals?

// lp status
const lp_no_problem = 0;				// no problem, yet
const lp_parsed = lp_no_problem+1;		// parsed a problem
const lp_phase1 = lp_parsed+1;			// done with Phase I
const lp_phase2 = lp_phase1+1;			// done with Phase II
const lp_optimal = lp_phase2+1;			// completely done - not necessarily Phase II for integer programming
const lp_no_solution = lp_optimal+1;	// no solution, don't continue

// verbosity level
const lp_verbosity_none = 0;			// how verbose should we be?
const lp_verbosity_tableaus = lp_verbosity_none + 1;		// show all tableaus
const lp_verbosity_solutions = lp_verbosity_tableaus + 1;	// tableaus and intermediate solutions

// globals
var lp_verboseLevel = lp_verbosity_none;
var lp_reportErrorsTo = "";  			// empty if default reporting, "alert" or id of	an html element
var lp_trace_string = "";				// string that will contain the tableaus, solutions, etc.

// error messages (should be reassignable by a parent container - eg in Spanish - so these are not consts)
var lp_noLPErr = "No LP problem given";
var lp_IllegCharsErr = "Illegal characters";
var lp_UnspecMaxMinErr = "Max or min not specified";
var lp_noRelationConstrErr = "Constraints must contain '=', '<=', or '>='";
var lo_tooManyTabloeausErr = "Number of tableaus exceeds ";
var lp_emptyFeasibleRegionErr = "No solution; feasible region empty";
var lp_noMaxErr = "No maximum value; the objective function can be arbitrarily large";
var lp_noMinErr = "No minimum value; the objective function can be arbitrarily large negative";
var lp_phase2TooSoonErr = "Attempting to do Phase 2 when Phase 1 is not complete.";
var lp_badExprErr = "Something's wrong in the expression ";
var lp_illegalCoeffErr = "illegal coefficient of ";
var lp_inExprErr = " in the expression\n";
var lp_objNotSetErr = "Objective not set in extractUnknowns";
var lp_noNiceSolutionErr = "No solution with the desired integer values exists"

// Setting up an lpProblem
// Do one of the following:
//   1) Supply an existing lpProblem when constructing the object
//   2) Set problemStr to a whole LP problem
//		For integer/mixed problems, add "integer x,y,z" as last line with unknowns that should be integer
//   3) Set objective to the object function, as a string of the form
//         "[max|min]inmize var = linear expression" and
//      Set constraints to an array of constraints of the form
//         "linear expr <=, >=, or = number"
//   4) Set maximize, objectiveName, unknowns, and numActualUnknowns, and
//      set tableaus to a one element array containing the first tableau
//
// Once the problem is set up, call solve().
//
// Success is indicated by this.status, which could be lp_optimal or lp_no_solution.
//
// For ordinary LP problems, solutions, including all intermediate steps, are available
// 		in this.objectiveValues and this.solutions, with tableaus in this.tableaus
//		Use the appropriate formatXXX() routine to get them nicely rounded and formatted.
//
// For integer LP problems, the actual solution is available in
// 		this.integerSolution and this.integerObjValue.
//		Use formatIntegerXXX() to get them nicely formatted.

class lpProblem
{
	constructor ( problem = null ) {
			// linear expression to optimize
		this.objective = (problem != null && typeof problem.objective == 'string')
							? problem.objective : "";

			// array of constraints, linear expr <=, >=, or = number
		this.constraints = (problem != null && Array.isArray(problem.constraints))
							? problem.constraints.slice() : [];

			// integer/mixed programming?
		this.isIntegral = (problem != null && typeof problem.isIntegral == 'boolean')
							? problem.isIntegral : false;

			// solve using integers, fractions, or decimals?
		this.mode = (problem != null && typeof problem.mode == 'number')
							? problem.mode : lp_Decimal;

			// false for minimize
		this.maximize = (problem != null && typeof problem.maximize == 'boolean')
							? problem.maximize : true;

			// either supplied with string problem or generated
		this.objectiveName = (problem != null && typeof problem.objectiveName == 'string')
							? problem.objectiveName : "Obj";

			// array of names of unknowns (includes slack/surplus variables)
		this.unknowns = (problem != null && Array.isArray(problem.unknowns))
							? problem.unknowns.slice() : [];

			// array of unknowns for which integer values are required (mixed programming)
		this.integerUnknowns = (problem != null && Array.isArray(problem.integerUnknowns))
							? problem.integerUnknowns.slice() : [];
			// whether or not to show the values of the slack and surplus variables in the solution
		this.showArtificialVariables = false;
			// initial matrix of system, a la Ax >= b.
			// doesn't need to be copied, as it won't change if already filled in
		this.systemMatrix = (problem != null && Array.isArray(problem.systemMatrix))
							? problem.systemMatrix : [];

		this.systemRowIsStarred = (problem != null && Array.isArray(problem.systemRowIsStarred))
							? problem.systemRowIsStarred : [];

			// same for right hand sides of constraints
		this.constraintRHS = (problem != null && Array.isArray(problem.constraintRHS))
							? problem.constraintRHS : [];

			// similar for objective function
		this.objectiveCoeffs = (problem != null && Array.isArray(problem.objectiveCoeffs))
							? problem.objectiveCoeffs : [];

			// additional constraints used in integer programming, indexed like integerUnknowns
		this.integerMins = (problem != null && Array.isArray(problem.integerMins))
							? problem.integerMins.slice() : [];
		this.integerMaxs = (problem != null && Array.isArray(problem.integerMaxs))
							? problem.integerMaxs.slice() : [];

			// how many original unknowns?
		this.numActualUnknowns = (problem != null && typeof problem.numActualUnknowns == 'number')
							? problem.numActualUnknowns : 0;

		this.rowIsStarred = [];			// ith entry is true if i row is starred

		this.tableaus = [];				// array of tableaus
		this.tableauDimensions = [];	// number of rows, number of columns
		this.maxNumTableaus=50;			// quite arbitrary make it a setting if associated error is thrown

		this.status = lp_no_problem;	// are we there yet?

		this.solutions = [];			// array of intermediate solutions
		this.objectiveValues = [];		// array of intermediate objective values
		this.error = "";				// error message for badly set up problem etc
		this.message = "";				// message when there is no solution for one reason or another

		this.integerSolution = [];		// used to return solution to integer programming problems
		this.integerObjValue = 0;

		this.problemStr = (problem != null && typeof problem == 'string') ? problem : "";

		// settings
		this.maxSigDigits = 13;			// try to push to 16 but issues with roundSigDig which internally uses three more
		this.sigDigits = 6;				// user specified for rounding of tableaus and results

	}

	// Functions

	solve ( ) {}								// solve it, return true if succeeded

	formatObjectiveValues ( mode = 0 ) {}			// return array of objective values, in proper form

	formatLastObjectiveValue ( mode = 0 ) {}		// same, just the last value

											// return array of unknowns, with or w/o slack vars
	formatUnknowns ( includeSlackVariables = false ) {}

											// use this to get the solutions, in proper form,
											// with or w/o slack vars
											// mode defaults to setting of this.mode
											// returns an array of arrays, each in order of unknowns
	formatSolutions ( includeSlackVariables = false, mode = 0 ) {}

											// same, but just last solution, not all intermediates
	formatLastSolution ( includeSlackVariables = false, mode = 0 ) {}

											// use these to get the integer solution when doing ILP
	formatIntegerObjectiveValue ( mode = 0) {}
	formatIntegerSolution ( includeSlackVariables = false ) {}

											// return string showing values of vars in last or integer solution,
											// using settings of showArtificialVariables & mode
	solutionToString () {}
											// same, but shows last solution, even if doing ILP
	lastSolutionToString () {}
}

// tableau class is a subclass of Array
// The 0th row and column contain labels
// The entries of the tableau itself are indexed from [1][1]
//
class tableau extends Array
{
	constructor ( arr = [] ) {			// construct from a given 2D array or tableau
		super();
		for ( var i = 0; i < arr.length; i++ )
			this[i] = arr[i].slice();
	}

	pivot ( pRow, pCol, sigDigs ) {}	// pivot, return a new tableau

	toString ( theMode, sigDigs ) {}	// returns an ascii formatted string representing the tableau

	toHTML ( theMode, sigDigs , params) {}		// returns an HTML table representing the tableau
}


text:
class PoolSvrEvtHandler : public apache::thrift::server::TServerEventHandler {
public:
    PoolSvrEvtHandler(std::shared_ptr<apache::thrift::concurrency::ThreadManager> thread_man,
                     unsigned int thread_min, unsigned int thread_max) :
        t_man(thread_man), t_min(thread_min), t_max(thread_max)
    {;}

    std::string stats(int reduce_in_use_by=0) {
       std::stringstream ss;
       ss << "(threads in use: " << t_man->workerCount() - t_man->idleWorkerCount() - reduce_in_use_by
          << "/" << t_man->workerCount() << " - connections waiting: " << t_man->pendingTaskCount() << ")";
       return ss.str();
    }

    virtual void preServe() override {
        std::cout << "  preServe " << stats() << std::endl;
    }

    virtual void* createContext(std::shared_ptr<apache::thrift::protocol::TProtocol> in,
                                std::shared_ptr<apache::thrift::protocol::TProtocol> out) override {
        std::cout << "  create   " << stats() << std::endl;
        if (t_man->idleWorkerCount() == 0 && t_man->workerCount() < t_max) {
            t_man->addWorker();
            std::cout << "    No idle threads, added a new worker thread\n           " << stats() << std::endl;
        }
        return new int(0);
    }

    virtual void deleteContext(void* svr_ctx,
                               std::shared_ptr<apache::thrift::protocol::TProtocol> in,
                               std::shared_ptr<apache::thrift::protocol::TProtocol> out) override {
        std::cout << "  delete   " << stats(1) << std::endl;
        if (t_man->idleWorkerCount() >= t_man->workerCount()/2 && t_man->workerCount() > t_min) {
            t_man->removeWorker();
            std::cout << "    Too many idle threads, deleted a worker thread\n           " << stats(1) << std::endl;
        }
        int * pCallCount = reinterpret_cast<int *>(svr_ctx);
        delete pCallCount;
    }

    virtual void processContext(void* svr_ctx, std::shared_ptr<apache::thrift::transport::TTransport> trans) override {
        int * call_count = reinterpret_cast<int *>(svr_ctx);
        std::cout << "    Client call #" << ++(*call_count) << std::endl;
    }

private:
    std::shared_ptr<apache::thrift::concurrency::ThreadManager> t_man;
    unsigned int t_min;
    unsigned int t_max;
};

#endif //_MY_SERVER_EVENT_HANDLER_H_


text:
#ifndef __XF_PEER_H
#define __XF_PEER_H

#include <freerdp/codec/rfx.h>
#include <freerdp/listener.h>
#include <freerdp/utils/stream.h>

#include "xfreerdp.h"

struct xf_peer_context
{
	rdpContext _p;

	STREAM* s;
	xfInfo* info;
	boolean activated;
	RFX_CONTEXT* rfx_context;
};
typedef struct xf_peer_context xfPeerContext;

void xf_peer_accepted(freerdp_listener* instance, freerdp_peer* client);

#endif /* __XF_PEER_H */


text:
package amery.jdk.basic;

/**
 * Created by ahan on 15/05/2017.
 */
public class StackSize {

    private int size = 1;

    public void stackLeak() {
        size++;
        stackLeak();
    }

    public static void main(String[] args) throws Throwable {
        StackSize gg = new StackSize();
        try {
            gg.stackLeak();
        } catch (Throwable e) {
            System.out.println(gg.size);
            throw e;
            //e.printStackTrace();
        }
    }
}


text:
"""Treadmill node bootstrap.
"""

import pkgutil

from .. import aliases

__path__ = pkgutil.extend_path(__path__, __name__)

DEFAULTS = {
    'treadmill_host_ticket': None,
    'treadmill_cpu': None,
    'treadmill_cpu_cores': None,
    'treadmill_mem': None,
    'treadmill_core_mem': None,
    'localdisk_img_location': None,
    'localdisk_img_size': None,
    'localdisk_block_dev': None,
    'localdisk_default_read_bps': None,
    'localdisk_default_read_iops': None,
    'localdisk_default_write_bps': None,
    'localdisk_default_write_iops': None,
}

ALIASES = aliases.ALIASES


text:
package execution

import (
	"encoding/json"
	"fmt"
	"reflect"
	"time"

	"github.com/golang/protobuf/ptypes"
	"github.com/golang/protobuf/ptypes/any"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/genproto/googleapis/longrunning"
	"google.golang.org/genproto/googleapis/rpc/code"
	"google.golang.org/genproto/googleapis/rpc/status"

	"github.com/twitter/scoot/bazel"
	"github.com/twitter/scoot/bazel/remoteexecution"
	"github.com/twitter/scoot/common/proto"
)

// Parse a generic longrunning.Operation structure into expected Execution API components.
// Deserializes Operation.Metadata as an ExecuteOperationMetadata always.
// Checks for Operation.Result as a Response and if found deserializes as an ExecuteResponse.
// Per Bazel API, does not check for Operation.Result as a GRPC Status/Error - not allowed.
func ParseExecuteOperation(op *longrunning.Operation) (*remoteexecution.ExecuteOperationMetadata,
	*status.Status, *remoteexecution.ExecuteResponse, error) {
	if op == nil {
		return nil, nil, nil, fmt.Errorf("Attempting to parse nil Operation")
	}

	eom := &remoteexecution.ExecuteOperationMetadata{}
	err := ptypes.UnmarshalAny(op.GetMetadata(), eom)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("Error deserializing metadata as ExecuteOperationMetadata: %s", err)
	}

	st := op.GetError()
	if op.GetResponse() == nil {
		return eom, st, nil, nil
	}

	res := &remoteexecution.ExecuteResponse{}
	err = ptypes.UnmarshalAny(op.GetResponse(), res)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("Error deserializing response as ExecuteResponse: %s", err)
	}
	return eom, st, res, nil
}

// TODO - used by bazel-integration, may be possible to replace with OperationToJson via bzutil and remove this
// JSON unmarshalling doesn't work for Operations with nested Results, as they're of unexported type isOperation_Result.
// Thus, we need custom unmarshalling logic.
func ExtractOpFromJson(opBytes []byte) (*longrunning.Operation, error) {
	var opMapTemplate interface{}
	err := json.Unmarshal(opBytes, &opMapTemplate)
	if err != nil {
		return nil, err
	}
	opMap := opMapTemplate.(map[string]interface{})
	op := &longrunning.Operation{}
	for key, val := range opMap {
		switch key {
		case "name":
			if name, ok := val.(string); !ok {
				return nil, deserializeErr("name", "string", val)
			} else {
				op.Name = name
			}
		case "metadata":
			metadata := &any.Any{}
			if metadataMap, ok := val.(map[string]interface{}); ok {
				for mKey, mVal := range metadataMap {
					switch mKey {
					case "type_url":
						if typeUrl, ok := mVal.(string); !ok {
							return nil, deserializeErr("type_url", "string", mVal)
						} else {
							metadata.TypeUrl = typeUrl
						}
					case "value":
						if value, ok := mVal.(string); !ok {
							return nil, deserializeErr("value", "string", mVal)
						} else {
							metadata.Value = []byte(value)
						}
					}
				}
				op.Metadata = metadata
			}
		case "done":
			if done, ok := val.(bool); !ok {
				return nil, deserializeErr("done", "bool", val)
			} else {
				op.Done = done
			}
		case "Result":
			if opResultMap, ok := val.(map[string]interface{}); ok {
				for resultKey, resultVal := range opResultMap {
					switch resultKey {
					case "Error":
						opErrorStatus := &status.Status{}
						opError := &longrunning.Operation_Error{
							Error: opErrorStatus,
						}
						op.Result = opError
						if errorMap, ok := resultVal.(map[string]interface{}); ok {
							for errKey, errVal := range errorMap {
								switch errKey {
								case "code":
									if code, ok := errVal.(float64); !ok {
										return nil, deserializeErr("code", "float64", errVal)
									} else {
										opErrorStatus.Code = int32(code)
									}
								case "message":
									if message, ok := errVal.(string); !ok {
										return nil, deserializeErr("message", "string", errVal)
									} else {
										opErrorStatus.Message = message
									}
								}
							}
						}
					case "Response":
						opResponseAny := &any.Any{}
						opResponse := &longrunning.Operation_Response{
							Response: opResponseAny,
						}
						op.Result = opResponse
						if responseMap, ok := resultVal.(map[string]interface{}); ok {
							for responseKey, responseVal := range responseMap {
								switch responseKey {
								case "type_url":
									if typeUrl, ok := responseVal.(string); !ok {
										return nil, deserializeErr("type_url", "string", responseVal)
									} else {
										opResponseAny.TypeUrl = typeUrl
									}
								case "value":
									if value, ok := responseVal.(string); !ok {
										return nil, deserializeErr("value", "string", responseVal)
									} else {
										opResponseAny.Value = []byte(value)
									}
								}
							}
						}
					}
				}
			}
		}
	}
	return op, nil
}

// Converts a longrunning.Operation to a Json-encoded []byte. Because an Operation's Result field is not
// natively compatible with json.Marshal, this does the minimum necessary extraction of nested data and
// wrapping with custom types so that it can be used with Marshal.
func OperationToJson(op *longrunning.Operation) ([]byte, error) {
	if op == nil {
		return nil, nil
	}

	eom, st, res, err := ParseExecuteOperation(op)
	if err != nil {
		return nil, err
	}

	ow := &operationWrapper{
		Name:     op.GetName(),
		Metadata: eom,
		Done:     op.GetDone(),
		Result: &operationResultWrapper{
			Error:    st,
			Response: res,
		},
	}
	return json.Marshal(ow)
}

type operationWrapper struct {
	Name     string                                    `json:"name"`
	Metadata *remoteexecution.ExecuteOperationMetadata `json:"metadata"`
	Done     bool                                      `json:"done"`
	Result   *operationResultWrapper
}

type operationResultWrapper struct {
	Error    *status.Status
	Response *remoteexecution.ExecuteResponse
}

// Create error for failing to deserialize a field as an expected type
func deserializeErr(keyName, expectedType string, value interface{}) error {
	return fmt.Errorf("value for key '%s' was not of type %s. %v: %s", keyName, expectedType, value, reflect.TypeOf(value))
}

// String conversion for human consumption of Operation's nested data
func ExecuteOperationToStr(op *longrunning.Operation) string {
	eom, st, res, err := ParseExecuteOperation(op)
	if err != nil {
		return ""
	}
	s := fmt.Sprintf("Operation: %s\n\tDone: %t\n", op.GetName(), op.GetDone())
	s += fmt.Sprintf("\tMetadata:\n")
	s += fmt.Sprintf("\t\tStage: %s\n", eom.GetStage())
	s += fmt.Sprintf("\t\tActionDigest: %s\n", bazel.DigestToStr(eom.GetActionDigest()))
	if st != nil {
		s += fmt.Sprintf("\tOperationError (rpc.Status):\n")
		s += fmt.Sprintf("\t\tCode: %s\n", code.Code_name[st.GetCode()])
		s += fmt.Sprintf("\t\tMessage: %s\n", st.GetMessage())
	}
	if res != nil {
		s += fmt.Sprintf("\tExecResponse:\n")
		s += fmt.Sprintf("\t\tStatus: %s\n", res.GetStatus())
		s += fmt.Sprintf("\t\t\tCode: %s\n", code.Code_name[res.GetStatus().GetCode()])
		s += fmt.Sprintf("\t\tCached: %t\n", res.GetCachedResult())
		s += fmt.Sprintf("\t\tActionResult:\n")
		s += fmt.Sprintf("\t\t\tExitCode: %d\n", res.GetResult().GetExitCode())
		s += fmt.Sprintf("\t\t\tOutputFiles: %s\n", res.GetResult().GetOutputFiles())
		s += fmt.Sprintf("\t\t\tOutputDirectories: %s\n", res.GetResult().GetOutputDirectories())
		s += fmt.Sprintf("\t\t\tStdoutDigest: %s\n", bazel.DigestToStr(res.GetResult().GetStdoutDigest()))
		s += fmt.Sprintf("\t\t\tStderrDigest: %s\n", bazel.DigestToStr(res.GetResult().GetStderrDigest()))
		if res.GetResult().GetExecutionMetadata() != nil {
			em := res.GetResult().GetExecutionMetadata()
			s += fmt.Sprintf("\t\t\tExecutionMetadata:\n")
			s += fmt.Sprintf("\t\t\t\tWorker: %s\n", em.GetWorker())
			s = addLatencyToStr(s, "\t\t\t\t", "QueueLatency", em.GetQueuedTimestamp(), em.GetWorkerStartTimestamp())
			s = addLatencyToStr(s, "\t\t\t\t", "WorkerTotal", em.GetWorkerStartTimestamp(), em.GetWorkerCompletedTimestamp())
			s = addLatencyToStr(s, "\t\t\t\t", "InputFetch", em.GetInputFetchStartTimestamp(), em.GetInputFetchCompletedTimestamp())
			s = addLatencyToStr(s, "\t\t\t\t", "Execution", em.GetExecutionStartTimestamp(), em.GetExecutionCompletedTimestamp())
			s = addLatencyToStr(s, "\t\t\t\t", "OutputUpload", em.GetOutputUploadStartTimestamp(), em.GetOutputUploadCompletedTimestamp())
		}
	}
	return s
}

func addLatencyToStr(inputStr, indent, label string, startTs, endTs *timestamp.Timestamp) string {
	if startTs == nil || endTs == nil {
		return inputStr
	}
	startTime, endTime := proto.GetTimeFromTimestamp(startTs), proto.GetTimeFromTimestamp(endTs)
	duration := endTime.Sub(startTime)
	ms := duration.Nanoseconds() / int64(time.Millisecond)
	inputStr += fmt.Sprintf("%s%s: %dms\n", indent, label, ms)
	return inputStr
}


text:
title: Nift
repo: nifty-site-manager/nsm
homepage: https://nift.cc
language:
  - C++
license:
  - MIT
templates:
  - Custom
description: A cross-platform open source git-like and LaTeX-like site manager.
twitter: nifty_site_man
startertemplaterepo: nsm-templates/basic-site
---

Nift, short for nifty site manager, is a cross-platform open source git-like and LaTeX-like site manager. You should be able to create any site you want (both static and non-static/dynamic) using Nift, though will need some kind of web server such as Apache, NGinx, a LAMP stack, etc. to host non-static/dynamic sites, whereas static sites can easily be hosted with platforms like BitBucket, GitHub, GitLab and Netlify.

### Philosophy

The intent for creating Nift (aka nsm) in the first place was to make a command-line site manager that was as git-like and LaTeX-like as possible, the creator/developer of Nift has achieved what was desired and hopes others may find it just as useful for their own wants and/or needs.