text:
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from astropy.io import fits
#import MakeModel
from PyAstronomy import pyasl
import pandas as pd
import sys
sys.path.insert(0, '../../github/BF-rvplotter')
import BF_functions as bff
'''
Make a basic model of the atmospheric O2 A-band in the 7650 A region.
Write out this model at STP.
Fit this model to a FITS spectrum.
Based on the examples provided in the TelFit-1.2 package, available
here: http://www.as.utexas.edu/~kgulliks/projects.html
This is kind of hacked together and loosely based on BF_python.py...

Input: three text files - telfitin, timefile, and gausspar
(a list of FITS infiles, a list of JD timestamps, and guesses for velocity shifts)
The timefile contents don't matter one bit here

Output: two plots in succession (like BF_python.py), and RV shift info printed to screen
(manually save the shift info if you want, and then use specshift.py to remove the shift)
'''

telfitin =  '../../RG_spectra/9970396/infiles_arcesBF_telfit.txt'
timefile =  '../../RG_spectra/9970396/bjdinfile_arcesBF.txt'
gausspar =  '../../RG_spectra/9970396/gausspars_telfit.txt'
shiftfile = '../../RG_spectra/9970396/shifts_TEST.txt'

# Parameters for the broadening function (don't change w00 or n if you want the A-band!)
w00 = 7595
n = 1000
stepV = 1.5
mbf = 171

##### first, the option to make a basic model...
# once this file exists, you don't have to re-create it each time

temp = 273.15 # Kelvin
pres = 1013.25 # hPa (1 hectoPascal = 100 Pa = 1 mbar)
humid = 50 # percent relative humidity
o2val = 2.0e5
angle = 45.0
co2 = 368.50
o3 = 3.90/100
ch4 = 1.80
co = 1.40/10

# Set the start and end wavelength, **in nm**
# This is for the O2 A-band
#wavestart = 758
#waveend = 772

# Make an instance of the Modeler class
#modeler = MakeModel.Modeler()
#modeler.MakeModel(pressure=pres, temperature=temp, humidity=humid, o2=o2val,
#	save=True, libfile=None, lowfreq=1e7/waveend, highfreq=1e7/wavestart, resolution=31000)

# Manually access the model file
#modelfile = "transmission" + "-%.2f" % pres + "-%.2f" % temp + "-%.1f" % humid + "-%.1f" % angle + "-%.2f" % (co2) + "-%.2f" % (o3 * 100) + "-%.2f" % ch4 + "-%.2f" % (co * 10)
#wavemod, fluxmod = np.loadtxt(modelfile, unpack=True)
#wavemod = wavemod*10
#print(wavemod, fluxmod)

##### next, compare the model with a real spectrum and find the RV shift...

# set variables and read stuff in
isAPOGEE = False # a necessary bff.logify_spec parameter
period = 1.0 # nobody cares
BJD0 = 2450000.0 # nobody cares
rvstd = 0 # there's no standard star
bcvstd = 0 # there's no standard star
amp = 5.0 # arbitrary multiplication factor
w1, m, r = bff.logify_spec(isAPOGEE, w00, n, stepV, mbf)
nspec, filenamelist, datetimelist, wavelist, speclist, source = bff.read_specfiles(infiles=telfitin, bjdinfile=timefile)

# interpolate everything onto the same log-spaced grid
newspeclist = []
yoffset = 1
plt.axis([w1[0], w1[-1], 0, 27])
plt.xlabel('wavelength')
for i in range (0, nspec):
	newspec = np.interp(w1, wavelist[i], speclist[i])
	newspeclist.append(newspec)
	plt.plot(w1, newspeclist[i]+yoffset) #, label=datetimelist[i].iso[0:10])
	yoffset = yoffset + 1
#plt.legend()
plt.show()

# single value decomposition
svd = pyasl.SVD()
svd.decompose(newspeclist[0], m)
bflist = []
bfsmoothlist = []
for i in range (0, nspec):
	# Obtain the broadening function
	bf = svd.getBroadeningFunction(newspeclist[i]) # this one is like a matrix
	bfarray = svd.getBroadeningFunction(newspeclist[i], asarray=True)
	# Smooth the array-like broadening function
	bfsmooth = amp*pd.rolling_window(bfarray, window=5, win_type='gaussian', std=1.5, center=True)
	# The rolling window makes nans at the start because it's a punk.
	for j in range(0,len(bfsmooth)):
		if np.isnan(bfsmooth[j]) == True:
			bfsmooth[j] = 0
	bflist.append(bf)
	bfsmoothlist.append(bfsmooth)
# Obtain the indices in RV space that correspond to the BF
bf_ind = svd.getRVAxis(r, 1)

# plot the smoothed BFs
# this plot is boring, skip it
#plt.axis([-100, 70, -0.2, 12])
#plt.xlabel('Velocity (km s$^{-1}$)')
#plt.ylabel('Broadening Function (arbitrary amplitude)')
#yoffset = 0.0
#for i in range(1, nspec):
#	plt.plot(bf_ind, bfsmoothlist[i]+yoffset, color='b')
#	yoffset = yoffset + 0.4
#plt.show()

# fit the smoothed BFs with two gaussians (only one is really used here)
bffitlist = bff.gaussparty(gausspar, nspec, filenamelist, bfsmoothlist, bf_ind)
rvraw1 = []; rvraw1_err = []
rvraw1.append(0), rvraw1_err.append(0)
for i in range(1, len(bffitlist)):
    rvraw1.append(bffitlist[i][0][1])
    rvraw1_err.append(bffitlist[i][2][1])

# write results of the first fit gaussian only to an outfile
outfile = open(shiftfile, 'w')
for (image, rv, err) in zip(filenamelist[1:], rvraw1[1:], rvraw1_err[1:]):
    print(image, rv, err, file=outfile)
outfile.close()
print('Shifts saved to {0}'.format(shiftfile))

# plot final BFs in individual panels
windowcols = 4		                        # how many window columns there should be
windowrows = np.rint(nspec/windowcols)+1	# how many window rows there should be
xmin = -19
xmax = 19
ymin = -0.05
ymax = 0.7
fig = plt.figure(1, figsize=(15,10))
fig.text(0.5, 0.04, 'Velocity (km s$^{-1}$)', ha='center', va='center', size=26)
fig.text(0.07, 0.5, 'Broadening Function', ha='center', va='center', size=26, rotation='vertical')
for i in range (1,nspec):
	ax = fig.add_subplot(windowrows, windowcols,i)
	ax.yaxis.set_major_locator(MultipleLocator(0.2))
	if i!=1 and i!=5 and i!=9 and i!=13 and i!=17 and i!=21 and i!=25:
		ax.set_yticklabels(())
	if i!=20 and i!=21 and i!=22 and i!=23 and i!=24 and i!=25:
		ax.set_xticklabels(())
	plt.subplots_adjust(wspace=0, hspace=0)
	plt.axis([xmin, xmax, ymin, ymax])
	plt.tick_params(axis='both', which='major', labelsize=14)
	plt.plot(bf_ind, bfsmoothlist[i], color='k', lw=1.5, label='Smoothed BF')
	plt.plot(bf_ind, bffitlist[i][1], color='#e34a33', lw=1.5, label='Two-Gaussian fit')
	if i==23: ax.legend(bbox_to_anchor=(2.1,0.7), loc=1, borderaxespad=0.,
						frameon=False, prop={'size':20})
plt.show()


text:
using System.Security;
using System;
using TestLibrary;

[SecuritySafeCritical]
public class WeakReferenceCtor
{
    public static int Main(string[] args)
    {
        WeakReferenceCtor test = new WeakReferenceCtor();
        TestFramework.BeginTestCase("Testing WeakReference.Ctor (2)");

        if (test.RunTests())
        {
            TestFramework.EndTestCase();
            TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestFramework.EndTestCase();
            TestFramework.LogInformation("FAIL");
            return 0;
        }
    }

    public bool RunTests()
    {
        bool retVal = true;

        TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;

        return retVal;
    }

    // ATTENTION!!! ATTENTION!!! ATTENTION!!!
    //
    // There is no guarantee that WeakReference objects will be collected after GC.Collect().
    // The bottom line is, compiler generated temps for objects created locally (within the
    // same function), castings, boxing/unboxing will get their lifetimes extended to the
    // end of the function.
    //
    // All these are due to changes related to the MinOpts feature made during the
    // Silverlight/Arrowhead timeframe. For more information, see DevDiv Bugs 170524.
    //
    // Many of these behaviors are not documented. If any of the underlying implementation is
    // changed, the tests will need to be updated as well.

    public bool PosTest1()
    {
        bool retVal = true;
        TestFramework.BeginScenario("Test short WeakReference ctor");

        try
        {
            string testStr = "Test";
            WeakReference extWR = new WeakReference(WRHelper.CreateAnObject(testStr), false);

            if (!WRHelper.VerifyObject(extWR, testStr))
            {
                TestFramework.LogError("001", "WeakReference target not as expected. Expected : Test; Actual: " + extWR.Target.ToString());
                retVal = false;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            //Dev10 Bug #413556: WeakReference object incorrectly kept alive. Enable after the test is fixed.
            //
            //if (extWR.Target != null)
            //{
            //    TestFramework.LogError("002", "WeakReference target not as expected. Expected : null; Actual: " + extWR.Target.ToString());
            //    retVal = false;
            //}

            if (extWR.TrackResurrection != false)
            {
                TestFramework.LogError("003", "WeakReference track resurrection not as expected. Expected : false; Actual: " + extWR.TrackResurrection);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestFramework.LogError("004", "Unexpected exception occurred: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest2()
    {
        bool retVal = true;
        TestFramework.BeginScenario("Test long WeakReference ctor");

        try
        {
            string testStr = "Test";
            WeakReference extWR = new WeakReference(WRHelper.CreateAnObject(testStr), true);

            if (!WRHelper.VerifyObject(extWR, testStr))
            {
                TestFramework.LogError("005", "WeakReference target not as expected. Expected : Test; Actual: " + extWR.Target.ToString());
                retVal = false;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            if (!WRHelper.VerifyObject(extWR, testStr))
            {
                TestFramework.LogError("006", "WeakReference target not as expected. Expected : null; Actual: " + extWR.Target.ToString());
                retVal = false;
            }

            if (extWR.TrackResurrection != true)
            {
                TestFramework.LogError("007", "WeakReference track resurrection not as expected. Expected : true; Actual: " + extWR.TrackResurrection);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestFramework.LogError("008", "Unexpected exception occurred: " + e);
            retVal = false;
        }

        return retVal;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Serialization;

namespace Orleans.CodeGeneration
{
    /// <summary>
    /// Functionality for invoking calls on a generic instance method.
    /// </summary>
    /// <remarks>
    /// Each instance of this class can invoke calls on one generic method.
    /// </remarks>
    public class GenericMethodInvoker : IEqualityComparer<object[]>
    {
        private static readonly ConcurrentDictionary<Type, MethodInfo> BoxMethods =
            new ConcurrentDictionary<Type, MethodInfo>();

        private static readonly Func<Type, MethodInfo> CreateBoxMethod = GetTaskConversionMethod;

        private static readonly MethodInfo GenericMethodInvokerDelegateMethodInfo =
            TypeUtils.Method((GenericMethodInvokerDelegate del) => del.Invoke(null, null));

        private static readonly ILFieldBuilder FieldBuilder = new ILFieldBuilder();

        private readonly Type grainInterfaceType;
        private readonly string methodName;
        private readonly int typeParameterCount;
        private readonly ConcurrentDictionary<object[], GenericMethodInvokerDelegate> invokers;
        private readonly Func<object[], GenericMethodInvokerDelegate> createInvoker;

        /// <summary>
        ///  Invoke the generic method described by this instance on the provided <paramref name="grain"/>.
        /// </summary>
        /// <param name="grain">The grain.</param>
        /// <param name="arguments">The arguments, including the method's type parameters.</param>
        /// <returns>The method result.</returns>
        private delegate Task<object> GenericMethodInvokerDelegate(IAddressable grain, object[] arguments);

        /// <summary>
        /// Initializes a new instance of the <see cref="GenericMethodInvoker"/> class.
        /// </summary>
        /// <param name="grainInterfaceType">The grain interface type which the method exists on.</param>
        /// <param name="methodName">The name of the method.</param>
        /// <param name="typeParameterCount">The number of type parameters which the method has.</param>
        public GenericMethodInvoker(Type grainInterfaceType, string methodName, int typeParameterCount)
        {
            this.grainInterfaceType = grainInterfaceType;
            this.methodName = methodName;
            this.typeParameterCount = typeParameterCount;
            this.invokers = new ConcurrentDictionary<object[], GenericMethodInvokerDelegate>(this);
            this.createInvoker = this.CreateInvoker;
        }

        /// <summary>
        /// Invoke the defined method on the provided <paramref name="grain"/> instance with the given <paramref name="arguments"/>.
        /// </summary>
        /// <param name="grain">The grain.</param>
        /// <param name="arguments">The arguments to the method with the type parameters first, followed by the method parameters types, and finally the parameter values..</param>
        /// <returns>The invocation result.</returns>
        public Task<object> Invoke(IAddressable grain, object[] arguments)
        {
            var argc = (arguments.Length - typeParameterCount) / 2;

            // As this is on a hot path, avoid allocating (LINQ) as much as possible
            var argv = arguments.AsSpan();

            // generic parameter type(s) + argument type(s) -- this is our invokers' cache-key
            var types = argv.Slice(0, typeParameterCount + argc);

            // argument values to be passed
            var argValues = argv.Slice(typeParameterCount + argc, argc);

            var invoker = this.invokers.GetOrAdd(types.ToArray(), this.createInvoker);

            return invoker(grain, argValues.ToArray());
        }

        /// <summary>
        /// Creates an invoker delegate for the type arguments specified in <paramref name="arguments"/>.
        /// </summary>
        /// <param name="arguments">The method arguments, including one or more type parameter(s) at the head of the array..</param>
        /// <returns>A new invoker delegate.</returns>
        private GenericMethodInvokerDelegate CreateInvoker(object[] arguments)
        {
            // obtain the generic type parameter(s)
            var typeParameters = arguments.Take(this.typeParameterCount).Cast<Type>().ToArray();

            // obtain the method argument type(s)
            var parameterTypes = arguments
                .Skip(typeParameterCount)
                .Cast<Type>()
                .ToArray();

            // get open generic method for this arity/parameter combination
            var openGenericMethodInfo = GetMethod(
                grainInterfaceType,
                methodName,
                typeParameters,
                parameterTypes);

            // close the generic type
            var concreteMethod = openGenericMethodInfo.MakeGenericMethod(typeParameters);

            // Next, create a delegate which will call the method on the grain, pushing each of the arguments,
            var il = new ILDelegateBuilder<GenericMethodInvokerDelegate>(
                FieldBuilder,
                $"GenericMethodInvoker_{this.grainInterfaceType}_{concreteMethod.Name}",
                GenericMethodInvokerDelegateMethodInfo);

            // Load the grain and cast it to the type the concrete method is declared on.
            // Eg: cast from IAddressable to IGrainWithGenericMethod.
            il.LoadArgument(0);
            il.CastOrUnbox(this.grainInterfaceType);

            // Load each of the method parameters from the argument array, skipping the type parameters.
            var methodParameters = concreteMethod.GetParameters();
            for (var i = 0; i < methodParameters.Length; i++)
            {
                il.LoadArgument(1); // Load the argument array.

                // load the particular argument.
                il.LoadConstant(i);

                il.LoadReferenceElement();

                // Cast the argument from 'object' to the type expected by the concrete method.
                il.CastOrUnbox(methodParameters[i].ParameterType);
            }

            // Call the concrete method.
            il.Call(concreteMethod);

            // If the result type is Task or Task<T>, convert it to Task<object>.
            var returnType = concreteMethod.ReturnType;
            if (returnType != typeof(Task<object>))
            {
                var boxMethod = BoxMethods.GetOrAdd(returnType, CreateBoxMethod);
                il.Call(boxMethod);
            }

            // Return the resulting Task<object>.
            il.Return();
            return il.CreateDelegate();
        }

        /// <summary>
        /// Returns a suitable <see cref="MethodInfo"/> for a method which will convert an argument of type <paramref name="taskType"/>
        /// into <see cref="Task{Object}"/>.
        /// </summary>
        /// <param name="taskType">The type to convert.</param>
        /// <returns>A suitable conversion method.</returns>
        private static MethodInfo GetTaskConversionMethod(Type taskType)
        {
            if (taskType == typeof(Task)) return TypeUtils.Method((Task task) => task.ToUntypedTask());
            if (taskType == typeof(Task<object>)) return TypeUtils.Method((Task<object> task) => task.ToUntypedTask());
            if (taskType == typeof(void)) return TypeUtils.Property(() => Task.CompletedTask).GetMethod;

            if (taskType.GetGenericTypeDefinition() != typeof(Task<>))
                throw new ArgumentException($"Unsupported return type {taskType}.");
            var innerType = taskType.GenericTypeArguments[0];
            var methods = typeof(OrleansTaskExtentions).GetMethods(BindingFlags.Static | BindingFlags.Public);
            foreach (var method in methods)
            {
                if (method.Name != nameof(OrleansTaskExtentions.ToUntypedTask) ||
                    !method.ContainsGenericParameters) continue;
                return method.MakeGenericMethod(innerType);
            }

            throw new ArgumentException($"Could not find conversion method for type {taskType}");
        }

        /// <summary>
        /// Performs equality comparison for the purpose of comparing type parameters only.
        /// </summary>
        /// <param name="x">One argument list.</param>
        /// <param name="y">The other argument list.</param>
        /// <returns><see langword="true"/> if the type parameters in the respective arguments are equal, <see langword="false"/> otherwise.</returns>
        bool IEqualityComparer<object[]>.Equals(object[] x, object[] y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null)) return false;
            if (ReferenceEquals(null, y)) return false;

            return x.SequenceEqual(y);
        }

        /// <summary>
        /// Returns a hash code for the provided argument list.
        /// </summary>
        /// <param name="obj">The argument list.</param>
        /// <returns>A hash code.</returns>
        int IEqualityComparer<object[]>.GetHashCode(object[] obj)
        {
            if (obj.Length == 0) return 0;

            unchecked
            {
                var result = 0;
                foreach (var type in obj)
                {
                    result = (result * 367) ^ type.GetHashCode();
                }

                return result;
            }
        }

        /// <summary>
        /// Returns the <see cref="MethodInfo"/> for the method on <paramref name="declaringType"/> with the provided name
        /// and number of generic type parameters.
        /// </summary>
        /// <param name="declaringType">The type which the method is declared on.</param>
        /// <param name="methodName">The method name.</param>
        /// <param name="typeParameters">The generic type parameters to use.</param>
        /// <param name="parameterTypes"></param>
        /// <returns>The identified method.</returns>
        private static MethodInfo GetMethod(
            Type declaringType,
            string methodName,
            Type[] typeParameters,
            Type[] parameterTypes
        )
        {
            MethodInfo methodInfo = null;

            var typeParameterCount = typeParameters.Length;

            bool skipMethod = false;

            var methods = declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
            foreach (var openMethod in methods)
            {
                if (!openMethod.IsGenericMethodDefinition) continue;

                // same name?
                if (!string.Equals(openMethod.Name, methodName, StringComparison.Ordinal)) continue;

                // same type parameter count?
                if (openMethod.GetGenericArguments().Length != typeParameterCount) continue;

                // close the definition
                MethodInfo closedMethod = openMethod.MakeGenericMethod(typeParameters);

                // obtain list of closed parameters (no generic placeholders any more)
                var parameterInfos = closedMethod.GetParameters();

                // same number of params?
                if (parameterInfos.Length == parameterTypes.Length)
                {
                    for (int i = 0; i < parameterInfos.Length; ++i)
                    {
                        // validate compatibility - assignable/covariant array etc.
                        if (!parameterInfos[i].ParameterType.IsAssignableFrom(parameterTypes[i]))
                        {
                            skipMethod = true;
                            break;
                        }
                    }

                    if (skipMethod)
                    {
                        skipMethod = false;
                        continue;
                    }

                    // found compatible overload; return generic definition, not closed method
                    methodInfo = openMethod;
                    break;
                }
            } // next method

            if (methodInfo is null)
            {
                var signature = string.Join(",",
                    parameterTypes.Select(t => t.Name));

                var typeParams = string.Join(",", typeParameters.Select(t => t.Name));

                throw new ArgumentException(
                    $"Could not find exact match for generic method {declaringType}.{methodName}" +
                    $"<{typeParams}>({signature}).");
            }

            return methodInfo;
        }
    }
}


text:
namespace cinder { namespace mtl {

    namespace geom {

        // NOTE: Metal uses "Line" and "Triangle", not the pluralized verions found in GL
        enum Primitive { POINT, LINE, LINE_STRIP, TRIANGLE, TRIANGLE_STRIP, NUM_PRIMITIVES };

        // Converts ci::geom::Primitive into (ObjC) MTLPrimitiveType
        // Returns MTLPrimitiveType (must be cast)
        extern int nativeMTLPrimativeTypeFromGeom( const ci::geom::Primitive geomPrimitive );

        // Converts ci::mtl::geom::Primitive into (ObjC) MTLPrimitiveType
        // Returns MTLPrimitiveType (must be cast)
        extern int nativeMTLPrimitiveType( const ci::mtl::geom::Primitive primitive );

        // Converts ci::geom::Primitive into a mtl::geom::Primitive
        extern Primitive mtlPrimitiveTypeFromGeom( const ci::geom::Primitive primitive );

        // Returns the shader index associated with a given attribute
        extern int defaultBufferIndexForAttribute( const ci::geom::Attrib attr );

    }
}}


text:
package com.orca.kam.rxpermission.legacy.fragment;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Window;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.orca.kam.rxpermission.legacy.PermissionContent_Legacy;
import com.orca.kam.rxpermission.legacy.activity.PermissionListener_Legacy;

import java.util.ArrayList;
import java.util.List;

import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS;
import static android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS;
import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
import static com.orca.kam.rxpermission.util.PermissionUtil.REQ_CODE_PERMISSION_REQUEST;
import static com.orca.kam.rxpermission.util.PermissionUtil.REQ_CODE_REQUEST_SETTING;
import static com.orca.kam.rxpermission.util.PermissionUtil.TAG;

/**
 * @author kam6512
 * @Create on 2017-05-05.
 */
public class PermissionFragment_Legacy extends Fragment {

    private Context context;
    private PermissionListener_Legacy listener;
    private PermissionContent_Legacy content;

    public void setListener(PermissionListener_Legacy listener) {
        if (listener != null) {
            this.listener = listener;
        }
    }

    public void setContent(PermissionContent_Legacy content) {
        if (content != null) {
            this.content = content;
        }
    }

    @Override public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        setWindowUntouchable();
        checkPermissions();
        Log.e(TAG, "IS FRAGMENT!!!!!!!!");
    }

    void setWindowUntouchable() {
        Window window = getActivity().getWindow();
        if (window != null) window.addFlags(FLAG_NOT_TOUCHABLE);
    }

    void checkPermissions() {
        List<String> deniedPermission = getDeniedPermissionList(content.getPermissions());
        if (deniedPermission.isEmpty()) {
            permissionGranted();
        } else {
            showRationaleDialog(deniedPermission);
        }
    }

    private void finish() {
        getActivity().getFragmentManager().beginTransaction().remove(this).commit();
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissionResults, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissionResults, grantResults);
        if (requestCode != REQ_CODE_PERMISSION_REQUEST) return;

        List<String> deniedPermissions = getDeniedPermissionList(permissionResults, grantResults);
        if (deniedPermissions.isEmpty()) {
            permissionGranted();
        } else {
            showPermissionDenyDialog(deniedPermissions);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void requestPermissions(@NonNull List<String> needPermissions) {
        requestPermissions(needPermissions.toArray(new String[needPermissions.size()]),
                REQ_CODE_PERMISSION_REQUEST);
    }

    private void showRationaleDialog(final List<String> needPermissions) {
        new MaterialDialog.Builder(context)
                .content(content.getExplanationMessage())
                .negativeText(content.getExplanationConfirmButtonText())
                .onNegative((dialog, which) -> requestPermissions(needPermissions))
                .cancelable(false)
                .show();
    }

    private void showPermissionDenyDialog(final List<String> deniedPermissions) {
        new MaterialDialog.Builder(context)
                .content(content.getDeniedMessage())
                .positiveText(content.getSettingButtonText())
                .negativeText(content.getDeniedCloseButtonText())
                .onPositive((dialog, which) -> showAppSettings())
                .onNegative((dialog, which) -> permissionDenied(deniedPermissions))
                .cancelable(false)
                .show();
    }

    private void showAppSettings() {
        Intent intent = new Intent();
        String packageName = content.getPackageName();
        if (!Strings.isNullOrEmpty(packageName)) {
            intent.setAction(ACTION_APPLICATION_DETAILS_SETTINGS)
                    .setData(Uri.parse("package:" + content.getPackageName()));
        } else {
            intent.setAction(ACTION_MANAGE_APPLICATIONS_SETTINGS);
        }
        startActivityForResult(intent, REQ_CODE_REQUEST_SETTING);
    }

    private List<String> getDeniedPermissionList(String[] permissions, int[] grantResults) {
        List<String> deniedPermissions = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] == PERMISSION_DENIED) {
                deniedPermissions.add(permissions[i]);
            }
        }
        return deniedPermissions;
    }

    private List<String> getDeniedPermissionList(List<String> permissions) {
        return Lists.newArrayList(Iterables.filter(permissions, permission -> !isGrantedPermission(permission)));
    }

    private boolean isGrantedPermission(String permission) {
        return ContextCompat.checkSelfPermission(context, permission) == PERMISSION_GRANTED;
    }

    void permissionGranted() {
        listener.permissionGranted();
        finish();
    }

    void permissionDenied(List<String> deniedPermissions) {
        listener.permissionDenied(deniedPermissions);
        finish();
    }
}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.diirt</groupId>
        <artifactId>pvmanager-all</artifactId>
        <version>3.1.6-SNAPSHOT</version>
    </parent>
    <artifactId>datasource-file</artifactId>
    <name>org.diirt.datasource.file</name>
    <description>Support for data source based on file updates.</description>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>datasource-test</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>datasource-vtype</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <!--  one of the tests in this module is not thread-safe -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <forkCount>1</forkCount>
                    <reuseForks>false</reuseForks>
                </configuration>
            </plugin>
            <plugin>
                <groupId>eu.somatik.serviceloader-maven-plugin</groupId>
                <artifactId>serviceloader-maven-plugin</artifactId>
                <version>${serviceloader.maven.plugin.version}</version>
                <configuration>
                    <services>
                        <param>org.diirt.datasource.file.FileFormat</param>
                        <param>org.diirt.datasource.DataSourceProvider</param>
                    </services>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
"use strict";

var React = require('react/addons');

var TestOutputComponent = React.createClass({
  render: function () {
    if (!this.props.show) {
      return null;
    }

    var result = null;
    if (this.props.output && this.props.output.result) {
      result =
{this.props.output.result}
;
    }

    var consoles = null;
    if (this.props.output && this.props.output.console) {
      consoles = this.props.output.console.map(function (message) {
        return
{message}

      });
    }

    return (

        ×

Hint 1

Please use console.log!

Hint 2

The last expression will be returned as a result!

        {consoles.length > 0 ?
Console:
 : null}
        {consoles}

Result:

        {result}

    );
  },
  close: function (e) {
    this.props.close();
    e.preventDefault();
  }
});

module.exports = TestOutputComponent;


text:
#ifndef NETLINK_ATTR_H_
#define NETLINK_ATTR_H_

#include <netlink/netlink.h>
#include <netlink/object.h>
#include <netlink/addr.h>
#include <netlink/data.h>
#include <netlink/msg.h>

#ifdef __cplusplus
extern "C" {
#endif

struct nl_msg;

/**
 * @name Basic Attribute Data Types
 * @{
 */

 /**
  * @ingroup attr
  * Basic attribute data types
  *
  * See \ref attr_datatypes for more details.
  */
enum {
	NLA_UNSPEC,	/**< Unspecified type, binary data chunk */
	NLA_U8,		/**< 8 bit integer */
	NLA_U16,	/**< 16 bit integer */
	NLA_U32,	/**< 32 bit integer */
	NLA_U64,	/**< 64 bit integer */
	NLA_STRING,	/**< NUL terminated character string */
	NLA_FLAG,	/**< Flag */
	NLA_MSECS,	/**< Micro seconds (64bit) */
	NLA_NESTED,	/**< Nested attributes */
	__NLA_TYPE_MAX,
};

#define NLA_TYPE_MAX (__NLA_TYPE_MAX - 1)

/** @} */

/**
 * @ingroup attr
 * Attribute validation policy.
 *
 * See \ref attr_datatypes for more details.
 */
struct nla_policy {
	/** Type of attribute or NLA_UNSPEC */
	uint16_t	type;

	/** Minimal length of payload required */
	uint16_t	minlen;

	/** Maximal length of payload allowed */
	uint16_t	maxlen;
};

/* Attribute parsing */
extern int		nla_ok(const struct nlattr *, int);
extern struct nlattr *	nla_next(const struct nlattr *, int *);
extern int		nla_parse(struct nlattr **, int, struct nlattr *,
				  int, struct nla_policy *);
extern int		nla_validate(struct nlattr *, int, int,
				     struct nla_policy *);
extern struct nlattr *	nla_find(struct nlattr *, int, int);

/* Unspecific attribute */
extern struct nlattr *	nla_reserve(struct nl_msg *, int, int);
extern int		nla_put(struct nl_msg *, int, int, const void *);

/**
 * nlmsg_find_attr - find a specific attribute in a netlink message
 * @arg nlh		netlink message header
 * @arg hdrlen		length of familiy specific header
 * @arg attrtype	type of attribute to look for
 *
 * Returns the first attribute which matches the specified type.
 */
static inline struct nlattr *nlmsg_find_attr(struct nlmsghdr *nlh, int hdrlen, int attrtype)
{
	return nla_find(nlmsg_attrdata(nlh, hdrlen),
			nlmsg_attrlen(nlh, hdrlen), attrtype);
}

/**
 * Return size of attribute whithout padding.
 * @arg payload		Payload length of attribute.
 *
 * @code
 *    <-------- nla_attr_size(payload) --------->
 *   +------------------+- - -+- - - - - - - - - +- - -+
 *   | Attribute Header | Pad |     Payload      | Pad |
 *   +------------------+- - -+- - - - - - - - - +- - -+
 * @endcode
 *
 * @return Size of attribute in bytes without padding.
 */
static inline int nla_attr_size(int payload)
{
	return NLA_HDRLEN + payload;
}

/**
 * Return size of attribute including padding.
 * @arg payload		Payload length of attribute.
 *
 * @code
 *    <----------- nla_total_size(payload) ----------->
 *   +------------------+- - -+- - - - - - - - - +- - -+
 *   | Attribute Header | Pad |     Payload      | Pad |
 *   +------------------+- - -+- - - - - - - - - +- - -+
 * @endcode
 *
 * @return Size of attribute in bytes.
 */
static inline int nla_total_size(int payload)
{
	return NLA_ALIGN(nla_attr_size(payload));
}

/**
 * Return length of padding at the tail of the attribute.
 * @arg payload		Payload length of attribute.
 *
 * @code
 *   +------------------+- - -+- - - - - - - - - +- - -+
 *   | Attribute Header | Pad |     Payload      | Pad |
 *   +------------------+- - -+- - - - - - - - - +- - -+
 *                                                <--->
 * @endcode
 *
 * @return Length of padding in bytes.
 */
static inline int nla_padlen(int payload)
{
	return nla_total_size(payload) - nla_attr_size(payload);
}

/**
 * Return type of the attribute.
 * @arg nla		Attribute.
 *
 * @return Type of attribute.
 */
static inline int nla_type(const struct nlattr *nla)
{
	return nla->nla_type & NLA_TYPE_MASK;
}

/**
 * Return pointer to the payload section.
 * @arg nla		Attribute.
 *
 * @return Pointer to start of payload section.
 */
static inline void *nla_data(const struct nlattr *nla)
{
	return (char *) nla + NLA_HDRLEN;
}

/**
 * Return length of the payload .
 * @arg nla		Attribute
 *
 * @return Length of payload in bytes.
 */
static inline int nla_len(const struct nlattr *nla)
{
	return nla->nla_len - NLA_HDRLEN;
}

/**
 * Copy attribute payload to another memory area.
 * @arg dest		Pointer to destination memory area.
 * @arg src		Attribute
 * @arg count		Number of bytes to copy at most.
 *
 * Note: The number of bytes copied is limited by the length of
 *       the attribute payload.
 *
 * @return The number of bytes copied to dest.
 */
static inline int nla_memcpy(void *dest, struct nlattr *src, int count)
{
	int minlen;

	if (!src)
		return 0;

	minlen = min_t(int, count, nla_len(src));
	memcpy(dest, nla_data(src), minlen);

	return minlen;
}

/**
 * Add abstract data as unspecific attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg data		Abstract data object.
 *
 * Equivalent to nla_put() except that the length of the payload is
 * derived from the abstract data object.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_data(struct nl_msg *msg, int attrtype, struct nl_data *data)
{
	return nla_put(msg, attrtype, nl_data_get_size(data),
		       nl_data_get(data));
}

/**
 * Add abstract address as unspecific attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg addr		Abstract address object.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_addr(struct nl_msg *msg, int attrtype, struct nl_addr *addr)
{
	return nla_put(msg, attrtype, nl_addr_get_len(addr),
		       nl_addr_get_binary_addr(addr));
}

/** @} */

/**
 * @name Integer Attributes
 */

/**
 * Add 8 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value to store as payload.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_u8(struct nl_msg *msg, int attrtype, uint8_t value)
{
	return nla_put(msg, attrtype, sizeof(uint8_t), &value);
}

/**
 * Return value of 8 bit integer attribute.
 * @arg nla		8 bit integer attribute
 *
 * @return Payload as 8 bit integer.
 */
static inline uint8_t nla_get_u8(struct nlattr *nla)
{
	return *(uint8_t *) nla_data(nla);
}

/**
 * Add 16 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value to store as payload.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_u16(struct nl_msg *msg, int attrtype, uint16_t value)
{
	return nla_put(msg, attrtype, sizeof(uint16_t), &value);
}

/**
 * Return payload of 16 bit integer attribute.
 * @arg nla		16 bit integer attribute
 *
 * @return Payload as 16 bit integer.
 */
static inline uint16_t nla_get_u16(struct nlattr *nla)
{
	return *(uint16_t *) nla_data(nla);
}

/**
 * Add 32 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value to store as payload.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_u32(struct nl_msg *msg, int attrtype, uint32_t value)
{
	return nla_put(msg, attrtype, sizeof(uint32_t), &value);
}

/**
 * Return payload of 32 bit integer attribute.
 * @arg nla		32 bit integer attribute.
 *
 * @return Payload as 32 bit integer.
 */
static inline uint32_t nla_get_u32(struct nlattr *nla)
{
	return *(uint32_t *) nla_data(nla);
}

/**
 * Add 64 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value to store as payload.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_u64(struct nl_msg *msg, int attrtype, uint64_t value)
{
	return nla_put(msg, attrtype, sizeof(uint64_t), &value);
}

/**
 * Return payload of u64 attribute
 * @arg nla		u64 netlink attribute
 *
 * @return Payload as 64 bit integer.
 */
static inline uint64_t nla_get_u64(struct nlattr *nla)
{
	uint64_t tmp;

	nla_memcpy(&tmp, nla, sizeof(tmp));

	return tmp;
}

/**
 * Add string attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg str		NUL terminated string.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_string(struct nl_msg *msg, int attrtype, const char *str)
{
	return nla_put(msg, attrtype, strlen(str) + 1, str);
}

/**
 * Return payload of string attribute.
 * @arg nla		String attribute.
 *
 * @return Pointer to attribute payload.
 */
static inline char *nla_get_string(struct nlattr *nla)
{
	return (char *) nla_data(nla);
}

static inline char *nla_strdup(struct nlattr *nla)
{
	return strdup(nla_get_string(nla));
}

/** @} */

/**
 * @name Flag Attribute
 */

/**
 * Add flag netlink attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_flag(struct nl_msg *msg, int attrtype)
{
	return nla_put(msg, attrtype, 0, NULL);
}

/**
 * Return true if flag attribute is set.
 * @arg nla		Flag netlink attribute.
 *
 * @return True if flag is set, otherwise false.
 */
static inline int nla_get_flag(struct nlattr *nla)
{
	return !!nla;
}

/** @} */

/**
 * @name Microseconds Attribute
 */

/**
 * Add a msecs netlink attribute to a netlink message
 * @arg n		netlink message
 * @arg attrtype	attribute type
 * @arg msecs 		number of msecs
 */
static inline int nla_put_msecs(struct nl_msg *n, int attrtype, unsigned long msecs)
{
	return nla_put_u64(n, attrtype, msecs);
}

/**
 * Return payload of msecs attribute
 * @arg nla		msecs netlink attribute
 *
 * @return the number of milliseconds.
 */
static inline unsigned long nla_get_msecs(struct nlattr *nla)
{
	return nla_get_u64(nla);
}

/**
 * Add nested attributes to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg nested		Message containing attributes to be nested.
 *
 * Takes the attributes found in the \a nested message and appends them
 * to the message \a msg nested in a container of the type \a attrtype.
 * The \a nested message may not have a family specific header.
 *
 * @see nla_put
 * @return 0 on success or a negative error code.
 */
static inline int nla_put_nested(struct nl_msg *msg, int attrtype, struct nl_msg *nested)
{
	return nla_put(msg, attrtype, nlmsg_len(nested->nm_nlh),
		       nlmsg_data(nested->nm_nlh));
}

/**
 * Start a new level of nested attributes.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type of container.
 *
 * @return Pointer to container attribute.
 */
static inline struct nlattr *nla_nest_start(struct nl_msg *msg, int attrtype)
{
	struct nlattr *start = (struct nlattr *) nlmsg_tail(msg->nm_nlh);

	if (nla_put(msg, attrtype, 0, NULL) < 0)
		return NULL;

	return start;
}

/**
 * Finalize nesting of attributes.
 * @arg msg		Netlink message.
 * @arg start		Container attribute as returned from nla_nest_start().
 *
 * Corrects the container attribute header to include the appeneded attributes.
 *
 * @return 0
 */
static inline int nla_nest_end(struct nl_msg *msg, struct nlattr *start)
{
	start->nla_len = (unsigned char *) nlmsg_tail(msg->nm_nlh) -
				(unsigned char *) start;
	return 0;
}

/**
 * Create attribute index based on nested attribute
 * @arg tb		Index array to be filled (maxtype+1 elements).
 * @arg maxtype		Maximum attribute type expected and accepted.
 * @arg nla		Nested Attribute.
 * @arg policy		Attribute validation policy.
 *
 * Feeds the stream of attributes nested into the specified attribute
 * to nla_parse().
 *
 * @see nla_parse
 * @return 0 on success or a negative error code.
 */
static inline int nla_parse_nested(struct nlattr *tb[], int maxtype, struct nlattr *nla,
		     struct nla_policy *policy)
{
	return nla_parse(tb, maxtype, (struct nlattr *)nla_data(nla), nla_len(nla), policy);
}

/**
 * Compare attribute payload with memory area.
 * @arg nla		Attribute.
 * @arg data		Memory area to compare to.
 * @arg size		Number of bytes to compare.
 *
 * @see memcmp(3)
 * @return An integer less than, equal to, or greater than zero.
 */
static inline int nla_memcmp(const struct nlattr *nla, const void *data, size_t size)
{
	int d = nla_len(nla) - size;

	if (d == 0)
		d = memcmp(nla_data(nla), data, size);

	return d;
}

/**
 * Compare string attribute payload with string
 * @arg nla		Attribute of type NLA_STRING.
 * @arg str		NUL terminated string.
 *
 * @see strcmp(3)
 * @return An integer less than, equal to, or greater than zero.
 */
static inline int nla_strcmp(const struct nlattr *nla, const char *str)
{
	int len = strlen(str) + 1;
	int d = nla_len(nla) - len;

	if (d == 0)
		d = memcmp(nla_data(nla), str, len);

	return d;
}

/**
 * Copy string attribute payload to a buffer.
 * @arg dst		Pointer to destination buffer.
 * @arg nla		Attribute of type NLA_STRING.
 * @arg dstsize		Size of destination buffer in bytes.
 *
 * Copies at most dstsize - 1 bytes to the destination buffer.
 * The result is always a valid NUL terminated string. Unlike
 * strlcpy the destination buffer is always padded out.
 *
 * @return The length of string attribute without the terminating NUL.
 */
static inline size_t nla_strlcpy(char *dst, const struct nlattr *nla, size_t dstsize)
{
	size_t srclen = (size_t)nla_len(nla);
	char *src = (char*)nla_data(nla);

	if (srclen > 0 && src[srclen - 1] == '\0')
		srclen--;

	if (dstsize > 0) {
		size_t len = (srclen >= dstsize) ? dstsize - 1 : srclen;

		memset(dst, 0, dstsize);
		memcpy(dst, src, len);
	}

	return srclen;
}

/**
 * @name Attribute Construction (Exception Based)
 * @{
 */

/**
 * @ingroup attr
 * Add unspecific attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg attrlen		Length of attribute payload.
 * @arg data		Head of attribute payload.
 */
#define NLA_PUT(msg, attrtype, attrlen, data) \
	do { \
		if (nla_put(msg, attrtype, attrlen, data) < 0) \
			goto nla_put_failure; \
	} while(0)

/**
 * @ingroup attr
 * Add atomic type attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg type		Atomic type.
 * @arg attrtype	Attribute type.
 * @arg value		Head of attribute payload.
 */
#define NLA_PUT_TYPE(msg, type, attrtype, value) \
	do { \
		type __tmp = value; \
		NLA_PUT(msg, attrtype, sizeof(type), &__tmp); \
	} while(0)

/**
 * Add 8 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value.
 */
#define NLA_PUT_U8(msg, attrtype, value) \
	NLA_PUT_TYPE(msg, uint8_t, attrtype, value)

/**
 * Add 16 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value.
 */
#define NLA_PUT_U16(msg, attrtype, value) \
	NLA_PUT_TYPE(msg, uint16_t, attrtype, value)

/**
 * Add 32 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value.
 */
#define NLA_PUT_U32(msg, attrtype, value) \
	NLA_PUT_TYPE(msg, uint32_t, attrtype, value)

/**
 * Add 64 bit integer attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		Numeric value.
 */
#define NLA_PUT_U64(msg, attrtype, value) \
	NLA_PUT_TYPE(msg, uint64_t, attrtype, value)

/**
 * Add string attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg value		NUL terminated character string.
 */
#define NLA_PUT_STRING(msg, attrtype, value) \
	NLA_PUT(msg, attrtype, strlen(value) + 1, value)

/**
 * Add flag attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 */
#define NLA_PUT_FLAG(msg, attrtype) \
	NLA_PUT(msg, attrtype, 0, NULL)

/**
 * Add msecs attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg msecs		Numeric value in micro seconds.
 */
#define NLA_PUT_MSECS(msg, attrtype, msecs) \
	NLA_PUT_U64(msg, attrtype, msecs)

/**
 * Add address attribute to netlink message.
 * @arg msg		Netlink message.
 * @arg attrtype	Attribute type.
 * @arg addr		Abstract address object.
 */
#define NLA_PUT_ADDR(msg, attrtype, addr) \
	NLA_PUT(msg, attrtype, nl_addr_get_len(addr), \
		nl_addr_get_binary_addr(addr))

/** @} */

/**
 * @name Iterators
 * @{
 */

/**
 * @ingroup attr
 * Iterate over a stream of attributes
 * @arg pos	loop counter, set to current attribute
 * @arg head	head of attribute stream
 * @arg len	length of attribute stream
 * @arg rem	initialized to len, holds bytes currently remaining in stream
 */
#define nla_for_each_attr(pos, head, len, rem) \
	for (pos = head, rem = len; \
	     nla_ok(pos, rem); \
	     pos = nla_next(pos, &(rem)))

/**
 * @ingroup attr
 * Iterate over a stream of nested attributes
 * @arg pos	loop counter, set to current attribute
 * @arg nla	attribute containing the nested attributes
 * @arg rem	initialized to len, holds bytes currently remaining in stream
 */
#define nla_for_each_nested(pos, nla, rem) \
	for (pos = (struct nlattr *)nla_data(nla), rem = nla_len(nla); \
	     nla_ok(pos, rem); \
	     pos = nla_next(pos, &(rem)))

/** @} */

#ifdef __cplusplus
}
#endif

#endif


text:
/*
 * File:   ecan.h
 * Author: Ducky
 *
 * Created on January 15, 2011, 6:09 PM
 *
 * This file contains function prototypes and configuration definitions for the
 * on-board ECAN module
 */

#ifndef ECAN_H
#define ECAN_H

#include "types.h"
#include "hardware.h"

// TODO automatic compile time error checking for ECAN and can timing in general

/* Timing Parameters
 * Design Guidelines:
 * Implicit: 1 TQ synchronization segment
 * Should be between 8 and 25 TQ in a NBT
 * PHSEG2 must be smaller than PRSEG and PH1SEG
 * PHSEG2 must be larger than SJW
 * Sampling happens at end of Phase Segment 1, must take place at 60-70% of bit time
 * Number of TQ must divide event into Fcan clock
 */

/**
 * CAN bitrate, in bits/sec.
 */
//#define ECAN_BITRATE 500000
#define ECAN_BITRATE 1000000
//#define ECAN_BITRATE 125000
/**
 * Synchronization Jump Width, in Time Quanta (TQ).
 * Code will automatically generate (subtract 1) the register value.
 * (1 TQ - 4 TQ)
 */
#define ECAN_SJW	1
/**
 * Propagation Segment, in Time Quanta (TQ).
 * Code will automatically generate (subtract 1) the register value.
 * (1 TQ - 8 TQ)
 */
#define ECAN_PRSEG	1
/**
 * Phase Segment 1, in Time Quanta (TQ).
 * Code will automatically generate (subtract 1) the register value.
 * (1 TQ - 8 TQ)
 */
#define ECAN_PHSEG1	5
/**
 * Phase Segment 2, in Time Quanta (TQ).
 * Code will automatically generate (subtract 1) the register value.
 * (1 TQ - 8 TQ)
 */
#define ECAN_PHSEG2	3

/**
 * Number of time quanta per bit. (8 TQ - 25 TQ)
 */
#define ECAN_NTQ (ECAN_SJW + ECAN_PRSEG + ECAN_PHSEG1 + ECAN_PHSEG2)
/**
 * CAN Baud Rate Prescaler.
 * Compiler generated and checked.
 */
#define ECAN_BRP ((((Fcy/2)/ECAN_NTQ)/ECAN_BITRATE)-1)

#if (Fcy > 40000000)
	#error "Fcan can not exceed 40 MHz"
#endif
#if (ECAN_SJW < 1) || (ECAN_SJW > 4)
	#error "ECAN_SJW must be between 1 TQ and 4 TQ"
#endif
#if (ECAN_PRSEG < 1) || (ECAN_PRSEG > 8)
	#error "ECAN_PRSEG must be between 1 TQ and 8 TQ"
#endif
#if (ECAN_PHSEG1 < 1) || (ECAN_PHSEG1 > 8)
	#error "ECAN_PHSEG1 must be between 1 TQ and 8 TQ"
#endif
#if (ECAN_PHSEG2 < 1) || (ECAN_PHSEG2 > 8)
	#error "ECAN_PHSEG2 must be between 1 TQ and 8 TQ"
#endif
#if (ECAN_NTQ < 8) || (ECAN_NTQ > 25)
	#error "ECAN_NTQ must be between 8 TQ and 25 TQ"
#endif
#if (ECAN_BRP > 63)
	#error "BRP must not exceed 63"
#endif

/**
 * Number of ECAN RX buffers to use.
 */
#define ECAN_NUM_BUFFERS	24
/**
 * The number of words per buffer, used in the calculation of buffer alignment.
 */
#define ECAN_BUFFER_WORDS	8
/**
 * Byte alignment boundary of the ECAN buffer.
 * This is necessary for the DMA module to function correctly.
 */
#define ECAN_ALIGN			512	// (ECAN_NUM_BUFFERS * ECAN_BUFFER_WORDS * 2)

#if ECAN_NUM_BUFFERS == 4
	#define ECAN_DMABS	0b000
#elif ECAN_NUM_BUFFERS == 6
	#define ECAN_DMABS	0b001
#elif ECAN_NUM_BUFFERS == 8
	#define ECAN_DMABS	0b010
#elif ECAN_NUM_BUFFERS == 12
	#define ECAN_DMABS	0b011
#elif ECAN_NUM_BUFFERS == 16
	#define ECAN_DMABS	0b100
#elif ECAN_NUM_BUFFERS == 24
	#define ECAN_DMABS	0b101
#elif ECAN_NUM_BUFFERS == 32
	#define ECAN_DMABS	0b110
#else
	#error "ECAN_NUM_BUFFERS must be either 4, 6, 8, 12, 16, 24, or 32"
#endif

/**
 * ECAN buffer number to direct a received message to the FIFO.
 */
#define ECAN_FILTER_FIFO		15

typedef enum {
	ECAN_MODE_OPERATE = 0b000,
	ECAN_MODE_DISABLE = 0b001,
	ECAN_MODE_LOOPBACK = 0b010,
	ECAN_MODE_LISTEN = 0b011,
	ECAN_MODE_CONFIG = 0b100,
	ECAN_MODE_LISTENALL	= 0b111
} eECANMode;

/*
 * Function Prototypes
 */
void ECAN_Init();
void ECAN_Config();
void ECAN_SetMode(eECANMode mode);
int8_t ECAN_SetStandardFilter(uint8_t filNum, uint16_t sidFilter, uint8_t maskNum, uint8_t bufNum);
int8_t ECAN_SetStandardMask(uint8_t maskNum,  uint16_t sidFilter);
void ECAN_DisableFilter(uint8_t filNum);
void ECAN_SetupDMA();
int8_t ECAN_GetNextRXBuffer();
int8_t ECAN_WriteStandardBuffer(uint8_t buffer,
	uint16_t sid, uint8_t dlc, uint8_t *data);
int8_t ECAN_ReadBuffer(uint8_t buffer, uint16_t *sid, uint32_t *eid,
	uint8_t dlc, uint8_t *data);
uint8_t ECAN_TransmitBuffer(uint8_t buffer);

#endif


text:
A clusterService contains one or many machines

### Machine

A Machine is a computer that has docker installed on it with it's remote API exposed for us

## Configure Docker API on OSX

1. Install socat with `brew install socat`
2. Start socat using the comand: `socat -d TCP-LISTEN:2376,range=127.0.0.1/32,reuseaddr,fork UNIX:/var/run/docker.sock`

You should now be able to access the local docker api using the URL: http://localhost:2376/version

## Folder Structure

```
data
|- builds
   |- <jobName>@<buildNumber>.xml
|- logs
   |- <jobName>@<buildNumber>.log
|- jobs
   |- <jobName>.xml
|- machines
   |- <machineName>.xml
```


text:
require 'active_support/core_ext/hash'

module NetworkExecutive
  class Configuration
    attr_accessor :name

    @@defaults = HashWithIndifferentAccess.new(
      name: 'My Network'
    )

    def initialize
      @@defaults.dup.each_pair { |k, v| self.send "#{k}=", v }
    end

    def defaults
      @@defaults
    end

    def attributes
      self.class.defaults.keys.each_with_object(HashWithIndifferentAccess.new) do |k, hash|
        hash[k] = self.send k
      end
    end
    alias_method :to_hash, :attributes
  end
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\modules\core\widgets\FlashMessage;

/* @var $this yii\web\View */
/* @var $model app\modules\blog\models\Tag */
/* @var $form yii\widgets\ActiveForm */
?>

    <?= $model->hasErrors() ?
        FlashMessage::widget([
            'type' => FlashMessage::ERROR_MESSAGE,
            'message' => Html::errorSummary($model),
        ]) :
        null
    ?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'slug')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
using System;
using System.Linq;
using Bytes2you.DataAccess.Data;

namespace Bytes2you.DataAccess.UnitTests.Testing.Mocks
{
    public class PersonDataEntityMock : IDataEntity<int>
    {
        public int Id { get; set; }
    }
}


text:
package headfirst.factory.pizzaaf;

public class MozzarellaCheese implements Cheese {

    public String toString() {
        return "Shredded Mozzarella";
    }
}


text: FireSearch has moved. See here for plugin https://github.com/gpshopper/firesearch


text:
<?php

declare(strict_types=1);

namespace GeoIO\Geometry;

use GeoIO\Dimension;
use function count;

class MultiLineString implements Geometry
{
    use CommonMethods;

    /**
     * @var LineString[]
     */
    private array $lineStrings;

    public function __construct(
        Dimension $dimension,
        ?int $srid = null,
        LineString ...$lineStrings,
    ) {
        $this->dimension = $dimension;
        $this->srid = $srid;
        $this->lineStrings = $lineStrings;

        Assert::geometry($this);
    }

    public function isEmpty(): bool
    {
        return 0 === count($this->lineStrings);
    }

    /**
     * @return LineString[]
     */
    public function getLineStrings(): array
    {
        return $this->lineStrings;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Low-Level Speciation of Cyanide in Waters|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2017-01-26" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Project Research Results

Final Report

                      2 publications for this project

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Low-Level Speciation of Cyanide in Waters

    EPA Contract Number: 68D01023

    Title: Low-Level Speciation of Cyanide in Waters

    Investigators:
     Wallschlager, Dirk

    Small Business:

      Frontier Geosciences Inc.

    	EPA Contact:

           Manager, SBIR Program

        Phase: I

      Project Period:
      April 1, 2001 through
        September 1, 2001

        Project Amount:

          $70,000

      RFA:
      Small Business Innovation Research (SBIR) - Phase I (2001)

        		RFA Text |
          Recipients Lists

      Research Category:

          Ecological Indicators/Assessment/Restoration
          ,
          SBIR - Monitoring
          ,
          Small Business Innovation Research (SBIR)

Description:

      	Frontier Geosciences, Inc., proposes to develop a novel method for the
speciation of a wide variety of different covalent and complex cyanides in
waters, based on the coupling of a chromatographic separation to the most
sensitive and selective cyanide detector that currently is available
commercially. This type of method development specifically is requested by the
U.S. Environmental Protection Agency (EPA) because the techniques currently
available for cyanide speciation do not meet all the requirements of the EPA and
the affected industries. Operationally defined techniques can only separate free
from complexed cyanide, and generally are susceptible to matrix interferences,
especially to false positive results. Conversely, the few available direct
speciation techniques that separate different cyanide species
chromatographically often use detectors that lack either sensitivity or
specificity, resulting in limited applicability of the method (only in strongly
contaminated environments) or in the lack of positive identification of a signal
as one defined cyanide species. Frontier Geosciences, Inc., collaborates closely
with the mining and petroleum industries and their regulatory counterparts in
the areas of metal(loid) analysis, speciation, and geochemistry, and has
experienced a very strong demand and need for direct, sensitive, specific, and
accurate cyanide determination and speciation during the last few years.

The anticipated solution for the problem investigated in this proposal
consists of an ion chromatographic (IC) separation of the anionic cyanide
species, coupled to an online UV-assisted wet chemical derivatization step that
breaks down all cyanide species to free CN , which then is detected by a flow
injection-gas diffusion-amperometric detection (FIGDAD) system. The final method
would permit the separation and quantification of at least nine different
cyanide species with detection limits of 1 µg/L per species. The Phase I
objectives are to: (1) couple IC to FIGDAD and demonstrate a detection limit of
1 µg/L for CN- ; (2) develop the separation of nine relevant cyanide
species; (3) demonstrate the feasibility of online UV-photolytic breakdown for
[Fe(CN)6]3- and [Fe(CN)6]4- ; and (4) demonstrate feasibility of the method
in real-world water samples and in alkaline leachates from cyanide-contaminated
soils/sediments.

Publications and Presentations:

        Publications have been submitted on this project: View all 2 publications for this project

Supplemental Keywords:

      small business, SBIR, monitoring, cyanide, water, leachates, mining, petroleum, engineering, chemistry, EPA, monitoring, analytical., RFA, Scientific Discipline, Toxics, Waste, Water, Ecosystem Protection/Environmental Exposure & Risk, National Recommended Water Quality, Contaminated Sediments, Chemistry, Monitoring/Modeling, Environmental Monitoring, Engineering,  Chemistry,  & Physics, Environmental Engineering, monitoring, cyanide, contaminated sediment, chromatographic

Progress and Final Reports:

                Final Report

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Thursday, January 26, 2017


text:
package logging

import "testing"

func TestLog(t *testing.T) {
	log := NewLogger("", NewWrappedCore(Info, Discard, Plain.ConsoleEncoder()))

	recovered := new(bool)
	panicFunc := func() {
		panic("DON'T PANIC!")
	}
	exitFunc := func() {
		*recovered = true
	}
	log.RecoverAndExit(panicFunc, exitFunc)

	if !*recovered {
		t.Fatalf("Exit function was never called")
	}
}


text:
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";
    var page = WinJS.UI.Pages.define("/html/scenario4_NumberParsing.html", {
        ready: function (element, options) {
            document.getElementById("displayButton").addEventListener("click", doDisplay, false);
        }
    });

    function doDisplay() {
        // This scenario uses the Windows.Globalization.NumberFormatting.DecimalFormatter,
        // Windows.Globalization.NumberFormatting.CurrencyFormatter and
        // Windows.Globalization.NumberFormatting.PercentFormatter classes to format and parse a number
        // percentage or currency.

        // Define percent formatters.
        var percentFormat = new Windows.Globalization.NumberFormatting.PercentFormatter();
        var percentFormatJP = new Windows.Globalization.NumberFormatting.PercentFormatter(["ja-JP"], "ZZ");
        var percentFormatFR = new Windows.Globalization.NumberFormatting.PercentFormatter(["fr-FR"], "ZZ");

        // Define decimal formatters.
        var decimalFormat = new Windows.Globalization.NumberFormatting.DecimalFormatter();
        decimalFormat.isGrouped = true;
        var decimalFormatJP = new Windows.Globalization.NumberFormatting.DecimalFormatter(["ja-JP"], "ZZ");
        decimalFormatJP.isGrouped = true;
        var decimalFormatFR = new Windows.Globalization.NumberFormatting.DecimalFormatter(["fr-FR"], "ZZ");
        decimalFormatFR.isGrouped = true;

        // Define currency formatters
        var userCurrency = Windows.System.UserProfile.GlobalizationPreferences.currencies;
        var currencyFormat = new Windows.Globalization.NumberFormatting.CurrencyFormatter(userCurrency);
        var currencyFormatJP = new Windows.Globalization.NumberFormatting.CurrencyFormatter("JPY", ["ja-JP"], "ZZ");
        var currencyFormatFR = new Windows.Globalization.NumberFormatting.CurrencyFormatter("EUR", ["fr-FR"], "ZZ");

        // Generate numbers for parsing.
        var percentNumber = 0.523;
        var decimalNumber = 12345.67;
        var currencyNumber = 1234.56;

        // Roundtrip the percent numbers by formatting and parsing.
        var percent1 = percentFormat.format(percentNumber);
        var percent1Parsed = percentFormat.parseDouble(percent1);

        var percent1JP = percentFormatJP.format(percentNumber);
        var percent1JPParsed = percentFormatJP.parseDouble(percent1JP);

        var percent1FR = percentFormatFR.format(percentNumber);
        var percent1FRParsed = percentFormatFR.parseDouble(percent1FR);

        // Generate the results for percent parsing.
        var results1 = "Percent parsing of " + percentNumber + "\n" +
                       "Formatted for current user: " + percent1 + " Parsed as current user: " + percent1Parsed + "\n" +
                       "Formatted for ja-JP: " + percent1JP + " Parsed for ja-JP: " + percent1JPParsed + "\n" +
                       "Formatted for fr-FR: " + percent1FR + " Parsed for fr-FR: " + percent1FRParsed;

        // Roundtrip the decimal numbers for formatting and parsing.
        var decimal1 = decimalFormat.format(decimalNumber);
        var decimal1Parsed = decimalFormat.parseDouble(decimal1);

        var decimal1JP = decimalFormatJP.format(decimalNumber);
        var decimal1JPParsed = decimalFormatJP.parseDouble(decimal1JP);

        var decimal1FR = decimalFormatFR.format(decimalNumber);
        var decimal1FRParsed = decimalFormatFR.parseDouble(decimal1FR);

        // Generate the results for decimal parsing.
        var results2 = "Decimal parsing of " + decimalNumber + "\n" +
                       "Formatted for current user: " + decimal1 + " Parsed as current user: " + decimal1Parsed + "\n" +
                       "Formatted for ja-JP: " + decimal1JP + " Parsed for ja-JP: " + decimal1JPParsed + "\n" +
                       "Formatted for fr-FR: " + decimal1FR + " Parsed for fr-FR: " + decimal1FRParsed;

        // Roundtrip the currency numbers for formatting and parsing.
        var currency1 = currencyFormat.format(currencyNumber);
        var currency1Parsed = currencyFormat.parseDouble(currency1);

        var currency1JP = currencyFormatJP.format(currencyNumber);
        var currency1JPParsed = currencyFormatJP.parseDouble(currency1JP);

        var currency1FR = currencyFormatFR.format(currencyNumber);
        var currency1FRParsed = currencyFormatFR.parseDouble(currency1FR);

        // Generate the results for decimal parsing.
        var results3 = "Currency parsing of " + currencyNumber + "\n" +
                       "Formatted for current user: " + currency1 + " Parsed as current user: " + currency1Parsed + "\n" +
                       "Formatted for ja-JP: " + currency1JP + " Parsed for ja-JP: " + currency1JPParsed + "\n" +
                       "Formatted for fr-FR: " + currency1FR + " Parsed for fr-FR: " + currency1FRParsed;

        // Display the results.
        var results = results1 + "\n\n" + results2 + "\n\n" + results3;

        document.getElementById("output").innerText = results;
    }
})();


text:
'use strict';

const Container                    = require('./Container');
const ContainerRegistrationService = require('./ContainerRegistrationService');
const ContainerResolutionService   = require('./ContainerResolutionService');
const ServiceDefinitionCatalog     = require('./ServiceDefinitionCatalog');
const DefinitionProviderCatalog    = require('./DefinitionProviderCatalog');
const InstanceDefinitionProvider   = require('./definitionProviders/InstanceDefinitionProvider');
const ModuleDefinitionProvider     = require('./definitionProviders/ModuleDefinitionProvider');
const ModuleEnumerator             = require('./facilities/ModuleEnumerator');

module.exports = function Deependency() {

  const DEFAULT_CONTAINER = 'Default';
  const instanceDefinitionProvider = new InstanceDefinitionProvider();
  const moduleDefinitionProvider   = new ModuleDefinitionProvider();

  var _containers = { };

  var _definitionProviderCatalog = new DefinitionProviderCatalog([
    moduleDefinitionProvider,
    instanceDefinitionProvider,
  ]);

  this.container = function (containerName) {

    var container = getOrCreateContainerByName(containerName || DEFAULT_CONTAINER);

    return container;

  };

  this.enumerateModules = function (rootPath, options) {

    var moduleEnumerator = new ModuleEnumerator(rootPath, options);

    return moduleEnumerator.enumerate();

  };

  var getOrCreateContainerByName = function (containerName) {

    var container = _containers[containerName];

    if (!container) {

      var definitionProviderCatalog = new DefinitionProviderCatalog(
        _definitionProviderCatalog.all()
      );

      var serviceDefinitionCatalog = new ServiceDefinitionCatalog();

      var containerRegistrationService = new ContainerRegistrationService(
        definitionProviderCatalog,
        serviceDefinitionCatalog
      );

      var containerResolutionService = new ContainerResolutionService(
        serviceDefinitionCatalog
      );

      container = new Container(containerRegistrationService, containerResolutionService);

      _containers[containerName] = container;

    }

    return container;

  };

};


text:
// Copyright (C) 2017 Peter Robinson and the Smart Contract Application Browser contributors.
package com.nelladragon.scab.language;

import com.nelladragon.common.crypto.Rand;

/**
 * List of thoughts.
 */
public class WordGenThoughts {

    private static String[] words = new String[] {
            "Do not argue with an idiot. He will drag you down to his level and beat you with experience.",
            "A day without smiling is a day wasted.",
            "Sometimes we expect more from others because we would be willing to do that much more for them.",
            "When tempted to fight fire with fire, remember that Fire Fighters usually uses water.",
            "Burial shrouds have no pockets.",
            "Live modestly.",
            "Where will you be next year?",
            "Live for today. Plan for tomorrow.",
            "It's no use going back to yesterday, because I was a different person then.",
            "Hardship often prepares an ordinary person for an extraordinary destiny.",
            "We are what we repeatedly do. Greatness then, is not an act, but a habit.",
            "The more I learn, the more I realize how much I don't know.",
            "Smile, it is good for you",
            "Take time to live life",
            "Smile",
            "Do the best you can",
            "Be the best person you can be",
            "what will you be doing in one year's time?",
            "less is more",
            "if in doubt, wait out"

    };

    public static String getRandomThoughts() {
        int len = words.length;
        int rand = Rand.generateRandomPositiveInt();
        int ofs = rand % len;
        return words[ofs];
    }

}


text:
package integration_test

import (
	"bytes"
	"encoding/json"
	"github.com/aclindsa/moneygo/internal/config"
	"github.com/aclindsa/moneygo/internal/handlers"
	"github.com/aclindsa/moneygo/internal/models"
	"github.com/aclindsa/moneygo/internal/store/db"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
)

var server *httptest.Server

func Delete(client *http.Client, url string) (*http.Response, error) {
	request, err := http.NewRequest(http.MethodDelete, url, nil)
	if err != nil {
		return nil, err
	}
	return client.Do(request)
}

func Put(client *http.Client, url string, contentType string, body io.Reader) (*http.Response, error) {
	request, err := http.NewRequest(http.MethodPut, url, body)
	if err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", contentType)
	return client.Do(request)
}

type TransactType interface {
	Read(string) error
}

func create(client *http.Client, input, output TransactType, urlsuffix string) error {
	obj, err := json.MarshalIndent(input, "", "  ")
	if err != nil {
		return err
	}
	response, err := client.Post(server.URL+urlsuffix, "application/json", bytes.NewReader(obj))
	if err != nil {
		return err
	}

	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if err != nil {
		return err
	}

	var e handlers.Error
	err = (&e).Read(string(body))
	if err != nil {
		return err
	}
	if e.ErrorId != 0 || len(e.ErrorString) != 0 {
		return &e
	}

	err = output.Read(string(body))
	if err != nil {
		return err
	}

	return nil
}

func read(client *http.Client, output TransactType, urlsuffix string) error {
	response, err := client.Get(server.URL + urlsuffix)
	if err != nil {
		return err
	}

	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if err != nil {
		return err
	}

	var e handlers.Error
	err = (&e).Read(string(body))
	if err != nil {
		return err
	}
	if e.ErrorId != 0 || len(e.ErrorString) != 0 {
		return &e
	}

	err = output.Read(string(body))
	if err != nil {
		return err
	}

	return nil
}

func update(client *http.Client, input, output TransactType, urlsuffix string) error {
	obj, err := json.MarshalIndent(input, "", "  ")
	if err != nil {
		return err
	}
	response, err := Put(client, server.URL+urlsuffix, "application/json", bytes.NewReader(obj))
	if err != nil {
		return err
	}

	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if err != nil {
		return err
	}

	var e handlers.Error
	err = (&e).Read(string(body))
	if err != nil {
		return err
	}
	if e.ErrorId != 0 || len(e.ErrorString) != 0 {
		return &e
	}

	err = output.Read(string(body))
	if err != nil {
		return err
	}

	return nil
}

func remove(client *http.Client, urlsuffix string) error {
	response, err := Delete(client, server.URL+urlsuffix)
	if err != nil {
		return err
	}

	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if err != nil {
		return err
	}

	var e handlers.Error
	err = (&e).Read(string(body))
	if err != nil {
		return err
	}
	if e.ErrorId != 0 || len(e.ErrorString) != 0 {
		return &e
	}

	return nil
}

func uploadFile(client *http.Client, filename, urlsuffix string) error {
	var buf bytes.Buffer
	mw := multipart.NewWriter(&buf)

	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	filewriter, err := mw.CreateFormFile("file", filename)
	if err != nil {
		return err
	}
	if _, err := io.Copy(filewriter, file); err != nil {
		return err
	}

	mw.Close()

	response, err := client.Post(server.URL+urlsuffix, mw.FormDataContentType(), &buf)
	if err != nil {
		return err
	}

	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	if err != nil {
		return err
	}

	var e handlers.Error
	err = (&e).Read(string(body))
	if err != nil {
		return err
	}
	if e.ErrorId != 0 || len(e.ErrorString) != 0 {
		return &e
	}

	return nil
}

func NewAmount(amt string) models.Amount {
	var a models.Amount
	if _, ok := a.SetString(amt); !ok {
		panic("Unable to call Amount.SetString()")
	}
	return a
}

func amountsMatch(a models.Amount, amt string) bool {
	cmp := NewAmount(amt)
	return a.Cmp(&cmp.Rat) == 0
}

func accountBalanceHelper(t *testing.T, client *http.Client, account *models.Account, balance string) {
	t.Helper()
	transactions, err := getAccountTransactions(client, account.AccountId, 0, 0, "")
	if err != nil {
		t.Fatalf("Couldn't fetch account transactions for '%s': %s\n", account.Name, err)
	}

	if !amountsMatch(transactions.EndingBalance, balance) {
		t.Errorf("Expected ending balance for '%s' to be '%s', but found %s\n", account.Name, balance, transactions.EndingBalance)
	}
}

func RunWith(t *testing.T, d *TestData, fn TestDataFunc) {
	testdata, err := d.Initialize()
	if err != nil {
		t.Fatalf("Failed to initialize test data: %s", err)
	}
	defer func() {
		err := testdata.Teardown()
		if err != nil {
			t.Fatal(err)
		}
	}()

	fn(t, testdata)
}

func RunTests(m *testing.M) int {
	envDbType := os.Getenv("MONEYGO_TEST_DB")
	var dbType config.DbType
	var dsn string

	switch envDbType {
	case "", "sqlite", "sqlite3":
		dbType = config.SQLite
		dsn = ":memory:"
	case "mariadb", "mysql":
		dbType = config.MySQL
		dsn = "root@127.0.0.1/moneygo_test&parseTime=true"
	case "postgres", "postgresql":
		dbType = config.Postgres
		dsn = "postgres://postgres@localhost/moneygo_test"
	default:
		log.Fatalf("Invalid value for $MONEYGO_TEST_DB: %s\n", envDbType)
	}

	if envDSN := os.Getenv("MONEYGO_TEST_DSN"); len(envDSN) > 0 {
		dsn = envDSN
	}

	db, err := db.GetStore(dbType, dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	db.Empty() // clear the DB tables

	server = httptest.NewTLSServer(&handlers.APIHandler{Store: db})
	defer server.Close()

	return m.Run()
}

func TestMain(m *testing.M) {
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	os.Exit(RunTests(m))
}


text:
require 'puppet/parameter/netscaler_name'
require 'puppet/property/netscaler_truthy'
require 'puppet/property/netscaler_traffic_domain'

Puppet::Type.newtype(:netscaler_rewritepolicylabel) do
  @doc = 'Manage basic netscaler rewrite policy label objects.'

  apply_to_device
  ensurable

  newparam(:name, :parent => Puppet::Parameter::NetscalerName, :namevar => true)

  newproperty(:transform_name) do
    desc "Types of transformations allowed by the policies bound to the label.
    The following types are supported:
    * http_req - HTTP requests
    * http_res - HTTP responses
    * othertcp_req - Non-HTTP TCP requests
    * othertcp_res - Non-HTTP TCP responses
    * url - URLs
    * text - Text strings
    * clientless_vpn_req - NetScaler clientless VPN requests
    * clientless_vpn_res - NetScaler clientless VPN responses
    * sipudp_req - SIP requests
    * sipudp_res - SIP responses
    * diameter_req - DIAMETER requests
    * diameter_res - DIAMETER responses."

    validate do |value|
      if ! [
        :http_req,
        :http_res,
        :othertcp_req,
        :othertcp_res,
        :url,
        :text,
        :clientless_vpn_req,
        :clientless_vpn_res,
        :sipudp_req,
        :sipudp_res,
        :diameter_req,
        :diameter_res
      ].any?{ |s| s.casecmp(value.to_sym) == 0 }
        fail ArgumentError, "Valid options: http_req, http_res, othertcp_req, othertcp_res, url, text, clientless_vpn_req, clientless_vpn_res, sipudp_req, sipudp_res, diameter_req, diameter_res"
      end
    end

    munge(&:downcase)
  end

  newproperty(:comments) do
    desc "Any comments to preserve information about this rewrite policy label."
  end
end


text:
package eap.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eap.util.StringUtil;
import eap.util.UrlUtil;

/**
 * <p> Title: </p>
 * <p> Description: </p>
 * @作者 chiknin@gmail.com
 * @创建时间
 * @版本 1.00
 * @修改记录
 * @see org.springframework.web.filter.CharacterEncodingFilter
 * <pre>
 * 版本       修改人         修改时间         修改内容描述
 * ----------------------------------------
 *
 * ----------------------------------------
 * </pre>
 */
public class CharacterEncodingFilter extends EnhanceFilter {

	private String encoding;
	private boolean forceEncoding = false;

	private String onceCharsetParamName = "_charset";

	@Override
	protected void doFilterCleaned(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException
	{
		String charset = UrlUtil.getUrlQueryStringAsMap(request.getQueryString()).get(onceCharsetParamName);
		if (StringUtil.isBlank(charset)) {
			charset = encoding;
		}

		if (charset != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
			request.setCharacterEncoding(charset);
			if (this.forceEncoding) {
				response.setCharacterEncoding(charset);
			}
		}

		filterChain.doFilter(request, response);
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}
	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}
	public String getOnceCharsetParamName() {
		return onceCharsetParamName;
	}
	public void setOnceCharsetParamName(String onceCharsetParamName) {
		this.onceCharsetParamName = onceCharsetParamName;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DayBar.Contract.Auth;
using Office365Api.Helpers.Office365;

namespace Office365Api.Helpers.Impl
{
    public class TokenGetService : ITokenGetService
    {
        private readonly CalendarHelper _auth;

        public TokenGetService(CalendarHelper auth)
        {
            _auth = auth;
        }

        public async Task<string> GetToken()
        {
            var token = await _auth.GetCalendarToken();

            return token;
        }
    }
}


text:
package org.hisp.dhis.period;

import java.util.Date;
import java.util.List;

import org.hisp.dhis.calendar.Calendar;
import org.hisp.dhis.calendar.DateTimeUnit;

import com.google.common.collect.Lists;

/**
 * @author Lars Helge Overland
 */
public class BiMonthlyPeriodType
    extends CalendarPeriodType
{
    private static final String ISO_FORMAT = "yyyyMMB";

    private static final String ISO8601_DURATION = "P2M";

    /**
     * The name of the BiMonthlyPeriodType, which is "BiMonthly".
     */
    public static final String NAME = "BiMonthly";

    public static final int FREQUENCY_ORDER = 61;

    public static final String SQL_INTERVAL = "2 months";

    // -------------------------------------------------------------------------
    // PeriodType functionality
    // -------------------------------------------------------------------------

    @Override
    public PeriodTypeEnum getPeriodTypeEnum()
    {
        return PeriodTypeEnum.BI_MONTHLY;
    }

    @Override
    public Period createPeriod( DateTimeUnit dateTimeUnit, Calendar calendar )
    {
        DateTimeUnit start = new DateTimeUnit( dateTimeUnit );
        start.setMonth( ((start.getMonth() - 1) - ((start.getMonth() - 1) % 2)) + 1 );
        start.setDay( 1 );

        DateTimeUnit end = new DateTimeUnit( start );

        end = calendar.plusMonths( end, 1 );
        end.setDay( calendar.daysInMonth( end.getYear(), end.getMonth() ) );

        return toIsoPeriod( start, end, calendar );
    }

    @Override
    public int getFrequencyOrder()
    {
        return FREQUENCY_ORDER;
    }

    @Override
    public String getSqlInterval()
    {
        return SQL_INTERVAL;
    }

    // -------------------------------------------------------------------------
    // CalendarPeriodType functionality
    // -------------------------------------------------------------------------
    @Override
    public DateTimeUnit getDateWithOffset( DateTimeUnit dateTimeUnit, int offset, Calendar calendar )
    {
        return calendar.plusMonths( dateTimeUnit, 2 * offset );
    }

    /**
     * Generates bimonthly Periods for the whole year in which the start date of
     * the given Period exists.
     */
    @Override
    public List<Period> generatePeriods( DateTimeUnit dateTimeUnit )
    {
        Calendar cal = getCalendar();

        dateTimeUnit.setMonth( 1 );
        dateTimeUnit.setDay( 1 );

        List<Period> periods = Lists.newArrayList();

        int year = dateTimeUnit.getYear();

        while ( dateTimeUnit.getYear() == year )
        {
            periods.add( createPeriod( dateTimeUnit, cal ) );
            dateTimeUnit = cal.plusMonths( dateTimeUnit, 2 );
        }

        return periods;
    }

    /**
     * Generates the last 6 bi-months where the last one is the bi-month which
     * the given date is inside.
     */
    @Override
    public List<Period> generateRollingPeriods( DateTimeUnit dateTimeUnit, Calendar calendar )
    {
        dateTimeUnit.setDay( 1 );
        DateTimeUnit iterationDateTimeUnit = calendar.minusMonths( dateTimeUnit, (dateTimeUnit.getMonth() % 2) + 10 );

        List<Period> periods = Lists.newArrayList();

        for ( int i = 0; i < 6; i++ )
        {
            periods.add( createPeriod( iterationDateTimeUnit, calendar ) );
            iterationDateTimeUnit = calendar.plusMonths( iterationDateTimeUnit, 2 );
        }

        return periods;
    }

    @Override
    public String getIsoDate( DateTimeUnit dateTimeUnit, Calendar calendar )
    {
        return String.format( "%d%02dB", dateTimeUnit.getYear(), (dateTimeUnit.getMonth() + 1) / 2 );
    }

    @Override
    public String getIsoFormat()
    {
        return ISO_FORMAT;
    }

    @Override
    public Date getRewindedDate( Date date, Integer rewindedPeriods )
    {
        Calendar cal = getCalendar();

        date = date != null ? date : new Date();
        rewindedPeriods = rewindedPeriods != null ? rewindedPeriods : 1;

        DateTimeUnit dateTimeUnit = cal.fromIso( DateTimeUnit.fromJdkDate( date ) );
        dateTimeUnit = cal.minusMonths( dateTimeUnit, rewindedPeriods * 2 );

        return cal.toIso( dateTimeUnit ).toJdkDate();
    }

    @Override
    public String getIso8601Duration()
    {
        return ISO8601_DURATION;
    }
}


text:
package com.francetelecom.clara.cloud.techmodel.cf.services.managed;

import com.francetelecom.clara.cloud.model.DependantModelItem;
import com.francetelecom.clara.cloud.model.DeploymentStateEnum;
import com.francetelecom.clara.cloud.model.XaasSubscription;
import com.francetelecom.clara.cloud.techmodel.cf.Space;
import com.francetelecom.clara.cloud.techmodel.cf.SpaceName;
import com.francetelecom.clara.cloud.techmodel.cf.services.DefaultServiceNameSpecification;
import org.springframework.util.Assert;

import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashSet;
import java.util.Set;

@XmlRootElement
@Entity
public class ManagedService extends XaasSubscription {

	private String serviceInstance;

	private String service;

	private String plan;

	@XmlElement(name = "space")
	@OneToOne
	private Space space;

	protected ManagedService() {
	}

	public ManagedService(String service, String plan, String serviceInstance, Space space) {
		super();
		setPlan(plan);
		setService(service);
		setServiceInstance(serviceInstance);
		setSpace(space);
	}

	public void activate() {
		setDeploymentState(DeploymentStateEnum.CREATED);
	}

	public void delete() {
		setDeploymentState(DeploymentStateEnum.REMOVED);
	}

	private void setService(String service) {
		Assert.hasText(plan,"unable to set service type <"+service+">. invalid type.");
		this.service = service;
	}

	private void setPlan(String plan) {
		Assert.hasText(plan,"unable to set service plan <"+plan+">. invalid plan.");
		this.plan = plan;
	}

	private void setServiceInstance(String serviceName) {
		new DefaultServiceNameSpecification().assertIsSatisfiedBy(serviceName);
		this.serviceInstance = serviceName;
	}

	private void setSpace(Space space) {
		Assert.notNull(space,"unable to scope service <"+serviceInstance+"> to space <"+space+">. invalid space.");
		this.space = space;
	}

	public String getService() {
		return service;
	}

	public String getServiceInstance() {
		return serviceInstance;
	}

	public String getPlan() {
		return plan;
	}

	public SpaceName getSpace() {
		return space.getSpaceName();
	}

	@Override
	public Set<DependantModelItem> listDepedencies() {
		Set<DependantModelItem> dependantModelItems = new HashSet<>();
		dependantModelItems.add(space);
		return dependantModelItems;
	}

}


text:
from jython.SchedulerLoad import SchedulerLoad
import sys

class AppworxLoad(SchedulerLoad):
  def __init__(self, args):
    SchedulerLoad.__init__(self, args)

if __name__ == "__main__":
  props = sys.argv[1]
  aw = AppworxLoad(props)
  aw.run()


text:
var SH = require("../lib/session_helper");
var async = require('async');
var moment = require('moment');
//Models
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment');

var mongoose = require('mongoose');
var Trip = mongoose.model('Trip');

exports.home = function(req, res){
	SH.getSessionData(req.session.user, function(data) {
		var asyncfunctions = [];
		var i;
		for(i = 0; i < data.trips.length; i++) {
			var func = function(cb) {
				var id = data.trips[i]._id;
				Comment.find({trip: id})
				.populate('user trip')
				.lean()
				.exec(function(err, comments) {
					i++;
					cb(null, comments);
				});
			};
			asyncfunctions.push(func);
		}
		i = 0;
		async.series(asyncfunctions, function(err, results) {
			for(var i = 0; i < results.length; i++) {
				data.trips[i].comments = results[i];
				for(var j = 0; j < data.trips[i].comments.length; j++) {
					var timeago = moment(data.trips[i].comments[j].created_at).fromNow();
					data.trips[i].comments[j].timeago = timeago;
				}
			}
			Trip.find({featured: true}, function(err, trips) {
				data.featured = trips;
				data.showPicUpload = true;
				res.render('index', data);
			});
		});
	});
};
exports.home2 = function(req, res){
	SH.getSessionData(req.session.user, function(data) {
		var asyncfunctions = [];
		var i;
		for(i = 0; i < data.trips.length; i++) {
			var func = function(cb) {
				var id = data.trips[i]._id;
				Comment.find({trip: id})
				.populate('user trip')
				.lean()
				.exec(function(err, comments) {
					i++;
					cb(null, comments);
				});
			};
			asyncfunctions.push(func);
		}
		i = 0;
		async.series(asyncfunctions, function(err, results) {
			for(var i = 0; i < results.length; i++) {
				data.trips[i].comments = results[i];
				for(var j = 0; j < data.trips[i].comments.length; j++) {
					var timeago = moment(data.trips[i].comments[j].created_at).fromNow();
					data.trips[i].comments[j].timeago = timeago;
				}
			}
			Trip.find({featured: true}, function(err, trips) {
				data.featured = trips;
				data.showPicUpload = false;
				res.render('index', data);
			});
		});
	});
};


text:
.. code-block:: matlab

    query = experiment.Session;


text:
require "administrate/field/has_one"
require "support/constant_helpers"
require "rails_helper"
require "administrate/resource_resolver"
require "administrate/page"
require "administrate/page/form"

describe Administrate::Field::HasOne do
  describe "#nested_form" do
    it "returns a form" do
      product_meta_tag = double
      field = Administrate::Field::HasOne.new(:product_meta_tag,
        product_meta_tag, :show)

      form = field.nested_form

      expect(form).to be_present
    end
  end

  describe ".permitted_attribute" do
    context "with custom class_name" do
      it "returns attributes from correct dashboard" do
        field = Administrate::Field::Deferred.new(Administrate::Field::HasOne.
            with_options(class_name: :product_meta_tag))

        field_name = "seo_meta_tag"
        attributes = field.permitted_attribute(field_name)
        expect(attributes[:"#{field_name}_attributes"]).
          to eq(%i(meta_title meta_description id))
      end
    end
  end

  describe "#to_partial_path" do
    it "returns a partial based on the page being rendered" do
      page = :show
      product_meta_tag = double
      field = Administrate::Field::HasOne.new(:product_meta_tag,
        product_meta_tag, page)

      path = field.to_partial_path

      expect(path).to eq("/fields/has_one/#{page}")
    end
  end
end


text:
package org.springframework.social.smartcloud.api;

import java.util.List;

/**
 * User: greg
 * Date: 13-08-22
 * Time: 10:37 AM
 */
public interface ContactOperations {

    List<Contact> getContacts();

}


text:
@implementation CustomTextField

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

- (CGRect)textRectForBounds:(CGRect)bounds {
    return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

@end


text:
import theme from '../../../theme';

module.exports = {
    wrapper: {
        display: 'block',
        height: theme.input.height,
        lineHeight: theme.input.lineHeight,
    },
    wrapper__inline: {
        display: 'inline',
    },

    // checkbox or radio
    control: {
        marginRight: '0.5em',
    },
};