text:
classdef EvaluateDepth < handle
    %EvaluateDepth Berechnet aus den Temperaturfeldern der Zeitschritte die
    %Schweißnahttiefe
    %   Detailed explanation goes here

    properties
        finishedTask@TaskManager;

        fineStepsTFields = [];

        checkingMelt = [];
    end

    methods
        function this = EvaluateDepth(finTask)
            this.finishedTask = finTask;
        end

        function CalcDepth(this, interpD)
            % Überführen in lokale Variablen
            stepsTFields = cell(1, size(this.finishedTask.InputVariParam, 1));
            for i = 1:size(this.finishedTask.InputVariParam, 1)
                if length(this.finishedTask.FinishedTFields) == 2
                    stepsTFields{i} = this.finishedTask.FinishedTFields{i,2};
                elseif length(this.finishedTask.FinishedTFields) == 1 && length(this.finishedTask.FinishedTFields{1,1}) > 2
                    stepsTFields{i} = this.finishedTask.FinishedTFields{i,1};
                else
                    error('Time steps are required.');
                end
            end

            stepsDiscretization = this.finishedTask.TimeStepDiscretisation;

            % Speichern der Schmelztemperaturen
            meltingTemp = zeros(1, size(this.finishedTask.InputVariParam, 1));
            for i = 1:size(this.finishedTask.InputVariParam, 1)
                meltingTemp(i) = this.finishedTask.InputMaterial(i,6);
            end

            % Logical Arrays mit Schmelztemperatur für jeden Zeitschritt
            % jedes Versuchs
            for i = 1:size(this.finishedTask.InputVariParam, 1)
                % Interpolieren der erhaltenen Zeitschritte -->
                % gleichmäßiges Netz + logical Array für Tm

                % Neue Diskretisierung
                newxLin = linspace(stepsDiscretization{1,i}{1,1}{1,1}(1,1), stepsDiscretization{1,i}{1,1}{1,1}(1,end), interpD);
                newyLin = linspace(stepsDiscretization{1,i}{1,1}{1,2}(1,1), stepsDiscretization{1,i}{1,1}{1,2}(1,end), interpD);
                newzLin = linspace(stepsDiscretization{1,i}{1,1}{1,3}(1,1), stepsDiscretization{1,i}{1,1}{1,3}(1,end), interpD);

                [newx, newy, newz] = meshgrid(newxLin, newyLin, newzLin);

                newx = reshape(newx, [numel(newx), 1]);
                newy = reshape(newy, [numel(newy), 1]);
                newz = reshape(newz, [numel(newz), 1]);

                melt = meltingTemp(i);
                stepsT = stepsTFields{i,1};

                stepsDiscParfor = stepsDiscretization{1,i};

                checkMelt = zeros(length(newx), length(stepsTFields{i}));
                parfor j = 1:length(stepsTFields{i})
                    % Alte Diskretisierung in richtige Form bringen
                    [oldx, oldy, oldz] = meshgrid(stepsDiscParfor{1,j}{1,1}, ...
                        stepsDiscParfor{1,j}{1,2}, ...
                        stepsDiscParfor{1,j}{1,3});

                    oldx = reshape(oldx, [numel(oldx), 1]);
                    oldy = reshape(oldy, [numel(oldy), 1]);
                    oldz = reshape(oldz, [numel(oldz), 1]);

                    % Durchfühung der Interpolation
                    stepsTFieldInterp = griddata(oldx, oldy, oldz, stepsT{j}, newx, newy, newz);

                    if sum(isnan(stepsTFieldInterp)) ~= 0
                        valueNan = isnan(stepsTFieldInterp);
                        secondInterp = griddata(oldx, oldy, oldz, stepsT{j}, newx, newy, newz, 'nearest');
                        stepsTFieldInterp(valueNan) = secondInterp(valueNan);
                    end

                    % Überprüfen auf Schmelztemperatur
                    checkMelt(:,j) = stepsTFieldInterp > melt;
                end

                % Verodern aller Zeitschritte
                checkMelt = any(checkMelt, 2);

                % Finden aller Punkte über Schmelztemperatur
                nonzerosEntries = find(checkMelt == 1);

                s =  [interpD, interpD, interpD];

                % Punkte in Indizes umwandeln
                [I, J, K] = ind2sub(s, nonzerosEntries);

                % Bereich für erneute Suche festlegen
                xIdx(2) = newxLin(max(J)+2);
                xIdx(1) = newxLin(min(J)-2);

                yIdx(2) = newyLin(max(I)+2);
                yIdx(1) = newyLin(min(I)-2);

                zIdx(2) = newzLin(max(K)+2);
                zIdx(1) = newzLin(min(K));

                % Erneute Berechnung starten
                [fineStepsFields, againFieldDiskretization] = this.RunAgain(xIdx, yIdx, zIdx, i);

                checkMeltAgain = zeros(interpD^3, length(fineStepsFields));
                parfor j = 1:length(fineStepsFields)
                    % Alte Diskretisierung in richtige Form bringen
                    [oldx, oldy, oldz] = meshgrid(againFieldDiskretization{j}{1,1}, ...
                        againFieldDiskretization{j}{1,2}, ...
                        againFieldDiskretization{j}{1,3});

                    oldx = reshape(oldx, [numel(oldx), 1]);
                    oldy = reshape(oldy, [numel(oldy), 1]);
                    oldz = reshape(oldz, [numel(oldz), 1]);

                    % Durchfühung der Interpolation
                    stepsTFieldInterp = griddata(oldx, oldy, oldz, fineStepsFields{j}, newx, newy, newz);

                    checkMeltAgain(:,j) = stepsTFieldInterp > melt;
                end

                % Verodern der neuen "genaueren" Punkte
                checkMeltAgain = any(checkMeltAgain, 2);

                % Speichern der Ergebnisse
                this.checkingMelt{i,1} = checkMelt;
                this.checkingMelt{i,2} = checkMeltAgain;

                this.fineStepsTFields{i} = fineStepsFields;
            end
        end
    end

    methods (Access = private)
        function [fineStepsTFields, againFieldDiskretization] = RunAgain(this, xIdx, yIdx, zIdx, versNum)
            againConfig = Config();

            % Anpassen an zu wiederholenden Versuch
            againConfig.Oscillation.AmplitudeX = this.finishedTask.InputVariParam(versNum, 1);
            againConfig.Oscillation.AmplitudeY = this.finishedTask.InputVariParam(versNum, 1);

            againConfig.Oscillation.FrequencyX = this.finishedTask.InputVariParam(versNum, 2);
            againConfig.Oscillation.FrequencyY = this.finishedTask.InputVariParam(versNum, 2);

            againConfig.Oscillation.Velocity = this.finishedTask.InputVariParam(versNum, 3);

            againConfig.WeldingParameter.LaserPower = this.finishedTask.InputVariParam(versNum, 4);

            againConfig.WeldingParameter.Fokus = this.finishedTask.InputVariParam(versNum, 5);

            againConfig.Oscillation.SeamLength = this.finishedTask.InputOscillation(versNum, 1);
            againConfig.Oscillation.Discretization = this.finishedTask.InputOscillation(versNum, 2);

            againConfig.Material.ThermalConductivity = this.finishedTask.InputMaterial(versNum, 1);
            againConfig.Material.Density = this.finishedTask.InputMaterial(versNum, 2);
            againConfig.Material.HeatCapacity = this.finishedTask.InputMaterial(versNum, 3);
            againConfig.Material.FresnelEpsilon = this.finishedTask.InputMaterial(versNum, 4);
            againConfig.Material.FusionEnthalpy = this.finishedTask.InputMaterial(versNum, 5);
            againConfig.Material.MeltingTemperature = this.finishedTask.InputMaterial(versNum, 6);
            againConfig.Material.VaporTemperature = this.finishedTask.InputMaterial(versNum, 7);
            againConfig.Material.AmbientTemperature = this.finishedTask.InputMaterial(versNum, 8);

            againConfig.ComponentGeo.L = this.finishedTask.InputComponent(versNum, 1);
            againConfig.ComponentGeo.B = this.finishedTask.InputComponent(versNum, 2);
            againConfig.ComponentGeo.D = this.finishedTask.InputComponent(versNum, 3);
            againConfig.ComponentGeo.Dx = this.finishedTask.InputComponent(versNum, 4);
            againConfig.ComponentGeo.Dy = this.finishedTask.InputComponent(versNum, 5);
            againConfig.ComponentGeo.Dz = this.finishedTask.InputComponent(versNum, 6);

            againConfig.WeldingParameter.WaveLength = this.finishedTask.InputWelding(versNum, 1);
            againConfig.WeldingParameter.WaistSize = this.finishedTask.InputWelding(versNum, 2);

            % Neues Trajektorien Objekt
            againTrajObj = CalcTrajectory(againConfig);
            againTrajObj.CalcOscillation();

            % Anpassen des auszuwertenden Bereichs
            oldXgrid = againConfig.ComponentGeo.FieldGrid.X;
            oldYgrid = againConfig.ComponentGeo.FieldGrid.Y;
            oldZgrid = againConfig.ComponentGeo.FieldGrid.Z;

            xgrid = linspace(xIdx(1), xIdx(2), length(oldXgrid));
            ygrid = linspace(yIdx(1), yIdx(2), length(oldYgrid));
            zgrid = linspace(zIdx(1), zIdx(2), length(oldZgrid));

            [x, y, z] = meshgrid(xgrid, ygrid, zgrid);

            newCompMesh = horzcat(reshape(x, numel(x) ,1), ...
                reshape(y, numel(y), 1), ...
                reshape(z, numel(z), 1));

            % Übertragen des neuen Netzes auf aktuelles Trajektorien Objekt
            againTrajObj.ComponentMesh = newCompMesh;

            % Festlegen der zu berechnenden Schritte
            evalueAgainSteps = 1:1:length(againTrajObj.WeldingTrajectory.X)-1;

            % Berechnung der Zeitschritte
            againTimeStepObj = TimeSteps(againConfig, againTrajObj, this.finishedTask.CalibrationStorage{versNum}, evalueAgainSteps);
            againTimeStepObj.Calc('normal');

            % Rückgabe der berechneten Zeitschritte
            fineStepsTFields = againTimeStepObj.TFieldTimeStep;

            % Rückgabe des verwendeten Netzes
            againFieldDiskretization = againTimeStepObj.AdaptMeshDiscretisation;
        end
    end

end


text:
"""CodeLab for displaying error stack trace w/ MLIR-based converter."""

import sys

from absl import app

import tensorflow as tf

def suppress_exception(f):
  def wrapped():
    try:
      f()
    except:  # pylint: disable=bare-except
      pass
  return wrapped

class TestModule(tf.Module):
  """The test model has unsupported op."""

  @tf.function(input_signature=[tf.TensorSpec(shape=[3, 3], dtype=tf.float32)])
  def model(self, x):
    y = tf.math.reciprocal(x)  # Not supported
    return y + y

# comment out the `@suppress_exception` to display the stack trace
@suppress_exception
def test_from_saved_model():
  """displaying stack trace when converting saved model."""
  test_model = TestModule()
  saved_model_path = '/tmp/test.saved_model'
  save_options = tf.saved_model.SaveOptions(save_debug_info=True)
  tf.saved_model.save(test_model, saved_model_path, options=save_options)

  # load the model and convert
  converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_path)
  converter.convert()

# comment out the `@suppress_exception` to display the stack trace
# @suppress_exception
def test_from_concrete_function():
  """displaying stack trace when converting concrete function."""
  @tf.function(input_signature=[tf.TensorSpec(shape=[3, 3], dtype=tf.float32)])
  def model(x):
    y = tf.math.reciprocal(x)  # not supported
    return y + y

  func = model.get_concrete_function()
  converter = tf.lite.TFLiteConverter.from_concrete_functions([func], model)
  converter.convert()

def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  sys.stdout.write('==== Testing from_concrete_functions ====\n')
  test_from_concrete_function()

  sys.stdout.write('==== Testing from_saved_model ====\n')
  test_from_saved_model()

if __name__ == '__main__':
  app.run(main)

redpajama_set_name: RedPajamaGithub


text:
package rkt

import "github.com/coreos/rkt/networking/netinfo"

// AppState defines the state of the app.
type AppState string

const (
	AppStateUnknown AppState = "unknown"
	AppStateCreated AppState = "created"
	AppStateRunning AppState = "running"
	AppStateExited  AppState = "exited"
)

type (
	// Mount defines the mount point.
	Mount struct {
		// Name of the mount.
		Name string `json:"name"`
		// Container path of the mount.
		ContainerPath string `json:"container_path"`
		// Host path of the mount.
		HostPath string `json:"host_path"`
		// Whether the mount is read-only.
		ReadOnly bool `json:"read_only"`
		// TODO(yifan): What about 'SelinuxRelabel bool'?
	}

	// App defines the app object.
	App struct {
		// Name of the app.
		Name string `json:"name"`
		// State of the app, can be created, running, exited, or unknown.
		State AppState `json:"state"`
		// Creation time of the container, nanoseconds since epoch.
		CreatedAt *int64 `json:"created_at,omitempty"`
		// Start time of the container, nanoseconds since epoch.
		StartedAt *int64 `json:"started_at,omitempty"`
		// Finish time of the container, nanoseconds since epoch.
		FinishedAt *int64 `json:"finished_at,omitempty"`
		// Exit code of the container.
		ExitCode *int32 `json:"exit_code,omitempty"`
		// Image ID of the container.
		ImageID string `json:"image_id"`
		// Mount points of the container.
		Mounts []*Mount `json:"mounts,omitempty"`
		// Annotations of the container.
		Annotations map[string]string `json:"annotations,omitempty"`
	}

	// Pod defines the pod object.
	Pod struct {
		// UUID of the pod.
		UUID string `json:"name"`
		// State of the pod, all valid values are defined in pkg/pod/pods.go.
		State string `json:"state"`
		// Networks are the information of the networks.
		Networks []netinfo.NetInfo `json:"networks,omitempty"`
		// AppNames are the names of the apps.
		AppNames []string `json:"app_names,omitempty"`
	}
)


text:
import * as React from 'react';

declare namespace F7Subnavbar {
  interface Props {
    slot? : string
    id? : string | number
    className? : string
    style? : React.CSSProperties
    sliding? : boolean
    title? : string
    inner? : boolean
    color? : string
    colorTheme? : string
    textColor? : string
    bgColor? : string
    borderColor? : string
    rippleColor? : string
    themeDark? : boolean

  }
}
declare class F7Subnavbar extends React.Component<F7Subnavbar.Props, {}> {

}
export default F7Subnavbar;


text:
AutoTileGenRearranger
=====================

A simple tool to convert the mangled mess of tiles output by [AutoTileGen](http://autotilegen.com/) into something a little more friendly.

It turns something like this:

![Sample AutoTileGen Output](https://raw.githubusercontent.com/FuzzyWuzzie/AutoTileGenRearranger/master/Tileset.png "Sample AutoTileGen Output")

Into this:

![Human-Friendly Version](https://raw.githubusercontent.com/FuzzyWuzzie/AutoTileGenRearranger/master/Tileset.png.r.png "Human-Friendly Version")

Requirements
============

* Python
* ImageMagick
* Python Wand
    - Install with: `pip install wand`

Usage
=====

```bash
python AutoTileGenRearranger.py Tileset.png
```

* Replace `Tileset.png` with the file spit out by AutoTileGen.
* The output file would then be `Tileset.png.r.png`


text:
@implementation CommodityModel

#pragma mark 根据字典初始化商品对象
-(CommodityModel *)initWithDictionary:(NSDictionary *)dic{
    if(self=[super init]){
        self.Id=[dic[@"Id"] longLongValue];
        self.commodityImageUrl=dic[@"commodityImageUrl"];
        self.commodityName=dic[@"commodityName"];
        self.commodityPrice=dic[@"commodityPrice"];
        self.commodityZX=dic[@"commodityZX"];
        self.commodityPraise=dic[@"commodityPraise"];
        self.commodityPerson=dic[@"commodityPerson"];
    }
    return self;
}

#pragma mark 初始化对象(静态方法)
+(CommodityModel *)commodityWithDictionary:(NSDictionary *)dic{
    CommodityModel *commodity=[[CommodityModel alloc]initWithDictionary:dic];
    return commodity;
}

-(NSString *)praise{
    return [NSString stringWithFormat:@"好评%@ %@人",_commodityPraise,_commodityPerson];
}

@end


text:
package edu.berkeley.nlp.util;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * A map from objects to doubles.  Includes convenience methods for getting,
 * setting, and incrementing element counts.  Objects not in the counter will
 * return a count of zero.  The counter is backed by a HashMap (unless specified
 * otherwise with the MapFactory constructor).
 *
 * @author Dan Klein
 */
public class Counter <E> implements Serializable {
  private static final long serialVersionUID = 1L;
  Map<E, Double> entries;

  /**
   * The elements in the counter.
   *
   * @return set of keys
   */
  public Set<E> keySet() {
    return entries.keySet();
  }

  /**
   * The number of entries in the counter (not the total count -- use totalCount() instead).
   */
  public int size() {
    return entries.size();
  }

  /**
   * True if there are no entries in the counter (false does not mean totalCount > 0)
   */
  public boolean isEmpty() {
    return size() == 0;
  }

  /**
   * Returns whether the counter contains the given key.  Note that this is the
   * way to distinguish keys which are in the counter with count zero, and those
   * which are not in the counter (and will therefore return count zero from
   * getCount().
   *
   * @param key
   * @return whether the counter contains the key
   */
  public boolean containsKey(E key) {
    return entries.containsKey(key);
  }

  /**
   * Get the count of the element, or zero if the element is not in the
   * counter.
   *
   * @param key
   * @return
   */
  public double getCount(E key) {
    Double value = entries.get(key);
    if (value == null)
      return 0;
    return value;
  }

  /**
   * Set the count for the given key, clobbering any previous count.
   *
   * @param key
   * @param count
   */
  public void setCount(E key, double count) {
    entries.put(key, count);
  }

  /**
   * Increment a key's count by the given amount.
   *
   * @param key
   * @param increment
   */
  public void incrementCount(E key, double increment) {
    setCount(key, getCount(key) + increment);
  }

  /**
   * Increment each element in a given collection by a given amount.
   */
  public void incrementAll(Collection<? extends E> collection, double count) {
    for (E key : collection) {
      incrementCount(key, count);
    }
  }

  public <T extends E> void incrementAll(Counter<T> counter) {
    for (T key : counter.keySet()) {
      double count = counter.getCount(key);
      incrementCount(key, count);
    }
  }

  /**
   * Finds the total of all counts in the counter.  This implementation iterates
   * through the entire counter every time this method is called.
   *
   * @return the counter's total
   */
  public double totalCount() {
    double total = 0.0;
    for (Map.Entry<E, Double> entry : entries.entrySet()) {
      total += entry.getValue();
    }
    return total;
  }

  /**
   * Finds the key with maximum count.  This is a linear operation, and ties are broken arbitrarily.
   *
   * @return a key with minumum count
   */
  public E argMax() {
    double maxCount = Double.NEGATIVE_INFINITY;
    E maxKey = null;
    for (Map.Entry<E, Double> entry : entries.entrySet()) {
      if (entry.getValue() > maxCount || maxKey == null) {
        maxKey = entry.getKey();
        maxCount = entry.getValue();
      }
    }
    return maxKey;
  }

  /**
   * Returns a string representation with the keys ordered by decreasing
   * counts.
   *
   * @return string representation
   */
  public String toString() {
    return toString(keySet().size());
  }

  /**
   * Returns a string representation which includes no more than the
   * maxKeysToPrint elements with largest counts.
   *
   * @param maxKeysToPrint
   * @return partial string representation
   */
  public String toString(int maxKeysToPrint) {
    return asPriorityQueue().toString(maxKeysToPrint);
  }

  /**
   * Builds a priority queue whose elements are the counter's elements, and
   * whose priorities are those elements' counts in the counter.
   */
  public PriorityQueue<E> asPriorityQueue() {
    PriorityQueue<E> pq = new PriorityQueue<E>(entries.size());
    for (Map.Entry<E, Double> entry : entries.entrySet()) {
      pq.add(entry.getKey(), entry.getValue());
    }
    return pq;
  }

  public Counter() {
    this(new MapFactory.HashMapFactory<E, Double>());
  }

  public Counter(MapFactory<E, Double> mf) {
    entries = mf.newMap();
  }

  public Counter(Counter<? extends E> counter) {
    this();
    incrementAll(counter);
  }

  public Counter(Collection<? extends E> collection) {
    this();
    incrementAll(collection, 1.0);
  }

  /**
   * Destructively normalize this Counter in place.
   */
  public void normalize() {
    double totalCount = totalCount();
    for (E key : keySet()) {
      setCount(key, getCount(key) / totalCount);
    }
  }

  public static void main(String[] args) {
    Counter<String> counter = new Counter<String>();
    System.out.println(counter);
    counter.incrementCount("planets", 7);
    System.out.println(counter);
    counter.incrementCount("planets", 1);
    System.out.println(counter);
    counter.setCount("suns", 1);
    System.out.println(counter);
    counter.setCount("aliens", 0);
    System.out.println(counter);
    System.out.println(counter.toString(2));
    System.out.println("Total: " + counter.totalCount());
  }

	/**
	 * @return
	 */
	public Counter<E> toLogSpace() {
		Counter<E> newCounter = new Counter<E>(this);
		for (E key : newCounter.keySet()) {
			newCounter.setCount(key, Math.log(getCount(key)));
    }
		return newCounter;
	}

}


text: pkill kanshi; kanshi&


text:
/* { dg-do compile } */
/* { dg-options "-fgnu-tm -fdump-tree-optimized" } */

void orig(void);
void xyzzy(void) __attribute__((transaction_wrap (orig)));

void foo() { __transaction_relaxed { orig (); } }

/* { dg-final { scan-tree-dump-times "xyzzy" 1 "optimized" } } */
/* { dg-final { cleanup-tree-dump "optimized" } } */


text:
The S3 to HDFS Sync Application Template continuously ingests files as blocks from the configured Amazon S3 location to the destination path in HDFS retaining one-to-one file traceability.
- The application scales linearly with number of block readers.
- The application is fault tolerant and can withstand node and cluster outages without data loss.
- The application is also highly performant and can perform as fast as the network bandwidth allows.
- The only configuration user needs to provide is source S3 connection parameters, bucket, directory and destination HDFS path, filename.
- This enterprise grade application template will dramatically reduce your time to market and cost of operations.

Import the application from DataTorrent AppHub and launch it to ingest your files from Amazon S3 to HDFS. Follow the tutorial videos or walkthrough document below to launch the template and run it.

### Jumpstart
Import and run application template as an operable proof of concept. Please watch the [walkthrough video](https://www.youtube.com/watch?v=gA2eNL1wTCA) to import and launch the application.

### Logical Plan

Here is a preview of the logical plan of the application template

![Logical Plan](http://datatorrent.com/wp-content/uploads/2016/11/S3_HDFS_Sync_App_DAG.png)

### Launch App Properties

Here is a preview of the properties to be set at application launch

![Launch App Properties](http://datatorrent.com/wp-content/uploads/2016/11/S3_HDFS_Sync_App_properties.png)

### Resources

Please find the walkthrough docs for app template as follows:

  http://http://docs.datatorrent.com/app-templates/s3-to-hdfs-sync/

Please find the GitHub URL for app template as follows:

  https://github.com/DataTorrent/app-templates/tree/master/s3-to-hdfs-sync

Please send feedback or feature requests to:

  feedback@datatorrent.com

Please join the user discussion groups:

  dt-users@googlegroups.com


text:
package fr.isen.cir58.teamregalad.regaplay.database;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;

import fr.isen.cir58.teamregalad.regaplay.RegaPlayApplication;
import fr.isen.cir58.teamregalad.regaplay.audio.Song;

/**
 * Created by aymeric on 10/31/15.
 */
public class MediaStoreHelper implements BaseColumns {
    public static String getAlbumArt(Context context, String albumKey) {
        String path = null;

        Uri table = MediaStoreContract.TABLE_ALBUMS;
        String[] projection = new String[]{MediaStoreContract.ALBUMS_ALBUM_ART};
        String selection = MediaStoreContract.ALBUMS_SELECTION_BY_ALBUM_KEY;
        String[] selectionArgs = new String[]{albumKey};
        String sortOrder = null;

        Cursor cursor = context.getContentResolver().query(table, projection, selection, selectionArgs, sortOrder);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStoreContract.ALBUMS_ALBUM_ART));
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }

        return path;
    }

    public static String getGenre(Context context, Long id) {
        String genre = null;

        Uri table = MediaStoreContract.TABLE_GENRES;
        String[] projection = new String[]{MediaStoreContract.GENRES_NAME};
        String selection = MediaStoreContract.GENRES_SELECTION_BY_ID;
        String[] selectionArgs = new String[]{id.toString()};
        String sortOrder = null;

        Cursor cursor = context.getContentResolver().query(table, projection, selection, selectionArgs, sortOrder);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                genre = cursor.getString(cursor.getColumnIndex(MediaStoreContract.GENRES_NAME));
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }
        return genre;
    }

    public static String getSongPath(Context context, Long id) {
        String path = null;

        Uri table = MediaStoreContract.TABLE_SONGS;
        String[] projection = MediaStoreContract.SONGS_PROJECTION_FULL;
        String selection = MediaStoreContract.SONGS_SELECTION_BY_ID;
        String[] selectionArgs = new String[]{id.toString()};
        String sortOrder = null;

        Cursor cursor = context.getContentResolver().query(table, projection, selection, selectionArgs, sortOrder);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_PATH));
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }

        return path;
    }

    public static Song getSong(Long id) {
        Uri table = MediaStoreContract.TABLE_SONGS;
        String[] projection = MediaStoreContract.SONGS_PROJECTION_FULL;
        String selection = MediaStoreContract.SONGS_SELECTION_BY_ID;
        String[] selectionArgs = new String[]{id.toString()};
        String sortOrder = null;

        Song song = null;
        Cursor cursor = RegaPlayApplication.getContext().getContentResolver().query(table, projection, selection, selectionArgs, sortOrder);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                song = new Song(
                        id,
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_TITLE)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_PATH)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.SONGS_ARTIST_ID)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_ARTIST)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.ALBUMS_ID)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_ALBUM)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.SONGS_YEAR)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.SONGS_DURATION)),
                        MediaStoreHelper.getGenre(RegaPlayApplication.getContext(), cursor.getLong(cursor.getColumnIndex(MediaStoreContract.SONGS_ID))),
                        MediaStoreHelper.getAlbumArt(RegaPlayApplication.getContext(), cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_ALBUM_KEY)))
                );
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }

        return song;
    }

    public static Song getSong(String path) {
        Uri table = MediaStoreContract.TABLE_SONGS;
        String[] projection = MediaStoreContract.SONGS_PROJECTION_FULL;
        String selection = MediaStoreContract.SONGS_SELECTION_BY_PATH;
        String[] selectionArgs = new String[]{path};
        String sortOrder = null;

        Song song = null;
        Cursor cursor = RegaPlayApplication.getContext().getContentResolver().query(table, projection, selection, selectionArgs, sortOrder);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                song = new Song(
                        cursor.getLong(cursor.getColumnIndex(MediaStoreContract.SONGS_ID)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_TITLE)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_PATH)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.SONGS_ARTIST_ID)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_ARTIST)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.ALBUMS_ID)),
                        cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_ALBUM)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.SONGS_YEAR)),
                        cursor.getInt(cursor.getColumnIndex(MediaStoreContract.SONGS_DURATION)),
                        MediaStoreHelper.getGenre(RegaPlayApplication.getContext(), cursor.getLong(cursor.getColumnIndex(MediaStoreContract.SONGS_ID))),
                        MediaStoreHelper.getAlbumArt(RegaPlayApplication.getContext(), cursor.getString(cursor.getColumnIndex(MediaStoreContract.SONGS_ALBUM_KEY)))
                );
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }

        return song;
    }
}


text:
require 'erb'
require File.expand_path('../shared/html_escape', __FILE__)

describe "ERB::Util.html_escape" do
  it_behaves_like :erb_util_html_escape, :html_escape
end


text:
@import url("maven-base.css") screen;
@import url("maven-theme.css") screen;
@import url("site.css") screen;
@import url("print.css") print;


text:
package com.ariscdc.coding.algorithm.sort;

/**
 * @author ariscdc
 * Aris Dela Cruz
 * https://github.com/ariscdc
 *
 * 3. Insertion Sort
 *
 * Start with a sorted sub-list of size 1.
 * Insert the next element into the sorted sub-list at the right position.
 * In the worst case, if the list is originally sorted in descending order, N elements
 * are checked and swapped for every selected element to get to the right position.
 * It has very low overhead and is traditionally the sort of choice when used with
 * faster algorithms which follow the divide and conquer approach.
 *
 * Time Complexity: O(n^2)
 * Space Complexity: O(1)
 *
 * Stable sort, entities which are equal are maintained in original order.
 * O(n^2) comparisons and O(n^2) swaps
 * Adaptive, able to know and break if list is already sorted.
 *
 * 20160207 1920-1955 (35 mins.)
 * 20160207 2140-2150 (10 mins.)
 *                    (45 mins.)
 */
public class InsertionSort {

    public static int[] sort(int[] elements) {

        if (elements == null || elements.length < 2) return elements;

        int swaps = 1;
        for (int i = 0; i < elements.length - 1; i++) {
            for (int j = i + 1; j > 0; j--) {
                if (elements[j] < elements[j - 1]) {
                    swapElements(elements, j - 1, j);
                    print(elements, swaps++);
                } else {
                    break;
                }
            }
        }
        return elements;
    }

    private static void print(int[] elements, int step) {

        System.out.printf("%03d: {", step);
        for (int i = 0; i < elements.length; i++) {
            if (i > 0) System.out.print(",");
            System.out.print(elements[i]);
        }
        System.out.println("}");
    }

    private static void swapElements(int[] elements, int i, int j) {

        int temp = elements[i];
        elements[i] = elements[j];
        elements[j] = temp;
    }

    public static void main(String[] args) {
        {
            int[] elements = { 1, 3, 2, 1, 9, 7, 0, 5, 3, 8, 6, 4, 3 };
            print(elements, 0);
            sort(elements);
        }
        System.out.println();
        {
            int[] elements = { 5, 4, 3, 2, 1 };
            print(elements, 0);
            sort(elements);
        }
    }
}


text:
package org.hl7.fhir.instance.model.valuesets;

// Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0

import org.hl7.fhir.instance.model.EnumFactory;

public class V3ActPriorityEnumFactory implements EnumFactory<V3ActPriority> {

  public V3ActPriority fromCode(String codeString) throws IllegalArgumentException {
    if (codeString == null || "".equals(codeString))
      return null;
    if ("A".equals(codeString))
      return V3ActPriority.A;
    if ("CR".equals(codeString))
      return V3ActPriority.CR;
    if ("CS".equals(codeString))
      return V3ActPriority.CS;
    if ("CSP".equals(codeString))
      return V3ActPriority.CSP;
    if ("CSR".equals(codeString))
      return V3ActPriority.CSR;
    if ("EL".equals(codeString))
      return V3ActPriority.EL;
    if ("EM".equals(codeString))
      return V3ActPriority.EM;
    if ("P".equals(codeString))
      return V3ActPriority.P;
    if ("PRN".equals(codeString))
      return V3ActPriority.PRN;
    if ("R".equals(codeString))
      return V3ActPriority.R;
    if ("RR".equals(codeString))
      return V3ActPriority.RR;
    if ("S".equals(codeString))
      return V3ActPriority.S;
    if ("T".equals(codeString))
      return V3ActPriority.T;
    if ("UD".equals(codeString))
      return V3ActPriority.UD;
    if ("UR".equals(codeString))
      return V3ActPriority.UR;
    throw new IllegalArgumentException("Unknown V3ActPriority code '"+codeString+"'");
  }

  public String toCode(V3ActPriority code) {
    if (code == V3ActPriority.A)
      return "A";
    if (code == V3ActPriority.CR)
      return "CR";
    if (code == V3ActPriority.CS)
      return "CS";
    if (code == V3ActPriority.CSP)
      return "CSP";
    if (code == V3ActPriority.CSR)
      return "CSR";
    if (code == V3ActPriority.EL)
      return "EL";
    if (code == V3ActPriority.EM)
      return "EM";
    if (code == V3ActPriority.P)
      return "P";
    if (code == V3ActPriority.PRN)
      return "PRN";
    if (code == V3ActPriority.R)
      return "R";
    if (code == V3ActPriority.RR)
      return "RR";
    if (code == V3ActPriority.S)
      return "S";
    if (code == V3ActPriority.T)
      return "T";
    if (code == V3ActPriority.UD)
      return "UD";
    if (code == V3ActPriority.UR)
      return "UR";
    return "?";
  }

}


text:
`mt19937` is A Mersenne Twister pseudo-random generator of 32-bit numbers with a state size of 19937 bits.

## Usage ##

### Installing ###

`npm install mt19937`

### About seed ###

The default seed is 4357, Call Seed() set the seed if you need before Fetch any Number.

### Set Seed ###

```js
var mt19937 = require('mt19937');

console.log(mt19937.Seed(4357));
```

### Fetch a 32bit number ###

```js
var mt19937 = require('mt19937');

console.log(mt19937.Next());
```

### Fetch a real number (double) ###

```js
var mt19937 = require('mt19937');

console.log(mt19937.NextDouble());
```

## License ##

(The MIT License)

Copyright (c) 2013 Xiangyi Kong <xy.kong@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
layout:         post
title:          'Upcoming Event: PHP Tour Luxembourg'
date:           2015-03-15 08:00:00
author:         'fdewinne'
image:          '/assets/2015-03-15/phptour-share.png'
hasDescription: true
categories:     news
---
![PHP Tour Luxembourg](/assets/2015-03-15/phptour.png)

Luxembourg is very proud to host PHP Tour in May 2015 and so are we!
Discover all the details about this great upcoming event.

<!--more-->

![PHP Tour Luxembourg](/assets/2015-03-15/phptour.png)

As you may already know, continuousphp is involved in the organization of PHP Tour Luxembourg.
PHP Tour was created a few years back by the French speaking community [AFUP](http://afup.org).

The event will take place in our home country on May 12 & 13 in the beautiful
[Abbey Neumünster](http://www.neimenster.lu/en/Culture/Pratical-information/Contact).

Program was unveiled a few days ago and one of the talks we submitted was selected.
[Oswald de Riemaecker](/about-us/#oswaldderiemaecker) will present a session about
the creation of a development and production environment using AWS, Chef, Vagrant and Docker.

continuousphp will also have a booth there where you can stop by to discuss Continuous Delivery
and Agile methodologies.

[Lear more about PHP Tour Luxembourg](http://www.afup.org/pages/phptourluxembourg2015/index.php)


text:
// Type definitions for lolex 2.1
// Project: https://github.com/sinonjs/lolex
// Definitions by: Wim Looman <https://github.com/Nemo157>
//                 Josh Goldberg <https://github.com/joshuakgoldberg>
//                 Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/**
 * Timer object used in node.
 */
export interface NodeTimer {
    /**
     * Stub method call. Does nothing.
     */
    ref(): void;

    /**
     * Stub method call. Does nothing.
     */
    unref(): void;
}

/**
 * Timer identifier for clock scheduling.
 */
export type TimerId = number | NodeTimer;

/**
 * Lolex clock for a browser environment.
 */
type BrowserClock = LolexClock<number>;

/**
 * Lolex clock for a Node environment.
 */
type NodeClock = LolexClock<NodeTimer> & {
    /**
     * Mimicks process.hrtime().
     *
     * @param prevTime   Previous system time to calculate time elapsed.
     * @returns High resolution real time as [seconds, nanoseconds].
     */
    hrtime(prevTime?: [number, number]): [number, number];
};

/**
 * Clock object created by lolex.
 */
type Clock = BrowserClock | NodeClock;

/**
 * Names of clock methods that may be faked by install.
 */
type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime";

/**
 * Controls the flow of time.
 */
export interface LolexClock<TTimerId extends TimerId> {
    /**
     * Current clock time.
     */
    now: number;

    /**
     * Implements the Date object but using this clock to provide the correct time.
     */
    Date: typeof Date;

    /**
     * Schedules a callback to be fired once timeout milliseconds have ticked by.
     *
     * @param callback   Callback to be fired.
     * @param timeout   How many ticks to wait to run the callback.
     * @param args   Any extra arguments to pass to the callback.
     * @returns Time identifier for cancellation.
     */
    setTimeout(callback: () => any, timeout: number, ...args: any[]): TTimerId;

    /**
     * Clears a timer, as long as it was created using setTimeout.
     *
     * @param id   Timer ID or object.
     */
    clearTimeout(id: TTimerId): void;

    /**
     * Schedules a callback to be fired every time timeout milliseconds have ticked by.
     *
     * @param callback   Callback to be fired.
     * @param timeout   How many ticks to wait between callbacks.
     * @param args   Any extra arguments to pass to the callback.
     * @returns Time identifier for cancellation.
     */
    setInterval(callback: () => any, timeout: number, ...args: any[]): TTimerId;

    /**
     * Clears a timer, as long as it was created using setInterval.
     *
     * @param id   Timer ID or object.
     */
    clearInterval(id: TTimerId): void;

    /**
     * Schedules the callback to be fired once 0 milliseconds have ticked by.
     *
     * @param callback   Callback to be fired.
     * @remarks You'll still have to call clock.tick() for the callback to fire.
     * @remarks If called during a tick the callback won't fire until 1 millisecond has ticked by.
     */
    setImmediate(callback: () => any): TTimerId;

    /**
     * Clears a timer, as long as it was created using setImmediate.
     *
     * @param id   Timer ID or object.
     */
    clearImmediate(id: TTimerId): void;

    /**
     * Simulates process.nextTick();
     */
    nextTick(callback: () => void): void;

    /**
     * Advances the clock to the the moment of the first scheduled timer, firing it.
     */
    next(): void;

    /**
     * Advance the clock, firing callbacks if necessary.
     *
     * @param time   How many ticks to advance by.
     */
    tick(time: number | string): void;

    /**
     * Runs all pending timers until there are none remaining.
     *
     * @remarks  If new timers are added while it is executing they will be run as well.
     */
    runAll(): void;

    /**
     * Takes note of the last scheduled timer when it is run, and advances the clock to
     * that time firing callbacks as necessary.
     */
    runToLast(): void;

    /**
     * Simulates a user changing the system clock.
     *
     * @param now   New system time.
     * @remarks This affects the current time but it does not in itself cause timers to fire.
     */
    setSystemTime(now?: number | Date): void;

    /**
     * Restores the original methods on the context that was passed to lolex.install,
     * or the native timers if no context was given.
     */
    uninstall(): void;
}

/**
 * Creates a clock.
 *
 * @param now   Current time for the clock.
 * @param loopLimit    Maximum number of timers that will be run when calling runAll()
 *                     before assuming that we have an infinite loop and throwing an error
 *                     (by default, 1000).
 * @type TClock   Type of clock to create.
 * @remarks The default epoch is 0.
 */
export declare function createClock<TClock extends Clock>(now?: number | Date, loopLimit?: number): TClock;

export interface LolexInstallOpts {
    /**
     * Installs lolex onto the specified target context (default: global)
     */
    target?: any;

    /**
     * Installs lolex with the specified unix epoch (default: 0)
     */
    now?: number;

    /**
     * An array with explicit function names to hijack. When not set, lolex will automatically fake all methods except nextTick
     * e.g., lolex.install({ toFake: ["setTimeout", "nextTick"]}) will fake only setTimeout and nextTick
     */
    toFake?: FakeMethod[];

    /**
     * The maximum number of timers that will be run when calling runAll() (default: 1000)
     */
    loopLimit?: number;

    /**
     * Tells lolex to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by
     * 20ms for every 20ms change in the real system time) (default: false)
     */
    shouldAdvanceTime?: boolean;

    /**
     * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change
     * in the real system time (default: 20)
     */
    advanceTimeDelta?: number;
}

/**
 * Creates a clock and installs it globally.
 *
 * @param now   Current time for the clock, as with lolex.createClock().
 * @param toFake   Names of methods that should be faked.
 * @type TClock   Type of clock to create.
 */
export declare function install<TClock extends Clock>(opts?: LolexInstallOpts): TClock;


text:
package column

import (
	"github.com/kshvakov/clickhouse/lib/binary"
)

type UInt8 struct{ base }

func (UInt8) Read(decoder *binary.Decoder) (interface{}, error) {
	v, err := decoder.UInt8()
	if err != nil {
		return uint8(0), err
	}
	return v, nil
}

func (u *UInt8) Write(encoder *binary.Encoder, v interface{}) error {
	switch v := v.(type) {
	case bool:
		return encoder.Bool(v)
	case uint8:
		return encoder.UInt8(v)
	case int64:
		return encoder.UInt8(uint8(v))
	case int:
		return encoder.UInt8(uint8(v))

	// this relies on Nullable never sending nil values through
	case *bool:
		return encoder.Bool(*v)
	case *uint8:
		return encoder.UInt8(*v)
	case *int64:
		return encoder.UInt8(uint8(*v))
	case *int:
		return encoder.UInt8(uint8(*v))
	}

	return &ErrUnexpectedType{
		T:      v,
		Column: u,
	}
}


text:
using Newtonsoft.Json;

namespace Ghpr.Core.Settings
{
    [JsonObject(MemberSerialization.OptIn)]
    public class ReporterSettings
    {
        [JsonProperty(PropertyName = "default")]
        public ProjectSettings DefaultSettings { get; set; }

        [JsonProperty(PropertyName = "projects")]
        public SpecificProjectSettings[] Projects { get; set; }
    }
}


text:
'use strict';

/**
* Extract the stem of a given word.
*
* @module @stdlib/nlp/porter-stemmer
*
* @example
* var porterStemmer = require( '@stdlib/nlp/porter-stemmer' );
*
* var out = porterStemmer( 'walking' );
* // returns 'walk'
*
* out = porterStemmer( 'walked' );
* // returns 'walk'
*
* out = porterStemmer( 'walks' );
* // returns 'walk'
*/

// MODULES //

var main = require( './main.js' );

// EXPORTS //

module.exports = main;


text:
typedef NS_OPTIONS(NSUInteger, EXAVAudioSessionMode)
{
  // These are enumerated in ascending order of priority.
  // The EXAVAudioSessionMode of the current experience (managed by EXAV) should be
  // the maximum of the EXAVAudioSessionModes required by each of the live EXAVObjects.
  EXAVAudioSessionModeInactive    = 0,
  EXAVAudioSessionModeActiveMuted = 1,
  EXAVAudioSessionModeActive      = 2
};

@protocol EXAVObject <NSObject> // For EXAVPlayerData and EXVideoView to interact with the Audio Session properly

- (void)pauseImmediately;

- (EXAVAudioSessionMode)getAudioSessionModeRequired; // TODO (clarity): is needsAudioSession a better name?

- (void)appDidForeground;

- (void)appDidBackgroundStayActive:(BOOL)stayActive;

- (void)handleAudioSessionInterruption:(NSNotification*)notification;

- (void)handleMediaServicesReset:(void (^)(void))finishCallback;

@end


text:
require "spec_helper"
require "digest/md5"
require "tmpdir"
require "chef/mixin/file_class"

class Chef::CFCCheck
  include Chef::Mixin::FileClass
end

describe Chef::Provider::RemoteDirectory do
  before do
    allow_any_instance_of(Chef::FileAccessControl).to receive(:set_all)

    @resource = Chef::Resource::RemoteDirectory.new(File.join(Dir.tmpdir, "tafty"))
    # in CHEF_SPEC_DATA/cookbooks/openldap/files/default/remotedir
    @resource.source "remotedir"
    @resource.cookbook("openldap")

    @cookbook_repo = ::File.expand_path(::File.join(CHEF_SPEC_DATA, "cookbooks"))
    Chef::Cookbook::FileVendor.fetch_from_disk(@cookbook_repo)

    @node = Chef::Node.new
    cl = Chef::CookbookLoader.new(@cookbook_repo)
    cl.load_cookbooks
    @cookbook_collection = Chef::CookbookCollection.new(cl)

    @events = Chef::EventDispatch::Dispatcher.new
    @run_context = Chef::RunContext.new(@node, @cookbook_collection, @events)

    @provider = Chef::Provider::RemoteDirectory.new(@resource, @run_context)
    @provider.current_resource = @resource.clone
  end

  describe "when the contents of the directory changed on the first run and not on the second run" do
    before do
      @resource_second_run = @resource.clone
      @provider_second_run = Chef::Provider::RemoteDirectory.new(@resource_second_run, @run_context)
      @provider.run_action(:create)
      @provider_second_run.run_action(:create)
    end
    it "identifies that the state has changed the after first run" do
      @provider_second_run.new_resource.updated_by_last_action? == true
    end
    it "identifies that the state has not changed after the second run" do
      @provider_second_run.new_resource.updated_by_last_action? == false
    end
  end

  describe "when access control is configured on the resource" do
    before do
      @resource.mode  "0750"
      @resource.group "wheel"
      @resource.owner "root"

      @resource.files_mode  "0640"
      @resource.files_group "staff"
      @resource.files_owner "toor"
      @resource.files_backup 23

      @resource.source "remotedir_root"
    end

    it "configures access control on intermediate directorys" do
      directory_resource = @provider.send(:directory_resource, File.join(Dir.tmpdir, "intermediate_dir"))
      expect(directory_resource.path).to  eq(File.join(Dir.tmpdir, "intermediate_dir"))
      expect(directory_resource.mode).to  eq("0750")
      expect(directory_resource.group).to eq("wheel")
      expect(directory_resource.owner).to eq("root")
      expect(directory_resource.recursive).to be_truthy
    end

    it "configures access control on files in the directory" do
      @resource.cookbook "berlin_style_tasty_cupcakes"
      cookbook_file = @provider.send(:cookbook_file_resource,
                                    "/target/destination/path.txt",
                                    "relative/source/path.txt")
      expect(cookbook_file.cookbook_name).to  eq("berlin_style_tasty_cupcakes")
      expect(cookbook_file.source).to         eq("remotedir_root/relative/source/path.txt")
      expect(cookbook_file.mode).to           eq("0640")
      expect(cookbook_file.group).to          eq("staff")
      expect(cookbook_file.owner).to          eq("toor")
      expect(cookbook_file.backup).to         eq(23)
    end

    it "respects sensitive flag" do
      @resource.cookbook "gondola_rides"
      @resource.sensitive true
      cookbook_file = @provider.send(:cookbook_file_resource,
                                    "/target/destination/path.txt",
                                    "relative/source/path.txt")
      expect(cookbook_file.sensitive).to eq(true)

      @resource.sensitive false
      cookbook_file = @provider.send(:cookbook_file_resource,
                                    "/target/destination/path.txt",
                                    "relative/source/path.txt")
      expect(cookbook_file.sensitive).to eq(false)
    end
  end

  describe "when creating the remote directory" do
    before do
      @node.automatic_attrs[:platform] = :just_testing
      @node.automatic_attrs[:platform_version] = :just_testing

      @destination_dir = Dir.mktmpdir << "/remote_directory_test"
      @resource.path(@destination_dir)
    end

    after { FileUtils.rm_rf(@destination_dir) }

    # CHEF-3552
    it "creates the toplevel directory without error " do
      @resource.recursive(false)
      @provider.run_action(:create)
      expect(::File.exist?(@destination_dir)).to be_truthy
    end

    it "transfers the directory with all contents" do
      @provider.run_action(:create)
      expect(::File.exist?(@destination_dir + "/remote_dir_file1.txt")).to be_truthy
      expect(::File.exist?(@destination_dir + "/remote_dir_file2.txt")).to be_truthy
      expect(::File.exist?(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")).to be_truthy
      expect(::File.exist?(@destination_dir + "/remotesubdir/remote_subdir_file2.txt")).to be_truthy
      expect(::File.exist?(@destination_dir + "/remotesubdir/.a_dotfile")).to be_truthy
      expect(::File.exist?(@destination_dir + "/.a_dotdir/.a_dotfile_in_a_dotdir")).to be_truthy
    end

    describe "only if it is missing" do
      it "should not overwrite existing files" do
        @resource.overwrite(true)
        @provider.run_action(:create)

        File.open(@destination_dir + "/remote_dir_file1.txt", "a") { |f| f.puts "blah blah blah" }
        File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") { |f| f.puts "blah blah blah" }
        file1md5 = Digest::MD5.hexdigest(File.read(@destination_dir + "/remote_dir_file1.txt"))
        subdirfile1md5 = Digest::MD5.hexdigest(File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt"))

        @provider.run_action(:create_if_missing)

        expect(file1md5.eql?(Digest::MD5.hexdigest(File.read(@destination_dir + "/remote_dir_file1.txt")))).to be_truthy
        expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")))).to be_truthy
      end
    end

    describe "with purging enabled" do
      before { @resource.purge(true) }

      it "removes existing files if purge is true" do
        @provider.run_action(:create)
        FileUtils.touch(@destination_dir + "/marked_for_death.txt")
        FileUtils.touch(@destination_dir + "/remotesubdir/marked_for_death_again.txt")
        @provider.run_action(:create)

        expect(::File.exist?(@destination_dir + "/remote_dir_file1.txt")).to be_truthy
        expect(::File.exist?(@destination_dir + "/remote_dir_file2.txt")).to be_truthy
        expect(::File.exist?(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")).to be_truthy
        expect(::File.exist?(@destination_dir + "/remotesubdir/remote_subdir_file2.txt")).to be_truthy

        expect(::File.exist?(@destination_dir + "/marked_for_death.txt")).to be_falsey
        expect(::File.exist?(@destination_dir + "/remotesubdir/marked_for_death_again.txt")).to be_falsey
      end

      it "removes files in subdirectories before files above" do
        @provider.run_action(:create)
        FileUtils.mkdir_p(@destination_dir + "/a/multiply/nested/directory/")
        FileUtils.touch(@destination_dir + "/a/foo.txt")
        FileUtils.touch(@destination_dir + "/a/multiply/bar.txt")
        FileUtils.touch(@destination_dir + "/a/multiply/nested/baz.txt")
        FileUtils.touch(@destination_dir + "/a/multiply/nested/directory/qux.txt")
        @provider.run_action(:create)
        expect(::File.exist?(@destination_dir + "/a/foo.txt")).to be_falsey
        expect(::File.exist?(@destination_dir + "/a/multiply/bar.txt")).to be_falsey
        expect(::File.exist?(@destination_dir + "/a/multiply/nested/baz.txt")).to be_falsey
        expect(::File.exist?(@destination_dir + "/a/multiply/nested/directory/qux.txt")).to be_falsey
      end

      it "removes directory symlinks properly", :not_supported_on_win2k3 do
        symlinked_dir_path = @destination_dir + "/symlinked_dir"
        @provider.action = :create
        @provider.run_action

        @fclass = Chef::CFCCheck.new

        Dir.mktmpdir do |tmp_dir|
          begin
            @fclass.file_class.symlink(tmp_dir.dup, symlinked_dir_path)
            expect(::File.exist?(symlinked_dir_path)).to be_truthy

            @provider.run_action

            expect(::File.exist?(symlinked_dir_path)).to be_falsey
            expect(::File.exist?(tmp_dir)).to be_truthy
          rescue Chef::Exceptions::Win32APIError
            skip "This must be run as an Administrator to create symlinks"
          end
        end
      end
    end

    describe "with overwrite disabled" do
      before { @resource.purge(false) }
      before { @resource.overwrite(false) }

      it "leaves modifications alone" do
        @provider.run_action(:create)
        ::File.open(@destination_dir + "/remote_dir_file1.txt", "a") { |f| f.puts "blah blah blah" }
        ::File.open(@destination_dir + "/remotesubdir/remote_subdir_file1.txt", "a") { |f| f.puts "blah blah blah" }
        file1md5 = Digest::MD5.hexdigest(::File.read(@destination_dir + "/remote_dir_file1.txt"))
        subdirfile1md5 = Digest::MD5.hexdigest(::File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt"))
        @provider.run_action(:create)
        expect(file1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + "/remote_dir_file1.txt")))).to be_truthy
        expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + "/remotesubdir/remote_subdir_file1.txt")))).to be_truthy
      end
    end

  end
end


text:
<?php

namespace Weew\Validator\Constraints;

use Weew\Validator\IConstraint;
use Weew\Validator\IValidationData;

/**
 * Checks if the value is a valid URL
 */
class UrlConstraint implements IConstraint {
    /**
     * @var string
     */
    protected $message;

    /**
     * UrlConstraint constructor.
     *
     * @param string $message
     */
    public function __construct($message = null) {
        $this->message = $message;
    }

    /**
     * Note, that any space characters in either the beginning or
     * the end of the string will result in a failure.
     *
     * @param $value
     * @param IValidationData $data
     *
     * @return bool
     */
    public function check($value, IValidationData $data = null) {
        if (is_string($value)) {
            return filter_var($value, FILTER_VALIDATE_URL) !== false;
        }

        return false;
    }

    /**
     * @return string
     */
    public function getMessage() {
        if ($this->message !== null) {
            return $this->message;
        }

        return 'Must be a url.';
    }

    /**
     * @return array
     */
    public function getOptions() {
        return [];
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.default = updateAshElementTree;

var _createAshElementTree = require('./createAshElementTree');

var _createAshElementTree2 = _interopRequireDefault(_createAshElementTree);

var _unmountComponents = require('./unmountComponents');

var _unmountComponents2 = _interopRequireDefault(_unmountComponents);

var _constants = require('../internals/constants');

var _constants2 = _interopRequireDefault(_constants);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var COMPONENT_ASH_ELEMENT = _constants2.default.COMPONENT_ASH_ELEMENT; /* eslint-disable complexity */

var ASH_NODE_ASH_ELEMENT = _constants2.default.ASH_NODE_ASH_ELEMENT;
var FUNCTION_ASH_ELEMENT = _constants2.default.FUNCTION_ASH_ELEMENT;

/**
 * Walks AshElement tree for updating.
 *
 * @param {AshElement} oldAshElement Old Ash Element
 * @param {AshElement} newAshElement New Ash Element
 * @param {Stream} stream View Stream
 * @param {boolean} isParentComponentDirty `True` if parent Component is dirty, else `false`
 * @returns {undefined} Always returns `undefined`
 */
function walkUpdateAshElementTree(oldAshElement, newAshElement, stream, isParentComponentDirty) {
	if (newAshElement === null && oldAshElement) {
		// deleting old children
		while (oldAshElement.parent.children.length) {
			(0, _unmountComponents2.default)(oldAshElement.parent.children[oldAshElement.parent.children.length - 1]);

			oldAshElement.parent.children.pop();
		}
	} else if (newAshElement && oldAshElement === null) {
		// the element tree is not complete
		(0, _createAshElementTree2.default)(newAshElement, stream);

		// new element must be added as a child
		newAshElement.parent.children[newAshElement.index] = newAshElement;
	} else if (newAshElement.type === COMPONENT_ASH_ELEMENT && oldAshElement.type === COMPONENT_ASH_ELEMENT && newAshElement.Spec === oldAshElement.Spec) {
		var newAshElementProps = newAshElement.args && newAshElement.args[0] ? newAshElement.args[0] : null;
		var newAshElementPassedChildren = newAshElement.args && newAshElement.args[1] ? newAshElement.args[1] : null;
		var oldAshElementPassedChildren = oldAshElement.args && oldAshElement.args[1] ? oldAshElement.args[1] : null;

		if (oldAshElement.instance.__isDirty || oldAshElement.instance.shouldUpdate(newAshElementProps) || newAshElementPassedChildren !== oldAshElementPassedChildren) {
			oldAshElement.args = newAshElement.args;
			oldAshElement.isDirty = true;
			oldAshElement.instance.__isDirty = false;

			oldAshElement.instance.onBeforeReceiveProps(newAshElementProps);

			oldAshElement.instance.props = newAshElementProps;
			oldAshElement.instance.children = newAshElementPassedChildren;

			// create child for the new element
			var render = oldAshElement.instance.render(oldAshElement.instance.props, oldAshElement.instance.state);

			oldAshElement.wasRendered = true;

			// adding children to the queue
			if (render) {
				render.owner = oldAshElement;
				render.parent = oldAshElement;
				render.index = 0;

				if (oldAshElement.children[0]) {
					walkUpdateAshElementTree(oldAshElement.children[0], render, stream, true);
				} else {
					walkUpdateAshElementTree(null, render, stream, true);
				}
			} else if (oldAshElement.children[0]) {
				// deleting old surplus children
				(0, _unmountComponents2.default)(oldAshElement.children[0]);
				oldAshElement.children.pop();
			}
		} else {
			walkUpdateAshElementTree(oldAshElement.children[0], oldAshElement.children[0], stream, false);
		}
	} else if (newAshElement.type === FUNCTION_ASH_ELEMENT && oldAshElement.type === FUNCTION_ASH_ELEMENT && newAshElement.spec === oldAshElement.spec) {
		var _newAshElementProps = newAshElement.args && newAshElement.args[0] ? newAshElement.args[0] : null;
		var oldAshElementProps = oldAshElement.args && oldAshElement.args[0] ? oldAshElement.args[0] : null;
		var _newAshElementPassedChildren = newAshElement.args && newAshElement.args[1] ? newAshElement.args[1] : null;
		var _oldAshElementPassedChildren = oldAshElement.args && oldAshElement.args[1] ? oldAshElement.args[1] : null;

		if (_newAshElementProps === oldAshElementProps && _newAshElementPassedChildren === _oldAshElementPassedChildren) {
			walkUpdateAshElementTree(oldAshElement.children[0], oldAshElement.children[0], stream, false);
		} else {
			// create child for the new element
			var _render = oldAshElement.spec(newAshElement.args[0], newAshElement.args[1]);

			oldAshElement.args = newAshElement.args;
			oldAshElement.isDirty = true;

			// adding children to the queue
			if (_render) {
				_render.owner = oldAshElement;
				_render.parent = oldAshElement;
				_render.index = 0;

				if (oldAshElement.children[0]) {
					walkUpdateAshElementTree(oldAshElement.children[0], _render, stream, true);
				} else {
					walkUpdateAshElementTree(null, _render, stream, true);
				}
			} else if (oldAshElement.children[0]) {
				// deleting old surplus children
				(0, _unmountComponents2.default)(oldAshElement.children[0]);
				oldAshElement.children.pop();
			}
		}
	} else if (newAshElement.type === ASH_NODE_ASH_ELEMENT && oldAshElement.type === ASH_NODE_ASH_ELEMENT) {
		if (isParentComponentDirty) {
			oldAshElement.args = newAshElement.args;
			oldAshElement.stream = stream;

			oldAshElement.instantiate();
		}

		// adding children to the queue
		for (var i = 0; i < newAshElement.children.length; i++) {
			if (newAshElement.children[i] && oldAshElement.children[i]) {
				newAshElement.children[i].owner = oldAshElement.owner;
				newAshElement.children[i].parent = oldAshElement;
				newAshElement.children[i].index = i;

				walkUpdateAshElementTree(oldAshElement.children[i], newAshElement.children[i], stream, isParentComponentDirty);
			} else if (newAshElement.children[i] && !oldAshElement.children[i]) {
				newAshElement.children[i].owner = oldAshElement.owner;
				newAshElement.children[i].parent = oldAshElement;
				newAshElement.children[i].index = i;

				walkUpdateAshElementTree(null, newAshElement.children[i], stream, isParentComponentDirty);
			}
		}

		// deleting old surplus children
		while (oldAshElement.children.length > newAshElement.children.length) {
			(0, _unmountComponents2.default)(oldAshElement.children[oldAshElement.children.length - 1]);
			oldAshElement.children.pop();
		}
	} else if (newAshElement.type === COMPONENT_ASH_ELEMENT && oldAshElement.type === COMPONENT_ASH_ELEMENT || newAshElement.type === COMPONENT_ASH_ELEMENT && oldAshElement.type === ASH_NODE_ASH_ELEMENT || newAshElement.type === COMPONENT_ASH_ELEMENT && oldAshElement.type === FUNCTION_ASH_ELEMENT || newAshElement.type === ASH_NODE_ASH_ELEMENT && oldAshElement.type === COMPONENT_ASH_ELEMENT || newAshElement.type === ASH_NODE_ASH_ELEMENT && oldAshElement.type === FUNCTION_ASH_ELEMENT || newAshElement.type === FUNCTION_ASH_ELEMENT && oldAshElement.type === FUNCTION_ASH_ELEMENT || newAshElement.type === FUNCTION_ASH_ELEMENT && oldAshElement.type === COMPONENT_ASH_ELEMENT || newAshElement.type === FUNCTION_ASH_ELEMENT && oldAshElement.type === ASH_NODE_ASH_ELEMENT) {
		newAshElement.owner = oldAshElement.owner;
		newAshElement.parent = oldAshElement.parent;
		newAshElement.index = oldAshElement.index;

		(0, _createAshElementTree2.default)(newAshElement, stream);
		(0, _unmountComponents2.default)(oldAshElement);

		// replace the old element
		if (oldAshElement.parent.type === COMPONENT_ASH_ELEMENT || oldAshElement.parent.type === FUNCTION_ASH_ELEMENT) {
			oldAshElement.parent.children[0] = newAshElement;
		} else if (oldAshElement.parent.type === ASH_NODE_ASH_ELEMENT) {
			oldAshElement.parent.children[oldAshElement.index] = newAshElement;
		}
	}
}

/**
 * Updates dirty component elements in AshElement tree.
 *
 * @param {AshElement} componentAshElement Component Ash Element to update
 * @param {ViewStream} stream ViewStream
 * @returns {AshElement} Updated Component Ash Element
 */
function updateAshElementTree(componentAshElement, stream) {
	var newAshElement = undefined;
	var oldAshElement = componentAshElement.children[0] || null;

	if (componentAshElement.instance.__isDirty) {
		newAshElement = componentAshElement.instance.render(componentAshElement.instance.props, componentAshElement.instance.state);
		newAshElement.wasRendered = true;
		componentAshElement.isDirty = true;

		if (newAshElement) {
			newAshElement.owner = componentAshElement;
			newAshElement.parent = componentAshElement;
			newAshElement.index = 0;
		}
	} else {
		newAshElement = componentAshElement.children[0] || null;
	}

	walkUpdateAshElementTree(oldAshElement, newAshElement, stream, componentAshElement.isDirty);

	return componentAshElement;
}


text:
angular.module('myApp.contacts')
    .component('users', {
        templateUrl: 'shared/users/users.html',
        controller: ['$scope', 'mocky', function($scope, mocky, $element){

            this.$onInit = function () {
                mocky.getContacts($scope);
            }
        }]
    })

.service("mocky",
    function ($http) {

        this.getContacts= function ($scope) {
            return $http.get('http://www.mocky.io/v2/580cd2d3100000a710540487')
                .then(function (response) {
                    $scope.users = response.data;
                }, function (response) {
                    $scope.users = [];
                });
        };
    }
)


text:
npm-config

Manage the npm configuration files

SYNOPSIS

npm.commands.config(args, callback)
var val = npm.config.get(key)
npm.config.set(key, val)

DESCRIPTION

This function acts much the same way as the command-line version.  The first
element in the array tells config what to do. Possible values are:

set

  Sets a config parameter.  The second element in args is interpreted as the
  key, and the third element is interpreted as the value.

get

  Gets the value of a config parameter. The second element in args is the
  key to get the value of.

delete (rm or del)

  Deletes a parameter from the config. The second element in args is the
  key to delete.

list (ls)

  Show all configs that aren't secret. No parameters necessary.

edit:

  Opens the config file in the default editor. This command isn't very useful
  programmatically, but it is made available.

To programmatically access npm configuration settings, or set them for
the duration of a program, use the npm.config.set and npm.config.get
functions instead.

SEE ALSO

npm(3)


text:
package me.lcw.jil.awt.parsers;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import me.lcw.jil.BaseImage;
import me.lcw.jil.ImageException;
import me.lcw.jil.awt.AWTImage;

public class PngFile {

  private PngFile(){
  }

  public static AWTImage open(byte[] ba) throws IOException, ImageException {
    return open(new ByteArrayInputStream(ba));
  }

  public static AWTImage open(InputStream is) throws IOException, ImageException {
    return AWTImage.fromBufferedImage(ImageIO.read(is));
  }

  public static AWTImage open(String filename) throws IOException, ImageException {
    return AWTImage.fromBufferedImage(ImageIO.read(new File(filename)));
  }

  public static void save(String saveTo, AWTImage image) throws IOException, ImageException {
    File file = new File(saveTo);
    ImageIO.write(image.getBufferedImage(), "png", file);
  }

  public static byte[] saveToByteArray(AWTImage image) throws IOException, ImageException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedImage tmp;
    if(image.getMode() == BaseImage.MODE.RGBA) {
      tmp = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
      tmp.getGraphics().drawImage(image.getBufferedImage(), 0, 0, null);
    } else {
      tmp = image.getBufferedImage();
    }
    ImageIO.write(tmp, "png", baos);
    return baos.toByteArray();
  }

}