text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2015-2018 The OpenZipkin Authors

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
    in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License
    is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
    or implied. See the License for the specific language governing permissions and limitations under
    the License.

-->
<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>io.zipkin.java</groupId>
    <artifactId>parent</artifactId>
    <version>2.7.4-SNAPSHOT</version>
  </parent>

  <artifactId>zipkin</artifactId>
  <name>Zipkin</name>

  <properties>
    <main.basedir>${project.basedir}/..</main.basedir>
    <main.java.version>1.6</main.java.version>
    <main.signature.artifact>java16</main.signature.artifact>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.zipkin.zipkin2</groupId>
      <artifactId>zipkin</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.auto.value</groupId>
      <artifactId>auto-value</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.jvnet</groupId>
      <artifactId>animal-sniffer-annotation</artifactId>
      <version>1.0</version>
      <!-- annotations are not runtime retention, so don't need a runtime dep -->
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.2</version>
    </dependency>

    <dependency>
      <groupId>com.squareup.okio</groupId>
      <artifactId>okio</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- to mock Platform calls -->
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito2</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- Need to block import of shaded packages in bnd.bnd as maven bundle plugin analyzes the unshaded jar -->
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <configuration>
          <instructions>
            <_include>-bnd.bnd</_include>
          </instructions>
        </configuration>
      </plugin>
      <!-- Use of gson is internal only -->
      <plugin>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadeTestJar>false</shadeTestJar>
              <minimizeJar>true</minimizeJar>
              <artifactSet>
                <excludes>
                  <exclude>io.zipkin.zipkin2:zipkin</exclude>
                </excludes>
              </artifactSet>
              <filters>
                <filter>
                  <artifact>com.google.code.gson:gson</artifact>
                  <includes>
                    <include>com/google/gson/stream/JsonReader*.class</include>
                    <include>com/google/gson/stream/JsonToken.class</include>
                    <include>com/google/gson/stream/MalformedJsonException.class</include>
                    <include>com/google/gson/internal/JsonReaderInternalAccess.class</include>
                  </includes>
                </filter>
              </filters>
              <relocations>
                <relocation>
                  <pattern>com.google.gson</pattern>
                  <shadedPattern>zipkin.internal.gson</shadedPattern>
                </relocation>
              </relocations>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <manifestEntries>
                    <Automatic-Module-Name>zipkin</Automatic-Module-Name>
                  </manifestEntries>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <id>default-jar</id>
            <configuration>
              <archive>
                <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
              </archive>
            </configuration>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
          <execution>
            <id>default-test-jar</id>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
<?php

namespace Saguajardo\BootstrapMenu\Traits;

use Illuminate\Support\Str;

trait Slugable
{
    /**
     * Set slug attribute.
     *
     * @param string $value
     * @return void
     */
    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = Str::slug($value, config('bootstrap-menu.separator'));
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <string>

#include "../../engine/pdevslib.h"

void packetdemux::init(double t,...) {
	//The 'parameters' variable contains the parameters transferred from the editor.
	va_list parameters;
	va_start(parameters,t);
	//To get a parameter: %Name% = va_arg(parameters,%Type%)
	//where:
	//      %Name% is the parameter name
	//	%Type% is the parameter type

	// TODO: using 4 is too rigid. Make the first param to be n and then iterate n times reading args
	for (int i=0;i<4;i++) {
		Labels[i] = va_arg(parameters,char*);
		printLog(LOG_LEVEL_INIT, "[INIT] %s: Label %u = %s \n", this->getName(), i, Labels[i].data());
	};

	char* fvar = va_arg(parameters,char*);
	n = readDefaultParameterValue<int>(fvar);
	printLog(LOG_LEVEL_INIT, "[INIT] %s: Number of Labels: %u \n", this->getName(), n);

	sigma = INF;
}
double packetdemux::ta(double t) {
	//This function returns a double.
	return sigma;
}
void packetdemux::dint(double t) {
	sigma=INF;
	if(packetBuffer.size() != 0){
		sigma = 0;
	}
}
void packetdemux::dext(Event x, double t) {
	//The input event is in the 'x' variable.
	//where:
	//     'x.value' is the value (pointer to void)
	//     'x.port' is the port number
	//     'e' is the time elapsed since last transition

	auto arrivedPacket = std::static_pointer_cast<TdaqPacket>(x.valuePtr);
	packetBuffer.push(arrivedPacket);

	printLog(10, "[%f] %s_ext: Packet arrived with FlowID=%s \n",t, this->getName(), arrivedPacket->FlowID);

	sigma = 0;
}
Event packetdemux::lambda(double t) {
	auto packetToSend = packetBuffer.front();
	packetBuffer.pop();

	for (int i=0;i<n;i++) {
		if (Labels[i].compare("*") == 0 || Labels[i].compare(packetToSend->FlowID) == 0) {
			printLog(10, "[%f] %s_lamb: forwarding packet %u(%s) by outport %u (matched label: %s) \n", t, this->getName(), packetToSend->ID, packetToSend->FlowID, i, Labels[i].data());
			return Event(packetToSend,i);
		}
	}

	return Event(NULL,0);
}
void packetdemux::exit() {
	//Code executed at the end of the simulation.
}


text:
//4. Write a method that finds the longest subsequence of equal numbers in given List<int>
//and returns the result as new List<int>. Write a program to test whether the method works correctly.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static List<int> LongestSeqEqual(List<int> list)
    {
        var result = new List<int>();
        int maxLength = 1;
        int currentLength = 1;
        int maxStart = 0;
        int currentStart = 0;
        for (int i = 1; i < list.Count; i++)
        {
            if(list[i - 1] == list[i])
            {
                currentLength++;
            }
            else
            {
                currentStart = i;
                currentLength = 1;
            }
            if(currentLength > maxLength)
            {
                maxLength = currentLength;
                maxStart = currentStart;
            }
        }
        for (int i = maxStart; i < maxStart + maxLength; i++)
        {
            result.Add(list[i]);
        }
        return result;
    }

    static void Main()
    {
        var list = new List<int>();
        Console.WriteLine("Please input a sequence of integers ending with empty line:");
        try
        {
            for (string input = Console.ReadLine(); input != string.Empty; input = Console.ReadLine())
            {
                list.Add(int.Parse(input));
            }
        }
        catch (System.FormatException)
        {
            Console.WriteLine("The input number was not in the correct format.");
        }
        Console.WriteLine("The longest sequence is: ");
        foreach (var item in LongestSeqEqual(list))
        {
            Console.WriteLine(item);
        }
    }
}


text:
<?php

namespace SimpSpector\Analyser\Formatter\Adapter;

use JMS\Serializer\SerializationContext;
use SimpSpector\Analyser\Result;

/**
 * @author David Badura <d.a.badura@gmail.com>
 */
class JsonAdapter extends SerializerAdapter
{
    /**
     * @param Result $result
     * @return string
     */
    public function format(Result $result)
    {
        return $this->serializer->serialize($result, 'json');
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'json';
    }
}


text:
package com.codepath.apps.restclienttemplate.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.codepath.apps.restclienttemplate.R;
import com.codepath.apps.restclienttemplate.TwitterApp;
import com.codepath.apps.restclienttemplate.TwitterClient;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.codepath.apps.restclienttemplate.models.User;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by anyazhang on 7/5/17.
 */

public class ModalFragment extends Fragment {

    TwitterClient client;
    Context context;
    private OnItemSelectedListener listener;
    public String userScreenName;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        client = TwitterApp.getRestClient();
        client.getProfileInfo(new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // deserialize the User obj
                User user = null;
                try {
                    user = User.fromJSON(response);
                    userScreenName = user.screenName;

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                openComposeModal(getContext());
            }
        });

    }

    public static ModalFragment newInstance(long reply_id, String tag) {
        ModalFragment fragmentModal = new ModalFragment();
        Bundle args = new Bundle();
        args.putLong("reply_id", reply_id);
        args.putString("tag", tag);
        fragmentModal.setArguments(args);

        return fragmentModal;
    }

    public interface OnItemSelectedListener {
        // This can be any number of events to be sent to the activity
        void updateTimeline(Tweet tweet, boolean updateMentions);
    }

    // Store the listener (activity) that will have events fired once the fragment is attached
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) context;
        } else {
            throw new ClassCastException(context.toString()
                    + " must implement ModalFragment.OnItemSelectedListener");
        }

    }

    public void openComposeModal(Context context) {
        client = TwitterApp.getRestClient();

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        final long reply_id = getArguments().getLong("reply_id", -1);
        final String tag = getArguments().getString("tag", "");

        boolean wrapInScrollView = false;

        final int MAX_TWEET_LENGTH = 140;

        Log.d("clicked", "reply");

        // inflate compose layout into view
        final View activity_compose = inflater.inflate(R.layout.activity_compose, null);

        // load data into view
        EditText etTweetBody = (EditText) activity_compose.findViewById(R.id.etTweetBody);
        etTweetBody.setText(tag);
        etTweetBody.setSelection(tag.length());
        final TextView tvCharCount = (TextView) activity_compose.findViewById(R.id.tvCharCount);
        tvCharCount.setText(String.valueOf(MAX_TWEET_LENGTH - tag.length()));

        // build modal
        new MaterialDialog.Builder(context)
                .title("Compose Tweet")
                .customView(activity_compose, wrapInScrollView)
                .positiveText("TWEET")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        EditText etTweet = (EditText) activity_compose.findViewById(R.id.etTweetBody);
                        String tweetText = etTweet.getText().toString();
                        Log.d("onSubmit", tweetText);
                        Log.d("onSubmit", "#" + String.valueOf(reply_id));
                        client.sendTweet(tweetText, reply_id, new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                Log.d("Success", String.valueOf(reply_id));
                                try {
                                    Tweet tweet = Tweet.fromJSON(response);
                                    if (listener != null) {
//                                        Log.d("tag", userScreenName);
//                                        Log.d("tag", String.valueOf(tag.equals("@" + userScreenName)));
                                        listener.updateTimeline(tweet, tag.equals("@" + userScreenName));
                                    }
                                    else {
                                        Log.d("listener", "couldn't update");
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                                Log.d("TwitterClient", response.toString());
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                Log.d("TwitterClient", responseString);
                                throwable.printStackTrace();

                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                Log.d("TwitterClient", errorResponse.toString());
                                throwable.printStackTrace();
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                                Log.d("TwitterClient", errorResponse.toString());
                                throwable.printStackTrace();
                            }
                        });
                    }
                })
                .show();
    }

}


text:
package com.ridebuddy.ui.models;

public class FbLogin {

	private String code,state;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	@Override
	public String toString() {
		return "FbLogin [code=" + code + ", state=" + state + "]";
	}
}


text:
package es.moki.ratelimitj.redis.extensions;

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class RedisStandaloneFlushExtension implements
        BeforeAllCallback, AfterAllCallback, AfterEachCallback {

    private static RedisClient client;
    private static StatefulRedisConnection<String, String> connect;

    @Override
    @SuppressWarnings("FutureReturnValueIgnored")
    public void afterAll(ExtensionContext context) {
        client.shutdownAsync();
    }

    @Override
    public void afterEach(ExtensionContext context) {
        connect.sync().flushdb();
    }

    @Override
    public void beforeAll(ExtensionContext context) {
        client = RedisClient.create("redis://localhost:7006");
        connect = client.connect();
    }

}


text:
from __future__ import print_function

# Imports
import math
import os
from enum import Enum

from constants import RUNCOMPSS_REL_PATH
from constants import CLEAN_PROCS_REL_PATH

############################################
# ERROR CLASS
############################################

class TestExecutionError(Exception):
    """
    Class representing an error when executing the tests

    :attribute msg: Error message when executing the tests
        + type: String
    """

    def __init__(self, msg):
        """
        Initializes the TestExecutionError class with the given error message

        :param msg: Error message when executing the tests
        """
        self.msg = msg

    def __str__(self):
        return str(self.msg)

############################################
# HELPER CLASS
############################################

class ExitValue(Enum):
    OK = 0,
    OK_RETRY = 1,
    SKIP = 2,
    UNSUPPORTED = 3,
    FAIL = 4

def str_exit_value_coloured(exit_value):
    """
    Returns the coloured string representation of the exit_value object

    :param exit_value: ExitValue object
        + type: ExitValue
    :return: The coloured string representation of the exit_value object
        + type: String
    """
    colour_white = "\033[0m"
    colour_red = "\033[31m"
    colour_green = "\033[32m"
    colour_orange = "\033[33m"
    colour_blue = "\033[34m"
    colour_purple = "\033[35m"

    if exit_value == ExitValue.OK:
        return colour_green + exit_value.name + colour_white
    if exit_value == ExitValue.OK_RETRY:
        return colour_orange + exit_value.name + colour_white
    if exit_value == ExitValue.SKIP:
        return colour_blue + exit_value.name + colour_white
    if exit_value == ExitValue.UNSUPPORTED:
        return colour_purple + exit_value.name + colour_white
    # FAIL
    return colour_red + exit_value.name + colour_white

def _merge_exit_values(ev1, ev2):
    """
    Merges the given two exit values preserving the worst result

    :param ev1: First ExitValue
        + type: ExitValue
    :param ev2: Second ExitValue
        + type: ExitValue
    :return: ExitValue representing the merge of the two given exit values preserving the worst result
        + type: ExitValue
    """
    if ev1 == ExitValue.FAIL or ev2 == ExitValue.FAIL:
        return ExitValue.FAIL
    if ev1 == ExitValue.OK_RETRY or ev2 == ExitValue.OK_RETRY:
        return ExitValue.OK_RETRY
    return ExitValue.OK

def get_exit_code(exit_value):
    if exit_value == ExitValue.OK or exit_value == ExitValue.OK_RETRY:
        return 0
    if exit_value == ExitValue.UNSUPPORTED or exit_value == ExitValue.SKIP:
        return 99
    # FAIL
    return 1

############################################
# PUBLIC METHODS
############################################

def execute_tests(cmd_args, compss_cfg):
    """
    Executes all the deployed tests and builds a result summary table.
    If failfast option is set, once a test fails the script exits.

    :param cmd_args: Object representing the command line arguments
        + type: argparse.Namespace
    :param compss_cfg:  Object representing the COMPSs test configuration options available in the given cfg file
        + type: COMPSsConfiguration
    :return: An ExitValue object indicating the exit status of the WORST test execution
        + type: ExitValue
    :raise TestExecutionError: If an error is encountered when creating the necessary structures to launch the test
    """
    # Load deployment structure folder paths
    compss_logs_root = compss_cfg.get_compss_base_log_dir()
    target_base_dir = compss_cfg.get_target_base_dir()
    execution_sanbdox = os.path.join(target_base_dir, "apps")

    # Execute all the deployed tests
    results = []
    for test_dir in sorted(os.listdir(execution_sanbdox)):
        test_path = os.path.join(execution_sanbdox, test_dir)
        ev, exec_time = _execute_test(test_dir, test_path, compss_logs_root, cmd_args, compss_cfg)
        results.append((test_dir, ev, exec_time))

        if cmd_args.fail_fast and ev == ExitValue.FAIL:
            print()
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            print("[ERROR] Test has failed and fail-fast option is set. Aborting...")
            break

    # Process test results
    headers = ["Test\nG. Id", " Test \nFamily", " Test  \nFam. Id", "Test Name", "Test Exec.\n  Folder", " Test\nResult", "Execution\n Time (s)"]
    results_info = []
    global_ev = ExitValue.OK
    for test_dir, ev, test_time in results:
        # Update global exit value
        global_ev = _merge_exit_values(global_ev, ev)
        # Colour the test exit value
        ev_color_str = str_exit_value_coloured(ev)
        # Retrieve test information
        test_global_num = int("".join(x for x in test_dir if x.isdigit()))
        test_name, _, family_dir, num_family = cmd_args.test_numbers["global"][test_global_num]
        # Append all information for rendering
        results_info.append([test_global_num, family_dir, num_family, test_name, test_dir, ev_color_str, test_time])

    # Print result summary table
    from tabulate import tabulate
    print()
    print("----------------------------------------")
    print("TEST RESULTS SUMMARY:")
    print()
    print(tabulate(results_info, headers=headers))
    print("----------------------------------------")

    # Return if any test has failed
    return global_ev

############################################
# INTERNAL METHODS
############################################

def _execute_test(test_name, test_path, compss_logs_root, cmd_args, compss_cfg):
    """
    Executes the given test with the given options and retrieves its exit value

    :param test_name: Name of the test (on deployment phase: #appXXX)
        + type: String
    :param test_path: Path of the test (on deployment phase)
        + type: String
    :param compss_logs_root: Root folder of the COMPSs logs (usually ~/.COMPSs)
        + type: String
    :param cmd_args: Object representing the command line arguments
        + type: argparse.Namespace
    :param compss_cfg: Object representing the COMPSs test configuration options available in the given cfg file
        + type: COMPSsConfiguration
    :return: An ExitValue object indicating the exit status of the test execution
        + type: ExitValue
    :return: Time spent on the test execution
        + type: Long
    :raise TestExecutionError: If an error is encountered when creating the necessary structures to launch the test
    """
    import time

    skip_file = os.path.join(test_path, "skip")
    if os.path.isfile(skip_file):
        print("[INFO] Skipping test " + str(test_name))
        return ExitValue.SKIP, 0

    # Else, execute test normally
    print("[INFO] Executing test " + str(test_name))

    target_base_dir = compss_cfg.get_target_base_dir()
    logs_sanbdox = os.path.join(target_base_dir, "logs")

    max_retries = cmd_args.retry
    retry = 1
    test_ev = ExitValue.FAIL
    start_time = time.time()
    while test_ev == ExitValue.FAIL and retry <= max_retries:
        if __debug__:
            print("[DEBUG] Executing test " + str(test_name) + " Retry: " + str(retry) + "/" + str(max_retries))
        # Create logs folder for current retry
        test_logs_path = os.path.join(logs_sanbdox, test_name + "_" + str(retry))
        try:
            os.makedirs(test_logs_path)
        except OSError:
            raise TestExecutionError("[ERROR] Cannot create application log dir " + str(test_logs_path))
        # Execute test specific execution file
        test_ev = _execute_test_cmd(test_path, test_logs_path, compss_logs_root, retry, compss_cfg)
        # Clean orphan processes (if any)
        _clean_procs(compss_cfg)
        # Sleep between executions
        time.sleep(2)
        # Increase retry counter
        retry = retry + 1
    end_time = time.time()
    # Return test exit value
    print("[INFO] Executed test " + str(test_name) + " with ExitValue " + test_ev.name)
    return test_ev, "%.3f" % (end_time - start_time)

def _execute_test_cmd(test_path, test_logs_path, compss_logs_root, retry, compss_cfg):
    """
    Executes the execution script of a given test

    :param test_path: Path to the test deployment folder
        + type: String
    :param test_logs_path: Path to store the execution logs
        + type: String
    :param compss_logs_root: Path of the root COMPSs log folder
        + type: String
    :param retry: Retry number
        + type: int
    :param compss_cfg: Object representing the COMPSs test configuration options available in the given cfg file
        + type: COMPSsConfiguration
    :return: An ExitValue object indicating the exit status of the test execution
        + type: ExitValue
    :raise TestExecutionError: If an error is encountered when creating the necessary structures to launch the test
    """
    # Create command
    execution_script_path = os.path.join(test_path, "execution")
    if not os.path.isfile(execution_script_path):
        raise TestExecutionError("[ERROR] Cannot find execution script " + str(execution_script_path))

    runcompss_bin = compss_cfg.get_compss_home() + RUNCOMPSS_REL_PATH
    runcompss_user_opts = compss_cfg.get_runcompss_opts()
    if runcompss_user_opts is None:
        runcompss_user_opts = ""

    cmd = [str(execution_script_path),
           str(runcompss_bin),
           str(compss_cfg.get_comm()),
           str(runcompss_user_opts),
           str(test_path),
           str(compss_logs_root),
           str(test_logs_path),
           str(retry),
           str(compss_cfg.get_execution_envs_str())]

    if __debug__:
        print("[DEBUG] Test execution command: " + str(cmd))

    # Invoke execution script
    import subprocess
    try:
        exec_env = os.environ.copy()
        exec_env["JAVA_HOME"] = compss_cfg.get_java_home()
        exec_env["COMPSS_HOME"] = compss_cfg.get_compss_home()
        p = subprocess.Popen(cmd, cwd=test_path, env=exec_env)
        p.communicate()
        exit_value = p.returncode
    except Exception:
        exit_value = -1

    # Log command exit_value/output/error
    print("[INFO] Text execution command EXIT_VALUE: " + str(exit_value))

    # Return exit status
    if exit_value == 0:
        if retry == 1:
            return ExitValue.OK
        return ExitValue.OK_RETRY
    if exit_value == 99:
        return ExitValue.UNSUPPORTED
    return ExitValue.FAIL

def _clean_procs(compss_cfg):
    """
    Cleans the remaining compss processes if any

    :param compss_cfg: Object representing the COMPSs test configuration options available in the given cfg file
        + type: COMPSsConfiguration
    :return:
    """
    clean_procs_bin = compss_cfg.get_compss_home() + CLEAN_PROCS_REL_PATH
    cmd = [clean_procs_bin]

    import subprocess
    try:
        p = subprocess.Popen(cmd)
        p.communicate()
        exit_value = p.returncode
    except Exception:
        exit_value = -1

    if exit_value != 0:
        print("[WARN] Captured error while executing clean_compss_procs between test executions. Proceeding anyways...")
        print("[WARN] clean_compss_procs command EXIT_VALUE: " + str(exit_value))


text:
using Goomer.Data.Models.BaseModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Goomer.Data.Common.Contracts
{
    public interface IDbRepository<T>
        where T : class, IAuditInfo, IDeletableEntity
    {
        IQueryable<T> All();

        IQueryable<T> AllWithDeleted();

        T GetById(object id);

        void Add(T entity);

        void Delete(T entity);

        void HardDelete(T entity);

        void Update(T entity);
    }
}


text:
package org.apache.camel.component.rxjava.engine;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import org.apache.camel.BindToRegistry;
import org.apache.camel.Exchange;
import org.apache.camel.FailedToStartRouteException;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.support.DefaultExchange;
import org.apache.camel.support.ExchangeHelper;
import org.junit.Assert;
import org.junit.Test;
import org.reactivestreams.Publisher;

public class RxJavaStreamsServiceTest extends RxJavaStreamsServiceTestSupport {

    @BindToRegistry("hello")
    private SampleBean bean = new SampleBean();

    public static class SampleBean {
        public String hello(String name) {
            return "Hello " + name;
        }
    }

    // ************************************************
    // fromStream/from
    // ************************************************

    @Test
    public void testFromStreamDirect() throws Exception {
        context.addRoutes(new RouteBuilder() {
            public void configure() {
                from("direct:reactive").to("reactive-streams:numbers");
            }
        });

        context.start();
        ProducerTemplate template = context.createProducerTemplate();

        AtomicInteger value = new AtomicInteger(0);

        Flowable.fromPublisher(crs.fromStream("numbers", Integer.class)).doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue())).subscribe();

        template.sendBody("direct:reactive", 1);
        template.sendBody("direct:reactive", 2);
        template.sendBody("direct:reactive", 3);
    }

    @Test
    public void testFromStreamTimer() throws Exception {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("timer:tick?period=5&repeatCount=30").setBody().header(Exchange.TIMER_COUNTER).to("reactive-streams:tick");
            }
        });

        final int num = 30;
        final CountDownLatch latch = new CountDownLatch(num);
        final AtomicInteger value = new AtomicInteger(0);

        Flowable.fromPublisher(crs.fromStream("tick", Integer.class)).doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue())).doOnNext(n -> latch.countDown())
            .subscribe();

        context.start();

        latch.await(5, TimeUnit.SECONDS);

        Assert.assertEquals(num, value.get());
    }

    @Test
    public void testFromStreamMultipleSubscriptionsWithDirect() throws Exception {
        context.start();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:reactive").to("reactive-streams:direct");
            }
        });

        CountDownLatch latch1 = new CountDownLatch(2);
        Flowable.fromPublisher(crs.fromStream("direct", Integer.class)).doOnNext(res -> latch1.countDown()).subscribe();

        CountDownLatch latch2 = new CountDownLatch(2);
        Flowable.fromPublisher(crs.fromStream("direct", Integer.class)).doOnNext(res -> latch2.countDown()).subscribe();

        template.sendBody("direct:reactive", 1);
        template.sendBody("direct:reactive", 2);

        Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
    }

    @Test
    public void testMultipleSubscriptionsWithTimer() throws Exception {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("timer:tick?period=50").setBody().header(Exchange.TIMER_COUNTER).to("reactive-streams:tick");
            }
        });

        CountDownLatch latch1 = new CountDownLatch(5);
        Disposable disp1 = Flowable.fromPublisher(crs.fromStream("tick", Integer.class)).subscribe(res -> latch1.countDown());

        context.start();

        // Add another subscription
        CountDownLatch latch2 = new CountDownLatch(5);
        Disposable disp2 = Flowable.fromPublisher(crs.fromStream("tick", Integer.class)).subscribe(res -> latch2.countDown());

        assertTrue(latch1.await(5, TimeUnit.SECONDS));
        assertTrue(latch2.await(5, TimeUnit.SECONDS));

        // Un subscribe both
        disp1.dispose();
        disp2.dispose();

        // No active subscriptions, warnings expected
        Thread.sleep(60);

        // Add another subscription
        CountDownLatch latch3 = new CountDownLatch(5);
        Disposable disp3 = Flowable.fromPublisher(crs.fromStream("tick", Integer.class)).subscribe(res -> latch3.countDown());

        assertTrue(latch3.await(5, TimeUnit.SECONDS));
        disp3.dispose();
    }

    @Test
    public void testFrom() throws Exception {
        context.start();

        Publisher<Exchange> timer = crs.from("timer:reactive?period=250&repeatCount=3");

        AtomicInteger value = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(3);

        Flowable.fromPublisher(timer).map(exchange -> ExchangeHelper.getHeaderOrProperty(exchange, Exchange.TIMER_COUNTER, Integer.class))
            .doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue())).doOnNext(res -> latch.countDown()).subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    }

    // ************************************************
    // fromPublisher
    // ************************************************

    @Test
    public void testFromPublisher() throws Exception {
        context.start();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:source").to("direct:stream").setBody().simple("after stream: ${body}");
            }
        });

        crs.process("direct:stream", publisher -> Flowable.fromPublisher(publisher).map(e -> {
            int i = e.getIn().getBody(Integer.class);
            e.getOut().setBody(-i);

            return e;
        }));

        for (int i = 1; i <= 3; i++) {
            Assert.assertEquals("after stream: " + (-i), template.requestBody("direct:source", i, String.class));
        }
    }

    @Test
    public void testFromPublisherWithConversion() throws Exception {
        context.start();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:source").to("direct:stream").setBody().simple("after stream: ${body}");
            }
        });

        crs.process("direct:stream", Integer.class, publisher -> Flowable.fromPublisher(publisher).map(Math::negateExact));

        for (int i = 1; i <= 3; i++) {
            Assert.assertEquals("after stream: " + (-i), template.requestBody("direct:source", i, String.class));
        }
    }

    // ************************************************
    // toStream/to
    // ************************************************

    @Test
    public void testToStream() throws Exception {
        context.addRoutes(new RouteBuilder() {
            public void configure() {
                from("reactive-streams:reactive").setBody().constant("123");
            }
        });

        context.start();

        Publisher<Exchange> publisher = crs.toStream("reactive", new DefaultExchange(context));
        Exchange res = Flowable.fromPublisher(publisher).blockingFirst();

        Assert.assertNotNull(res);

        String content = res.getIn().getBody(String.class);

        Assert.assertNotNull(content);
        Assert.assertEquals("123", content);
    }

    @Test
    public void testTo() throws Exception {
        context.start();

        AtomicInteger value = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(1);

        Flowable.just(1, 2, 3).flatMap(e -> crs.to("bean:hello", e, String.class)).doOnNext(res -> Assert.assertEquals("Hello " + value.incrementAndGet(), res))
            .doOnNext(res -> latch.countDown()).subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    }

    @Test
    public void testToWithExchange() throws Exception {
        context.start();

        AtomicInteger value = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(1);

        Flowable.just(1, 2, 3).flatMap(e -> crs.to("bean:hello", e)).map(e -> e.getOut()).map(e -> e.getBody(String.class))
            .doOnNext(res -> Assert.assertEquals("Hello " + value.incrementAndGet(), res)).doOnNext(res -> latch.countDown()).subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    }

    @Test
    public void testToFunction() throws Exception {
        context.start();

        AtomicInteger value = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(1);
        Function<Object, Publisher<String>> fun = crs.to("bean:hello", String.class);

        Flowable.just(1, 2, 3).flatMap(fun::apply).doOnNext(res -> Assert.assertEquals("Hello " + value.incrementAndGet(), res)).doOnNext(res -> latch.countDown()).subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    }

    @Test
    public void testToFunctionWithExchange() throws Exception {
        context.start();

        AtomicInteger value = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(1);
        Function<Object, Publisher<Exchange>> fun = crs.to("bean:hello");

        Flowable.just(1, 2, 3).flatMap(fun::apply).map(e -> e.getOut()).map(e -> e.getBody(String.class))
            .doOnNext(res -> Assert.assertEquals("Hello " + value.incrementAndGet(), res)).doOnNext(res -> latch.countDown()).subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    }

    // ************************************************
    // subscriber
    // ************************************************

    @Test
    public void testSubscriber() throws Exception {
        context.start();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:reactor").to("mock:result");
            }
        });

        Flowable.just(1, 2, 3).subscribe(crs.subscriber("direct:reactor", Integer.class));

        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(3);
        mock.assertIsSatisfied();

        int idx = 1;
        for (Exchange ex : mock.getExchanges()) {
            Assert.assertEquals(new Integer(idx++), ex.getIn().getBody(Integer.class));
        }
    }

    // ************************************************
    // misc
    // ************************************************

    @Test(expected = FailedToStartRouteException.class)
    public void testOnlyOneCamelProducerPerPublisher() throws Exception {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:one").to("reactive-streams:stream");
                from("direct:two").to("reactive-streams:stream");
            }
        });

        context.start();
    }
}


text:
<?php

namespace Letunovskiymn\KorablikBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SMSReaderControllerTest extends WebTestCase
{
}


text:
import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({

  currentTarget: computed.reads('originalModel.targetType'),

  hasCurrentTarget: function() {
    const ol = this.get('originalModel');
    if (!ol) {
      return false
    }
    const currentTarget = this.get('currentTarget');
    return  currentTarget && currentTarget !== 'none';
  }.property('currentTarget'),

  currentCss(type) {
    return this.get('hasCurrentTarget') && type === this.get('currentTarget') ? ' current' : '';
  },

  targets: function() {
    return [
      {
        type: 'none',
        label: 'loggingPage.targetTypes.disable',
        css: 'none' +  this.currentCss('none'),
        classNames: '',
        available: true,
        disabled: false,
      },
      {
        type: 'embedded',
        // label: 'loggingPage.targetTypes.embedded',
        css: 'embedded' +  this.currentCss('embedded'),
        classNames: '',
        available: true,
        disabled: false,
      },
      {
        type: 'elasticsearch',
        label: 'loggingPage.targetTypes.elasticsearch',
        css: 'elasticsearch' +  this.currentCss('elasticsearch'),
        available: true,
        disabled: false,
      },
      {
        type: 'splunk',
        label: '',
        css: 'splunk' +  this.currentCss('splunk'),
        available: true,
        disabled: false,
      },
      {
        type: 'kafka',
        label: '',
        css: 'kafka' +  this.currentCss('kafka'),
        available: true,
        disabled: false,
      },
      {
        type: 'syslog',
        label: 'loggingPage.targetTypes.syslog',
        css: 'syslog' +  this.currentCss('syslog'),
        available: true,
        disabled: false,
      },
    ].filter(item => {
      return this.get('isClusterLevel') || item.type !== 'embedded';
    });
  }.property('isClusterLevel', 'currentTarget'),
});


text:
**MyElectronicProjects**

:Date: |today|
:PDF: `MyElectronicProjects.pdf <MyElectronicProjects.pdf>`_

Table of Contents
------------------------

.. toctree::
   :maxdepth: 1
   :numbered:
   :glob:

   readme
   strip
   projects/*/*


text:
.. _find-the-ip-address:

*****************************
Find IP address of your board
*****************************

.. note::
   This section assumes you have connected your board to a network with a
   DHCP server - e.g. your home network where your router is the DHCP server.
   Your board will be assigned a dynamic IP address which means it can change
   over time or if you reset your router or your board. In practice most routers
   Will assign the same IP address to the same device, the IP address may change
   and you will need to follow these steps again to find the new IP address for
   your board.

You can find the IP address in several ways.

Ping
====

The default hostname of a board is `pynq`. Your network may support hostname
resolution. This means that if you try to connect to the hostname of your board,
the hostname will used to lookup the IP address to the board.

From a command prompt or terminal on your host PC run:

.. code-block:: console

   ping pynq

This may automatically resolve the hostname to the IP address, and you can return
to previous section to connect to your board.

Serial terminal
===============

This is a good way to get the IP address of your board and general troubleshooting.
Follow the instructions if you need help :ref:`opening-a-serial-terminal`.

* Connect a USB cable and open a serial terminal to the board
* Run the following to report information about the board's network adapters

.. code-block:: console

   ip a

This will return info similar to the output below:

.. code-block:: console
   :emphasize-lines: 11,21

   1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
      link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
      inet 127.0.0.1/8 scope host lo
         valid_lft forever preferred_lft forever
      inet6 ::1/128 scope host
         valid_lft forever preferred_lft forever
   2: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN group default qlen 1000
      link/ether 1a:ee:e0:5e:27:89 brd ff:ff:ff:ff:ff:ff
   3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
      link/ether 00:05:6b:01:c6:66 brd ff:ff:ff:ff:ff:ff
      inet 192.168.68.136/24 brd 192.168.68.255 scope global dynamic eth0
         valid_lft 7146sec preferred_lft 7146sec
      inet 192.168.2.99/24 brd 192.168.2.255 scope global eth0:1
         valid_lft forever preferred_lft forever
      inet6 fe80::205:6bff:fe01:c666/64 scope link
         valid_lft forever preferred_lft forever
   4: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
      link/sit 0.0.0.0 brd 0.0.0.0
   5: wlan0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
      link/ether d4:7b:b0:08:36:d2 brd ff:ff:ff:ff:ff:ff
      inet 192.168.68.145/24 brd 192.168.68.255 scope global dynamic wlan0
         valid_lft 7025sec preferred_lft 7025sec

Check your router
=================

You can usually find details of all devices on your network, including the IP address
that has been assigned to each device.
Check the manual for your router or look for log-in details on a sticker on your router.

Scan your network
=================

Apps are available for smart phones and PCs that allow them to scan WiFi networks
and identify devices connected to the network. This can be a convenient way to find
the IP address of your board.

Search your App Store for "network scanner" or similar to find a suitable App.
`Fing <https://www.fing.com/>`_ which is available for Windows, Apple and
Android is one example.


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerella muehlenbergiae Ellis

### Remarks
null


text:
/**
 * The type My sq lite open helper.
 *
 * @author JuKyYoon
 */

package pineapple.iq_quest;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    /**
     * Instantiates a new My sq lite open helper.
     * db name and version
     * @param context the context
     * @param name    the name
     * @param factory the factory
     * @param version the version
     */

    public MySQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //make a new datatable
        db.execSQL("CREATE TABLE MONEYBOOK (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age TEXT, iq TEXT);");
    }

    // if version is changed, this method is called
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * Insert.
     * add a data into the datatable
     * @param name the name
     * @param age  the age
     * @param iq   the iq
     */
    public void insert(String name, String age, String iq) {
        SQLiteDatabase db = getWritableDatabase(); //open the database for writing and reading
        db.execSQL("INSERT INTO MONEYBOOK VALUES(null, '" + name + "', " + age + ", '" + iq + "');"); //insert into datatable values
        db.close(); //close the database
    }

    /**
     * Update.
     *
     * @param name the name
     * @param iq   the iq
     */
    public void update(String name, int iq) {
        SQLiteDatabase db = getWritableDatabase();

        db.execSQL("UPDATE MONEYBOOK SET price=" +iq + " WHERE item='" + name + "';");
        db.close();
    }

    /**
     * Delete.
     * delete the specific database
     * @param name the name
     */
    public void delete(String name) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM MONEYBOOK WHERE item='" + name + "';");
        db.close();
    }

    /**
     * Delete all.
     * delete all database
     * @param
     *
     * @return void
     */
    public void deleteAll() {
        SQLiteDatabase db = getWritableDatabase(); //open the database for writing and reading
        db.execSQL("DELETE FROM MONEYBOOK"); //all database is deleted
        db.close(); //close the database
    }

    /**
     * Gets result.
     * all data is printed in the datatable using Cursor
     * @return the result
     */
    public String getResult() {

        SQLiteDatabase db = getReadableDatabase();
        String result = "";

        Cursor cursor = db.rawQuery("SELECT * FROM MONEYBOOK ORDER BY iq desc", null);
        while (cursor.moveToNext()) {
            result += cursor.getString(1)
                    + " | "
                    + cursor.getInt(2)
                    + "살 | IQ = "
                    + cursor.getString(3)
                    + "\n";
        }

        return result;
    }
}


text:
HEX_REGEX = /\A\h{16}\z/

shared_examples 'makes requests without tracing' do
  context 'Tracer is not set' do
    before do
      Trace.tracer = nil
      ::Trace.sample_rate = 1 # make sure initialized
    end
    include_examples 'make requests', false
  end

  context 'We are not sampling this request' do
    before do
      Trace.tracer = Trace::NullSender.new
      ::Trace.sample_rate = 0 # make sure initialized
    end
    include_examples 'make requests', false
  end
end

shared_examples 'makes requests with tracing' do
  around do |example|
    Trace.tracer = Trace::NullSender.new
    ::Trace.sample_rate = 1 # make sure initialized
    ZipkinTracer::TraceContainer.with_trace_id(trace_id) do
      example.run
    end
  end

  before do
    allow(::Trace).to receive(:default_endpoint).and_return(::Trace::Endpoint.new('127.0.0.1', '80', service_name))
    allow(::Trace::Endpoint).to receive(:host_to_i32).with(hostname).and_return(host_ip)
  end

  include_examples 'make requests', true
end

shared_examples 'make requests' do |expect_to_trace_request|
  let(:hostname) { 'service.example.com' }
  let(:host_ip) { 0x11223344 }
  let(:url_path) { '/some/path/here' }
  let(:raw_url) { "https://#{hostname}#{url_path}" }
  let(:tracer) { Trace.tracer }
  let(:trace_id) { ::Trace::TraceId.new(1, 2, 3, true, ::Trace::Flags::DEBUG) }
  let(:write_b3_single_format) { false }
  before { allow(Trace).to receive(:write_b3_single_format).and_return(write_b3_single_format) }

  # helper to check host component of annotation
  def expect_host(host, host_ip, service_name)
    expect(host).to be_a_kind_of(::Trace::Endpoint)
    expect(host.ipv4).to eq(host_ip)
    expect(host.service_name).to eq(service_name)
  end

  def expect_tracing
    expect(tracer).to receive(:start_span).with(anything, 'post').and_call_original
    expect(tracer).to receive(:end_span).with(anything).and_call_original

    expect_any_instance_of(Trace::Span).to receive(:kind=).with('CLIENT')

    expect_any_instance_of(Trace::Span).to receive(:remote_endpoint=) do |_, host|
      expect_host(host, hostname, service_name)
    end

    expect_any_instance_of(Trace::Span).to receive(:record_tag) do |_, key, value|
      expect(key).to eq('http.method')
      expect(value).to eq('POST')
    end

    expect_any_instance_of(Trace::Span).to receive(:record_tag) do |_, key, value|
      expect(key).to eq('http.path')
      expect(value).to eq(url_path)
    end

    expect_any_instance_of(Trace::Span).to receive(:record_tag) do |_, key, value|
      expect(key).to eq('http.status_code')
      expect(value).to eq('404')
    end

    expect_any_instance_of(Trace::Span).to receive(:record_tag) do |_, key, value|
      expect(key).to eq('error')
      expect(value).to eq('404')
    end
  end

  context 'with tracing id' do
    let(:trace_id) { ::Trace::TraceId.new(1, 2, 3, true, ::Trace::Flags::DEBUG) }

    it 'expects tracing' do
      if expect_to_trace_request
        expect_tracing
        process('', url)
      end
    end

    context 'write_b3_single_format is false' do
      it 'sets the X-B3 request headers with a new spanID' do
        request_headers  = nil
        ZipkinTracer::TraceContainer.with_trace_id(trace_id) do
          request_headers = process('', url)
        end

        expect(request_headers['X-B3-TraceId']).to eq('0000000000000001')
        expect(request_headers['X-B3-ParentSpanId']).to eq('0000000000000003')
        expect(request_headers['X-B3-SpanId']).not_to eq('0000000000000002')
        expect(request_headers['X-B3-SpanId']).to match(HEX_REGEX)
        expect(request_headers['X-B3-Sampled']).to eq('true')
        expect(request_headers['X-B3-Flags']).to eq('1')
      end
    end

    context 'write_b3_single_format is true' do
      let(:write_b3_single_format) { true }

      it 'sets the B3 single request header with a new spanID' do
        request_headers  = nil
        ZipkinTracer::TraceContainer.with_trace_id(trace_id) do
          request_headers = process('', url)
        end

        expect(request_headers['b3']).to match(/\A0000000000000001-\h{16}-d-0000000000000003\z/)
      end
    end

    it 'the original spanID is restored after the calling the middleware' do
      old_trace_id = ZipkinTracer::TraceContainer.current
      ZipkinTracer::TraceContainer.with_trace_id(old_trace_id) do
        process('', url)
      end
      expect(ZipkinTracer::TraceContainer.current).to eq(old_trace_id)
    end
  end

  context 'without tracing id' do
    it 'expects tracing' do
      if expect_to_trace_request
        expect_tracing
        process('', url)
      end
    end

    context 'write_b3_single_format is false' do
      it 'generates a new ID, and sets the X-B3 request headers' do
        request_headers = process('', url)

        expect(request_headers['X-B3-TraceId']).to match(HEX_REGEX)
        expect(request_headers['X-B3-ParentSpanId']).to match(HEX_REGEX)
        expect(request_headers['X-B3-SpanId']).to match(HEX_REGEX)
        expect(request_headers['X-B3-Sampled']).to match(/(true|false)/)
        expect(request_headers['X-B3-Flags']).to match(/(1|0)/)
      end
    end

    context 'write_b3_single_format is true' do
      let(:write_b3_single_format) { true }

      it 'generates a new ID, and sets the B3 single request header' do
        request_headers = process('', url)

        expect(request_headers['b3']).to match(/\A\h{16}-\h{16}-[01d]-\h{16}\z/)
      end
    end
  end

  context 'Trace has not been sampled' do
    let(:trace_id) { ::Trace::TraceId.new(1, 2, 3, false, 0) }

    context 'write_b3_single_format is false' do
      it 'sets the X-B3 request headers with a new spanID' do
        request_headers = nil
        ZipkinTracer::TraceContainer.with_trace_id(trace_id) do
          request_headers = process('', url)
        end

        expect(request_headers['X-B3-TraceId']).to eq('0000000000000001')
        expect(request_headers['X-B3-ParentSpanId']).to eq('0000000000000003')
        expect(request_headers['X-B3-SpanId']).not_to eq('0000000000000003')
        expect(request_headers['X-B3-SpanId']).to match(HEX_REGEX)
        expect(request_headers['X-B3-Sampled']).to eq('false')
        expect(request_headers['X-B3-Flags']).to eq('0')
      end
    end

    context 'write_b3_single_format is true' do
      let(:write_b3_single_format) { true }

      it 'sets the B3 single request header with a new spanID' do
        request_headers = nil
        ZipkinTracer::TraceContainer.with_trace_id(trace_id) do
          request_headers = process('', url)
        end

        expect(request_headers['b3']).to match(/\A0000000000000001-\h{16}-0-0000000000000003\z/)
      end
    end

    it 'the original spanID is restored after the calling the middleware' do
      old_trace_id = ZipkinTracer::TraceContainer.current
      ZipkinTracer::TraceContainer.with_trace_id(old_trace_id) do
        process('', url)
      end
      expect(ZipkinTracer::TraceContainer.current).to eq(old_trace_id)
    end

    it 'does not trace the request' do
      expect(tracer).not_to receive(:set_rpc_name)
      expect(tracer).not_to receive(:record)
      process('', url)
    end

    it 'does not create any annotation' do
      expect(Trace::Annotation).not_to receive(:new)
      process('', url)
    end
  end

  context 'when looking up hostname raises' do
    let(:host_ip) { 0x7f000001 } # expect stubbed 'null' IP

    before do
      allow(::Trace::Endpoint).to receive(:host_to_i32).with(hostname).and_raise(SocketError)
    end

    it 'expects tracing' do
      if expect_to_trace_request
        expect_tracing
        process('', url)
      end
    end
  end
end


text:
<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Form;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Acme\DemoBundle\Entity\Post;
use Acme\DemoBundle\Form\PostType;

use FOS\RestBundle\View\View as FOSView;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\Util\Codes;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Controller\Annotations\View;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Voryx\RESTGeneratorBundle\Controller\VoryxController;

//MANUAL_EXAMPLE SEE http://voryx.net/rest-apis-with-symfony2-the-easy-way/

/**
 * Post controller.
 * @RouteResource("Post")
 */
class PostRESTController extends VoryxController
{
    /**
     * Get a Post entity
     *
     * @View(serializerEnableMaxDepthChecks=true)
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *
     */
    public function getAction(Post $entity)
    {
        return $entity;
    }

    /**
     * Get all Post entities.
     *
     * @View(serializerEnableMaxDepthChecks=true)
     *
     * @param \FOS\RestBundle\Request\ParamFetcherInterface $paramFetcher
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing notes.")
     * @QueryParam(name="limit", requirements="\d+", default="20", description="How many notes to return.")
     * @QueryParam(name="order_by", nullable=true, array=true, description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC")
     * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3")
     *
     */
    public function cgetAction(ParamFetcherInterface $paramFetcher)
    {
        try {
            $offset = $paramFetcher->get('offset');
            $limit = $paramFetcher->get('limit');
            $order_by = $paramFetcher->get('order_by');
            $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array();

            $em = $this->getDoctrine()->getManager();
            $entities = $em->getRepository('AcmeDemoBundle:Post')->findBy($filters, $order_by, $limit, $offset);
            if ($entities) {
                return $entities;
            } else {
                return FOSView::create('Not Found', Codes::HTTP_NO_CONTENT);
            }
        } catch (\Exception $e) {
            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Create a Post entity.
     *
     * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     *
     */
    public function postAction(Request $request)
    {

        $entity = new Post();
        $form = $this->createForm(new PostType(), $entity, array("method" => $request->getMethod()));
        $this->removeExtraFields($request, $form);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $entity;
        }

        return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
    }

    /**
     * Update a Post entity.
     *
     * @View(serializerEnableMaxDepthChecks=true)
     *
     * @param Request $request
     * @param $entity
     * @return \Symfony\Component\HttpFoundation\Response
     *
     *
     */
    public function putAction(Request $request, Post $entity)
    {

        try {
            $em = $this->getDoctrine()->getManager();
            $request->setMethod('PATCH'); //Treat all PUTs as PATCH
            $form = $this->createForm(new PostType(), $entity, array("method" => $request->getMethod()));
            $this->removeExtraFields($request, $form);
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em->flush();

                return $entity;
            }

            return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
        } catch (\Exception $e) {
            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
        }

    }

/**
    * Partial Update to a Post entity.
    *
    * @View(serializerEnableMaxDepthChecks=true)
    *
    * @param Request $request
    * @param $entity
    * @return \Symfony\Component\HttpFoundation\Response
    *
*
    */
    public function patchAction(Request $request, Post $entity)
    {

        return $this->putAction($request, $entity);

    }

    /**
     * Delete a Post entity.
     *
     * @View(statusCode=204)
     *
     * @param Request $request
     * @param $entity
     * @internal param $id
     * @return \Symfony\Component\HttpFoundation\Response
     *
     */
    public function deleteAction(Request $request, Post $entity)
    {

        try {
            $em = $this->getDoctrine()->getManager();
            $em->merge($entity);
            $em->remove($entity);
            $em->flush();

            return null;
        } catch (\Exception $e) {
            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
        }

    }

}


text: Gists on data science, analytics, AI go here


text: Licensed under the BSD 3-Clause license, the full text of which can be read in [LICENSE](LICENSE).


text:
namespace Lenoard.Security.SqlServer
{
    public class SqlServerPermissionStore : IPermissionStore
    {
        public PermissionNodeCollection RootNodes { get; }
    }
}


text:
package io.fabric8.docker.provider;

import io.fabric8.api.AutoScaleRequest;
import io.fabric8.api.Container;
import io.fabric8.api.ContainerAutoScaler;
import io.fabric8.api.Containers;
import io.fabric8.api.DockerHostConfiguration;
import io.fabric8.api.DockerScalingRequirements;
import io.fabric8.api.FabricRequirements;
import io.fabric8.api.FabricService;
import io.fabric8.api.HostConfiguration;
import io.fabric8.api.NameValidator;
import io.fabric8.api.ProfileRequirements;
import io.fabric8.api.SshHostConfiguration;
import io.fabric8.internal.autoscale.AutoScalers;
import io.fabric8.internal.autoscale.HostProfileCounter;
import io.fabric8.internal.autoscale.LoadSortedHostConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.SortedSet;

import static io.fabric8.internal.autoscale.AutoScalers.filterHosts;

/**
 */
public class DockerAutoScaler implements ContainerAutoScaler {
    private static final transient Logger LOG = LoggerFactory.getLogger(DockerAutoScaler.class);

    private final DockerContainerProvider containerProvider;

    public DockerAutoScaler(DockerContainerProvider containerProvider) {
        this.containerProvider = containerProvider;
    }

    @Override
    public int getWeight() {
        return 80;
    }

    @Override
    public void createContainers(AutoScaleRequest request) throws Exception {
        int count = request.getDelta();
        String profile = request.getProfile();
        String version = request.getVersion();
        FabricService fabricService = request.getFabricService();
        if (fabricService != null) {

            Container[] containers = fabricService.getContainers();
            FabricRequirements requirements = request.getFabricRequirements();
            List<? extends HostConfiguration> hostConfigurations = requirements.getDockerHosts();
            HostProfileCounter hostProfileCounter = new HostProfileCounter();
            AutoScalers.createHostToProfileScaleMap(hostProfileCounter, hostConfigurations, containers);

            // TODO this is actually generic to all providers! :)
            for (int i = 0; i < count; i++) {
                CreateDockerContainerOptions.Builder builder = createAutoScaleOptions(request, fabricService, hostProfileCounter);
                if (builder == null) {
                    return;
                }

                NameValidator nameValidator = Containers.createNameValidator(fabricService.getContainers());
                String name = Containers.createContainerName(containers, profile, containerProvider.getScheme(), nameValidator);

                CreateDockerContainerOptions options = builder.name(name).build();
                LOG.info("Creating container name " + name + " version " + version + " profile " + profile + " " + count + " container(s)");
                fabricService.createContainers(options);
            }
        } else {
            LOG.warn("Could not create version " + version + " profile " + profile + " due to missing FabricService");
        }
    }

    protected CreateDockerContainerOptions.Builder createAutoScaleOptions(AutoScaleRequest request, FabricService fabricService, HostProfileCounter hostProfileCounter) {
        String profile = request.getProfile();
        String version = request.getVersion();
        CreateDockerContainerOptions.Builder builder = chooseHostOptions(request, hostProfileCounter);
        if (builder == null) {
            return null;
        }
        String zookeeperUrl = fabricService.getZookeeperUrl();
        String zookeeperPassword = fabricService.getZookeeperPassword();
        return builder.number(1).version(version).profiles(profile).zookeeperUrl(zookeeperUrl).zookeeperPassword(zookeeperPassword);
    }

    /**
     * This method is public for easier testing
     */
    public static CreateDockerContainerOptions.Builder chooseHostOptions(AutoScaleRequest request, HostProfileCounter hostProfileCounter) {
        CreateDockerContainerOptions.Builder builder = CreateDockerContainerOptions.builder();
        FabricRequirements requirements = request.getFabricRequirements();
        ProfileRequirements profileRequirements = request.getProfileRequirements();
        DockerScalingRequirements scalingRequirements = profileRequirements.getDockerScalingRequirements();
        List<DockerHostConfiguration> hosts = requirements.getDockerHosts();
        if (hosts.isEmpty()) {
            // lets default to use the current docker container provider as there are no others configured
            return builder;
        }
        SortedSet<LoadSortedHostConfiguration<DockerHostConfiguration>> sortedHostConfigurations = filterHosts(profileRequirements, scalingRequirements, hostProfileCounter, hosts);
        DockerHostConfiguration hostConfig = null;
        if (!sortedHostConfigurations.isEmpty()) {
            LoadSortedHostConfiguration<DockerHostConfiguration> first = sortedHostConfigurations.first();
            hostConfig = first.getConfiguration();
        }
        if (hostConfig == null) {
            LOG.warn("Could not create version " + request.getVersion() + " profile " + request.getProfile() + " as no matching hosts could be found for " + scalingRequirements);
            request.getProfileAutoScaleStatus().noSuitableHost("" + scalingRequirements);
            return null;
        }
        return builder;
    }

    @Override
    public void destroyContainers(String profile, int count, List<Container> containers) {
        // TODO

    }
}


text:
namespace Rcpp{
namespace sugar{

	template <int RTYPE, bool LHS_NA, typename LHS_T, bool RHS_NA, typename RHS_T >
	class Minus_Vector_Vector :
	    public Rcpp::VectorBase<RTYPE,true, Minus_Vector_Vector<RTYPE,LHS_NA,LHS_T,RHS_NA,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<RTYPE,LHS_NA,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<RTYPE,RHS_NA,RHS_T> RHS_TYPE ;
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::traits::Extractor< RTYPE, LHS_NA, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor< RTYPE, RHS_NA, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			STORAGE x = lhs[i] ;
			if( Rcpp::traits::is_na<RTYPE>( x ) ) return x ;
			STORAGE y = rhs[i] ;
			return Rcpp::traits::is_na<RTYPE>( y ) ? y : ( x - y ) ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;
	// RTYPE = REALSXP
	template <bool LHS_NA, typename LHS_T, bool RHS_NA, typename RHS_T >
	class Minus_Vector_Vector<REALSXP,LHS_NA,LHS_T,RHS_NA,RHS_T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Vector_Vector<REALSXP,LHS_NA,LHS_T,RHS_NA,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,LHS_NA,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<REALSXP,RHS_NA,RHS_T> RHS_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP, LHS_NA, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<REALSXP, RHS_NA, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline double operator[]( R_xlen_t i ) const {
		    return lhs[i] - rhs[i] ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;

	template <int RTYPE, typename LHS_T, bool RHS_NA, typename RHS_T >
	class Minus_Vector_Vector<RTYPE,false,LHS_T,RHS_NA,RHS_T> : public Rcpp::VectorBase<RTYPE,true, Minus_Vector_Vector<RTYPE,false,LHS_T,RHS_NA,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<RTYPE,false,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<RTYPE,RHS_NA,RHS_T> RHS_TYPE ;
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::traits::Extractor<RTYPE, false, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<RTYPE, RHS_NA, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			STORAGE y = rhs[i] ;
			if( Rcpp::traits::is_na<RTYPE>( y ) ) return y ;
			return lhs[i] - y ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;
	// RTYPE = REALSXP
	template <typename LHS_T, bool RHS_NA, typename RHS_T >
	class Minus_Vector_Vector<REALSXP,false,LHS_T,RHS_NA,RHS_T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Vector_Vector<REALSXP,false,LHS_T,RHS_NA,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,false,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<REALSXP,RHS_NA,RHS_T> RHS_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP, false, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<REALSXP, RHS_NA, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline double operator[]( R_xlen_t i ) const {
			return lhs[i] - rhs[i] ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;

	template <int RTYPE, bool LHS_NA, typename LHS_T, typename RHS_T >
	class Minus_Vector_Vector<RTYPE,LHS_NA,LHS_T,false,RHS_T> : public Rcpp::VectorBase<RTYPE,true, Minus_Vector_Vector<RTYPE,LHS_NA,LHS_T,false,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<RTYPE,LHS_NA,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<RTYPE,false,RHS_T> RHS_TYPE ;
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::traits::Extractor<RTYPE, LHS_NA, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<RTYPE, false, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			STORAGE x = lhs[i] ;
			if( Rcpp::traits::is_na<RTYPE>( x ) ) return x ;
			return x - rhs[i] ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;
	// RTYPE = REALSXP
	template <bool LHS_NA, typename LHS_T, typename RHS_T >
	class Minus_Vector_Vector<REALSXP,LHS_NA,LHS_T,false,RHS_T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Vector_Vector<REALSXP,LHS_NA,LHS_T,false,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,LHS_NA,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<REALSXP,false,RHS_T> RHS_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP, LHS_NA, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<REALSXP, false, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline double operator[]( R_xlen_t i ) const {
			return lhs[i] - rhs[i] ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;

	template <int RTYPE, typename LHS_T, typename RHS_T >
	class Minus_Vector_Vector<RTYPE,false,LHS_T,false,RHS_T> :
	    public Rcpp::VectorBase<RTYPE,false, Minus_Vector_Vector<RTYPE,false,LHS_T,false,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<RTYPE,false,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<RTYPE,false,RHS_T> RHS_TYPE ;
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::traits::Extractor<RTYPE, false, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<RTYPE, false, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			return lhs[i] - rhs[i] ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;
	template <typename LHS_T, typename RHS_T >
	class Minus_Vector_Vector<REALSXP,false,LHS_T,false,RHS_T> :
	    public Rcpp::VectorBase<REALSXP,false, Minus_Vector_Vector<REALSXP,false,LHS_T,false,RHS_T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,false,LHS_T> LHS_TYPE ;
		typedef typename Rcpp::VectorBase<REALSXP,false,RHS_T> RHS_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP, false, LHS_T>::type LHS_EXT ;
		typedef typename Rcpp::traits::Extractor<REALSXP, false, RHS_T>::type RHS_EXT ;

		Minus_Vector_Vector( const LHS_TYPE& lhs_, const RHS_TYPE& rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_.get_ref()) {}

		inline double operator[]( R_xlen_t i ) const {
			return lhs[i] - rhs[i] ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const LHS_EXT& lhs ;
		const RHS_EXT& rhs ;
	} ;

	template <int RTYPE, bool NA, typename T>
	class Minus_Vector_Primitive :
	    public Rcpp::VectorBase<RTYPE,true, Minus_Vector_Primitive<RTYPE,NA,T> > {
	public:
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::VectorBase<RTYPE,NA,T> VEC_TYPE ;
		typedef typename Rcpp::traits::Extractor<RTYPE,NA,T>::type VEC_EXT ;

		Minus_Vector_Primitive( const VEC_TYPE& lhs_, STORAGE rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_), rhs_na( Rcpp::traits::is_na<RTYPE>(rhs_) ) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			if( rhs_na ) return rhs ;
			STORAGE x = lhs[i] ;
			return Rcpp::traits::is_na<RTYPE>(x) ? x : (x - rhs) ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const VEC_EXT& lhs ;
		STORAGE rhs ;
		bool rhs_na ;
	} ;
	template <bool NA, typename T>
	class Minus_Vector_Primitive<REALSXP,NA,T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Vector_Primitive<REALSXP,NA,T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,NA,T> VEC_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP,NA,T>::type VEC_EXT ;

		Minus_Vector_Primitive( const VEC_TYPE& lhs_, double rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_){}

		inline double operator[]( R_xlen_t i ) const {
			return lhs[i] - rhs ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const VEC_EXT& lhs ;
		double rhs ;
	} ;

	template <int RTYPE, typename T>
	class Minus_Vector_Primitive<RTYPE,false,T> :
	    public Rcpp::VectorBase<RTYPE,true, Minus_Vector_Primitive<RTYPE,false,T> > {
	public:
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::VectorBase<RTYPE,false,T> VEC_TYPE ;
		typedef typename Rcpp::traits::Extractor<RTYPE,false,T>::type VEC_EXT ;

		Minus_Vector_Primitive( const VEC_TYPE& lhs_, STORAGE rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_), rhs_na( Rcpp::traits::is_na<RTYPE>(rhs_) ) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			if( rhs_na ) return rhs ;
			STORAGE x = lhs[i] ;
			return Rcpp::traits::is_na<RTYPE>(x) ? x : (x - rhs) ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const VEC_EXT& lhs ;
		STORAGE rhs ;
		bool rhs_na ;
	} ;
	template <typename T>
	class Minus_Vector_Primitive<REALSXP,false,T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Vector_Primitive<REALSXP,false,T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,false,T> VEC_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP,false,T>::type VEC_EXT ;

		Minus_Vector_Primitive( const VEC_TYPE& lhs_, double rhs_ ) :
			lhs(lhs_.get_ref()), rhs(rhs_){}

		inline double operator[]( R_xlen_t i ) const {
			return lhs[i] - rhs ;
		}

		inline R_xlen_t size() const { return lhs.size() ; }

	private:
		const VEC_EXT& lhs ;
		double rhs ;
	} ;

	template <int RTYPE, bool NA, typename T>
	class Minus_Primitive_Vector :
	    public Rcpp::VectorBase<RTYPE,true, Minus_Primitive_Vector<RTYPE,NA,T> > {
	public:
		typedef typename Rcpp::VectorBase<RTYPE,NA,T> VEC_TYPE ;
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::traits::Extractor<RTYPE,NA,T>::type VEC_EXT ;

		Minus_Primitive_Vector( STORAGE lhs_, const VEC_TYPE& rhs_ ) :
			lhs(lhs_), rhs(rhs_.get_ref()), lhs_na( Rcpp::traits::is_na<RTYPE>(lhs_) ) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			if( lhs_na ) return lhs ;
			return lhs - rhs[i] ;
		}
		inline R_xlen_t size() const { return rhs.size() ; }

	private:
		STORAGE lhs ;
		const VEC_EXT& rhs ;
		bool lhs_na ;
	} ;
	template <bool NA, typename T>
	class Minus_Primitive_Vector<REALSXP,NA,T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Primitive_Vector<REALSXP,NA,T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,NA,T> VEC_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP,NA,T>::type VEC_EXT ;

		Minus_Primitive_Vector( double lhs_, const VEC_TYPE& rhs_ ) :
			lhs(lhs_), rhs(rhs_.get_ref()){}

		inline double operator[]( R_xlen_t i ) const {
			return lhs - rhs[i] ;
		}
		inline R_xlen_t size() const { return rhs.size() ; }

	private:
		double lhs ;
		const VEC_EXT& rhs ;
	} ;

	template <int RTYPE, typename T>
	class Minus_Primitive_Vector<RTYPE,false,T> :
	    public Rcpp::VectorBase<RTYPE,true, Minus_Primitive_Vector<RTYPE,false,T> > {
	public:
		typedef typename Rcpp::VectorBase<RTYPE,false,T> VEC_TYPE ;
		typedef typename traits::storage_type<RTYPE>::type STORAGE ;
		typedef typename Rcpp::traits::Extractor<REALSXP,false,T>::type VEC_EXT ;

		Minus_Primitive_Vector( STORAGE lhs_, const VEC_TYPE& rhs_ ) :
			lhs(lhs_), rhs(rhs_.get_ref()), lhs_na( Rcpp::traits::is_na<RTYPE>(lhs_) ) {}

		inline STORAGE operator[]( R_xlen_t i ) const {
			if( lhs_na ) return lhs ;
		    return lhs - rhs[i] ;
		}

		inline R_xlen_t size() const { return rhs.size() ; }

	private:
		STORAGE lhs ;
		const VEC_EXT& rhs ;
		bool lhs_na ;

	} ;
	template <typename T>
	class Minus_Primitive_Vector<REALSXP,false,T> :
	    public Rcpp::VectorBase<REALSXP,true, Minus_Primitive_Vector<REALSXP,false,T> > {
	public:
		typedef typename Rcpp::VectorBase<REALSXP,false,T> VEC_TYPE ;
		typedef typename Rcpp::traits::Extractor<REALSXP,false,T>::type VEC_EXT ;

		Minus_Primitive_Vector( double lhs_, const VEC_TYPE& rhs_ ) :
			lhs(lhs_), rhs(rhs_.get_ref()){}

		inline double operator[]( R_xlen_t i ) const {
			return lhs - rhs[i] ;
		}

		inline R_xlen_t size() const { return rhs.size() ; }

	private:
		double lhs ;
		const VEC_EXT& rhs ;
	} ;

}

template <int RTYPE,bool NA, typename T, typename U>
inline typename traits::enable_if<traits::is_convertible<typename traits::remove_const_and_reference<U>::type, typename traits::storage_type<RTYPE>::type>::value, sugar::Minus_Vector_Primitive< RTYPE , NA, T > >::type
operator-(
	const VectorBase<RTYPE,NA,T>& lhs,
	const U &rhs
) {
	return sugar::Minus_Vector_Primitive<RTYPE,NA,T>( lhs, rhs ) ;
}

template <int RTYPE,bool NA, typename T, typename U>
inline typename traits::enable_if<traits::is_convertible<typename traits::remove_const_and_reference<U>::type, typename traits::storage_type<RTYPE>::type>::value, sugar::Minus_Primitive_Vector< RTYPE , NA,T> >::type
operator-(
	const U &lhs,
	const VectorBase<RTYPE,NA,T>& rhs
) {
	return sugar::Minus_Primitive_Vector<RTYPE,NA,T>( lhs, rhs ) ;
}

template <int RTYPE,bool LHS_NA, typename LHS_T, bool RHS_NA, typename RHS_T>
inline sugar::Minus_Vector_Vector<
	RTYPE ,
	LHS_NA, LHS_T,
	RHS_NA, RHS_T
	>
operator-(
	const VectorBase<RTYPE,LHS_NA,LHS_T>& lhs,
	const VectorBase<RTYPE,RHS_NA,RHS_T>& rhs
) {
	return sugar::Minus_Vector_Vector<
		RTYPE,
		LHS_NA,LHS_T,
		RHS_NA,RHS_T
		>( lhs, rhs ) ;
}

}

#endif


text:
<?php

namespace nterms\listjs;

use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\base\InvalidConfigException;
use yii\base\Widget;

class ListJs extends Widget
{
	/**
	 * @var array the HTML attributes (name-value pairs) for the container tag.
	 * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
	 */
	public $options = [];

	/**
	 * @var array list.js options. Read [this](http://www.listjs.com/docs/options) for list of options.
	 */
	public $clientOptions = [];

	/**
	 * @var string HTML content, preferably a list or table.
	 * If the widget is used in content capturing mode this will be ignored.
	 */
	public $content = '';

	/**
	 * @var string name of the view file to render the content.
	 * If the widget is used in content capturing mode or a string is assigned to [[content]] property this will be ignored.
	 */
	public $view;

	/**
	 * @var boolean whether to show the search field
	 */
	public $search;

	/**
	 * @var array HTML attributes (name-value pairs) for the search input tag.
	 */
	public $searchOptions = [];

	/**
	 * @var array list of name-value pairs for rendering the sorting buttons list.
	 * Value being the HTML attributes for the button. Special parameter `label` is used
	 * as the button text
	 * ```
	 * ...
	 * 'sort' => [
	 *     'name' => [
	 *         'class' => 'sort',
	 *         'label' => Yii::t('app', 'Sort by name'),
	 *     ],
	 * ],
	 * ...
	 * ```
	 */
	public $sort = [];

	/**
	 * @var string name of the view file to render the content.
	 * If the widget is used in content capturing mode or a string is assigned to [[content]] property this will be ignored.
	 */
	public $layout = "{search}\n{sort}\n{content}";

	/**
	 * @var array parameters to be passed to [[view]] when it is being rendered.
	 * This property is used only when [[view]] is rendered to generate the content of the widget.
	 */
	public $viewParams = [];

	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		parent::init();

		if(!isset($this->options['id'])) {
            $this->options['id'] = $this->getId();
        }

		if(!isset($this->clientOptions['id'])) {
            $this->clientOptions['id'] = $this->options['id'];
        }

		if(empty($this->clientOptions['valueNames'])) {
			throw new InvalidConfigException('The "valueNames" property of "clientOptions" should be set.');
		}

		ob_start();
	}

	/**
	 * Runs the widget.
	 */
	public function run()
	{
		$content = ob_get_clean();
		$search = '';
		$sort = [];

		$view = $this->getView();

		ListJsAsset::register($view);

		$js = "var yii2lj" . ucfirst(strtolower(str_replace('-', '', $this->clientOptions['id']))) . " = new List('" . $this->clientOptions['id'] . "', " . json_encode($this->clientOptions) . ");";
		$view->registerJs($js, $view::POS_READY);

		if(empty($content)) {
			if(empty($this->content)) {
				$content = $this->content;
			} elseif($this->view != null && is_string($this->view)) {
				$content = $view->render($this->view, $this->viewParams);
			}
		}

		if($this->search) {
			$search = Html::tag('input', '', array_merge([
				'class' => 'form-control search',
				'placeholder' => 'Search',
			], $this->searchOptions));
		}

		if(!empty($this->sort)) {
			foreach($this->sort as $key => $field) {
				if(is_string($field) && in_array($field, $this->clientOptions['valueNames'])) {
					$sort[] = Html::button($field, ['class' => 'btn btn-default sort', 'data-sort' => $field]);
				} elseif(is_array($field) && in_array($key, $this->clientOptions['valueNames'])) {
					$label = isset($field['label']) ? $field['label'] : $key;
					$sort[] = Html::button($label, array_merge([
						'class' => 'btn btn-default sort',
						'data-sort' => $key,
					], $field));
				}
			}
		}

		$html = str_replace(['{search}', '{sort}', '{content}'], [$search, implode(' ', $sort), $content], $this->layout);

		echo Html::tag('div', $html, $this->options);
	}
}


text:
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import merge from 'webpack-merge';
import baseConfig from './webpack.config.base';

const config = merge(baseConfig, {
  devtool: 'cheap-module-source-map',

  entry: [
    'babel-polyfill',
    './app/index'
  ],

  output: {
    publicPath: '../dist/'
  },

  module: {
    rules: [
      // Extract all .global.css to style.css as is
      {
        test: /\.global\.css$/,
        loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader'})
      },

      // Pipe other styles through css modules and apend to style.css
      {
        test: /^((?!\.global).)*\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
        })
      }
    ]
  },

  plugins: [
    // https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
    // https://github.com/webpack/webpack/issues/864
    new webpack.optimize.OccurrenceOrderPlugin(),

    // NODE_ENV should be production so that modules do not perform certain development checks
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),

    // Minify without warning messages and IE8 support
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        screw_ie8: true,
        warnings: false
      }
    }),

    // Set the ExtractTextPlugin output filename
    new ExtractTextPlugin({filename: 'style.css', allChunks: true})
  ],

  // https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works
  target: 'electron-renderer'
});

export default config;


text:
using AnnuaireCertifies.Domaine;
using System.Linq;
using System.Collections.Generic;
using AnnuaireCertifies.Domaine.Results;

namespace AnnuaireCertifies.Business.Depots
{
    public partial interface IDepotArticleAvis : IDepot<ArticleAvis>
    {
        IEnumerable<AvisResult> GetDerniersAvis(bool isFromApi = false);

        IEnumerable<AvisResult> GetVosAvis(long personneId);

        IEnumerable<dynamic> Search(long? statutApprobationID, string email, long langueID, string libelle, bool uniquementAvecPreuveAchat);

        ArticleAvisDto GetArticleAvis(long utilisateurID, long articleAvisID);

        ArticleAvis SaveInfosGenerales(ArticleAvisDto model, long utilisateurID);

        bool CheckPermission(long personneID, long articleAvisID, int mode);

        IEnumerable<AvisResult> GetAvis(long articleID);

        bool RemoveAvis(long idAvis, long personneID);

        IEnumerable<DbErrorMsg> ArchiveByInternaute(long utilisateurID, long articleAvisID);
        IEnumerable<DbErrorMsg> ArchiveByArticle(long utilisateurID, long articleAvisID);
    }
}


text:
package org.ppwcode.vernacular.persistence_III;

import static org.ppwcode.metainfo_I.License.Type.APACHE_V2;

import org.ppwcode.metainfo_I.Copyright;
import org.ppwcode.metainfo_I.License;
import org.ppwcode.metainfo_I.vcs.SvnInfo;
import org.toryt.annotations_I.Basic;
import org.toryt.annotations_I.Expression;
import org.toryt.annotations_I.Invars;
import org.toryt.annotations_I.MethodContract;

/**
 *
This exception signals a versioning conflict: we tried to change data in persistent
 *   storage for {@link #getPersistentBean()}, but the data in persistent storage has
 *   changed already, since the last time we looked. We will not overwrite this more
 *   recent data without user interaction.

 *
 * @author    Jan Dockx
 * @author    PeopleWare n.v.
 */
@Copyright("2004 - $Date$, PeopleWare n.v.")
@License(APACHE_V2)
@SvnInfo(revision = "$Revision$",
         date     = "$Date$")
public class AlreadyChangedException extends PersistenceException {

  /*<construction>*/
  //------------------------------------------------------------------

  @MethodContract(
    pre = {
      @Expression("persistentBean != null")
    },
    post = {
      @Expression("persistentBean == _persistentBeanType"),
      @Expression("message == _message"),
      @Expression("cause == _cause")
    }
  )
  public AlreadyChangedException(PersistentBean<?> persistentBean, String message, Throwable cause) {
    super(message, cause);
    assert persistentBean != null;
    $persistentBean = persistentBean;
  }

  /*</construction;>*/

  /*<property name="persistentBean">*/
  //------------------------------------------------------------------

  @Basic(invars = @Expression("persistentBean != null"))
  public final PersistentBean<?> getPersistentBean() {
    return $persistentBean;
  }

  @Invars(@Expression("$persistentBean != null"))
  private final PersistentBean<?> $persistentBean;

  /*</property>*/

}


text:
import config from '../../../config'

import {
  getProviderName,
  getMaterialGroupLookupTable,
  getMaterialLookupTable,
  getFinishGroupLookupTable,
  getMaterialConfigLookupTable
} from './material'

describe('getMaterialGroupLookupTable()', () => {
  it('returns map of material groups', () => {
    const materialGroups = [
      {
        id: 'material-group-1'
      },
      {
        id: 'material-group-2'
      }
    ]

    expect(getMaterialGroupLookupTable(materialGroups), 'to equal', {
      'material-group-1': {id: 'material-group-1'},
      'material-group-2': {id: 'material-group-2'}
    })
  })
})

describe('getMaterialLookupTable()', () => {
  it('returns map of materials', () => {
    const materialGroups = [
      {
        materials: [
          {
            id: 'material-1'
          },
          {
            id: 'material-2'
          }
        ]
      }
    ]

    expect(getMaterialLookupTable(materialGroups), 'to equal', {
      'material-1': {id: 'material-1'},
      'material-2': {id: 'material-2'}
    })
  })
})

describe('getFinishGroupLookupTable()', () => {
  it('returns map of finish groups', () => {
    const materialGroups = [
      {
        materials: [
          {
            finishGroups: [
              {
                id: 'finish-group-1'
              },
              {
                id: 'finish-group-2'
              }
            ]
          }
        ]
      }
    ]

    expect(getFinishGroupLookupTable(materialGroups), 'to equal', {
      'finish-group-1': {id: 'finish-group-1'},
      'finish-group-2': {id: 'finish-group-2'}
    })
  })
})

describe('getMaterialConfigLookupTable()', () => {
  it('returns map of material configs', () => {
    const materialGroups = [
      {
        materials: [
          {
            finishGroups: [
              {
                materialConfigs: [
                  {
                    id: 'material-config-1'
                  },
                  {
                    id: 'material-config-2'
                  }
                ]
              }
            ]
          }
        ]
      }
    ]

    expect(getMaterialConfigLookupTable(materialGroups), 'to equal', {
      'material-config-1': {id: 'material-config-1'},
      'material-config-2': {id: 'material-config-2'}
    })
  })
})

describe('getProviderName()', () => {
  let sandbox

  beforeEach(() => {
    sandbox = sinon.sandbox.create()
    sandbox
      .stub(config, 'providers')
      .value([{vendorId: 'some-vendor-id', name: 'some-vendor-name'}])
  })

  afterEach(() => {
    sandbox.restore()
  })

  it('returns the provider name from the config', () => {
    expect(getProviderName('some-vendor-id'), 'to equal', 'some-vendor-name')
  })

  it('returns the vendor id if not found in the config', () => {
    expect(getProviderName('some-unknown-vendor-id'), 'to equal', 'some-unknown-vendor-id')
  })
})