text:
/* global assert, process, setup, suite, test */
var entityFactory = require('../helpers').entityFactory;

var SRC = '/base/tests/assets/box/Box.gltf';

suite('gltf-model', function () {
  setup(function (done) {
    var el;
    var asset = document.createElement('a-asset-item');
    asset.setAttribute('id', 'gltf');
    asset.setAttribute('src', SRC);
    el = this.el = entityFactory({assets: [asset]});
    if (el.hasLoaded) { done(); }
    el.addEventListener('loaded', function () { done(); });
  });

  test('can load', function (done) {
    var el = this.el;
    el.addEventListener('model-loaded', function () {
      assert.ok(el.components['gltf-model'].model);
      done();
    });
    el.setAttribute('gltf-model', '#gltf');
  });

  test('can load with url()', function (done) {
    var el = this.el;
    el.addEventListener('model-loaded', function () {
      assert.ok(el.components['gltf-model'].model);
      done();
    });
    el.setAttribute('gltf-model', `url(${SRC})`);
  });

  test('can load multiple models', function (done) {
    var el = this.el;
    var el2 = document.createElement('a-entity');
    var elPromise = new Promise(function (resolve) {
      el.addEventListener('model-loaded', resolve);
    });
    var el2Promise = new Promise(function (resolve) {
      el2.addEventListener('model-loaded', resolve);
    });

    Promise.all([elPromise, el2Promise]).then(function () {
      assert.ok(el.getObject3D('mesh'));
      assert.ok(el2.getObject3D('mesh'));
      assert.notEqual(el.components['gltf-model'].model, el2.components['gltf-model'].model);
      done();
    });

    el2.addEventListener('loaded', function () {
      el.setAttribute('gltf-model', '#gltf');
      el2.setAttribute('gltf-model', '#gltf');
    });
    el.sceneEl.appendChild(el2);
  });
});


text:
"""
Wind-driver entrainment test case.

Based on Kato-Phillips laboratory tests.

Initial water column is stratified with a constant density gradient.
Circulation is driven by constant wind stress at the surface. Wind-induced
mixing begins to destroy stratification, creating a well-mixed surfacelayer.
The depth of the surface layer follows an empirical relation versus time.

Surface friction velocity is u_s = 0.01 m s-1.
Initially buoyancy frequency is constant N = 0.01 s-1.

[1] http://www.gotm.net/
[2] Karna et al. (2012). Coupling of a discontinuous Galerkin finite element
    marine model with a finite difference turbulence closure model.
    Ocean Modelling, 47:55-64.
    http://dx.doi.org/10.1016/j.ocemod.2012.01.001
"""
from thetis import *
import pytest

def run_katophillips(**model_options):
    physical_constants['rho0'] = 1027.0  # NOTE must match empirical setup

    outputdir = 'outputs'
    # set mesh resolution
    dx = 2500.0
    layers = 20
    depth = 50.0

    # generate unit mesh and transform its coords
    nx = 3  # nb elements in flow direction
    lx = nx*dx
    ny = 2  # nb elements in cross direction
    ly = ny*dx
    mesh2d = PeriodicRectangleMesh(nx, ny, lx, ly, direction='x', reorder=True)
    # move mesh, center to (0,0)
    mesh2d.coordinates.dat.data[:, 0] -= lx/2
    mesh2d.coordinates.dat.data[:, 1] -= ly/2

    dt = 60.0
    t_end = 4 * 3600.0
    t_export = 5*60.0
    u_mag = 1.0

    # bathymetry
    p1_2d = get_functionspace(mesh2d, 'CG', 1)
    bathymetry2d = Function(p1_2d, name='Bathymetry')
    bathymetry2d.assign(depth)

    wind_stress_x = 0.1027  # Pa
    wind_stress_2d = Constant((wind_stress_x, 0))

    # create solver
    solver_obj = solver.FlowSolver(mesh2d, bathymetry2d, layers)
    options = solver_obj.options
    options.use_nonlinear_equations = False
    options.solve_salinity = True
    options.solve_temperature = False
    options.constant_temperature = Constant(10.0)
    options.use_implicit_vertical_diffusion = True
    options.use_bottom_friction = False
    options.use_turbulence = True
    options.use_ale_moving_mesh = False
    options.use_baroclinic_formulation = True
    options.use_limiter_for_tracers = False
    options.vertical_viscosity = Constant(1.3e-6)  # background value
    options.vertical_diffusivity = Constant(1.4e-7)  # background value
    options.wind_stress = wind_stress_2d
    options.no_exports = True
    options.simulation_export_time = t_export
    options.timestepper_options.use_automatic_timestep = False
    options.timestep = dt
    options.simulation_end_time = t_end
    options.output_directory = outputdir
    options.horizontal_velocity_scale = Constant(u_mag)
    options.check_salinity_overshoot = True
    options.fields_to_export = ['uv_2d', 'elev_2d', 'elev_3d', 'uv_3d',
                                'w_3d', 'w_mesh_3d', 'salt_3d',
                                'baroc_head_3d', 'uv_dav_2d', 'eddy_visc_3d',
                                'shear_freq_3d', 'buoy_freq_3d',
                                'tke_3d', 'psi_3d', 'eps_3d', 'len_3d', ]
    options.update(model_options)
    if options.timestepper_type in ['LeapFrog', 'SSPRK22']:
        options.use_ale_moving_mesh = True
    if hasattr(options.timestepper_options, 'use_automatic_timestep'):
        options.timestepper_options.use_automatic_timestep = False

    solver_obj.create_function_spaces()

    # initial conditions
    buoyfreq0 = 0.01
    rho_grad = -buoyfreq0**2 * physical_constants['rho0'] / physical_constants['g_grav']
    beta = 0.7865  # haline contraction coefficient [kg m-3 psu-1]
    salt_grad = rho_grad/beta
    salt_init3d = Function(solver_obj.function_spaces.H, name='initial salinity')
    x, y, z = SpatialCoordinate(solver_obj.mesh)
    salt_init_expr = salt_grad*z
    salt_init3d.interpolate(salt_init_expr)

    solver_obj.assign_initial_conditions(salt=salt_init3d)

    solver_obj.iterate()

    # check mixed layer depth
    npoints = layers*4
    tol = 1e-4
    z = np.linspace(-tol, -depth + tol, npoints)
    x = np.zeros_like(z)
    y = np.zeros_like(z)
    xyz = np.vstack((x, y, z)).T
    tke_arr = np.array(solver_obj.fields.tke_3d.at(tuple(xyz)))
    # mixed layer depth: lowest point where tke > tol
    tke_tol = 1e-5
    ix = tke_arr > tke_tol
    if ix.any():
        ml_depth = -z[ix].min()
    else:
        ml_depth = 0.0
    # correct depth
    u_s = 0.01
    buoyfreq0 = 0.01
    target = 1.05*u_s*np.sqrt(solver_obj.simulation_time/buoyfreq0)
    rtol = 0.05
    rel_err = (ml_depth - target)/target
    assert rel_err > -rtol, 'mixed layer is too shallow: {:} < {:}'.format(ml_depth, target)
    assert rel_err < rtol, 'mixed layer is too deep: {:} > {:}'.format(ml_depth, target)
    print_output('Mixed layer depth: {:.2f} (target: {:.2f}) PASSED'.format(ml_depth, target))

@pytest.fixture(params=['rt-dg', 'dg-dg'])
def element_family(request):
    return request.param

@pytest.fixture(params=['LeapFrog', 'SSPRK22'])
def timestepper_type(request):
    return request.param

def test_katophillips(element_family, timestepper_type):
    run_katophillips(element_family=element_family,
                     timestepper_type=timestepper_type)

if __name__ == '__main__':
    run_katophillips(element_family='dg-dg',
                     timestepper_type='SSPRK22',
                     no_exports=False)

redpajama_set_name: RedPajamaGithub


text:
namespace MobileApp.Core.ViewModels.Abstract
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Input;

    using Cirrious.MvvmCross.Plugins.Messenger;
    using Cirrious.MvvmCross.ViewModels;

    using MobileApp.Core.Interfaces;
    using MobileApp.Core.Models.DataContracts;
    using MobileApp.Core.Models.Messages;
    using MobileApp.Core.Services.UtilityService.Logger;

    /// <summary>
    /// Provides abstract table source collection
    /// </summary>
    /// <typeparam name="TViewModel">View model</typeparam>
    /// <typeparam name="TModel"> model</typeparam>
    public abstract class BaseListViewModel<TViewModel, TModel> : AccountAccessViewModel
        where TModel : IModel<TViewModel> where TViewModel : BaseListItemViewModel<TModel>, ISelectable
    {
        #region Fields

        protected MvxSubscriptionToken ContactToken;

        protected MvxSubscriptionToken SelectionToken;

        private readonly MvxCommand<TViewModel> itemSelectedCommand;

        private readonly IViewModelStorage<TModel, TViewModel> viewModelStorage;

        private CustomObservableCollection<TViewModel> collection = new CustomObservableCollection<TViewModel>();

        private TViewModel selectedItem;

        #endregion

        #region Constructors and Destructors

        protected BaseListViewModel(
            INotificationService message,
            IMvxMessenger events,
            ILogger logger,
            IAccountService accountData,
            IViewModelStorage<TModel, TViewModel> viewModelStorage)
            : base(accountData, events, message, logger)
        {
            this.viewModelStorage = viewModelStorage;
            this.itemSelectedCommand = new MvxCommand<TViewModel>(this.RefreshItemsSelection);
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Collection of <see cref="ContactViewModel" />. Get and set
        /// </summary>
        public CustomObservableCollection<TViewModel> Context
        {
            get
            {
                return this.collection;
            }
        }

        /// <summary>
        /// Is collection support selection of several items
        /// </summary>
        public bool IsMultiSelect { get; set; }

        /// <summary>
        /// Gets the item selected command.
        /// </summary>
        public ICommand ItemSelectedCommand
        {
            get
            {
                return this.itemSelectedCommand;
            }
        }

        /// <summary>
        /// Item that selected
        /// </summary>
        public TViewModel SelectedItem
        {
            get
            {
                return this.selectedItem;
            }
            set
            {
                if (this.selectedItem.Equals(value))
                {
                    return;
                }

                this.selectedItem = value;
                this.RaisePropertyChanged(() => this.SelectedItem);
            }
        }

        #endregion

        #region Properties

        protected abstract Dictionary<string, object> Filters { get; }

        /// <summary>
        /// Get singleton collection of view models
        /// </summary>
        protected IViewModelStorage<TModel, TViewModel> ViewModelStorage
        {
            get
            {
                return this.viewModelStorage;
            }
        }

        #endregion

        #region Public Methods and Operators

        public override void CleansAfter()
        {
            base.CleansAfter();

            this.EventHub.Unsubscribe<Message<TViewModel>>(this.SelectionToken);
            this.EventHub.Unsubscribe<Message<TModel>>(this.ContactToken);
        }

        public virtual void ClearContext()
        {
            this.collection.Clear();
            this.ViewModelStorage.Clear();
        }

        /// <summary>
        /// Get all managed objects here
        /// </summary>
        public override void MakeMess()
        {
            base.MakeMess();

            this.SelectionToken = this.EventHub.Subscribe<Message<TViewModel>>(this.OnSelectionChanged, tag: DateTime.Now.ToString("O"));
            this.ContactToken = this.EventHub.Subscribe<Message<TModel>>(this.OnContactUpdated);
        }

        public override void Start()
        {
            base.Start();

            this.InvokeOnMainThread(
                delegate
                    {
                        this.IsLoading = false;
                        this.RaisePropertyChanged(() => this.Context);
                    });
        }

        #endregion

        #region Methods

        protected void OnSelectionChanged(Message<TViewModel> message)
        {
            if (message == null)
            {
                this.ErrorAction(new ArgumentNullException("message"));
            }
            else
            {
                this.ItemSelectedCommand.Execute(message.Data);
            }
        }

        protected virtual void UpdateCollection()
        {
            this.IsLoading = true;

            var task = this.ViewModelStorage.FilteredList(this.Filters);

            this.collection = new CustomObservableCollection<TViewModel>(task.Result);

            this.InvokeOnMainThread(
                delegate
                    {
                        this.IsLoading = false;
                        this.RaisePropertyChanged(() => this.Context);
                    });
        }

        private void OnContactUpdated(Message<TModel> message)
        {
            if (message == null)
            {
                this.ErrorAction(new ArgumentNullException("message"));
            }
            else
            {
                this.ViewModelStorage.AddOrUpdate(message.Data);
            }
        }

        private void RefreshItemsSelection(TViewModel viewModel)
        {
            if (this.Context.Count <= 0)
            {
                return;
            }

            if (this.IsMultiSelect)
            {
                var item = this.Context.FirstOrDefault(n => n.Equals(viewModel));
                if (item != null)
                {
                    item.IsSelected = !item.IsSelected;
                }
            }
            else
            {
                foreach (var item in this.Context)
                {
                    if (item.Equals(viewModel))
                    {
                        item.IsSelected = !item.IsSelected;
                    }
                    else
                    {
                        item.IsSelected = false;
                    }
                }
            }
        }

        #endregion
    }
}


text:
from __future__ import print_function
import tensorflow as tf
import numpy as np
import cPickle
from tensorflow.contrib import slim

#Load features and labels
features = cPickle.load(open('nn_features.p', 'rb'))
val_features = cPickle.load(open('nn_val_features.p', 'rb'))
test_features = cPickle.load(open('nn_test_features.p', 'rb'))
labels = cPickle.load(open('labels.p', 'rb'))

#to normalize submatrix which is not sparse
l = [i for i in range(143, features.shape[1])]
mu = np.mean(features, axis=0)
std = np.mean(features, axis=0)
features[:,l] = (features[:,l] - mu[l]) / std[l]
val_features[:,l] = (val_features[:,l] - mu[l]) / std[l]
test_features[:,l] = (test_features[:,l] - mu[l]) / std[l]

mask = np.random.choice(features.shape[0], features.shape[0], replace=False)
features = features[mask]
labels = labels[mask]

positive_mask = []
negative_mask = []
for i in range(labels.shape[0]):
	if np.array_equal(labels[i], [0,1]):
		positive_mask.append(i)
	else:
		negative_mask.append(i)
pos_features = features[positive_mask]
pos_labels = labels[positive_mask]
neg_features = features[negative_mask]
neg_labels = labels[negative_mask]

#change these values later
learning_rate = 0.001
training_epochs = 10
display_step = 1
in_dim = features.shape[1]
n_samples = features.shape[0]
batch_size = 128
num_features = features.shape[1]
num_classes = labels.shape[1]
n_hidden1 = 256
n_hidden2 = 256
n_hidden3 = 256
reg_strength = 5e-4
dropout_rate = 0.5

#define placeholder for our input
X = tf.placeholder("float", [None, num_features])
Y = tf.placeholder("float", [None, num_classes])
#drop_p = tf.placeholder(tf.float32)

def model(x):
    layer = slim.fully_connected(x,n_hidden1, weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
                               weights_regularizer=slim.l2_regularizer(reg_strength),scope='hidden1')
    layer = slim.batch_norm(layer, scope='bn1')
    layer = slim.dropout(layer, dropout_rate, scope='dropout1')
    layer = slim.fully_connected(layer,n_hidden2, weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
                               weights_regularizer=slim.l2_regularizer(reg_strength),scope='hidden2')
    layer = slim.batch_norm(layer, scope='bn2')
    layer = slim.dropout(layer, dropout_rate, scope='dropout2')
    layer = slim.fully_connected(layer,n_hidden3, weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
                               weights_regularizer=slim.l2_regularizer(reg_strength),scope='hidden3')
    out_layer = slim.fully_connected(layer,num_classes, activation_fn=None, weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
                               weights_regularizer=slim.l2_regularizer(reg_strength),scope='out_layer')
    return out_layer

recommendor = model(X)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(recommendor, Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)

probabilities = tf.nn.softmax(recommendor)

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    # Training cycle
    for epoch in range(training_epochs):
        avg_loss = 0.
        total_batch = int(features.shape[0]/batch_size)
        # Loop over all batches
        start = 0
        end = batch_size
        for i in range(total_batch):
            #batch_x, batch_y = features[start:end], labels[start:end]
            pos_mask = np.random.choice(pos_features.shape[0], batch_size/2, replace=False)
            neg_mask = np.random.choice(neg_features.shape[0], batch_size/2, replace=False)
            batch_x = np.vstack((pos_features[pos_mask], neg_features[neg_mask]))
            batch_y = np.vstack((pos_labels[pos_mask], neg_labels[neg_mask]))
            shuffle = np.random.choice(batch_x.shape[0], batch_x.shape[0], replace=False)
            batch_x = batch_x[shuffle]
            batch_y = batch_y[shuffle]
            # Run optimization op (backprop) and loss op (to get loss value)
            _, c = sess.run([optimizer, loss], feed_dict={X: batch_x,
                                                          Y: batch_y})
            # Compute average loss
            avg_loss += c / total_batch
            start = end
            end += batch_size
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "loss=", \
                "{:.9f}".format(avg_loss))
    print("Optimization Finished!")
    probs = sess.run(probabilities, feed_dict={X: val_features})
    test_probs = sess.run(probabilities, feed_dict={X: test_features})

print('Probabilies: ', probs[:,1])
f = open('validate_nolabel.txt', 'r')
header = f.readline()
content = f.readlines()
f.close()
f = open('nn_val_res.txt', 'w')
f.write(header)
for i in range(len(content)):
	data = content[i].replace('\n', '').replace('\r', '')
	data += ',' + str(probs[i,1]) + '\n'
	f.write(data)
f.close()

f = open('test_data.txt', 'r')
header = f.readline()
content = f.readlines()
f.close()
print('Test Probabilies: ', test_probs[:,1])
f = open('nn_test_res.txt', 'w')
f.write(header)
for i in range(len(content)):
    data = content[i].replace('\n', '').replace('\r', '')
    data += ',' + str(test_probs[i,1]) + '\n'
    f.write(data)
f.close()


text:
"""add_network_driver_baymodel_column

Revision ID: 3be65537a94a
Revises: 4e263f236334
Create Date: 2015-09-03 20:51:54.229436

"""

# revision identifiers, used by Alembic.
revision = '3be65537a94a'
down_revision = '4e263f236334'

from alembic import op  # noqa: E402

from oslo_db.sqlalchemy.types import String  # noqa: E402

import sqlalchemy as sa  # noqa: E402

from sqlalchemy.dialects.mysql import TINYTEXT  # noqa: E402

def upgrade():
    op.add_column('baymodel', sa.Column('network_driver',
                  String(255, mysql_ndb_type=TINYTEXT), nullable=True))


text:
IonicModule
.controller('$ionicTabs', [
  '$scope',
  '$element',
  '$ionicHistory',
function($scope, $element, $ionicHistory) {
  var self = this;
  var selectedTab = null;
  var previousSelectedTab = null;
  var selectedTabIndex;
  self.tabs = [];

  self.selectedIndex = function() {
    return self.tabs.indexOf(selectedTab);
  };
  self.selectedTab = function() {
    return selectedTab;
  };
  self.previousSelectedTab = function() {
    return previousSelectedTab;
  };

  self.add = function(tab) {
    $ionicHistory.registerHistory(tab);
    self.tabs.push(tab);
  };

  self.remove = function(tab) {
    var tabIndex = self.tabs.indexOf(tab);
    if (tabIndex === -1) {
      return;
    }
    //Use a field like '$tabSelected' so developers won't accidentally set it in controllers etc
    if (tab.$tabSelected) {
      self.deselect(tab);
      //Try to select a new tab if we're removing a tab
      if (self.tabs.length === 1) {
        //Do nothing if there are no other tabs to select
      } else {
        //Select previous tab if it's the last tab, else select next tab
        var newTabIndex = tabIndex === self.tabs.length - 1 ? tabIndex - 1 : tabIndex + 1;
        self.select(self.tabs[newTabIndex]);
      }
    }
    self.tabs.splice(tabIndex, 1);
  };

  self.deselect = function(tab) {
    if (tab.$tabSelected) {
      previousSelectedTab = selectedTab;
      selectedTab = selectedTabIndex = null;
      tab.$tabSelected = false;
      (tab.onDeselect || noop)();
      tab.$broadcast && tab.$broadcast('$ionicHistory.deselect');
    }
  };

  self.select = function(tab, shouldEmitEvent) {
    var tabIndex;
    if (isNumber(tab)) {
      tabIndex = tab;
      if (tabIndex >= self.tabs.length) return;
      tab = self.tabs[tabIndex];
    } else {
      tabIndex = self.tabs.indexOf(tab);
    }

    if (arguments.length === 1) {
      shouldEmitEvent = !!(tab.navViewName || tab.uiSref);
    }

    if (selectedTab && selectedTab.$historyId == tab.$historyId) {
      if (shouldEmitEvent) {
        $ionicHistory.goToHistoryRoot(tab.$historyId);
      }

    } else if (selectedTabIndex !== tabIndex) {
      forEach(self.tabs, function(tab) {
        self.deselect(tab);
      });

      selectedTab = tab;
      selectedTabIndex = tabIndex;

      if (self.$scope && self.$scope.$parent) {
        self.$scope.$parent.$activeHistoryId = tab.$historyId;
      }

      //Use a funny name like $tabSelected so the developer doesn't overwrite the var in a child scope
      tab.$tabSelected = true;
      (tab.onSelect || noop)();

      if (shouldEmitEvent) {
        $scope.$emit('$ionicHistory.change', {
          type: 'tab',
          tabIndex: tabIndex,
          historyId: tab.$historyId,
          navViewName: tab.navViewName,
          hasNavView: !!tab.navViewName,
          title: tab.title,
          url: tab.href,
          uiSref: tab.uiSref
        });
      }
    }
  };

  self.hasActiveScope = function() {
    for (var x = 0; x < self.tabs.length; x++) {
      if ($ionicHistory.isActiveScope(self.tabs[x])) {
        return true;
      }
    }
    return false;
  };

  self.showTabBar = function(shouldShow) {
    if (shouldShow) $element.removeClass('tabs-item-hide');
    else $element.addClass('tabs-item-hide');
  };

}]);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Thoughts, research and life!">
    <link rel="shortcut icon" href="/en/favicon.ico">

    <title>ourren</title>

    <link rel="canonical" href="http://www.ourren.com/en/en/page2/">

    <link rel="stylesheet" href="/en/css/bootstrap.min.css">

    <link rel="stylesheet" href="/en/css/clean-blog.css">

    <link rel="stylesheet" href="/en/css/syntax.css">

    <link href='//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            ourren

                    Home

                    Project

                    Slide

                    About

ourren

                    Thoughts, research and life!

            Remove common words using nltk

            Remove common words and stopwords from the data sets.

Posted by ourren on January 15, 2015

            Latex environment on Mac OS X

            Install Latex with Sublime and Skim on Mac OS X.

Posted by ourren on December 25, 2014

            Security conferences ranking

            Top security conference list and some related resources.

Posted by ourren on December 10, 2014

            Several necessary work before doing research

            A short summary about security resource and writing tool.

Posted by ourren on December 4, 2014

            NLP resources for beginners

            Some books and package about NLP technology.

Posted by ourren on December 2, 2014

        ← Newer Posts

        Older Posts →

Copyright © ourren 2015


text:
package org.papoose.tck.event;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import static org.ops4j.pax.exam.CoreOptions.equinox;
import static org.ops4j.pax.exam.CoreOptions.felix;
import static org.ops4j.pax.exam.CoreOptions.knopflerfish;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.provision;
import static org.ops4j.pax.exam.MavenUtils.asInProject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.EventAdmin;

import org.papoose.event.EventAdminServiceFactory;

/**
 * @version $Revision: $ $Date: $
 */
@RunWith(JUnit4TestRunner.class)
public class PapooseEventAdminImplTest extends BaseEventAdminImplTest
{
    private ExecutorService executor;
    private ScheduledExecutorService scheduledExecutor;
    private EventAdminServiceFactory eventAdmin;
    private ServiceRegistration sr;

    @Configuration
    public static Option[] configure()
    {
        return options(
                equinox(),
                felix(),
                knopflerfish(),
                // papoose(),
                provision(
                        mavenBundle().groupId("org.papoose.cmpn").artifactId("papoose-event").version(asInProject())
                )
        );
    }

    @Override
    protected void lowerTimeout()
    {
        eventAdmin.setTimeout(100);
        eventAdmin.setTimeUnit(TimeUnit.MILLISECONDS);
    }

    @Before
    public void before()
    {
        executor = Executors.newFixedThreadPool(5);
        scheduledExecutor = Executors.newScheduledThreadPool(2);
        eventAdmin = new EventAdminServiceFactory(bundleContext, executor, scheduledExecutor);

        eventAdmin.start();

        sr = bundleContext.registerService(EventAdmin.class.getName(), eventAdmin, null);
    }

    @After
    public void after()
    {
        sr.unregister();

        eventAdmin.stop();

        executor.shutdown();
        scheduledExecutor.shutdown();
    }
}


text:
import React from 'react';
import {Route} from 'react-router';

export default () => {
  /**
   * Please keep routes in alphabetical order
   */
  return (
    <Route path="/" />
  );
};


text:
import './lib/modules.js';
import './lib/server/templates.js';


text:
package pt.davidafsilva.ghn.service.auth;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.reactivestreams.Publisher;

import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;

import io.netty.handler.codec.http.HttpResponseStatus;
import pt.davidafsilva.ghn.model.User;
import pt.davidafsilva.ghn.model.mutable.Configuration;
import pt.davidafsilva.ghn.service.AbstractGitHubService;
import pt.davidafsilva.ghn.util.Schedulers;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.http.client.HttpClient;
import reactor.ipc.netty.http.client.HttpClientRequest;

/**
 * @author david
 */
public class GitHubAuthService extends AbstractGitHubService {

  // initialize the request body
  private static final String TOKEN_AUTH_REQUEST_BODY = "{\n" +
      "  \"scopes\": [\n" +
      "    \"notifications\"\n" +
      "  ],\n" +
      "  \"note\": \"GitHub Notification Hub token\"\n" +
      "}";
  // url path
  private static final String LOGIN_URL_PATH = "/user";
  private static final String TOKEN_URL_PATH = "/authorizations";
  private static final String GRAVATAR_URL = "https://www.gravatar.com/";

  // properties
  private final HttpClient client;
  private final String loginUrl;
  private final String tokenUrl;

  public GitHubAuthService(final Configuration applicationOptions) {
    this.client = HttpClient.create(opt -> opt.sslSupport().disablePool());
    this.loginUrl = url(applicationOptions, LOGIN_URL_PATH);
    this.tokenUrl = url(applicationOptions, TOKEN_URL_PATH);
  }

  public Mono<User> loginWithToken(final String token) {
    return doLogin(null, token, null, r -> (u, t) -> addTokenAuthorization(r, t));
  }

  public Mono<User> loginWithPassword(final String user, final String password, final String code) {
    return doLogin(user, password, code, r -> (u, p) -> addBasicAuthorization(r, u, p));
  }

  public Mono<String> createToken(final String user, final String password, final String code) {
    return client.post(tokenUrl, request -> sendRequest(request, user, password, code,
        r -> (u, p) -> addBasicAuthorization(r, u, p),
        r -> r.sendString(Mono.just(TOKEN_AUTH_REQUEST_BODY))))
        .mapError(this::is2FactorRequired, TwoFactorAuthRequiredException::new)
        .mapError(this::isUnauthorizedOrForbidden, InvalidCredentialsException::new)
        .mapError(this::isTokenAlreadyCreated, TokenExistsException::new)
        .filter(r -> r.status() == HttpResponseStatus.CREATED)
        .flatMap(r -> decodeJson(r, new ObjectMapper()))
        .filter(json -> json.has("token"))
        .map(json -> json.get("token").asText())
        .next()
        .subscribeOn(Schedulers.io());
  }

  private Mono<User> doLogin(final String u, final String p, final String c,
      final Function<HttpClientRequest, BiFunction<String, String, HttpClientRequest>> authStrategy) {
    return client.get(loginUrl, request -> sendRequest(request, u, p, c, authStrategy,
        HttpClientRequest::send))
        .mapError(this::is2FactorRequired, TwoFactorAuthRequiredException::new)
        .mapError(this::isUnauthorizedOrForbidden, InvalidCredentialsException::new)
        .filter(r -> r.status() == HttpResponseStatus.OK)
        .flatMap(r -> decodeJson(r, new ObjectMapper()))
        .map(json -> new User(getUsername(json), p, getAvatarUrl(json).orElse(null)))
        .next()
        .subscribeOn(Schedulers.io());
  }

  private String getUsername(final JsonNode json) {
    return json.get("login").asText();
  }

  private Optional<String> getAvatarUrl(final JsonNode json) {
    if (json.has("avatar_url")) {
      return Optional.of(json.get("avatar_url").asText());
    }
    if (json.has("gravatar_id")) {
      return Optional.of(GRAVATAR_URL + json.get("gravatar_id").asText());
    }

    return Optional.empty();
  }

  private Publisher<Void> sendRequest(final HttpClientRequest request,
      final String user, final String password, final String code,
      final Function<HttpClientRequest, BiFunction<String, String, HttpClientRequest>> authStrategy,
      final Function<HttpClientRequest, Publisher<Void>> sendFunction) {
    return Mono.just(request)
        .map(this::addUserAgent)
        .map(this::addAcceptHeeader)
        .map(r -> addOtpHeader(r, code))
        .map(r -> authStrategy.apply(r).apply(user, password))
        .map(sendFunction)
        .block();
  }
}


text:
RSpec.shared_examples "base container" do
  describe "#name" do
    it "should access the @name" do
      context.name "fubar"
      expect(context.name).to eql("fubar")
    end
  end

  describe "#image" do
    it "should access the @image" do
      context.image "blah"
      expect(context.image).to eql("blah")
    end
  end

  describe "#command" do
    it "should access the @command" do
      context.command "blah"
      expect(context.command).to eql("blah")
    end
  end

  describe "#mounts" do
    it "should collect host/container mounts" do
      context.mounts a: :b
      context.mounts c: :d
      expect(context.mounts).to eql({a: :b, c: :d})
    end
  end
end


text:
"""Create, read, and delete databases in the Azure Cosmos DB SQL API service.
"""

from typing import Any, Dict, Optional, Union, cast
from azure.core.async_paging import AsyncItemPaged
from azure.core.credentials import TokenCredential

from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.tracing.decorator import distributed_trace

from ..cosmos_client import _parse_connection_str, _build_auth
from ._cosmos_client_connection_async import CosmosClientConnection
from .._base import build_options as _build_options, _set_throughput_options
from ..offer import ThroughputProperties
from ._retry_utility_async import _ConnectionRetryPolicy
from ._database import DatabaseProxy
from ..documents import ConnectionPolicy, DatabaseAccount
from ..exceptions import CosmosResourceNotFoundError

__all__ = ("CosmosClient",)

def _build_connection_policy(kwargs: Dict[str, Any]) -> ConnectionPolicy:
    # pylint: disable=protected-access
    policy = kwargs.pop('connection_policy', None) or ConnectionPolicy()

    # Connection config
    policy.RequestTimeout = kwargs.pop('request_timeout', None) or \
                            kwargs.pop('connection_timeout', None) or \
                            policy.RequestTimeout
    policy.ConnectionMode = kwargs.pop('connection_mode', None) or policy.ConnectionMode
    policy.ProxyConfiguration = kwargs.pop('proxy_config', None) or policy.ProxyConfiguration
    policy.EnableEndpointDiscovery = kwargs.pop('enable_endpoint_discovery', None) or policy.EnableEndpointDiscovery
    policy.PreferredLocations = kwargs.pop('preferred_locations', None) or policy.PreferredLocations
    policy.UseMultipleWriteLocations = kwargs.pop('multiple_write_locations', None) or \
                                       policy.UseMultipleWriteLocations

    # SSL config
    verify = kwargs.pop('connection_verify', None)
    policy.DisableSSLVerification = not bool(verify if verify is not None else True)
    ssl = kwargs.pop('ssl_config', None) or policy.SSLConfiguration
    if ssl:
        ssl.SSLCertFile = kwargs.pop('connection_cert', None) or ssl.SSLCertFile
        ssl.SSLCaCerts = verify or ssl.SSLCaCerts
        policy.SSLConfiguration = ssl

    # Retry config
    retry_options = policy.RetryOptions
    total_retries = kwargs.pop('retry_total', None)
    retry_options._max_retry_attempt_count = total_retries or retry_options._max_retry_attempt_count
    retry_options._fixed_retry_interval_in_milliseconds = kwargs.pop('retry_fixed_interval', None) or \
        retry_options._fixed_retry_interval_in_milliseconds
    max_backoff = kwargs.pop('retry_backoff_max', None)
    retry_options._max_wait_time_in_seconds = max_backoff or retry_options._max_wait_time_in_seconds
    policy.RetryOptions = retry_options
    connection_retry = policy.ConnectionRetryConfiguration
    if not connection_retry:
        connection_retry = _ConnectionRetryPolicy(
            retry_total=total_retries,
            retry_connect=kwargs.pop('retry_connect', None),
            retry_read=kwargs.pop('retry_read', None),
            retry_status=kwargs.pop('retry_status', None),
            retry_backoff_max=max_backoff,
            retry_on_status_codes=kwargs.pop('retry_on_status_codes', []),
            retry_backoff_factor=kwargs.pop('retry_backoff_factor', 0.8),
        )
    policy.ConnectionRetryConfiguration = connection_retry

    return policy

class CosmosClient(object):  # pylint: disable=client-accepts-api-version-keyword
    """A client-side logical representation of an Azure Cosmos DB account.

    Use this client to configure and execute requests to the Azure Cosmos DB service.

    :param str url: The URL of the Cosmos DB account.
    :param credential: Can be the account key, or a dictionary of resource tokens.
    :type credential: Union[str, Dict[str, str], ~azure.core.credentials_async.AsyncTokenCredential]
    :keyword str consistency_level: Consistency level to use for the session. Default value is None (account-level).
        More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels

    .. admonition:: Example:

        .. literalinclude:: ../samples/examples_async.py
            :start-after: [START create_client]
            :end-before: [END create_client]
            :language: python
            :dedent: 0
            :caption: Create a new instance of the Cosmos DB client:
            :name: create_client
    """

    def __init__(
            self,
            url: str,
            credential: Union[str, Dict[str, str], TokenCredential],
            *,
            consistency_level: Optional[str] = None,
            **kwargs: Any
    ) -> None:
        """Instantiate a new CosmosClient."""
        auth = _build_auth(credential)
        connection_policy = _build_connection_policy(kwargs)
        self.client_connection = CosmosClientConnection(
            url,
            auth=auth,
            consistency_level=consistency_level,
            connection_policy=connection_policy,
            **kwargs
        )

    def __repr__(self) -> str:
        return "<CosmosClient [{}]>".format(self.client_connection.url_connection)[:1024]

    async def __aenter__(self):
        await self.client_connection.pipeline_client.__aenter__()
        await self.client_connection._setup()
        return self

    async def __aexit__(self, *args):
        return await self.client_connection.pipeline_client.__aexit__(*args)

    async def close(self) -> None:
        """Close this instance of CosmosClient."""
        await self.__aexit__()

    @classmethod
    def from_connection_string(
            cls,
            conn_str: str,
            *,
            credential: Optional[Union[str, Dict[str, str]]] = None,
            consistency_level: Optional[str] = None,
            **kwargs: Any
    ) -> "CosmosClient":
        """Create a CosmosClient instance from a connection string.

        This can be retrieved from the Azure portal.For full list of optional
        keyword arguments, see the CosmosClient constructor.

        :param str conn_str: The connection string.
        :keyword credential: Alternative credentials to use instead of the key provided in the connection string.
        :paramtype credential: Union[str, Dict[str, str]]
        :keyword str consistency_level: Consistency level to use for the session. Default value is None (account-level).
            More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels
        :returns: a CosmosClient instance
        :rtype: ~azure.cosmos.aio.CosmosClient
        """
        settings = _parse_connection_str(conn_str, credential)
        return cls(
            url=settings['AccountEndpoint'],
            credential=settings['AccountKey'],
            consistency_level=consistency_level,
            **kwargs
        )

    @staticmethod
    def _get_database_link(database_or_id: Union[DatabaseProxy, str, Dict[str, str]]) -> str:
        if isinstance(database_or_id, str):
            return "dbs/{}".format(database_or_id)
        try:
            return cast("DatabaseProxy", database_or_id).database_link
        except AttributeError:
            pass
        database_id = cast("Dict[str, str]", database_or_id)["id"]
        return "dbs/{}".format(database_id)

    @distributed_trace_async
    async def create_database(  # pylint: disable=redefined-builtin
            self,
            id: str,
            **kwargs: Any
    ) -> DatabaseProxy:
        """
        Create a new database with the given ID (name).

        :param str id: ID (name) of the database to create.
        :keyword offer_throughput: The provisioned throughput for this offer.
        :paramtype offer_throughput: int or ~azure.cosmos.ThroughputProperties.
        :keyword str session_token: Token for use with Session consistency.
        :keyword dict[str, str] initial_headers: Initial headers to be sent as part of the request.
        :keyword str etag: An ETag value, or the wildcard character (*). Used to check if the resource
            has changed, and act according to the condition specified by the `match_condition` parameter.
        :keyword match_condition: The match condition to use upon the etag.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword response_hook: A callable invoked with the response metadata.
        :paramtype response_hook: Callable[[Dict[str, str], Dict[str, Any]], None]
        :raises ~azure.cosmos.exceptions.CosmosResourceExistsError: Database with the given ID already exists.
        :returns: A DatabaseProxy instance representing the new database.
        :rtype: ~azure.cosmos.aio.DatabaseProxy

        .. admonition:: Example:

            .. literalinclude:: ../samples/examples_async.py
                :start-after: [START create_database]
                :end-before: [END create_database]
                :language: python
                :dedent: 0
                :caption: Create a database in the Cosmos DB account:
                :name: create_database
        """

        request_options = _build_options(kwargs)
        response_hook = kwargs.pop('response_hook', None)
        offer_throughput = kwargs.pop('offer_throughput', None)
        _set_throughput_options(offer=offer_throughput, request_options=request_options)

        result = await self.client_connection.CreateDatabase(database=dict(id=id), options=request_options, **kwargs)
        if response_hook:
            response_hook(self.client_connection.last_response_headers, result)
        return DatabaseProxy(self.client_connection, id=result["id"], properties=result)

    @distributed_trace_async
    async def create_database_if_not_exists(  # pylint: disable=redefined-builtin
            self,
            id: str,
            **kwargs: Any
    ) -> DatabaseProxy:
        """
        Create the database if it does not exist already.

        If the database already exists, the existing settings are returned.

        ..note::
            This function does not check or update existing database settings or
            offer throughput if they differ from what is passed in.

        :param str id: ID (name) of the database to read or create.
        :keyword int offer_throughput: The provisioned throughput for this offer.
        :keyword str session_token: Token for use with Session consistency.
        :keyword dict[str, str] initial_headers: Initial headers to be sent as part of the request.
        :keyword str etag: An ETag value, or the wildcard character (*). Used to check if the resource
            has changed, and act according to the condition specified by the `match_condition` parameter.
        :keyword match_condition: The match condition to use upon the etag.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword response_hook: A callable invoked with the response metadata.
        :paramtype response_hook: Callable[[Dict[str, str], Dict[str, Any]], None]
        :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The database read or creation failed.
        :returns: A DatabaseProxy instance representing the database.
        :rtype: ~azure.cosmos.DatabaseProxy
        """
        try:
            database_proxy = self.get_database_client(id)
            await database_proxy.read(**kwargs)
            return database_proxy
        except CosmosResourceNotFoundError:
            return await self.create_database(
                id,
                **kwargs
            )

    def get_database_client(self, database: Union[str, DatabaseProxy, Dict[str, Any]]) -> DatabaseProxy:
        """Retrieve an existing database with the ID (name) `id`.

        :param database: The ID (name), dict representing the properties, or :class:`DatabaseProxy`
            instance of the database to get.
        :type database: Union[str, ~azure.cosmos.DatabaseProxy, Dict[str, Any]]
        :returns: A `DatabaseProxy` instance representing the retrieved database.
        :rtype: ~azure.cosmos.DatabaseProxy
        """
        try:
            id_value = database.id
        except AttributeError:
            try:
                id_value = database['id']
            except TypeError:
                id_value = database

        return DatabaseProxy(self.client_connection, id_value)

    @distributed_trace
    def list_databases(
            self,
            **kwargs: Any
    ) -> AsyncItemPaged[Dict[str, Any]]:
        """List the databases in a Cosmos DB SQL database account.

        :keyword int max_item_count: Max number of items to be returned in the enumeration operation.
        :keyword str session_token: Token for use with Session consistency.
        :keyword dict[str, str] initial_headers: Initial headers to be sent as part of the request.
        :keyword response_hook: A callable invoked with the response metadata.
        :paramtype response_hook: Callable[[Dict[str, str]], None]
        :returns: An AsyncItemPaged of database properties (dicts).
        :rtype: AsyncItemPaged[Dict[str, str]]
        """
        feed_options = _build_options(kwargs)
        response_hook = kwargs.pop('response_hook', None)
        max_item_count = kwargs.pop('max_item_count', None)
        if max_item_count is not None:
            feed_options["maxItemCount"] = max_item_count

        result = self.client_connection.ReadDatabases(options=feed_options, **kwargs)
        if response_hook:
            response_hook(self.client_connection.last_response_headers)
        return result

    @distributed_trace
    def query_databases(
            self,
            **kwargs: Any
    ) -> AsyncItemPaged[Dict[str, Any]]:
        """Query the databases in a Cosmos DB SQL database account.

        :keyword Union[str, Dict[str, Any]] query: The Azure Cosmos DB SQL query to execute.
        :keyword parameters: Optional array of parameters to the query.
            Each parameter is a dict() with 'name' and 'value' keys.
        :paramtype parameters: List[Dict[str, Any]]
        :keyword int max_item_count: Max number of items to be returned in the enumeration operation.
        :keyword str session_token: Token for use with Session consistency.
        :keyword dict[str, str] initial_headers: Initial headers to be sent as part of the request.
        :keyword response_hook: A callable invoked with the response metadata.
        :paramtype response_hook: Callable[[Dict[str, str]], None]
        :returns: An AsyncItemPaged of database properties (dicts).
        :rtype: AsyncItemPaged[Dict[str, str]]
        """
        feed_options = _build_options(kwargs)
        response_hook = kwargs.pop('response_hook', None)
        max_item_count = kwargs.pop('max_item_count', None)
        if max_item_count is not None:
            feed_options["maxItemCount"] = max_item_count

        parameters = kwargs.pop('parameters', None)
        query = kwargs.pop('query', None)
        result = self.client_connection.QueryDatabases(
            query=query if parameters is None else dict(query=query, parameters=parameters),
            options=feed_options,
            **kwargs)
        if response_hook:
            response_hook(self.client_connection.last_response_headers)
        return result

    @distributed_trace_async
    async def delete_database(
            self,
            database: Union[str, DatabaseProxy, Dict[str, Any]],
            **kwargs: Any
    ) -> None:
        """Delete the database with the given ID (name).

        :param database: The ID (name), dict representing the properties, or :class:`DatabaseProxy`
            instance of the database to delete.
        :type database: Union[str, ~azure.cosmos.DatabaseProxy, Dict[str, Any]]
        :keyword str session_token: Token for use with Session consistency.
        :keyword dict[str, str] initial_headers: Initial headers to be sent as part of the request.
        :keyword str etag: An ETag value, or the wildcard character (*). Used to check if the resource
            has changed, and act according to the condition specified by the `match_condition` parameter.
        :keyword match_condition: The match condition to use upon the etag.
        :paramtype match_condition: ~azure.core.MatchConditions
        :keyword response_hook: A callable invoked with the response metadata.
        :paramtype response_hook: Callable[[Dict[str, str]], None]
        :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the database couldn't be deleted.
        :rtype: None
        """
        request_options = _build_options(kwargs)
        response_hook = kwargs.pop('response_hook', None)

        database_link = self._get_database_link(database)
        await self.client_connection.DeleteDatabase(database_link, options=request_options, **kwargs)
        if response_hook:
            response_hook(self.client_connection.last_response_headers)

    @distributed_trace_async
    async def _get_database_account(self, **kwargs: Any) -> DatabaseAccount:
        """Retrieve the database account information.

        :keyword response_hook: A callable invoked with the response metadata.
        :paramtype response_hook: Callable[[Dict[str, str]], None]
        :returns: A `DatabaseAccount` instance representing the Cosmos DB Database Account.
        :rtype: ~azure.cosmos.DatabaseAccount
        """
        response_hook = kwargs.pop('response_hook', None)
        result = await self.client_connection.GetDatabaseAccount(**kwargs)
        if response_hook:
            response_hook(self.client_connection.last_response_headers)
        return result


text:
@implementation UIImageView (MLBSDImageLoader)

- (void)mlb_sd_setImageWithURL:(NSString *)url placeholderImageName:(NSString *)placeholderImageName {
    [self mlb_sd_setImageWithURL:url placeholderImageName:placeholderImageName cachePlachoderImage:YES];
}

- (void)mlb_sd_setImageWithURL:(NSString *)url placeholderImageName:(NSString *)placeholderImageName cachePlachoderImage:(BOOL)cachePlachoderImage {
    if ([[SDImageCache sharedImageCache] diskImageExistsWithKey:url]) {
        self.image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:url];
    } else {
        UIImage *placeholderImage;
        if (IsStringNotEmpty(placeholderImageName)) {
            if (cachePlachoderImage) {
                placeholderImage = [UIImage imageNamed:placeholderImageName];
            } else {
                NSString *pathOfImage = [[NSBundle mainBundle] pathForResource:placeholderImageName ofType:@"png"];
                placeholderImage = [UIImage imageWithContentsOfFile:pathOfImage];
            }
        }
        [self sd_setImageWithURL:[url mlb_encodedURL] placeholderImage:placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[SDImageCache sharedImageCache] storeImage:image forKey:url toDisk:YES];
            });
        }];
    }
}

@end


text:
namespace extensions {

// static
BluetoothAPI* BluetoothAPIFactory::GetForProfile(Profile* profile) {
  return static_cast<BluetoothAPI*>(
      GetInstance()->GetServiceForProfile(profile, true));
}

// static
BluetoothAPIFactory* BluetoothAPIFactory::GetInstance() {
  return Singleton<BluetoothAPIFactory>::get();
}

BluetoothAPIFactory::BluetoothAPIFactory()
    : ProfileKeyedServiceFactory("BluetoothAPI",
                                 ProfileDependencyManager::GetInstance()) {
  DependsOn(ExtensionSystemFactory::GetInstance());
}

BluetoothAPIFactory::~BluetoothAPIFactory() {
}

ProfileKeyedService* BluetoothAPIFactory::BuildServiceInstanceFor(
    content::BrowserContext* profile) const {
  return new BluetoothAPI(static_cast<Profile*>(profile));
}

content::BrowserContext* BluetoothAPIFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  return chrome::GetBrowserContextRedirectedInIncognito(context);
}

bool BluetoothAPIFactory::ServiceIsCreatedWithProfile() const {
  return true;
}

bool BluetoothAPIFactory::ServiceIsNULLWhileTesting() const {
  return true;
}

}  // namespace extensions


text:
<?php

namespace AdminBundle\Controller;

use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use TomJerryBundle\Interfaces\AuditableControllerInterface;
use Symfony\Component\HttpFoundation\Request;
use TomJerryBundle\Controller\uploaderHandler;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Description of AttendenceController
 *
 * @author akhil
 */
class SubjectsController extends Controller {

    public function manageSubjectsAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $form = $this->createFormBuilder()
                ->setAction($this->generateUrl('masters_add_subjects'))
                ->setMethod("POST")
                ->add('class', 'entity', array(
                    'class' => 'AdminBundle:ClassRoom',
                    'property' => 'classNum',
                    'empty_value' => 'Select Class',
                    'label' => 'Class:',
                    'attr' => array('class' => 'form-control')
                ))
                ->add('division', 'entity', array(
                    'class' => 'AdminBundle:Division',
                    'property' => 'division',
                    'empty_value' => 'Select Division',
                    'label' => 'Division:',
                    'attr' => array('class' => 'form-control')
                ))
                ->add('save', 'submit', array('label' => 'Add Subjects', 'attr' => array('class' => 'btn btn-success')))
                ->getForm();
        $form->handleRequest($request);
        if ($form->isValid()) {
            $class = $form['class']->getData();
            $division = $form['division']->getData();
            return $this->redirect($this->generateUrl('add_subject_table', array('class' => $class->getId(), 'division' => $division->getId())));
        }
        return $this->render('AdminBundle:MainAdmin/Subjects:subjectsManage.html.twig', array('form' => $form->createView()));
    }

    public function redirectSubjectsLinkAction($class, $division) {
        $em = $this->getDoctrine()->getManager();
        $classRoomSelected = $em->getRepository("AdminBundle:ClassRoom")->findOneById($class);
        $divisionSelected = $em->getRepository("AdminBundle:Division")->findOneById($division);
        $subjects = $em->getRepository("AdminBundle:Subjects")->findAll();
        $subjectsLink = $em->getRepository("AdminBundle:SubjectClassLink")->findBy(array('classId' => $class, 'divisionId' => $division));
        return $this->render('AdminBundle:MainAdmin/Subjects:linkSubjectsToClass.html.twig', array(
                    'subjects' => $subjects,
                    'subjectsLinks' => $subjectsLink,
                    'class' => $classRoomSelected,
                    'division' => $divisionSelected));
    }

    public function addSubjectsToClassAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $class = $request->request->get('class');
        $division = $request->request->get('division');
        $classRoomSelected = $em->getRepository("AdminBundle:ClassRoom")->findOneById($class);
        $divisionSelected = $em->getRepository("AdminBundle:Division")->findOneById($division);

        $subjects = $em->getRepository("AdminBundle:Subjects")->findAll();
        $subjectsLink = $em->getRepository("AdminBundle:SubjectClassLink")->findBy(array('classId' => $class, 'divisionId' => $division));
        return $this->render('AdminBundle:MainAdmin/Subjects:linkSubjectsToClass.html.twig', array(
                    'subjects' => $subjects,
                    'subjectsLinks' => $subjectsLink,
                    'class' => $classRoomSelected,
                    'division' => $divisionSelected));
    }

    public function addNewSubjectToMasterAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $subjectName = $request->request->get('subject');
        $subjectNameUpper = strtoupper($subjectName);
        $subjectNameUpperTrimd = str_replace(' ', '', $subjectNameUpper);

        $subjects = $em->getRepository("AdminBundle:Subjects")->findAll();
        foreach ($subjects as $subject) {
            $existingSubjectLower = $subject->getSubjectName();
            $existingSubjectUpper = strtoupper($existingSubjectLower);
            $existingSubjectUpperTrimd = str_replace(' ', '', $existingSubjectUpper);
            if ($subjectNameUpperTrimd === $existingSubjectUpperTrimd) {
                return new JsonResponse(false);
            }
        }
        $newSubject = new \AdminBundle\Entity\Subjects();
        $newSubject->setSubjectName($subjectName);
        $em->persist($newSubject);
        $em->flush();
        return new JsonResponse(true);
    }

    public function subjectsListMasterTableAction($classId, $dividionId) {
        $em = $this->getDoctrine()->getManager();
        $subjects = $em->getRepository("AdminBundle:Subjects")->findAll();
        $subjectsLinks = $em->getRepository("AdminBundle:SubjectClassLink")->findBy(array('classId' => $classId, 'divisionId' => $dividionId));

        if ($subjects) {
            foreach ($subjects as $subject) {
                $masterSubject[] = $subject->getId();
            }
        } else {
            $masterSubject = array();
        }

        if ($subjectsLinks) {
            foreach ($subjectsLinks as $subjectsLink) {
                $existingSubjects[] = $subjectsLink->getSubjectId()->getId();
            }
        } else {
            $existingSubjects = array();
        }
        $subjectsToPassIds = array_diff($masterSubject, $existingSubjects);
        if (count($subjectsToPassIds) != 0) {
            foreach ($subjectsToPassIds as $subjectsToPassId) {
                $mainSub = $em->getRepository("AdminBundle:Subjects")->findOneById($subjectsToPassId);
                $subjectsToPass[] = $mainSub;
            }
        } else {
            $subjectsToPass = array();
        }
        return $this->render('AdminBundle:MainAdmin/Subjects:subjectsListTable.html.twig', array(
                    'subjectsToPass' => $subjectsToPass,
                    'class' => $classId,
                    'actionFlag' => 'leftTable',
                    'division' => $dividionId));
    }

    public function subjectsListLinkTableAction($classId, $dividionId) {
        $em = $this->getDoctrine()->getManager();
        $subjectsLinksArray = $em->getRepository("AdminBundle:SubjectClassLink")->findBy(array('classId' => $classId, 'divisionId' => $dividionId));
        if ($subjectsLinksArray) {
            foreach ($subjectsLinksArray as $subjectsLinkArray) {
                $subjectsLinks[] = $subjectsLinkArray->getSubjectId();
            }
        } else {
            $subjectsLinks = array();
        }
        return $this->render('AdminBundle:MainAdmin/Subjects:subjectsListTable.html.twig', array(
                    'subjectsToPass' => $subjectsLinks,
                    'class' => $classId,
                    'actionFlag' => 'rightTable',
                    'division' => $dividionId));
    }

    public function linkFromMasterToClassAction(Request $request, $classId, $dividionId) {
        $em = $this->getDoctrine()->getManager();
        $subjectsIds = $request->request->get('subjects');
        $class = $em->getRepository("AdminBundle:ClassRoom")->findOneById($classId);
        $division = $em->getRepository("AdminBundle:Division")->findOneById($dividionId);
        foreach ($subjectsIds as $subjectsId) {
            $subject = $em->getRepository("AdminBundle:Subjects")->findOneById($subjectsId);
            $subjectLink = new \AdminBundle\Entity\SubjectClassLink();
            $subjectLink->setClassId($class);
            $subjectLink->setDivisionId($division);
            $subjectLink->setSubjectId($subject);
            $em->persist($subjectLink);
        }
        $em->flush();
        return new JsonResponse(true);
    }

    public function removeSubjectClassLinkAction($classId, $dividionId, $subjectId) {
        $em = $this->getDoctrine()->getManager();
        $link = $em->getRepository("AdminBundle:SubjectClassLink")->findOneBy(array('classId' => $classId, 'divisionId' => $dividionId, 'subjectId' => $subjectId));
        $em->remove($link);
        $em->flush();
        return $this->redirect($this->generateUrl('add_subject_table', array('class' => $classId, 'division' => $dividionId)));
    }

}


text:
//
//  ItemView.m
//  EtsySearch
//
//  Created by Pablo Padilla on 5/18/14.
//  Copyright (c) 2014 pgpbpadilla. All rights reserved.
//

#import "ESItemView.h"

@implementation ESItemView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _imageView.image = nil;
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
#ifndef __Q_MITK_SLICE_NAVIGATION_LISTENER_H
#define __Q_MITK_SLICE_NAVIGATION_LISTENER_H

#include <mitkTimeGeometry.h>
#include <mitkPoint.h>

#include <itkEventObject.h>

#include <QObject>

#include <org_mitk_gui_qt_common_Export.h>

namespace itk
{
  class Object;
}

namespace mitk
{
  class SliceNavigationController;
  struct IRenderWindowPart;
}

/** @brief Helper class to allow QmitkAbstractView and derived classes to react on changes of the slice/time navigation.
 Purpose of the class to be used in view and to give the respective view class (by composition) the posibility to react
 on changes of the currently selected timepoint or position in the world geometry.\n
 It also offers convinient signals that are only triggered when the selected timepoint or the selected possition of the
 active render window have realy changed.\n
 In order to setup this class properly the following things must be regarded:
 - View class must also derive public from mitk::IRenderWindowPartListener
 - View class must implement void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) and pass the renderWindowPart to the listener.

    void QmitkMyView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
    {
      this->m_SliceNavigationListener.RenderWindowPartActivated(renderWindowPart);
    }

 - View class must implement void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) and pass the renderWindowPart to the listener.

    void QmitkMyView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)
    {
    this->m_SliceNavigationListener.RenderWindowPartDeactivated(renderWindowPart);
    }

 - View class must pass its on render window part in its CreateQtPartControl(QWidget* parent)

    this->m_SliceNavigationListener.RenderWindowPartActivated(this->GetRenderWindowPart());

 - View class must connect the SliceChanged signal of the listener as see fit.
*/
class MITK_QT_COMMON QmitkSliceNavigationListener : public QObject
  {
    Q_OBJECT

  public:
    QmitkSliceNavigationListener();
    ~QmitkSliceNavigationListener() override;

    mitk::TimePointType GetCurrentSelectedTimePoint() const;
    mitk::Point3D GetCurrentSelectedPosition() const;

  signals:
    /** Signal triggered as soon as there is any change. It may be a change in the position/slice or of the selected timepoint.*/
    void SliceChanged();
    /** Convinience signal that can be used if you are only interested in changes of the current selected time point.
     Changes in spatial position will be ignored.*/
    void SelectedTimePointChanged(const mitk::TimePointType& newTimePoint);
    /** Convinience signal that can be used if you are only interested in changes of the current selected position.
     Changes in time will be ignored.*/
    void SelectedPositionChanged(const mitk::Point3D& newPoint);

  public slots:
    void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart);
    void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart);

  protected slots:
      /** Overwrite function to implement the behavior on slice/time changes. */
      void OnSliceChangedDelayed();

  protected:

    /**	@brief Calls OnSliceChangedDelayed so the event isn't triggered multiple times. */
    void OnSliceChangedInternal(const itk::EventObject& e);

    void OnSliceNavigationControllerDeleted(const itk::Object* sender, const itk::EventObject& /*e*/);

    /** Initializes and sets the observers that are used to monitor changes in the selected position
    or time point in order to actualize the view.h*/
    bool InitObservers();
    void RemoveObservers(const mitk::SliceNavigationController* deletedSlicer);
    /** Removes all observers of the deletedPart. If null pointer is passed all observers will be removed.*/
    void RemoveAllObservers(mitk::IRenderWindowPart* deletedPart = nullptr);

    mitk::IRenderWindowPart* m_renderWindowPart;

    // Needed for observing the events for when a slice or time step is changed.
    bool m_PendingSliceChangedEvent;

    /**Helper structure to manage the registered observer events.*/
    struct ObserverInfo
    {
      mitk::SliceNavigationController* controller;
      int observerTag;
      std::string renderWindowName;
      mitk::IRenderWindowPart* renderWindowPart;

      ObserverInfo(mitk::SliceNavigationController* controller, int observerTag,
        const std::string& renderWindowName, mitk::IRenderWindowPart* part);
    };

    typedef std::multimap<const mitk::SliceNavigationController*, ObserverInfo> ObserverMapType;
    ObserverMapType m_ObserverMap;

    mitk::Point3D m_CurrentSelectedPosition;
    mitk::TimePointType m_CurrentSelectedTimePoint;
  };

#endif


text:
package libj.poi.plugin;

import java.text.DecimalFormat;
import java.util.Date;

import libj.error.RuntimeError;
import libj.poi.Plugin;
import libj.utils.App;
import libj.utils.Cal;
import libj.utils.Text;
import libj.xml.XMLSchema;

public class Formatter implements Plugin {

	private static String formatDate = "formatDate";
	private static String formatDouble = "formatDouble";

	public boolean hasFunc(String funcName) {

		return Text.isEqualsAny(funcName, formatDate, formatDouble);
	}

	public String call(String funcName, Object[] args) throws Exception {

		if (funcName.equals(formatDate)) {
			return formatDate(args);
		} else if (funcName.equals(formatDouble)) {
			return formatDouble(args);
		} else {
			throw new RuntimeError("Invalid function: %s.%s", App.thisClassSimpleName(), funcName);
		}
	}

	private String formatDate(Object[] args) throws Exception {

		Date date;

		if (args[0] instanceof Date) {
			date = (Date)args[0];
		} else if (args[0] instanceof String) {
			date = (Date) XMLSchema.createObject(Date.class, (String) args[0]);
		} else {
			throw new RuntimeError("Invalid date: %s", args[0].toString());
		}

		String format = args[1].toString();

		return Cal.formatDate(date, format);
	}

	private String formatDouble(Object[] args) throws Exception {

		Double number;

		if (args[0] instanceof Date) {
			number = (Double) args[0];
		} else if (args[0] instanceof String) {
			number = (Double) XMLSchema.createObject(Double.class, (String) args[0]);
		} else {
			throw new RuntimeError("Invalid double: %s", args[0].toString());
		}

		String format = args[1].toString();

		DecimalFormat df = new DecimalFormat(format);

		return df.format(number);
	}

}


text:
@interface OtherSayingTableViewCell ()
@property (strong, nonatomic) IBOutlet UILabel *saying;

@property (strong, nonatomic) IBOutlet UIImageView *titleImage;

@property (strong, nonatomic) IBOutlet UILabel *timeLable;

@end

@implementation OtherSayingTableViewCell

-(void)setModel:(otherModel *)model{

    self.saying.text = model.comment_public;
    [self.titleImage sd_setImageWithURL:[NSURL URLWithString:model.client_avatar]];
    self.timeLable.text = model.datetime_formatted;

}

- (void)awakeFromNib {
    // Initialization code

    self.titleImage.layer.cornerRadius = 20;
    self.titleImage.clipsToBounds = YES;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
<?php

class Phake_Matchers_IgnoreRemainingMatcherTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Phake_Matchers_AnyParameters
     */
    private $matcher;

    public function setUp()
    {
        $this->matcher = new Phake_Matchers_IgnoreRemainingMatcher();
    }

    public static function matchesDataProvider()
    {
        return array(
            array(array()),
            array(array('foo')),
            array(array('foo', 'bar')),
        );
    }

    /**
     * @dataProvider matchesDataProvider
     */
    public function testMatches($arg)
    {
        $this->assertNull($this->matcher->doArgumentsMatch($arg));
    }

    public function testToString()
    {
        $this->assertEquals('<any parameters>', $this->matcher->__toString());
    }

    public function testSetNextThrowsInvalidException()
    {
        $this->setExpectedException('InvalidArgumentException', 'Other matchers cannot be checked after you ignore remaining parameters.');
        $this->matcher->setNextMatcher(Phake::mock('Phake_Matchers_IChainableArgumentMatcher'));
    }
}


text:
#include "d3d9.hpp"

#include <algorithm>
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>

#include <windows.h>
#include <winnt.h>
#include <winternl.h>

#include <d3d9.h>

#include <hadesmem/config.hpp>
#include <hadesmem/detail/detour_ref_counter.hpp>
#include <hadesmem/detail/last_error_preserver.hpp>
#include <hadesmem/detail/winternl.hpp>
#include <hadesmem/find_procedure.hpp>
#include <hadesmem/patcher.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/region.hpp>

#include "callbacks.hpp"
#include "direct_3d_9.hpp"
#include "helpers.hpp"
#include "main.hpp"
#include "module.hpp"

namespace
{
class D3D9Impl : public hadesmem::cerberus::D3D9Interface
{
public:
  virtual std::size_t RegisterOnFrame(
    std::function<hadesmem::cerberus::OnFrameD3D9Callback> const& callback)
    final
  {
    auto& callbacks = hadesmem::cerberus::GetOnFrameD3D9Callbacks();
    return callbacks.Register(callback);
  }

  virtual void UnregisterOnFrame(std::size_t id) final
  {
    auto& callbacks = hadesmem::cerberus::GetOnFrameD3D9Callbacks();
    return callbacks.Unregister(id);
  }

  virtual std::size_t RegisterOnReset(
    std::function<hadesmem::cerberus::OnResetD3D9Callback> const& callback)
    final
  {
    auto& callbacks = hadesmem::cerberus::GetOnResetD3D9Callbacks();
    return callbacks.Register(callback);
  }

  virtual void UnregisterOnReset(std::size_t id) final
  {
    auto& callbacks = hadesmem::cerberus::GetOnResetD3D9Callbacks();
    return callbacks.Unregister(id);
  }

  virtual std::size_t RegisterOnRelease(
    std::function<hadesmem::cerberus::OnReleaseD3D9Callback> const& callback)
    final
  {
    auto& callbacks = hadesmem::cerberus::GetOnReleaseD3D9Callbacks();
    return callbacks.Register(callback);
  }

  virtual void UnregisterOnRelease(std::size_t id) final
  {
    auto& callbacks = hadesmem::cerberus::GetOnReleaseD3D9Callbacks();
    return callbacks.Unregister(id);
  }
};

std::unique_ptr<hadesmem::PatchDetour>&
  GetDirect3DCreate9Detour() HADESMEM_DETAIL_NOEXCEPT
{
  static std::unique_ptr<hadesmem::PatchDetour> detour;
  return detour;
}

std::unique_ptr<hadesmem::PatchDetour>&
  GetDirect3DCreate9ExDetour() HADESMEM_DETAIL_NOEXCEPT
{
  static std::unique_ptr<hadesmem::PatchDetour> detour;
  return detour;
}

std::pair<void*, SIZE_T>& GetD3D9Module() HADESMEM_DETAIL_NOEXCEPT
{
  static std::pair<void*, SIZE_T> module{};
  return module;
}

extern "C" IDirect3D9* WINAPI
  Direct3DCreate9Detour(UINT sdk_version) HADESMEM_DETAIL_NOEXCEPT
{
  auto& detour = GetDirect3DCreate9Detour();
  auto const ref_counter =
    hadesmem::detail::MakeDetourRefCounter(detour->GetRefCount());
  hadesmem::detail::LastErrorPreserver last_error_preserver;

  HADESMEM_DETAIL_TRACE_FORMAT_A("Args: [%u].", sdk_version);

  auto const direct3d_create_9 =
    detour->GetTrampoline<decltype(&Direct3DCreate9Detour)>();
  last_error_preserver.Revert();
  auto ret = direct3d_create_9(sdk_version);
  last_error_preserver.Update();

  HADESMEM_DETAIL_TRACE_FORMAT_A("Ret: [%p].", ret);

  if (ret)
  {
    HADESMEM_DETAIL_TRACE_A("Succeeded.");
    HADESMEM_DETAIL_TRACE_A("Proxying IDirect3D9.");
    ret = new hadesmem::cerberus::Direct3D9Proxy(ret);
  }
  else
  {
    HADESMEM_DETAIL_TRACE_A("Failed.");
  }

  return ret;
}

extern "C" HRESULT WINAPI
  Direct3DCreate9ExDetour(UINT sdk_version,
                          IDirect3D9Ex** d3d9_ex) HADESMEM_DETAIL_NOEXCEPT
{
  auto& detour = GetDirect3DCreate9ExDetour();
  auto const ref_counter =
    hadesmem::detail::MakeDetourRefCounter(detour->GetRefCount());
  hadesmem::detail::LastErrorPreserver last_error_preserver;

  HADESMEM_DETAIL_TRACE_FORMAT_A("Args: [%u] [%p].", sdk_version, d3d9_ex);
  auto const direct3d_create_9_ex =
    detour->GetTrampoline<decltype(&Direct3DCreate9ExDetour)>();
  last_error_preserver.Revert();
  auto const ret = direct3d_create_9_ex(sdk_version, d3d9_ex);
  last_error_preserver.Update();
  HADESMEM_DETAIL_TRACE_FORMAT_A("Ret: [%p].", ret);

  if (SUCCEEDED(ret))
  {
    HADESMEM_DETAIL_TRACE_A("Succeeded.");
    HADESMEM_DETAIL_TRACE_A("Proxying IDirect3D9Ex.");
    *d3d9_ex = static_cast<IDirect3D9Ex*>(
      static_cast<void*>(new hadesmem::cerberus::Direct3D9Proxy(*d3d9_ex)));
  }
  else
  {
    HADESMEM_DETAIL_TRACE_A("Failed.");
  }

  return ret;
}
}

namespace hadesmem
{
namespace cerberus
{
Callbacks<OnFrameD3D9Callback>& GetOnFrameD3D9Callbacks()
{
  static Callbacks<OnFrameD3D9Callback> callbacks;
  return callbacks;
}

Callbacks<OnResetD3D9Callback>& GetOnResetD3D9Callbacks()
{
  static Callbacks<OnResetD3D9Callback> callbacks;
  return callbacks;
}

Callbacks<OnReleaseD3D9Callback>& GetOnReleaseD3D9Callbacks()
{
  static Callbacks<OnReleaseD3D9Callback> callbacks;
  return callbacks;
}

D3D9Interface& GetD3D9Interface() HADESMEM_DETAIL_NOEXCEPT
{
  static D3D9Impl d3d9_impl;
  return d3d9_impl;
}

void InitializeD3D9()
{
  InitializeSupportForModule(L"D3D9", DetourD3D9, UndetourD3D9, GetD3D9Module);
}

void DetourD3D9(HMODULE base)
{
  auto const& process = GetThisProcess();
  auto& module = GetD3D9Module();
  if (CommonDetourModule(process, L"D3D9", base, module))
  {
    DetourFunc(process,
               base,
               "Direct3DCreate9",
               GetDirect3DCreate9Detour(),
               Direct3DCreate9Detour);
    DetourFunc(process,
               base,
               "Direct3DCreate9Ex",
               GetDirect3DCreate9ExDetour(),
               Direct3DCreate9ExDetour);
  }
}

void UndetourD3D9(bool remove)
{
  auto& module = GetD3D9Module();
  if (CommonUndetourModule(L"D3D9", module))
  {
    UndetourFunc(L"Direct3DCreate9", GetDirect3DCreate9Detour(), remove);
    UndetourFunc(L"Direct3DCreate9Ex", GetDirect3DCreate9ExDetour(), remove);

    module = std::make_pair(nullptr, 0);
  }
}
}
}


text:
'use strict';
app.controller('mealsController', ['$scope', '$location', 'mealsService', function ($scope, $location, mealsService) {

    $scope.meals = [];
    $scope.filter = mealsService.filter;
    $scope.errorWrapper = mealsService.errorWrapper;

    var refreshFunction = function () {
        mealsService.refreshMeals().then(function () {
            $scope.meals = mealsService.meals;
        }, function (error) {
        });
    };

    refreshFunction();

    $scope.refreshMeals = refreshFunction;

    $scope.addMeal = function () {
        mealsService.displayEditMeal();
    };

    $scope.editMeal = function (meal) {
        mealsService.displayEditMeal(meal);
    };

    $scope.deleteMeal = function (meal) {
        mealsService.deleteMeal(meal);
    };

    $scope.filterClicked = function ($event) {
        $scope.filter.isFilterActive = !$scope.filter.isFilterActive;
        if (!$scope.filter.isFilterActive) {
            $scope.filter.clearDates();
            $scope.filter.clearTimes();
            $scope.filter.exportToQueryString();
            $scope.refreshMeals();
        }
    };

    $scope.filterDateClicked = function ($event) {
        $scope.filter.isFilterDateActive = !$scope.filter.isFilterDateActive;
        if (!$scope.filter.isFilterDateActive) {
            $scope.filter.clearDates();
            $scope.filter.exportToQueryString();
            $scope.refreshMeals();
        }
    };

    $scope.filterTimeClicked = function ($event) {
        $scope.filter.isFilterTimeActive = !$scope.filter.isFilterTimeActive;
        if (!$scope.filter.isFilterTimeActive) {
            $scope.filter.clearTimes();
            $scope.filter.exportToQueryString();
            $scope.refreshMeals();
        }
    };

    $scope.datePicker = {};
    $scope.datePicker.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();
        if($event.srcElement.id=="from")
            $scope.openedFrom = true;
        else
            $scope.openedTo = true;
    };

    $scope.datePicker.dateOptions = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.timeChanged = function()
    {
        if ($scope.filter.timeFrom != null || $scope.filter.timeTo != null)
            $scope.filter.isFilteredDataLoaded = false;
    }
}]);


text:
"use strict";
/**
 * Angular wrapper for velocityjs animation library
 * @requires velocityjs {@link https://github.com/julianshapiro/velocity}
 * @module sn.velocity
 * @author SOON_
 */
angular.module("sn.velocity", [
    "sn.velocity.snVelocity",
    "sn.velocity.snVelocityGroup",
    "sn.velocity.snVelocityToggle"
]);


text:
<?php

declare(strict_types=1);

namespace Set005;

class Greeter
{
    public function greet(): string
    {
        return 'Hello world!';
    }
}


text:
Let's suppose that there are two groups of people. A man maybe in both groups.
It's needed to find the first man from the first group who is in the second group too.

###### Algorithm
Given two lists, it's required to find the first element from the first list which is contained in the second list.
We need to go through the first list until the first occurrence of the element in the second list.

**[Main class which runs all the examples](SearchApp.scala)**

#### Java

```java
public static Optional<Man> search(List<Man> firstGroup, List<Man> secondGroup)  {
    for (Man manFromFirstGroup : firstGroup) {
        if (!secondGroup.contains(manFromFirstGroup)){
            continue;
        }

        return Optional.of(manFromFirstGroup);
    }

    return Optional.empty();
}
```

* [Search with Java](JavaSearch.java) full code example

#### Scala

```scala
@tailrec
def search(firstGroup: Seq[Man], secondGroup: Seq[Man]): Option[Man] = {

  firstGroup match {
    case manFromFirstGroup :: rest =>
      secondGroup.find(manFromSecondGroup => manFromFirstGroup == manFromSecondGroup) match {
        case foundPerson@Some(man) => foundPerson
        case None => search(rest, secondGroup)
      }
      case Nil => None
    }
}
```

* [Functional search with scala](ScalaFunctionalSearch.scala) full code example
* [Procedural search with scala](ScalaProceduralSearch.scala) full code example


text:
from pyforms import conf
import logging, traceback
logger = logging.getLogger(__file__)

if conf.PYFORMS_MODE in ['GUI','GUI-OPENCSP']:

	from pyforms.gui.Controls.ControlBase 			import ControlBase
	from pyforms.gui.Controls.ControlText 			import ControlText
	from pyforms.gui.Controls.ControlBoundingSlider import ControlBoundingSlider
	from pyforms.gui.Controls.ControlButton 		import ControlButton
	from pyforms.gui.Controls.ControlCheckBoxList 	import ControlCheckBoxList
	from pyforms.gui.Controls.ControlCheckBox 		import ControlCheckBox
	from pyforms.gui.Controls.ControlCombo 			import ControlCombo
	from pyforms.gui.Controls.ControlDir 			import ControlDir
	from pyforms.gui.Controls.ControlDockWidget 	import ControlDockWidget
	from pyforms.gui.Controls.ControlEmptyWidget 	import ControlEmptyWidget
	from pyforms.gui.Controls.ControlFile 			import ControlFile
	from pyforms.gui.Controls.ControlFilesTree 		import ControlFilesTree
	from pyforms.gui.Controls.ControlLabel 			import ControlLabel
	from pyforms.gui.Controls.ControlList 			import ControlList
	from pyforms.gui.Controls.ControlMdiArea 		import ControlMdiArea
	from pyforms.gui.Controls.ControlNumber 		import ControlNumber

	try:
		from pyforms.gui.Controls.ControlMatplotlib 	import ControlMatplotlib
	except:
		print("Matplot lib not installed or not working properly")
		logger.debug(traceback.format_exc())

	try:
		from pyforms.gui.Controls.ControlWeb 			import ControlWeb
	except:
		print("QtWebKit lib not installed or not working properly")
		logger.debug(traceback.format_exc())

	try:
		from pyforms.gui.Controls.ControlOpenGL 		import ControlOpenGL
		from pyforms.gui.Controls.ControlImage 			import ControlImage
		from pyforms.gui.Controls.ControlPlayer.ControlPlayer 	import ControlPlayer
	except:
		print("GL widgets or Opencv not installed")
		logger.debug(traceback.format_exc())

	from pyforms.gui.Controls.ControlProgress 		import ControlProgress
	from pyforms.gui.Controls.ControlSlider 		import ControlSlider
	from pyforms.gui.Controls.ControlTextArea 		import ControlTextArea
	from pyforms.gui.Controls.ControlToolBox 		import ControlToolBox
	from pyforms.gui.Controls.ControlTree 			import ControlTree
	from pyforms.gui.Controls.ControlTreeView 		import ControlTreeView
	try:
		from pyforms.gui.Controls.ControlVisVis 		import ControlVisVis
		from pyforms.gui.Controls.ControlVisVisVolume 	import ControlVisVisVolume
	except:
		print("VisVis not installed")
		logger.debug(traceback.format_exc())
	from pyforms.gui.Controls.ControlEventTimeline.ControlEventTimeline 	import ControlEventTimeline
	from pyforms.gui.Controls.ControlEventsGraph.ControlEventsGraph 	import ControlEventsGraph

	try:
		from pyforms.gui.Controls.ControlCodeEditor 		import ControlCodeEditor
	except:
		print("QScintilla2 not installed")
		logger.debug(traceback.format_exc())

elif conf.PYFORMS_MODE in ['TERMINAL']:

	from pyforms.terminal.Controls.ControlBase 			import ControlBase
	from pyforms.terminal.Controls.ControlText 			import ControlText
	from pyforms.terminal.Controls.ControlButton 		import ControlButton
	from pyforms.terminal.Controls.ControlCheckBox 		import ControlCheckBox
	from pyforms.terminal.Controls.ControlCombo 		import ControlCombo
	from pyforms.terminal.Controls.ControlFile 			import ControlFile
	from pyforms.terminal.Controls.ControlDir 			import ControlDir
	from pyforms.terminal.Controls.ControlImage 		import ControlImage
	from pyforms.terminal.Controls.ControlSlider 		import ControlSlider
	from pyforms.terminal.Controls.ControlPlayer 		import ControlPlayer
	from pyforms.terminal.Controls.ControlProgress 		import ControlProgress

elif conf.PYFORMS_MODE in ['WEB']:

	from pyforms_web.web.Controls.ControlBase 			import ControlBase
	from pyforms_web.web.Controls.ControlText 			import ControlText
	from pyforms_web.web.Controls.ControlBoundingSlider import ControlBoundingSlider
	from pyforms_web.web.Controls.ControlDate 			import ControlDate
	from pyforms_web.web.Controls.ControlButton 		import ControlButton
	from pyforms_web.web.Controls.ControlCheckBox 		import ControlCheckBox
	from pyforms_web.web.Controls.ControlCombo 			import ControlCombo
	from pyforms_web.web.Controls.ControlDir 			import ControlDir
	from pyforms_web.web.Controls.ControlFile 			import ControlFile
	from pyforms_web.web.Controls.ControlImage 			import ControlImage
	from pyforms_web.web.Controls.ControlSlider 		import ControlSlider
	from pyforms_web.web.Controls.ControlPlayer	 		import ControlPlayer
	from pyforms_web.web.Controls.ControlProgress 		import ControlProgress
	from pyforms_web.web.Controls.ControlVisVis			import ControlVisVis
	from pyforms_web.web.Controls.ControlList 			import ControlList
	from pyforms_web.web.Controls.ControlLabel 			import ControlLabel
	from pyforms_web.web.Controls.ControlTimeout 		import ControlTimeout
	from pyforms_web.web.Controls.ControlEmptyWidget	import ControlEmptyWidget
	from pyforms_web.web.Controls.ControlWorkflow		import ControlWorkflow


text:
from __future__ import absolute_import
from __future__ import division

import click

from guild import click_util

@click.command("list, ls")
@click.argument("terms", metavar="[TERM]...", nargs=-1)
@click.option("-a", "--all", help="Show all installed Python packages.", is_flag=True)
@click_util.use_args
def list_packages(args):
    """List installed packages.

    Specify one or more `TERM` arguments to show packages matching any
    of the specified values.

    """
    from . import packages_impl

    packages_impl.list_packages(args)


text:
<?php
namespace Rails\Assets\File;

abstract class Copy extends File
{
    public static function getNeighbor(File $origin, $filename)
    {
        if (!self::isSameType($origin, $filename)) {
            return false;
        }

        $filename  = str_replace('\\', '/', $filename);
        $nameParts = explode(
            '.',
            pathinfo($filename, PATHINFO_BASENAME)
        );

        $subPaths  = explode('/', trim(
            substr($filename, strlen(
                pathinfo($origin->originalFilePath(), PATHINFO_DIRNAME)
            )),
            '/'
        ));
        array_pop($subPaths);

        $neighbor             = clone $origin;
        $neighbor->name       = array_shift($nameParts);
        $neighbor->extensions = $nameParts;
        $neighbor->subPaths   = $subPaths;
        $neighbor->originalFilePath = $filename;
        return $neighbor;
    }

    public static function isSameType(File $origin, $filename)
    {
        $extensions = explode(
            '.',
            pathinfo($filename, PATHINFO_BASENAME)
        );
        array_shift($extensions);
        return $origin->type() == array_shift($extensions);
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Workout = mongoose.model('Workout'),
	_ = require('lodash');

/**
 * Get the error message from error object
 */
var getErrorMessage = function (err) {
    var message = '';

    if (err.code) {
        switch (err.code) {
            case 11000:
            case 11001:
                message = 'Workout already exists';
                break;
            default:
                message = 'Something went wrong';
        }
    } else {
        for (var errName in err.errors) {
            if (err.errors[errName].message) message = err.errors[errName].message;
        }
    }

    return message;
};

/**
 * Create a workout
 */
exports.create = function (req, res) {
    var workout = new Workout(req.body);
    workout.user = req.user;

    workout.save(function (err) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(workout);
        }
    });
};

/**
 * Show the current workout
 */
exports.read = function (req, res) {
    res.jsonp(req.workout);
};

/**
 * Update a workout
 */
exports.update = function (req, res) {
    var workout = req.workout;

    workout = _.extend(workout, req.body);

    workout.save(function (err) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(workout);
        }
    });
};

/**
 * Delete a workout
 */
exports.delete = function (req, res) {
    var workout = req.workout;

    workout.remove(function (err) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(workout);
        }
    });
};

/**
 * List of Workouts
 */

exports.list = function (req, res) {
    Workout.find().sort('-created').populate('user', 'displayName').exec(function (err, workouts) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(workouts);
        }
    });
};

/**
 * Workout middleware
 */
exports.workoutByID = function (req, res, next, id) {
    Workout.findById(id).populate('user', 'displayName').exec(function (err, workout) {
        if (err) return next(err);
        if (!workout) return next(new Error('Failed to load workout ' + id));
        req.workout = workout;
        next();
    });
};

/**
 * Workout authorization middleware
 */
exports.hasAuthorization = function (req, res, next) {
    /*if (req.workout.user.id !== req.user.id) {
		return res.send(403, {
			message: 'User is not authorized'
		});
	}*/
    next();
};


text:
A little DSL for writing [react.js](http://facebook.github.io/react/) components as [PogoScript](http://pogoscript.org) CommonJS modules, instead of using [JSX](http://facebook.github.io/react/docs/jsx-in-depth.html)

## Usage

Start with a module looking like this:

    module.exports = component {
        render () =
            div (
                p { id = 'para' } "First paragraph"
                p { class = 'zomg' } "Second paragraph"
            )
    }

...compile it to JavaScript like this:

    require('pogo-react').compile! ("./component.pogo", "./component.js")

...then use it from React like this:

    Component = require('./component.js')
    instance = Component { prop = 'value' }
    React.renderComponent(instance, document.body)

## License

BSD