text:
package org.slc.sli.dal.aspect;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

import com.mongodb.DBCollection;

import org.apache.commons.lang3.tuple.Pair;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;

import org.slc.sli.common.util.tenantdb.TenantContext;
import org.slc.sli.dal.MongoStat;

/**
 * Tracks calls to mongo template and mongo driver
 * Collects performance information.
 * Logs slow queries
 *
 * @author dkornishev
 *
 */
@Aspect
@SuppressWarnings("PMD.MoreThanOneLogger")
public class MongoTrackingAspect {

    private static final Logger LOG = LoggerFactory.getLogger(MongoTrackingAspect.class);

    private static final Logger PERF_LOG = LoggerFactory.getLogger("MongoPerformance");

    private static final long SLOW_QUERY_THRESHOLD = 50;  // ms

    private static boolean enabled = false;

    @Value("${sli.api.performance.tracking}")
    private String dbCallTracking;

    @Value("${sli.mongo.tracking}")
    public void setEnabledConfig(String enabledConfig) {
        setEnabled(enabledConfig);
    }

    @Value("${sli.mongo.tracking.interval.seconds}")
    private String trackingInterval;

    @Autowired
    private MongoStat dbCallTracker;

    @SuppressWarnings("boxing")
    private static void setEnabled(String enabledConfig) {
        enabled = Boolean.valueOf(enabledConfig);
    }

    private static boolean isEnabled() {
        return enabled;
    }

    // Map<jobId, Map<(db,function,collection), (opCount,totalElapsedMs)>>
    private ConcurrentMap<String, Pair<AtomicLong, ConcurrentMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>>>> stats = new ConcurrentHashMap<String, Pair<AtomicLong, ConcurrentMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>>>>();

    @Around("call(* org.springframework.data.mongodb.core.MongoTemplate.*(..)) && !this(MongoTrackingAspect) && !within(org..*Test) && !within(org..*MongoPerfRepository)")
    public Object track(ProceedingJoinPoint pjp) throws Throwable {

        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        if (isEnabled()) {
            MongoTemplate mt = (MongoTemplate) pjp.getTarget();
            String collection = determineCollectionName(pjp);
            proceedAndTrack(pjp, mt.getDb().getName(), pjp.getSignature().getName(), collection, start, end);
        }
        if (Boolean.valueOf(dbCallTracking)) {
            dbCallTracker.incrementHitCount();
            // dbCallTracker.addMetric("t", pjp.getSignature().toShortString(), end-start);
        }

        return result;
    }

    @Around("call(* com.mongodb.DBCollection.*(..)) && !this(MongoTrackingAspect) && !within(org..*Test) && !within(org..*MongoPerfRepository)")
    public Object trackDBCollection(ProceedingJoinPoint pjp) throws Throwable {

        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        if (isEnabled()) {
            DBCollection col = (DBCollection) pjp.getTarget();
            proceedAndTrack(pjp, col.getDB().getName(), pjp.getSignature().getName(), col.getName(), start, end);
        }
        if (Boolean.valueOf(dbCallTracking)) {
            dbCallTracker.incrementHitCount();
            // dbCallTracker.addMetric("t", pjp.getSignature().toShortString(), end-start);
        }
        return result;
    }

    /**
     * Track calls in the various implementation of the Repository interface.
     */

    // Note: This is commented out, because it incurs overhead at runtime
    // @Around("call(* org.slc.sli.domain.Repository+.*(..)) && !this(MongoTrackingAspect) && !within(org..*Test) && !within(org..*MongoPerfRepository)")
    public Object trackDALCalls(ProceedingJoinPoint pjp) throws Throwable {
        return trackCalls(pjp);
    }

    private Object trackCalls(ProceedingJoinPoint pjp) throws Throwable {

        Object result;
        if (Boolean.valueOf(dbCallTracking)) {
            dbCallTracker.addEvent("s", pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName(), System.currentTimeMillis(), null);
            result = pjp.proceed();
            long end = System.currentTimeMillis();
            // capture the arguments
            Object[] callArgs = pjp.getArgs();
            List<String> args = new ArrayList<String>(callArgs.length);
            for(Object ca : callArgs) {
                args.add((null == ca) ? null : ca.getClass().getName() + ":" + ca.toString());
            }
            dbCallTracker.addEvent("e", "", end, args);
        }
        else {
            result = pjp.proceed();
        }

        return result;
    }

    private void proceedAndTrack(ProceedingJoinPoint pjp, String db, String function, String collection, long start,
            long end) throws Throwable {
        long elapsed = end - start;
        trackCallStatistics(db, function, collection, start, elapsed);

        logSlowQuery(elapsed, db, function, collection, pjp);

    }

    private void trackCallStatistics(String db, String function, String collection, long start, long elapsed) {
        String jobId = TenantContext.getJobId();

        if (jobId != null) {
            long trackingInt = Long.valueOf(trackingInterval) * 1000;
            if (trackingInt <= 0) {
                trackingInt = 1000;
            }

            long jobBegin = start;
            long startInt = start;

            // Init map for job.
            if (stats.get(jobId) == null) {
                ConcurrentMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>> jobStats = new ConcurrentHashMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>>();
                Pair<AtomicLong, ConcurrentMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>>> jobStatsPair = Pair
                        .of(new AtomicLong(start), jobStats);

                stats.putIfAbsent(jobId, jobStatsPair);

            } else if (stats.get(jobId).getLeft().get() == 0) {
                stats.get(jobId).getLeft().set(start);
            } else {
                jobBegin = stats.get(jobId).getLeft().get();
                startInt = ((stats.get(jobId).getRight().size() - 1) * trackingInt) + jobBegin;
            }

            // Init map for intervals.
            // FIXME: Calendar and SimpleDateFormat objects are expensive to create.
            // Can we just use epoch time from System.currentTimeMillis()
            String currJobInterval = null;
            long newInt = (((start - jobBegin) / trackingInt) * trackingInt) + jobBegin;
            if (newInt < startInt) {
                startInt = newInt;
            }
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
            while (newInt >= startInt) {
                long endInt = startInt + trackingInt;
                calendar.setTimeInMillis(startInt);
                String startTimeStamp = formatter.format(calendar.getTime());
                calendar.setTimeInMillis(endInt);
                String endTimeStamp = formatter.format(calendar.getTime());
                currJobInterval = String.format("%s - %s", startTimeStamp, endTimeStamp);
                stats.get(jobId).getRight()
                        .putIfAbsent(currJobInterval, new ConcurrentHashMap<String, Pair<AtomicLong, AtomicLong>>());
                startInt = endInt;
            }

            // Init map for stats.
            String collectionKeyName = collection.replaceAll("\\.", "DOT");
            String statsKey = String.format("%s#%s#%s", db, function, collectionKeyName);
            stats.get(jobId).getRight().get(currJobInterval)
                    .putIfAbsent(statsKey, Pair.of(new AtomicLong(0), new AtomicLong(0)));

            // Increment.
            Pair<AtomicLong, AtomicLong> pair = stats.get(jobId).getRight().get(currJobInterval).get(statsKey);
            pair.getLeft().incrementAndGet();
            pair.getRight().addAndGet(elapsed);

            PERF_LOG.info(function + "," + db + "," + collectionKeyName + "," + elapsed);
        }
    }

    private void logSlowQuery(long elapsed, String db, String function, String collection, ProceedingJoinPoint pjp) {
        if (elapsed > SLOW_QUERY_THRESHOLD) {
            LOG.debug(String.format("Slow query: %s#%s#%s (%d ms)", db, function, collection, elapsed));
        }
    }

    private String determineCollectionName(ProceedingJoinPoint pjp) {
        String collection = "UNKNOWN";
        Object[] args = pjp.getArgs();
        if (args.length > 0 && args[0] instanceof String) {
            collection = (String) args[0];
        } else if (args.length > 1 && args[1] instanceof String) {
            collection = (String) args[1];
        } else if (args.length > 2 && args[2] instanceof String) {
            collection = (String) args[2];
        }

        if (collection.lastIndexOf("_") > -1) {
            collection = collection.substring(0, collection.lastIndexOf("_"));
        }

        if (pjp.getSignature().getName().equals("executeCommand")) {
            collection = "EXEC-UNKNOWN";
        }
        return collection;
    }

    public Map<String, ? extends Map<String, Pair<AtomicLong, AtomicLong>>> getStats() {
        String jobId = TenantContext.getJobId();
        if ((jobId != null) && (this.stats.get(jobId) != null)) {
            return this.stats.get(jobId).getRight();
        }
        return null;
    }

    public void reset() {
        String jobId = TenantContext.getJobId();
        if (jobId != null) {
            ConcurrentMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>> jobStats = new ConcurrentHashMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>>();
            Pair<AtomicLong, ConcurrentMap<String, ConcurrentMap<String, Pair<AtomicLong, AtomicLong>>>> jobStatsPair = Pair
                    .of(new AtomicLong(0), jobStats);
            this.stats.put(jobId, jobStatsPair);
        }
        LOG.info("Mongo tracking stats are now cleared for job {}.", jobId);
    }

}


text:
clear:
	rm  src/vim/vim/plugins/vim-devicons/doc/tags

push:
	git add --all && git commit -m "$(shell date)" && git push --set-upstream origin master

redpajama_set_name: RedPajamaGithub


text:
Rencontre technologique du Saguenay—Lac-St-Jean

        {% include top_nav.html %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MultiProcess.Client
{
    using System.Windows;

    using MultiProcess.Client.EventArg;

    /// <summary>
    /// The player speed.
    /// </summary>
    public enum PlayerSpeed
    {
        /// <summary>
        /// The two x spped.
        /// </summary>
        TwoX,

        /// <summary>
        /// The three x speed.
        /// </summary>
        ThreeX,

        /// <summary>
        /// The four x speed.
        /// </summary>
        FourX,
    }

    /// <summary>
    /// The play direction.
    /// </summary>
    public enum PlayDirection
    {
        /// <summary>
        /// The forward direction.
        /// </summary>
        Forward,

        /// <summary>
        /// The reverse direction.
        /// </summary>
        Reverse,
    }

    /// <summary>
    /// This interface defines the player operations to be called from client.
    /// </summary>
    public interface IMediaPlayer : IDisposable
    {
        /// <summary>
        /// Setup the player object
        /// </summary>
        /// <returns>
        /// Player UI element
        /// </returns>
        UIElement SetupPlayerObject();

        /// <summary>
        /// Play live stream (MSTG only player)
        /// </summary>
        /// <returns>
        /// Play succeeded
        /// </returns>
        bool Play();

        /// <summary>
        /// Play recorded stream
        /// </summary>
        /// <param name="startTime">
        /// Start time for recorded
        /// </param>
        /// <param name="endTime">
        /// End time for recorded
        /// </param>
        /// <returns>
        /// Play succeeded
        /// </returns>
        bool Play(DateTime startTime, DateTime endTime);

        /// <summary>
        /// The pause.
        /// </summary>
        void Pause();

        /// <summary>
        /// Stop operation. This will also send teardown in case of rtsp playback.
        /// </summary>
        void Stop();

        /// <summary>
        /// The take snapshot.
        /// </summary>
        /// <param name="fileName">
        /// The file name.
        /// </param>
        void TakeSnapshot(string fileName);

        /// <summary>
        /// To clean up any used resources.
        /// </summary>
        /// <param name="retainProcessHost">
        /// Whether to retain the ProcessHost instance after this exit (RIC ONLY).
        /// </param>
        void Exit(bool retainProcessHost = false);

        /// <summary>
        /// Initialize with URI or other paramters
        /// </summary>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <returns>
        /// The initialize.
        /// </returns>
        bool Initialize(string uri);

        /// <summary>
        /// Checks whether SDK is installed or not
        /// </summary>
        /// <returns></returns>

        /// <summary>
        /// The streaming statistics updated.
        /// </summary>
        event EventHandler<StreamingStaticsEventArgs> StreamingStatisticsUpdated;

        /// <summary>
        ///   Indicates the status of a streaming channel for this media player
        /// </summary>
        event StreamingStatusEventHanlder StreamingStatusChanged;

        /// <summary>
        ///   This event is to handle the select event on the player object.
        /// </summary>
        event SelectEventHandler Selected;

        /// <summary>
        ///   This event is to handle the drag event on the player object.
        /// </summary>
        event DragStartEventHandler DragStart;

        /// <summary>
        ///   This event is to handle the drop event on the player object.
        /// </summary>
        event DragEventHandler Drop;

        /// <summary>
        /// The player error.
        /// </summary>
        event PlayerErrorEventHandler PlayerError;

        /// <summary>
        /// The play state changed.
        /// </summary>
        event PlayStateChangedEventHandler PlayStateChanged;

        /// <summary>
        /// The play position changed.
        /// </summary>
        event PlayPositionChangedEventHandler PlayPositionChanged;

        /// <summary>
        /// Gets the width.
        /// </summary>
        double Width { get; }

        /// <summary>
        /// Gets the height.
        /// </summary>
        double Height { get; }

    }

    /// <summary>
    /// The play position changed event handler.
    /// </summary>
    /// <param name="secondsBackFromEnd">
    /// The seconds back from end.
    /// </param>
    public delegate void PlayPositionChangedEventHandler(int secondsBackFromEnd);

    /// <summary>
    /// The play state changed event handler.
    /// </summary>
    /// <param name="playState">
    /// The play state.
    /// </param>
    public delegate void PlayStateChangedEventHandler(PlayState playState);

    /// <summary>
    /// The streaming status event handler.
    /// </summary>
    /// <param name="status">
    /// The status.
    /// </param>
    /// <param name="errorCode">
    /// The errorCode.
    /// </param>
    public delegate void StreamingStatusEventHanlder(ConnectionStatus status, string errorCode);

    /// <summary>
    /// The select event handler.
    /// </summary>
    /// <param name="sender">
    /// The sender.
    /// </param>
    /// <param name="e">
    /// The e.
    /// </param>
    public delegate void SelectEventHandler(object sender, EventArgs e);

    /// <summary>
    /// The drag start event handler.
    /// </summary>
    /// <param name="sender">
    /// The sender.
    /// </param>
    /// <param name="e">
    /// The e.
    /// </param>
    public delegate void DragStartEventHandler(object sender, EventArgs e);

    /// <summary>
    /// The player error event handler.
    /// </summary>
    /// <param name="sender">
    /// The sender.
    /// </param>
    /// <param name="e">
    /// The e.
    /// </param>
    public delegate void PlayerErrorEventHandler(object sender, PlayerErrorEventArgs e);
}


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="">
    <meta name="author" content="">

    <title>Akhil Gupta - about</title>

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

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

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://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>
                Home

                        Home

                        About

                        Recent Post

                        Contact

About Me

                        This is what I do.

 I am pre-final year student in SRM University. My motto is "Code Problems And Decode Life".

 I am interested in developing multilingual Natural Language Processing solutions and combining Corpus Linguistics and ML approaches to perform enterprise-level textual analysis

 Text classification

 Named entity recognition

 Sentimental analysis

                Focused on developing intelligent algorithmic analytical data solutions for different domains like retail, healthcare, finance, academia and eCommerce.

                Frameworks and languages.

                    well versed with Python, Django, and Javascipt. worked with Nosql Databases such as MongoDB, Cassandra and also deployed few application such as language model and entity tagger on graph database - Neo4j.

Copyright © Akhil Gupta 2016


text:
Lorem.NET for netstandard
=========================

A .NET library for all things random!  Updated to use a netstandard library (to give as wide support as possible).

[![Build status](https://ci.appveyor.com/api/projects/status/81i490v2mfq1h0gw/branch/master?svg=true)](https://ci.appveyor.com/project/trichards57/lorem-universal-net/branch/master)
[![Documentation Status](https://readthedocs.org/projects/loremdnxnet/badge/?version=latest)](https://loremdnxnet.readthedocs.io/en/latest/?badge=latest)
[![NuGet](https://img.shields.io/nuget/v/Lorem.Universal.NET.svg?maxAge=2592000)](https://www.nuget.org/packages/Lorem.Universal.NET/)

Usage
-----

### Text Helpers

```csharp
// this will generate a string with three words:
string words = LoremNET.Lorem.Words(3);

// this will generate a string with two to five words:
string words = LoremNET.Lorem.Words(2, 5);

// this will generate a string with five to ten words with "uppercaseFirstLetter" set to "false" and "includePunctuation" set to "true":
string words = LoremNET.Lorem.Words(5, 10, false, true);

// a sentence is the same as "Words" except that it will include punctuation by default and will include a "." at the end of a string:
string sentence = LoremNET.Lorem.Sentence(5, 10);

// a paragraph is a string composed of multiple sentences; this paragraph will have five to six words per sentence, and four to ten sentences:
string paragraph = LoremNET.Lorem.Paragraph(5, 6, 4, 10);

// paragraphs is an array of paragraphs; this method will have eight to nine words per sentence, four to five sentences per paragraph, and one to three paragraphs:
IEnumerable<string> paragraphs = LoremNET.Lorem.Paragraphs(8, 9, 4, 5, 1, 3);
```

Breaking Change : As of v4.0, anything returning an IEnumerable can no-longer be relied on to return a stable result over multiple iterations.  Technically IEnumerable<T> doesn't promise
this anyway, but previous version's implementation did produce a repeatable result.

Thanks to BaileyMillerSSI for pointing out the problem with the previous implementation and large results.

### Extras

```csharp
// this will generate a random valid email address:
string email = LoremNET.Lorem.Email();

// this will generate a random hex number (i.e. a color)
string hex = LoremNET.Lorem.HexNumber();

// this will generate a random DateTime object between 1/1/1950 and the current DateTime:
DateTime dateTime = LoremNET.Lorem.DateTime();

// this will generate a random DateTime object between 1/1/1995 and 12/31/2020:
DateTime dateTime = LoremNET.Lorem.DateTime(new DateTime(1995, 1, 1), new DateTime(2020, 12, 31))

// this will return "true" 55% of the time:
bool isTruth = LoremNET.Lorem.Chance(55, 100);

// this will randomly select an item from the group:
string[] numbers = GetNumbers();
string number = LoremNET.Lorem.Random(numbers);

// this will randomly select a value from the enum:
MyEnum value = LoremNET.Lorem.Enum<MyEnum>();

```

### RandomHelper

Lorem.NET includes a thread-safe System.Random instance.

```csharp
int i = LoremNET.RandomHelper.Instance.Next(1, 2);
```


text:
using System;
using System.Collections.Generic;
using BEPUphysics.BroadPhaseSystems;
using BEPUphysics.Entities;
using BEPUutilities;
using BEPUutilities.Threading;

namespace BEPUphysics.UpdateableSystems.ForceFields
{
    ///
    /// Superclass of objects which apply forces to entities in some field.
    ///
    public abstract class ForceField : Updateable, IDuringForcesUpdateable
    {
        private readonly Action<int> subfunction;
        private IList<Entity> affectedEntities;
        private float currentTimestep;
        private ForceFieldShape shape;

        ///
        /// Gets or sets whether or not threading is allowed.
        ///
        public bool AllowMultithreading { get; set; }

        ///
        /// Gets or sets the query accelerator used by the force field to find entities.
        ///
        public IQueryAccelerator QueryAccelerator { get; set; }
        ///
        /// Gets or sets the multithreaded looper used by the force field.
        ///
        public IParallelLooper ParallelLooper { get; set; }

        ///
        /// Constructs a force field.
        ///
        /// <param name="shape">Shape to use for the force field.</param>
        protected ForceField(ForceFieldShape shape)
        {
            Shape = shape;
            subfunction = new Action<int>(CalculateImpulsesSubfunction);
            AllowMultithreading = true;
        }

        ///
        /// Gets or sets whether the the force field will force affected entities to wake up.
        ///
        public bool ForceWakeUp { get; set; }

        ///
        /// Gets or sets the shape of the force field used to determine which entities to apply forces to.
        ///
        public ForceFieldShape Shape
        {
            get { return shape; }
            set
            {
                if (value != null && value.ForceField != null)
                    throw new ArgumentException("The force field shape already belongs to another force field.");
                //Get rid of my old shape.
                if (shape != null)
                {
                    shape.ForceField = null;
                }
                //Get my new shape!
                shape = value;
                if (shape != null)
                {
                    shape.ForceField = this;
                }
            }
        }

        ///
        /// Performs any custom logic desired prior to the force application.
        ///
        protected virtual void PreUpdate()
        {

        }

        ///
        /// Applies forces specified by the given calculation delegate to bodies in the volume.
        /// Called automatically when needed by the owning Space.
        ///
        /// <param name="dt">Time since the last frame in simulation seconds.</param>
        void IDuringForcesUpdateable.Update(float dt)
        {
            PreUpdate();
            affectedEntities = Shape.GetPossiblyAffectedEntities();
            if (AllowMultithreading && ParallelLooper != null && ParallelLooper.ThreadCount > 1)
            {
                currentTimestep = dt;
                ParallelLooper.ForLoop(0, affectedEntities.Count, subfunction);
            }
            else
            {
                currentTimestep = dt;
                //No multithreading, so do it directly.
                int count = affectedEntities.Count;
                for (int i = 0; i < count; i++)
                {
                    CalculateImpulsesSubfunction(i);
                }
            }
        }

        ///
        /// Calculates the impulse to apply to the entity.
        ///
        /// <param name="e">Affected entity.</param>
        /// <param name="dt">Duration between simulation updates.</param>
        /// <param name="impulse">Impulse to apply to the entity.</param>
        protected abstract void CalculateImpulse(Entity e, float dt, out Vector3 impulse);

        private void CalculateImpulsesSubfunction(int index)
        {
            Entity e = affectedEntities[index];
            if (e.isDynamic && (e.activityInformation.IsActive || ForceWakeUp) && Shape.IsEntityAffected(e))
            {
                if (ForceWakeUp)
                    e.activityInformation.Activate();
                Vector3 impulse;
                CalculateImpulse(e, currentTimestep, out impulse);
                e.ApplyLinearImpulse(ref impulse);
            }
        }

        ///
        /// Called after the object is added to a space.
        ///
        /// <param name="newSpace">Space to which the field has been added.</param>
        public override void OnAdditionToSpace(Space newSpace)
        {
            base.OnAdditionToSpace(newSpace);
            var space = newSpace;
            if(space != null)
            {
                ParallelLooper = space.ParallelLooper;
                QueryAccelerator = space.BroadPhase.QueryAccelerator;
            }
        }

        ///
        /// Called before an object is removed from its space.
        ///
        /// <param name="oldSpace">Space from which the object has been removed.</param>
        public override void OnRemovalFromSpace(Space oldSpace)
        {
            base.OnRemovalFromSpace(oldSpace);
            ParallelLooper = null;
            QueryAccelerator = null;
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TAlex.PowerCalc.ViewModels.Plot2D;

namespace TAlex.PowerCalc.Views
{
    /// <summary>
    /// Interaction logic for Traces2DWindow.xaml
    /// </summary>
    public partial class Traces2DWindow : Window
    {
        #region Properties

        public Traces2DModel Model
        {
            get { return (Traces2DModel)DataContext; }
        }

        #endregion

        #region Constructors

        public Traces2DWindow()
        {
            InitializeComponent();
        }

        public Traces2DWindow(Traces2DModel.StateMode mode, Trace2DCollection traces)
            : this()
        {
            Model.SetState(mode, traces);
            Model.Traces.CollectionChanged += Traces_CollectionChanged;
        }

        #endregion

        #region Event Handlers

        private void TracesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count > 0)
            {
                try
                {
                    if (Model.Traces.Contains(e.RemovedItems[0]))
                    {
                        Model.UpdateTrace((Trace2D)e.RemovedItems[0]);
                    }
                }
                catch (Exception exc)
                {
                    TracesList.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        TracesList.SelectionChanged -= TracesList_SelectionChanged;
                        TracesList.SelectedItem = e.RemovedItems[0];
                        TracesList.SelectionChanged += TracesList_SelectionChanged;
                        MessageBox.Show(this, exc.Message, Properties.Resources.MessageBoxCaptionText, MessageBoxButton.OK, MessageBoxImage.Error);
                    }));
                }
            }
        }

        private void Traces_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                TracesList.SelectedItem = (Trace2D)e.NewItems[0];
                expressionTextBox.Focus();
            }
        }

        #endregion
    }
}


text:
FROM python:3.4

ADD . /src
WORKDIR /src
RUN python setup.py install
CMD ["python", "test-script.py"]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Linn. Soc. , Bot. 10(no. 45): 293 (1868)

#### Original name
Hiatula caespitosa Berk. & M.A. Curtis

### Remarks
null


text:
import * as tl from 'vsts-task-lib/task';
import * as Q from 'q';
import * as querystring from "querystring";
import * as httpClient from 'vso-node-api/HttpClient';
import * as restClient from 'vso-node-api/RestClient';

var httpObj = new httpClient.HttpCallbackClient(tl.getVariable("AZURE_HTTP_USER_AGENT"));
var defaultAuthUrl = 'https://login.windows.net/';
var azureApiVersion = '2016-09-01';

function getAccessToken(SPN, endpointUrl: string): Q.Promise<string> {

	var deferred = Q.defer<string>();
	var envAuthUrl = (SPN.envAuthUrl) ? SPN.envAuthUrl : defaultAuthUrl;
	var authorityUrl = envAuthUrl + SPN.tenantID + "/oauth2/token/";

	var post_data = querystring.stringify({
		resource: endpointUrl,
		client_id: SPN.servicePrincipalClientID,
		grant_type: "client_credentials",
		client_secret: SPN.servicePrincipalKey
	});

	var requestHeader = {
		"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
	};

	tl.debug(`Requesting for bearer token ${authorityUrl}`);
	httpObj.send("POST", authorityUrl, post_data, requestHeader, (error, response, body) => {
		if(error) {
			deferred.reject(error);
		}
		else if (response.statusCode == 200) {
			deferred.resolve(JSON.parse(body).access_token);
		}
		else {
			deferred.reject(tl.loc("CouldNotFetchAcessToken", response.statusCode, response.statusMessage, body));
		};
	});

    return deferred.promise;
}

export async function getNetworkInterfacesInRG(SPN, endpointUrl: string, resourceGroupName: string) {

	var deferred = Q.defer<any>();
	var restUrl = SPN.url + "subscriptions/" + SPN.subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Network/networkInterfaces?api-version=" + azureApiVersion;
	var accessToken = await getAccessToken(SPN, endpointUrl);

	var requestHeader = {
		Authorization: 'Bearer ' + accessToken
	};

	tl.debug(`Getting all network interfaces in the resource group ${resourceGroupName}`);
	httpObj.get('GET', restUrl, requestHeader, (error, response, body) => {
		if(error) {
			deferred.reject(error);
		}
		else if(response.statusCode == 200) {
			deferred.resolve(JSON.parse(body).value);
		}
		else {
			deferred.reject(tl.loc("CouldNotFetchNetworkInterfacesInRg", resourceGroupName, response.statusCode, response.statusMessage, body));
		}

	});
	return deferred.promise;
}

export async function getLoadBalancer(SPN, endpointUrl: string, name: string, resourceGroupName: string) {

	var deferred = Q.defer<any>();
	var restUrl = SPN.url + "subscriptions/" + SPN.subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Network/loadBalancers/" + name + "?api-version=" + azureApiVersion;
	var accessToken = await getAccessToken(SPN, endpointUrl);

	var requestHeader = {
		authorization: 'Bearer ' + accessToken
	}

	tl.debug(`Getting the load balancer: ${name}`);
	httpObj.get('GET', restUrl, requestHeader, (error, response, body) => {
        if(error) {
            deferred.reject(error);
        }
        else if(response.statusCode === 200) {
            deferred.resolve(JSON.parse(body));
        }
        else {
        	deferred.reject(tl.loc("CouldNotFetchLoadBalancer", name, response.statusCode, response.statusMessage, body));
        }
    });

    return deferred.promise;
}

export async function getNetworkInterface(SPN, endpointUrl, name: string, resourceGroupName: string) {
	var deferred = Q.defer<any>();
	var restUrl = SPN.url + "subscriptions/" + SPN.subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Network/networkInterfaces/" + name + "?api-version=" + azureApiVersion;
	var accessToken = await getAccessToken(SPN, endpointUrl);

	var requestHeader = {
		authorization: 'Bearer ' + accessToken
	}

	tl.debug(`Getting the Network Interface: ${name}`);
	httpObj.get('GET', restUrl, requestHeader, (error, response, body) => {
        if(error) {
            deferred.reject(error);
        }
        else if(response.statusCode === 200) {
            deferred.resolve(JSON.parse(body));
        }
        else {
        	deferred.reject(tl.loc("CouldNotFetchNetworkInterface", name, response.statusCode, response.statusMessage, body));
        }
    });

    return deferred.promise;
}

async function checkProvisioningState(url: string, accessToken: string) {
	var deferred = Q.defer();
	var headers = {
		Authorization: "Bearer " + accessToken
	};
	httpObj.get("GET", url, headers, (error, response, body) => {
		if(error){
			deferred.reject(error);
		}
		else if(response.statusCode == 200) {
			deferred.resolve(JSON.parse(body).status);
		}
		else {
			deferred.reject(body);
		}
	});
	return deferred.promise;
}

export async function setNetworkInterface(SPN, endpointUrl: string, nic, resourceGroupName: string){

	var deferred = Q.defer();
	var restUrl = SPN.url + "subscriptions/" + SPN.subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Network/networkInterfaces/" + nic.name + "?api-version=" + azureApiVersion;
	var accessToken = await getAccessToken(SPN, endpointUrl);
	var requestHeader = {
		"Content-Type": "application/json; charset=utf-8",
		"Authorization": 'Bearer ' + accessToken
	};

	tl._writeLine(tl.loc("SettingTheNetworkInterface", nic.name));
	var maxRetries = 10;
	var sleepTime = (Math.floor(Math.random() * 6) + 5) * 1000;	// sleep time in ms
	var retryCount = 1;

	setTimeout (function putNetworkInterface() {
		if(retryCount > maxRetries) {
			deferred.reject(tl.loc("MaxRetriesExceededForSettingNetworkInterface", nic.name));
			return;
		}

		tl.debug(`Trial Count = ${retryCount}`);
		httpObj.send("PUT", restUrl, JSON.stringify(nic, null, 2), requestHeader, (error, response, body) => {
	        if(error) {
	            deferred.reject(error);
	        }
	        else if(response.statusCode == 200) {

	        	// wait for the provisioning state to be succeeded
	        	// check after every 20 seconds
	        	var asyncUrl = response.headers["azure-asyncoperation"];
	        	var checkStatusRetryCount = 0;
	        	var checkStatusWaitTime = 20000;
	        	setTimeout( async function checkSuccessStatus() {
	        		try {
	        			var provisioningState =  await checkProvisioningState(asyncUrl, accessToken);
	        			tl.debug("Status = " + provisioningState);
	        			if(provisioningState == "Succeeded") {
	        				return deferred.resolve("setNICStatusSuccess");
	        			}
	        		}
	        		catch(error) {
	        			// ignore errors and retry setting the network interface
	        			tl.debug(`Checking provisioning state errored out : ${error}`);
	        			retryCount++;
	        			tl.debug("Retrying setting network interface after " + sleepTime/1000 + " sec");
	        			return setTimeout(putNetworkInterface, sleepTime);
	        		}
	        		if(++checkStatusRetryCount == 10) {
	        			// Retry setting the network interface
	        			retryCount++;
	        			tl.debug("Retrying setting network interface after " + sleepTime/1000 + " sec");
	        			setTimeout(putNetworkInterface, sleepTime);
	        		}
					else {
						// Re-check the status of the provisioning state
						setTimeout(checkSuccessStatus, checkStatusWaitTime);
					}
	        	}, 1);
	        }
	        else if(response.statusCode == 429){
	        	body = JSON.parse(body);
	        	if(body["error"] && body["error"].code == "RetryableError") {
	        		retryCount++;
	        		tl.debug(JSON.stringify(body, null, 4));
        			tl.debug("Retrying setting network interface after " + sleepTime/1000 + " sec");
        			setTimeout(putNetworkInterface, sleepTime);
	        	}
	        }
	        else {
	        	deferred.reject(tl.loc("FailedSettingNetworkInterface", nic.name, response.statusCode, response.statusMessage, body));
	        }
		});
	}, 1);

	return deferred.promise;
}


text:
// Copyright 2017 Google 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.

package com.google.iosdevicecontrol.testing;

import com.google.common.io.ByteStreams;
import com.google.iosdevicecontrol.IosDevice;
import com.google.iosdevicecontrol.IosDeviceException;
import com.google.iosdevicecontrol.IosDeviceSocket;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/** Fake implementaton of IosDeviceSocket. s */
public class FakeIosDeviceSocket extends IosDeviceSocket {
  private volatile boolean closed;
  private final ByteArrayInputStream input;
  private final ByteArrayOutputStream output;

  public FakeIosDeviceSocket(IosDevice device, byte[] inputBytes) {
    super(device);
    input = new ByteArrayInputStream(inputBytes);
    output = new ByteArrayOutputStream();
  }

  @Override
  public int read(byte[] bytes) throws IosDeviceException {
    if (closed) {
      throw new IosDeviceException(device(), "socket closed");
    }
    try {
      return ByteStreams.read(input, bytes, 0, bytes.length);
    } catch (IOException e) {
      throw new IosDeviceException(device(), e);
    }
  }

  @Override
  public void write(byte[] bytes) throws IosDeviceException {
    if (closed) {
      throw new IosDeviceException(device(), "socket closed");
    }
    try {
      output.write(bytes);
    } catch (IOException e) {
      throw new IosDeviceException(device(), e);
    }
  }

  @Override
  public void close() throws IosDeviceException {
    closed = true;
  }

  /** Return an array of all bytes written to the socket. */
  public byte[] bytesWritten() {
    return output.toByteArray();
  }
}


text:
/**
 *
 */
/**
 * @author Takatsugu
 *
 */
package com.yasudanetwork.struts2.flush.exceptionhandler;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus assimilatus Britzelm.

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.togglz.core.logging (Togglz 2.1.0.Final API)</title>
<meta name="date" content="2014-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.togglz.core.logging

Interfaces

Log

Classes

Jdk14LogProvider

Jdk14LogProvider.Jdk14Log

LogFactory


text:
using ArmiesService.Common;
using ArmiesService.Controllers.Data;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System.Threading.Tasks;

namespace ArmiesService.Queries.Army
{
    class ArmyQuery : IQuery<ArmyGetDto>
    {
        static ArmyQuery()
        {
            BsonClassMap.RegisterClassMap<ArmyGetDto>(cm =>
            {
                cm.MapIdProperty(e => e.OwnerLogin);
                cm.MapProperty(e => e.Squads).SetElementName("squads");
            });

            BsonClassMap.RegisterClassMap<SquadGetDto>(cm =>
            {
                cm.MapProperty(e => e.Armors).SetElementName("armors");
                cm.MapProperty(e => e.Weapons).SetElementName("weapons");
                cm.MapProperty(e => e.Quantity).SetElementName("quantity");
                cm.MapProperty(e => e.Type).SetElementName("type");
            });
        }

        private readonly IMongoDatabase database;
        private readonly IGetCurrentUserLoginStrategy currentUserLogin;

        public ArmyQuery(IMongoDatabase database, IGetCurrentUserLoginStrategy currentUserLogin)
        {
            this.database = database;
            this.currentUserLogin = currentUserLogin;
        }

        public async Task<ArmyGetDto> AskAsync()
        {
            var login = currentUserLogin.Get();
            var collection = database.GetCollection<ArmyGetDto>("armies");
            return await collection.Find(army => army.OwnerLogin == login).FirstOrDefaultAsync();
        }
    }
}


text:
<?php

class Mollie_Mpm_Test_Model_Totals_PaymentFee_QuoteTaxTest extends Mollie_Mpm_Test_TestHelpers_TestCase
{
    public function testDoesNotSetThePaymentFeeWhenTheAdddressHasNoItems()
    {
        $quote = Mage::getModel('sales/quote');
        $address = Mage::getModel('sales/quote_address');
        $address->setQuote($quote);

        /** @var Mollie_Mpm_Model_Totals_PaymentFee_Quote $instance */
        $instance = Mage::getModel('mpm/totals_paymentFee_quoteTax');

        $instance->collect($address);

        $this->assertFalse($address->hasMollieMpmPaymentFeeTax());
        $this->assertFalse($address->hasBaseMollieMpmPaymentFeeTax());
    }

    public function testSetsToFeeToZeroWhenTheMethodIsNotSupported()
    {
        $quote = Mage::getModel('sales/quote');
        $quoteItem = Mage::getModel('sales/quote_item');

        $address = Mage::getModel('sales/quote_address');
        $address->setQuote($quote);
        $address->setData('cached_items_all', []);
        $address->setData('cached_items_nonnominal', [$quoteItem]);

        /** @var Mollie_Mpm_Model_Totals_PaymentFee_Quote $instance */
        $instance = Mage::getModel('mpm/totals_paymentFee_quoteTax');

        $instance->collect($address);

        $this->assertTrue($address->hasMollieMpmPaymentFeeTax());
        $this->assertSame(0, $address->getMollieMpmPaymentFeeTax());
        $this->assertTrue($address->hasBaseMollieMpmPaymentFeeTax());
        $this->assertSame(0, $address->getBaseMollieMpmPaymentFeeTax());
    }

    public function testSetsToFeeToZeroWhenThePaymentFeeIsNotSet()
    {
        $method = 'mollie_klarnapaylater';

        Mage::app()->getStore()->setConfig(sprintf('payment/%s/payment_surcharge', $method), 0);

        $quote = Mage::getModel('sales/quote');
        $quote->getPayment()->setMethod($method);
        $quoteItem = Mage::getModel('sales/quote_item');

        $address = Mage::getModel('sales/quote_address');
        $address->setQuote($quote);
        $address->setData('cached_items_all', []);
        $address->setData('cached_items_nonnominal', [$quoteItem]);

        /** @var Mollie_Mpm_Model_Totals_PaymentFee_Quote $instance */
        $instance = Mage::getModel('mpm/totals_paymentFee_quoteTax');

        $instance->collect($address);

        $this->assertTrue($address->hasMollieMpmPaymentFeeTax());
        $this->assertSame(0, $address->getMollieMpmPaymentFeeTax());
        $this->assertTrue($address->hasBaseMollieMpmPaymentFeeTax());
        $this->assertSame(0, $address->getBaseMollieMpmPaymentFeeTax());
    }

    public function testSetsThePaymentFeeCorrect()
    {
        $method = 'mollie_klarnapaylater';

        Mage::app()->getStore()->setConfig(sprintf('payment/%s/payment_surcharge', $method), 1);

        $quote = Mage::getModel('sales/quote');
        $quote->getPayment()->setMethod($method);
        $quoteItem = Mage::getModel('sales/quote_item');

        $address = Mage::getModel('sales/quote_address');
        $address->setQuote($quote);
        $address->setData('cached_items_all', []);
        $address->setData('cached_items_nonnominal', [$quoteItem]);

        /** @var Mollie_Mpm_Model_Totals_PaymentFee_Quote $instance */
        $instance = Mage::getModel('mpm/totals_paymentFee_quoteTax');

        $instance->collect($address);

        $this->assertTrue($address->hasMollieMpmPaymentFeeTax());
        $this->assertSame(0.17355371900826444, $address->getMollieMpmPaymentFeeTax());
        $this->assertTrue($address->hasBaseMollieMpmPaymentFeeTax());
        $this->assertSame(0.17355371900826444, $address->getBaseMollieMpmPaymentFeeTax());
    }
}


text:
TARGET=ray
# you need to use g++ 4.9 for both CNTK and C++14 features
CXX = mpic++
OPTIMIZE = -O3
CPP11 = -std=c++11 -std=c++1y
WARNING = -Wall
DEBUG = #-g
CNTKDIR = ~/cntk
CNTK_VERSION=2.4
CFLAGS = ${OPTIMIZE} ${WARNING} ${CPP11} ${DEBUG}  -I ${CNTKDIR}/Include/
CNTK_LIBS = -lCntk.Core-${CNTK_VERSION} -lCntk.Math-${CNTK_VERSION} -lCntk.Eval-${CNTK_VERSION}
LIBS = -lm -pthread -L ${CNTKDIR}/cntk/lib -L ${CNTKDIR}/cntk/dependencies/lib ${CNTK_LIBS}
RM = rm

SRCS=${shell ls src/*.cpp}
HEDS=${shell ls src/*.h}
OBJS=${SRCS:.cpp=.o}

.SUFFIXES:.cpp .o .h

.PHONY: all
all : ${TARGET}

${TARGET} : ${OBJS}
	${CXX} ${CFLAGS} -o $@ ${OBJS} ${LIBS}

.cpp.o:
	${CXX} ${CFLAGS} -c $< -o $@

.PHONY: clean

clean:
	${RM} -f ${TARGET} src/*~ src/*.o *~

Command.o: src/Command.cpp src/Command.h src/DynamicKomi.h src/GoBoard.h \
 src/Pattern.h src/UctSearch.h src/ZobristHash.h src/Message.h
Command.o: src/Command.h
DynamicKomi.o: src/DynamicKomi.cpp src/DynamicKomi.h src/GoBoard.h \
 src/Pattern.h src/UctSearch.h src/ZobristHash.h src/Message.h
DynamicKomi.o: src/DynamicKomi.h src/GoBoard.h src/Pattern.h \
 src/UctSearch.h src/ZobristHash.h
GoBoard.o: src/GoBoard.cpp src/GoBoard.h src/Pattern.h src/Semeai.h \
 src/UctRating.h src/PatternHash.h src/ZobristHash.h
GoBoard.o: src/GoBoard.h src/Pattern.h
Gtp.o: src/Gtp.cpp src/DynamicKomi.h src/GoBoard.h src/Pattern.h \
 src/UctSearch.h src/ZobristHash.h src/Gtp.h src/Nakade.h src/UctRating.h \
 src/PatternHash.h src/Message.h src/Point.h src/Rating.h \
 src/Simulation.h
Gtp.o: src/Gtp.h
Ladder.o: src/Ladder.cpp src/Message.h src/GoBoard.h src/Pattern.h \
 src/UctSearch.h src/ZobristHash.h src/Ladder.h src/SearchBoard.h \
 src/Point.h
Ladder.o: src/Ladder.h src/GoBoard.h src/Pattern.h
Message.o: src/Message.cpp src/Message.h src/GoBoard.h src/Pattern.h \
 src/UctSearch.h src/ZobristHash.h src/Point.h
Message.o: src/Message.h src/GoBoard.h src/Pattern.h src/UctSearch.h \
 src/ZobristHash.h
Nakade.o: src/Nakade.cpp src/Message.h src/GoBoard.h src/Pattern.h \
 src/UctSearch.h src/ZobristHash.h src/Nakade.h src/Point.h
Nakade.o: src/Nakade.h src/GoBoard.h src/Pattern.h
Pattern.o: src/Pattern.cpp src/GoBoard.h src/Pattern.h
Pattern.o: src/Pattern.h
PatternHash.o: src/PatternHash.cpp src/PatternHash.h src/GoBoard.h \
 src/Pattern.h
PatternHash.o: src/PatternHash.h src/GoBoard.h src/Pattern.h
Point.o: src/Point.cpp src/GoBoard.h src/Pattern.h src/Point.h
Point.o: src/Point.h
Rating.o: src/Rating.cpp src/Message.h src/GoBoard.h src/Pattern.h \
 src/UctSearch.h src/ZobristHash.h src/Nakade.h src/Point.h src/Rating.h \
 src/UctRating.h src/PatternHash.h src/Semeai.h src/Utility.h
Rating.o: src/Rating.h src/GoBoard.h src/Pattern.h src/UctRating.h \
 src/PatternHash.h
RayMain.o: src/RayMain.cpp src/Command.h src/GoBoard.h src/Pattern.h \
 src/Gtp.h src/PatternHash.h src/Rating.h src/UctRating.h src/Semeai.h \
 src/UctSearch.h src/ZobristHash.h
SearchBoard.o: src/SearchBoard.cpp src/SearchBoard.h src/GoBoard.h \
 src/Pattern.h
SearchBoard.o: src/SearchBoard.h src/GoBoard.h src/Pattern.h
Seki.o: src/Seki.cpp src/GoBoard.h src/Pattern.h src/Point.h src/Seki.h \
 src/Semeai.h
Seki.o: src/Seki.h src/GoBoard.h src/Pattern.h
Semeai.o: src/Semeai.cpp src/GoBoard.h src/Pattern.h src/Message.h \
 src/UctSearch.h src/ZobristHash.h src/Point.h src/Semeai.h \
 src/UctRating.h src/PatternHash.h
Semeai.o: src/Semeai.h src/GoBoard.h src/Pattern.h
Simulation.o: src/Simulation.cpp src/GoBoard.h src/Pattern.h \
 src/Message.h src/UctSearch.h src/ZobristHash.h src/Point.h src/Rating.h \
 src/UctRating.h src/PatternHash.h src/Simulation.h
Simulation.o: src/Simulation.h src/GoBoard.h src/Pattern.h
UctRating.o: src/UctRating.cpp src/Ladder.h src/GoBoard.h src/Pattern.h \
 src/Message.h src/UctSearch.h src/ZobristHash.h src/Nakade.h \
 src/PatternHash.h src/Point.h src/Semeai.h src/Utility.h src/UctRating.h
UctRating.o: src/UctRating.h src/GoBoard.h src/Pattern.h \
 src/PatternHash.h
UctSearch.o: src/UctSearch.cpp src/DynamicKomi.h src/GoBoard.h \
 src/Pattern.h src/UctSearch.h src/ZobristHash.h src/Ladder.h \
 src/Message.h src/PatternHash.h src/Seki.h src/Simulation.h \
 src/UctRating.h src/Utility.h
UctSearch.o: src/UctSearch.h src/GoBoard.h src/Pattern.h \
 src/ZobristHash.h
Utility.o: src/Utility.cpp src/Utility.h
Utility.o: src/Utility.h
ZobristHash.o: src/ZobristHash.cpp src/Nakade.h src/GoBoard.h \
 src/Pattern.h src/ZobristHash.h
ZobristHash.o: src/ZobristHash.h src/GoBoard.h src/Pattern.h


text:
package firewalls

import (
	"strings"

	"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud/meta"
	"google.golang.org/api/compute/v1"
	v1 "k8s.io/api/core/v1"
	"k8s.io/client-go/tools/record"
	"k8s.io/ingress-gce/pkg/flags"
	"k8s.io/ingress-gce/pkg/utils"
	"k8s.io/klog/v2"
	"k8s.io/legacy-cloud-providers/gce"
)

// FirewallParams holds all data needed to create firewall for L4 LB
type FirewallParams struct {
	Name              string
	IP                string
	SourceRanges      []string
	DestinationRanges []string
	PortRanges        []string
	NodeNames         []string
	Protocol          string
	L4Type            utils.L4LBType
}

func EnsureL4FirewallRule(cloud *gce.Cloud, nsName string, params *FirewallParams, sharedRule bool) error {
	fa := NewFirewallAdapter(cloud)
	existingFw, err := fa.GetFirewall(params.Name)
	if err != nil && !utils.IsNotFoundError(err) {
		return err
	}

	nodeTags, err := cloud.GetNodeTags(params.NodeNames)
	if err != nil {
		return err
	}
	fwDesc, err := utils.MakeL4LBFirewallDescription(nsName, params.IP, meta.VersionGA, sharedRule)
	if err != nil {
		klog.Warningf("EnsureL4FirewallRule(%v): failed to generate description for L4 %s rule, err: %v", params.Name, params.L4Type.ToString(), err)
	}
	expectedFw := &compute.Firewall{
		Name:         params.Name,
		Description:  fwDesc,
		Network:      cloud.NetworkURL(),
		SourceRanges: params.SourceRanges,
		TargetTags:   nodeTags,
		Allowed: []*compute.FirewallAllowed{
			{
				IPProtocol: strings.ToLower(params.Protocol),
				Ports:      params.PortRanges,
			},
		},
	}
	if flags.F.EnablePinhole {
		expectedFw.DestinationRanges = params.DestinationRanges
	}
	if existingFw == nil {
		klog.V(2).Infof("EnsureL4FirewallRule(%v): creating L4 %s firewall rule", params.Name, params.L4Type.ToString())
		err = fa.CreateFirewall(expectedFw)
		if utils.IsForbiddenError(err) && cloud.OnXPN() {
			gcloudCmd := gce.FirewallToGCloudCreateCmd(expectedFw, cloud.NetworkProjectID())

			klog.V(3).Infof("EnsureL4FirewallRule(%v): Could not create L4 %s firewall on XPN cluster: %v. Raising event for cmd: %q", params.Name, params.L4Type.ToString(), err, gcloudCmd)
			return newFirewallXPNError(err, gcloudCmd)
		}
		return err
	}

	// Don't compare the "description" field for shared firewall rules
	if firewallRuleEqual(expectedFw, existingFw, sharedRule) {
		return nil
	}

	klog.V(2).Infof("EnsureL4FirewallRule(%v): patching L4 %s firewall", params.Name, params.L4Type.ToString())
	err = fa.PatchFirewall(expectedFw)
	if utils.IsForbiddenError(err) && cloud.OnXPN() {
		gcloudCmd := gce.FirewallToGCloudUpdateCmd(expectedFw, cloud.NetworkProjectID())
		klog.V(3).Infof("EnsureL4FirewallRule(%v): Could not patch L4 %s firewall on XPN cluster: %v. Raising event for cmd: %q", params.Name, params.L4Type.ToString(), err, gcloudCmd)
		return newFirewallXPNError(err, gcloudCmd)
	}
	return err
}

func EnsureL4FirewallRuleDeleted(cloud *gce.Cloud, fwName string) error {
	fa := NewFirewallAdapter(cloud)
	if err := utils.IgnoreHTTPNotFound(fa.DeleteFirewall(fwName)); err != nil {
		if utils.IsForbiddenError(err) && cloud.OnXPN() {
			gcloudCmd := gce.FirewallToGCloudDeleteCmd(fwName, cloud.NetworkProjectID())
			klog.V(3).Infof("EnsureL4FirewallRuleDeleted(%v): could not delete traffic firewall on XPN cluster. Raising event.", fwName)
			return newFirewallXPNError(err, gcloudCmd)
		}
		return err
	}
	return nil
}

func firewallRuleEqual(a, b *compute.Firewall, skipDescription bool) bool {
	if len(a.Allowed) != len(b.Allowed) {
		return false
	}
	for i := range a.Allowed {
		if !allowRulesEqual(a.Allowed[i], b.Allowed[i]) {
			return false
		}
	}

	if !utils.EqualStringSets(a.DestinationRanges, b.DestinationRanges) {
		return false
	}

	if !utils.EqualStringSets(a.SourceRanges, b.SourceRanges) {
		return false
	}

	if !utils.EqualStringSets(a.TargetTags, b.TargetTags) {
		return false
	}

	if !skipDescription && a.Description != b.Description {
		return false
	}
	return true
}

func allowRulesEqual(a *compute.FirewallAllowed, b *compute.FirewallAllowed) bool {
	return a.IPProtocol == b.IPProtocol &&
		utils.EqualStringSets(a.Ports, b.Ports)
}

func ensureFirewall(svc *v1.Service, shared bool, params *FirewallParams, cloud *gce.Cloud, recorder record.EventRecorder) error {
	nsName := utils.ServiceKeyFunc(svc.Namespace, svc.Name)
	err := EnsureL4FirewallRule(cloud, nsName, params, shared)
	if err != nil {
		if fwErr, ok := err.(*FirewallXPNError); ok {
			recorder.Eventf(svc, v1.EventTypeNormal, "XPN", fwErr.Message)
			return nil
		}
		return err
	}
	return nil
}

// EnsureL4LBFirewallForHc creates or updates firewall rule for shared or non-shared health check to nodes
func EnsureL4LBFirewallForHc(svc *v1.Service, shared bool, params *FirewallParams, cloud *gce.Cloud, recorder record.EventRecorder) error {
	return ensureFirewall(svc, shared, params, cloud, recorder)
}

// EnsureL4LBFirewallForNodes creates or updates firewall rule for LB traffic to nodes
func EnsureL4LBFirewallForNodes(svc *v1.Service, params *FirewallParams, cloud *gce.Cloud, recorder record.EventRecorder) error {
	return ensureFirewall(svc /*shared = */, false, params, cloud, recorder)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:osc="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/public_menu_shared"
        android:icon="@mipmap/ic_brows_share"
        android:title="@string/share_to"
        android:visible="true"
        osc:showAsAction="always"/>

</menu>


text:
static int staticVar; // expected-note + {{'staticVar' declared here}}
static int staticFunction(); // expected-note + {{'staticFunction' declared here}}
static struct { int x; } staticStruct; // expected-note + {{'staticStruct' declared here}}

inline int useStatic () { // expected-note 3 {{use 'static' to give inline function 'useStatic' internal linkage}}
  staticFunction(); // expected-warning{{static function 'staticFunction' is used in an inline function with external linkage}}
  (void)staticStruct.x; // expected-warning{{static variable 'staticStruct' is used in an inline function with external linkage}}
  return staticVar; // expected-warning{{static variable 'staticVar' is used in an inline function with external linkage}}
}

extern inline int useStaticFromExtern () { // no suggestions
  staticFunction(); // expected-warning{{static function 'staticFunction' is used in an inline function with external linkage}}
  return staticVar; // expected-warning{{static variable 'staticVar' is used in an inline function with external linkage}}
}

static inline int useStaticFromStatic () {
  staticFunction(); // no-warning
  return staticVar; // no-warning
}

extern inline int useStaticInlineFromExtern () {
  // Heuristic: if the function we're using is also inline, don't warn.
  // This can still be wrong (in this case, we end up inlining calls to
  // staticFunction and staticVar) but this got very noisy even using
  // standard headers.
  return useStaticFromStatic(); // no-warning
}

static int constFunction() __attribute__((const));

inline int useConst () {
  return constFunction(); // no-warning
}

#else
// -------
// This is the main source file.
// -------

#define INCLUDE
#include "inline.c"

// Check that we don't allow illegal uses of inline
inline int a; // expected-error{{'inline' can only appear on functions}}
typedef inline int b; // expected-error{{'inline' can only appear on functions}}
int d(inline int a); // expected-error{{'inline' can only appear on functions}}

// Check that the warnings from the "header file" aren't on by default in
// the main source file.

inline int useStaticMainFile () {
  staticFunction(); // no-warning
  return staticVar; // no-warning
}

// Check that the warnings show up when explicitly requested.

#pragma clang diagnostic push
#pragma clang diagnostic warning "-Wstatic-in-inline"

inline int useStaticAgain () { // expected-note 2 {{use 'static' to give inline function 'useStaticAgain' internal linkage}}
  staticFunction(); // expected-warning{{static function 'staticFunction' is used in an inline function with external linkage}}
  return staticVar; // expected-warning{{static variable 'staticVar' is used in an inline function with external linkage}}
}

#pragma clang diagnostic pop

inline void defineStaticVar() { // expected-note {{use 'static' to give inline function 'defineStaticVar' internal linkage}}
  static const int x = 0; // ok
  static int y = 0; // expected-warning {{non-constant static local variable in inline function may be different in different files}}
}

extern inline void defineStaticVarInExtern() {
  static const int x = 0; // ok
  static int y = 0; // ok
}

// Check behavior of line markers.
# 1 "XXX.h" 1
inline int useStaticMainFileInLineMarker() { // expected-note 2 {{use 'static' to give inline function 'useStaticMainFileInLineMarker' internal linkage}}
  staticFunction(); // expected-warning{{static function 'staticFunction' is used in an inline function with external linkage}}
  return staticVar; // expected-warning{{static variable 'staticVar' is used in an inline function with external linkage}}
}
# 100 "inline.c" 2

inline int useStaticMainFileAfterLineMarker() {
  staticFunction(); // no-warning
  return staticVar; // no-warning
}

#endif


text:
import json
from base64 import b64decode
from datetime import date, datetime, time, timedelta

from .._compat import to_bytes, to_native
from ..adapters.oracle import Oracle
from . import for_type, parsers
from .base import BasicParser, ListsParser

class OracleParser(BasicParser):
    @for_type("integer")
    def _integer(self, value):
        return int(value)

    @for_type("text")
    def _text(self, value):
        return value

    @for_type("clob")
    def _clob(self, value):
        return value

    @for_type("blob")
    def _blob(self, value):
        # decoded = b64decode(value.read())
        decoded = b64decode(to_bytes(value))
        try:
            decoded = to_native(decoded)
        except:
            pass
        return decoded

    @for_type("json")
    def _json(self, value):
        return json.loads(value)

    @for_type("date")
    def _date(self, value):
        if isinstance(value, datetime):
            return value.date()
        (y, m, d) = map(int, str(value)[:10].strip().split("-"))
        return date(y, m, d)

    @for_type("list:reference")
    def _list_references(self, value, field_type):
        return super(OracleParser, self)._list_references.f(self, value, field_type)

class OracleListsParser(ListsParser):
    @for_type("list:integer")
    def _list_integers(self, value):
        return super(OracleListsParser, self)._list_integers.f(self, value)

    @for_type("list:string")
    def _list_strings(self, value):
        return super(OracleListsParser, self)._list_strings.f(self, value)

@parsers.register_for(Oracle)
class OracleCommonparser(OracleParser, OracleListsParser):
    pass


text:
package com.paybook.sync;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Attachment extends Paybook{

	public String id_attachment;
	public String id_account;
	public String id_user;
	public String id_external;
	public String id_attachment_type;
	public String id_transaction;
	public String is_valid;
	public String file;
	public String mime;
	public String url;
	public HashMap<String,Object> extra;
    public String content;
	public String dt_refresh;

	public Attachment() throws Error{
	}

	private static List<Attachment> get(Session session, String id_user, HashMap<String, Object> options) throws Error{
		List<Attachment> attachments = null;
		JSONObject response = null;
		try{
			HashMap<String, Object> data = options;

			if(session != null && StringUtils.isBlank(id_user)){
				data.put("token", session.token);
			}else if(session == null && StringUtils.isNotBlank(id_user)){
				data.put("api_key", Paybook.api_key);
				data.put("id_user", id_user);
			}//End of IF

			response = call("attachments", Method.GET, data);
			String responseInString = response.get("response").toString();
			ObjectMapper mapper = new ObjectMapper();
			attachments = mapper.readValue(responseInString, new TypeReference<List<Attachment>>(){});
		}catch(Error e){
			throw e;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			throw new Error(500,false,e.getMessage(),null);
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			throw new Error(500,false,e.getMessage(),null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new Error(500,false,e.getMessage(),null);
		}
    	return attachments;
	}//End of GET

	public static List<Attachment> get(Session session, HashMap<String, Object> options) throws Error{
    	return get(session,"",options);
    }//End of get

    public static List<Attachment> get(Session session) throws Error{
    	HashMap<String, Object> options = new HashMap<String, Object>();
    	return get(session,"",options);
    }//End of get

    public static List<Attachment> get(String id_user, HashMap<String, Object> options) throws Error{
    	return get(null,id_user,options);
    }//End of get

    public static List<Attachment> get(String id_user) throws Error{
    	HashMap<String, Object> options = new HashMap<String, Object>();
    	return get(null,id_user,options);
    }//End of get

	private static List<Attachment> get(Session session, String id_user, String id_attachment) throws Error{
		List<Attachment> attachments  = new ArrayList<Attachment>();;
		JSONObject response = null;
		try{
			HashMap<String, Object> data = new HashMap<String,Object>();
			if(session != null && StringUtils.isBlank(id_user)){
				data.put("token", session.token);
			}else if(session == null && StringUtils.isNotBlank(id_user)){
				data.put("api_key", Paybook.api_key);
				data.put("id_user", id_user);
			}//End of IF
			Map<String,String> headers = new HashMap<String,String>();
			headers.put("Content-Type", "application/xml");
			response = call("attachments/"+id_attachment, Method.GET, data, headers);
			String responseInString = response.get("content").toString();
			Attachment attachment = new Attachment();
			attachment.content = responseInString;
			attachments.add(attachment);
		}catch(Error e){
			throw e;
		}
    	return attachments;
	}//End of GET

    public static List<Attachment> get(Session session, String id_attachment) throws Error{
    	return get(session,"",id_attachment);
    }//End of get

    public static List<Attachment> get(String id_user, String id_attachment) throws Error{
    	return get(null,id_user,id_attachment);
    }//End of get

    private static int get_count(Session session, String id_user, HashMap<String, Object> options) throws Error{
		int attachments;
		JSONObject response = null;
		try{
			HashMap<String, Object> data = options;
			if(session != null && StringUtils.isBlank(id_user)){
				data.put("token", session.token);
			}else if(session == null && StringUtils.isNotBlank(id_user)){
				data.put("api_key", Paybook.api_key);
				data.put("id_user", id_user);
			}//End of IF

			response = call("attachments/count", Method.GET, data);
			attachments = response.getJSONObject("response").getInt("count");
		}catch(Error e){
			throw e;
		}
    	return attachments;
	}//End of GET

	public static int get_count(Session session, HashMap<String, Object> options) throws Error{
    	return get_count(session,"",options);
    }//End of get

    public static int get_count(Session session) throws Error{
    	HashMap<String, Object> options = new HashMap<String, Object>();
    	return get_count(session,"",options);
    }//End of get

    public static int get_count(String id_user, HashMap<String, Object> options) throws Error{
    	return get_count(null,id_user,options);
    }//End of get

    public static int get_count(String id_user) throws Error{
    	HashMap<String, Object> options = new HashMap<String, Object>();
    	return get_count(null,id_user,options);
    }//End of get

    @SuppressWarnings("unchecked")
	private static HashMap<String,Object> get_extra(Session session, String id_user, String id_attachment) throws Error{
    	HashMap<String,Object> attachments = null;
		JSONObject response = null;
		try{
			HashMap<String, Object> data = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			if(session != null && StringUtils.isBlank(id_user)){
				data.put("token", session.token);
			}else if(session == null && StringUtils.isNotBlank(id_user)){
				data.put("api_key", Paybook.api_key);
				data.put("id_user", id_user);
			}//End of IF

			response = call("attachments/" + id_attachment + "/extra", Method.GET, data);
			String responseInString = response.get("response").toString();
			attachments = mapper.readValue(responseInString, HashMap.class);
		}catch(Error e){
			throw e;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			throw new Error(500,false,e.getMessage(),null);
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			throw new Error(500,false,e.getMessage(),null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new Error(500,false,e.getMessage(),null);
		}
    	return attachments;
	}//End of GET

	public static HashMap<String,Object> get_extra(Session session, String id_attachment) throws Error{
    	return get_extra(session,"",id_attachment);
    }//End of get

    public static HashMap<String,Object> get_extra(String id_user, String id_attachment) throws Error{
    	return get_extra(null,id_user,id_attachment);
    }//End of get

}


text:
package com.gary.garytool.business.stock;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2016/2/23.
 */
public class StockUtil {

    public static final String CHARACTER = "UTF-8";
    public static final String SEPARATOR_ATTR_TAG = "\t";
    public static final String SEPARATOR_OBJECT_TAG = "\n";

    public static void saveFileDay(Context context,String key,String value){

        SharedPreferences sp =context.getSharedPreferences("config.txt", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static String getFileDay(Context context,String key){
            SharedPreferences sp =context.getSharedPreferences("config.txt",  Context.MODE_PRIVATE);
            return sp.getString(key, "");
    }

    // 写在/mnt/sdcard/目录下面的文件
    public static void writeSDFile(String pathName,String fileName, String message) {
        writeSDFile(pathName,fileName,message,false);
    }

    public   static   void  writeSDFile(String pathName,String fileName, String message,boolean isAdd) {
        try {

            File file = new File(pathName + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }

            StringBuilder before=new StringBuilder();
            //读取旧数据
            if(isAdd)
            {
                InputStreamReader   inputStreamReader = new InputStreamReader(new FileInputStream(file), StockUtil.CHARACTER);
                BufferedReader   reader= new BufferedReader(inputStreamReader);
                String line;
                while ((line = reader.readLine()) != null) {
                    if(line.contains("4-2"))
                        continue;
                    before.append(StockUtil.SEPARATOR_OBJECT_TAG+line );
                }
                reader.close();
                inputStreamReader.close();
            }

            FileOutputStream fout= new FileOutputStream(file.getPath());

            //写入新数据
            fout.write(message.getBytes());

            //写入旧数据
            if(isAdd&&before.length()>0)
            {
                fout.write(before.toString().getBytes());
            }

            fout.close();
        } catch (Exception e) {

        }

    }

    public static String getSDPath(String dir){

        File sdDir;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if(!sdCardExist) {
            return "";
        }

        sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        File fileDir = new File(sdDir+dir);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        return fileDir.getPath();
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if(c.get(Calendar.DAY_OF_WEEK) == 1){
            dayForWeek = 7;
        }else{
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    public static String getYesterday(String today) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date d = null;
        try {
            d = df.parse(today);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        cal.add(Calendar.DATE, -1);  //减1天
        return df.format(cal.getTime());
    }
}


text:
namespace BalloonsPops
{
    using System;
    using System.Collections.Generic;

    internal class PersonScoreComparer : IComparer<Player>
    {
        public int Compare(Player x, Player y)
        {
            return x.Score.CompareTo(y.Score);
        }
    }
}


text:
using Citicon.Data;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;

namespace Citicon.DataProcess
{
    internal sealed class GetProjectListWithApprovedProjectDesignByClient : DataProcessBase
    {
        public GetProjectListWithApprovedProjectDesignByClient(Client client)
        {
            Client = client ?? throw new ArgumentNullException(nameof(client));
        }

        private Client Client;

        private MySqlCommand CreateCommand(MySqlConnection connection)
        {
            var command = Utility.CreateProcedureCommand("GetProjectListWithApprovedProjectDesignByClient", connection);
            command.Parameters.AddWithValue("@_ClientId", Client.Id);

            return command;
        }

        public Task<IEnumerable<Project>> ExecuteAsync(MySqlConnection connection)
        {
            return ProcessUtility.HandleReadingIEnumerableAsync(CreateCommand(connection), FromReader);
        }

        public Task<IEnumerable<Project>> ExecuteAsync()
        {
            return ProcessUtility.HandleExecuteAsync(ExecuteAsync);
        }

        private Project FromReader(DbDataReader reader)
        {
            return new Project()
            {
                Id = reader.GetUInt64("Id"),
                Name = reader.GetString("Name"),
                Client = Client
            };
        }
    }
}


text:
import { Component } from 'react'
import { FullPage } from 'react-full-page'
import Head from 'next/head'
import Menu from '@components/menu'
import Footer from '@components/footer'

class Layout extends Component {
	state = { loaded: false };

	componentDidMount() { this.setState({ loaded: true }) }
	componentWillUnmount() { this.setState({ loaded: false }) }

	render() {
		const {loaded} = this.state
		const {title, children} = this.props
		const slideNames = children.map(({props}) => props.name)

		return (
			<main role="application">
				{<Head>
					<title>Blackome Digital | {title || 'Digital Agency'}</title>
					{loaded && <link rel="stylesheet" href="https://goo.gl/dYYWqf" />}
				</Head>}
				{<Menu />}
				<FullPage>
					{children}
					{<Footer slides={slideNames} />}
				</FullPage>
			</main>
		)
	}
}

export default Layout


text:
#pragma once

/*
 * This file was created to handle endianness problem when writing to binary
 * files. The bug could occur when an integer is being written to a binary file
 * and read from a different system. If systems have different endianness, the
 * order of bytes could get reversed.
 *
 * NUM: 0x04030201
 * LITTLE_ENDIAN => 0x01020304
 * BIG_ENDIAN    => 0x04030201
 *
 * e.g. If the writing system (little endian) have 0x04030201 in its variable
 * and wants to write it to file, it would be in the order of 0x01, 0x02, 0x03
 * 0x04. And when the reading system (big endian) reads with the same order and
 * store it in an integer, our original 0x04030201 becomes 0x01020304.
 *
 * To prevent this from happening, we are always going to assume that the file
 * format is going to be little endian, and GOMC will perform conversion to
 * little or big endian based on the type of system.
 *
 * This header file will include tools to detect the endianness of the system
 * and functions to convert the little endian to big endian and big endian to
 * little endian.
 *
 * For developers outside of this header file, two functions should only be
 * used:
 *
 * // converts host integer to file integer
 * uint64_t htof64(uint64_t host_integer)
 * // converts host integer to file integer
 * uint64_t ftoh64(uint64_t file_integer)
 *
 * Before writing to file, make sure you use htof64() and after reading use
 * ftoh64()!
 *
 */

#include <stdlib.h>
#include <stdint.h>

#define bswap_64(x)                            \
  ((((x) & 0xff00000000000000ull) >> 56)       \
   | (((x) & 0x00ff000000000000ull) >> 40)     \
   | (((x) & 0x0000ff0000000000ull) >> 24)     \
   | (((x) & 0x000000ff00000000ull) >> 8)      \
   | (((x) & 0x00000000ff000000ull) << 8)      \
   | (((x) & 0x0000000000ff0000ull) << 24)     \
   | (((x) & 0x000000000000ff00ull) << 40)     \
   | (((x) & 0x00000000000000ffull) << 56))

#define bswap_32(x)               \
  ((((x) & 0xff000000) >> 24)     \
   | (((x) & 0x00ff0000) >> 8)    \
   | (((x) & 0x0000ff00) << 8)    \
   | (((x) & 0x000000ff) << 24))

#define bswap_16(x)          \
  ((((x) & 0xff00) >> 8)     \
   | (((x) & 0x00ff) << 8))

enum ENDIANNESS {
  LT_ENDIAN,
  BG_ENDIAN
};

inline ENDIANNESS GetEndian() {
  long int endian = 0x0000000000000001;
  return (*(char *) &endian == 0x01) ? LT_ENDIAN : BG_ENDIAN;
}

inline uint64_t htof64(uint64_t host_integer) {
  if(GetEndian() == LT_ENDIAN) {
    // Same endianness, so just return the same integer
    return host_integer;
  } else {
    // need to reverse here
    return bswap_64(host_integer);
  }
}

inline uint64_t ftoh64(uint64_t file_integer) {
  if(GetEndian() == LT_ENDIAN) {
    // Same endianness, so just return the same integer
    return file_integer;
  } else {
    // need to reverse order here
    return bswap_64(file_integer);
  }
}

inline uint32_t htof32(uint32_t host_integer) {
  if(GetEndian() == LT_ENDIAN) {
    return host_integer;
  } else {
    return bswap_32(host_integer);
  }
}

inline uint32_t ftoh32(uint32_t file_integer) {
  if(GetEndian() == LT_ENDIAN) {
    return file_integer;
  } else {
    return bswap_32(file_integer);
  }
}

inline uint16_t htof16(uint32_t host_integer) {
  if(GetEndian() == LT_ENDIAN) {
    return host_integer;
  } else {
    return bswap_16(host_integer);
  }
}

inline uint16_t ftoh16(uint16_t file_integer) {
  if(GetEndian() == LT_ENDIAN) {
    return file_integer;
  } else {
    return bswap_16(file_integer);
  }
}


text:
from __future__ import absolute_import

import logging
import click
import cachetools
try:
    import cPickle as pickle
except ImportError:
    import pickle
from copy import deepcopy
from pathlib import Path
from pandas import to_datetime
from datetime import datetime

import datacube
from datacube.api.core import Datacube
from datacube.model import DatasetType, GeoPolygon, Range
from datacube.model.utils import make_dataset, xr_apply, datasets_to_doc
from datacube.storage.storage import write_dataset_to_netcdf
from datacube.ui import click as ui
from datacube.utils import read_documents, intersect_points, union_points

from datacube.ui.click import cli

_LOG = logging.getLogger('agdc-ingest')

FUSER_KEY = 'fuse_data'

def find_diff(input_type, output_type, index, ingestion_bounds=None, **query):
    from datacube.api.grid_workflow import GridWorkflow
    workflow = GridWorkflow(index, output_type.grid_spec)

    tiles_in = workflow.list_tiles(product=input_type.name, **query)
    tiles_out = workflow.list_tiles(product=output_type.name, **query)

    def update_dict(d, **kwargs):
        result = d.copy()
        result.update(kwargs)

        if ingestion_bounds is not None:
            polygon = d['geobox'].geographic_extent.points
            # Need to programatically figure out the upper left and lower right.
            #polygon[0] = UL, polygon[2] = LR
            # http://www.geeksforgeeks.org/find-two-rectangles-overlap/
            # if top left x1 > bottom right x2 or top left x2 > bottom right x1
            # if top left y1 < bottom right y2 or top left y2 < bottom right y1
            if polygon[0][0] > ingestion_bounds['right'] or ingestion_bounds['left'] > polygon[2][0]:
                   return None
            if polygon[0][1] < ingestion_bounds['bottom'] or ingestion_bounds['top'] < polygon[2][1]:
                   return None
            return result
        return result

    tasks = [update_dict(tile, index=key) for key, tile in tiles_in.items() if key not in tiles_out]
    tasks = list(filter(None, tasks))
    return tasks

def morph_dataset_type(source_type, config):
    output_type = DatasetType(source_type.metadata_type, deepcopy(source_type.definition))
    output_type.definition['name'] = config['output_type']
    output_type.definition['managed'] = True
    output_type.definition['description'] = config['description']
    output_type.definition['storage'] = config['storage']
    output_type.metadata_doc['format'] = {'name': 'NetCDF'}

    def merge_measurement(measurement, spec):
        measurement.update({k: spec.get(k, measurement[k]) for k in ('name', 'nodata', 'dtype')})
        return measurement

    output_type.definition['measurements'] = [merge_measurement(output_type.measurements[spec['src_varname']], spec)
                                              for spec in config['measurements']]
    return output_type

def get_variable_params(config):
    chunking = config['storage']['chunking']
    chunking = [chunking[dim] for dim in config['storage']['dimension_order']]

    variable_params = {}
    for mapping in config['measurements']:
        varname = mapping['name']
        variable_params[varname] = {k: v for k, v in mapping.items() if k in {'zlib',
                                                                              'complevel',
                                                                              'shuffle',
                                                                              'fletcher32',
                                                                              'contiguous',
                                                                              'attrs'}}
        variable_params[varname]['chunksizes'] = chunking

    return variable_params

def get_app_metadata(config, config_file):
    doc = {
        'lineage': {
            'algorithm': {
                'name': 'datacube-ingest',
                'version': config.get('version', 'unknown'),
                'repo_url': 'https://github.com/GeoscienceAustralia/datacube-ingester.git',
                'parameters': {'configuration_file': config_file}
            },
        }
    }
    return doc

def get_filename(config, tile_index, sources):
    file_path_template = str(Path(config['location'], config['file_path_template']))
    time_format = '%Y%m%d%H%M%S%f'
    return Path(file_path_template.format(
        tile_index=tile_index,
        start_time=to_datetime(sources.time.values[0]).strftime(time_format),
        end_time=to_datetime(sources.time.values[-1]).strftime(time_format)))

def get_measurements(source_type, config):
    def merge_measurement(measurement, spec):
        measurement.update({k: spec.get(k) or measurement[k] for k in ('nodata', 'dtype', 'resampling_method')})
        return measurement

    return [merge_measurement(source_type.measurements[spec['src_varname']].copy(), spec)
            for spec in config['measurements']]

def get_namemap(config):
    return {spec['src_varname']: spec['name'] for spec in config['measurements']}

def make_output_type(index, config):
    source_type = index.products.get_by_name(config['source_type'])
    if not source_type:
        click.echo("Source DatasetType %s does not exist", config['source_type'])
        click.get_current_context().exit(1)

    output_type = morph_dataset_type(source_type, config)
    _LOG.info('Created DatasetType %s', output_type.name)
    output_type = index.products.add(output_type)

    return source_type, output_type

def save_tasks_to_file(config, tasks, taskfile):
    with open(taskfile, 'wb') as stream:
        pickler = pickle.Pickler(stream, pickle.HIGHEST_PROTOCOL)
        pickler.dump(config)
        for task in tasks:
            pickler.dump(task)
    _LOG.info('Saved config and tasks to %s', taskfile)

def stream_unpickler(taskfile):
    with open(taskfile, 'rb') as stream:
        unpickler = pickle.Unpickler(stream)
        while True:
            try:
                yield unpickler.load()
            except EOFError:
                break

def load_tasks_from_file(taskfile):
    stream = stream_unpickler(taskfile)
    config = next(stream)
    return config, stream

@cachetools.cached(cache={}, key=lambda index, id_: id_)
def get_full_lineage(index, id_):
    return index.datasets.get(id_, include_sources=True)

def load_config_from_file(index, config):
    config_name = Path(config).name
    _, config = next(read_documents(Path(config)))
    config['filename'] = config_name

    return config

def create_task_list(index, output_type, year, source_type, config):
    query = {}
    if year:
        query['time'] = Range(datetime(year=year, month=1, day=1), datetime(year=year+1, month=1, day=1))
    bounds = None
    if config['ingestion_bounds']:
        bounds = config['ingestion_bounds']

    tasks = find_diff(source_type, output_type, index, ingestion_bounds=bounds, **query)
    _LOG.info('%s tasks discovered', len(tasks))

    def update_sources(sources):
        return tuple(get_full_lineage(index, dataset.id) for dataset in sources)

    def update_task(task):
        for i in range(task['sources'].size):
            task['sources'].values[i] = update_sources(task['sources'].values[i])
        return task

    tasks = (update_task(task) for task in tasks)
    return tasks

def ingest_work(config, source_type, output_type, index, sources, geobox):
    namemap = get_namemap(config)
    measurements = get_measurements(source_type, config)
    variable_params = get_variable_params(config)
    global_attributes = config['global_attributes']

    with datacube.set_options(reproject_threads=1):
        fuse_func = {'copy': None}[config.get(FUSER_KEY, 'copy')]
        data = Datacube.product_data(sources, geobox, measurements, fuse_func=fuse_func)
    nudata = data.rename(namemap)
    file_path = get_filename(config, index, sources)

    def _make_dataset(labels, sources):
        sources_union = union_points(*[source.extent.to_crs(geobox.crs).points for source in sources])
        valid_data = intersect_points(geobox.extent.points, sources_union)
        dataset = make_dataset(dataset_type=output_type,
                               sources=sources,
                               extent=geobox.extent,
                               center_time=labels['time'],
                               uri=file_path.absolute().as_uri(),
                               app_info=get_app_metadata(config, config['filename']),
                               valid_data=GeoPolygon(valid_data, geobox.crs))
        return dataset
    datasets = xr_apply(sources, _make_dataset, dtype='O')  # Store in Dataarray to associate Time -> Dataset
    nudata['dataset'] = datasets_to_doc(datasets)

    write_dataset_to_netcdf(nudata, global_attributes, variable_params, file_path)

    return datasets

def process_tasks(index, config, source_type, output_type, tasks, executor):
    def check_valid(task):
        if FUSER_KEY in config:
            return True

        require_fusing = [source for source in task['sources'].values if len(source) > 1]
        if require_fusing:
            _LOG.warning('Skipping %s - no "%s" specified in config: %s', task['index'], FUSER_KEY, require_fusing)

        return not require_fusing

    results = []
    successful = failed = 0
    for task in tasks:
        if check_valid(task):
            results.append(executor.submit(ingest_work,
                                           config=config,
                                           source_type=source_type,
                                           output_type=output_type,
                                           **task))
        else:
            failed += 1

    for result in executor.as_completed(results):
        try:
            datasets = executor.result(result)
            for dataset in datasets.values:
                index.datasets.add(dataset, skip_sources=True)
            successful += 1
        except Exception:  # pylint: disable=broad-except
            _LOG.exception('Task failed')
            failed += 1
            continue

    return successful, failed

@cli.command('ingest', help="Ingest datasets")
@click.option('--config-file', '-c',
              type=click.Path(exists=True, readable=True, writable=False, dir_okay=False),
              help='Ingest configuration file')
@click.option('--year', type=click.IntRange(1960, 2060))
@click.option('--save-tasks', help='Save tasks to the specified file',
              type=click.Path(exists=False))
@click.option('--load-tasks', help='Load tasks from the specified file',
              type=click.Path(exists=True, readable=True, writable=False, dir_okay=False))
@click.option('--dry-run', '-d', is_flag=True, default=False, help='Check if everything is ok')
@ui.executor_cli_options
@ui.pass_index(app_name='agdc-ingest')
def ingest_cmd(index, config_file, year, save_tasks, load_tasks, dry_run, executor):
    if config_file:
        config = load_config_from_file(index, config_file)
        source_type, output_type = make_output_type(index, config)
        tasks = create_task_list(index, output_type, year, source_type, config)
    elif load_tasks:
        config, tasks = load_tasks_from_file(load_tasks)
        source_type, output_type = make_output_type(index, config)
    else:
        click.echo('Must specify exactly one of --config-file, --load-tasks')
        click.get_current_context().exit(1)

    if dry_run:
        for task in tasks:
            click.echo('Would create %s' % get_filename(config, task['index'], task['sources']))
        return

    if save_tasks:
        save_tasks_to_file(config, tasks, save_tasks)
        return

    successful, failed = process_tasks(index, config, source_type, output_type, tasks, executor)
    click.echo('%d successful, %d failed' % (successful, failed))