text:
import datetime
import urllib
import logging
import md5
import re

from django.db import models
from django.contrib import admin
from django.utils.encoding import smart_unicode
from django.template import Template

from agro.sources import utils
from agro.models import Entry

from tagging.fields import TagField

log = logging.getLogger('agro.sources.flickr')

# model definition
class Photo(Entry):
    photo_id    = models.CharField(max_length=200,)
    server      = models.IntegerField(null=True,)
    secret      = models.CharField(max_length=200,null=True,)

    original_secret = models.CharField(max_length=200,null=True,)
    original_format = models.CharField(max_length=4,null=True,)

    num_comments= models.IntegerField(blank=True, null=True,)

    taken_at    = models.DateTimeField(null=True,)
    uploaded_at = models.DateTimeField(null=True,)

    exif        = models.TextField(blank=True, null=True, )

    class Meta:
        ordering = ['-uploaded_at']
        unique_together = [('photo_id', 'server'),]
        app_label = "agro"

    def __unicode__(self):
        return self.title

    @property
    def photog(self):
        return self.owner_user

    @property
    def format_template(self):
        return Template("
 {{ curr_object.title }}
")

    # image urls
    @property
    def image(self):
        """ this is a 500px (longest side) image """
        return self._build_image_url()
    @property
    def thumbnail(self):
        """ this is a 100px (longest side) image """
        return self._build_image_url('t')
    @property
    def square(self):
        """ this is a 75x75 image """
        return self._build_image_url('s')
    @property
    def small(self):
        """ this is a 240px (longest side) image """
        return self._build_image_url('m')
    @property
    def large(self):
        """ this is a 1024 (longest side) image """
        return self._build_image_url('b')
    @property
    def original(self):
        """ original image, gif, png, or jpg. original size as well """
        return self._build_image_url('o')

    def _build_image_url(self, size=None):
        if size in list('stmb'):
            return "http://static.flickr.com/%s/%s_%s_%s.jpg" % (self.server, self.photo_id, self.secret, size)
        elif size == 'o':
            return "http://static.flickr.com/%s/%s_%s_o.%s" % (self.server, self.photo_id, self.original_secret, self.original_format)
        return "http://static.flickr.com/%s/%s_%s.jpg" % (self.server, self.photo_id, self.secret)

# admin definition
class PhotoAdmin(admin.ModelAdmin):
    list_display = ('photo_id', 'title', 'taken_at', 'uploaded_at',)
    date_hierarchy = 'uploaded_at'

# retrieve function, this is how we handle items
def retrieve(force, **args):
    """ this is how we will handle photos """

    username, user_id = args['account']
    flickr = FClient(args['api_key'])

    last_update = datetime.datetime.fromtimestamp(0)
    if force:
        log.info("Forcing update of all available photos")
    else:
        try:
            last_update = Photo.objects.filter(owner_user=username).order_by('-uploaded_at')[0].uploaded_at
        except Exception, e:
            log.debug("%s", e)

    log.debug('last update: %s', last_update)
    page = 1

    while True:
        res = flickr.exe_method('people.getPublicPhotos', user_id=user_id, extras="date_taken,last_update,tags", per_page='500', page=page)
        if res is False:
            log.error('error')
            break

        res = res['photos']
        for photo in res['photo']:
            photo_up_time = datetime.datetime.fromtimestamp(float(photo['lastupdate']))
            if last_update <= photo_up_time:
                log.debug('current photo upload time: %s', photo_up_time)
                _handle_photo(flickr, photo, username)
            else:
                break
        page += 1

        if page > res['pages']:
            log.info('no more photos')
            break

class FClient(object):
    def __init__(self, api_key):
        if isinstance(api_key, (tuple, list)):
            self.api_key, self.secret, self.token = api_key
            self.signed = True
        else:
            self.api_key =  api_key
            self.signed = False

        self.method = 'flickr'
        self.format = 'json'
        self.nojsoncallback = '1'

        log.debug('flickrclient created.')

    def exe_method(self, method, **kwargs):
        kwargs['method']    = '%s.%s' % (self.method,method)
        kwargs['api_key']   = self.api_key
        kwargs['format']    = self.format
        kwargs['nojsoncallback']= self.nojsoncallback

        url = "http://api.flickr.com/services/rest/?"

        for k,v in kwargs.iteritems():
            kwargs[k] = v

        if self.signed:
            kwargs['auth_token'] = self.token
            params = self.encode_and_sign(**kwargs)
            res = utils.get_remote_data(url + params, rformat='json')
        else:
            res = utils.get_remote_data(url + urllib.urlencode(kwargs), rformat='json')

        if res.get("stat", "") == "fail":
            log.error("flickr retrieve failed.")
            log.error("%s" % res.get("stat"))
            return False

        return res

    def sign(self, dictionary):
        data = [self.secret]
        for key in sorted(dictionary.keys()):
            data.append(key)
            datum = dictionary[key]
            if isinstance(datum, unicode):
                raise IllegalArgumentException("No Unicode allowed, "
                        "argument %s (%r) should have been UTF-8 by now"
                        % (key, datum))
            data.append(datum)

        md5_hash = md5.new()
        md5_hash.update(''.join(data))
        return md5_hash.hexdigest()

    def encode_and_sign(self, **kwargs):
        '''URL encodes the data in the dictionary, and signs it using the
        given secret, if a secret was given.
        '''

        dictionary = make_utf8(kwargs)
        if self.secret:
            dictionary['api_sig'] = self.sign(dictionary)
        return urllib.urlencode(dictionary)

def _handle_photo(flickr_obj, photo, user):
    photo_id        = photo['id']
    secret          = smart_unicode(photo['secret'])

    log.info('working with photo => id: %s, secret: %s', photo_id, secret)

    info = flickr_obj.exe_method('photos.getInfo', photo_id=photo_id, secret=secret)['photo']

    photo_obj, created = Photo.objects.get_or_create(
        photo_id    = photo_id,
        owner_user  = smart_unicode(user),
        uploaded_at = datetime.datetime.fromtimestamp(utils.safeint(info["dates"]["posted"])),
        timestamp = datetime.datetime.fromtimestamp(utils.safeint(info["dates"]["posted"])),
        source_type = "photo"
    )

    try:
        photo_obj.url               = "http://www.flickr.com/photos/%s/%s" % (photo_obj.owner_user, photo_obj.photo_id)
        photo_obj.secret            = secret
        photo_obj.server            = utils.safeint(smart_unicode(photo['server']))
        photo_obj.original_secret   = smart_unicode(info['originalsecret'])
        photo_obj.original_format   = smart_unicode(info['originalformat'])
        photo_obj.taken_at          = photo['datetaken']
        photo_obj.title             = smart_unicode(photo['title'])
        photo_obj.description       = smart_unicode(info['description']['_content'])
        photo_obj.num_comments      = utils.safeint(info["comments"]["_content"])
        photo_obj.tags              = smart_unicode(photo['tags'])
        photo_obj.save()
    except Exception, e:
        log.error('%s' % e)

admin.site.register(Photo, PhotoAdmin)

def make_utf8(dictionary):
    '''Encodes all Unicode strings in the dictionary to UTF-8. Converts
    all other objects to regular strings.

    Returns a copy of the dictionary, doesn't touch the original.
    '''

    result = {}

    for (key, value) in dictionary.iteritems():
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        else:
            value = str(value)
        result[key] = value

    return result


text:
Modules
=======

.. automodule:: cpucoolerchart
   :members: __version__

.. automodule:: cpucoolerchart.app
   :members:

.. automodule:: cpucoolerchart.cache
   :members:

.. automodule:: cpucoolerchart.command

.. automodule:: cpucoolerchart.crawler
   :members:

.. automodule:: cpucoolerchart.crawler_data

.. automodule:: cpucoolerchart.extensions
   :members:

.. automodule:: cpucoolerchart.models
   :members:

.. automodule:: cpucoolerchart.views
   :members:

redpajama_set_name: RedPajamaGithub


text:
package org.killbill.billing.invoice.dao;

import java.math.BigDecimal;
import java.util.UUID;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.util.UUIDs;
import org.killbill.billing.util.dao.TableName;
import org.killbill.billing.util.entity.dao.EntityModelDao;
import org.killbill.billing.util.entity.dao.EntityModelDaoBase;

public class InvoiceItemModelDao extends EntityModelDaoBase implements EntityModelDao<InvoiceItem> {

    private InvoiceItemType type;
    private UUID invoiceId;
    private UUID accountId;
    private UUID bundleId;
    private UUID subscriptionId;
    private String description;
    private String planName;
    private String phaseName;
    private String usageName;
    private LocalDate startDate;
    private LocalDate endDate;
    private BigDecimal amount;
    private BigDecimal rate;
    private Currency currency;
    private UUID linkedItemId;

    public InvoiceItemModelDao() { /* For the DAO mapper */ }

    public InvoiceItemModelDao(final UUID id, final DateTime createdDate, final InvoiceItemType type, final UUID invoiceId,
                               final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String description, final String planName,
                               final String phaseName, final String usageName, final LocalDate startDate, final LocalDate endDate, final BigDecimal amount,
                               final BigDecimal rate, final Currency currency, final UUID linkedItemId) {
        super(id, createdDate, createdDate);
        this.type = type;
        this.invoiceId = invoiceId;
        this.accountId = accountId;
        this.bundleId = bundleId;
        this.subscriptionId = subscriptionId;
        this.description = description;
        this.planName = planName;
        this.phaseName = phaseName;
        this.usageName = usageName;
        this.startDate = startDate;
        this.endDate = endDate;
        this.amount = amount;
        this.rate = rate;
        this.currency = currency;
        this.linkedItemId = linkedItemId;
    }

    public InvoiceItemModelDao(final DateTime createdDate, final InvoiceItemType type, final UUID invoiceId, final UUID accountId,
                               final UUID bundleId, final UUID subscriptionId, final String description, final String planName,
                               final String phaseName, final String usageName, final LocalDate startDate, final LocalDate endDate, final BigDecimal amount,
                               final BigDecimal rate, final Currency currency, final UUID linkedItemId) {
        this(UUIDs.randomUUID(), createdDate, type, invoiceId, accountId, bundleId, subscriptionId, description, planName, phaseName, usageName,
             startDate, endDate, amount, rate, currency, linkedItemId);
    }

    public InvoiceItemModelDao(final InvoiceItem invoiceItem) {
        this(invoiceItem.getId(), invoiceItem.getCreatedDate(), invoiceItem.getInvoiceItemType(), invoiceItem.getInvoiceId(), invoiceItem.getAccountId(), invoiceItem.getBundleId(),
             invoiceItem.getSubscriptionId(), invoiceItem.getDescription(), invoiceItem.getPlanName(), invoiceItem.getPhaseName(), invoiceItem.getUsageName(), invoiceItem.getStartDate(), invoiceItem.getEndDate(),
             invoiceItem.getAmount(), invoiceItem.getRate(), invoiceItem.getCurrency(), invoiceItem.getLinkedItemId());
    }

    public InvoiceItemType getType() {
        return type;
    }

    public UUID getInvoiceId() {
        return invoiceId;
    }

    public UUID getAccountId() {
        return accountId;
    }

    public UUID getBundleId() {
        return bundleId;
    }

    public UUID getSubscriptionId() {
        return subscriptionId;
    }

    public String getDescription() {
        return description;
    }

    public String getPlanName() {
        return planName;
    }

    public String getPhaseName() {
        return phaseName;
    }

    public String getUsageName() {
        return usageName;
    }

    public LocalDate getStartDate() {
        return startDate;
    }

    public LocalDate getEndDate() {
        return endDate;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public BigDecimal getRate() {
        return rate;
    }

    public Currency getCurrency() {
        return currency;
    }

    public UUID getLinkedItemId() {
        return linkedItemId;
    }

    public void setType(final InvoiceItemType type) {
        this.type = type;
    }

    public void setInvoiceId(final UUID invoiceId) {
        this.invoiceId = invoiceId;
    }

    public void setAccountId(final UUID accountId) {
        this.accountId = accountId;
    }

    public void setBundleId(final UUID bundleId) {
        this.bundleId = bundleId;
    }

    public void setSubscriptionId(final UUID subscriptionId) {
        this.subscriptionId = subscriptionId;
    }

    public void setPlanName(final String planName) {
        this.planName = planName;
    }

    public void setPhaseName(final String phaseName) {
        this.phaseName = phaseName;
    }

    public void setUsageName(final String usageName) {
        this.usageName = usageName;
    }

    public void setStartDate(final LocalDate startDate) {
        this.startDate = startDate;
    }

    public void setEndDate(final LocalDate endDate) {
        this.endDate = endDate;
    }

    public void setAmount(final BigDecimal amount) {
        this.amount = amount;
    }

    public void setRate(final BigDecimal rate) {
        this.rate = rate;
    }

    public void setCurrency(final Currency currency) {
        this.currency = currency;
    }

    public void setLinkedItemId(final UUID linkedItemId) {
        this.linkedItemId = linkedItemId;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("InvoiceItemModelDao{");
        sb.append("type=").append(type);
        sb.append(", invoiceId=").append(invoiceId);
        sb.append(", accountId=").append(accountId);
        sb.append(", bundleId=").append(bundleId);
        sb.append(", subscriptionId=").append(subscriptionId);
        sb.append(", description='").append(description).append('\'');
        sb.append(", planName='").append(planName).append('\'');
        sb.append(", phaseName='").append(phaseName).append('\'');
        sb.append(", usageName='").append(usageName).append('\'');
        sb.append(", startDate=").append(startDate);
        sb.append(", endDate=").append(endDate);
        sb.append(", amount=").append(amount);
        sb.append(", rate=").append(rate);
        sb.append(", currency=").append(currency);
        sb.append(", linkedItemId=").append(linkedItemId);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        final InvoiceItemModelDao that = (InvoiceItemModelDao) o;

        if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
            return false;
        }
        if (amount != null ? amount.compareTo(that.amount) != 0 : that.amount != null) {
            return false;
        }
        if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
            return false;
        }
        if (currency != that.currency) {
            return false;
        }
        if (description != null ? !description.equals(that.description) : that.description != null) {
            return false;
        }
        if (endDate != null ? endDate.compareTo(that.endDate) != 0 : that.endDate != null) {
            return false;
        }
        if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
            return false;
        }
        if (linkedItemId != null ? !linkedItemId.equals(that.linkedItemId) : that.linkedItemId != null) {
            return false;
        }
        if (phaseName != null ? !phaseName.equals(that.phaseName) : that.phaseName != null) {
            return false;
        }
        if (planName != null ? !planName.equals(that.planName) : that.planName != null) {
            return false;
        }
        if (usageName != null ? !usageName.equals(that.usageName) : that.usageName != null) {
            return false;
        }
        if (rate != null ? rate.compareTo(that.rate) != 0 : that.rate != null) {
            return false;
        }
        if (startDate != null ? startDate.compareTo(that.startDate) != 0 : that.startDate != null) {
            return false;
        }
        if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
            return false;
        }
        if (type != that.type) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0);
        result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
        result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
        result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        result = 31 * result + (planName != null ? planName.hashCode() : 0);
        result = 31 * result + (phaseName != null ? phaseName.hashCode() : 0);
        result = 31 * result + (usageName != null ? usageName.hashCode() : 0);
        result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
        result = 31 * result + (endDate != null ? endDate.hashCode() : 0);
        result = 31 * result + (amount != null ? amount.hashCode() : 0);
        result = 31 * result + (rate != null ? rate.hashCode() : 0);
        result = 31 * result + (currency != null ? currency.hashCode() : 0);
        result = 31 * result + (linkedItemId != null ? linkedItemId.hashCode() : 0);
        return result;
    }

    @Override
    public TableName getTableName() {
        return TableName.INVOICE_ITEMS;
    }

    @Override
    public TableName getHistoryTableName() {
        return null;
    }
}


text:
package com.squareup.wire;

import java.util.LinkedHashMap;
import java.util.Map;

final class ExtensionRegistry {

  private final Map<Class<? extends ExtendableMessage<?>>, Map<Integer, Extension<?, ?>>>
      extensionsByTag = new LinkedHashMap<Class<? extends ExtendableMessage<?>>,
                Map<Integer, Extension<?, ?>>>();
  private final Map<Class<? extends ExtendableMessage<?>>, Map<String, Extension<?, ?>>>
      extensionsByName = new LinkedHashMap<Class<? extends ExtendableMessage<?>>,
          Map<String, Extension<?, ?>>>();

  public <T extends ExtendableMessage<T>, E> void add(Extension<T, E> extension) {
    Class<? extends ExtendableMessage<?>> messageClass = extension.getExtendedType();
    Map<Integer, Extension<?, ?>> tagMap = extensionsByTag.get(messageClass);
    Map<String, Extension<?, ?>> nameMap = extensionsByName.get(messageClass);
    if (tagMap == null) {
      tagMap = new LinkedHashMap<Integer, Extension<?, ?>>();
      nameMap = new LinkedHashMap<String, Extension<?, ?>>();
      extensionsByTag.put(messageClass, tagMap);
      extensionsByName.put(messageClass, nameMap);
    }
    tagMap.put(extension.getTag(), extension);
    nameMap.put(extension.getName(), extension);
  }

  @SuppressWarnings("unchecked")
  public <T extends ExtendableMessage<T>, E> Extension<T, E>
      getExtension(Class<T> messageClass, int tag) {
    Map<Integer, Extension<?, ?>> map = extensionsByTag.get(messageClass);
    return map == null ? null : (Extension<T, E>) map.get(tag);
  }

  @SuppressWarnings("unchecked")
  public <T extends ExtendableMessage<T>, E> Extension<T, E>
      getExtension(Class<T> messageClass, String name) {
    Map<String, Extension<?, ?>> nameMap = extensionsByName.get(messageClass);
    return nameMap == null ? null : (Extension<T, E>) nameMap.get(name);
  }
}


text:
There are basically two types of routes based on the type of request handler, synchronous and
asynchronous. Each route defines basic information like method, uri, documentation string and
handler.

The two main methods for creating routes are:

* `Route.sync(String method, String uri, SyncHandler<T> handler)`
* `Route.async(String method, String uri, AsyncHandler<T> handler)`

Since `RoutingEngine` expects routes of the type `Route<AsyncHandler<T>>`, both `Route.sync` and
`Route.async` return a `Route<AsyncHandler<T>>` and can thus be directly used for registering
routes.

A route added with `RoutingEngine.registerAutoRoute(s)()`, or using the `Middlewares::autoSerialize`
or `Middlewares::apolloDefaults` will serialize its response payload with the `AutoSerializer`.
Routes added with `RoutingEngine.registerRoutes()` must return `Response<ByteString>`s, and
no further processing will be done.

## Route handler reply types

Instead of returning a plain type `T`, a route handler may return a
[`Response<T>`](/apollo-api/src/main/java/com/spotify/apollo/Response.java), which is a wrapper
where you can specify extra information about the reply (see
[Response](/apollo-api/docs/response.md)).

The matrix of sync/async and plain/response combinations looks like this:

|      Type        | `SyncHandler<T>` | `AsyncHandler<T>` |
|:---------------: | -------------- | --------------- |
|     **`T`**      | `T` - A plain synchronous payload replied with status code `200 OK` | `CompletionStage<T>` - A plain asynchronous payload replied with status code `200 OK` |
| **`Response<T>`** | `Response<T>` - A synchronous payload with custom status code and headers | `CompletionStage<Response<T>>` - An asynchronous payload with custom status code and headers |

## Route providers

[`RouteProvider`](/apollo-api/src/main/java/com/spotify/apollo/route/RouteProvider.java) is a
functional interface for creating a
[`Stream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)
of routes.

This is useful for when the application needs to group routes in some logical way and treat them
all in bulk. A REST-ful api with endpoints grouped by resource is a common use case.

```java
static class BlogPost implements RouteProvider {

  @Override
  public Stream<? extends Route<? extends AsyncHandler<?>>> routes() {
    return Stream.of(
        Route.sync("GET", "/blogpost/<id>", ctx -> getPost(ctx.pathArgs().get("id"))),
        Route.sync("POST", "/blogpost", ctx -> createPost(ctx))
    );
  }

  // Post getPost(String id) { ... }
  // Post createPost(RequestContext context) { ... }
}

public static void init(Environment environment) {
  // ...
  environment.routingEngine()
      .registerAutoRoutes(new BlogPost());
}
```

For more utilities that manipulate routes, see the [`apollo-extra`](/apollo-extra) module.


text:
<?php

namespace Renatomefi\TestBundle\MongoDB;

/**
 * Class AssertMongoUtils
 * @package Renatomefi\TestBundle\MongoDB
 * @codeCoverageIgnore
 */
trait AssertMongoUtils
{

    /**
     * @inheritdoc
     */
    protected function assertMongoDateFormat($dateObj)
    {
        if (is_array($dateObj)) $dateObj = (object)$dateObj;

        $this->assertTrue(($dateObj instanceof \stdClass), $dateObj);
        $this->assertNotEmpty($dateObj->sec);
        $this->assertNotEmpty($dateObj->usec);

        $date = new \MongoDate($dateObj->sec, $dateObj->usec);
        $this->assertTrue(($date instanceof \MongoDate));
    }

    /**
     * @inheritdoc
     */
    protected function assertMongoDuplicateEntry(\StdClass $response, $duplicateKey = null)
    {
        $this->assertObjectHasAttribute('code', $response);
        $this->assertEquals(409, $response->code);

        $this->assertObjectHasAttribute('message', $response);
        $this->assertStringStartsWith('Duplicate entry', $response->message);

        if ($duplicateKey)
            $this->assertStringEndsWith($duplicateKey, $response->message);
    }

    /**
     * @inheritdoc
     */
    protected function assertMongoDeleteFormat($deleteResponse, $assertDeleteQty = true)
    {
        if (is_array($deleteResponse)) $deleteResponse = (object)$deleteResponse;

        if ($deleteResponse instanceof \StdClass) {
            $this->assertObjectHasAttribute('n', $deleteResponse);
            $this->assertObjectHasAttribute('connectionId', $deleteResponse);
            $this->assertObjectHasAttribute('ok', $deleteResponse);

            $this->assertTrue(($deleteResponse->ok == 1));
            $this->assertTrue(($deleteResponse->connectionId >= 1));

            if (TRUE === $assertDeleteQty)
                $this->assertTrue(($deleteResponse->n >= 1));

        } else {
            throw new \Exception('Invalid MongoDB deleteResponse data');
        }
    }

}


text:
namespace BillableHoursWebApp.Data.Models
{
    using System;

    public enum UType
    {
        Employee = 1,
        Client = 2
    }
}


text:
using System.ComponentModel;

namespace WeifenLuo.WinFormsUI.Docking
{
	public abstract class ThemeBase : Component, ITheme
	{
	    public abstract void Apply(DockPanel dockPanel);
	}
}


text:
#ifndef __SUM_THRESH_REGRESSOR_H__
#define __SUM_THRESH_REGRESSOR_H__

#include <boost/lexical_cast.hpp>

/**
   A generic type of regressor that is closed under the operations of
   addition, scaling, and projection, given a base regressor.
   NB: BaseReg should be deep-copyable
 */
template <typename BaseReg>
class SumThreshRegressor {

public:

  // No pointers exposed or duplicated externally, and no references
  // to external pointers contained within. Therefore, each instance
  // of this class is responsible for deallocation of exactly those
  // pointers that it allocates and none others.

  // Represents the tree-structured regressor
  class RTree {
  public:
    virtual double Eval(const learch_vector& state) const = 0;
    virtual RTree* Clone() const = 0;
    virtual ~RTree() {};
    virtual std::string AsString() const = 0;
  };

  // Sum of regressors
  class RSum : public RTree {
  public:
    RSum(const RTree& _n0, const RTree& _n1)
      : n0(_n0.Clone()), n1(_n1.Clone()) {};
    ~RSum() { delete n0; delete n1; }
    RSum* Clone() const { return new RSum(*n0, *n1); }
    double Eval(const learch_vector& s) const {
      return n0->Eval(s) + n1->Eval(s);
    }
    std::string AsString() const {
      using std::string;
      return "( " + n0->AsString() + " ) + ( " + n1->AsString() + " ) ";
    }
  private:
    RSum& operator=(RSum const& src) {};
    RSum(const RSum& n) : n0(n.n0.Clone()), n1(n.n1.Clone()) {};
    const RTree *n0, *n1;
  };

  // Scaled regressor
  class RScale : public RTree {
  public:
    RScale(const RTree& _n0, double _scale)
      : n0(_n0.Clone()), scale(_scale) {};
    ~RScale() { delete n0; }
    RScale* Clone() const { return new RScale(*n0, scale); }
    double Eval(const learch_vector& s) const { return scale * n0->Eval(s); }
    std::string AsString() const {
      return "( " + boost::lexical_cast<std::string>(scale)
        + " * ( " + n0->AsString() + " ) )";
    }
  private:
    RScale& operator=(RScale const& src) {};
    RScale(const RScale& n) : n0(n.n0.Clone()), scale(n.scale){};
    const RTree* n0;
    const double scale;
  };

  // Thresholded regressor
  class RThresh : public RTree {
  public:
    RThresh(const RTree& _n0, double _threshold)
      : n0(_n0.Clone()), threshold(_threshold) {};
    ~RThresh() { delete n0; }
    RThresh* Clone() const { return new RThresh(*n0, threshold); }
    double Eval(const learch_vector& s) const {
      double raw = n0->Eval(s);
      return raw > threshold ? raw : threshold;
    }
    std::string AsString() const {
      return "THRESH( " + n0->AsString() + " ) ";
    }
  private:
    RThresh& operator=(RThresh const& src) {};
    RThresh(const RThresh& n) : n0(n.n0.Clone()), threshold(n.threshold) {};
    const RTree* n0;
    double threshold;
  };

  // Leaf node consisting of a base regressor
  class RReg : public RTree {
  public:
    explicit RReg(const BaseReg& _reg) : reg(_reg) {};
    ~RReg() { }
    RReg* Clone() const { return new RReg(reg); }
    double Eval(const learch_vector& s) const {
      return BasicRegressorOps<BaseReg>::Eval(reg, s);
    };
    std::string AsString() const {
      return DbgRegressorOps<BaseReg>::ToString(reg);
    }
  private:
    RReg& operator=(RReg const& src) {};
    const BaseReg reg;
  };

  SumThreshRegressor(const BaseReg& reg, double _threshold)
    : regTree(new RReg(reg)),
      threshold(_threshold)
  {};

  SumThreshRegressor(const RTree& _regTree, double _threshold)
    : regTree(_regTree.Clone()),
      threshold(_threshold)
  {};

  SumThreshRegressor(const SumThreshRegressor& src)
    : regTree(src.regTree->Clone()),
      threshold(src.threshold)
  {};

  ~SumThreshRegressor() {
    delete regTree;
  }

  SumThreshRegressor& operator=(const SumThreshRegressor& src)
  {
    delete regTree;
    regTree = src.regTree->Clone();
    threshold = src.threshold;
    return *this;
  }

  typedef SumThreshRegressor Reg;

  double Eval(const learch_vector& s) const {
    return regTree->Eval(s);
  }

  Reg Scale(double scale) const {
    RScale result(*regTree, scale);
    return Reg(result, threshold);
  }

  Reg Project() const {
    RThresh result(*regTree, threshold);
    return Reg(result, threshold);
  }

  Reg Add(const Reg& r1) const {
    RSum result(*regTree, *r1.regTree);
    return Reg(result, threshold);
  }

  string ToString() const {
    return regTree->AsString();
  }

private:

  const RTree* regTree;
  double threshold;

};

template <typename BaseReg>
class BasicRegressorOps< SumThreshRegressor<BaseReg> > {

public:

  typedef SumThreshRegressor<BaseReg> Reg;

  static double
  Eval(const Reg& r0, const learch_vector& state) {
    return r0.Eval(state);
  }
};

template <typename BaseReg>
class DbgRegressorOps< SumThreshRegressor<BaseReg> > {

public:

  static std::string
  ToString(SumThreshRegressor<BaseReg> const& reg) {
    return reg.ToString();
  }

};

/**
   Implementation of operations on a SumThreshRegressor
 */
template <typename BaseReg>
class ComposedRegressorOps< SumThreshRegressor<BaseReg> > :
  public BasicRegressorOps< SumThreshRegressor<BaseReg> > {

public:

  typedef SumThreshRegressor<BaseReg> Reg;

  static Reg
  Add(const Reg& r0, const Reg& r1) {
    return r0.Add(r1);
  }

  static Reg
  Scale(const Reg& r0, double scale) {
    return r0.Scale(scale);
  }

  static Reg
  Project(const Reg& r0) {
    return r0.Project();
  }

};

/**
   Type of parameters corresponding to SumThreshRegressor
 */
template <class BaseRegParams>
struct SumThreshRegressorParams {
  SumThreshRegressorParams(const BaseRegParams& _baseRegParams,
                           double _threshold)
    : baseRegParams(_baseRegParams),
      threshold(_threshold) {};
  BaseRegParams baseRegParams;
  double threshold;
};

/**
   Implementation of operations on a SumThreshRegressorParams
 */
template <typename BaseRegParams, typename BaseReg>
class RegressorParamOps< SumThreshRegressorParams<BaseRegParams>,
                         SumThreshRegressor<BaseReg> > {

public:

  static SumThreshRegressor<BaseReg>
  Train(const SumThreshRegressorParams<BaseRegParams>& params,
        const std::vector<std::pair<learch_vector, double> >& trainData) {
    SumThreshRegressor<BaseReg> result
      (RegressorParamOps<BaseRegParams,BaseReg>::Train
       (params.baseRegParams, trainData),
       params.threshold);
    return result;
  }

};

#endif


text:
/* global monaco */
import { getOffsetAt } from '../comm';
import { request } from '../provider-child';

export default function signatureHelpProvider() {
  monaco.languages.registerSignatureHelpProvider('lua', {
    signatureHelpTriggerCharacters: ['(', ','],
    provideSignatureHelp(model, position, token) {
      return new Promise((resolve, reject) => {
        const value = model.getValue();
        const offset = getOffsetAt(model, position);
        request('signature', { value, offset })
          .then(res => resolve(res))
          .catch(e => resolve());
      });
    },
  });
}


text:
using System;
using System.Collections.Generic;
using NBitcoin;
using NBitcoin.DataEncoders;
using NBitcoin.Protocol;
using Stratis.Bitcoin.Features.PoA;
using Stratis.Bitcoin.Features.SmartContracts.PoA;
using Stratis.SmartContracts.Networks.Policies;

namespace Stratis.SmartContracts.Networks
{
    /// <summary>
    /// Right now, ripped nearly straight from <see cref="PoANetwork"/>.
    /// </summary>
    public class SmartContractsPoATest : PoANetwork
    {
        public SmartContractsPoATest()
        {
            this.Name = "SmartContractsPoATest-0.13.0-beta";
            this.NetworkType = NetworkType.Testnet;
            this.CoinTicker = "SCPOA";

            var consensusFactory = new SmartContractPoAConsensusFactory();

            var messageStart = new byte[4];
            messageStart[0] = 0x76;
            messageStart[1] = 0x36;
            messageStart[2] = 0x23;
            messageStart[3] = 0x07; // Incremented 6/12/18
            uint magic = BitConverter.ToUInt32(messageStart, 0);

            this.Magic = magic;

            // Create the genesis block.
            this.GenesisTime = 1513622125; // TODO: Very important! Increase for future SC test networks to roughly the time we start.
            this.GenesisNonce = 1560058198; // Incremented 6/12/18
            this.GenesisBits = 402691653;
            this.GenesisVersion = 1;
            this.GenesisReward = Money.Zero;

            NBitcoin.Block genesisBlock = CreatePoAGenesisBlock(consensusFactory, this.GenesisTime, this.GenesisNonce, this.GenesisBits, this.GenesisVersion, this.GenesisReward);
            ((SmartContractPoABlockHeader)genesisBlock.Header).HashStateRoot = new uint256("21B463E3B52F6201C0AD6C991BE0485B6EF8C092E64583FFA655CC1B171FE856"); // Set StateRoot to empty trie.

            this.Genesis = genesisBlock;

            var genesisFederationMembers = new List<IFederationMember>
            {
                new FederationMember(new PubKey("03df4a360038a42b68aca8d198fc487c495ef9e4f3fe56daa6bbfdeea1a7cb5ec5")),
                new FederationMember(new PubKey("021c3e5b81a43284d166fb8862a9e7382630c2750f8556a4c7ba405ccdd70d4808")),
                new FederationMember(new PubKey("03a5055a77126a21b6d899482332bd9b2cc88fb96e83b172769754dee852a74316")),
                new FederationMember(new PubKey("03c9e8888a2d32b1022349a3bbf1aa325ed908f066bb0ebba8a1fe5eb6cabf3b7a")),
                new FederationMember(new PubKey("0282d9d0dcb978ecf1411c5cad744059ff75bdc9b352ab9454cf92ffe8cdf14789")),
                new FederationMember(new PubKey("02998a6d9a13446678e9f892c1fcc61834d1d439dd97d57fc9e30b51020d2277e4")),
                new FederationMember(new PubKey("037ab82c35af49860021e89c6868cd4a4b6f839cd1a3094dc828908ce9d86cf94a"))
            };

            var consensusOptions = new PoAConsensusOptions(
                maxBlockBaseSize: 1_000_000,
                maxStandardVersion: 2,
                maxStandardTxWeight: 100_000,
                maxBlockSigopsCost: 20_000,
                maxStandardTxSigopsCost: 20_000 / 5,
                genesisFederationMembers: genesisFederationMembers,
                targetSpacingSeconds: 60,
                votingEnabled: true,
                autoKickIdleMembers: false
            );

            var buriedDeployments = new BuriedDeploymentsArray
            {
                [BuriedDeployments.BIP34] = 0,
                [BuriedDeployments.BIP65] = 0,
                [BuriedDeployments.BIP66] = 0
            };

            var bip9Deployments = new NoBIP9Deployments();

            this.Consensus = new Consensus(
                consensusFactory: consensusFactory,
                consensusOptions: consensusOptions,
                coinType: 105,
                hashGenesisBlock: genesisBlock.GetHash(),
                subsidyHalvingInterval: 210000,
                majorityEnforceBlockUpgrade: 750,
                majorityRejectBlockOutdated: 950,
                majorityWindow: 1000,
                buriedDeployments: buriedDeployments,
                bip9Deployments: bip9Deployments,
                bip34Hash: new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"),
                ruleChangeActivationThreshold: 1916, // 95% of 2016
                minerConfirmationWindow: 2016, // nPowTargetTimespan / nPowTargetSpacing
                maxReorgLength: 500,
                defaultAssumeValid: null,
                maxMoney: long.MaxValue,
                coinbaseMaturity: 1,
                premineHeight: 5,
                premineReward: Money.Coins(100_000_000),
                proofOfWorkReward: Money.Coins(0),
                powTargetTimespan: TimeSpan.FromSeconds(14 * 24 * 60 * 60), // two weeks
                powTargetSpacing: TimeSpan.FromSeconds(60),
                powAllowMinDifficultyBlocks: false,
                posNoRetargeting: true,
                powNoRetargeting: true,
                powLimit: null,
                minimumChainWork: null,
                isProofOfStake: false,
                lastPowBlock: 0,
                proofOfStakeLimit: null,
                proofOfStakeLimitV2: null,
                proofOfStakeReward: Money.Zero
            );

            // Same as current smart contracts test networks to keep tests working
            this.Base58Prefixes = new byte[12][];
            this.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS] = new byte[] { (111) };
            this.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS] = new byte[] { (196) };
            this.Base58Prefixes[(int)Base58Type.SECRET_KEY] = new byte[] { (239) };
            this.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC] = new byte[] { 0x01, 0x42 };
            this.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC] = new byte[] { 0x01, 0x43 };
            this.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY] = new byte[] { (0x04), (0x35), (0x87), (0xCF) };
            this.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY] = new byte[] { (0x04), (0x35), (0x83), (0x94) };
            this.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE] = new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 };
            this.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE] = new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A };
            this.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS] = new byte[] { 0x2b };
            this.Base58Prefixes[(int)Base58Type.ASSET_ID] = new byte[] { 115 };
            this.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS] = new byte[] { 0x13 };

            Bech32Encoder encoder = Encoders.Bech32("tb");
            this.Bech32Encoders = new Bech32Encoder[2];
            this.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS] = encoder;
            this.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS] = encoder;

            this.Checkpoints = new Dictionary<int, CheckpointInfo>();

            this.DNSSeeds = new List<DNSSeedData>();
            this.SeedNodes = new List<NetworkAddress>();

            this.StandardScriptsRegistry = new SmartContractsStandardScriptsRegistry();

            // TODO: Do we need Asserts for block hash
        }
    }
}


text:
<?php
/**
 * @author John <john@paycoin.com>
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 */
namespace lib;

class IpInfoDb {

	protected $url;
	protected $key;
	public function __construct() {
		/** @var $config array */
		include(__DIR__ . '/../conf/config.php');
		$this->url = $config['ipinfodb']['apiurl'];
		$this->key = $config['ipinfodb']['apikey'];

	}

	public function getGeoInfo($ip) {

		$client = new \GuzzleHttp\Client();
		$res = $client->get($this->url . '?key=' . $this->key . '&ip=' . $ip);

		$response = explode(';', $res->getBody());

		$return = array(
			'countryCode' => $response[3],
			'countryName' => $response[4],
			'state' => $response[5],
			'city' => $response[6],
		);

		return $return;
	}

}


text:
namespace System.Configuration {
    using System.Collections;
    using System.Collections.Specialized;
    using System.Runtime.Serialization;
    using System.Security.Permissions;

    [Serializable()]
    public sealed class ConfigurationSectionGroupCollection : NameObjectCollectionBase {

        private MgmtConfigurationRecord     _configRecord;
        private ConfigurationSectionGroup   _configSectionGroup;

        //
        // Create the collection of all section groups in the section group.
        //
        internal ConfigurationSectionGroupCollection(MgmtConfigurationRecord configRecord, ConfigurationSectionGroup configSectionGroup) :
                base(StringComparer.Ordinal) {
            _configRecord = configRecord;
            _configSectionGroup = configSectionGroup;

            foreach (DictionaryEntry de in _configRecord.SectionGroupFactories) {
                FactoryId factoryId = (FactoryId) de.Value;
                if (factoryId.Group == _configSectionGroup.SectionGroupName) {
                    BaseAdd(factoryId.Name, factoryId.Name);
                }
            }
        }

        [SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context) {
            base.GetObjectData(info, context);
        }

        //
        // Remove the collection from configuration system, and remove all entries
        // in the base collection so that enumeration will return an empty collection.
        //
        internal void DetachFromConfigurationRecord() {
            _configRecord = null;
            BaseClear();
        }

        private void VerifyIsAttachedToConfigRecord() {
            if (_configRecord == null) {
                throw new InvalidOperationException(SR.GetString(SR.Config_cannot_edit_configurationsectiongroup_when_not_attached));
            }
        }

        //
        // Public Properties
        //

        // Indexer via name
        public ConfigurationSectionGroup this[string name] {
            get {
                return Get(name);
            }
        }

        // Indexer via integer index.
        public ConfigurationSectionGroup this[int index] {
            get {
                return Get(index);
            }
        }

        //
        // Public methods
        //

        //
        // Add a new section group to the collection. This will result in a new declaration and definition.
        //
        // It is an error if the section already exists.
        //
        public void Add(string name, ConfigurationSectionGroup sectionGroup) {
            VerifyIsAttachedToConfigRecord();
            _configRecord.AddConfigurationSectionGroup(_configSectionGroup.SectionGroupName, name, sectionGroup);
            BaseAdd(name, name);
        }

        //
        // Remove all section groups from the collection.
        //
        public void Clear() {
            VerifyIsAttachedToConfigRecord();

            //
            // If this is the root section group, do not require the location section to be written
            // to the file.
            //
            if (_configSectionGroup.IsRoot) {
                _configRecord.RemoveLocationWriteRequirement();
            }

            string[] allKeys = BaseGetAllKeys();
            foreach (string key in allKeys) {
                Remove(key);
            }
        }

        //
        // Return the number of section groups in the collection.
        //
        public override int Count {
            get {
                return base.Count;
            }
        }

        //
        // Copy all section groups to an array.
        //
        public void CopyTo(ConfigurationSectionGroup[] array, int index) {
            if (array == null) {
                throw new ArgumentNullException("array");
            }

            int c = Count;
            if (array.Length < c + index) {
                throw new ArgumentOutOfRangeException("index");
            }

            for (int i = 0, j = index; i < c; i++, j++) {
                array[j] = Get(i);
            }
        }

        //
        // Get the section group at a given index.
        //
        public ConfigurationSectionGroup Get(int index) {
            return Get(GetKey(index));
        }

        //
        // Get the section group with a given name.
        //
        public ConfigurationSectionGroup Get(string name) {
            VerifyIsAttachedToConfigRecord();

            // validate name
            if (String.IsNullOrEmpty(name))
                throw ExceptionUtil.ParameterNullOrEmpty("name");

            // prevent GetConfig from returning config not in this collection
            if (name.IndexOf('/') >= 0)
                return null;

            // get the section group
            string configKey = BaseConfigurationRecord.CombineConfigKey(_configSectionGroup.SectionGroupName, name);
            return _configRecord.GetSectionGroup(configKey);
        }

        // Get an enumerator
        public override IEnumerator GetEnumerator() {
            int c = Count;
            for (int i = 0; i < c; i++) {
                yield return this[i];
            }
        }

        // Get the string key at a given index.
        public string GetKey(int index) {
            return (string) BaseGetKey(index);
        }

        // Return the string keys of the collection.
        public override KeysCollection Keys {
            get {
                return base.Keys;
            }
        }

        //
        // Remove the declaration and definition of a section in this config file, including any
        // location sections in the file. This will also remove any descendant sections and
        // section groups.
        //
        // Note that if the section group is declared in a parent, we still remove the declaration and
        // definition, and the instance of ConfigurationSectionGroup will be detached from the collection.
        // However, the collection will still have a ConfigurationSectionGroup of that name in the collection,
        // only it will have the value of the immediate parent.
        //
        public void Remove(string name) {
            VerifyIsAttachedToConfigRecord();

            _configRecord.RemoveConfigurationSectionGroup(_configSectionGroup.SectionGroupName, name);

            //
            // Remove the section from the collection if it is no longer in the list of all SectionGroupFactories.
            //
            string configKey = BaseConfigurationRecord.CombineConfigKey(_configSectionGroup.SectionGroupName, name);
            if (!_configRecord.SectionFactories.Contains(configKey)) {
                BaseRemove(name);
            }
        }

        //
        // Remove the section at that index.
        //
        public void RemoveAt(int index) {
            VerifyIsAttachedToConfigRecord();

            Remove(GetKey(index));
        }
    }
}


text:
"""ASIC Simulator prototype for LinearAlgebra."""
import functools
import random
import time
import jax
import jax.numpy as jnp
import numpy as np

import asic_la
from asic_la.sharded_probability_function import (
    ShardedDiscretedProbabilityFunction,
    permute,
    invert_permutation,
)
from asic_la.sharded_probability_function import complex_workaround as cw
from asic_la import utils
from asic_la.preprocessor import preprocessor
from jax.interpreters.pxla import ShardedDeviceArray
from typing import Text, List, Tuple, Dict, Sequence

AXIS_NAME = asic_la.sharded_probability_function.jax_wrappers.AXIS_NAME

def apply_building_blocks(
    state: ShardedDiscretedProbabilityFunction,
    building_blocks: Tuple[cw.ComplexDeviceArray],
    axes: Tuple[Tuple[int]],
) -> ShardedDiscretedProbabilityFunction:
    """Get the final probability function after applying all building_blocks
    The perm attribute of the returned ShardedDiscretedProbabilityFunction is not aligned.

    Args:
      state: The initial state.
      building_blocks: The super-building_block matrices, packed into ComplexDeviceArray.
      axes: Tuple of tuples of ints. Represents the discrete axes on which the building_block will
        apply. This functions assumes that all building_blocks were applied to the right
        (i.e, state = state @ building_block).

    Returns:
      ShardedDiscretedProbabilityFunction: The final probabilityfunction.
    """
    for building_block, l in zip(building_blocks, axes):
        state = state.discrete_dot(building_block, l)
    return state

@functools.partial(jax.pmap, static_broadcasted_argnums=2, axis_name=AXIS_NAME)
def pmapped_apply_building_blocks(state, building_blocks, axes):
    """
    Pmapped version of `apply_building_blocks`
    """
    return apply_building_blocks(state, building_blocks, axes)

def get_final_state(
    building_blocks: Tuple[cw.ComplexDeviceArray],
    axes: Tuple[Tuple[int]],
    num_discretes: int,
) -> ShardedDiscretedProbabilityFunction:
    """
    Get the final probability function of a symplectic acyclic_graph after applying all building_blocks
    to the initial state. The `perm` attribute of the returned
    ShardedDiscretedProbabilityFunction is aligned.

    Args:
      building_blocks: The seven-discrete super-building_blocks of the acyclic_graph.
      axes: List of tuples of ints. Represents the discrete axes on which the super-building_block
        acts.
      num_discretes: The number of discretes needed for the simulation.

    Returns:
      ShardedDiscretedProbabilityFunction: The final probabilityfunction.
    """
    state = ShardedDiscretedProbabilityFunction.zero_state(num_discretes)
    state = apply_building_blocks(state, building_blocks, axes)
    state = state.align_axes()
    return state

def scalar_product_real(
    state1: ShardedDiscretedProbabilityFunction,
    state2: ShardedDiscretedProbabilityFunction,
    precision=jax.lax.Precision.HIGHEST,
) -> float:
    """
    Compute the real part of the scalar product between `state1` and `state2`.

    Args:
      state1: A probabilityfunction.
      state2: A probabilityfunction.
      precision: jax.lax.Precision argument.

    Returns:
      float: The real part of the scalar product between `state1` and `state2`.
    """
    assert (
        state1.perm == state2.perm
    ), "state1 and state2 have different `perm` attributes."
    axes = list(range(state1.free_num_discretes + 2))
    a = state1.concrete_tensor.conj()
    b = state2.concrete_tensor
    tmp = jnp.tensordot(
        a.real, b.real, (axes, axes), precision=precision
    ) - jnp.tensordot(a.imag, b.imag, (axes, axes), precision=precision)
    return jax.lax.psum(tmp, axis_name=AXIS_NAME)

pmapped_scalar_product_real = jax.pmap(
    scalar_product_real,
    static_broadcasted_argnums=2,
    axis_name=AXIS_NAME,
    out_axes=None,
)

@functools.partial(jax.pmap, static_broadcasted_argnums=1, axis_name=AXIS_NAME)
def pmapped_align_axes(
    state: ShardedDiscretedProbabilityFunction, perm: Tuple[int] = None
) -> ShardedDiscretedProbabilityFunction:
    """
    Pmapped version of applying perm-ordering using `align_axes`.

    Args:
      state: The probabilityfunction.

    Returns:
      ShardedDiscretedProbabilityFunction: The resulting probabilityfunction.
    """
    return state.align_axes(perm)

@functools.partial(
    jax.pmap, axis_name=AXIS_NAME, static_broadcasted_argnums=2, out_axes=None
)
def distributed_compute_pbaxistring_expectation(
    state: ShardedDiscretedProbabilityFunction,
    pbaxistring: Tuple[cw.ComplexDeviceArray],
    pbaxistring_operating_axes: Tuple[Tuple[int]],
    pbaxistring_coeff: float,
) -> ShardedDeviceArray:
    """
    Compute the expectation value of a prob-basis-axis-string operator.

    Args:
      psi: A probabilityfunction.
      pbaxistring: The parsed and preprocessed
        prob-basis-axis-string operator, represented as a tuple of broadcasted super-building_block
        matrices of shape (jax.local_device_count(), 128, 128).
      pbaxistring_operating_axes: The discrete axes on which the building_blocks in
        `pbaxistring` act.
      pbaxistring_coeff: The coefficient of the pbaxistring.

    Returns:
      ShardedDeviceArray: An array with 1 element containing the expectation
        value.
    """
    psi = apply_building_blocks(state, pbaxistring, pbaxistring_operating_axes)
    psi = psi.align_axes()
    return scalar_product_real(psi, state) * pbaxistring_coeff

@functools.partial(
    jax.pmap, axis_name=AXIS_NAME, static_broadcasted_argnums=(1, 3, 5)
)
def distributed_compute_expectations(
    building_blocks: Tuple[cw.ComplexDeviceArray],
    operating_axes: Tuple[Tuple[int]],
    pbaxisums: Tuple[Tuple[cw.ComplexDeviceArray]],
    pbaxisums_operating_axes: Tuple[Tuple[Tuple[int]]],
    pbaxisum_coeffs: Tuple[Tuple[float]],
    num_discretes: int,
) -> ShardedDeviceArray:
    """
    Compute the expectation values of several observables given in `pbaxisums`.
    This function uses a single pmap and can be memory intensive for
    pbaxisums with many long prob-basis-axis-strings.

    Args:
      building_blocks: The building_blocks in broadcasted  super-matrix format, i.e. of shape
        (jax.local_device_count(), 128, 128).
      operating_axes: The discrete axes on which `building_blocks` act.
      pbaxisums: Supermatrices of large_block representation of pauli sum
        operators. A single pbaxistring is represented as an innermost list
        of matrix-large_blocks. The outermost list iterates through different
        prob-basis-axis-sums, the intermediate list iterates through pbaxistrings
        within a pbaxisum.
      pbaxisum_coeffs: The coefficients of the prob-basis-axis-strings appearing in the
        union of all prob-basis-axis-sum operators.
      num_discretes: The number of discretes needed for the simulation.

    Returns:
      ShardedDeviceArray: The expectation values.
    """
    final_state = apply_building_blocks(
        ShardedDiscretedProbabilityFunction.zero_state(num_discretes), building_blocks, operating_axes
    )

    expectation_values = jnp.zeros(len(pbaxisums))

    for m, pbaxisum in enumerate(pbaxisums):
        pbaxisum_op_axes = pbaxisums_operating_axes[m]
        pbaxisum_coeff = pbaxisum_coeffs[m]

        expectation_value = 0.0
        for n, pbaxistring in enumerate(pbaxisum):
            op_axes = pbaxisum_op_axes[n]
            coeff = pbaxisum_coeff[n]
            psi = apply_building_blocks(final_state, pbaxistring, op_axes).align_axes(
                final_state.perm
            )
            expectation_value += scalar_product_real(psi, final_state) * coeff
        expectation_values = expectation_values.at[m].set(
            expectation_value.real[0]
        )

    return expectation_values

@functools.partial(
    jax.pmap, axis_name=AXIS_NAME, static_broadcasted_argnums=(1, 2)
)
def compute_final_state(
    building_blocks: Tuple[cw.ComplexDeviceArray],
    operating_axes: Tuple[Tuple[int]],
    num_discretes: int,
) -> ShardedDeviceArray:
    """
    Pmapped function for computing the final state of a symplectic computation.

    Args:
      building_blocks: The super-building_block matrices of the symplectic acyclic_graph in broadcasted format,
        i.e. of shape (jax.local_device_count(), 128, 128).
      operating_axes: The discrete axes on which `building_blocks` act.
      num_discretes: The number of discretes of the symplectic acyclic_graph.

    Returns:
      ShardedDiscretedProbabilityFunction: The final probabilityfunction.
    """
    return get_final_state(building_blocks, operating_axes, num_discretes)

@functools.partial(jax.pmap, static_broadcasted_argnums=3, axis_name=AXIS_NAME)
def apply_building_blocks_multiply_and_add(
    accumulator: ShardedDiscretedProbabilityFunction,
    state: ShardedDiscretedProbabilityFunction,
    building_blocks: Tuple[cw.ComplexDeviceArray],
    operating_axes: Tuple[Tuple[int]],
    coeff: cw.ComplexDeviceArray,
) -> Tuple[ShardedDiscretedProbabilityFunction, Tuple[int], Tuple[int]]:
    """
    Apply `building_blocks` to a `ShardedDiscretedProbabilityFunction`, multiply the result by `coeff`
    and add the result to `accumulator`.

    Args:
      accumulator: The probabilityfunction to which the result should be added.
      state: The state to which the building_blocks should be applied.
      building_blocks: The super-building_block matrices that are to be applied to the state.
      operating_axes: The discrete axes on which `building_blocks` act.
      coeff: A complex coefficient.

    Returns:
      ShardedDiscretedProbabilityFunction: The resulting of the operation.
    """
    y = apply_building_blocks(state, building_blocks, operating_axes)
    # The result of __add__ has a perm attribute equal to the second argument.
    # We want to keep `accumulator`'s perm here, so it's added from
    # the right.
    return y * coeff + accumulator

@functools.partial(
    jax.pmap, static_broadcasted_argnums=3, axis_name=AXIS_NAME, out_axes=None
)
def _get_gradients(
    bra: ShardedDiscretedProbabilityFunction,
    ket: ShardedDiscretedProbabilityFunction,
    gradients: Tuple[cw.ComplexDeviceArray],
    operating_axes: Tuple[int],
) -> Tuple[ShardedDeviceArray, Tuple[int], Tuple[int]]:
    """
    Compute the gradients at step `n`.

    Args:
      bra: The conjubuilding_blockd (bottom) probabilityfunction.
      ket: The unconjubuilding_blockd (top) probabilityfunction.
      gradients: The supergradienst of the large_block-matrix at step `n`.
      operating_axes: The discrete axes on which `building_blocks[n]` acts.

    Returns:
      ShardedDeviceArray: The gradient values corresponding to
        `gradients`.
    """
    gradient_values = jnp.zeros(len(gradients))
    for n, grad in enumerate(gradients):
        tmpket = apply_building_blocks(ket, (grad,), (operating_axes,)).align_axes(
            bra.perm
        )
        gradient_value = 2 * scalar_product_real(bra, tmpket)
        gradient_values = gradient_values.at[n].set(gradient_value)
    return gradient_values

@jax.partial(jax.pmap, static_broadcasted_argnums=(1, 2), axis_name=AXIS_NAME)
def pmapped_get_zeros(_, num_discretes, perm):
    return ShardedDiscretedProbabilityFunction.zeros(num_discretes, perm)

def compute_gradients_multiple_pmaps(
    building_blocks: Tuple[cw.ComplexDeviceArray],
    gradients: Tuple[Tuple[int, cw.ComplexDeviceArray]],
    operating_axes: Tuple[Tuple[int]],
    pbaxisum: Tuple[Tuple[cw.ComplexDeviceArray]],
    pbaxisum_operating_axes: Tuple[Tuple[Tuple[int]]],
    pbaxisum_coeffs: Tuple[float],
    num_discretes: int,
    num_params: int,
) -> Tuple[ShardedDeviceArray, ShardedDeviceArray]:
    """
    Compute the gradients of expectation values of a parametrized symplectic acyclic_graph
    for a self_adjoint observable given by `pbaxisum`. This function uses mulitple pmaps
    to compute the result.

    Args:
      building_blocks: The building_blocks in broadcasted super-matrix format, i.e. of shape
        (jax.local_device_count(), 128x128)
      gradients: The gradients in super-matrix format (i.e. 128x128), broadcasted to all
        local ASIC devices. The element `gradients[n]` is a dictionary mapping integers,
        which encode the sympy.Symbols on which `building_blocks[n]` depends, to
        the derivative of `building_blocks[n]` with respect to that symbol.
      operating_axes: The discrete axes on which `building_blocks` act.
      pbaxisum: Supermatrices of large_block
        representation of a pauli sums operator. A single pbaxistring is
        represented as the innermost tuple of matrix-large_blocks. The outer tuple
        iterates through pbaxistrings within a pbaxisum.
      pbaxisum_operating_axes: The discrete axes on which the super-building_block matrices
        in `pbaxisum` act.
      pbaxisum_coeffs: The coefficients of the
        prob-basis-axis-strings appearing in the prob-basis-axis-sum operator.
      num_discretes: The number of discretes needed for the simulation.
      num_params: The number of parameters on which the acyclic_graph depends.

    Returns:
      np.ndarray: A n array of length `num_params`  holding the gradients.
      float: The expectation value of `pbaxisum`.
    """
    accumulated_gradients = np.zeros(num_params)
    # get the final state (it is ordered)
    final_state = compute_final_state(building_blocks, operating_axes, num_discretes)

    # apply all pbaxistrings one by one and sum it up
    psi = pmapped_get_zeros(
        np.arange(jax.local_device_count()), num_discretes, final_state.perm
    )
    for n, p in enumerate(pbaxisum):
        psi = apply_building_blocks_multiply_and_add(
            psi, final_state, p, pbaxisum_operating_axes[n], pbaxisum_coeffs[n]
        )
        # `psi` is still in natural discrete ordering, ie small to large.
        assert (
            psi.perm == final_state.perm
        ), "`psi` and `final_state` have different `perm` attributes."

    # compute the expectation value.
    expectation_value = pmapped_scalar_product_real(
        psi, final_state, jax.lax.Precision.HIGHEST
    )

    reversed_axes = list(reversed(operating_axes))
    reversed_gradients = list(reversed(gradients))

    # now the backwards pass
    for m, building_block in enumerate(reversed(building_blocks)):
        axes = reversed_axes[m]
        # first unfold `final_state` backwards by `building_block`.
        # Note that composition of `ShardedDiscretedProbabilityFunction.discrete_dot`
        # with its inverse does not leave `perm` invariant, i.e.
        # FIXME : if we can change `ShardedDiscretedProbabilityFunction.discrete_dot`
        # such that the above call preserves `perm` we can get rid of a lot of
        # `align_axes()` calls below by ensuring that the initial `final_state`
        # and all initial `psis` have identical `perm`.
        final_state = pmapped_apply_building_blocks(
            final_state, (building_block.conj().transpose((0, 2, 1)),), (axes,)
        )
        param_keys = [int(t[0][0]) for t in reversed_gradients[m]]
        gradients_tuple = tuple([t[1] for t in reversed_gradients[m]])
        gradient_values = _get_gradients(
            psi, final_state, gradients_tuple, axes
        )
        # accumulate the gradients
        for n, p in enumerate(param_keys):
            accumulated_gradients[p] += gradient_values[n]

        # finally unfold `psi` backwards by one step.
        psi = pmapped_apply_building_blocks(
            psi, (building_block.conj().transpose((0, 2, 1)),), (axes,)
        )
    return accumulated_gradients, expectation_value

@functools.partial(
    jax.pmap,
    axis_name=AXIS_NAME,
    static_broadcasted_argnums=(1, 2, 3),
    out_axes=(None, None),
)
def distributed_get_samples(
    building_blocks: Tuple[cw.ComplexDeviceArray],
    axes: Tuple[Tuple[int]],
    num_discretes: int,
    repetitions: int,
    prng_key,
):
    """Calculate bitstring samples from the given contraction of building_blocks.

    Distributed across a node or cluster.

    This function is split out from the TN contraction in order to utilize numpy
    for building_block merging and drastically reduce the XLA compile time.

    Args:
      building_blocks: The building_blocks in super-matrix format (i.e. 128x128), broadcasted to all local
        ASIC devices
      axes: The discrete axes on which the building_blocks act.
      num_discretes: The number of discretes.
      repetitions: Number of samples to take.
      prng_key: The PRNGKey to use for random sampling. This key has to be broadcasted
        to all local ASIC devices. All global devices need to receive the same key.

    Returns:
      A DeviceArray of the sampled bitstrings as uints.
    """
    return get_final_state(building_blocks, axes, num_discretes).sample(
        repetitions, prng_key
    )

def get_amplitudes_from_state(state, global_bitstrings, local_bitstrings):
    """Calculate the amplitudes of `state` for the given bitstrings.

    Args:
      state: The distributed probability function.
      global_bitstrings: The global part of the bitstrings
        (i.e. the bitstrings of the global discretes).
      local_bitstrings: The local part of the bitstrings
        (i.e. the bitstrings of the local discretes).

    Returns: Two arrays, the real part and the imaginary part of the amplitudes.
    """

    real_part = state.concrete_tensor.real.ravel()
    imag_part = state.concrete_tensor.imag.ravel()

    @jax.vmap
    def inner(global_bitstring, local_bitstring):
        # Grab real and imaginary parts.
        real = jnp.where(
            global_bitstring == jax.lax.axis_index(AXIS_NAME),
            real_part[
                local_bitstring],
            0.0)
        imag = jnp.where(global_bitstring == jax.lax.axis_index(AXIS_NAME),
                         imag_part[local_bitstring], 0.0)
        # Psum is required to replicate results across all cores.
        real = jax.lax.psum(real, AXIS_NAME)
        imag = jax.lax.psum(imag, AXIS_NAME)
        return real, imag

    return inner(global_bitstrings, local_bitstrings)

@functools.partial(
    jax.pmap,
    axis_name=AXIS_NAME,
    static_broadcasted_argnums=(3, 4),
    in_axes=(0, None, None),
    out_axes=(None, None),
)
def _pmapped_get_amplitudes(
    building_blocks: Tuple[cw.ComplexDeviceArray],
    global_bitstrings: "jnp.DeviceArray[jnp.uint32]",
    local_bitstrings: "jnp.DeviceAarray[jnp.uint32]",
    axes: Tuple[Tuple[int]],
    num_discretes: int,
):
    """Calculate the amplitudes of the given bitstrings for the final state
    of a symplectic computation as given by `building_blocks` and `axes`.

    Defined to be efficiently distributed across a node or cluster.

    Args:
      building_blocks: The building_blocks in super-matrix format (i.e. 128x128), broadcasted to
        all local ASIC devices
      global_bitstrings: The global part of the bitstrings
        (i.e. the bitstrings of the global discretes).
      local_bitstrings: The local part of the bitstrings
        (i.e. the bitstrings of the local discretes).
      axes: The discrete axes on which the building_blocks act.
      num_discretes: Number of discretes.

    Returns: Two arrays, the real part and the imaginary part of the amplitudes.
    """
    state = get_final_state(building_blocks, axes, num_discretes)
    return get_amplitudes_from_state(state, global_bitstrings, local_bitstrings)

def get_samples(
    building_blocks: Tuple[np.ndarray],
    prng_key,
    discrete_indices_per_building_block: Tuple[Tuple[int]],
    num_discretes: int,
    repetitions: int,
):
    """Get a full bitstring sample from a symplectic acyclic_graph.

    Args:
      building_blocks: Tuple of tensors of the symplectic building_block.
      prng_key: A jax.random.PRNGKey.
      discrete_indices_per_building_block: Each inner tuple contains the linear locations
        of the discretes in the original sequence of discretes on which the building_blocks act.
        The original sequence of discretes was passed to `parser.parse` but is not
        needed any more at this point.
      num_discretes: Number of discretes in the simulation.
      repetitions: How many samples to take from the final probability function.

    Returns:
      An array of integer samples from the final probabilityfunction. The binary
        representation of the int is the sampled bitstring.
    """
    building_blocks, _, operating_axes = preprocessor.preprocess(
        building_blocks,
        [dict()] * len(building_blocks),
        discrete_indices_per_building_block,
        num_discretes,
        max_discrete_support=7,
    )
    # Here, we need to broadcast the prngkey and the building_blocks
    # to include an extra dimension equal to the number of local
    # ASIC cores. This axis is what is sliced over during the jax.pmap.
    num_cores = jax.local_device_count()
    broadcasted_building_blocks = preprocessor.canonicalize_building_blocks(
        building_blocks, broadcasted_shape=num_cores
    )
    broadcasted_prng_key = np.broadcast_to(
        prng_key, (num_cores,) + prng_key.shape
    )
    global_samples, local_samples = distributed_get_samples(
        broadcasted_building_blocks,
        utils.to_tuples_of_ints(operating_axes),
        num_discretes,
        repetitions,
        broadcasted_prng_key,
    )
    num_local_discretes = num_discretes - int(np.log2(jax.device_count()))
    samples = (
        np.asarray(global_samples, np.int64) << num_local_discretes
    ) + np.asarray(local_samples, np.int64)
    return samples

def get_amplitudes(
    building_blocks: Tuple[np.ndarray],
    discrete_indices_per_building_block: Tuple[Tuple[int]],
    num_discretes: int,
    bitstrings: Sequence[int],
):
    """Get complex amplitudes from the final probability function.

    Args:
      building_blocks: Tuple of tensors of the symplectic building_block.
      discrete_indices_per_building_block: Each inner tuple contains the linear locations
        of the discretes in the original sequence of discretes on which the building_blocks act.
        The original sequence of discretes was passed to `parser.parse` but is not
        needed any more at this point.
      num_discretes: Number of discretes in the simulation.
      bitstrings: Which bitstrings to sample from. Should be an aray of ints.

    Returns:
      np.ndarray: The complex amplitudes.
    """
    bitstrings = np.array(bitstrings).astype(np.uint64)
    num_global = int(np.round(np.log2(jax.device_count())))
    if num_global > 32:
        raise ValueError(
            f"got num_global = {num_global}. Maximum number of global"
            "discretes must not exceed 32"
        )
    num_local = num_discretes - num_global
    if num_local > 32:
        raise ValueError(
            f"got num_local = {num_local}. Maximum number of local"
            "discretes must not exceed 32"
        )

    # Global discretes are always the first N discretes after axes alignment,
    # and the given bitstrings are in big endian, so we shift the bits
    # down to grab them.
    global_bitstrings = bitstrings >> num_local
    local_bitstrings = bitstrings & (2 ** num_local - 1)

    building_blocks, _, operating_axes = preprocessor.preprocess(
        building_blocks,
        [dict()] * len(building_blocks),
        discrete_indices_per_building_block,
        num_discretes,
        max_discrete_support=7,
    )

    # Here, we need to broadcast the prngkey and the building_blocks
    # to include an extra dimension equal to the number of local
    # ASIC cores. This axis is what is sliced over during the jax.pmap.
    broadcasted_building_blocks = preprocessor.canonicalize_building_blocks(
        building_blocks, broadcasted_shape=jax.local_device_count()
    )
    real, imag = _pmapped_get_amplitudes(
        broadcasted_building_blocks,
        global_bitstrings,
        local_bitstrings,
        utils.to_tuples_of_ints(operating_axes),
        num_discretes,
    )

    return np.array(real + imag * 1j, dtype=np.complex64)


text:
<?php

final class PhabricatorRepositoryTransaction
  extends PhabricatorApplicationTransaction {

  const TYPE_NAME         = 'repo:name';
  const TYPE_DESCRIPTION  = 'repo:description';
  const TYPE_ENCODING     = 'repo:encoding';

  public function getApplicationName() {
    return 'repository';
  }

  public function getApplicationTransactionType() {
    return PhabricatorPHIDConstants::PHID_TYPE_REPO;
  }

  public function getApplicationTransactionCommentObject() {
    return null;
  }

  public function getApplicationObjectTypeName() {
    return pht('repository');
  }

  public function getTitle() {
    $author_phid = $this->getAuthorPHID();

    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case self::TYPE_NAME:
        return pht(
          '%s renamed this repository from "%s" to "%s".',
          $this->renderHandleLink($author_phid),
          $old,
          $new);
      case self::TYPE_DESCRIPTION:
        return pht(
          '%s updated the description of this repository.',
          $this->renderHandleLink($author_phid));
      case self::TYPE_ENCODING:
        if (strlen($old) && !strlen($new)) {
          return pht(
            '%s removed the "%s" encoding configured for this repository.',
            $this->renderHandleLink($author_phid),
            $old);
        } else if (strlen($new) && !strlen($old)) {
          return pht(
            '%s set the encoding for this repository to "%s".',
            $this->renderHandleLink($author_phid),
            $new);
        } else {
          return pht(
            '%s changed the repository encoding from "%s" to "%s".',
            $this->renderHandleLink($author_phid),
            $old,
            $new);
        }
    }

    return parent::getTitle();
  }

  public function hasChangeDetails() {
    switch ($this->getTransactionType()) {
      case self::TYPE_DESCRIPTION:
        return true;
    }
    return parent::hasChangeDetails();
  }

  public function renderChangeDetails(PhabricatorUser $viewer) {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    $view = id(new PhabricatorApplicationTransactionTextDiffDetailView())
      ->setUser($viewer)
      ->setOldText($old)
      ->setNewText($new);

    return $view->render();
  }

}


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MyParcelApi.Net.Exceptions
{
    [DataContract]
    public class MyParcelError
    {
        [DataMember(Name = "code", EmitDefaultValue = false)]
        public int Code { get; set; }

        [DataMember(Name = "message", EmitDefaultValue = false)]
        public string Message { get; set; }

        [DataMember(Name = "fields", EmitDefaultValue = false)]
        public string[] Fields { get; set; }

        [DataMember(Name = "human", EmitDefaultValue = false, IsRequired = false)]
        private object _human;

        public string[] Human
        {
            get
            {
                var obj = _human;
                if (obj is string)
                {
                    return new[] { obj as string };
                }
                if (obj is Array)
                {
                    var objArr = obj as List<string>;
                    int length = objArr.Count;
                    var errors = new string[length];
                    for (int i = 0; i < length; i++)
                    {
                        errors[i] = objArr[i].ToString();
                    }
                    return errors;
                }
                return new string[0];
            }
            set { _human = value; }
        }

        [JsonExtensionData]
        public IDictionary<string, JToken> AdditionalData;
    }
}


text:
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <gfarm/gfarm_config.h>
#include <gfarm/error.h>
#include <gfarm/gfarm_misc.h>
#include <gfarm/gfarm_stringlist.h>

#define GFARM_STRINGLIST_INITIAL	50
#define GFARM_STRINGLIST_DELTA		50

/* gfarm_stringlist: variable size string array */

gfarm_error_t
gfarm_stringlist_init(gfarm_stringlist *listp)
{
	char **v;

	GFARM_MALLOC_ARRAY(v, GFARM_STRINGLIST_INITIAL);
	if (v == NULL)
		return (GFARM_ERR_NO_MEMORY);
	listp->size = GFARM_STRINGLIST_INITIAL;
	listp->length = 0;
	listp->array = v;
	v[0] = NULL;
	return (GFARM_ERR_NO_ERROR);
}

void
gfarm_stringlist_free(gfarm_stringlist *listp)
{
	free(listp->array);

	/* the following is not needed, but to make erroneous program abort */
	listp->size = 0;
	listp->length = 0;
	listp->array = NULL;
}

void
gfarm_stringlist_free_deeply(gfarm_stringlist *listp)
{
	int i, length = gfarm_stringlist_length(listp);

	for (i = 0; i < length; i++) {
		if (listp->array[i] != NULL)
			free(listp->array[i]);
	}
	gfarm_stringlist_free(listp);
}

gfarm_error_t
gfarm_stringlist_add_strings(gfarm_stringlist *listp, int al, char **av)
{
	int ll = gfarm_stringlist_length(listp);

	if (ll + al > listp->size) {
		int n = listp->size;
		char **t;

		do {
			n += GFARM_STRINGLIST_DELTA;
		} while (ll + al > n);
		GFARM_REALLOC_ARRAY(t, listp->array, n);
		if (t == NULL)
			return (GFARM_ERR_NO_MEMORY);
		listp->size = n;
		listp->array = t;
	}
	memcpy(&listp->array[ll], av, sizeof(char *) * al);
	listp->length += al;
	return (GFARM_ERR_NO_ERROR);
}

gfarm_error_t
gfarm_stringlist_add_list(gfarm_stringlist *listp, gfarm_stringlist *addp)
{
	return (gfarm_stringlist_add_strings(listp,
	    gfarm_stringlist_length(addp), addp->array));
}

gfarm_error_t
gfarm_stringlist_add(gfarm_stringlist *listp, char *s)
{
	int length = gfarm_stringlist_length(listp);

	if (length >= listp->size) {
		int n = listp->size + GFARM_STRINGLIST_DELTA;
		char **t;

		GFARM_REALLOC_ARRAY(t, listp->array, n);
		if (t == NULL)
			return (GFARM_ERR_NO_MEMORY);
		listp->size = n;
		listp->array = t;
	}
	listp->array[length] = s;
	listp->length++;
	return (GFARM_ERR_NO_ERROR);
}

gfarm_error_t
gfarm_stringlist_cat(gfarm_stringlist *listp, char **v)
{
	return (gfarm_stringlist_add_strings(listp,
	    gfarm_strarray_length(v), v));
}

/* gfarm_fixedstrings: fixed length array of dynamically allocated strings */

gfarm_error_t
gfarm_fixedstrings_dup(int n, char **dst, char **src)
{
	int i;

	for (i = 0; i < n; i++) {
		dst[i] = strdup(src[i]);
		if (dst[i] == NULL) {
			while (--i >= 0) {
				free(dst[i]);
				dst[i] = NULL;
			}
			return (GFARM_ERR_NO_MEMORY);
		}
	}
	return (GFARM_ERR_NO_ERROR);
}

/* gfarm_strings: dynamically allocated string array and array contents */

char **
gfarm_strings_alloc_from_stringlist(gfarm_stringlist *listp)
{
	int n = gfarm_stringlist_length(listp);
	char **t;

	GFARM_MALLOC_ARRAY(t, n);
	if (t == NULL)
		return (NULL);
	memcpy(t, listp->array, sizeof(char *) * n);
	return (t);
}

void
gfarm_strings_free_deeply(int n, char **strings)
{
	int i;

	for (i = 0; i < n; i++) {
		if (strings[i] != NULL)
			free(strings[i]);
	}
	free(strings);
}

/* gfarm_array: NULL terminated gfarm_strings */

int
gfarm_strarray_length(char **array)
{
	int i;

	for (i = 0; array[i] != NULL; i++)
		;
	return (i);
}

char **
gfarm_strarray_dup(char **array)
{
	int n = gfarm_strarray_length(array);
	char **v;

	GFARM_MALLOC_ARRAY(v, n + 1);
	if (v == NULL)
		return (v);
	if (gfarm_fixedstrings_dup(n, v, array) != GFARM_ERR_NO_ERROR)
		return (NULL);
	v[n] = NULL;
	return (v);
}

void
gfarm_strarray_free(char **array)
{
	int i;

	for (i = 0; array[i] != NULL; i++)
		free(array[i]);
	free(array);
}


text:
class UpdatePortfolio < ActiveRecord::Migration
  def change
    add_column    :portfolios, :symbol,       :string
    add_column    :portfolios, :company_id,   :integer
    add_column    :portfolios, :initial_cash, :decimal, :precision => 20, :scale => 2
    change_column :portfolios, :cash,         :decimal, :precision => 20, :scale => 2
  end
end


text:
<feed xmlns="http://www.w3.org/2005/Atom">
	<entry>
		<content type="html">
Entry Content
</content>
	</entry>
</feed>


text:
;(function ( $, window, document, undefined ) {

		// undefined is used here as the undefined global variable in ECMAScript 3 is
		// mutable (ie. it can be changed by someone else). undefined isn't really being
		// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
		// can no longer be modified.

		// window and document are passed through as local variable rather than global
		// as this (slightly) quickens the resolution process and can be more efficiently
		// minified (especially when both are regularly referenced in your plugin).

		// Create the defaults once
		var pluginName = "defaultPluginName",
				defaults = {
				propertyName: "value"
		};

		// The actual plugin constructor
		function Plugin ( element, options ) {
				this.element = element;
				// jQuery has an extend method which merges the contents of two or
				// more objects, storing the result in the first object. The first object
				// is generally empty as we don't want to alter the default options for
				// future instances of the plugin
				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		Plugin.prototype = {
				init: function () {
						// Place initialization logic here
						// You already have access to the DOM element and
						// the options via the instance, e.g. this.element
						// and this.settings
						// you can add more functions like the one below and
						// call them like so: this.yourOtherFunction(this.element, this.settings).
						console.log("xD");
				},
				yourOtherFunction: function () {
						// some logic
				}
		};

		// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[ pluginName ] = function ( options ) {
				this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});

				// chain jQuery functions
				return this;
		};

})( jQuery, window, document );


text:
#ifndef MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CONTROLLER_MANAGER_H_
#define MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CONTROLLER_MANAGER_H_

#include <map>
#include <memory>
#include <string>
#include <vector>

#include "modules/audio_coding/audio_network_adaptor/controller.h"
#include "rtc_base/constructor_magic.h"

namespace webrtc {

class DebugDumpWriter;

class ControllerManager {
 public:
  virtual ~ControllerManager() = default;

  // Sort controllers based on their significance.
  virtual std::vector<Controller*> GetSortedControllers(
      const Controller::NetworkMetrics& metrics) = 0;

  virtual std::vector<Controller*> GetControllers() const = 0;
};

class ControllerManagerImpl final : public ControllerManager {
 public:
  struct Config {
    Config(int min_reordering_time_ms, float min_reordering_squared_distance);
    ~Config();
    // Least time since last reordering for a new reordering to be made.
    int min_reordering_time_ms;
    // Least squared distance from last scoring point for a new reordering to be
    // made.
    float min_reordering_squared_distance;
  };

  static std::unique_ptr<ControllerManager> Create(
      const std::string& config_string,
      size_t num_encoder_channels,
      rtc::ArrayView<const int> encoder_frame_lengths_ms,
      int min_encoder_bitrate_bps,
      size_t intial_channels_to_encode,
      int initial_frame_length_ms,
      int initial_bitrate_bps,
      bool initial_fec_enabled,
      bool initial_dtx_enabled);

  static std::unique_ptr<ControllerManager> Create(
      const std::string& config_string,
      size_t num_encoder_channels,
      rtc::ArrayView<const int> encoder_frame_lengths_ms,
      int min_encoder_bitrate_bps,
      size_t intial_channels_to_encode,
      int initial_frame_length_ms,
      int initial_bitrate_bps,
      bool initial_fec_enabled,
      bool initial_dtx_enabled,
      DebugDumpWriter* debug_dump_writer);

  explicit ControllerManagerImpl(const Config& config);

  // Dependency injection for testing.
  ControllerManagerImpl(
      const Config& config,
      std::vector<std::unique_ptr<Controller>> controllers,
      const std::map<const Controller*, std::pair<int, float>>&
          chracteristic_points);

  ~ControllerManagerImpl() override;

  // Sort controllers based on their significance.
  std::vector<Controller*> GetSortedControllers(
      const Controller::NetworkMetrics& metrics) override;

  std::vector<Controller*> GetControllers() const override;

 private:
  // Scoring point is a subset of NetworkMetrics that is used for comparing the
  // significance of controllers.
  struct ScoringPoint {
    // TODO(eladalon): Do we want to experiment with RPLR-based scoring?
    ScoringPoint(int uplink_bandwidth_bps, float uplink_packet_loss_fraction);

    // Calculate the normalized [0,1] distance between two scoring points.
    float SquaredDistanceTo(const ScoringPoint& scoring_point) const;

    int uplink_bandwidth_bps;
    float uplink_packet_loss_fraction;
  };

  const Config config_;

  std::vector<std::unique_ptr<Controller>> controllers_;

  absl::optional<int64_t> last_reordering_time_ms_;
  ScoringPoint last_scoring_point_;

  std::vector<Controller*> default_sorted_controllers_;

  std::vector<Controller*> sorted_controllers_;

  // |scoring_points_| saves the scoring points of various
  // controllers.
  std::map<const Controller*, ScoringPoint> controller_scoring_points_;

  RTC_DISALLOW_COPY_AND_ASSIGN(ControllerManagerImpl);
};

}  // namespace webrtc

#endif  // MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CONTROLLER_MANAGER_H_


text:
layout: base
title:  'Statistics of Definitizer in UD_Cebuano-GJA'
udver: '2'
---

## Treebank Statistics: UD_Cebuano-GJA: Features: `Definitizer`

This feature is language-specific.
It occurs with 1 different values: `Yes`.

3 tokens (0%) have a non-empty value of `Definitizer`.
3 types (1%) occur at least once with a non-empty value of `Definitizer`.
3 lemmas (1%) occur at least once with a non-empty value of `Definitizer`.
The feature is used with 2 part-of-speech tags: <tt>ADJ</tt> (2; 0% instances), <tt>NOUN</tt> (1; 0% instances).

### `ADJ`

2 <tt>ADJ</tt> tokens (6% of all `ADJ` tokens) have a non-empty value of `Definitizer`.

The most frequent other feature values with which `ADJ` and `Definitizer` co-occurred: <tt>Gender</tt><tt>=EMPTY</tt> (2; 100%).

`ADJ` tokens may have the following values of `Definitizer`:

* `Yes` (2; 100% of non-empty `Definitizer`): kadugaya, Samoka

### `NOUN`

1 <tt>NOUN</tt> tokens (1% of all `NOUN` tokens) have a non-empty value of `Definitizer`.

`NOUN` tokens may have the following values of `Definitizer`:

* `Yes` (1; 100% of non-empty `Definitizer`): lenggwahea


text:
package com.github.opengl8080.gradle.plugin.assertj;

import java.util.function.Supplier;

public class DebugLogger {
    private static boolean debug = false;

    static void init(AssertjGenConfiguration config) {
        DebugLogger.debug = config.debug;
    }

    public static void debug(Supplier<String> messageSupplier) {
        if (!debug) {
            return;
        }

        String message = messageSupplier.get();
        System.out.println("[DEBUG] " + message);
    }
}


text:
/*
** @$=@$=@$=
*/
/*
**				DICOM 93
**		     Electronic Radiology Laboratory
**		   Mallinckrodt Institute of Radiology
**		Washington University School of Medicine
**
** Module Name(s):
** Author, Date:	Stephen M. Moore, 14-Apr-1993
** Intent:		This module defines several constants and function
**			prototypes for the LST facility which is used to
**			manipulate objects in linked lists.
** Last Update:		$Author: mohanar $, $Date: 2006/08/25 20:55:49 $
** Source File:		$RCSfile: lst.h,v $
** Revision:		$Revision: 1.1 $
** Status:		$State: Exp $
*/

#ifndef LST_IS_IN
#define LST_IS_IN

#ifdef  __cplusplus
extern "C" {
#endif

#define LST_K_BEFORE		0x00000000
#define LST_K_AFTER		0xFFFFFFFF

#ifndef LST_KEYS
typedef void LST_HEAD;
typedef void LST_NODE;
#endif

typedef unsigned long LST_END;

LST_HEAD *LST_Create(void);
CONDITION LST_Destroy(LST_HEAD ** list);
CONDITION LST_Enqueue(LST_HEAD ** list, LST_NODE * node);
CONDITION LST_Push(LST_HEAD ** list, LST_NODE * node);
LST_NODE *LST_Dequeue(LST_HEAD ** list);
LST_NODE *LST_Pop(LST_HEAD ** list);
unsigned long LST_Count(LST_HEAD ** list);
LST_NODE *LST_Head(LST_HEAD ** list);
LST_NODE *LST_Current(LST_HEAD ** list);
LST_NODE *LST_Tail(LST_HEAD ** list);
CONDITION LST_Insert(LST_HEAD ** list, LST_NODE * node, LST_END where);
LST_NODE *LST_Remove(LST_HEAD ** list, LST_END dir);
LST_NODE *LST_Next(LST_HEAD ** list);
LST_NODE *LST_Previous(LST_HEAD ** list);
LST_NODE *LST_Position(LST_HEAD ** list, LST_NODE * node);
CONDITION LST_Sort(LST_HEAD ** list, size_t nodeSize, int (*compare) ());
LST_NODE *LST_Index(LST_HEAD ** list, int index);
char *LST_Message(CONDITION cond);

#define LST_Top(x) LST_Head((x))
#define LST_Front(x) LST_Head((x))

#define LST_NORMAL		/* Normal return from LST package */ \
	FORM_COND(FAC_LST, SEV_SUCC, 1)
#define LST_LISTNOTEMPTY	/* Attempt to destroy list with elements */ \
	FORM_COND(FAC_LST, SEV_ERROR, 3)
#define LST_BADEND		/* */ \
	FORM_COND(FAC_LST, SEV_ERROR, 5)
#define LST_NOCURRENT	/* */ \
	FORM_COND(FAC_LST, SEV_ERROR, 7)

#ifdef  __cplusplus
}
#endif

#endif


text:
'use strict'

const Joi = require('joi')
const Bluebird = require('bluebird')
const Error = require('./Error')

module.exports = {
  validate: function (schema, payload, context) {
    return new Bluebird((resolve, reject) => {
      Joi.validate(payload, schema, { context }, err => {
        if (err) return reject(new Error.OptimizelyInvalidRequestError('Validation Error: ' + err.details[0].message))
        return resolve(payload)
      })
    })
  }
}


text:
body {
    background-color: blue;
    font-size: 500%;
}