text:
package eu.toolchain.serializer;

import eu.toolchain.serializer.collection.DefaultListSerializer;
import eu.toolchain.serializer.collection.DefaultMapSerializer;
import eu.toolchain.serializer.collection.DefaultNavigableMapSerializer;
import eu.toolchain.serializer.collection.DefaultNavigableSetSerializer;
import eu.toolchain.serializer.collection.DefaultSetSerializer;
import eu.toolchain.serializer.collection.DefaultSortedMapSerializer;
import eu.toolchain.serializer.collection.DefaultSortedSetSerializer;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class DefaultCollectionsProvider implements CollectionsProvider {
  final Serializer<Integer> size;

  @Override
  public <T> Serializer<List<T>> list(Serializer<T> value) {
    return new DefaultListSerializer<T>(size, value);
  }

  @Override
  public <K, V> Serializer<Map<K, V>> map(Serializer<K> key, Serializer<V> value) {
    return new DefaultMapSerializer<K, V>(size, key, value);
  }

  @Override
  public <K extends Comparable<?>, V> Serializer<SortedMap<K, V>> sortedMap(
    Serializer<K> key, Serializer<V> value
  ) {
    return new DefaultSortedMapSerializer<K, V>(size, key, value);
  }

  @Override
  public <K extends Comparable<?>, V> Serializer<NavigableMap<K, V>> navigableMap(
    Serializer<K> key, Serializer<V> value
  ) {
    return new DefaultNavigableMapSerializer<K, V>(size, key, value);
  }

  @Override
  public <T> Serializer<Set<T>> set(Serializer<T> value) {
    return new DefaultSetSerializer<T>(size, value);
  }

  @Override
  public <T extends Comparable<?>> Serializer<SortedSet<T>> sortedSet(Serializer<T> value) {
    return new DefaultSortedSetSerializer<T>(size, value);
  }

  @Override
  public <T extends Comparable<?>> Serializer<NavigableSet<T>> navigableSet(
    Serializer<T> serializer
  ) {
    return new DefaultNavigableSetSerializer<T>(size, serializer);
  }
}

redpajama_set_name: RedPajamaGithub


text:
munun Cookbook
==============
[![Build Status](https://secure.travis-ci.org/opscode-cookbooks/munin.png?branch=master)](http://travis-ci.org/opscode-cookbooks/munin)

Installs and configures Munin for a server and for clients using Chef Server search capabilities.

Requirements
------------
Requires Chef 0.10.0+ for Chef environments. Supports both chef-solo and chef-client ( with node searches support ).

Chef-solo:
- Since there is no search support for chef-solo, current node object will be used instead.
- See Data Bags section below in order to configure access to Munin web UI.

Chef-client:
- The monitoring server that uses this recipe should have a role named '`monitoring`'. This is configurable with an attribute (see below). The recipes use search, and narrow the results to nodes in the same `chef_environment`.

### Platforms
- Debian/Ubuntu
- Red Hat 5.7, 6.1
- ArchLinux

## Cookbooks

- apache2 - Not required (users can simply be in a data bag and the recipe will search), but useful for setting the openid list (see __OpenID Authentication__, below).
- users (see __Data Bags__) - Not required, but recommended to install perl cpan modules for munin plugins
- perl
- nginx

Attributes
----------
- `node['munin']['web_server_port']` - port that the munin vhost runs on, default 80
- `node['munin']['sysadmin_email']` - default email address for serveradmin in vhost.
- `node['munin']['server_auth_method']` - the authentication method to use, default is openid. Any other value will use htauth basic with an htpasswd file.
- `node['munin']['multi_environment_monitoring']` - allow multi-environment monitoring.  Default is false.
- `node['munin']['server_role']` - role of the munin server. Default is monitoring.
- `node['munin']['docroot']` - document root for the server apache vhost. on archlinux, the default is `/srv/http/munin`, or `/var/www/munin` on other platforms.
- `node['munin']['web_server']` - supports apache or nginx, default is "apache"
- `node['munin']['public_domain']` - override munin domain.
- `node['munin']['max_processes']` - Maximum number of simultaneous Munin-update processes. When not set, munin will use as many as necessary. Default is to use as many as necessary.
- `node['munin']['max_graph_jobs']` - Maximum number of parallel processes used by munin-graph when calling rrdgraph, default is "6"
- `node['munin']['max_cgi_graph_jobs']` - Maximum number of parallel munin-cgi-graph or munin-fastcgi-graph jobs, default is "6"

Recipes
-------
### client
The client recipe installs munin-node package and starts the service. It also searches for a node with the role for the munin server, by default `node['munin']['server_role']`. On Archlinux, it builds the list of plugins to enable.

### server
The server recipe will set up the munin server with Apache. It will create a cron job for generating the munin graphs, search for any nodes that have munin attributes (`node['munin']`), and use those nodes to connect for the graphs.

Optionally the server can be setup with NGINX.

Data Bags
---------
Create a `users` data bag that will contain the users that will be able to log into the Munin webui. Each user can use htauth with a specified password, or an openid. Users that should be able to log in should be in the sysadmin group. Example user data bag item:

```json
{
  "id": "munin",
  "groups": "sysadmin",
  "htpasswd": "hashed_htpassword",
  "openid": "http://munin.myopenid.com/"
}
```

When using `server_auth_method` 'openid', use the openid in the data bag item. Any other value for this attribute (e.g., "htauth", "htpasswd", etc) will use the htpasswd value as the password in `/etc/munin/htpasswd.users`.

- The openid must have the http:// and trailing /*. See __OpenID Authentication__ below for more information.

The htpasswd must be the hashed value. Get this value with htpasswd:

```text
% htpasswd -n -s munin
New password:
Re-type new password:
nagiosadmin:{SHA}oCagzV4lMZyS7jl2Z0WlmLxEkt4=
```

For example use the `{SHA}oCagzV4lMZyS7jl2Z0WlmLxEkt4=` value in the data bag.

Usage
-----
Create a role named `monitoring` that includes the munin::server recipe in the run list. Adjust the docroot to suit your environment.

```ruby
name 'monitoring'
description 'The monitoring server'
run_list(
  'recipe[munin::server]'
)
```

Apply this role to a node and it will be the munin server. Optionally create a DNS entry for it as munin, that will be used in the Apache vhost.

Use Chef 0.10's environments. For example, create a "production" environment Ruby DSL file and upload it to the Chef Server

```ruby
name 'production'
description 'Nodes in production'
```

For chef-client mode clients will automatically search for the server based on the value of the `node['munin']['server_role']` attribute in the same environment. If you don't use `monitoring` as the role name, change it in a role that is applied to any nodes that get the `munin::client` recipe.

### OpenID Authentication
The recipe `apache2::mod_auth_openid` is updated to a version of the module that apparently does not support the `AuthOpenIDUserProgram` directive anymore. The virtual host file has been updated to use the Apache HTTPD `require user` directive, with a concatenated list from `node['apache']['allowed_openids']`. This value must be an array of OpenIDs. Use of the `users::sysadmins` recipe will set this up based on data bag search results.

### Custom Plugins
This section describes how to add custom munin plugins.

The munin cookbook now has a definition that can be used to enable a new plugin for data gathering on a client. If an existing munin plugin is desired, call the definition

```ruby
munin_plugin 'nfs_client'
```

By default the plugin file name is the name parameter here. Specify the plugin parameter to use something else.

```ruby
munin_plugin 'nfs_client'
  plugin 'nfs_client_'
end
```

This creates a symlink from the plugins distribution directory, `/usr/share/munin/plugins` to the enabled plugins directory, `/etc/munin/plugins`, and once the server poller picks it up will have new graph data for that plugin. See the plugins distribution directory for available plugins or add your own.

If a custom plugin is required, add the plugin file to the munin cookbook in `site-cookbooks/munin/files/default/plugins`. Call the definition specifying that the plugin file should be downloaded from the cookbook.

```ruby
munin_plugin 'nfs_client_custom'
  create_file true
end
```

By default in both cases, the plugin is enabled. If a plugin should be disabled, use the `enable` parameter

```ruby
munin_plugin 'nfs_client_custom'
  enable false
end
```

Some plugins may require other configuration. For example, to use the memcache plugins, you'll need the `Cache::Memcache` cpan module installed, and use the `munin_plugin` definition. The perl cookbook from opscode includes a definition to handle this easily.

```ruby
cpan_module 'Cache::Memcached'
```

Then for example in your memcache recipe

```ruby
%w(
  memcached_bytes_
  memcached_connections_
  memcached_hits_
  memcached_items_
  memcached_requests_
  memcached_responsetime_
  memcached_traffic_
).each do |plugin_name|
  munin_plugin plugin_name do
    plugin "#{plugin_name}#{node['ipaddress'].gsub('.', '_')}_#{node[:memcached][:port]}"
    create_file true
  end
end
```

License & Authors
-----------------
- Author:: Nathan Haneysmith <nathan@opscode.com>
- Author:: Joshua Timberman <joshua@opscode.com>

```text
Copyright 2009-2013, Opscode, Inc

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.
```


text:
import {Feature} from "../../utils/feature.js";

export default new Feature({
  id: 'device-motion',
  aliases: ['accelerometer'],
  name: 'Device Motion',
  description: [
    `The first-generation device motions support is a part of Device Orientation API. It allows Web applications to access the accelerometer data
        expressed as acceleration (in m/s2) and gyroscope data expressed as rotation angle change (in °/s) for each of the three dimensions, provided as events.`,
    `Since mid-2018 the newer, separate specifications for each sensor type, based on the Generic Sensor API are being introduced. The APIs providing direct access to the readings
        of physical devices (Accelerometer API, Gyroscope API and Magnetometer API) as well as high-level fusion sensors made up by combining
         the readings of the physical sensors (Linear Acceleration Sensor API and Gravity Sensor API).`,
    `For the detection of the device's static position and orientation, see <a href="/device-position.html">Device Position</a>.`
  ],
  api: `
As a part of (older) Device Orientation API

window.addEventListener('devicemotion', listener)

An event fired when the significant changes in the device's acceleration or rotation has occured.

event.acceleration

A part of the event's payload returning the data about the current device's acceleration excluding gravity for all three axes
         (acceleration.x, acceleration.y, acceleration.z).

event.accelerationIncludingGravity

A part of the event's payload returning the data about the current device's acceleration including gravity if the device is unable
          to provide the data without the gravity effect using event.acceleration.

event.rotationRate

A part of the event's payload returning the data about the current device's rotation rates for all three axes
         (rotationRate.alpha, rotationRate.beta, rotationRate.gamma).

event.interval

A part of the event's payload returning the interval (in ms) at which the data is obtained from the accelerometer.

Accelerometer API

sensor = new Accelerometer()

Creates an object serving as a direct accessor to the accelerometer readings.

sensor.addEventListener('reading', listener)

An event fired when the accelerometer reading has changed, indicating that the sensor object contains updated acceleration in rad/s for all three axes (sensor.x, sensor.y, sensor.z).

sensor.start()

Starts listening for the sensor readings.

Gyroscope API

sensor = new Gyroscope()

Creates an object serving as a direct accessor to the gyroscope readings.

sensor.addEventListener('reading', listener)

An event fired when the gyroscope reading has changed, indicating that the sensor object contains updated angular velocity in rad/s for all three axes (sensor.x, sensor.y, sensor.z).

sensor.start()

Starts listening for the sensor readings.

Magnetometer API

sensor = new Magnetometer()

Creates an object serving as a direct accessor to the magnetometer readings.

sensor.addEventListener('reading', listener)

An event fired when the magnetometer reading has changed, indicating that the sensor object contains updated magnetic field for all three axes (sensor.x, sensor.y, sensor.z).

sensor.start()

Starts listening for the sensor readings.

Linear Acceleration Sensor API

sensor = new LinearAccelerationSensor()

Creates an object serving as an accessor to the linear acceleration readings based on accelerometer and either gyroscope or magnetometer.

sensor.addEventListener('reading', listener)

An event fired when the accelerometer reading has changed, indicating that the sensor object contains updated acceleration values in m/s2 for all three axes (sensor.x, sensor.y, sensor.z).

sensor.start()

Starts listening for the sensor readings.

Gravity Sensor API

sensor = new GravitySensor()

Creates an object serving as an accessor to the gravity readings based on accelerometer and gyroscope.

sensor.addEventListener('reading', listener)

An event fired when the accelerometer reading has changed, indicating that the sensor object contains updated acceleration values in m/s2 for all three axes (sensor.x, sensor.y, sensor.z).

sensor.start()

Starts listening for the sensor readings.

`,
  caniuse: 'deviceorientation',
  tests: [
    Feature.windowContains('DeviceMotionEvent'),
    Feature.windowContains('Accelerometer'),
    Feature.windowContains('Gyroscope'),
    Feature.windowContains('Magnetometer'),
    Feature.windowContains('LinearAccelerationSensor'),
    Feature.windowContains('GravitySensor'),
  ],
  demo: {
    html: `

    API used

    linear acceleration (excl. gravity)

    acceleration incl. gravity

    rotation rate

    interval (ms)

Demo based on HTML5 Rocks article.
`,
    js: `if ('LinearAccelerationSensor' in window && 'Gyroscope' in window) {
  document.getElementById('moApi').innerHTML = 'Generic Sensor API';

  let lastReadingTimestamp;
  let accelerometer = new LinearAccelerationSensor();
  accelerometer.addEventListener('reading', e => {
    if (lastReadingTimestamp) {
      intervalHandler(Math.round(accelerometer.timestamp - lastReadingTimestamp));
    }
    lastReadingTimestamp = accelerometer.timestamp
    accelerationHandler(accelerometer, 'moAccel');
  });
  accelerometer.start();

  if ('GravitySensor' in window) {
    let gravity = new GravitySensor();
    gravity.addEventListener('reading', e => accelerationHandler(gravity, 'moAccelGrav'));
    gravity.start();
  }

  let gyroscope = new Gyroscope();
  gyroscope.addEventListener('reading', e => rotationHandler({
    alpha: gyroscope.x,
    beta: gyroscope.y,
    gamma: gyroscope.z
  }));
  gyroscope.start();

} else if ('DeviceMotionEvent' in window) {
  document.getElementById('moApi').innerHTML = 'Device Motion API';

  var onDeviceMotion = function (eventData) {
    accelerationHandler(eventData.acceleration, 'moAccel');
    accelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
    rotationHandler(eventData.rotationRate);
    intervalHandler(eventData.interval);
  }

  window.addEventListener('devicemotion', onDeviceMotion, false);
} else {
  document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}

function accelerationHandler(acceleration, targetId) {
  var info, xyz = "[X, Y, Z]";

  info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
  info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
  info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
  document.getElementById(targetId).innerHTML = info;
}

function rotationHandler(rotation) {
  var info, xyz = "[X, Y, Z]";

  info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
  info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
  info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));
  document.getElementById("moRotation").innerHTML = info;
}

function intervalHandler(interval) {
  document.getElementById("moInterval").innerHTML = interval;
}`,
    jsOnExit: `if (onDeviceMotion) {
    window.removeEventListener('devicemotion', onDeviceMotion);
}`
  },
  links: [
    {
      url: 'https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion',
      title: 'Device Orientation API Specification Draft'
    },
    {url: 'https://w3c.github.io/accelerometer/', title: 'Accelerometer API Specification Draft'},
    {url: 'https://w3c.github.io/gyroscope/', title: 'Gyroscope API Specification Draft'},
    {url: 'https://w3c.github.io/sensors/', title: 'Generic Sensor API Specification Draft'},
    {url: 'https://www.w3.org/TR/motion-sensors/', title: 'Motion Sensors Explainer'},
    {
      url: 'https://developers.google.com/web/updates/2017/09/sensors-for-the-web',
      title: 'Google Developers: Sensors For The Web'
    },
    {url: 'https://github.com/kenchris/sensor-polyfills', title: 'Polyfills for the W3C Generic Sensor APIs'}
  ]
})


text:
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build cgo && !netgo && (dragonfly || freebsd)

package net

/*
#include <netdb.h>
*/
import "C"

const cgoAddrInfoFlags = (C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL) & C.AI_MASK


text:
package de.yadrone.base.utils;

public class ARDroneUtils {
	public static final int PORT=5556;
	public static final int VIDEO_PORT=5555;
	public static final int NAV_PORT=5554;
	public static final int CONTROL_PORT = 5559;
}


text:
package org.ehcache.clustered;

import org.ehcache.clustered.client.config.ClusteredResourcePool;
import org.ehcache.clustered.client.config.ClusteringServiceConfiguration;
import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder;
import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder;
import org.ehcache.clustered.client.internal.EhcacheClientEntity;
import org.ehcache.clustered.client.internal.service.ClusteredTierCreationException;
import org.ehcache.clustered.client.internal.service.ClusteredTierDestructionException;
import org.ehcache.clustered.client.internal.service.ClusteredTierManagerConfigurationException;
import org.ehcache.clustered.client.internal.service.ClusteringServiceFactory;
import org.ehcache.clustered.client.service.ClusteringService;
import org.ehcache.clustered.common.Consistency;
import org.ehcache.clustered.common.internal.ServerStoreConfiguration;
import org.ehcache.clustered.common.internal.exceptions.InvalidStoreException;
import org.ehcache.clustered.common.internal.exceptions.InvalidStoreManagerException;
import org.ehcache.impl.serialization.CompactJavaSerializer;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.terracotta.testing.rules.BasicExternalCluster;
import org.terracotta.testing.rules.Cluster;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Collections;

import static org.ehcache.config.units.MemoryUnit.MB;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class BasicLifeCyclePassiveReplicationTest {

  private static final String RESOURCE_CONFIG =
      "<service xmlns:ohr='http://www.terracotta.org/config/offheap-resource' id=\"resources\">"
      + "<ohr:offheap-resources>"
      + "<ohr:resource name=\"primary-server-resource\" unit=\"MB\">16</ohr:resource>"
      + "</ohr:offheap-resources>" +
      "</service>\n";

  @ClassRule
  public static Cluster CLUSTER =
      new BasicExternalCluster(new File("build/cluster"), 2, Collections.<File>emptyList(), "", RESOURCE_CONFIG, "");

  @Before
  public void startServers() throws Exception {
    CLUSTER.getClusterControl().waitForActive();
    CLUSTER.getClusterControl().waitForRunningPassivesInStandby();
  }

  @After
  public void tearDown() throws Exception {
    CLUSTER.getClusterControl().terminateActive();
    CLUSTER.getClusterControl().startAllServers();
  }

  @Test
  public void testCreateCacheReplication() throws Exception {

    ClusteringServiceConfiguration configuration =
        ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI())
            .autoCreate()
            .build();

    ClusteringService service = new ClusteringServiceFactory().create(configuration);

    service.start(null);

    EhcacheClientEntity clientEntity = getEntity(service);

    clientEntity.createCache("testCache", getServerStoreConfiguration("primary-server-resource"));

    CLUSTER.getClusterControl().terminateActive();

    try {
      clientEntity.createCache("testCache", getServerStoreConfiguration("primary-server-resource"));
      fail("ClusteredTierCreationException Expected.");
    } catch (ClusteredTierCreationException e) {
      assertThat(e.getCause(), instanceOf(InvalidStoreException.class));
      assertThat(e.getCause().getMessage(), is("Clustered tier 'testCache' already exists"));
    }

    service.stop();

  }

  @Test
  public void testDestroyCacheReplication() throws Exception {

    ClusteringServiceConfiguration configuration =
        ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI())
            .autoCreate()
            .build();

    ClusteringService service = new ClusteringServiceFactory().create(configuration);

    service.start(null);

    EhcacheClientEntity clientEntity = getEntity(service);

    clientEntity.createCache("testCache", getServerStoreConfiguration("primary-server-resource"));

    clientEntity.releaseCache("testCache");
    clientEntity.destroyCache("testCache");

    CLUSTER.getClusterControl().terminateActive();

    try {
      clientEntity.destroyCache("testCache");
      fail("ClusteredTierReleaseException Expected.");
    } catch (ClusteredTierDestructionException e) {
      assertThat(e.getCause(), instanceOf(InvalidStoreException.class));
      assertThat(e.getCause().getMessage(), is("Clustered tier 'testCache' does not exist"));
    }

    service.stop();

  }

  @Test
  public void testConfigureReplication() throws Exception {
    ClusteringServiceConfiguration configuration =
        ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI())
            .autoCreate()
            .build();

    ClusteringService service = new ClusteringServiceFactory().create(configuration);

    service.start(null);

    EhcacheClientEntity clientEntity = getEntity(service);

    CLUSTER.getClusterControl().terminateActive();

    try {
      clientEntity.configure(configuration.getServerConfiguration());
      fail("ClusteredTierManagerConfigurationException Expected.");
    } catch (ClusteredTierManagerConfigurationException e) {
      assertThat(e.getCause(), instanceOf(InvalidStoreManagerException.class));
      assertThat(e.getCause().getMessage(), is("Clustered Tier Manager already configured"));
    }

    service.stop();
  }

  private static EhcacheClientEntity getEntity(ClusteringService clusteringService) throws NoSuchFieldException, IllegalAccessException {
    Field entity = clusteringService.getClass().getDeclaredField("entity");
    entity.setAccessible(true);
    return (EhcacheClientEntity)entity.get(clusteringService);
  }

  private static ServerStoreConfiguration getServerStoreConfiguration(String resourceName) {
    ClusteredResourcePool resourcePool = ClusteredResourcePoolBuilder.clusteredDedicated(resourceName, 4, MB);
    return new ServerStoreConfiguration(resourcePool.getPoolAllocation(),
        String.class.getName(), String.class.getName(), null, null, CompactJavaSerializer.class.getName(), CompactJavaSerializer.class
        .getName(), Consistency.STRONG);
  }

}


text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.Graphics
{
	public interface IDimension : IDimensionGetter, IDimensionSetter
	{

	}
}


text:
import commonware.log

from rest_framework.permissions import BasePermission
from tastypie.authorization import Authorization, ReadOnlyAuthorization
from waffle import flag_is_active, switch_is_active

from access import acl

log = commonware.log.getLogger('z.api')

class OwnerAuthorization(Authorization):

    def is_authorized(self, request, object=None):
        # There is no object being passed, so we'll assume it's ok
        if not object:
            return True
        # There is no request user or no user on the object.
        if not request.amo_user:
            return False

        return self.check_owner(request, object)

    def check_owner(self, request, object):
        if not object.user:
            return False
        # If the user on the object and the amo_user match, we are golden.
        return object.user.pk == request.amo_user.pk

class AppOwnerAuthorization(OwnerAuthorization):

    def check_owner(self, request, object):
        # If the user on the object and the amo_user match, we are golden.
        try:
            if object.authors.filter(user__id=request.amo_user.pk):
                return True

        # Appropriately handles AnonymousUsers when `amo_user` is None.
        except AttributeError:
            return False

        # Reviewers can see non-public apps.
        if request.method == 'GET':
            if acl.action_allowed(request, 'Apps', 'Review'):
                return True

class AnonymousReadOnlyAuthorization(ReadOnlyAuthorization):
    """
    Allows read-only access for anonymous users and optional auth for
    authenticated users.

    If the user is anonymous, only ``GET`` requests are allowed.

    If the user is authenticated, a custom authorization object can be used.
    If no object is set, authenticated users always have access.

    Keyword Arguments

    **authorizer=None**
        If set, this authorization object will be used to check the action for
        authenticated users.
    """

    def __init__(self, *args, **kw):
        self.authorizer = kw.pop('authorizer', None)
        super(AnonymousReadOnlyAuthorization, self).__init__(*args, **kw)

    def is_authorized(self, request, object=None):
        if request.user.is_anonymous():
            sup = super(AnonymousReadOnlyAuthorization, self)
            res = sup.is_authorized(request, object)
            log.info('ReadOnlyAuthorization returned: %s' % res)
            return res
        if self.authorizer:
            res = self.authorizer.is_authorized(request, object)
            log.info('Authorizer %s returned: %s' %
                     (self.authorizer.__class__.__name__, res))
            return res
        return True

class PermissionAuthorization(Authorization):

    def __init__(self, app, action, *args, **kw):
        self.app, self.action = app, action

    def is_authorized(self, request, object=None):
        if acl.action_allowed(request, self.app, self.action):
            return True
        log.info('Permission authorization failed')
        return False

    has_permission = is_authorized

class AllowSelf(BasePermission):
    """
    Permission class to use when you are dealing with UserProfile models and
    you want only the corresponding user to be able to access his UserProfile
    instance.
    """
    def has_permission(self, request, view):
        return request.user.is_authenticated()

    def has_object_permission(self, request, view, object):
        try:
            return object.pk == request.amo_user.pk

        # Appropriately handles AnonymousUsers when `amo_user` is None.
        except AttributeError:
            return False

class AllowNone(BasePermission):

    def has_permission(self, request, view):
        return False

    def has_object_permission(self, request, view, obj):
        return False

class AllowOwner(BasePermission):
    """
    Permission class to use when you are dealing with a model instance that has
    a "user" FK pointing to an UserProfile, and you want only the corresponding
    user to be able to access your instance.

    Do not use with models pointing to an User! There is no guarantee that the
    pk is the same between a User and an UserProfile instance.
    """
    def has_permission(self, request, view):
        return request.user.is_authenticated()

    def has_object_permission(self, request, view, obj):
        return obj.user.pk == request.amo_user.pk

class AllowAppOwner(BasePermission):

    def has_permission(self, request, view):
        return not request.user.is_anonymous()

    def has_object_permission(self, request, view, object):
        try:
            return object.authors.filter(user__id=request.amo_user.pk).exists()

        # Appropriately handles AnonymousUsers when `amo_user` is None.
        except AttributeError:
            return False

class AllowAppOwnerOrPermission(BasePermission):
    """
    Allows app owners or users with the specified permission.
    """
    def __init__(self, app, action):
        self.app = app
        self.action = action

    def has_permission(self, request, view):
        return not request.user.is_anonymous()

    def has_object_permission(self, request, view, object):
        try:
            return (
                acl.action_allowed(request, self.app, self.action) or
                object.authors.filter(user__id=request.amo_user.pk).exists())

        # Appropriately handles AnonymousUsers when `amo_user` is None.
        except AttributeError:
            return False

    def __call__(self, *a):
        """
        Ignore DRF's nonsensical need to call this object.
        """
        return self

class AllowReviewerReadOnly(BasePermission):

    def is_authorized(self, request, object=None):
        if request.method == 'GET' and acl.action_allowed(request,
                                                          'Apps', 'Review'):
            return True

def flag(name):
    return type('FlagPermission', (WafflePermission,),
                {'type': 'flag', 'name': name})

def switch(name):
    return type('SwitchPermission', (WafflePermission,),
                {'type': 'switch', 'name': name})

class WafflePermission(BasePermission):

    def has_permission(self, request, view):
        if self.type == 'flag':
            return flag_is_active(request, self.name)
        elif self.type == 'switch':
            return switch_is_active(self.name)
        raise NotImplementedError

class GroupPermission(BasePermission):

    def __init__(self, app, action):
        self.app = app
        self.action = action

    def has_permission(self, request, view):
        return acl.action_allowed(request, self.app, self.action)

    def __call__(self, *a):
        """
        ignore DRF's nonsensical need to call this object.
        """
        return self


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Pl. Coromandel 1:42, t. 56. 1795

#### Original name
null

### Remarks
null


text:
number: 281
date: 2020-08-10 09:15:00

title: "Yes, It's All Your Fault: Active vs. Passive Mindsets"
authors: "Shane Parrish"
tags:
- Active
- Mindset

site: "Farnam Street"
address: "https://fs.blog/2019/03/active-mindset/"
---

It's not that you can't do something it's that unless you have literally done everything, you're choosing not to because the price is too high. Stop lying to yourself.


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2020 informedcitizenry <informedcitizenry@gmail.com>
//
// Licensed under the MIT license. See LICENSE for full license information.
//
//-----------------------------------------------------------------------------

using System;

namespace Core6502DotNet
{
    /// <summary>
    /// A class that assembles miscellaneous directives, such as error and warn messages.
    /// </summary>
    public sealed class MiscAssembler : AssemblerBase
    {
        #region Constructors

        /// <summary>
        /// Constructs a DotNetAsm.MiscAssembler class.
        /// </summary>
        /// <param name="services">The shared <see cref="AssemblyServices"/> object.</param>
        public MiscAssembler(AssemblyServices services)
            :base(services)
        {
            Reserved.DefineType("Directives",
                    ".assert", ".bank", ".end",
                    ".eor", ".echo", ".forcepass",
                    ".format", ".invoke",
                    ".initmem", ".target",
                    ".error", ".errorif",
                    ".pron", ".proff",
                    ".warnif", ".warn",
                    ".dsection", ".section"
                );
            ExcludedInstructionsForLabelDefines.Add(".section");
            Services.PassChanged += (s, a) => Services.PrintOff = false;
        }

        #endregion

        #region Methods

        void ThrowConditional(SourceLine line)
        {
            if (line.Operand.Children.Count < 2 ||
                line.Operand.Children[1].Children.Count == 0)
            {
                Services.Log.LogEntry(line, line.Operand, $"Missing arguments for directive \"{line.InstructionName}\".");
            }
            else if (line.Operand.Children.Count > 2 || !line.Operand.Children[1].Children[0].ToString().Trim().EnclosedInDoubleQuotes())
            {
                Services.Log.LogEntry(line, line.Operand, $"Argument error for directive \"{line.InstructionName}\".");
            }
            else if (Services.Evaluator.EvaluateCondition(line.Operand.Children[0].Children))
            {
                if (line.Operand.Children.Count > 1)
                    Output(line, line.Operand.Children[1]);
                else
                    Output(line, $"Expression \"{line.UnparsedSource.Substring(line.Operand.Position)}\" evaluated to true.");
            }
        }

        void SetEor(SourceLine line)
        {
            if (!line.OperandHasToken)
            {
                Services.Log.LogEntry(line, line.Instruction, "Too few arguments for directive \".eor\".");
                return;
            }
            var eor = Services.Evaluator.Evaluate(line.Operand.Children, sbyte.MinValue, byte.MaxValue);
            var eor_b = Convert.ToByte(eor);
            Services.Output.Transform = (delegate (byte b)
            {
                b ^= eor_b;
                return b;
            });
        }

        void SetBank(SourceLine line)
        {
            if (!line.OperandHasToken)
                Services.Log.LogEntry(line, "Too few arguments for directive \".bankmode\".");
            else
                Services.Output.SetBank((int)Services.Evaluator.Evaluate(line.Operand, sbyte.MinValue, byte.MaxValue));
        }

        protected override string OnAssembleLine(SourceLine line)
        {
            var instruction = line.InstructionName;
            switch (instruction)
            {
                case ".assert":
                    DoAssert(line);
                    break;
                case ".bank":
                    SetBank(line);
                    break;
                case ".warnif":
                case ".errorif":
                    ThrowConditional(line);
                    break;
                case ".echo":
                case ".error":
                case ".warn":
                    if (line.OperandHasToken && line.Operand.Children.Count == 1 &&
                        StringHelper.ExpressionIsAString(line.Operand.Children[0], Services.SymbolManager))
                    {
                        Output(line, line.Operand.Children[0]);
                    }
                    else if (instruction.Equals(".echo"))
                    {
                        if (Services.Evaluator.ExpressionIsCondition(line.Operand.Children))
                            Output(line, Services.Evaluator.EvaluateCondition(line.Operand).ToString());
                        else
                            Output(line, Services.Evaluator.Evaluate(line.Operand.Children, Evaluator.CbmFloatMinValue, Evaluator.CbmFloatMaxValue).ToString());
                    }
                    else
                    {
                        Services.Log.LogEntry(line, line.Operand,
                            "String expression expected.");
                    }
                    break;
                case ".eor":
                    SetEor(line);
                    break;
                case ".forcepass":
                    if (line.OperandHasToken)
                        Services.Log.LogEntry(line, line.Operand,
                            "Unexpected expression found.");
                    else if (Services.CurrentPass == 0)
                        Services.PassNeeded = true;
                    break;
                case ".invoke":
                    InvokeFunction(line);
                    break;
                case ".proff":
                case ".pron":
                    if (line.OperandHasToken)
                        Services.Log.LogEntry(line, line.Operand,
                            "Unexpected expression found.");
                    else
                        Services.PrintOff = instruction.Equals(".proff");
                    break;
                case ".dsection":
                    DefineSection(line);
                    break;
                case ".section":
                    return SetSection(line);
                case ".format":
                case ".target":
                    if (Services.CurrentPass == 0)
                    {
                        if (Services.Output.HasOutput)
                            Services.Log.LogEntry(line, line.Instruction, "Cannot specify target format after assembly has started.");
                        else if (!line.OperandHasToken || !line.OperandExpression.Trim().EnclosedInDoubleQuotes())
                            Services.Log.LogEntry(line, line.Operand, "Expression must be a string.");
                        else if (!string.IsNullOrEmpty(Services.OutputFormat))
                            Services.Log.LogEntry(line, line.Operand, "Output format was previously specified.");
                        else
                            Services.SelectFormat(line.OperandExpression.Trim().TrimOnce('"'));
                        if (instruction.Equals(".target"))
                            Services.Log.LogEntry(line, line.Instruction, "\".target\" is deprecated. Use \".format\" instead.", false);
                    }
                    break;
                default:
                    InitMem(line);
                    break;
            }
            return string.Empty;
        }

        void DefineSection(SourceLine line)
        {
            if (!string.IsNullOrEmpty(line.LabelName))
                throw new SyntaxException(line.Label.Position, "Label definitions are not allowed for directive \".dsection\".");
            if (Services.CurrentPass == 0)
            {
                var parms = line.Operand.Children;
                if (parms.Count < 2)
                    throw new SyntaxException(line.Operand.Position,
                        "Section definition missing one or more parameters.");
                if (parms.Count > 3)
                    throw new SyntaxException(line.Operand.LastChild.Position,
                        $"Unexpected parameter \"{parms[3]}\" in section definition.");

                var name = parms[0].ToString().Trim();
                if (!name.EnclosedInDoubleQuotes())
                    throw new SyntaxException(parms[0].Position, "Section name must be a string.");
                if (!Services.Options.CaseSensitive)
                    name = name.ToLower();

                var endsParameter = parms.Count == 3;
                if (!Services.Evaluator.ExpressionIsConstant(parms[1]) ||
                    (endsParameter && !Services.Evaluator.ExpressionIsConstant(parms[2])))
                    throw new SyntaxException(parms[1].Position,
                        "Section start and end parameters must be constant expressions.");
                var starts = Convert.ToInt32(Services.Evaluator.Evaluate(parms[1]));
                var ends = BinaryOutput.MaxAddress + 1;
                if (endsParameter)
                    ends = Convert.ToInt32(Services.Evaluator.Evaluate(parms[2]));

                Services.Output.DefineSection(name, starts, ends);
            }
        }

        void InvokeFunction(SourceLine line)
        {
            if (!line.OperandHasToken || line.Operand.Children[0].Children.Count == 0)
                Services.Log.LogEntry(line, line.Operand, "Missing function name from invocation directive.");
            else if (line.Operand.Children[0].Children.Count < 2)
                Services.Log.LogEntry(line, line.Operand, "Missing function parameters.");
            else if (line.Operand.Children[0].Children.Count > 2)
                Services.Log.LogEntry(line, line.Operand.Children[0].Children[2],
                    "Unexpected expression.");
            else
                Services.Evaluator.Invoke(line.Operand.Children[0].Children[0], line.Operand.Children[0].Children[1]);
        }

        string SetSection(SourceLine line)
        {
            if (!line.OperandExpression.EnclosedInDoubleQuotes())
                throw new SyntaxException(line.Operand.Position, "Directive expects a string expression.");
            var sectionName = line.OperandExpression.Trim();
            if (!Services.Options.CaseSensitive)
                sectionName = sectionName.ToLower();
            if (!Services.Output.SetSection(sectionName))
                throw new SyntaxException(line.Operand.Position,
                    $"Section {line.Operand} not defined or previously selected.");
            if (!string.IsNullOrEmpty(line.LabelName))
            {
                if (line.LabelName.Equals("*"))
                    Services.Log.LogEntry(line, "Redundant assignment of program counter for directive \".section\".", false);
                else if (line.LabelName[0].IsSpecialOperator())
                    Services.SymbolManager.DefineLineReference(line.LabelName, Services.Output.LogicalPC);
                else
                    Services.SymbolManager.DefineSymbolicAddress(line.LabelName);
                return $"=${Services.Output.LogicalPC:x4}                  {line.LabelName}  // section {line.Operand}";
            }
            return $"* = ${Services.Output.LogicalPC:x4}  // section {line.Operand}";
        }

        void InitMem(SourceLine line)
        {
            if (!line.OperandHasToken)
            {
                Services.Log.LogEntry(line, line.Instruction, "Expected expression.");
            }
            else if (line.Operand.Children.Count > 1)
            {
                Services.Log.LogEntry(line, line.Operand.Children[1].Position, "Too many arguments for instruction.");
            }
            else
            {
                var amount = Services.Evaluator.Evaluate(line.Operand.Children, sbyte.MinValue, byte.MaxValue);
                Services.Output.InitMemory(Convert.ToByte((int)amount & 0xFF));
            }
        }

        void Output(SourceLine line, string output)
        {
            var type = line.InstructionName.Substring(0, 5);
            var doEcho = type.Equals(".echo") && (Services.CurrentPass == 0 || Services.Options.EchoEachPass);
            if (doEcho)
                Console.WriteLine(output);
            else if (Services.CurrentPass == 0)
                Services.Log.LogEntry(line, line.Operand, output, type.Equals(".erro"));
        }

        void Output(SourceLine line, Token operand)
        {
            if (StringHelper.ExpressionIsAString(operand, Services.SymbolManager))
                Output(line, StringHelper.GetString(operand, Services.SymbolManager, Services.Evaluator));
            else
                Output(line, Services.Evaluator.Evaluate(operand).ToString());
        }

        void DoAssert(SourceLine line)
        {
            if (line.Operand.Children.Count == 0)
            {
                Services.Log.LogEntry(line, line.Operand, "One or more arguments expected for assertion directive.");
            }
            else if (line.Operand.Children.Count > 2)
            {
                Services.Log.LogEntry(line, line.Operand.Children[2], "Unexpected expression found.");
            }
            else if (!Services.Evaluator.EvaluateCondition(line.Operand.Children[0]))
            {
                if (line.Operand.Children.Count > 1)
                    Output(line, line.Operand.Children[1]);
                else
                    Output(line, "Assertion failed.");
            }
        }

        #endregion
    }
}


text:
#pragma once

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "storage/index/abstract_index.hpp"
#include "types.hpp"
#include "variable_length_key_store.hpp"

namespace hyrise {

class CompositeGroupKeyIndexTest;
class BaseDictionarySegment;

/**
 *
 * The CompositeGroupKey-Index works on an arbitrary number of dictionary compressed segments.
 * It uses three structures:
 *      - a position list containing record positions (ie ChunkOffsets)
 *      - a sorted store containing all unique concatenated keys of the input segments
 *      - an offset list storing where the positions for a certain concatenated key start at
 *        in the position list
 *
 * An example structure along with the corresponding dictionary segment's attribute vectors might look like this:
 *    +---+-----------+     +------------+---------+-----------+
 *    |(i)| AV1 | AV2 |     |Concatenated| Offsets | Positions |
 *    |   |     |     |     |    Key     |         |           |
 *    +---+-----------+     +------------+---------+-----------+
 *    | 0 |  4  |  1  |     |     03     |    0    |     4     | ie key '03' can be found at i = 4 in the AV
 *    | 1 |  2  |  2  |     |     10     |    1    |     6     |
 *    | 2 |  3  |  4  |     |     12     |    2    |     5     |
 *    | 3 |  2  |  2  |     |     22     |    3    |     1     | ie key '22' can be found at i = 1 and 3
 *    | 4 |  0  |  3  |     |     34     |    5    |     3     |
 *    | 5 |  1  |  2  |     |     41     |    6    |     2     |
 *    | 6 |  1  |  0  |     |     51     |    7    |     0     |
 *    | 7 |  5  |  1  |     |            |         |     7     | ie key '51' can be found at i = 7 in the AV
 *    +---+-----------+     +------------+---------+-----------+
 *
 * Find more information about this in our wiki: https://github.com/hyrise/hyrise/wiki/Composite-GroupKey-Index
 */
class CompositeGroupKeyIndex : public AbstractIndex {
  friend class CompositeGroupKeyIndexTest;

 public:
  /**
   * Predicts the memory consumption in bytes of creating this index.
   * See AbstractIndex::estimate_memory_consumption()
   */
  static size_t estimate_memory_consumption(ChunkOffset row_count, ChunkOffset distinct_count, uint32_t value_bytes);

  CompositeGroupKeyIndex(CompositeGroupKeyIndex&&) = default;

  explicit CompositeGroupKeyIndex(const std::vector<std::shared_ptr<const AbstractSegment>>& segments_to_index);

 private:
  Iterator _lower_bound(const std::vector<AllTypeVariant>& values) const final;
  Iterator _upper_bound(const std::vector<AllTypeVariant>& values) const final;
  Iterator _cbegin() const final;
  Iterator _cend() const final;
  std::vector<std::shared_ptr<const AbstractSegment>> _get_indexed_segments() const final;

  size_t _memory_consumption() const final;

  /**
   * Creates a VariableLengthKey using the values given as parameters.
   *
   * The order of the values matters! The key '14' created from the values '1' and '4'
   * is not the same as the key '41', created from the same values but provided in a different order.
   *
   * We need to provide the information whether the key is used for an upper- or lower-bound
   * search to make sure the key will be mapped to the correct positions in case the last value
   * is not present in the corresponding dictionary segment. Consider the following example:
   *
   *    +------------+---------+-----------+
   *    |Concatenated| Offsets | Positions |
   *    |    Key     |         |           |
   *    +------------+---------+-----------+
   *    |     03     |    0    |     4     |
   *    |     10     |    1    |     6     |
   *    |     12     |    2    |     5     |
   *    |     22     |    3    |     1     |
   *    |     34     |    5    |     3     |
   *    |     41     |    6    |     2     |
   *    |     51     |    7    |     0     |
   *    +------------+---------+-----------+
   *
   * If the search values would correspond to the attribute values '1' and '0', we would
   * want to have the key '10' for a lower-bound-query on the keystore, but use the key '11' for an
   * upper-bound-query. To be able to create the correct search-key, we thus have to provide the
   * information what query the key will be used for.
   *
   * @returns a VariableLengthKey created based on the given values
   */
  VariableLengthKey _create_composite_key(const std::vector<AllTypeVariant>& values, bool is_upper_bound) const;

  /**
   *
   * @returns an iterator pointing to the first ChunkOffset in the position-vector
   * that belongs to the given VariableLengthKey
   */
  Iterator _get_position_iterator_for_key(const VariableLengthKey& key) const;

 private:
  // the segments the index is based on
  std::vector<std::shared_ptr<const BaseDictionarySegment>> _indexed_segments;

  // contains concatenated value-ids
  VariableLengthKeyStore _keys;

  // the start positions within _position_list for every key
  std::vector<ChunkOffset> _key_offsets;

  // contains positions, ie ChunkOffsets, for the concatenated value-ids
  std::vector<ChunkOffset> _position_list;
};
}  // namespace hyrise


text:
var _ = require("lodash"),
    util = require("util");

function squeezeArgs(_arguments) {
    //Format args
    let index = -1, argsIndexesToRemove = [];
    for (let i in _arguments) {
        index++;
        if (_.isString(_arguments[i])) {
            _arguments[i] = _arguments[i].replace(/%([a-z%])/g, function (match, format) {
                // if we encounter an escaped % then don't increase the array index
                if (format === '%') return match;
                index++;
                argsIndexesToRemove.push(index);
                let replacingValue = _arguments[index];
                if (_.isPlainObject(replacingValue))
                    replacingValue = util.inspect(replacingValue, {showHidden: true, depth: null});
                if (_.isFunction(replacingValue))
                    replacingValue = '[Function: ' + (replacingValue.name === '' ? 'anonymous' : replacingValue.name) + ']';
                return replacingValue;
            });
            argsIndexesToRemove.forEach(function (ind) {
                delete _arguments[ind];
            });
            argsIndexesToRemove = [];
        }
    }
    return _.map(_arguments);
}

//CustomError("codeString", "my message", "next hello", 404, {info:"hello"}, {otherInfo:3}, "warning");
function CustomError() {
    let _arguments = squeezeArgs(arguments);
    for (let i = 0; i < _arguments.length; i++) {
        //Deal with string _arguments
        if (_.isString(_arguments[i]) && _arguments[i].length > 0) {
            if (_arguments[i] == "fatal" || _arguments[i] == "warning" || _arguments[i] == "notice")
                this.level = _arguments[i];
            else if (_arguments[i].length < 35 && _.camelCase(_arguments[i]) == _arguments[i])
                this.codeString = _arguments[i];
            else // a message
            {
                if (!this.message)
                    this.message = _arguments[i];
                else
                    this.message += " " + _arguments[i];
            }
        }
        else if (_.isFinite(_arguments[i]))
            this.code = _arguments[i];
        else if (_.isObject(_arguments[i]))
            this.use(_arguments[i]);
    }
    this.code = _.isFinite(this.code) ? this.code : 500;
    this.level = this.level || 'fatal';
    this.name = 'Error';
    this.isCustomError = true;
    this.stack = Error.call(this, this.message || this.codeString).stack;
    this.message = this.message || this.codeString; //a human-readable message
}

CustomError.prototype = Object.create(Error.prototype, {
    constructor: {
        value: CustomError,
        writable: true,
        configurable: true
    }
});

function useThat(feedArray, method) {
    for (let i = 0; i < feedArray.length; i++) {
        let e = feedArray[i],
            err = _.get(e, 'error') || e;
        if (_.isObject(err) && (err instanceof Error || e.error != void 0 /* level 1 */ || e.isCustomError === true /* level 2 */)) {
            let keys;
            if (err instanceof Error && !err.isCustomError) // native JS error, so hidden properties
                keys = _.union(['message', 'stack', 'code', 'codeString', 'level', 'info', 'extra'], Object.getOwnPropertyNames(err));
            else
                keys = _.keys(err);
            for (let k of keys) {
                if (k === 'isCustomError')
                    continue;
                if (err[k] != void 0) {
                    if (_.isPlainObject(err[k])) { // e.g err.info
                        if (this.info == void 0)
                            this.info = {};
                        _[method](this.info, err[k]);
                    }
                    else {
                        if (k === 'message' && err.message != void 0 && err.message != '' && this.message === this.codeString) {
                            this.message = err.message;
                            this.stack = 'Error: ' + err.message + this.stack.substr(this.stack.indexOf('\n'));
                        }
                        _[method](this, { [k]: err[k] });
                    }
                }
            }
        }
        else if (_.isPlainObject(err)) {
            if (this.info != void 0)
                _[method](this.info, err);
            else
                this.info = err;
        }
        else {
            if (this.info == void 0)
                this.info = {};
            if (!_.isArray(this.info.unclassified))
                this.info.unclassified = [];
            this.info.unclassified.push(e);
        }
    }
    return this;
};

CustomError.prototype.unstack = function unstack() {
    delete this.stack;
    return this;
};

CustomError.prototype.override = function override(...items) {
    return useThat.call(this, items, 'defaults'); // _.default(this, previousError)
};

CustomError.prototype.use = function use(...items) {
    return useThat.call(this, items, 'extend'); // _.extend(this, previousError)
};

CustomError.prototype.toObject = function toObject(opts) {
    if (opts == void 0)
        opts = {};
    if (_.isFunction(opts))
        return opts.call(this);
    var obj = {
        error: {
            message: this.message,
            level: this.level,
            stack: this.stack,
            codeString: this.codeString,
            code: this.code,
            info: this.info,
            isCustomError: true
        }
    };
    if (_.isArray(opts.omit) || _.isString(opts.omit))
        obj.error = _.omit(obj.error, opts.omit);
    else if (_.isArray(opts.pick) || _.isString(opts.pick))
        obj.error = _.pick(obj.error, opts.pick);
    return obj;
};

CustomError.prototype.toJSON = CustomError.prototype.toObject;

module.exports = CustomError;


text:
These TJBot Node-RED flows are an easy way to get started with bringing TJBot to Life.
Node-RED is a great way to teach developers about programming without dropping them down into Node.js code.

These TJBot Node-RED recipes showcase:
* Twitter Tone Analysis (blinks the LED colors and waves his arm on joyful tweets)
* Speech to Text to control the LED color and waves his arm
* Weather report
* TJBot LED Party is a simple flow that randomly generates colors / blinks the TJBot NeoPixel
* Watson Visual Recognition Image Classification and Text Extraction using a Pi Camera

There are screenshots posted so you can see the Node-RED flows in the Pictures directory.

If you're interested in trying these recipes on your TJBot / Raspberry Pi, find them here:
https://github.com/johnwalicki/TJBot-Node-RED/flows

## Node-RED flows in this repository:
This flow listens to a Twitter feed, calls Tone Analyzer, speaks the Tweets, blinks the NeoPixel different colors based on tone scores, and waves TJBots arm on joyful tweets.
![TJBot Twitter Tone Analysis flow](/pictures/TJBotTweetToneAnalysisBlinkLEDWave.png?raw=true "TJBot Twitter Analyzer flow")
___
This flow records speech from a Raspberry Pi microphone. Ask TJBot the *weather*, say a *color* to set the LED, get down to *Party*, or ask TJBot to *wave* his arm.
![TJBot Speech to Text Control the LED color and Wave flow](/pictures/TJBotSetColorWaveviaSpeechCommand.png?raw=true "TJBot Speech to Text flow")
___
This flow announces the current Weather Conditions using Text to Speech.
![TJBot Announce the Weather conditions using Text to Speech flow](/pictures/TJBotWeatherForecastTTSAnnouncements.png?raw=true "TJBot Speech to Text flow")
___
TJBot loves to party so I created a simple flow that randomly generates colors and blinks the TJBot NeoPixel.
![TJBot LED Party flow](/pictures/TJBotLEDParty.png?raw=true "TJBot LED Party flow")
___
I've taught TJBot to read and identify images by using Watson Visual Recognition and Text Extraction.
![TJBot Visual Recognition Image Classification Text Extraction flow](/pictures/TJBot-CameraFlow.png?raw=true "TJBot Watson Vision flow")
A browser screenshot of the "TJBot Cam" Node-RED Dashboard that shows Image Classification.
![TJBot Visual Recognition Image Classification Node-RED Dashboard](/pictures/TJBot-CameraResults-racecar.png?raw=true "TJBot Node-RED Dashboard Racecar")
A browser screenshot of the "TJBot Cam" Node-RED Dashboard that shows Text Extraction.
![TJBot Visual Recognition Image Classification Node-RED Dashboard](/pictures/TJBot-CameraResults-Party.png?raw=true "TJBot Node-RED Dashboard Party Text Extraction")

## Node-RED Dependencies and Install Instructions
These flows use a variety of Node-RED nodes that you might need to install on your Raspberry Pi.
* node-red-node-watson
* node-red-dashboard
* node-red-contrib-camerapi
* node-red-contrib-micropi
* node-red-contrib-speakerpi
* node-red-node-base64
* node-red-contrib-play-audio
* node-red-node-pi-neopixel
* node-red-node-weather-underground

Here are install and configuration instructions that will set up all of the node-red nodes onto your Raspberry Pi.  Remember to restart the Node-RED service or reboot the Raspberry Pi after the installs complete.  The --unsafe-perm is required for the successful installation of node-red-contrib-speakerpi. The libasound2-dev dependency is required for the compile of node-red-contrib-speakerpi which needs a header file alsa/asoundlib.h provided by libasound2-dev

```
$ sudo apt-get install libasound2-dev
$ sudo chmod 777 /usr/lib/node_modules
$ mkdir /home/pi/audio
```
If you have not configured ALSA and the MicroPi / SpeakerPi nodes on your Raspberry Pi, you might need to remove the following parameter from /boot/config.txt
```
# Enable audio (loads snd_bcm2835)
# dtparam=audio=on
```
You might also want to make certain that you are not blacklisting too many modules in /etc/modprobe.d/*.conf

Finally, run this npm command:
```
$ sudo npm --unsafe-perm -g install node-red-node-watson node-red-dashboard node-red-contrib-camerapi node-red-node-base64 node-red-contrib-play-audio node-red-contrib-micropi node-red-node-pi-neopixel node-red-node-weather-underground node-red-contrib-speakerpi
```


text:
<?php

final class HeraldActionConfig {

  const ACTION_ADD_CC       = 'addcc';
  const ACTION_REMOVE_CC    = 'remcc';
  const ACTION_EMAIL        = 'email';
  const ACTION_NOTHING      = 'nothing';
  const ACTION_AUDIT        = 'audit';
  const ACTION_FLAG         = 'flag';

  public static function getActionMessageMapForRuleType($rule_type) {
    $generic_mappings = array(
      self::ACTION_NOTHING      => 'Do nothing',
      self::ACTION_ADD_CC       => 'Add emails to CC',
      self::ACTION_REMOVE_CC    => 'Remove emails from CC',
      self::ACTION_EMAIL        => 'Send an email to',
      self::ACTION_AUDIT        => 'Trigger an Audit',
      self::ACTION_FLAG         => 'Mark with flag',
    );

    switch ($rule_type) {
      case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
        $specific_mappings = array(
          self::ACTION_AUDIT        => 'Trigger an Audit for project',
        );
        break;
      case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
        $specific_mappings = array(
          self::ACTION_ADD_CC       => 'CC me',
          self::ACTION_REMOVE_CC    => 'Remove me from CC',
          self::ACTION_EMAIL        => 'Email me',
          self::ACTION_AUDIT        => 'Trigger an Audit by me',
        );
        break;
      case null:
        $specific_mappings = array();
        // Use generic mappings, used on transcript.
        break;
      default:
        throw new Exception("Unknown rule type '${rule_type}'");
    }
    return $specific_mappings + $generic_mappings;
  }

  public static function getActionMessageMap($content_type,
                                             $rule_type) {
    $map = self::getActionMessageMapForRuleType($rule_type);
    switch ($content_type) {
      case HeraldContentTypeConfig::CONTENT_TYPE_DIFFERENTIAL:
        return array_select_keys(
          $map,
          array(
            self::ACTION_ADD_CC,
            self::ACTION_REMOVE_CC,
            self::ACTION_EMAIL,
            self::ACTION_FLAG,
            self::ACTION_NOTHING,
          ));
      case HeraldContentTypeConfig::CONTENT_TYPE_COMMIT:
        return array_select_keys(
          $map,
          array(
            self::ACTION_EMAIL,
            self::ACTION_AUDIT,
            self::ACTION_FLAG,
            self::ACTION_NOTHING,
          ));
      case HeraldContentTypeConfig::CONTENT_TYPE_MERGE:
        return array_select_keys(
          $map,
          array(
            self::ACTION_EMAIL,
            self::ACTION_NOTHING,
          ));
      case HeraldContentTypeConfig::CONTENT_TYPE_OWNERS:
        return array_select_keys(
          $map,
          array(
            self::ACTION_EMAIL,
            self::ACTION_NOTHING,
          ));
      default:
        throw new Exception("Unknown content type '{$content_type}'.");
    }
  }

  /**
   * Create a HeraldAction to save from data.
   *
   * $data is of the form:
   *   array(
   *     0 => <action type>
   *     1 => array(<targets>)
   *   )
   */
  public static function willSaveAction($rule_type,
                                        $author_phid,
                                        $data) {
    $obj = new HeraldAction();
    $obj->setAction($data[0]);

    // for personal rule types, set the target to be the owner of the rule
    if ($rule_type == HeraldRuleTypeConfig::RULE_TYPE_PERSONAL) {
      switch ($obj->getAction()) {
        case HeraldActionConfig::ACTION_EMAIL:
        case HeraldActionConfig::ACTION_ADD_CC:
        case HeraldActionConfig::ACTION_REMOVE_CC:
        case HeraldActionConfig::ACTION_AUDIT:
          $data[1] = array($author_phid => $author_phid);
          break;
        case HeraldActionConfig::ACTION_FLAG:
          // Make sure flag color is valid; set to blue if not.
          $color_map = PhabricatorFlagColor::getColorNameMap();
          if (empty($color_map[$data[1]])) {
            $data[1] = PhabricatorFlagColor::COLOR_BLUE;
          }
          break;
        case HeraldActionConfig::ACTION_NOTHING:
          break;
        default:
          throw new Exception('Unrecognized action type: ' .
                              $obj->getAction());
      }
    }

    if (is_array($data[1])) {
      $obj->setTarget(array_keys($data[1]));
    } else {
      $obj->setTarget($data[1]);
    }

    return $obj;
  }

}


text:
/*----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 *---------------------------------------------------------------------------*/

/** @defgroup los_mux Mutex
 * @ingroup kernel
 */

#ifndef _LOS_MUX_H
#define _LOS_MUX_H

#include "los_base.h"
#include "los_sys.h"
#include "los_list.h"
#include "los_task.h"

#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif /* __cplusplus */
#endif /* __cplusplus */

/**
 * @ingroup los_mux
 * Mutex error code: The memory request fails.
 *
 * Value: 0x02001d00
 *
 * Solution: Decrease the number of mutexes defined by LOSCFG_BASE_IPC_MUX_LIMIT.
 */
#define LOS_ERRNO_MUX_NO_MEMORY         LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x00)

/**
 * @ingroup los_mux
 * Mutex error code: The mutex is not usable.
 *
 * Value: 0x02001d01
 *
 * Solution: Check whether the mutex ID and the mutex state are applicable for the current operation.
 */
#define LOS_ERRNO_MUX_INVALID            LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x01)

/**
* @ingroup los_mux
* Mutex error code: Null pointer.
*
* Value: 0x02001d02
*
* Solution: Check whether the input parameter is usable.
*/
#define LOS_ERRNO_MUX_PTR_NULL           LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x02)

/**
* @ingroup los_mux
* Mutex error code: No mutex is available and the mutex request fails.
*
* Value: 0x02001d03
*
* Solution: Increase the number of mutexes defined by LOSCFG_BASE_IPC_MUX_LIMIT.
*/
#define LOS_ERRNO_MUX_ALL_BUSY           LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x03)

/**
* @ingroup los_mux
* Mutex error code: The mutex fails to be locked in non-blocking mode because it is locked by another thread.
*
* Value: 0x02001d04
*
* Solution: Lock the mutex after it is unlocked by the thread that owns it, or set a waiting time.
*/
#define LOS_ERRNO_MUX_UNAVAILABLE       LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x04)

/**
* @ingroup los_mux
* Mutex error code: The mutex is being locked during an interrupt.
*
* Value: 0x02001d05
*
* Solution: Check whether the mutex is being locked during an interrupt.
*/
#define LOS_ERRNO_MUX_PEND_INTERR       LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x05)

/**
* @ingroup los_mux
* Mutex error code: A thread locks a mutex after waiting for the mutex to be unlocked by another thread when the task scheduling is disabled.
*
* Value: 0x02001d06
*
* Solution: Check whether the task scheduling is disabled, or set uwtimeout to 0, which means that the thread will not wait for the mutex to become available.
*/
#define LOS_ERRNO_MUX_PEND_IN_LOCK      LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x06)

/**
* @ingroup los_mux
* Mutex error code: The mutex locking times out.
*
* Value: 0x02001d07
*
* Solution: Increase the waiting time or set the waiting time to LOS_WAIT_FOREVER (forever-blocking mode).
*/
#define LOS_ERRNO_MUX_TIMEOUT           LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x07)

/**
 * @ingroup los_mux
 *
 * Value: 0x02001d08
 * Not in use temporarily.
 */
#define LOS_ERRNO_MUX_OVERFLOW          LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x08)

/**
* @ingroup los_mux
* Mutex error code: The mutex to be deleted is being locked.
*
* Value: 0x02001d09
*
* Solution: Delete the mutex after it is unlocked.
*/
#define LOS_ERRNO_MUX_PENDED            LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x09)

/**
 * @ingroup los_mux
 *
 * Value: 0x02001d0A
 * Not in use temporarily.
 */
#define LOS_ERRNO_MUX_GET_COUNT_ERR     LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x0A)

/**
 * @ingroup los_mux
 *
 * Value: 0x02001d0B
 * Not in use temporarily.
 */
#define LOS_ERRNO_MUX_REG_ERROR         LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x0B)

/**
 *@ingroup los_mux
 *@brief Create a mutex.
 *
 *@par Description:
 *This API is used to create a mutex. If there are available mutexes, the mutex is successfully created with a handle to the mutex returned.
 *@attention
 *

 *
The total number of mutexes is pre-configured. If there are no available mutexes, the mutex creation fails.

 *

 *
 *@param puwMuxHandle   [OUT] ID of the handle to the successfully created mutex.
 *
 *@retval #LOS_ERRNO_MUX_PTR_NULL           0x02001d02: The puwMuxHandle pointer is NULL.
 *@retval #LOS_ERRNO_MUX_ALL_BUSY           0x02001d03: The mutex fails to be created because all mutexes in the OS are being in use.
 *@retval #LOS_OK                          0x00000000: The mutex is successfully created.
 *@par Dependency:
 *

los_mux.h: the header file that contains the API declaration.

 *@see LOS_MuxDelete
 *@since Huawei LiteOS V100R001C00
 */
extern UINT32 LOS_MuxCreate(UINT32 *puwMuxHandle);

/**
 *@ingroup los_mux
 *@brief Delete a mutex.
 *
 *@par Description:
 *This API is used to delete a specified mutex and add it to the list of available mutexes.
 *@attention
 *

 *
The mutex that is not owned or waited on by any thread is able to be successfully deleted.

 *

 *
 *@param puwMuxHandle   [IN] ID of the handle to the mutex to be deleted.
 *
 *@retval #LOS_ERRNO_MUX_INVALID            0x02001d01: The mutex fails to be deleted because it is not usable or it is being in use.
 *@retval #LOS_ERRNO_MUX_PENDED             0x02001d09: The mutex fails to be deleted because it is locked.
 *@retval #LOS_OK                          0x00000000: The mutex is successfully deleted.
 *@par Dependency:
 *

los_mux.h: the header file that contains the API declaration.

 *@see LOS_MuxDelete
 *@since Huawei LiteOS V100R001C00
 */
extern UINT32 LOS_MuxDelete(UINT32 puwMuxHandle);

/**
 *@ingroup los_mux
 *@brief Wait to lock a mutex.
 *
 *@par Description:
 *This API is used to wait for a specified period of time to lock a mutex.
 *@attention
 *

 *
The function fails if the mutex that is waited on is already locked by another thread when the task scheduling is disabled.

 *
Do not wait on a mutex during an interrupt.

 *
The priority inheritance protocol is supported. If a higher-priority thread is waiting on a mutex, it changes the priority of the thread that owns the mutex to avoid priority inversion.

 *
A recursive mutex can be locked more than once by the same thread.

 *

 *
 *@param uwMuxHandle    [IN] ID of the handle to the mutex to be waited on.
 *@param uwTimeout      [IN] Waiting time. The value range is [0,LOS_WAIT_FOREVER].
 *
 *@retval #LOS_ERRNO_MUX_INVALID            0x02001d01: The mutex state (for example, the mutex does not exist or is not in use) is not applicable for the current operation.
 *@retval #LOS_ERRNO_MUX_UNAVAILABLE        0x02001d04: The mutex fails to be locked because it is locked by another thread and a period of time is not set for waiting for the mutex to become available.
 *@retval #LOS_ERRNO_MUX_PEND_INTERR        0x02001d05: The mutex is being locked during an interrupt.
 *@retval #LOS_ERRNO_MUX_PEND_IN_LOCK       0x02001d06: The mutex is waited on when the task scheduling is disabled.
 *@retval #LOS_ERRNO_MUX_TIMEOUT            0x02001d07: The mutex waiting times out.
 *@retval #LOS_OK                          0x00000000: The mutex is successfully locked.
 *@par Dependency:
 *

los_mux.h: the header file that contains the API declaration.

 *@see LOS_MuxPost
 *@since Huawei LiteOS V100R001C00
 */
extern UINT32 LOS_MuxPend(UINT32 uwMuxHandle, UINT32 uwTimeout);

/**
 *@ingroup los_mux
 *@brief Release a mutex.
 *
 *@par Description:
 *This API is used to release a specified mutex.
 *@attention
 *

 *
Do not release a mutex during an interrupt.

 *
If a recursive mutex is locked for many times, it must be unlocked for the same times to be released.

 *

 *
 *@param uwMuxHandle    [IN] ID of the handle to the mutex to be released.
 *
 *@retval #LOS_ERRNO_MUX_INVALID            0x02001d01: The mutex state (for example, the mutex does not exist or is not in use) is not applicable for the current operation.
 *@retval #LOS_ERRNO_MUX_PEND_INTERR        0x02001d05: The mutex is being released during an interrupt.
 *@retval #LOS_ERRNO_MUX_INVALID            0x02001d01: The mutex state (for example, the mutex to be released is owned by another thread) is not applicable for the current operation.
 *@retval #LOS_OK                          0x00000000: The mutex is successfully released.
 *@par Dependency:
 *

los_mux.h: the header file that contains the API declaration.

 *@see LOS_MuxPend
 *@since Huawei LiteOS V100R001C00
 */
extern UINT32 LOS_MuxPost(UINT32 uwMuxHandle);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */

#endif /* _LOS_MUX_H */


text:
package codesample.springboot.security;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByUsername(String username);
}


text:
<?php

namespace Mautic\PointBundle\Model;

use Mautic\CoreBundle\Helper\DateTimeHelper;
use Mautic\CoreBundle\Helper\IpLookupHelper;
use Mautic\CoreBundle\Model\FormModel as CommonFormModel;
use Mautic\LeadBundle\Entity\Lead;
use Mautic\LeadBundle\Model\LeadModel;
use Mautic\PointBundle\Entity\LeadTriggerLog;
use Mautic\PointBundle\Entity\Trigger;
use Mautic\PointBundle\Entity\TriggerEvent;
use Mautic\PointBundle\Event as Events;
use Mautic\PointBundle\PointEvents;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

/**
 * Class TriggerModel
 */
class TriggerModel extends CommonFormModel
{
    /**
     * @deprecated Remove in 2.0
     *
     * @var MauticFactory
     */
    protected $factory;

    /**
     * @var IpLookupHelper
     */
    protected $ipLookupHelper;

    /**
     * @var LeadModel
     */
    protected $leadModel;

    /**
     * @var TriggerEventModel
     */
    protected $pointTriggerEventModel;

    /**
     * EventModel constructor.
     *
     * @param IpLookupHelper $ipLookupHelper
     * @param LeadModel $leadModel
     * @param TriggerEventModel $pointTriggerEventModel
     */
    public function __construct(IpLookupHelper $ipLookupHelper, LeadModel $leadModel, TriggerEventModel $pointTriggerEventModel)
    {
        $this->ipLookupHelper = $ipLookupHelper;
        $this->leadModel = $leadModel;
        $this->pointTriggerEventModel = $pointTriggerEventModel;
    }

    /**
     * {@inheritdoc}
     *
     * @return \Mautic\PointBundle\Entity\TriggerRepository
     */
    public function getRepository()
    {
        return $this->em->getRepository('MauticPointBundle:Trigger');
    }

    /**
     * Retrieves an instance of the TriggerEventRepository
     *
     * @return \Mautic\PointBundle\Entity\TriggerEventRepository
     */
    public function getEventRepository()
    {
        return $this->em->getRepository('MauticPointBundle:TriggerEvent');
    }

    /**
     * {@inheritdoc}
     */
    public function getPermissionBase()
    {
        return 'point:triggers';
    }

    /**
     * {@inheritdoc}
     *
     * @throws MethodNotAllowedHttpException
     */
    public function createForm($entity, $formFactory, $action = null, $options = array())
    {
        if (!$entity instanceof Trigger) {
            throw new MethodNotAllowedHttpException(array('Trigger'));
        }
        $params = (!empty($action)) ? array('action' => $action) : array();
        return $formFactory->create('pointtrigger', $entity, $params);
    }

    /**
     * {@inheritdoc}
     *
     * @param  \Mautic\PointBundle\Entity\Trigger $entity
     * @param  bool                               $unlock
     */
    public function saveEntity($entity, $unlock = true)
    {
        $isNew = ($entity->getId()) ? false : true;

        parent::saveEntity($entity, $unlock);

        //should we trigger for existing leads?
        if ($entity->getTriggerExistingLeads() && $entity->isPublished()) {
            $events    = $entity->getEvents();
            $repo      = $this->getEventRepository();
            $persist   = array();
            $ipAddress = $this->ipLookupHelper->getIpAddress();

            foreach ($events as $event) {
                $filter = array('force' => array(
                    array(
                        'column' => 'l.date_added',
                        'expr'   => 'lte',
                        'value'  => (new DateTimeHelper($entity->getDateAdded()))->toUtcString()
                    ),
                    array(
                        'column' => 'l.points',
                        'expr'   => 'gte',
                        'value'  => $entity->getPoints()
                    )
                ));

                if (!$isNew) {
                    //get a list of leads that has already had this event applied
                    $leadIds = $repo->getLeadsForEvent($event->getId());
                    if (!empty($leadIds)) {
                        $filter['force'][] = array(
                            'column' => 'l.id',
                            'expr'   => 'notIn',
                            'value'  => $leadIds
                        );
                    }
                }

                //get a list of leads that are before the trigger's date_added and trigger if not already done so
                $leads     = $this->leadModel->getEntities(array(
                    'filter' => $filter
                ));

                foreach ($leads as $l) {
                    if ($this->triggerEvent($event->convertToArray(), $l, true)) {
                        $log = new LeadTriggerLog();
                        $log->setIpAddress($ipAddress);
                        $log->setEvent($event);
                        $log->setLead($l);
                        $log->setDateFired(new \DateTime());
                        $event->addLog($log);
                        $persist[] = $event;
                    }
                }
            }

            if (!empty($persist)) {
                $repo->saveEntities($persist);
            }
        }
    }

    /**
     * {@inheritdoc}
     *
     * @return Trigger|null
     */
    public function getEntity($id = null)
    {
        if ($id === null) {
            return new Trigger();
        }

        return parent::getEntity($id);
    }

    /**
     * {@inheritdoc}
     *
     * @throws MethodNotAllowedHttpException
     */
    protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null)
    {
        if (!$entity instanceof Trigger) {
            throw new MethodNotAllowedHttpException(array('Trigger'));
        }

        switch ($action) {
            case "pre_save":
                $name = PointEvents::TRIGGER_PRE_SAVE;
                break;
            case "post_save":
                $name = PointEvents::TRIGGER_POST_SAVE;
                break;
            case "pre_delete":
                $name = PointEvents::TRIGGER_PRE_DELETE;
                break;
            case "post_delete":
                $name = PointEvents::TRIGGER_POST_DELETE;
                break;
            default:
                return null;
        }

        if ($this->dispatcher->hasListeners($name)) {
            if (empty($event)) {
                $event = new Events\TriggerEvent($entity, $isNew);
            }

            $this->dispatcher->dispatch($name, $event);
            return $event;
        }

        return null;
    }

    /**
     * @param Trigger $entity
     * @param array   $sessionEvents
     *
     * @return void
     */
    public function setEvents(Trigger $entity, $sessionEvents)
    {
        $order   = 1;
        $existingActions = $entity->getEvents();

        foreach ($sessionEvents as $properties) {
            $isNew = (!empty($properties['id']) && isset($existingActions[$properties['id']])) ? false : true;
            $event = !$isNew ? $existingActions[$properties['id']] : new TriggerEvent();

            foreach ($properties as $f => $v) {
                if (in_array($f, array('id', 'order')))
                    continue;

                $func = "set" .  ucfirst($f);
                if (method_exists($event, $func)) {
                    $event->$func($v);
                }
            }
            $event->setTrigger($entity);
            $event->setOrder($order);
            $order++;
            $entity->addTriggerEvent($properties['id'], $event);
        }

        // Persist if editing the trigger
        if ($entity->getId()) {
            $this->pointTriggerEventModel->saveEntities($entity->getEvents());
        }
    }

    /**
     * Gets array of custom events from bundles subscribed PointEvents::TRIGGER_ON_BUILD
     *
     * @return mixed
     */
    public function getEvents()
    {
        static $events;

        if (empty($events)) {
            //build them
            $events = array();
            $event  = new Events\TriggerBuilderEvent($this->translator);
            $this->dispatcher->dispatch(PointEvents::TRIGGER_ON_BUILD, $event);
            $events = $event->getEvents();
        }
        return $events;
    }

    /**
     * Gets array of custom events from bundles inside groups
     *
     * @return mixed
     */
    public function getEventGroups()
    {
        $events = $this->getEvents();
        $groups = array();
        foreach ($events as $key => $event) {
            $groups[$event['group']][$key] = $event;
        }
        return $groups;
    }

    /**
     * Triggers a specific event
     *
     * @param array   $event
     * @param Lead    $lead
     * @param bool    $force
     *
     * @return bool Was event triggered
     */
    public function triggerEvent($event, Lead $lead = null,  $force = false)
    {
        //only trigger events for anonymous users
        if (!$force && !$this->security->isAnonymous()) {
            return false;
        }

        if ($lead == null) {
            $lead      = $this->leadModel->getCurrentLead();
        }

        if (!$force) {
            //get a list of events that has already been performed on this lead
            $appliedEvents = $this->getEventRepository()->getLeadTriggeredEvents($lead->getId());

            //if it's already been done, then skip it
            if (isset($appliedEvents[$event['id']])) {
                return false;
            }
        }

        $availableEvents = $this->getEvents();
        $eventType       = $event['type'];

        //make sure the event still exists
        if (!isset($availableEvents[$eventType])) {
            return false;
        }

        $settings = $availableEvents[$eventType];
        $args     = array(
            'event'    => $event,
            'lead'     => $lead,
            'factory'  => $this->factory, // WHAT??
            'config'   => $event['properties']
        );

        if (is_callable($settings['callback'])) {
            if (is_array($settings['callback'])) {
                $reflection = new \ReflectionMethod($settings['callback'][0], $settings['callback'][1]);
            } elseif (strpos($settings['callback'], '::') !== false) {
                $parts      = explode('::', $settings['callback']);
                $reflection = new \ReflectionMethod($parts[0], $parts[1]);
            } else {
                $reflection = new \ReflectionMethod(null, $settings['callback']);
            }

            $pass = array();
            foreach ($reflection->getParameters() as $param) {
                if (isset($args[$param->getName()])) {
                    $pass[] = $args[$param->getName()];
                } else {
                    $pass[] = null;
                }
            }

            return $reflection->invokeArgs($this, $pass);
        }

        return false;
    }

    /**
     * Trigger events for the current lead
     *
     * @param Lead $lead
     */
    public function triggerEvents(Lead $lead)
    {
        $points = $lead->getPoints();

        //find all published triggers that is applicable to this points
        /** @var \Mautic\PointBundle\Entity\TriggerEventRepository $repo */
        $repo   = $this->getEventRepository();
        $events = $repo->getPublishedByPointTotal($points);

        if (!empty($events)) {
            //get a list of actions that has already been applied to this lead
            $appliedEvents = $repo->getLeadTriggeredEvents($lead->getId());
            $ipAddress     = $this->ipLookupHelper->getIpAddress();
            $persist       = array();
            foreach ($events as $event) {
                if (isset($appliedEvents[$event['id']])) {
                    //don't apply the event to the lead if it's already been done
                    continue;
                }

                if ($this->triggerEvent($event, $lead, true)) {
                    $log = new LeadTriggerLog();
                    $log->setIpAddress($ipAddress);
                    $log->setEvent($this->em->getReference('MauticPointBundle:TriggerEvent', $event['id']));
                    $log->setLead($lead);
                    $log->setDateFired(new \DateTime());
                    $persist[] = $log;
                }
            }

            if (!empty($persist)) {
                $this->getEventRepository()->saveEntities($persist);

                $this->em->clear('Mautic\PointBundle\Entity\LeadTriggerLog');
                $this->em->clear('Mautic\PointBundle\Entity\TriggerEvent');
            }
        }
    }

    /**
     * Returns configured color based on passed in $points
     *
     * @param $points
     *
     * @return string
     */
    public function getColorForLeadPoints($points)
    {
        static $triggers;

        if (!is_array($triggers)) {
            $triggers = $this->getRepository()->getTriggerColors();
        }

        foreach ($triggers as $trigger) {
            if ($points >= $trigger['points']) {
                return $trigger['color'];
            }
        }

        return '';
    }
}


text:
/**
 * Template class
 *
 * Set up templating base. Uses underscore.js for templating.
 */

var TemplateClass = Base.extend({

    constructor: function() {},

    init: function() {
        App.Log.debug( 'Templating library loaded', 'sys' );
    },

    // fetch the template from the user templates file. optionally, data
    // can be passed in to render with but is not necessary.
    //
    render: function( template /*, data */ ) {
        var data = ( arguments.length > 1 )
            ? arguments[ 1 ]
            : {},
            compiled = _.template( template );

        return compiled( data );
    }

});

// End of file


text:
using System.Runtime.InteropServices;
using System;

internal class NullableTest
{
    private static bool BoxUnboxToNQ<T>(T o)
    {
        return Helper.Compare((WithMultipleGCHandleStruct)(object)o, Helper.Create(default(WithMultipleGCHandleStruct)));
    }

    private static bool BoxUnboxToQ<T>(T o)
    {
        return Helper.Compare((WithMultipleGCHandleStruct?)(object)o, Helper.Create(default(WithMultipleGCHandleStruct)));
    }

    private static int Main()
    {
        WithMultipleGCHandleStruct? s = Helper.Create(default(WithMultipleGCHandleStruct));

        if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
            return ExitCode.Passed;
        else
            return ExitCode.Failed;
    }
}


text:
import {Component, Input, OnInit, ViewChild} from "@angular/core";
import 'highcharts/adapters/standalone-framework.src';
import {Chart} from "./models/Chart";

const Highcharts = require('highcharts/highcharts.src');

@Component({
	selector : 'chart',
	template : require('./chart-component.html')
})
export class ChartComponent {
	chart : any;

	@ViewChild('chartPlaceholder') chartPlaceholder;

	@Input()
	set data(data : Chart) {

		if (data) {
			let config = {
				chart: {height: data.height},
//				colors: data.colors,
				title: {text: data.title},
				xAxis: {type: 'category', categories: data.categories},
				yAxis: data.yAxis,
				series: data.series,
				legend: data.legend
			};

			this.chart = Highcharts.chart(this.chartPlaceholder.nativeElement, config);

			let vm = this;
			setTimeout(() => vm.chart.reflow(), 1);
		}
	}
}


text: import noisyor


text:
const should = require('should'),
    sinon = require('sinon'),
    rewire = require('rewire'),
    registry = rewire('../../../../server/services/routing/registry'),
    sandbox = sinon.sandbox.create();

describe('UNIT: services/routing/registry', function () {
    let getRssUrlStub;

    beforeEach(function () {
        getRssUrlStub = sandbox.stub();
    });

    afterEach(function () {
        sandbox.restore();
    });

    describe('fn: getRssUrl', function () {
        it('no url available', function () {
            should.not.exist(registry.getRssUrl());
        });

        it('single collection, no index collection', function () {
            registry.setRouter('CollectionRouter', {
                name: 'CollectionRouter',
                routerName: 'podcast',
                getRssUrl: sandbox.stub().returns('/podcast/rss/')
            });

            registry.getRssUrl().should.eql('/podcast/rss/');
        });

        it('single collection, no index collection, rss disabled', function () {
            registry.setRouter('CollectionRouter', {
                name: 'CollectionRouter',
                routerName: 'podcast',
                getRssUrl: sandbox.stub().returns(null)
            });

            should.not.exist(registry.getRssUrl());
        });

        it('index collection', function () {
            registry.setRouter('CollectionRouter', {
                name: 'CollectionRouter',
                routerName: 'podcast',
                getRssUrl: sandbox.stub().returns('/podcast/rss/')
            });

            registry.setRouter('CollectionRouter', {
                name: 'CollectionRouter',
                routerName: 'index',
                getRssUrl: sandbox.stub().returns('/rss/')
            });

            registry.getRssUrl().should.eql('/rss/');
        });
    });
});


text:
/*
 * Created on 29.09.2004
 *
 */
package net.strongdesign.stg.traversal;

import java.util.*;
import net.strongdesign.stg.*;
import net.strongdesign.util.*;
/**
 * @author mark and dominic
 *
 */
public abstract class GraphOperations {

	public static SortedSet<List<Node>> findSimplePaths(
			Node startNode,
			Node endNode,
			Condition<Node> abortPath) {

		SortedSet<List<Node>> resultingPaths =
			new TreeSet<List<Node>>(new CollectionSizeComparator()); // return value
		List<Node> visitedNodes = new ArrayList<Node>();

		visitedNodes.add(startNode);
		if (startNode == endNode) {
			resultingPaths.add(visitedNodes);
		}
		else {
			for (Node childOfStart : startNode.getChildren())
				if (!visitedNodes.contains(childOfStart))
					dfsSimplePath(childOfStart, endNode, abortPath, visitedNodes, resultingPaths);
		}

		return resultingPaths;
	}

	private static void dfsSimplePath(
			Node node,
			Node endNode,
			Condition<Node> abortPath,
			List<Node> visitedNodes,
			Set<List<Node>> results) {

		visitedNodes.add(node);

		if (node == endNode) {
			// add a shallow copy of visitedNodes to 'results' as a resulting simple path
			results.add(new ArrayList<Node>(visitedNodes)); // take a copy, visitedNodes cannot be null
			visitedNodes.remove(node); // removes last element
			return;
		}

		if (abortPath.fulfilled(node)) { // startNode will never be checked!
			visitedNodes.remove(node); // remove last element
			return;
		}

		for (Node child : node.getChildren())
			if (!visitedNodes.contains(child))
				dfsSimplePath(child, endNode, abortPath, visitedNodes, results);

		visitedNodes.remove(node); // removes last element
	}

	public static Pair<Integer, List<Node>> findShortestPath (
			Node startNode,
			Node endNode,
			Condition<Node> abortPath,
			Collector<Place, Integer> placeCost,
			Collector<Transition, Integer> transitionCost,
			Collector<Pair<Node,Node>, Integer> arcCost) {

		TreeSet<Pair<Integer,List<Node>>> currentPaths = new TreeSet<Pair<Integer,List<Node>>>();

		List<Node> startList = new LinkedList<Node>();
		startList.add(startNode);
		currentPaths.add(new Pair<Integer,List<Node>>(new Integer(0), startList  ));

		while (currentPaths.size() > 0) {
			Pair<Integer,List<Node>> actPath = currentPaths.first();
			currentPaths.remove(actPath);
			Integer cost = actPath.a;
			List<Node> path = actPath.b;

			Node lastNode = path.get(path.size()-1);
			if (lastNode == endNode ) return actPath;

			if (abortPath.fulfilled(lastNode)) continue;

			for (Node newNode : lastNode.getChildren()) {
				List<Node> newPath = new LinkedList<Node>(path);
				if (newPath.contains(newNode)) continue;
				newPath.add(newNode);
				Integer nodeCost=null, newCost;
				Integer newarcCost = arcCost.operation(new Pair<Node,Node>(lastNode, newNode));

				if (newNode instanceof Place)
					nodeCost =  placeCost.operation((Place)newNode);
				if (newNode instanceof Transition)
					nodeCost =  transitionCost.operation((Transition)newNode);

				newCost = new Integer(cost.intValue()+nodeCost.intValue()+newarcCost.intValue());
				currentPaths.add(new Pair<Integer,List<Node>>(newCost, newPath));
			}
		}

		return null;
	}

	public static List<Vector<Node>> getCyclesWith(Set<Node> nodes) {
		List<Vector<Node>> result = new LinkedList<Vector<Node>>();
		if (nodes.isEmpty())
			return result;

		Node finalNode = nodes.iterator().next();
		nodes.remove(finalNode);
		Stack<Node> path = new Stack<Node>();
		path.add(finalNode);

		getCyclesWith(path, nodes, result);

		nodes.add(finalNode);
		return result;
	}

	private static void getCyclesWith(Stack<Node> path, Set<Node> targets, List<Vector<Node>> cycles) {
		//PRECONDITION: path contains a regular path (witout loops)

		//follow each possible child
		for (Node child : path.peek().getChildren()) {
			//found an undesired cycle?
			//NO!
			if (! path.contains(child)) {
				//the start node is at first position of path, therefore in the best case a node of targtes was found

				//target found!, remove it and call with new target set
				if (targets.contains(child)) {
					targets.remove(child);
					path.push(child);
					getCyclesWith(path, targets, cycles);
					path.pop();
					targets.add(child);
				}
				//no target found, this is the standard case
				else {
					path.push(child);
					getCyclesWith(path, targets, cycles);
					path.pop();
				}
			}
			//found a node of the path, is it the start node?
			else if (child == path.get(0)) //yes it is! the cycle was close
				cycles.add( new Vector<Node>(path)  );
		}
	}
}


text:
namespace StickyNotes.Pages
{
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Navigation;

    public partial class InviteUser : BasePage
    {
        public InviteUser()
        {
            InitializeComponent();
            InitializeDataContext();
        }

        private string email;

        public string Email
        {
            get { return email; }
            set { email = value; NotifyPropertyChanged("Email"); }
        }

        private int BoardId;

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string id;
            if (NavigationContext.QueryString.TryGetValue("boardId", out id))
            {
                this.BoardId = int.Parse(id);
            }

            base.OnNavigatedTo(e);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.OnlineRepository.BoardInvite(SettingsManager.SessionToken, this.Email, this.BoardId, (response) =>
            {
                if (response.code != HttpStatusCode.Created)
                {
                    MessageBox.Show("There was an error adding the user to the board. The board may have been deleted, the user may not exist, or the user may already have been added.", "Error", MessageBoxButton.OK);
                }
                else
                {
                    NavigationService.Navigate(new Uri("/Pages/BoardList.xaml", UriKind.Relative));
                }
            });
        }
    }
}


text:
using System.ComponentModel;
using System.Runtime.CompilerServices;
//using TIG.Todo.Common.Annotations;

namespace TIG.Todo.Common
{
    public class Bindable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

		//[NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(
			//[CallerMemberName]
			string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}