text:
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
 *  (C) 2001 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */
#if !defined(MPICH_MPIDRMA_H_INCLUDED)
#define MPICH_MPIDRMA_H_INCLUDED

/*
 * RMA Declarations.  We should move these into something separate from
 * a Request.
 */
/* to send derived datatype across in RMA ops */
typedef struct MPIDI_RMA_dtype_info { /* for derived datatypes */
    int           is_contig;
    int           max_contig_blocks;
    int           size;
    MPI_Aint      extent;
    int           dataloop_size; /* not needed because this info is sent in packet header. remove it after lock/unlock is implemented in the device */
    void          *dataloop;  /* pointer needed to update pointers
                                 within dataloop on remote side */
    int           dataloop_depth;
    int           eltype;
    MPI_Aint ub, lb, true_ub, true_lb;
    int has_sticky_ub, has_sticky_lb;
} MPIDI_RMA_dtype_info;

/* for keeping track of RMA ops, which will be executed at the next sync call */
typedef struct MPIDI_RMA_ops {
    struct MPIDI_RMA_ops *next;  /* pointer to next element in list */
    /* FIXME: It would be better to setup the packet that will be sent, at
       least in most cases (if, as a result of the sync/ops/sync sequence,
       a different packet type is needed, it can be extracted from the
       information otherwise stored). */
    /* FIXME: Use enum for RMA op type? */
    int type;  /* MPIDI_RMA_PUT, MPID_REQUEST_GET,
		  MPIDI_RMA_ACCUMULATE, MPIDI_RMA_LOCK */
    void *origin_addr;
    int origin_count;
    MPI_Datatype origin_datatype;
    int target_rank;
    MPI_Aint target_disp;
    int target_count;
    MPI_Datatype target_datatype;
    MPI_Op op;  /* for accumulate */
    int lock_type;  /* for win_lock */
    /* Used to complete operations */
    struct MPID_Request *request;
    MPIDI_RMA_dtype_info dtype_info;
    void *dataloop;
} MPIDI_RMA_ops;

typedef struct MPIDI_PT_single_op {
    int type;  /* put, get, or accum. */
    void *addr;
    int count;
    MPI_Datatype datatype;
    MPI_Op op;
    void *data;  /* for queued puts and accumulates, data is copied here */
    MPI_Request request_handle;  /* for gets */
    int data_recd;  /* to indicate if the data has been received */
} MPIDI_PT_single_op;

typedef struct MPIDI_Win_lock_queue {
    struct MPIDI_Win_lock_queue *next;
    int lock_type;
    MPI_Win source_win_handle;
    MPIDI_VC_t * vc;
    struct MPIDI_PT_single_op *pt_single_op;  /* to store info for lock-put-unlock optimization */
} MPIDI_Win_lock_queue;

/* Routine use to tune RMA optimizations */
void MPIDI_CH3_RMA_SetAccImmed( int flag );

#endif


text:
package com.appleframework.qos.server.statistics.mybatis2.dto.table;

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

/**
 * <p>
 * jQuery DataTables's PagingCriteria.
 * </p>
 *
 * @author mumu@yfyang
 * @version 1.0 2013-09-05 10:37 PM
 * @since JDK 1.5
 */
public final class PagingCriteria {
    /** The constant DEFAULT_CRITERIA. */
    private static final PagingCriteria DEFAULT_CRITERIA = new PagingCriteria(0, PagingCriteria.DEFAULT_SIZE, PagingCriteria.DEFAULT_SIZE);
    /** default page size. */
    private static final int DEFAULT_SIZE = 10;
    /** start display */
    private final int displayStart;
    /** disaplaySize */
    private final int displaySize;
    /** sort fields */
    private final List<SortField> sortFields;
    /** search field information */
    private final List<SearchField> searchFields;
    /** pageNumber */
    private final int pageNumber;

    /**
     * Instantiates a new Paging criteria.
     *
     * @param displayStart the display start
     * @param displaySize  the display size
     * @param pageNumber   the page number
     * @param sortFields   the sort fields
     * @param searchFields the search information
     */
    private PagingCriteria(int displayStart
            , int displaySize
            , int pageNumber
            , List<SortField> sortFields
            , List<SearchField> searchFields) {
        this.displayStart = displayStart;
        this.displaySize = displaySize;
        this.pageNumber = pageNumber;
        this.sortFields = sortFields;
        this.searchFields = searchFields;
    }

    /**
     * Instantiates a new Paging criteria and not sort\search.
     *
     * @param displaySize  the display size
     * @param displayStart the display start
     * @param pageNumber   the page number
     */
    private PagingCriteria(int displayStart
            , int displaySize
            , int pageNumber) {
        this.displaySize = displaySize;
        this.displayStart = displayStart;
        this.pageNumber = pageNumber;
        this.searchFields = new ArrayList<SearchField>(0);
        this.sortFields = new ArrayList<SortField>(0);
    }

    /**
     * Instantiates a new Paging criteria and no search.
     *
     * @param displaySize  the display size
     * @param displayStart the display start
     * @param pageNumber   the page number
     * @param sortFields   the sort fields
     */
    private PagingCriteria(int displayStart
            , int displaySize
            , int pageNumber
            , List<SortField> sortFields) {
        this.sortFields = sortFields;
        this.displaySize = displaySize;
        this.displayStart = displayStart;
        this.pageNumber = pageNumber;
        this.searchFields = new ArrayList<SearchField>(0);
    }

    /**
     * Instantiates a new Paging criteria and no sort.
     *
     * @param displayStart the display start
     * @param displaySize  the display size
     * @param searchFields the search fields
     * @param pageNumber   the page number
     */
    private PagingCriteria(int displayStart
            , int displaySize
            , List<SearchField> searchFields
            , int pageNumber) {
        this.displayStart = displayStart;
        this.displaySize = displaySize;
        this.searchFields = searchFields;
        this.pageNumber = pageNumber;
        this.sortFields = new ArrayList<SortField>(0);
    }

    /**
     * Create criteria with all paramter.
     *
     * @param displayStart the display start
     * @param displaySize  the display size
     * @param pageNumber   the page number
     * @param sortFields   the sort fields
     * @param searchFields the search fields
     * @return the paging criteria
     */
    public static PagingCriteria createCriteriaWithAllParamter(int displayStart
            , int displaySize
            , int pageNumber
            , List<SortField> sortFields
            , List<SearchField> searchFields) {
        return new PagingCriteria(displayStart, displaySize, pageNumber, sortFields, searchFields);
    }

    /**
     * Create criteria with sort.
     *
     * @param displayStart the display start
     * @param displaySize  the display size
     * @param pageNumber   the page number
     * @param sortFields   the sort fields
     * @return the paging criteria
     */
    public static PagingCriteria createCriteriaWithSort(int displayStart, int displaySize, int pageNumber
            , List<SortField> sortFields) {
        return new PagingCriteria(displayStart, displaySize, pageNumber, sortFields);
    }

    /**
     * Create criteria with search.
     *
     * @param displayStart the display start
     * @param displaySize  the display size
     * @param pageNumber   the page number
     * @param searchFields the search fields
     * @return the paging criteria
     */
    public static PagingCriteria createCriteriaWithSearch(int displayStart, int displaySize, int pageNumber
            , List<SearchField> searchFields) {
        return new PagingCriteria(displayStart, displaySize, searchFields, pageNumber);
    }

    /**
     * Create criteria.
     *
     * @param displayStart the display start
     * @param displaySize  the display size
     * @param pageNumber   the page number
     * @return the paging criteria
     */
    public static PagingCriteria createCriteria(int displayStart, int displaySize, int pageNumber) {
        return new PagingCriteria(displayStart, displaySize, pageNumber);
    }

    /**
     * Get default criteria.
     *
     * @return the paging criteria
     */
    public static PagingCriteria getDefaultCriteria() {
        return DEFAULT_CRITERIA;
    }

    /**
     * Gets display start.
     *
     * @return the display start
     */
    public Integer getDisplayStart() {
        return displayStart;
    }

    /**
     * Gets display size.
     *
     * @return the display size
     */
    public Integer getDisplaySize() {
        return displaySize;
    }

    /**
     * Gets search fields.
     *
     * @return the search fields
     */
    public List<SearchField> getSearchFields() {
        if (this.searchFields == null) {
            return new ArrayList<SearchField>(0);
        }
        return Collections.unmodifiableList(searchFields);
    }

    /**
     * Gets sort fields.
     *
     * @return the sort fields
     */
    public List<SortField> getSortFields() {
        if (this.sortFields == null) {
            return new ArrayList<SortField>(0);
        }
        return Collections.unmodifiableList(sortFields);
    }

    /**
     * Gets page number.
     *
     * @return the page number
     */
    public Integer getPageNumber() {
        return pageNumber;
    }

}

redpajama_set_name: RedPajamaGithub


text:
int main(int argc, char * argv[])
{
    int nt = omp_get_max_threads();
    return nt;
}


text:
package org.influxdb.msgpack;

import java.util.Iterator;
import java.util.List;

import org.influxdb.dto.QueryResult;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

import static org.junit.jupiter.api.Assertions.*;

@RunWith(JUnitPlatform.class)
@EnabledIfEnvironmentVariable(named = "INFLUXDB_VERSION", matches = "1\\.6|1\\.5|1\\.4")
public class MessagePackTraverserTest {

  @Test
  public void testTraverseMethod() {
    MessagePackTraverser traverser = new MessagePackTraverser();

    /*  a json-like view of msgpack_1.bin

    {"results":[{"statement_id":0,"series":[{"name":"disk","columns":["time","atag","free","used"],
          "values":[[(5,0x00005b556c-252f-23-6438),"a",1,60],[(5,0x00005b556c-252f-23-6438),"b",2,70]],"partial":true}],"partial":true}]}
    {"results":[{"statement_id":0,"series":[{"name":"disk","columns":["time","atag","free","used"],"values":[[(5,0x00005b556c-252f-23-6438),"c",3,80]]}]}]}

    */

    Iterator<QueryResult> iter = traverser.traverse(MessagePackTraverserTest.class.getResourceAsStream("msgpack_1.bin")).iterator();
    assertTrue(iter.hasNext());
    QueryResult result = iter.next();
    List<List<Object>> values = result.getResults().get(0).getSeries().get(0).getValues();
    Assertions.assertEquals(2, values.size());

    assertEquals(1532325083803052600L, values.get(0).get(0));
    assertEquals("b", values.get(1).get(1));

    assertTrue(iter.hasNext());
    result = iter.next();
    values = result.getResults().get(0).getSeries().get(0).getValues();
    Assertions.assertEquals(1, values.size());
    assertEquals(3, values.get(0).get(2));

    assertFalse(iter.hasNext());
  }

  @Test
  public void testParseMethodOnNonEmptyResult() {
    MessagePackTraverser traverser = new MessagePackTraverser();
    /* a json-like view of msgpack_2.bin

    {"results":[{"statement_id":0,"series":[{"name":"measurement_957996674028300","columns":["time","device","foo"],
          "values":[[(5,0x000058-797a00000),"one",1.0],[(5,0x000058-79-78100000),"two",2.0],[(5,0x000058-79-6a200000),"three",3.0]]}]}]}
    */
    QueryResult queryResult = traverser.parse(MessagePackTraverserTest.class.getResourceAsStream("msgpack_2.bin"));
    List<List<Object>> values = queryResult.getResults().get(0).getSeries().get(0).getValues();
    Assertions.assertEquals(3, values.size());
    assertEquals(1485273600000000000L, values.get(0).get(0));
    assertEquals("two", values.get(1).get(1));
    assertEquals(3.0, values.get(2).get(2));
  }

  @Test
  public void testParseMethodOnEmptyResult() {
    MessagePackTraverser traverser = new MessagePackTraverser();
    /* a json-like view of msgpack_3.bin

      {"results":[{"statement_id":0,"series":[]}]}

    */
    QueryResult queryResult = traverser.parse(MessagePackTraverserTest.class.getResourceAsStream("msgpack_3.bin"));
    System.out.println();
    assertNull(queryResult.getResults().get(0).getSeries());

  }
}


text:
namespace dynet {

struct FHuberForward {
  FHuberForward(float c) : c(c) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    const float a = fabs(x);
    return (a < c) ? x*x : c*(2*a - c);
  }
  const float c;
};

// template <typename T> int sgn(T val) {
//   return ((T(0) < val) - (val < T(0)));
// }

struct FL1Backward {
  FL1Backward(float d) : d(d) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return ((0.f < x) - (x < 0.f)) * d;
  }
  const float d;
};

struct FHuberBackward {
  FHuberBackward(float c, float dEdf) : c(c), d(dEdf) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    const float a = fabs(x);
    return (2 * d) * ((a < c) ? x : c * ((0.f < x) - (x < 0.f)));
  }
  const float c;
  const float d;
};

struct FProduct {
  DYNET_DEVICE_FUNC inline float operator()(float a, float b) const {
    return a * b;
  }
};

struct FQuotient {
  DYNET_DEVICE_FUNC inline float operator()(float a, float b) const {
    return a / b;
  }
};

struct FConstantPlus {
  FConstantPlus(float c) : c(c) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return c + x;
  }
  float c;
};

struct FConstantMinus {
  FConstantMinus(float c) : c(c) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return c - x;
  }
  float c;
};

struct FNegate {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return -x;
  }
};

struct FErf {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return erff(x);
  }
};

struct FTanh {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
#ifdef FAST_TANH
    float x2 = x * x;
    float a = x * (135135.0f + x2 * (17325.0f + x2 * (378.0f + x2)));
    float b = 135135.0f + x2 * (62370.0f + x2 * (3150.0f + x2 * 28.0f));
    return a / b;
#else
     return tanhf(x);
#endif
  }
};

struct FLog {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return logf(x);
  }
};

struct FMaxBackwardInv {
  DYNET_DEVICE_FUNC inline float operator()(float u, float d) const {
    return (1.f - u) * d;
  }
};

struct FSqrtBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return d / (2.f * t);
  }
};

struct FErfBackward {
  DYNET_DEVICE_FUNC inline float operator()(float x, float d) const {
    return 1.1283791670955125738961589f * expf(-x * x) * d;
  }
};

struct FTanhBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return (1.f - t * t) * d;
  }
};

struct FLogBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return (1.f / t) * d;
  }
};

struct FPairwiseRankLoss {
  FPairwiseRankLoss(float m) : margin(m) {}
  DYNET_DEVICE_FUNC float operator()(float a, float b) const {
    float d = margin - a + b;
    return d > 0.f ? d : 0.f;
  }
  float margin;
};

struct FRectifyBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return (t) ? d : 0.f;
  }
};

struct FRectifyNegateBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return (t) ? -d : 0.f;
  }
};

struct FSoftmaxNormalize {
  explicit FSoftmaxNormalize(float logz) : logz(logz) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return expf(x - logz);
  }
  float logz;
};

struct FSoftmaxBackward {
  explicit FSoftmaxBackward(float off_diag_sum) : off_diag_sum(off_diag_sum) {}
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return (off_diag_sum + d) * t;
  }
  float off_diag_sum;
};

struct FNegLogSoftmaxBackward {
  FNegLogSoftmaxBackward(float lz, float err) : logz(lz), d(err) {}
  DYNET_DEVICE_FUNC inline float operator()(float t) const {
    return expf(t - logz) * d;
  }
  float logz;
  float d;
};

struct FPtrNegLogSoftmaxBackward {
  FPtrNegLogSoftmaxBackward(const float* lz, const float* err) : logz(lz), d(err) {}
  DYNET_DEVICE_FUNC inline float operator()(float t) const {
    return expf(t - *logz) * *d;
  }
  const float* logz;
  const float* d;
};

struct FLogSoftmaxNormalize {
  explicit FLogSoftmaxNormalize(float logz) : logz(logz) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return x - logz;
  }
  float logz;
};

struct FWeightedError {
  float operator()(float t, float d) const {
    return expf(t) * d / expf(t);
  }
};

struct FLogSoftmaxBackward {
  explicit FLogSoftmaxBackward(float off_diag_sum) : off_diag_sum(off_diag_sum) {}
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return off_diag_sum * expf(t) + d;
    //return (off_diag_sum + d) * t;
  }
  float off_diag_sum;
};

struct FRectify {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return (x > 0.f) ? x : 0.f;
  }
};

struct FSoftSign {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return x / (1.f + (x < 0.f ? -x : x));
  }
};

struct FSoftSignBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    float a = 1.f - (t < 0.f ? -t : t);
    return a * a * d;
  }
};

struct FLogisticSigmoid {
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return 1.f / (1.f + expf(-x));
  }
};

struct FLogisticSigmoidBackward {
  DYNET_DEVICE_FUNC inline float operator()(float t, float d) const {
    return (1.f - t) * t * d;
  }
};

struct FSqDist {
  DYNET_DEVICE_FUNC inline float operator()(float a, float b) const {
    float d = a - b;
    return d * d;
  }
};

struct FEuclideanBackward {
  FEuclideanBackward(int i, const float* s) : i(i), scalar(s) {}
  DYNET_DEVICE_FUNC inline float operator()(float a, float b) const {
    return (i == 0 ? 2.f : -2.f) * (*scalar) * (a - b);
  }
  int i;
  const float* scalar;
};

struct FL2SGDUpdate {
  FL2SGDUpdate(float l, float s) : lambda(l), scale(-s) {}
  DYNET_DEVICE_FUNC inline float operator()(float x, float g) const {
    return scale * g - x * lambda;
  }
  float lambda;
  float scale;
};

struct FBinaryLogLoss {
  DYNET_DEVICE_FUNC inline float operator()(float x, float x_true) const {
    if (x_true == 1.f) {
      if (x == 0.f) return -1.f * log(DYNET_DEVICE_MIN);
      return -1.f * log(x);
    }
    else if (x_true == 0.f) {
      if (x == 1.f) return -1.f * log(DYNET_DEVICE_MIN);
      else return (x_true - 1.f) * log1pf(-x);
    }
    else {
      if (x == 0.f) return -1.f * log(DYNET_DEVICE_MIN);
      else if (x == 1.f) return -1.f * log(DYNET_DEVICE_MIN);
      else return -1.f * (x_true * log(x) + (1.f - x_true) * log1pf(-x));
    }
  }
};

struct FBinaryLogLossBackward {
  explicit FBinaryLogLossBackward(float d) : d(d) {}
  DYNET_DEVICE_FUNC inline float operator()(float x, float x_true) const {
    if (x == x_true) return 0;
    if (x == 0.f) x = DYNET_DEVICE_MIN;
    if (x == 1.f) x = 0.9999999f;
    if (x_true == 1.f) {
      return d * -x_true / x;
    } else if (x_true == 0.f) {
      return d * (1.f - x_true) / (1.f - x);
    }
    return d * ((1.f - x_true) / (1.f - x) + (-x_true / x));
  }
  float d;
};

struct FELUForward {
  explicit FELUForward(float alpha, float lambda) : alpha(alpha), lambda(lambda) {}
  DYNET_DEVICE_FUNC inline float operator()(float x) const {
    return lambda * ((x > 0.f) ? x : alpha * (expm1f(x)));
  }
  float alpha, lambda;
};

struct FELUBackward {
  explicit FELUBackward(float alpha, float lambda) : alpha(alpha), lambda(lambda) {}
  DYNET_DEVICE_FUNC inline float operator()(float x, float d) const {
    return d * ((x > 0.f) ? lambda : lambda * alpha * expf(x));
  }
  float alpha, lambda;
};

} // namespace dynet

#endif


text:
WebsocketServer::WebsocketServer(QObject *parent) : QObject(parent)
{
    m_server = new QWebSocketServer("Epsolar", QWebSocketServer::NonSecureMode, this);

    connect( m_server, &QWebSocketServer::newConnection, this, &WebsocketServer::incoming );
    m_server->listen(QHostAddress::Any, 7175);
}

void WebsocketServer::incoming()
{
    QWebSocket *socket = m_server->nextPendingConnection();

    connect( socket, &QWebSocket::disconnected, this, &WebsocketServer::disconnected );
    m_clients.append(socket);

    emit newConnection(socket);
}

void WebsocketServer::disconnected()
{
    QWebSocket *client = qobject_cast< QWebSocket * >( sender() );
    if( m_clients.contains(client) )
        m_clients.removeOne(client);

    client->deleteLater();
}

int WebsocketServer::broadcast(const QString &packet)
{
    //printf("JSON: %s\n\n", packet.toStdString().c_str());
    int received = 0;
    foreach( QWebSocket *socket, m_clients )
    {
        socket->sendTextMessage(packet);
        received++;
    }
    return received;
}


text:
require 'fog/core/model'

module Fog
  module Compute
    class Linode
      class NodeBalancerFlavor < Fog::Model
        attribute :price_monthly
        attribute :price_hourly
        attribute :connections
      end
    end
  end
end


text:
redirect_to: https://anvio.org/help/7.1/artifacts/configuration-ini
---


text:
import optimus.project_specific.shared
import optimus.project_specific.hcv_target
import optimus.project_specific.prioritize


text:
"""
Support for Sensibo wifi-enabled home thermostats.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.sensibo/
"""

import asyncio
import logging

import aiohttp
import async_timeout
import voluptuous as vol

from homeassistant.const import (
    ATTR_TEMPERATURE, CONF_API_KEY, CONF_ID, TEMP_CELSIUS, TEMP_FAHRENHEIT)
from homeassistant.components.climate import (
    ATTR_CURRENT_HUMIDITY, ClimateDevice, PLATFORM_SCHEMA)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util.temperature import convert as convert_temperature

REQUIREMENTS = ['pysensibo==1.0.1']

_LOGGER = logging.getLogger(__name__)

ALL = 'all'
TIMEOUT = 10

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_API_KEY): cv.string,
    vol.Optional(CONF_ID, default=ALL): vol.All(cv.ensure_list, [cv.string]),
})

_FETCH_FIELDS = ','.join([
    'room{name}', 'measurements', 'remoteCapabilities',
    'acState', 'connectionStatus{isAlive}'])
_INITIAL_FETCH_FIELDS = 'id,' + _FETCH_FIELDS

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up Sensibo devices."""
    import pysensibo

    client = pysensibo.SensiboClient(
        config[CONF_API_KEY], session=async_get_clientsession(hass),
        timeout=TIMEOUT)
    devices = []
    try:
        for dev in (
                yield from client.async_get_devices(_INITIAL_FETCH_FIELDS)):
            if config[CONF_ID] == ALL or dev['id'] in config[CONF_ID]:
                devices.append(SensiboClimate(client, dev))
    except aiohttp.client_exceptions.ClientConnectorError:
        _LOGGER.exception('Failed to connct to Sensibo servers.')
        return False

    if devices:
        async_add_devices(devices)

class SensiboClimate(ClimateDevice):
    """Representation os a Sensibo device."""

    def __init__(self, client, data):
        """Build SensiboClimate.

        client: aiohttp session.
        data: initially-fetched data.
        """
        self._client = client
        self._id = data['id']
        self._do_update(data)

    def _do_update(self, data):
        self._name = data['room']['name']
        self._measurements = data['measurements']
        self._ac_states = data['acState']
        self._status = data['connectionStatus']['isAlive']
        capabilities = data['remoteCapabilities']
        self._operations = sorted(capabilities['modes'].keys())
        self._current_capabilities = capabilities[
            'modes'][self.current_operation]
        temperature_unit_key = self._ac_states['temperatureUnit']
        self._temperature_unit = \
            TEMP_CELSIUS if temperature_unit_key == 'C' else TEMP_FAHRENHEIT
        self._temperatures_list = self._current_capabilities[
            'temperatures'][temperature_unit_key]['values']

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return {ATTR_CURRENT_HUMIDITY: self.current_humidity}

    @property
    def temperature_unit(self):
        """Return the unit of measurement which this thermostat uses."""
        return self._temperature_unit

    @property
    def available(self):
        """Return True if entity is available."""
        return self._status

    @property
    def target_temperature(self):
        """Return the temperature we try to reach."""
        return self._ac_states['targetTemperature']

    @property
    def target_temperature_step(self):
        """Return the supported step of target temperature."""
        if self.temperature_unit == self.unit_of_measurement:
            # We are working in same units as the a/c unit. Use whole degrees
            # like the API supports.
            return 1
        else:
            # Unit conversion is going on. No point to stick to specific steps.
            return None

    @property
    def current_operation(self):
        """Return current operation ie. heat, cool, idle."""
        return self._ac_states['mode']

    @property
    def current_humidity(self):
        """Return the current humidity."""
        return self._measurements['humidity']

    @property
    def current_temperature(self):
        """Return the current temperature."""
        # This field is not affected by temperature_unit.
        # It is always in C / nativeTemperatureUnit
        if 'nativeTemperatureUnit' not in self._ac_states:
            return self._measurements['temperature']
        return convert_temperature(
            self._measurements['temperature'],
            TEMP_CELSIUS,
            self.temperature_unit)

    @property
    def operation_list(self):
        """List of available operation modes."""
        return self._operations

    @property
    def current_fan_mode(self):
        """Return the fan setting."""
        return self._ac_states.get('fanLevel')

    @property
    def fan_list(self):
        """List of available fan modes."""
        return self._current_capabilities.get('fanLevels')

    @property
    def current_swing_mode(self):
        """Return the fan setting."""
        return self._ac_states.get('swing')

    @property
    def swing_list(self):
        """List of available swing modes."""
        return self._current_capabilities.get('swing')

    @property
    def name(self):
        """Return the name of the entity."""
        return self._name

    @property
    def is_aux_heat_on(self):
        """Return true if AC is on."""
        return self._ac_states['on']

    @property
    def min_temp(self):
        """Return the minimum temperature."""
        return self._temperatures_list[0]

    @property
    def max_temp(self):
        """Return the maximum temperature."""
        return self._temperatures_list[-1]

    @asyncio.coroutine
    def async_set_temperature(self, **kwargs):
        """Set new target temperature."""
        temperature = kwargs.get(ATTR_TEMPERATURE)
        if temperature is None:
            return
        temperature = int(temperature)
        if temperature not in self._temperatures_list:
            # Requested temperature is not supported.
            if temperature == self.target_temperature:
                return
            index = self._temperatures_list.index(self.target_temperature)
            if temperature > self.target_temperature and index < len(
                    self._temperatures_list) - 1:
                temperature = self._temperatures_list[index + 1]
            elif temperature < self.target_temperature and index > 0:
                temperature = self._temperatures_list[index - 1]
            else:
                return

        with async_timeout.timeout(TIMEOUT):
            yield from self._client.async_set_ac_state_property(
                self._id, 'targetTemperature', temperature)

    @asyncio.coroutine
    def async_set_fan_mode(self, fan):
        """Set new target fan mode."""
        with async_timeout.timeout(TIMEOUT):
            yield from self._client.async_set_ac_state_property(
                self._id, 'fanLevel', fan)

    @asyncio.coroutine
    def async_set_operation_mode(self, operation_mode):
        """Set new target operation mode."""
        with async_timeout.timeout(TIMEOUT):
            yield from self._client.async_set_ac_state_property(
                self._id, 'mode', operation_mode)

    @asyncio.coroutine
    def async_set_swing_mode(self, swing_mode):
        """Set new target swing operation."""
        with async_timeout.timeout(TIMEOUT):
            yield from self._client.async_set_ac_state_property(
                self._id, 'swing', swing_mode)

    @asyncio.coroutine
    def async_turn_aux_heat_on(self):
        """Turn Sensibo unit on."""
        with async_timeout.timeout(TIMEOUT):
            yield from self._client.async_set_ac_state_property(
                self._id, 'on', True)

    @asyncio.coroutine
    def async_turn_aux_heat_off(self):
        """Turn Sensibo unit on."""
        with async_timeout.timeout(TIMEOUT):
            yield from self._client.async_set_ac_state_property(
                self._id, 'on', False)

    @asyncio.coroutine
    def async_update(self):
        """Retrieve latest state."""
        try:
            with async_timeout.timeout(TIMEOUT):
                data = yield from self._client.async_get_device(
                    self._id, _FETCH_FIELDS)
                self._do_update(data)
        except aiohttp.client_exceptions.ClientError:
            _LOGGER.warning('Failed to connect to Sensibo servers.')


text:
//go:build !ignore_autogenerated
// +build !ignore_autogenerated

/*

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.
*/

// Code generated by controller-gen. DO NOT EDIT.

package v1beta1

import (
	runtime "k8s.io/apimachinery/pkg/runtime"
)

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Notebook) DeepCopyInto(out *Notebook) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	in.Status.DeepCopyInto(&out.Status)
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Notebook.
func (in *Notebook) DeepCopy() *Notebook {
	if in == nil {
		return nil
	}
	out := new(Notebook)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Notebook) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NotebookCondition) DeepCopyInto(out *NotebookCondition) {
	*out = *in
	in.LastProbeTime.DeepCopyInto(&out.LastProbeTime)
	in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime)
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NotebookCondition.
func (in *NotebookCondition) DeepCopy() *NotebookCondition {
	if in == nil {
		return nil
	}
	out := new(NotebookCondition)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NotebookList) DeepCopyInto(out *NotebookList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ListMeta.DeepCopyInto(&out.ListMeta)
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]Notebook, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NotebookList.
func (in *NotebookList) DeepCopy() *NotebookList {
	if in == nil {
		return nil
	}
	out := new(NotebookList)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *NotebookList) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NotebookSpec) DeepCopyInto(out *NotebookSpec) {
	*out = *in
	in.Template.DeepCopyInto(&out.Template)
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NotebookSpec.
func (in *NotebookSpec) DeepCopy() *NotebookSpec {
	if in == nil {
		return nil
	}
	out := new(NotebookSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NotebookStatus) DeepCopyInto(out *NotebookStatus) {
	*out = *in
	if in.Conditions != nil {
		in, out := &in.Conditions, &out.Conditions
		*out = make([]NotebookCondition, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	in.ContainerState.DeepCopyInto(&out.ContainerState)
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NotebookStatus.
func (in *NotebookStatus) DeepCopy() *NotebookStatus {
	if in == nil {
		return nil
	}
	out := new(NotebookStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NotebookTemplateSpec) DeepCopyInto(out *NotebookTemplateSpec) {
	*out = *in
	in.Spec.DeepCopyInto(&out.Spec)
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NotebookTemplateSpec.
func (in *NotebookTemplateSpec) DeepCopy() *NotebookTemplateSpec {
	if in == nil {
		return nil
	}
	out := new(NotebookTemplateSpec)
	in.DeepCopyInto(out)
	return out
}


text:
package main

import (
	"net/http"

	"github.com/koffeinsource/kaffeeshare/targets/check"
	"github.com/koffeinsource/kaffeeshare/targets/cron"
	"github.com/koffeinsource/kaffeeshare/targets/email"
	"github.com/koffeinsource/kaffeeshare/targets/share"
	"github.com/koffeinsource/kaffeeshare/targets/show"
	"github.com/koffeinsource/kaffeeshare/targets/startpage"
	"github.com/koffeinsource/kaffeeshare/targets/update"
	"google.golang.org/appengine"

	"github.com/gorilla/mux"
)

var router = mux.NewRouter()

//<domain>/k/twitter/connect/<namespace>
//<domain>/k/twitter/disconnect/<namespace>
//<domain>/k/email/connect/<namespace>
//<domain>/k/share/<namespace> <- extension url

func init() {
	router.StrictSlash(true)

	router.HandleFunc("/", startpage.Dispatch)
	router.HandleFunc("/k/check/json/{namespace}", check.DispatchJSON)

	// should actually be share/get as we don't do json here
	router.HandleFunc("/k/share/json/{namespace}", share.DispatchJSON)
	router.HandleFunc("/k/share/slack/{namespace}", share.DispatchSlack)

	router.HandleFunc("/k/update/json/{namespace}", update.DispatchJSON)

	router.HandleFunc("/k/show/json/{namespace}", show.DispatchJSON)
	router.HandleFunc("/k/show/www/{namespace}", show.DispatchWWW)
	router.HandleFunc("/k/show/rss/{namespace}", show.DispatchRSS)

	router.HandleFunc("/c/clear_test/", cron.ClearTest)
	router.HandleFunc("/c/clear_test", cron.ClearTest)

	// TODO move to router
	http.HandleFunc("/_ah/mail/", email.DispatchEmail)
	http.Handle("/", router)
}

func main() {
	/*	http.HandleFunc("/", indexHandler)

		port := os.Getenv("PORT")
		if port == "" {
			port = "8080"
			log.Printf("Defaulting to port %s", port)
		}

		log.Printf("Listening on port %s", port)
		if err := http.ListenAndServe(":"+port, nil); err != nil {
			log.Fatal(err)
		}*/

	appengine.Main()
}


text:
<?php

final class DrydockResourceQuery extends DrydockQuery {

  private $ids;
  private $phids;
  private $statuses;
  private $types;
  private $blueprintPHIDs;
  private $datasourceQuery;

  public function withIDs(array $ids) {
    $this->ids = $ids;
    return $this;
  }

  public function withPHIDs(array $phids) {
    $this->phids = $phids;
    return $this;
  }

  public function withTypes(array $types) {
    $this->types = $types;
    return $this;
  }

  public function withStatuses(array $statuses) {
    $this->statuses = $statuses;
    return $this;
  }

  public function withBlueprintPHIDs(array $blueprint_phids) {
    $this->blueprintPHIDs = $blueprint_phids;
    return $this;
  }

  public function withDatasourceQuery($query) {
    $this->datasourceQuery = $query;
    return $this;
  }

  protected function loadPage() {
    $table = new DrydockResource();
    $conn_r = $table->establishConnection('r');

    $data = queryfx_all(
      $conn_r,
      'SELECT resource.* FROM %T resource %Q %Q %Q',
      $table->getTableName(),
      $this->buildWhereClause($conn_r),
      $this->buildOrderClause($conn_r),
      $this->buildLimitClause($conn_r));

    $resources = $table->loadAllFromArray($data);

    return $resources;
  }

  protected function buildWhereClause(AphrontDatabaseConnection $conn_r) {
    $where = array();

    if ($this->ids !== null) {
      $where[] = qsprintf(
        $conn_r,
        'id IN (%Ld)',
        $this->ids);
    }

    if ($this->phids !== null) {
      $where[] = qsprintf(
        $conn_r,
        'phid IN (%Ls)',
        $this->phids);
    }

    if ($this->types !== null) {
      $where[] = qsprintf(
        $conn_r,
        'type IN (%Ls)',
        $this->types);
    }

    if ($this->statuses !== null) {
      $where[] = qsprintf(
        $conn_r,
        'status IN (%Ls)',
        $this->statuses);
    }

    if ($this->blueprintPHIDs !== null) {
      $where[] = qsprintf(
        $conn_r,
        'blueprintPHID IN (%Ls)',
        $this->blueprintPHIDs);
    }

    if ($this->datasourceQuery !== null) {
      $where[] = qsprintf(
        $conn_r,
        'name LIKE %>',
        $this->datasourceQuery);
    }

    $where[] = $this->buildPagingClause($conn_r);

    return $this->formatWhereClause($where);
  }

}


text:
import numpy as np

from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.models.rbm import RBM
from pylearn2.models.s3c import S3C, E_Step, Grad_M_Step
from pylearn2.training_algorithms.default import DefaultTrainingAlgorithm
from pylearn2.training_algorithms.training_algorithm import NoBatchSizeError

def test_multiple_monitoring_datasets():
    # tests that DefaultTrainingAlgorithm can take multiple
    # monitoring datasets.

    BATCH_SIZE = 2
    BATCHES = 3
    NUM_FEATURES = 4
    dim = 3
    m = 10

    rng = np.random.RandomState([2014, 02, 25])
    X = rng.randn(m, dim)
    Y = rng.randn(m, dim)

    train = DenseDesignMatrix(X=X)
    test = DenseDesignMatrix(X=Y)

    algorithm = DefaultTrainingAlgorithm(
        batch_size=BATCH_SIZE,
        batches_per_iter=BATCHES,
        monitoring_dataset={'train': train, 'test': test})

    model = S3C(nvis=NUM_FEATURES, nhid=1,
                irange=.01, init_bias_hid=0., init_B=1.,
                min_B=1., max_B=1., init_alpha=1.,
                min_alpha=1., max_alpha=1., init_mu=0.,
                m_step=Grad_M_Step(learning_rate=0.),
                e_step=E_Step(h_new_coeff_schedule=[1.]))

    algorithm.setup(model=model, dataset=train)
    algorithm.train(dataset=train)

def test_unspecified_batch_size():

    # Test that failing to specify the batch size results in a
    # NoBatchSizeError

    m = 1
    dim = 2
    rng = np.random.RandomState([2014, 03, 17])
    X = rng.randn(m, dim)
    train = DenseDesignMatrix(X=X)

    rbm = RBM(nvis=dim, nhid=3)
    trainer = DefaultTrainingAlgorithm()
    try:
        trainer.setup(rbm, train)
    except NoBatchSizeError:
        return
    raise AssertionError("Missed the lack of a batch size")

if __name__ == '__main__':
    test_multiple_monitoring_datasets()


text:
// ***********************************************************************
// Assembly         : ACBr.Net.CTe
// Author           : RFTD
// Created          : 11-10-2016
//
// Last Modified By : RFTD
// Last Modified On : 11-10-2016
// ***********************************************************************
// <copyright file="InutilizacaoResponse.cs" company="ACBr.Net">
//		        		   The MIT License (MIT)
//	     		    Copyright (c) 2016 Grupo ACBr.Net
//
//	 Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//	 The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//	 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************

using System.ServiceModel;
using System.Xml;
using ACBr.Net.DFe.Core.Service;

namespace ACBr.Net.CTe.Services
{
    [MessageContract(WrapperName = "cteInutilizacaoCTResponse", IsWrapped = false)]
    public sealed class InutilizacaoResponse : ResponseBase
    {
        #region Constructors

        public InutilizacaoResponse()
        {
        }

        public InutilizacaoResponse(DFeWsCabecalho cabecalho, XmlNode result)
        {
            Cabecalho = cabecalho;
            Result = result;
        }

        #endregion Constructors

        #region Propriedades

        [MessageBodyMember(Name = "cteInutilizacaoCTResult", Namespace = "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao", Order = 0)]
        public XmlNode Result;

        #endregion Propriedades
    }
}


text:
#define SVN_DATE       "$Date: 2011-10-18 12:42:04 +0200 (Tue, 18 Oct 2011) $"
#define SVN_AUTHOR     "$Author: iveselyk $"
#define SVN_REVISION   "$Revision: 86 $"
#define SVN_ID         "$Id: TRecurrentCu.cc 86 2011-10-18 10:42:04Z iveselyk $"

#define MODULE_VERSION "1.0.0 "__TIME__" "__DATE__" "SVN_ID

/*** TNetLib includes */
#include "Error.h"
#include "Timer.h"
#include "Features.h"
#include "Labels.h"
#include "Common.h"
#include "MlfStream.h"
#include "UserInterface.h"
#include "Timer.h"

/*** TNet includes */
#include "cuObjectiveFunction.h"
#include "cuNetwork.h"
#include "cuRecurrent.h"

/*** STL includes */
#include <iostream>
#include <sstream>
#include <numeric>

//////////////////////////////////////////////////////////////////////
// DEFINES
//

#define SNAME "TNET"

using namespace TNet;

void usage(const char* progname)
{
  const char *tchrptr;
  if ((tchrptr = strrchr(progname, '\\')) != NULL) progname = tchrptr+1;
  if ((tchrptr = strrchr(progname, '/')) != NULL) progname = tchrptr+1;
  fprintf(stderr,
"\n%s version " MODULE_VERSION "\n"
"\nUSAGE: %s [options] DataFiles...\n\n"
"\n:TODO:\n\n"
" Option                                                     Default\n\n"
" -c         Enable crossvalidation                          off\n"
" -m file    Set label map of NN outputs                     \n"
" -n f       Set learning rate to f                          0.06\n"
" -o ext     Set target model ext                            None\n"
" -A         Print command line arguments                    Off\n"
" -C cf      Set config file to cf                           Default\n"
" -D         Display configuration variables                 Off\n"
" -H mmf     Load NN macro file                              \n"
" -I mlf     Load master label file mlf                      \n"
" -L dir     Set input label (or net) dir                    Current\n"
" -M dir     Dir to write NN macro files                     Current\n"
" -O fn      Objective function [mse,xent]                   xent\n"
" -S file    Set script file                                 None\n"
" -T N       Set trace flags to N                            0\n"
" -V         Print version information                       Off\n"
" -X ext     Set input label file ext                        lab\n"
"\n"
"BUNCHSIZE CACHESIZE CROSSVALIDATE FEATURETRANSFORM LEARNINGRATE LEARNRATEFACTORS MLFTRANSC MOMENTUM NATURALREADORDER OBJECTIVEFUNCTION OUTPUTLABELMAP PRINTCONFIG PRINTVERSION RANDOMIZE SCRIPT SEED SOURCEMLF SOURCEMMF SOURCETRANSCDIR SOURCETRANSCEXT TARGETMMF TARGETMODELDIR TARGETMODELEXT TRACE WEIGHTCOST\n"
"\n"
"STARTFRMEXT ENDFRMEXT CMEANDIR CMEANMASK VARSCALEDIR VARSCALEMASK VARSCALEFN TARGETKIND DERIVWINDOWS DELTAWINDOW ACCWINDOW THIRDWINDOW\n"
"\n"
" %s is Copyright (C) 2010-2011 Karel Vesely\n"
" licensed under the APACHE License, version 2.0\n"
" Bug reports, feedback, etc, to: iveselyk@fit.vutbr.cz\n"
"\n", progname, progname, progname);
  exit(-1);
}

///////////////////////////////////////////////////////////////////////
// MAIN FUNCTION
//

int main(int argc, char *argv[]) try
{
  const char* p_option_string =
    " -m r   OUTPUTLABELMAP"
    " -n r   LEARNINGRATE"
    " -D n   PRINTCONFIG=TRUE"
    " -H l   SOURCEMMF"
    " -I r   SOURCEMLF"
    " -L r   SOURCETRANSCDIR"
    " -S l   SCRIPT"
    " -T r   TRACE"
    " -V n   PRINTVERSION=TRUE"
    " -X r   SOURCETRANSCEXT";

  UserInterface        ui;
  FeatureRepository    feature_repo;
  LabelRepository      label_repo;
  CuNetwork            network;
  CuNetwork            transform_network;
  CuObjectiveFunction* p_obj_function = NULL;
  Timer                timer;
  Timer                timer_frontend;
  double               time_frontend = 0.0;

  const char*                       p_source_mmf_file;
  const char*                       p_input_transform;
  const char*                       p_targetmmf;

  const char*                       p_script;
  const char*                       p_output_label_map;

  BaseFloat                         learning_rate;
  const char*                       learning_rate_factors;
  BaseFloat                         momentum;
  BaseFloat                         weightcost;
  int                               bptt;
  CuObjectiveFunction::ObjFunType   obj_fun_id;

  const char*                       p_source_mlf_file;
  const char*                       p_src_lbl_dir;
  const char*                       p_src_lbl_ext;

  bool                              cross_validate;

  int                               trace;

  // variables for feature repository
  bool                              swap_features;
  int                               target_kind;
  int                               deriv_order;
  int*                              p_deriv_win_lenghts;
  int                               start_frm_ext;
  int                               end_frm_ext;
        char*                       cmn_path;
        char*                       cmn_file;
  const char*                       cmn_mask;
        char*                       cvn_path;
        char*                       cvn_file;
  const char*                       cvn_mask;
  const char*                       cvg_file;

  // OPTION PARSING ..........................................................
  // use the STK option parsing
  if (argc == 1) { usage(argv[0]); return 1; }
  int args_parsed = ui.ParseOptions(argc, argv, p_option_string, SNAME);

  // OPTION RETRIEVAL ........................................................
  // extract the feature parameters
  swap_features = !ui.GetBool(SNAME":NATURALREADORDER", TNet::IsBigEndian());

  target_kind = ui.GetFeatureParams(&deriv_order, &p_deriv_win_lenghts,
       &start_frm_ext, &end_frm_ext, &cmn_path, &cmn_file, &cmn_mask,
       &cvn_path, &cvn_file, &cvn_mask, &cvg_file, SNAME":", 0);

  // extract other parameters
  p_source_mmf_file   = ui.GetStr(SNAME":SOURCEMMF",     NULL);
  p_input_transform   = ui.GetStr(SNAME":FEATURETRANSFORM",  NULL);

  p_targetmmf         = ui.GetStr(SNAME":TARGETMMF",     NULL);

  p_script            = ui.GetStr(SNAME":SCRIPT",         NULL);
  p_output_label_map  = ui.GetStr(SNAME":OUTPUTLABELMAP", NULL);

  learning_rate       = ui.GetFlt(SNAME":LEARNINGRATE"  , 0.06f);
  learning_rate_factors = ui.GetStr(SNAME":LEARNRATEFACTORS", NULL);
  momentum            = ui.GetFlt(SNAME":MOMENTUM"      , 0.0);
  weightcost          = ui.GetFlt(SNAME":WEIGHTCOST"    , 0.0);
  bptt                = ui.GetInt(SNAME":BPTT"          , 4);

  obj_fun_id          = static_cast<CuObjectiveFunction::ObjFunType>(
                        ui.GetEnum(SNAME":OBJECTIVEFUNCTION",
                                   CuObjectiveFunction::CROSS_ENTROPY, //< default
                                   "xent", CuObjectiveFunction::CROSS_ENTROPY,
                                   "mse", CuObjectiveFunction::MEAN_SQUARE_ERROR
                        ));

  p_source_mlf_file   = ui.GetStr(SNAME":SOURCEMLF",       NULL);
  p_src_lbl_dir       = ui.GetStr(SNAME":SOURCETRANSCDIR", NULL);
  p_src_lbl_ext       = ui.GetStr(SNAME":SOURCETRANSCEXT", "lab");

  cross_validate      = ui.GetBool(SNAME":CROSSVALIDATE",  false);

  trace               = ui.GetInt(SNAME":TRACE",               0);
  //if(trace&1) {
    CuDevice::Instantiate().Verbose(true);
  //}

  //throw away...
  ui.GetInt(SNAME":BUNCHSIZE", 256);
  ui.GetInt(SNAME":CACHESIZE", 12800);
  ui.GetBool(SNAME":RANDOMIZE", true);

  // process the parameters
  if(ui.GetBool(SNAME":PRINTCONFIG", false)) {
    std::cout << std::endl;
    ui.PrintConfig(std::cout);
    std::cout << std::endl;
  }
  if(ui.GetBool(SNAME":PRINTVERSION", false)) {
    std::cout << std::endl;
    std::cout << "======= "MODULE_VERSION" =======" << std::endl;
    std::cout << std::endl;
  }
  ui.CheckCommandLineParamUse();

  // the rest of the parameters are the feature files
  for (; args_parsed < argc; args_parsed++) {
    feature_repo.AddFile(argv[args_parsed]);
  }

  //**************************************************************************
  //**************************************************************************
  // OPTION PARSING DONE .....................................................

  //read the input transform network
  if(NULL != p_input_transform) {
    if(trace&1) TraceLog(std::string("Reading input transform network: ")+p_input_transform);
    transform_network.ReadNetwork(p_input_transform);
  }

  //read the neural network
  if(NULL != p_source_mmf_file) {
    if(trace&1) TraceLog(std::string("Reading network: ")+p_source_mmf_file);
    network.ReadNetwork(p_source_mmf_file);
  } else {
    Error("Source MMF must be specified [-H]");
  }

  // initialize the feature repository
  feature_repo.Init(
    swap_features, start_frm_ext, end_frm_ext, target_kind,
    deriv_order, p_deriv_win_lenghts,
    cmn_path, cmn_mask, cvn_path, cvn_mask, cvg_file
  );
  if(NULL != p_script) {
    feature_repo.AddFileList(p_script);
  } else {
    Warning("WARNING: The script file is missing [-S]");
  }

  // initialize the label repository
  if(NULL == p_source_mlf_file)
    Error("Source mlf file file is missing [-I]");
  if(NULL == p_output_label_map)
    Error("Output label map is missing [-m]");
  label_repo.Init(p_source_mlf_file, p_output_label_map, p_src_lbl_dir, p_src_lbl_ext);

  //get objective function instance
  p_obj_function = CuObjectiveFunction::Factory(obj_fun_id);

  //set the learnrate, etc
  network.SetLearnRate(learning_rate, learning_rate_factors);
  network.SetMomentum(momentum);
  network.SetWeightcost(weightcost);

  //set the BPTT order
  for(int i=0; i<network.Layers(); i++) {
    if(network.Layer(i).GetType() == CuComponent::RECURRENT) {
      dynamic_cast<CuRecurrent&>(network.Layer(i)).BpttOrder(bptt);
    }
  }

  //**********************************************************************
  //**********************************************************************
  // INITIALIZATION DONE .................................................
  //
  // Start training
  timer.Start();
  if(cross_validate) {
    std::cout << "===== TRecurrentCu CROSSVAL STARTED =====" << std::endl;
  } else {
    std::cout << "===== TRecurrentCu TRAINING STARTED =====" << std::endl;
  }

  feature_repo.Rewind();

  //**********************************************************************
  //**********************************************************************
  // MAIN LOOP
  //
  int frames = 0;
  Matrix<BaseFloat> targets_host;
  CuMatrix<BaseFloat> feats, output, targets, globerr;
  for(feature_repo.Rewind(); !feature_repo.EndOfList(); feature_repo.MoveNext()) {

    timer_frontend.Start();

    Matrix<BaseFloat> feats_host, globerr_host;
    CuMatrix<BaseFloat> feats_original;
    CuMatrix<BaseFloat> feats_expanded;

    //read feats, perfrom feature transform
    feature_repo.ReadFullMatrix(feats_host);
    feats_original.CopyFrom(feats_host);
    transform_network.Propagate(feats_original,feats_expanded);

    //trim the start/end context
    int rows = feats_expanded.Rows()-start_frm_ext-end_frm_ext;
    feats.Init(rows,feats_expanded.Cols());
    feats.CopyRows(rows,start_frm_ext,feats_expanded,0);

    timer_frontend.End(); time_frontend += timer_frontend.Val();

    //read the targets
    label_repo.GenDesiredMatrix(targets_host,feats.Rows(),
                                feature_repo.CurrentHeader().mSamplePeriod,
                                feature_repo.Current().Logical().c_str());
    targets.CopyFrom(targets_host);

    //reset the history context
    for(int i=0; i<network.Layers(); i++) {
      if(network.Layer(i).GetType() == CuComponent::RECURRENT) {
        dynamic_cast<CuRecurrent&>(network.Layer(i)).ClearHistory();
      }
    }

    CuMatrix<BaseFloat> input_row(1,feats.Cols());
    CuMatrix<BaseFloat> output_row(1,network.GetNOutputs());
    CuMatrix<BaseFloat> target_row(1,network.GetNOutputs());
    CuMatrix<BaseFloat> error_row(1,network.GetNOutputs());
    for(size_t frm=0; frm<feats.Rows(); frm++) {
      //select data rows
      input_row.CopyRows(1,frm,feats,0);
      target_row.CopyRows(1,frm,targets,0);

      //forward
      network.Propagate(input_row,output_row);

      //xetropy
      p_obj_function->Evaluate(output_row,target_row,error_row);

      if(!cross_validate) {
        //backward
        network.Backpropagate(error_row);
      }
    }

    frames += feats.Rows();
    std::cout << "." << std::flush;
  }

  //**********************************************************************
  //**********************************************************************
  // TRAINING FINISHED .................................................
  //
  // Let's store the network, report the log

  if(cross_validate) {
    if(trace&1) TraceLog("Crossval finished");
  } else {
    if(trace&1) TraceLog("Training finished");
  }

  //write the network
  if(!cross_validate) {
    if (NULL != p_targetmmf) {
      if(trace&1) TraceLog(std::string("Writing network: ")+p_targetmmf);
      network.WriteNetwork(p_targetmmf);
    } else {
      Error("forgot to specify --TARGETMMF argument");
    }
  }

  timer.End();
  std::cout << std::endl;
  std::cout << "===== TRecurrentCu FINISHED ( " << timer.Val() << "s ) "
            << "[FPS:" << float(frames) / timer.Val()
            << ",RT:" << 1.0f / (float(frames) / timer.Val() / 100.0f)
            << "] =====" << std::endl;

  //report objective function (accuracy, frame counts...)
  std::cout << "-- " << (cross_validate?"CV":"TR") << p_obj_function->Report();
  std::cout << "T-fe: " << time_frontend << std::endl;

  return  0; ///finish OK

} catch (std::exception& rExc) {
  std::cerr << "Exception thrown" << std::endl;
  std::cerr << rExc.what() << std::endl;
  return  1;
}


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Armature.Core.Common;
using Armature.Core.Logging;
using JetBrains.Annotations;

namespace Armature.Core.UnitSequenceMatcher
{
  /// <summary>
  ///   Base class exposing the collection of children matchers, gathering and merging build actions from children with its own.
  /// </summary>
  public abstract class UnitSequenceMatcherWithChildren : UnitSequenceMatcher
  {
    private HashSet<IUnitSequenceMatcher> _children;

    protected UnitSequenceMatcherWithChildren(int weight) : base(weight) { }

    private HashSet<IUnitSequenceMatcher> LazyChildren { [DebuggerStepThrough] get => _children ?? (_children = new HashSet<IUnitSequenceMatcher>()); }

    [NotNull]
    public override ICollection<IUnitSequenceMatcher> Children { [DebuggerStepThrough] get { return LazyChildren; } }

    /// <summary>
    ///   Gets and merges matched actions from all children matchers
    /// </summary>
    /// <param name="inputMatchingWeight">The weight of matching which passed to children to calculate a final weight of matching.</param>
    /// <param name="unitBuildingSequence">The sequence of units building in this build session.</param>
    [DebuggerStepThrough]
    [CanBeNull]
    protected MatchedBuildActions GetChildrenActions(int inputMatchingWeight, ArrayTail<UnitInfo> unitBuildingSequence) =>
      _children?.Aggregate(
        (MatchedBuildActions)null,
        (current, child) => current.Merge(child.GetBuildActions(unitBuildingSequence, inputMatchingWeight)));

    [SuppressMessage("ReSharper", "ArrangeThisQualifier")]
    protected MatchedBuildActions GetActions(ArrayTail<UnitInfo> buildingUnitsSequence, int inputWeight)
    {
      MatchedBuildActions matchedBuildActions;
      if (buildingUnitsSequence.Length > 1)
      {
        Log.WriteLine(LogLevel.Verbose, this.ToString);  // pass group method, do not call ToString
        using (Log.AddIndent())
        {
          matchedBuildActions = GetChildrenActions(
            inputWeight + Weight,
            buildingUnitsSequence.GetTail(1)); // pass the rest of the sequence to children and return their actions
        }
      }
      else
      {
        matchedBuildActions = GetOwnActions(Weight + inputWeight);
        if (matchedBuildActions == null)
          Log.WriteLine(LogLevel.Trace, () => string.Format("{0}{{not matched}}", this));
        else
          using (Log.Block(LogLevel.Verbose, this.ToString)) // pass group method, do not call ToString
          {
            // ReSharper disable once RedundantArgumentDefaultValue
            matchedBuildActions.ToLog(LogLevel.Verbose);
          }
      }

      return matchedBuildActions;
    }
  }
}


text:
using Newtonsoft.Json;

namespace TMDbLib.Objects.Account
{
    public class Gravatar
    {
        [JsonProperty("hash")]
        public string Hash { get; set; }
    }
}


text:
package com.ducetech.framework.data;

import com.ducetech.framework.support.service.DynamicConfigService;
import com.ducetech.framework.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 数据库数据初始化处理器基类
 */
public abstract class DatabaseDataInitializeProcessor {

    private final static Logger logger = LoggerFactory.getLogger(DatabaseDataInitializeProcessor.class);

    private SqlSessionFactory sqlSessionFactory;

    public void initialize(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
        logger.debug("Invoking data process for {}", this);
        initializeInternal();
        //确保最后提交事务
        commitAndResumeTransaction();
        if (DynamicConfigService.isDevMode()) {
            //重置恢复模拟数据设置的临时时间
            DateUtil.setCurrentDate(null);
        }
    }

    /**
     * 帮助类方法,从当前类的classpath路径下面读取文本内容为String字符串
     * @param fileName 文件名称
     * @return
     */
    protected String getStringFromTextFile(String fileName) {
        InputStream is = this.getClass().getResourceAsStream(fileName);
        try {
            String text = IOUtils.toString(is, "UTF-8");
            return text;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    protected int executeNativeSQL(String sql) {
        //TODO
        return 0;
    }

    /**
     * 查询整个数据对象表
     */
    @SuppressWarnings("unchecked")
    protected <X> List<X> findAll(Class<X> entity) {
        //TODO
        return null;
    }

    /**
     * 获取表数据总记录数
     */
    protected int countTable(Class<?> entity) {
        //TODO
        return 0;
    }

    /**
     * 判定实体对象对应表是否为空
     */
    protected boolean isEmptyTable(Class<?> entity) {
        //TODO
        return true;
    }

    /**
     * 提交当前事务并新起一个事务
     */
    protected void commitAndResumeTransaction() {
        //TODO
    }

    public abstract void initializeInternal();
}


text:
package org.apache.camel.reifier;

import org.apache.camel.AggregationStrategy;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Expression;
import org.apache.camel.Processor;
import org.apache.camel.model.EnrichDefinition;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.Enricher;
import org.apache.camel.processor.aggregate.AggregationStrategyBeanAdapter;
import org.apache.camel.spi.RouteContext;

public class EnrichReifier extends ExpressionReifier<EnrichDefinition> {

    EnrichReifier(ProcessorDefinition<?> definition) {
        super(EnrichDefinition.class.cast(definition));
    }

    @Override
    public Processor createProcessor(RouteContext routeContext) throws Exception {

        Expression exp = definition.getExpression().createExpression(routeContext);
        boolean isShareUnitOfWork = definition.getShareUnitOfWork() != null && definition.getShareUnitOfWork();
        boolean isIgnoreInvalidEndpoint = definition.getIgnoreInvalidEndpoint() != null && definition.getIgnoreInvalidEndpoint();

        Enricher enricher = new Enricher(exp);
        enricher.setShareUnitOfWork(isShareUnitOfWork);
        enricher.setIgnoreInvalidEndpoint(isIgnoreInvalidEndpoint);
        AggregationStrategy strategy = createAggregationStrategy(routeContext);
        if (strategy != null) {
            enricher.setAggregationStrategy(strategy);
        }
        if (definition.getAggregateOnException() != null) {
            enricher.setAggregateOnException(definition.getAggregateOnException());
        }
        return enricher;
    }

    private AggregationStrategy createAggregationStrategy(RouteContext routeContext) {
        AggregationStrategy strategy = definition.getAggregationStrategy();
        if (strategy == null && definition.getAggregationStrategyRef() != null) {
            Object aggStrategy = routeContext.lookup(definition.getAggregationStrategyRef(), Object.class);
            if (aggStrategy instanceof AggregationStrategy) {
                strategy = (AggregationStrategy) aggStrategy;
            } else if (aggStrategy != null) {
                AggregationStrategyBeanAdapter adapter = new AggregationStrategyBeanAdapter(aggStrategy, definition.getAggregationStrategyMethodName());
                if (definition.getAggregationStrategyMethodAllowNull() != null) {
                    adapter.setAllowNullNewExchange(definition.getAggregationStrategyMethodAllowNull());
                    adapter.setAllowNullOldExchange(definition.getAggregationStrategyMethodAllowNull());
                }
                strategy = adapter;
            } else {
                throw new IllegalArgumentException("Cannot find AggregationStrategy in Registry with name: " + definition.getAggregationStrategyRef());
            }
        }

        if (strategy instanceof CamelContextAware) {
            ((CamelContextAware) strategy).setCamelContext(routeContext.getCamelContext());
        }

        return strategy;
    }

}


text:
package definiti.core

import definiti.common.ast.TypeReference

object Constants {
  val boolean = TypeReference("Boolean")
  val integer = TypeReference("Integer")
  val number = TypeReference("Number")
  val string = TypeReference("String")
  val unit = TypeReference("unit")
  val date = TypeReference("Date")

  def list(typ: String) = TypeReference("List", Seq(TypeReference(typ)))

  def option(typ: String) = TypeReference("Option", Seq(TypeReference(typ)))
}


text:
title: "In a nice suit"
excerpt: "PaperFaces portrait of @pepfre drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-pepfre-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-pepfre-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---

PaperFaces portrait of project donator [@pepfre](https://twitter.com/pepfre).

{% include_cached boilerplate/paperfaces.md %}


text:
import * as _ from 'lodash';
import * as React from 'react';
import { reduxForm } from 'redux-form';
import { FormComponentProps } from './interfaces';
import Contact from './contact';
import Service from './contact.service';
import { DecoratorComponent as Component } from '../decorator';
import { UiDismissableComponent as Dismissable, UiIconComponent as Icon } from '../ui';
import { UtilsValidator as createValidator } from '../utils';

@Component( {
  actions: { send: Service.sendEmail },
  entities: { contact: Service.fetchItem },
  prefix: 'contact-form',
  styles: {
    Component: 'form-horizontal',
    SubmitButton: 'btn btn-default',
    SubmitSection: 'form-group',
    SubmitWrapper: 'col-xs-offset-3 col-sm-9',
  },
} )
@reduxForm( {
  fields: [ 'email', 'message', 'name' ],
  form: 'contact-form',
  touchOnChange: true,
  validate: createValidator( { email: 'length:0:80,emailAtSign,emailUsername,emailDomain,required', message: 'required', name: 'required' } ),
} )
export default class ContactFormComponent extends React.Component<FormComponentProps, any> {
  public defaultProps: FormComponentProps = {
    formatEmail: ( contact: Contact, information: any ): any => {
      let html: string = `Bonjour ${ contact.name },<br /><br />Cet e-mail provient du formulaire de contact du site ${ contact.website }`;
      html += `<br/>Vous avez reçu un message de ${ information.name }( ${ information.email } ) :<br />${ information.message }`;
      return { from: information.name + ' <' + information.email + '>', html, subject: `MESSAGERIE DU SITE ${ contact.website }`, to: contact.email };
    },
  };

  public componentWillReceiveProps( nextProps: FormComponentProps ): void {
    if ( _.get( this.props, 'requests.send.loading' ) && !_.get( nextProps, 'requests.send.loading' ) ) nextProps.initializeForm( { message: '' } );
  }

  public render(): JSX.Element {
    const { contact, fields: { email, name, message }, formatEmail, handleSubmit, id, requests, send, styles }: FormComponentProps = this.props;

    return (
      <form className = { styles.Component } onSubmit = { handleSubmit( ( data ) => send( contact.slug, formatEmail( contact, data ) ) ) }>
        <Dismissable actionID = "send" compID = { id } styles = { styles.Dismissable } { ..._.get( requests, 'send' ) } />
        { this._renderInput( name, { label: 'Nom', placeholder: 'Nom...', type: 'text' } ) }
        { this._renderInput( email, { label: 'Courriel', placeholder: 'Courriel...', type: 'text' } ) }
        { this._renderInput( message, { label: 'Message', placeholder: 'Message...', rows: 6, type: 'textarea' } ) }
        { this._renderSubmit( this.props ) }
      </form>
    );
  }

  private _renderInput( field: any, attributes: any ): JSX.Element {
    const attrs: any = field.touched ? _.merge( attributes, { bsStyle: field.error ? 'error' : 'success', help: field.error } ) : attributes;
    return (

        { attrs.label }

          <input type = { attrs.type } className = "form-control" placeholder = { attrs.placeholder } />

    );
    // return <Input labelClassName="col-xs-3" wrapperClassName="col-xs-9" hasFeedback { ...attrs } { ...field } />;
  }

  private _renderSubmit( props: FormComponentProps ): JSX.Element {
    const { requests, styles }: FormComponentProps = props;
    const [ disabled, icon, iconSpin, label ]: any = _.get( requests, 'send.loading' ) ? [ true, 'cog', true, 'Envoi en cours...' ] : [ false, 'paper-plane', false, 'Envoyer' ];

    return (

          <button className = { styles.SubmitButton } disabled = { disabled } type = "submit"><Icon icon = { icon } spin = { iconSpin } />{ label }</button>

    );
  }

}


text:
package com.hivemq.spi.config;

import java.io.File;

/**
 * Useful information about HiveMQ and the underlying system
 *
 * @author Christoph Schäbel
 * @since 3.0
 */
public interface SystemInformation {

    /**
     * @return the version string of HiveMQ
     */
    String getHiveMQVersion();

    /**
     * @return the home folder of HiveMQ
     */
    File getHiveMQHomeFolder();

    /**
     * @return the plugin folder of HiveMQ
     */
    File getPluginFolder();

    /**
     * @return the config folder of HiveMQ
     */
    File getConfigFolder();

    /**
     * @return the log folder of HiveMQ
     */
    File getLogFolder();

    /**
     * @return the license folder of HiveMQ
     */
    File getLicenseFolder();

    /**
     * @return the data folder of HiveMQ
     */
    File getDataFolder();

    /**
     * @return the backup folder of HiveMQ
     */
    File getBackupFolder();

    /**
     * @return the timestamp of HiveMQ start
     */
    long getRunningSince();
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mucor corticolus Hagem

### Remarks
null


text:
**Please note: the Bits-Service is not actively maintained anymore. [More information](https://lists.cloudfoundry.org/g/cf-dev/message/8660).**

The bits-service is an extraction from existing functionality of the [cloud controller](https://github.com/cloudfoundry/cloud_controller_ng). It encapsulates all "bits operations" into its own, separately scalable service. All bits operations comprise buildpacks, droplets, app_stashes, packages and the buildpack_cache.

[The API](http://cloudfoundry-incubator.github.io/bits-service/) is a work in progress and will most likely change.

## Supported Backends

Bits currently supports [WebDAV](https://en.wikipedia.org/wiki/WebDAV) and the following [Fog](http://fog.io/) connectors:

* AWS S3
* Azure
* Google
* Local (NFS)
* Openstack

## Development

The CI config is in the [bits-service-ci](https://github.com/cloudfoundry-incubator/bits-service-ci) repo.

## Additional Notes

It can be used standalone or through its [BOSH-release](https://github.com/cloudfoundry-incubator/bits-service-release).

## Getting Started

Make sure you have a working [Go environment](https://golang.org/doc/install) and the Go vendoring tool [glide](https://github.com/Masterminds/glide#install) is properly installed.

To install bitsgo:

```bash
mkdir -p $GOPATH/src/github.com/cloudfoundry-incubator
cd $GOPATH/src/github.com/cloudfoundry-incubator

git clone https://github.com/cloudfoundry-incubator/bits-service.git
cd bits-service

glide install

cd cmd/bitsgo
go install
```

Then run it:

```
bitsgo --config my/path/to/config.yml
```

To run tests:

1. Install [ginkgo](https://onsi.github.io/ginkgo/#getting-ginkgo)
1. Configure `$PATH`:

   ```bash
   export PATH=$GOPATH/bin:$PATH
   ```

1. Run tests with

	 ```bash
	 scripts/run-unit-tests
	 ```

## Contributing to Bits-Service
The Bits-Service team is happy to receive  feedback, suggestions, improvements and Pull Requests.

**If you want to create a Pull Request against Bits-Service please make sure that the Unit Tests are passing successfully** (as described in the [Getting Started section](#Getting-started))

If you would like to discuss about possible changes or improvements feel free to reach out to us via [Bits-Service Cloud Foundry Slack](https://cloudfoundry.slack.com/messages/C0BNGJY0G)


text:
jawr-main-repo
==============
[![Build Status](https://travis-ci.org/j-a-w-r/jawr-main-repo.svg?branch=master)](https://travis-ci.org/j-a-w-r/jawr-main-repo)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/net.jawr/jawr-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/net.jawr/jawr-core)

Jawr main repository :

This repository contains the links to all Jawr related repositories, which are reference as subtrees.
The core repository is named Jawr.

The project documentation is available at the following link : https://j-a-w-r.github.io


text:
CURRENT_DIR=$(pwd)

CURRENT_DIR=$(pwd)
PARENT_DIR=$(basename ${CURRENT_DIR})

echo "CURRENT_DIR: ${CURRENT_DIR}"
echo "PARENT_DIR: ${PARENT_DIR}"

docker-compose up


text:
/**
 * Imports
 */
import BaseStore from 'fluxible/addons/BaseStore';
import orderActions from '../../constants/orders';

/**
 * Store
 */
class OrderStore extends BaseStore {

    static storeName = 'OrderStore';

    static handlers = {
        [orderActions.ORDER_CREATE]: 'handleCreateRequest',
        [orderActions.ORDER_CREATE_SUCCESS]: 'handleCreateSuccess',
        [orderActions.ORDER_CREATE_ERROR]: 'handleCreateError',

        [orderActions.ORDER_CLEAR]: 'handleOrderClear'
    };

    constructor(dispatcher) {
        super(dispatcher);
        this.loading = false;
        this.error = undefined;
        this.order = undefined;
    }

    getState() {
        return {
            loading: this.loading,
            error: this.error,
            order: this.order
        }
    }

    //
    // Isomorphic stuff
    //

    dehydrate() {
        return this.getState();
    }

    rehydrate(state) {
        this.loading = state.loading;
        this.error = state.error;
        this.order = state.order;
    }

    //
    // Getters
    //

    isLoading() {
        return this.loading === true;
    }

    getError() {
        return this.error;
    }

    getOrder() {
        return this.order;
    }

    //
    // Handlers
    //

    // Create

    handleCreateRequest() {
        this.loading = true;
        this.emitChange();
    }

    handleCreateSuccess(payload) {
        this.loading = false;
        this.error = null;
        this.order = payload;
        this.emitChange();
    }

    handleCreateError(payload) {
        this.loading = false;
        this.error = payload;
        this.emitChange();
    }

    // Clear store

    handleOrderClear() {
        this.loading = false;
        this.order = null;
        this.error = null;
        this.emitChange();
    }
}

/**
 * Export
 */
export default OrderStore;


text:
import { createReducer } from 'utils/createReducer';
import { nextPage, prevPage, toStart, toPage, searchHero } from '../actions';

interface IPage {
  limit: number;
  page: number;
}

const initialState: IPage = {
  limit: 18,
  page: 1
};

export default createReducer({
  [nextPage]: (state: IPage): IPage => ({
    ...state,
    page: state.page + 1
  }),
  [prevPage]: (state: IPage): IPage => ({
    ...state,
    page: state.page - 1
  }),
  [toStart]: (state: IPage): IPage => ({
    ...state,
    page: initialState.page
  }),
  [toPage]: (state: IPage, page: number): IPage => ({
    ...state,
    page
  }),
  [searchHero]: (state: IPage): IPage => ({
    ...state,
    page: initialState.page
  })
}, initialState);


text:
				<bx_if:delete>

				</bx_if:delete>


text:
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated';

import { ApiService } from './shared';
import { HomeComponent } from './home';
import { AboutComponent } from './about';

import '../style/app.scss';

/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'my-app', // <my-app></my-app>
  providers: [ApiService],
  directives: [...ROUTER_DIRECTIVES],
  template: require('./app.component.html'),
  styles: [require('./app.component.scss')],
})
@RouteConfig([
  {path: '/', component: HomeComponent, name: 'Home'},
  {path: '/About', component: AboutComponent, name: 'About'}
])
export class AppComponent {
  url = process.env.ENV === 'webpack' ? '/hackers-toolkit/img/angular.png' : 'img/angular.png';

  constructor(private api: ApiService) {
  }
}


text:
namespace base {
class SequencedTaskRunner;
}

namespace bookmarks {

class BookmarkModel;

// BookmarkStorage handles writing bookmark model to disk (as opposed to
// ModelLoader which takes care of loading).
//
// Internally BookmarkStorage uses BookmarkCodec to do the actual write.
class BookmarkStorage
    : public base::ImportantFileWriter::BackgroundDataSerializer {
 public:
  // How often the file is saved at most.
  static constexpr base::TimeDelta kSaveDelay = base::Milliseconds(2500);

  // Creates a BookmarkStorage for the specified model. The data will saved to a
  // file using the specified |file_path|. A backup file may be generated using
  // a name derived from |file_path| (appending suffix kBackupExtension). All
  // disk writes will be executed as a task in a backend task runner.
  BookmarkStorage(BookmarkModel* model, const base::FilePath& file_path);

  BookmarkStorage(const BookmarkStorage&) = delete;
  BookmarkStorage& operator=(const BookmarkStorage&) = delete;

  ~BookmarkStorage() override;

  // Schedules saving the bookmark bar model to disk.
  void ScheduleSave();

  // Notification the bookmark bar model is going to be deleted. If there is
  // a pending save, it is saved immediately.
  void BookmarkModelDeleted();

  // ImportantFileWriter::BackgroundDataSerializer implementation.
  base::ImportantFileWriter::BackgroundDataProducerCallback
  GetSerializedDataProducerForBackgroundSequence() override;

  // Returns whether there is still a pending write.
  bool HasScheduledSaveForTesting() const;

 private:
  // The state of the bookmark file backup. We lazily backup this file in order
  // to reduce disk writes until absolutely necessary. Will also leave the
  // backup unchanged if the browser starts & quits w/o changing bookmarks.
  enum BackupState {
    // No attempt has yet been made to backup the bookmarks file.
    BACKUP_NONE,
    // A request to backup the bookmarks file has been posted, but not yet
    // fulfilled.
    BACKUP_DISPATCHED,
    // The bookmarks file has been backed up (or at least attempted).
    BACKUP_ATTEMPTED
  };

  // Serializes the data and schedules save using ImportantFileWriter.
  // Returns true on successful serialization.
  bool SaveNow();

  // The model. The model is NULL once BookmarkModelDeleted has been invoked.
  raw_ptr<BookmarkModel> model_;

  // Sequenced task runner where disk writes will be performed at.
  scoped_refptr<base::SequencedTaskRunner> backend_task_runner_;

  // Helper to write bookmark data safely.
  base::ImportantFileWriter writer_;

  // The state of the backup file creation which is created lazily just before
  // the first scheduled save.
  bool backup_triggered_ = false;

  // Used to track the frequency of saves starting from the first save.
  base::TimeTicks last_scheduled_save_;
};

}  // namespace bookmarks

#endif  // COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_STORAGE_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samdide.android.androidbilling" >

    <uses-permission android:name="com.android.vending.BILLING" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package org.apache.hadoop.yarn.service;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.KerberosInfo;
import org.apache.hadoop.security.SecurityInfo;
import org.apache.hadoop.security.token.TokenInfo;
import org.apache.hadoop.yarn.service.conf.YarnServiceConstants;
import org.apache.hadoop.yarn.service.impl.pb.service.ClientAMProtocolPB;

import java.lang.annotation.Annotation;

/**
 * Security Info for Client to Service AM protocol.
 */
public class ClientAMSecurityInfo extends SecurityInfo{
  @Override
  public KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf) {
    if (!protocol.equals(ClientAMProtocolPB.class)) {
      return null;
    }
    return new KerberosInfo() {

      @Override
      public Class<? extends Annotation> annotationType() {
        return null;
      }

      @Override
      public String serverPrincipal() {
        return YarnServiceConstants.PRINCIPAL;
      }

      @Override
      public String clientPrincipal() {
        return null;
      }
    };
  }

  @Override
  public TokenInfo getTokenInfo(Class<?> protocol, Configuration conf) {
    return null;
  }
}


text:
package mock

import "github.com/kusubooru/teian/teian"

type SuggestionStore struct {
	CreateFn      func(username string, sugg *teian.Suggestion) error
	CreateInvoked bool

	OfUserFn      func(username string) ([]teian.Suggestion, error)
	OfUserInvoked bool

	AllFn      func() ([]teian.Suggestion, error)
	AllInvoked bool

	DeleteFn      func(username string, id uint64) error
	DeleteInvoked bool

	CheckQuotaFn      func(username string, n teian.Quota) (teian.Quota, error)
	CheckQuotaInvoked bool
}

func (s *SuggestionStore) Create(username string, sugg *teian.Suggestion) error {
	s.CreateInvoked = true
	return s.CreateFn(username, sugg)
}
func (s *SuggestionStore) OfUser(username string) ([]teian.Suggestion, error) {
	s.OfUserInvoked = true
	return s.OfUserFn(username)
}
func (s *SuggestionStore) All() ([]teian.Suggestion, error) {
	s.AllInvoked = true
	return s.AllFn()
}
func (s *SuggestionStore) Delete(username string, id uint64) error {
	s.DeleteInvoked = true
	return s.DeleteFn(username, id)
}
func (s *SuggestionStore) CheckQuota(username string, n teian.Quota) (teian.Quota, error) {
	s.CheckQuotaInvoked = true
	return s.CheckQuotaFn(username, n)
}


text:
package org.dozer.classmap;

import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.lang3.StringUtils;
import org.dozer.util.MappingUtils;

/**
 * Internal class that determines the appropriate class mapping to be used for
 * the source and destination object being mapped. Only intended for internal
 * use.
 *
 * @author tierney.matt
 * @author garsombke.franz
 */
public class ClassMappings {

  // Cache key --> Mapping Structure
  private ConcurrentMap<String, ClassMap> classMappings = new ConcurrentHashMap<String, ClassMap>();
  private ClassMapKeyFactory keyFactory;

  public ClassMappings() {
    keyFactory = new ClassMapKeyFactory();
  }

  // Default mappings. May be ovewritten due to multiple threads generating same mapping
  public void addDefault(Class<?> srcClass, Class<?> destClass, ClassMap classMap) {
    classMappings.put(keyFactory.createKey(srcClass, destClass), classMap);
  }

  public void add(Class<?> srcClass, Class<?> destClass, ClassMap classMap) {
    ClassMap result = classMappings.put(keyFactory.createKey(srcClass, destClass), classMap);
    failOnDuplicate(result, classMap);
  }

  public void add(Class<?> srcClass, Class<?> destClass, String mapId, ClassMap classMap) {
    ClassMap result = classMappings.put(keyFactory.createKey(srcClass, destClass, mapId), classMap);
    failOnDuplicate(result, classMap);
  }

  public void addAll(ClassMappings additionalClassMappings) {
    Map<String, ClassMap> newMappings = additionalClassMappings.getAll();
    for (Entry<String, ClassMap> entry : newMappings.entrySet()) {
      ClassMap result = classMappings.put(entry.getKey(), entry.getValue());
      failOnDuplicate(result, entry.getValue());
    }
  }

  public void failOnDuplicate(Object result, ClassMap classMap) {
    if (result != null && !classMap.getSrcClassName().equals(classMap.getDestClassName())) {
      throw new IllegalArgumentException("Duplicate Class Mapping Found. Source: " + classMap.getSrcClassName()
              + " Destination: " + classMap.getDestClassName() + " map-id: " + classMap.getMapId());
    }
  }

  public Map<String, ClassMap> getAll() {
    return new HashMap<String, ClassMap>(classMappings);
  }

  public long size() {
    return classMappings.size();
  }

  public ClassMap find(Class<?> srcClass, Class<?> destClass) {
    return classMappings.get(keyFactory.createKey(srcClass, destClass));
  }

  public boolean contains(Class<?> srcClass, Class<?> destClass, String mapId) {
    String key = keyFactory.createKey(srcClass, destClass, mapId);
    return classMappings.containsKey(key);
  }

  public ClassMap find(Class<?> srcClass, Class<?> destClass, String mapId) {
    final String key = keyFactory.createKey(srcClass, destClass, mapId);
    ClassMap mapping = classMappings.get(key);

    if (mapping == null) {
      mapping = findInterfaceMapping(destClass, srcClass, mapId);
      if (mapping != null) {
        ClassMap previous = classMappings.putIfAbsent(keyFactory.createKey(srcClass, destClass, mapId), mapping);
        if (previous != null) {
          mapping = previous;
        }
      }
    }

    // one more try...
    // if the mapId is not null looking up a map is easy
    if (!MappingUtils.isBlankOrNull(mapId) && mapping == null) {
      // probably a more efficient way to do this...
      for (Entry<String, ClassMap> entry : classMappings.entrySet()) {
        ClassMap classMap = entry.getValue();
        if (StringUtils.equals(classMap.getMapId(), mapId)
                && classMap.getSrcClassToMap().isAssignableFrom(srcClass)
                && classMap.getDestClassToMap().isAssignableFrom(destClass)) {
          return classMap;
        } else if (StringUtils.equals(classMap.getMapId(), mapId) && srcClass.equals(destClass)) {
          return classMap;
        }
      }

      // If map-id was specified and mapping was not found, then fail
      MappingUtils.throwMappingException("Class mapping not found by map-id: " + key);
    }

    return mapping;
  }

  // Look for an interface mapping
  private ClassMap findInterfaceMapping(Class<?> destClass, Class<?> srcClass, String mapId) {
    // Use object array for keys to avoid any rare thread synchronization issues
    // while iterating over the custom mappings.
    // See bug #1550275.
    Object[] keys = classMappings.keySet().toArray();
    for (Object key : keys) {
      ClassMap map = classMappings.get(key);
      Class<?> mappingDestClass = map.getDestClassToMap();
      Class<?> mappingSrcClass = map.getSrcClassToMap();

      if ((mapId == null && map.getMapId() != null) || (mapId != null && !mapId.equals(map.getMapId()))) {
        continue;
      }

      if (isInterfaceImplementation(srcClass, mappingSrcClass)) {
        if (isInterfaceImplementation(destClass, mappingDestClass)) {
          return map;
        } else if (destClass.equals(mappingDestClass)) {
          return map;
        }
      }

      // Destination could be an abstract type. Picking up the best concrete type to use.
      if ((destClass.isAssignableFrom(mappingDestClass) && isAbstract(destClass)) ||
              (isInterfaceImplementation(destClass, mappingDestClass))) {
        if (MappingUtils.getRealClass(srcClass).equals(mappingSrcClass)) {
          return map;
        }
      }

    }
    return null;
  }

  private boolean isInterfaceImplementation(Class<?> type, Class<?> mappingType) {
    return mappingType.isInterface() && mappingType.isAssignableFrom(type);
  }

  private static boolean isAbstract(Class<?> destClass) {
    return Modifier.isAbstract(destClass.getModifiers());
  }

}


text:
namespace mojo {
template <>
struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
    StructTraits<smbfs::mojom::IPAddressDataView, net::IPAddress> {
  static base::span<const uint8_t> address_bytes(
      const net::IPAddress& ip_address) {
    return ip_address.bytes();
  }

  static bool Read(smbfs::mojom::IPAddressDataView obj, net::IPAddress* out);
};

}  // namespace mojo

#endif  // ASH_COMPONENTS_SMBFS_IP_ADDRESS_MOJOM_TRAITS_H_


text:
import sys
if sys.version_info < (3,6):
    sys.exit('Sorry, Python < 3.6 is not supported')
import os

from setuptools import setup

from devml import __version__

if os.path.exists('README.md'):
    LONG = open('README.md').read()
else:
    LONG = ''

setup(
    name='devml',
    version=__version__,
    url='https://github.com/noahgift/devml',
    license='MIT',
    author='Noah Gift',
    author_email='consulting@noahgift.com',
    description="""Machine Learning, Statistics and Utilities around Developer Productivity,
        Company Productivity and Project Productivity""",
    long_description=LONG,
    packages=['devml'],
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=[
        'pandas',
        'click',
        'PyGithub',
        'gitpython',
        'sensible',
        'scipy',
        'numpy',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.6',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
    scripts=["dml"],
)


text:
/**************************************************************************/
/*!
    @file     cmd_i2c_scan.c
    @author   K. Townsend (microBuilder.eu)

    @brief    Scans the I2C bus and displays a list of any addresses where
	          a valid I2C response occured.
    @ingroup  CLI

    @section LICENSE

    Software License Agreement (BSD License)

    Copyright (c) 2012, K. Townsend (microbuilder.eu)
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holders nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include <stdio.h>

#include "projectconfig.h"
#include "core/i2c/i2c.h"

#if defined(CFG_ENABLE_I2C)

/**************************************************************************/
/*!
    'sysinfo' command handler
*/
/**************************************************************************/
void cmd_i2c_scan(uint8_t argc, char **argv)
{
  uint8_t addr;
  bool match;

  i2cInit(I2CMASTER);

  // "Scanning I2C bus for devices"
  printf("%s%s%s", STRING(LOCALISATION_TEXT_Scanning_I2C_bus_for_devices), CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE);
  printf("     0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F%s", CFG_PRINTF_NEWLINE);
  printf("00:          ");

  // Scan through I2C address range (0x03-0x77)
  for (addr = 0x03; addr < 0x78; addr++)
  {
    if (!(addr % 0x10))
    {
      printf("%s", CFG_PRINTF_NEWLINE);
      printf("%X: ", addr);
    }

    // Check if we get an ACK at this address
    match = i2cCheckAddress(addr << 1);
    if (match)
    {
      // I2C device found
      printf("%02x ", addr);
    }
    else
    {
      // I2C slave didn't acknowledge the master transfer
      // The device probably isn't connected
      printf("-- ");
    }
  }

  printf("%s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE);
  // "All addresses are in 7-bit format and are not"
  printf("%s%s", STRING(LOCALISATION_TEXT_All_addresses_are_in_7bit_L1), CFG_PRINTF_NEWLINE);
  // "shifted to include the read bit."
  printf("%s%s", STRING(LOCALISATION_TEXT_All_addresses_are_in_7bit_L2), CFG_PRINTF_NEWLINE);
}

#endif /* CFG_ENABLE_I2C */