text:
using UnityEngine;
using System.Collections;

public class Level : MonoBehaviour {
    public int levelNumber = 0;
    public int levelWidth = 5;
    public int levelHeight = 5;
    public int levelFill = 1;

    public int tileWidth = 128;
    public int tileHeight = 128;

    public GameObject tileSprite;
    public GameObject transparentSprite;
    public GameObject boat;
    public GameObject player;
    public GameObject rubberDuck;
    public GameObject background;
    public GameObject octopus;
    public int maxDucks = 4;
    public int maxOctopus = 1;
	public Texture winScreen;

    private int currentDucks = 0;
    private int currentOctopus = 0;
    private int[,] levelTiles;
    private GameObject[,] tiles;
    private const int EMPTY_TILE = 0;
    private const int FILLED_TILE = 1;
    private const int TRANSPARENT_TILE = 2;
	private int winCondition;
	private float winScreenTimer = 5f;
	private bool youWin;

    void Start() {
		winCondition = Random.Range(30, 51);
        transform.position = new Vector3(-(levelWidth/2.0f), -(float)2*levelHeight, 0f);
        // Setup background, level, boat and player spawn points
            SpawnBackground();
            SpawnLevel();
            SpawnBoat();
            SpawnPlayer ();

            // Setup event listener to level up
            Messenger.AddListener("level up", LevelUp);
            Messenger.AddListener("respawn player", MovePlayer);
    }

	void LevelUp() {
		Debug.Log(player.GetComponent<PlayerControl>().getProgress() );
		if(player.GetComponent<PlayerControl>().getProgress() >= winCondition){
			youWin = true;
		} else {
			levelNumber++;
			levelWidth += Random.Range (1, 4);
			levelHeight += Random.Range (1, 2);
			DestroyAll();
			MoveBackground();
			SpawnLevel();
	        MoveBoat();
			MovePlayer();
		}
	}

	void SpawnBackground() {
		Vector3 backgroundPosition = new Vector3(levelWidth * 0.5f, levelHeight-1.5f, 0f);
		background = (GameObject)Instantiate(background, backgroundPosition, Quaternion.identity);
	}

	void MoveBackground() {
		background.transform.position = new Vector3(levelWidth * 0.5f, levelHeight-1.5f, 0f);
	}

	void SpawnBoat() {
		Vector3 boatStartPosition = new Vector3(levelWidth * 0.5f, levelHeight-1, 0f);
		boat = (GameObject)Instantiate(boat, boatStartPosition, Quaternion.identity);
	}

        void MoveBoat() {
		boat.transform.position = new Vector3(levelWidth * 0.5f, levelHeight-1, 0f);
  	}

	void SpawnPlayer() {
		Vector3 playerStartPosition = new Vector3(levelWidth * 0.5f, levelHeight-3, 0f);
		player = (GameObject)Instantiate(player, playerStartPosition, Quaternion.identity);
	}

	void MovePlayer() {
		player.transform.position = new Vector3(levelWidth * 0.5f, levelHeight-3, 0f);
	}

	void SpawnLevel() {
		//Create the level
		currentDucks = 0;
		currentOctopus = 0;
		maxDucks = (levelNumber + 1) * Random.Range(2, 6);
		maxOctopus = levelNumber / 2;
		levelFill = Mathf.CeilToInt (levelNumber / 10f);
		Debug.Log (levelFill);
		levelTiles = new int[levelWidth, levelHeight];
		levelTiles = TemplateLevel();
		tiles = new GameObject[levelWidth, levelHeight];
		for (int col = 0; col < levelHeight; col++) {
			for(int row = 0; row < levelWidth; row++) {
				// Randomly mark tile as filled
				if(levelTiles[row, col] != FILLED_TILE && levelTiles[row, col] != TRANSPARENT_TILE && col != levelHeight-2) {
					levelTiles[row, col] = randomFillTile ();
				}
				// Create game objects for each filled tile
				if(levelTiles[row, col] == FILLED_TILE) {
					tiles[row, col] = (GameObject)Instantiate(tileSprite, new Vector3(row, col, 1), Quaternion.identity);
					tiles[row, col].transform.Rotate(0, 0, (Random.Range(0, 13)*37), Space.World);
				}
				else if(levelTiles[row, col] == TRANSPARENT_TILE) {
					tiles[row, col] = (GameObject)Instantiate(transparentSprite, new Vector3(row, col, 1), Quaternion.identity);
				}
				// Randomly spawn rubber ducks
				if(randomSpawnDucks() &&
				   currentDucks < maxDucks &&
				   levelTiles[row, col] != FILLED_TILE &&
				   levelTiles[row, col] != TRANSPARENT_TILE)
				{
					Instantiate(rubberDuck, new Vector3(row, col, 1), Quaternion.identity);
					currentDucks += 1;
				}
				// Randomly spawn octopus
				if(randomSpawnOctopus() &&
				   currentOctopus < maxOctopus &&
				   levelTiles[row, col] != FILLED_TILE &&
				   levelTiles[row, col] != TRANSPARENT_TILE)
				{
					Instantiate(octopus, new Vector3(row, col, 1), Quaternion.identity);
					currentOctopus += 1;
				}
			}
		}
	}

    int[,] TemplateLevel() {
        int[,] levelTemplate = new int[levelWidth, levelHeight];
		for (int col = 0; col < levelHeight; col++) {
			levelTemplate [0, col] = FILLED_TILE;					// left wall
			levelTemplate [levelWidth - 1, col] = FILLED_TILE;		// right wall
		}
		for (int row = 0; row < levelWidth; row++) {
			levelTemplate[row, 0] = FILLED_TILE;					// floor
			levelTemplate[row, levelHeight-1] = TRANSPARENT_TILE;	// ceiling
        }
        return levelTemplate;
    }

    int randomFillTile() {
        int fill = 0;
        int random = Random.Range(0, 13);
        if (random < levelFill) {
                fill = 1;
        }
        return fill;
    }

    bool randomSpawnDucks() {
        bool spawn = false;
        int random = Random.Range(0, levelNumber+1);
        if (random < 1) {
                spawn = true;
        }
        return spawn;
    }

	bool randomSpawnOctopus() {
		bool spawn = false;
		int random = Random.Range(0, levelNumber+5);
		if (random < 1) {
			spawn = true;
		}
		return spawn;
	}

	void DestroyAll() {
		object[] allObjects = Resources.FindObjectsOfTypeAll(typeof(GameObject)) ;
		foreach (object thisObject in allObjects) {
			if (((GameObject)thisObject).activeInHierarchy) {
				if (((GameObject)thisObject).tag != "LevelBuilder" &&
				    ((GameObject)thisObject).tag != "MainCamera" &&
				    ((GameObject)thisObject).tag != "Player" &&
				    ((GameObject)thisObject).tag != "Background" &&
				    ((GameObject)thisObject).tag != "SoundManager" &&
				    ((GameObject)thisObject).tag != "Boat")
				{
					Debug.Log(((GameObject)thisObject).ToString());
					try {
						Debug.Log(((GameObject)thisObject).GetComponent("MessengerHelper").ToString());
					}
					catch (System.Exception e) {
						Destroy((GameObject)thisObject);
					}
				}
			}
		}
	}

    public int getLevelHeight() {
        return this.levelHeight;
    }

    public int getLevelWidth(){
        return this.levelWidth;

    }

    // Update is called once per frame
    void Update() {

		if(youWin){
			if(winScreenTimer < 0){
				youWin = false;
				winCondition += Random.Range( 1, 10 );
				player.GetComponent<PlayerControl>().resetProgress();
				SpawnLevel();
				winScreenTimer = 5f;
			} else {
				winScreenTimer -= Time.deltaTime;

			}
		}
    }

    void OnGUI() {
		if(youWin){
			GUI.Box(new Rect(0, 0, 1136, 640), winScreen);
		}
    }

    public int getCurrentDucks(){
        return currentDucks;
    }

	public int getWinCondition(){
		return winCondition;
	}
}


text:
var group_info = require('../groups.json');

exports.gInfo = function(req, res) {
	var gid = req.params.id;
	console.log(gid);
	//gid = parseInt(gid);
	var groupinfo = group_info.group[gid-1];
	console.log(groupinfo);
	res.json(groupinfo);
}

redpajama_set_name: RedPajamaGithub


text:
package io.spring.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.task.configuration.DefaultTaskConfigurer;
import org.springframework.stereotype.Component;

/**
 * @author Michael Minella
 */
@Component
public class CustomTaskConfigurer extends DefaultTaskConfigurer {

	@Autowired
	public CustomTaskConfigurer(@Qualifier("secondDataSource") DataSource dataSource) {
		super(dataSource);
	}
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMoveData {
    public string name;
    public bool isMoving = false;
    public float moveTimerLimit;
    public float moveTimerCurrent = 0f;

    public List<PlayerMoveData> otherMovingCheckList;

    public PlayerMoveData(string newName)
    {
        name = newName;
    }
    public void InitOtherMoveStopList(List<PlayerMoveData> newOtherMovingCheckList)
    {
        otherMovingCheckList = newOtherMovingCheckList;
    }
    /*
    public void InitTimerLimit(float newMoveTimerLimit)
    {
        moveTimerLimit = newMoveTimerLimit;
    }
    public void StartMoveTimer()
    {
        moveTimerCurrent = moveTimerLimit;
    }

    public void WaitMovingTimer()
    {
        if (isMoving)
        {
            if (moveTimerCurrent > 0)
            {
                moveTimerCurrent -= Time.deltaTime;
            }
            else
            {
                isMoving = false;
            }
        }
    }
    */

    public bool OtherMoveIsMoving()
    {
        int count = 0;
        foreach (PlayerMoveData move in otherMovingCheckList)
        {
            if (move.isMoving.Equals(true))
            {
                count += 1;
            }
        }
        return count.Equals(otherMovingCheckList.Count);
    }
}


text:
DGR2_NP_BEGIN
class DGR2_API XmlClsNodeParserLodge : private Uncopyable
{
public:
    static XmlClsNodeParserLodge& GetInst();
    void join(const std::xStrT& clsname, XmlClsNodeParser& parser);
    XmlClsNodeParser* getClsNodeParser(const std::xStrT& clsname);
private:
    XmlClsNodeParserLodge();
    ~XmlClsNodeParserLodge();
    typedef std::map<std::xStrT, XmlClsNodeParser*> Name2ParserMapType;
    Name2ParserMapType parser_map_;
};
NP_END

#define JOIN_PARSER_LODGE(DGRCls, ParserCls) { XmlClsNodeParser* parser = new ParserCls(); XmlClsNodeParserLodge::GetInst().join(_X(#DGRCls), *parser); }

#endif


text:
<?php

require_once "src/Util/TsugiDOM.php";
require_once "src/Util/CC.php";
require_once "src/Util/CC_LTI.php";

use \Tsugi\Util\CC_LTI;

class CC_LTI_TEST extends \PHPUnit\Framework\TestCase
{
    public function testGeneral() {

        $lti_dom = new CC_LTI();
        $lti_dom->set_title('Autograder: Single-table SQL');
        $lti_dom->set_description('Create a single SQL table and insert some records.');
        $lti_dom->set_secure_launch_url('https://www.php-intro.com/tools/sql/index.php');
        $lti_dom->set_custom('exercise','single_mysql.php');
        $lti_dom->set_extension('apphome','http://www.php-intro.com');
        $save = $lti_dom->saveXML();
        $xmlout = '<?xml version="1.0" encoding="UTF-8"?>
<cartridge_basiclti_link xmlns="http://www.imsglobal.org/xsd/imslticc_v1p0" xmlns:blti="http://www.imsglobal.org/xsd/imsbasiclti_v1p0" xmlns:lticm="http://www.imsglobal.org/xsd/imslticm_v1p0" xmlns:lticp="http://www.imsglobal.org/xsd/imslticp_v1p0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd">
  <blti:title>Autograder: Single-table SQL</blti:title>
  <blti:description>Create a single SQL table and insert some records.</blti:description>
  <blti:custom>
    <lticm:property name="caliper_url">$Caliper.url</lticm:property>
    <lticm:property name="exercise">single_mysql.php</lticm:property>
  </blti:custom>
  <blti:extensions platform="www.tsugi.org">
    <lticm:property name="apphome">http://www.php-intro.com</lticm:property>
  </blti:extensions>
  <blti:extensions platform="canvas.instructure.com">
    <lticm:property name="canvas_caliper_url">$Caliper.url</lticm:property>
  </blti:extensions>
  <blti:launch_url>https://www.php-intro.com/tools/sql/index.php</blti:launch_url>
  <blti:secure_launch_url>https://www.php-intro.com/tools/sql/index.php</blti:secure_launch_url>
  <blti:vendor>
    <lticp:code>tsugi.org</lticp:code>
    <lticp:name>Tsugi Learning Platform</lticp:name>
    <lticp:description>
        Tsugi is a learning platform and set of APIs that make it easy to build
        highly interoperable learning tools for use in standards compliant
        Learning Management Systems like Sakai, Moodle, Blackboard, Brightspace, and Canvas.
    </lticp:description>
    <lticp:url>http://www.tsugi.org</lticp:url>
    <lticp:contact>
      <lticp:email>tsugi@apereo.org</lticp:email>
    </lticp:contact>
  </blti:vendor>
</cartridge_basiclti_link>
';
        $this->assertEquals($xmlout,$save);

    }
}


text:
/*
 * OrdersList Messages
 *
 * This contains all the text for the OrdersList component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  from: {
    id: 'app.components.OrdersList.from',
    defaultMessage: 'Order from',
  },
  owner: {
    id: 'app.components.OrdersList.owner',
    defaultMessage: 'Owner',
  },
  price: {
    id: 'app.components.OrdersList.price',
    defaultMessage: 'Price',
  },
});


text:
export default function(
    $scope,
    $rootScope,
    $log,
    $ionicNativeTransitions,
    $ionicModal,
    $ionicPlatform,
    $ionicHistory
) {

    'ngInject';

    var vm = this;
    vm.modal = null;
    vm.isEnable = $ionicNativeTransitions.isEnabled();
    vm.enable = enable;
    vm.disable = disable;
    vm.stateGo = stateGo;
    vm.locationUrl = locationUrl;
    vm.disableWithoutDisablingIonicTransitions = disableWithoutDisablingIonicTransitions;
    vm.openModal = openModal;
    vm.goBack = goBack;

    $rootScope.$on('ionicNativeTransitions.success', function() {
        $log.info('yeah!');
    });

    $rootScope.$on('ionicNativeTransitions.error', function() {
        $log.info(':(');
    });

    function openModal() {
        if (vm.modal) {
            vm.modal.show();
            return;
        }
        vm.modal = $ionicModal.fromTemplate(`
            <ion-modal-view>
                <ion-header-bar>

Modal

                    <button class="button button-clear button-assertive" ng-click="close()">

                    </button>
                </ion-header-bar>
                <ion-content class="has-footer has-footer padding">
                    modal
                </ion-content>
            </ion-modal-view>
            `, {
            scope: $rootScope.$new(),
        });
        vm.modal.show();
        vm.modal.scope.close = () => {
            console.log('modal close', JSON.stringify($ionicPlatform.$backButtonActions))
            vm.modal.remove();
            vm.modal = null;
        };
    }

    function enable() {
        $ionicNativeTransitions.enable();
        vm.isEnable = $ionicNativeTransitions.isEnabled();
    }

    function disable() {
        $ionicNativeTransitions.enable(false);
        vm.isEnable = $ionicNativeTransitions.isEnabled();
    }

    function disableWithoutDisablingIonicTransitions() {
        $ionicNativeTransitions.enable(false, true);
        vm.isEnable = $ionicNativeTransitions.isEnabled();
    }

    function stateGo() {
        $ionicNativeTransitions.stateGo('four', {
            test: 'buyakacha!',
            testParamUrl: 'hihi'
        }, {
            "type": "slide",
            "direction": "up", // 'left|right|up|down', default 'left' (which is like 'next')
            "duration": 1500, // in milliseconds (ms), default 400
        }, {
            reload: true
        });
    }

    function locationUrl() {
        $ionicNativeTransitions.locationUrl('/three');
    }

    function goBack(count) {
        console.log('count', count, $ionicHistory.viewHistory())
        $rootScope.$ionicGoBack(count);
    }
}


text:
package com.amaiaeskisabel.popularmovies.fragments;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.amaiaeskisabel.popularmovies.R;
import com.amaiaeskisabel.popularmovies.activities.DetailMovieActivity;
import com.amaiaeskisabel.popularmovies.adapters.MoviesAdapter;
import com.amaiaeskisabel.popularmovies.api.MovieDBAPI;
import com.amaiaeskisabel.popularmovies.helpers.NetworkMonitoring;
import com.amaiaeskisabel.popularmovies.models.APIResponse;
import com.amaiaeskisabel.popularmovies.models.Movie;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A placeholder fragment containing a simple view.
 */

public class BrowserMoviesActivityFragment extends Fragment {

    @Bind(R.id.grid_movies) GridView gridview;

    private MoviesAdapter mMovieAdapter;
    private ArrayList<Movie> mMoviesList;

    public BrowserMoviesActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.fragment_browser_movies, container, false);
        ButterKnife.bind(this, rootView);
        mMovieAdapter = createMovieAdapter();
        gridview.setAdapter(mMovieAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(rootView.getContext(), DetailMovieActivity.class);
                intent.putExtra("movie", mMoviesList.get(position));
                startActivity(intent);
            }
        });
        return rootView;
    }

    private MoviesAdapter createMovieAdapter() {
        if(mMovieAdapter!=null) {
            mMovieAdapter.clearMoviePosters();
            addPostertoMovieAdapter();
        } else{
            mMovieAdapter = new MoviesAdapter(getActivity());
        }
        return mMovieAdapter;
    }

    public void addPostertoMovieAdapter() {
        ArrayList<String> mMoviePosters = new ArrayList<>();
        for (Movie movie : mMoviesList) {
            mMoviePosters.add(movie.getPosterCompleteURL(MovieDBAPI.getThumbnailW185()));
        }
        mMovieAdapter.addMoviePosters(mMoviePosters);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onStart() {
        super.onStart();
        if(NetworkMonitoring.cheakNetworkConnectivity(getActivity())) {
            updateMovies();
        } else {
            Toast.makeText(getActivity(), "You do not have an Internet connection", Toast.LENGTH_LONG).show();
        }
    }

    private void updateMovies() {
        FetchMoviesTask fetchMoviesTask = new FetchMoviesTask();
        String sortOrder = getSortPreference();
        String preference = setSortPreference(sortOrder);
        fetchMoviesTask.execute(preference, sortOrder);
    }

    private String getSortPreference() {

        SharedPreferences sharedPrefs =
                PreferenceManager.getDefaultSharedPreferences(getActivity());

        String sortOrderBy = sharedPrefs.getString(
                getString(R.string.pref_sort_by_key),
                getString(R.string.pref_sort_by_most_popular));

        return sortOrderBy;
    }

    private String setSortPreference(String sortOrderBy) {

        String preference = null;
        if (sortOrderBy.equals(getString(R.string.pref_sort_by_most_popular))) {
            preference = MovieDBAPI.getMostPopularUrl();
        } else if (sortOrderBy.equals(getString(R.string.pref_sort_by_highest_rated))) {
            preference = MovieDBAPI.getHighestRatedUrl();
        }
        return preference;
    }

    private class FetchMoviesTask extends AsyncTask<String, Void, ArrayList<Movie>> {

        private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();

        @Override
        protected ArrayList<Movie> doInBackground(String... params) {

            URL url;
            HttpURLConnection urlConnection = null;
            InputStream inputStream;
            Reader reader = null;

            ArrayList<Movie> movies = new ArrayList<Movie>();

            try {
                url = createURL(params[0], params[1]);
                urlConnection = makeGetRequestToMovieDB(url);
                inputStream = urlConnection.getInputStream();
                if (inputStream != null) {
                    reader = new InputStreamReader(inputStream);
                    movies = castMoviesJsonToMoviesList(reader);
                    inputStream.close();
                } else {
                    return null;
                }
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                return null;
            } finally {
                closeURLConnection(urlConnection);
                closeStreamReader(reader);
            }
            if(movies!=null && !movies.isEmpty()) {
                return movies;
            } else {
                return null;
            }
        }

        @Override
        protected void onPostExecute(ArrayList<Movie> movies) {
            super.onPostExecute(movies);
            if(movies!=null) {
                if(mMoviesList==null) {
                    mMoviesList = new ArrayList<>();
                } else {
                    mMoviesList.clear();
                }
                mMoviesList = (ArrayList<Movie>) movies.clone();
                addPostertoMovieAdapter();
            }
        }

        protected URL createURL(String preference, String sortOrderBy) {
            try {
                Uri builtUri = Uri.parse(MovieDBAPI.getApiUrl() + preference);
                if (preference.equals(MovieDBAPI.getHighestRatedValue())) {
                    builtUri = builtUri.buildUpon().appendQueryParameter(MovieDBAPI.getSortBy(),sortOrderBy).build();
                }
                builtUri = builtUri.buildUpon().appendQueryParameter(MovieDBAPI.getApiKeyParam(),MovieDBAPI.getApiKey()).build();
                return new URL(builtUri.toString());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected HttpURLConnection makeGetRequestToMovieDB(URL url) {
            HttpURLConnection urlConnection;
            try {
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                return urlConnection;
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected ArrayList<Movie> castMoviesJsonToMoviesList(Reader reader) {
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            APIResponse result = gson.fromJson(reader, APIResponse.class);
            return result.getResultsMovies();
        }

        protected void closeURLConnection(HttpURLConnection urlConnection) {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        protected void closeStreamReader(Reader reader) {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }
    }
}


text:
class Participant < ActiveRecord::Base
  # You could use a self-referential polymorphic join here
  belongs_to :user
  has_many :bids
  has_many :auctions, through: :bids
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace BuenosDias.I18n
{
    [ContentProperty("Text")]
    public class TranslateExtension : IMarkupExtension
    {
        public string Text { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Text == null)
            {
                return string.Empty;
            }

            var rm = Resources.ResourceManager;
            var translation = rm.GetString(Text);

            if (translation == null)
            {
#if DEBUG
                throw new ArgumentException(string.Format("Key '{0}' was not found.", Text));
#else
				translation = Text;
#endif
            }

            return translation;
        }
    }
}


text:
#ifndef QWT_SPLINE_LOCAL_H
#define QWT_SPLINE_LOCAL_H

#include "qwt_global.h"
#include "qwt_spline.h"

/*!
  \brief A spline with C1 continuity

  QwtSplineLocal offers several standard algorithms for interpolating
  a curve with polynomials having C1 continuity at the control points.
  All algorithms are local in a sense, that changing one control point
  only few polynomials.
 */
class QWT_EXPORT QwtSplineLocal: public QwtSplineC1
{
public:
    /*!
        \brief Spline interpolation type

        All type of spline interpolations are lightweight algorithms
        calculating the slopes at a point by looking 1 or 2 points back
        and ahead.
     */
    enum Type
    {
        /*!
          A cardinal spline

          The cardinal spline interpolation is a very cheap calculation with
          a locality of 1.
         */
        Cardinal,

        /*!
          Parabolic blending is a cheap calculation with a locality of 1. Sometimes
          it is also called Cubic Bessel interpolation.
         */
        ParabolicBlending,

        /*!
          The algorithm of H.Akima is a calculation with a locality of 2.
         */
        Akima,

        /*!
          Piecewise Cubic Hermite Interpolating Polynomial (PCHIP) is an algorithm
          that is popular because of being offered by MATLAB.

          It preserves the shape of the data and respects monotonicity. It has a
          locality of 1.
         */
        PChip
    };

    QwtSplineLocal( Type type );
    virtual ~QwtSplineLocal();

    Type type() const;

    virtual uint locality() const QWT_OVERRIDE;

    virtual QPainterPath painterPath( const QPolygonF & ) const QWT_OVERRIDE;
    virtual QVector<QLineF> bezierControlLines( const QPolygonF & ) const QWT_OVERRIDE;

    // calculating the parametric equations
    virtual QVector<QwtSplinePolynomial> polynomials( const QPolygonF & ) const QWT_OVERRIDE;
    virtual QVector<double> slopes( const QPolygonF & ) const QWT_OVERRIDE;

private:
    const Type d_type;
};

#endif


text:
require 'spec_helper'

describe DesignsController do
  before do
    @account = Factory(:account)
    Account.stub!(:find).and_return(@account)
    controller.stub!(:require_user).and_return(true)
  end

  describe "GET index" do
    before do
      @designs = (1..3).collect{ Factory(:design, :account => @account) }
      get :index, :account_id => @account.id
    end

    it { should assign_to(:designs).with(@designs) }
    it { should respond_with(:success) }
    it { should respond_with_content_type(:html) }
  end

  describe "GET show" do
    before do
      @design = Factory(:design, :account => @account)
      get :show, :account_id => @account.id, :id => @design.id
    end

    it { should assign_to(:design).with(@design) }
    it { should respond_with(:success) }
    it { should respond_with_content_type(:html) }
  end

  describe "GET new" do
    before do
      get :new, :account_id => @account.id
    end

    it { should assign_to(:design).with_kind_of(Design) }
    it { should respond_with(:success) }
    it { should respond_with_content_type(:html) }
  end

  describe "GET edit" do
    before do
      @design = Factory(:design, :account => @account)
      get :edit, :account_id => @account.id, :id => @design.id
    end

    it { should assign_to(:design).with(@design) }
    it { should respond_with(:success) }
    it { should respond_with_content_type(:html) }
  end

  describe "POST create" do
    context "with valid attributes" do
      before do
        @design_attributes = Factory.attributes_for(:design, :account => @account)
        post :create, :account_id => @account.id, :design => @design_attributes
      end

      it { should assign_to(:design).with_kind_of(Design) }
      it { should respond_with(:redirect) }
      it { should set_the_flash.to(/success/) }
    end

    context "without valid attributes" do
      before do
        @design_attributes = Factory.attributes_for(:design, :name => "", :account => @account)
        post :create, :account_id => @account.id, :design => @design_attributes
      end

      it { should assign_to(:design).with_kind_of(Design) }
      it { should respond_with(:success) }
      it { should render_template(:new) }
    end
  end

  describe "PUT update" do
    context "with valid attributes" do
      before do
        @design_attributes = Factory.attributes_for(:design, :account => @account)
        @design = Factory(:design, :account => @account)
        put :update, :account_id => @account.id, :id => @design.id, :design => @design_attributes
      end

      it { should assign_to(:design).with_kind_of(Design) }
      it { should respond_with(:redirect) }
    end

    context "without valid attributes" do
      before do
        @design_attributes = Factory.attributes_for(:design, :name => "", :account => @account)
        @design = Factory(:design, :account => @account)

        put :update, :account_id => @account.id, :id => @design.id, :design => @design_attributes
      end

      it { should assign_to(:design).with(@design) }
      it { should respond_with(:success) }
      it { should render_template(:edit) }
    end
  end

  describe "DELETE destroy" do
    before do
      @design = Factory(:design, :account => @account)
      delete :destroy, :account_id => @account.id, :id => @design.id
    end

    it "should deactivate the front page" do
      @design.reload.active.should be_false
    end
    it { should respond_with(:redirect) }
  end
end


text:
package proxypool

import (
	"testing"
	"time"
)

func TestValidateParallel(t *testing.T) {
	cfg := DefaultConfig()
	pList, err := cfg.Provider.Load()
	if err != nil {
		t.Fail()
	}
	if len(pList) == 0 {
		return
	}

	pending := make([]ProxyInfo, len(pList))
	for i, item := range pList {
		pending[i] = ProxyInfo{
			Host: item.Host,
			Port: item.Port,
			Type: Protocol(item.Type),
		}
	}

	c := make(chan []*ProxyQuality)
	go func() {
		c <- validateParallel(pending, cfg.Validator, 5)
	}()

	select {
	case qualities := <-c:
		if len(qualities) != len(pending) {
			t.Error("Missing varify result")
		}
	case <-time.After(time.Second * 12):
		t.Error("Timeout in validate")
	}

}


text:
require "mongoid/sessions/mongo_uri"

module Mongoid
  module Sessions
    module Factory
      extend self

      # Create a new session given the named configuration. If no name is
      # provided, return a new session with the default configuration. If a
      # name is provided for which no configuration exists, an error will be
      # raised.
      #
      # @example Create the session.
      #   Factory.create(:secondary)
      #
      # @param [ String, Symbol ] name The named session configuration.
      #
      # @raise [ Errors::NoSessionConfig ] If no config could be found.
      #
      # @return [ Moped::Session ] The new session.
      #
      # @since 3.0.0
      def create(name = nil)
        return default unless name
        config = Mongoid.sessions[name]
        raise Errors::NoSessionConfig.new(name) unless config
        create_session(config)
      end

      # Get the default session.
      #
      # @example Get the default session.
      #   Factory.default
      #
      # @raise [ Errors::NoSessionConfig ] If no default configuration is
      #   found.
      #
      # @return [ Moped::Session ] The default session.
      #
      # @since 3.0.0
      def default
        create_session(Mongoid.sessions[:default])
      end

      private

      # Create the session for the provided config.
      #
      # @api private
      #
      # @example Create the session.
      #   Factory.create_session(config)
      #
      # @param [ Hash ] configuration The session config.
      #
      # @return [ Moped::Session ] The session.
      #
      # @since 3.0.0
      def create_session(configuration)
        raise Errors::NoSessionsConfig.new unless configuration
        config, options = parse(configuration)
        configuration.merge!(config) if configuration.delete(:uri)
        session = Moped::Session.new(config[:hosts], options)
        session.use(config[:database])
        if authenticated?(config)
          session.login(config[:username], config[:password])
        end
        session
      end

      # Are we authenticated with this session config?
      #
      # @api private
      #
      # @example Is this session authenticated?
      #   Factory.authenticated?(config)
      #
      # @param [ Hash ] config The session config.
      #
      # @return [ true, false ] If we are authenticated.
      #
      # @since 3.0.0
      def authenticated?(config)
        config.has_key?(:username) && config.has_key?(:password)
      end

      # Parse the configuration. If a uri is provided we need to extract the
      # elements of it, otherwise the options are left alone.
      #
      # @api private
      #
      # @example Parse the config.
      #   Factory.parse(config)
      #
      # @param [ Hash ] config The configuration.
      #
      # @return [ Array<Hash> ] The configuration, parsed.
      #
      # @since 3.0.0
      def parse(config)
        options = config[:options].try(:dup) || {}
        parsed = config.has_key?(:uri) ? MongoUri.new(config[:uri]).to_hash : config
        [ parsed, options.symbolize_keys ]
      end
    end
  end
end


text:
namespace dsa {

typedef boost::asio::ip::tcp::socket tcp_socket;
typedef boost::asio::ssl::stream<tcp_socket> ssl_socket;

// Secure TCP connection. Used for DSA connections over secure TCP.
// Handles DSA handshake, combining outgoing messages,
// and separating incoming messages.
class StcpConnection : public BaseSocketConnection {
  class WriteBuffer : public ConnectionWriteBuffer {
    StcpConnection &connection;
    size_t size = 0;

   public:
    explicit WriteBuffer(StcpConnection &connection) : connection(connection){};

    size_t max_next_size() const override;
    void add(const Message &msg, int32_t rid, int32_t ack_id) override;
    void write(WriteHandler &&callback) override;
  };

 protected:
  void continue_read_loop(shared_ptr_<Connection> &&sthis) final {
    start_read(std::move(sthis));
  }
  shared_ptr_<ssl_socket> _socket;

  void destroy_impl() override;

 public:
  StcpConnection(const SharedLinkStrandRef &strand, const string_ &dsid_prefix,
                 const string_ &path = "");

  void start_read(shared_ptr_<Connection> &&connection) final;

  std::unique_ptr<ConnectionWriteBuffer> get_write_buffer() override;

  ssl_socket::lowest_layer_type &socket();
};

}  // namespace dsa

#endif  // DSA_SDK_STCP_CONNECTION_H


text:
package jenkins.management;

import hudson.model.AdministrativeMonitor;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

@Restricted(NoExternalUse.class)
public class AdministrativeMonitorsApiData {
    private final List<AdministrativeMonitor> monitorsList = new ArrayList<>();

    AdministrativeMonitorsApiData(List<AdministrativeMonitor> monitors) {
        monitorsList.addAll(monitors);
    }

    public List<AdministrativeMonitor> getMonitorsList() {
        return this.monitorsList;
    }

    public boolean hasActiveMonitors() {
        return !this.monitorsList.isEmpty();
    }
}


text:
> Cloudflare Async Util

## Installation

```sh
$ npm install cf-util-async
```

## Usage

Running async functions in a series:

```js
import http from 'cf-util-http';
import {series} from 'cf-util-async';

series([
  cb => http.get('endpoint-1.json', null, cb), // If an error occurs, then the rest of the callbacks are not called.
  cb => http.get('endpoint-2.json', null, cb)
], (err, results) => {
  if (err) {
    console.log(err.body); // > { errors: [{ message: 'Error!' }] }
  } else {
    console.log(res.body); // > [{ result: { id: 1, ... } }, { result: { id: 2, ... } }]
  }
});
```

Running async functions in parallel:

```js
import http from 'cf-util-http';
import {parallel} from 'cf-util-async';

parallel([
  cb => http.get('endpoint-1.json', null, cb),
  cb => http.get('endpoint-2.json', null, cb)
], (err, results) => {
  if (err) {
    console.log(err.body); // > { errors: [{ message: 'Error!' }] }
  } else {
    console.log(res.body); // > [{ result: { id: 1, ... } }, { result: { id: 2, ... } }]
  }
});
```


text:
.. image:: docs/pax_logo_bw_cropped.png

The Processor for Analyzing XENON (PAX) is used for doing digital signal
processing and other data processing on the XENON100/XENON1T raw data.

* Free software: BSD license
* Documentation: http://xenon1t.github.io/pax/.

.. image:: https://travis-ci.org/XENON1T/pax.svg?branch=master
    :target: https://travis-ci.org/XENON1T/pax
.. image:: https://coveralls.io/repos/XENON1T/pax/badge.svg?branch=master
    :target: https://coveralls.io/r/XENON1T/pax?branch=master
.. image:: http://img.shields.io/badge/gitter-XENON1T/pax-blue.svg
    :target: https://gitter.im/XENON1T/pax

Installation prerequisites
==========================

We will assume you are installing on Mac or Linux here. For installation on Windows,
see `this FAQ entry <http://xenon1t.github.io/pax/faq.html#can-i-set-up-pax-on-my-windows-machine>`_.

Instead of installing pax you can use pax from the central installation on xecluster or other cluster. See the `FAQ <https://github.com/XENON1T/pax/blob/master/docs/faq.rst>`_ for more details.

If you wish to develop pax, you can either follow these instructions from the beginning which installs your own copy of the Anaconda libraries, or use an existing Anaconda installation (skip to the "Setting Up the Anaconda Libraries" section below for this).

Installing Python 3 and Anaconda Libraries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Pax is written in Python; we recommend the scientific python distribution `Anaconda <https://store.continuum.io/cshop/anaconda/>`_. To install this in Linux do::

  wget http://repo.continuum.io/archive/Anaconda3-2.4.0-Linux-x86_64.sh  # Linux
  bash Anaconda3-2.4.0-Linux-x86_64.sh  # Say 'yes' to appending to .bashrc and specify the installation directory
  conda install -q conda=4.1.1
--------------------------------

The last line is a temporary workaround.

For Mac OS X, you should instead download the .sh file located here:

    http://repo.continuum.io/archive/Anaconda3-2.4.0-MacOSX-x86_64.sh

In the directory containing the file above, run the following command::

    bash Anaconda3-2.4.0-MacOSX-x86_64.sh  # Say 'yes' to appending to .bashrc and specify the installation directory

Setting Up the Anaconda Libraries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For both Linux and Mac OS X::

  export PATH=~/anaconda3/bin:$PATH  # If installed in default location, otherwise replace with the
                                     # path you specified above or the path of the central installation

You need to point Anaconda to the physics-specific packages e.g. ROOT.  You can do this by running the following::

  conda config --add channels http://conda.anaconda.org/NLeSC

Check that no other ROOT is seen
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Several people have encountered ROOT incompatibility issues when installing pax. Before continuing, we advise you to check that no other ROOT version that can be seen by your terminal, e.g try::

  root

Which should return ``bash: root: command not found``.  Also check that Python cannot see ROOT::

  python -c "import ROOT"

should say ``ImportError: No module named 'ROOT'``.

If there are multiple versions of ROOT around, strange segfaults and other weird issues can result. This is an issue with ROOT and not pax.

Additional python packages
^^^^^^^^^^^^^^^^^^^^^^^^^^

Pax depends on several other python packages. While most python packages will install automatically,
some contain C++ code which must be compiled. With Anaconda you can get appropriate binaries
for your platform using the `conda` tool as follows. Make sure to replace <environment_name> with the desired name of your environment (usually it is 'pax' for central installations) in the following command::

  conda install conda
  conda create -n <environment_name> python=3.4 root=6 numpy scipy=0.18.1 pyqt=4.11 matplotlib pandas cython h5py numba pip python-snappy pytables scikit-learn rootpy pymongo psutil jupyter dask root_pandas jpeg=8d isl=0.12.2 gmp=5.1.2 glibc=2.12.2 graphviz=2.38.0=4 gsl=1.16 linux-headers=2.6.32 mpc=1.0.1 mpfr=3.1.2 pcre=8.37 python-snappy=0.5 pyopenssl=0.15.1

If you do not want ROOT support, or have ROOT-related issues, you can leave out root and rootpy in the above command. Everything in pax, except of course ROOT I/O, will continue to work. You can also try root=6 for the newer version of ROOT.

Note the command to install an old version of conda above: if you use the latest conda (as of October 2016) everything will appear to install, but you'll end up with a version of python where you can't import ROOT (so pax won't work if you need ROOT support). For more information, see https://github.com/remenska/root-conda-recipes/issues/6.

Whenever you want to use `pax`, you have to run the following command to set it up your environment (containing all the dependencies)::

  source activate <environment_name>

You can put this in your `.bashrc` if you want it to be setup when you login. For the rest of the installation and to run pax, be sure to be inside this environment. There should be (<environment_name>) at the beginning of your command line.

-----------------------------------

Of course we assume you have a functional basic compilation environment. On a fresh Ubuntu you may have to do e.g.

  sudo apt-get install build-essential

to setup the necessary compilers.

On a Mac, please run the following to make sure that ROOT works::

  xcode-select --install

Git and Github
^^^^^^^^^^^^^^

You must have `git` installed, which you can test by running at the command line::

  git

To get the code of pax, you need access to the private XENON1T github repository.  You can get this by emailing the `pax` developers.

Installing pax
==============

There are two ways to install pax. Either method will automatically try to install any python packages pax depends on -- although we hope you installed the most important ones already (see above). If a module does not install, try using `conda` or `pip` to install missing dependencies.

**WARNING: If you are working with a central installation of Anaconda, e.g. on Midway, Stockholm, or xecluster, there is a risk of overwriting the central installation (we are still working out some permissions issues)!** To avoid this, make sure you are either using your own installation of Anaconda or have created a new environment by replacing <environment_name> in the instructions above.

Option 1: User installation
^^^^^^^^^^^^^^^^^^^^^^^^^^^

In this option the pax code will be hidden away somewhere deep in python's directory structure so you won't accidentally look at it and learn our dangerous secrets. Also, you will only be able to update pax after we make a new release (about once a month). If this appeals to you, run::

    pip install git+https://github.com/XENON1T/pax.git

To update to a newer version, add ` --upgrade`` to the command above (or just run the same command again).

Option 2: Developer installation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In this option you'll know where the code is, so you can look at it, play with it, and if you change anything you don't need to reinstall for your changes to take effect... However, be aware you are using the very latest ('nightly') version of pax, which may contain more bugs (but often contains less bugs).

First `cd` to the folder you want pax to be installed. Then run::

    git clone https://github.com/XENON1T/pax.git
    source activate <environment_name>  # Make sure you specify your own environment
                                        # when using a central installation of Anaconda
    cd pax
    python setup.py develop

To update to the latest pax, go to the directory with pax and run `git pull`.

If you think you've made a useful change, you can contribute it! But please check the
`relevant documentation section`_ first.

.. _relevant documentation section: CONTRIBUTING.rst

To check if your installation is working
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Execute::

    paxer --version

or

    paxer --input ~/pax/pax/data/XENON100_120402_2000_000000.xed --stop_after 1 --plot --config="XENON100"

You should see a nice plot of a XENON100 event.

Pax Tutorial
============
This section assumes that pax is installed, either from the instructions above
or via `the FAQ on running the code at LNGS <http://xenon1t.github.io/pax/faq.html#how-do-i-run-pax-at-lngs-on-xecluster>`_.

Now you should be able to run the command::

  paxer --help

from anywhere, which will give you a list of other command line options. If you have a graphical display, try `paxer --plot` and `paxer --plot_interactive`. You can select some data with the `--input` option::

  paxer --input /archive/data/xenon100/run_14/xe100_150213_1411/xe100_150213_1411_000000.xed --event 0 --plot --config="XENON100"

If you want to do something nonstandard, you can create your own configuration file
like `my_file.ini`::

   [pax]
   parent_configuration = 'XENON100'
   input = 'XED.ReadXED'
   output = [ 'Plotting.PlotChannelWaveforms3D',
              #'Plotting.PlotEventSummary',
            ]

   [Plotting]
   log_scale_entire_event = False
   #output_name = 'plots'  # Uncomment to write plot to disk

You can load this file with `paxer` by using the `config_path` option::

  paxer --config_path my_file.ini --input /archive/data/xenon100/run_14/xe100_150213_1411/xe100_150213_1411_000000.xed --event 0

You can uncomment the `output_dir` line to write the plots to a file.  Also, try
playing with what is in the list of outputs.  For example, you can reactivate
the `PlotEventSummary` that was produced in the first command from above.

There are many, many configuration options you can change.
You can look through other configuration files such as `_base.ini` and `XENON100.ini` to get an idea of what you can do. Also, you can try to explore what plugins are included in pax. You can ask us questions on gitter (click button above) or email. Oh, and did we mention the the documentation at http://xenon1t.github.io/pax/?


text:
package cz.cuni.mff.odcleanstore.fusiontool;

import com.google.code.externalsorting.ExternalSort;
import cz.cuni.mff.odcleanstore.conflictresolution.ConflictResolverFactory;
import cz.cuni.mff.odcleanstore.conflictresolution.ResolutionFunctionRegistry;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.ConflictResolutionPolicyImpl;
import cz.cuni.mff.odcleanstore.conflictresolution.impl.DistanceMeasureImpl;
import cz.cuni.mff.odcleanstore.conflictresolution.quality.SourceQualityCalculator;
import cz.cuni.mff.odcleanstore.conflictresolution.quality.impl.DecidingConflictFQualityCalculator;
import cz.cuni.mff.odcleanstore.conflictresolution.quality.impl.ODCSSourceQualityCalculator;
import cz.cuni.mff.odcleanstore.fusiontool.config.*;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.ResourceDescriptionConflictResolver;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.impl.NestedResourceDescriptionQualityCalculatorImpl;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.impl.ResourceDescriptionConflictResolverImpl;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.AlternativeUriNavigator;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterable;
import cz.cuni.mff.odcleanstore.fusiontool.conflictresolution.urimapping.UriMappingIterableImpl;
import cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException;
import cz.cuni.mff.odcleanstore.fusiontool.io.LargeCollectionFactory;
import cz.cuni.mff.odcleanstore.fusiontool.io.MapdbCollectionFactory;
import cz.cuni.mff.odcleanstore.fusiontool.io.MemoryCollectionFactory;
import cz.cuni.mff.odcleanstore.fusiontool.io.RepositoryFactory;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.ExternalSortingInputLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.InputLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.SubjectsSetInputLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.TransitiveSubjectsSetInputLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesFileLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.data.AllTriplesRepositoryLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.entity.FederatedSeedSubjectsLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.fiter.FederatedResourceDescriptionFilter;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.fiter.MappedResourceFilter;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.fiter.RequiredClassFilter;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.fiter.ResourceDescriptionFilter;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.metadata.MetadataLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.sameas.SameAsLinkFileLoader;
import cz.cuni.mff.odcleanstore.fusiontool.loaders.sameas.SameAsLinkRepositoryLoader;
import cz.cuni.mff.odcleanstore.fusiontool.source.ConstructSource;
import cz.cuni.mff.odcleanstore.fusiontool.source.ConstructSourceImpl;
import cz.cuni.mff.odcleanstore.fusiontool.source.DataSource;
import cz.cuni.mff.odcleanstore.fusiontool.source.DataSourceImpl;
import cz.cuni.mff.odcleanstore.fusiontool.util.*;
import cz.cuni.mff.odcleanstore.fusiontool.writers.*;
import cz.cuni.mff.odcleanstore.vocabulary.ODCSInternal;
import org.openrdf.model.Model;
import org.openrdf.model.URI;
import org.openrdf.model.impl.TreeModel;
import org.openrdf.repository.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Loads and prepares all inputs for data fusion executor, executes data fusion and outputs additional metadata
 * such as canonical URIs.
 * See sample configuration files (sample-config-full.xml) for overview of all processing options.
 * <p/>
 * This class is not thread-safe.
 * @see LDFusionToolExecutor
 */
public class LDFusionToolComponentFactory implements FusionComponentFactory {
    private static final Logger LOG = LoggerFactory.getLogger(LDFusionToolComponentFactory.class);

    private static final CloseableRDFWriterFactory rdfWriterFactory = new CloseableRDFWriterFactory();

    /** An instance of {@link cz.cuni.mff.odcleanstore.fusiontool.io.RepositoryFactory}. */
    protected final RepositoryFactory repositoryFactory;

    /** Global configuration. */
    protected final Config config;

    /** Indicates if resources to process should be discovered transitively. */
    protected final boolean isTransitive;

    private ProfilingTimeCounter<EnumFusionCounters> executorTimeProfiler;

    private MemoryProfiler executorMemoryProfiler;

    /**
     * Creates new instance.
     * @param config global configuration
     */
    public LDFusionToolComponentFactory(Config config) {
        this.config = config;
        isTransitive = false; // TODO
        repositoryFactory = new RepositoryFactory(config.getParserConfig());
        executorTimeProfiler = ProfilingTimeCounter.createInstance(EnumFusionCounters.class, config.isProfilingOn());
        executorMemoryProfiler = MemoryProfiler.createInstance(config.isProfilingOn());
    }

    @Override
    public LDFusionToolExecutor getExecutor(UriMappingIterable uriMapping) {
        return new LDFusionToolExecutor(
                hasVirtuosoSource(config.getDataSources()),
                config.getMaxOutputTriples(),
                getInputFilter(uriMapping),
                executorTimeProfiler,
                executorMemoryProfiler
        );
    }

    @Override
    public InputLoader getInputLoader() throws IOException, LDFusionToolException {
        long memoryLimit = calculateMemoryLimit();
        if (config.isLocalCopyProcessing()) {
            Collection<AllTriplesLoader> allTriplesLoaders = getAllTriplesLoaders();
            return new ExternalSortingInputLoader(allTriplesLoaders,
                    LDFusionToolUtils.getResourceDescriptionProperties(config),
                    config.getTempDirectory(),
                    config.getParserConfig(),
                    memoryLimit);
        } else {
            Collection<DataSource> dataSources = getDataSources();
            SparqlRestriction seedResourceDescription = getSeedResourceRestriction();
            UriCollection seedSubjects = getSeedSubjects(dataSources, seedResourceDescription);
            LargeCollectionFactory largeCollectionFactory = createLargeCollectionFactory();
            return (isTransitive)
                    ? new TransitiveSubjectsSetInputLoader(seedSubjects, dataSources, largeCollectionFactory, config.getOutputMappedSubjectsOnly())
                    : new SubjectsSetInputLoader(seedSubjects, dataSources, largeCollectionFactory, config.getOutputMappedSubjectsOnly());
        }
    }

    private SparqlRestriction getSeedResourceRestriction() {
        if (config.getRequiredClassOfProcessedResources() == null) {
            return null;
        } else {
            final String varPrefix = "be3611ab1a_"; // some unique prefix
            return new SparqlRestrictionImpl(String.format("?%sr rdf:type <%s>", varPrefix, config.getRequiredClassOfProcessedResources().stringValue()),
                    varPrefix + "r");
        }
    }

    protected ResourceDescriptionFilter getInputFilter(UriMappingIterable uriMapping) {
        List<ResourceDescriptionFilter> inputFilters = new ArrayList<>();
        if (config.getRequiredClassOfProcessedResources() != null) {
            inputFilters.add(new RequiredClassFilter(uriMapping, config.getRequiredClassOfProcessedResources()));
        }
        if (config.getOutputMappedSubjectsOnly()) {
            inputFilters.add(new MappedResourceFilter(new AlternativeUriNavigator(uriMapping)));
        }

        return FederatedResourceDescriptionFilter.fromList(inputFilters);
    }

    /**
     * Returns an initialized collection of input triple loaders.
     * @return collection of input triple loaders
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException error
     */
    protected Collection<AllTriplesLoader> getAllTriplesLoaders() throws LDFusionToolException {
        List<AllTriplesLoader> loaders = new ArrayList<>(config.getDataSources().size());
        for (DataSourceConfig dataSourceConfig : config.getDataSources()) {
            try {
                AllTriplesLoader loader;
                if (dataSourceConfig.getType() == EnumDataSourceType.FILE) {
                    loader = new AllTriplesFileLoader(dataSourceConfig, config.getParserConfig());
                } else {
                    DataSource dataSource = DataSourceImpl.fromConfig(dataSourceConfig, config.getPrefixes(), repositoryFactory);
                    loader = new AllTriplesRepositoryLoader(dataSource);
                }
                loaders.add(loader);
            } catch (LDFusionToolException e) {
                // clean up already initialized loaders
                for (AllTriplesLoader loader : loaders) {
                    LDFusionToolUtils.closeQuietly(loader);
                }
                throw e;
            }
        }
        return loaders;
    }

    /**
     * Initializes data sources from configuration.
     * @return initialized data sources
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException I/O error
     */
    protected Collection<DataSource> getDataSources() throws LDFusionToolException {
        List<DataSource> dataSources = new ArrayList<>(config.getDataSources().size());
        for (DataSourceConfig dataSourceConfig : config.getDataSources()) {
            try {
                DataSource dataSource = DataSourceImpl.fromConfig(dataSourceConfig, config.getPrefixes(), repositoryFactory);
                dataSources.add(dataSource);
            } catch (LDFusionToolException e) {
                // clean up already initialized repositories
                for (DataSource initializedDataSource : dataSources) {
                    try {
                        initializedDataSource.getRepository().shutDown();
                    } catch (RepositoryException e2) {
                        // ignore
                    }
                }
                throw e;
            }
        }
        return dataSources;
    }

    /**
     * Initializes construct sources from configuration.
     * @param constructSourceConfigs configuration for data sources
     * @return initialized construct sources
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException I/O error
     */
    protected Collection<ConstructSource> getConstructSources(List<ConstructSourceConfig> constructSourceConfigs)
            throws LDFusionToolException {
        List<ConstructSource> constructSources = new ArrayList<>();
        for (ConstructSourceConfig constructSourceConfig : constructSourceConfigs) {
            try {
                ConstructSource constructSource =
                        ConstructSourceImpl.fromConfig(constructSourceConfig, config.getPrefixes(), repositoryFactory);
                constructSources.add(constructSource);
            } catch (LDFusionToolException e) {
                // clean up already initialized repositories
                for (ConstructSource initializedDataSource : constructSources) {
                    try {
                        initializedDataSource.getRepository().shutDown();
                    } catch (RepositoryException e2) {
                        // ignore
                    }
                }
                throw e;
            }
        }
        return constructSources;
    }

    /**
     * Returns metadata for conflict resolution.
     * @return metadata for conflict resolution
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException error
     */
    @Override
    public Model getMetadata() throws LDFusionToolException {
        Collection<ConstructSource> metadataSources = getConstructSources(config.getMetadataSources());
        Model metadata = new TreeModel();
        for (ConstructSource source : metadataSources) {
            MetadataLoader loader = new MetadataLoader(source);
            loader.loadNamedGraphsMetadata(metadata);
        }
        return metadata;
    }

    /**
     * Reads and resolves sameAs links and returns the result canonical URI mapping.
     * @return canonical URI mapping
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException error
     * @throws java.io.IOException I/O error
     */
    @Override
    public UriMappingIterable getUriMapping() throws LDFusionToolException, IOException {
        // FIXME: preference of prefixes from configuration
        Set<String> preferredURIs = getPreferredURIs(
                config.getPropertyResolutionStrategies().keySet(),
                config.getCanonicalURIsInputFile(),
                config.getPreferredCanonicalURIs());
        UriMappingIterableImpl uriMapping = new UriMappingIterableImpl(preferredURIs);

        // TODO: rework
        List<ConstructSourceConfig> repositorySameAsSourcesConfig = new ArrayList<>();
        List<ConstructSourceConfig> fileSameAsSourcesConfig = new ArrayList<>();
        for (ConstructSourceConfig sourceConfig : config.getSameAsSources()) {
            if (sourceConfig.getType() == EnumDataSourceType.FILE) {
                fileSameAsSourcesConfig.add(sourceConfig);
            } else {
                repositorySameAsSourcesConfig.add(sourceConfig);
            }
        }

        for (ConstructSourceConfig source : fileSameAsSourcesConfig) {
            SameAsLinkFileLoader loader = new SameAsLinkFileLoader(source, config.getParserConfig(), config.getSameAsLinkTypes());
            loader.loadSameAsMappings(uriMapping);
        }

        Collection<ConstructSource> repositorySameAsSources = getConstructSources(repositorySameAsSourcesConfig);
        for (ConstructSource source : repositorySameAsSources) {
            SameAsLinkRepositoryLoader loader = new SameAsLinkRepositoryLoader(source);
            loader.loadSameAsMappings(uriMapping);
        }
        return uriMapping;
    }

    /**
     * Returns set of URIs preferred for canonical URIs.
     * The URIs are loaded from canonicalURIsInputFile if given and URIs present in settingsPreferredURIs are added.
     * @param settingsPreferredURIs URIs occurring on fusion tool configuration
     * @param canonicalURIsInputFile file with canonical URIs to be loaded; can be null
     * @param preferredCanonicalURIs default set of preferred canonical URIs
     * @return set of URIs preferred for canonical URIs
     * @throws java.io.IOException error reading canonical URIs from file
     */
    protected static Set<String> getPreferredURIs(
            Set<URI> settingsPreferredURIs, File canonicalURIsInputFile,
            Collection<String> preferredCanonicalURIs) throws IOException {

        Set<String> preferredURIs = new HashSet<>(settingsPreferredURIs.size());
        for (URI uri : settingsPreferredURIs) {
            preferredURIs.add(uri.stringValue());
        }
        if (canonicalURIsInputFile != null) {
            new CanonicalUriFileHelper().readCanonicalUris(canonicalURIsInputFile, preferredURIs);
        }
        preferredURIs.addAll(preferredCanonicalURIs);

        return preferredURIs;
    }

    /**
     * Returns collections of seed subjects, i.e. the initial URIs for which
     * corresponding quads are loaded and resolved.
     * @param dataSources initialized data sources
     * @param seedResourceRestriction SPARQL restriction on URI resources which are initially loaded and processed
     * or null to iterate all subjects
     * @return collection of seed subject URIs
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException query error
     */
    protected UriCollection getSeedSubjects(Collection<DataSource> dataSources, SparqlRestriction seedResourceRestriction)
            throws LDFusionToolException {
        FederatedSeedSubjectsLoader loader = new FederatedSeedSubjectsLoader(dataSources);
        return loader.getTripleSubjectsCollection(seedResourceRestriction);
    }

    /**
     * Creates factory object for large collections depending on configuration.
     * If cache is enabled, the collection is backed by a file, otherwise kept in memory.
     * @return factory for large collections
     * @throws java.io.IOException I/O error
     */
    protected LargeCollectionFactory createLargeCollectionFactory() throws IOException {
        if (config.getEnableFileCache()) {
            return new MapdbCollectionFactory(config.getTempDirectory());
        } else {
            return new MemoryCollectionFactory();
        }
    }

    /**
     * Creates and initializes output writer (which can be composed of multiple writers if multiple outputs are defined).
     * @return output writer
     * @throws java.io.IOException I/O error
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException configuration error
     */
    @Override
    public CloseableRDFWriter getRDFWriter() throws IOException, LDFusionToolException {
        List<CloseableRDFWriter> writers = new ArrayList<>(config.getOutputs().size());
        for (Output output : config.getOutputs()) {
            CloseableRDFWriter writer = rdfWriterFactory.createRDFWriter(output);
            writers.add(writer);
            writeNamespaceDeclarations(writer, config.getPrefixes());
        }

        return writers.size() == 1
                ? writers.get(0)
                : new FederatedRDFWriter(writers);
    }

    /**
     * Writes namespace declarations to the given output writer.
     * @param writer output writer
     * @param nsPrefixes map of namespace prefixes
     * @throws java.io.IOException I/O error
     */
    protected void writeNamespaceDeclarations(CloseableRDFWriter writer, Map<String, String> nsPrefixes) throws IOException {
        for (Map.Entry<String, String> entry : nsPrefixes.entrySet()) {
            writer.addNamespace(entry.getKey(), entry.getValue());
        }
    }

    /**
     * Creates conflict resolver initialized according to given configuration.
     * @param metadata metadata for conflict resolution
     * @param uriMapping mapping of URIs to their canonical URI
     * @return initialized conflict resolver
     */
    @Override
    public ResourceDescriptionConflictResolver getConflictResolver(Model metadata, UriMappingIterable uriMapping) {
        DistanceMeasureImpl distanceMeasure = new DistanceMeasureImpl();
        SourceQualityCalculator sourceQualityCalculator = new ODCSSourceQualityCalculator(
                config.getScoreIfUnknown(),
                config.getPublisherScoreWeight());
        ResolutionFunctionRegistry registry = ConflictResolverFactory.createInitializedResolutionFunctionRegistry(
                sourceQualityCalculator,
                config.getAgreeCoefficient(),
                distanceMeasure);
        NestedResourceDescriptionQualityCalculatorImpl nestedResourceDescriptionQualityCalculator = new NestedResourceDescriptionQualityCalculatorImpl(
                new DecidingConflictFQualityCalculator(sourceQualityCalculator, config.getAgreeCoefficient(), distanceMeasure));

        // TODO
        //if (config.getOutputConflictsOnly()) {
        //    builder.setConflictClusterFilter(new ConflictingClusterConflictClusterFilter());
        //}
        return new ResourceDescriptionConflictResolverImpl(
                registry,
                new ConflictResolutionPolicyImpl(config.getDefaultResolutionStrategy(), config.getPropertyResolutionStrategies()),
                uriMapping,
                metadata,
                config.getResultDataURIPrefix() + ODCSInternal.QUERY_RESULT_GRAPH_URI_INFIX + "/",
                nestedResourceDescriptionQualityCalculator
        );
    }

    @Override
    public UriMappingWriter getCanonicalUriWriter(UriMappingIterable uriMapping) throws IOException {
        return new CanonicalUriFileWriter(config.getCanonicalURIsOutputFile());
    }

    /**
     * Returns writer for owl:sameAs links according to the given URI mapping to given outputs.
     * @throws java.io.IOException I/O error
     */
    @Override
    public UriMappingWriter getSameAsLinksWriter() throws IOException {
        return new SameAsLinkWriter(config.getOutputs(), config.getPrefixes());
    }

    /**
     * Indicates whether a source of type {@link cz.cuni.mff.odcleanstore.fusiontool.config.EnumDataSourceType#VIRTUOSO} is present in the given data sources.
     * @param sources configuration of data sources
     * @return true iff sources contain a Virtuoso data source
     */
    protected boolean hasVirtuosoSource(List<DataSourceConfig> sources) {
        for (DataSourceConfig sourceConfig : sources) {
            if (sourceConfig.getType() == EnumDataSourceType.VIRTUOSO) {
                return true;
            }
        }
        return false;
    }

    /**
     * Calculates maximum memory limit available for data structures.
     * @return memory limit in bytes
     */
    protected long calculateMemoryLimit() {
        return Math.min(
                config.getMemoryLimit() != null ? config.getMemoryLimit() : Long.MAX_VALUE,
                (long) (ExternalSort.estimateAvailableMemory() * config.getMaxFreeMemoryUsage()));
    }

    public ProfilingTimeCounter<EnumFusionCounters> getExecutorTimeProfiler() {
        return executorTimeProfiler;
    }

    public MemoryProfiler getExecutorMemoryProfiler() {
        return executorMemoryProfiler;
    }
}


text:
package service

import (
	"context"

	"go-common/app/job/main/passport-encrypt/model"
	"go-common/library/log"
)

// fullMigration full migration
func (s *Service) fullMigration(start, end, inc, limit int64, group string) {
	var count int64

	for {
		log.Info(" group is %s,start %d, end %d,inc %d,limit %d", group, start, end, inc, limit)
		var (
			res      []*model.OriginAccount
			err      error
			effected int64
		)
		if res, err = s.d.AsoAccounts(context.TODO(), start, end); err != nil {
			log.Error("error is (%+v)\n", err)
			break
		}

		for _, acc := range res {
			enAcc := EncryptAccount(acc)
			if effected, err = s.d.AddAsoAccount(context.TODO(), enAcc); err != nil || effected == 0 {
				log.Error("insert error (%+v)", err)
			}
		}
		start = end
		count = end
		end = end + inc

		if count >= limit {
			break
		}
	}
}


text:
import sys
import pandas as pd
import numpy as np
from sklearn.preprocessing import RobustScaler
from sklearn.ensemble import GradientBoostingClassifier
from evaluate_model import evaluate_model

dataset = sys.argv[1]
num_param_combinations = int(sys.argv[2])
random_seed = int(sys.argv[3])

np.random.seed(random_seed)

pipeline_components = [RobustScaler, GradientBoostingClassifier]
pipeline_parameters = {}

n_estimators_values = np.random.choice(list(range(50, 1001, 50)), size=num_param_combinations)
min_impurity_decrease_values = np.random.exponential(scale=0.01, size=num_param_combinations)
max_features_values = np.random.choice(list(np.arange(0.01, 1., 0.01)) + ['sqrt', 'log2', None], size=num_param_combinations)
learning_rate_values = np.random.uniform(low=1e-10, high=5., size=num_param_combinations)
loss_values = np.random.choice(['deviance', 'exponential'], size=num_param_combinations)
max_depth_values = np.random.choice(list(range(1, 51)) + [None], size=num_param_combinations)

all_param_combinations = zip(n_estimators_values, min_impurity_decrease_values, max_features_values, learning_rate_values, loss_values, max_depth_values)
pipeline_parameters[GradientBoostingClassifier] = \
   [{'n_estimators': n_estimators, 'min_impurity_decrease': min_impurity_decrease, 'max_features': max_features, 'learning_rate': learning_rate, 'loss': loss, 'max_depth': max_depth, 'random_state': 324089}
     for (n_estimators, min_impurity_decrease, max_features, learning_rate, loss, max_depth) in all_param_combinations]

evaluate_model(dataset, pipeline_components, pipeline_parameters)


text:
// #define ENABLE_CTK_WIDGETS_WIDGET

#include "QmitkMultiLabelSegmentationUtilitiesView.h"
#include "BooleanOperations/QmitkBooleanOperationsWidget.h"
#include "MorphologicalOperations/QmitkMorphologicalOperationsWidget.h"
#include "SurfaceToImage/QmitkSurfaceToImageWidget.h"
#include "ImageMasking/QmitkImageMaskingWidget.h"

QmitkMultiLabelSegmentationUtilitiesView::QmitkMultiLabelSegmentationUtilitiesView() :
m_BooleanOperationsWidget(NULL),
m_MorphologicalOperationsWidget(NULL),
m_SurfaceToImageWidget(NULL),
m_ImageMaskingWidget(NULL)
{
}

QmitkMultiLabelSegmentationUtilitiesView::~QmitkMultiLabelSegmentationUtilitiesView()
{
}

void QmitkMultiLabelSegmentationUtilitiesView::CreateQtPartControl(QWidget* parent)
{
  m_Controls.setupUi(parent);

  mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart();

  mitk::SliceNavigationController* timeNavigationController = renderWindowPart != NULL
    ? renderWindowPart->GetTimeNavigationController()
    : NULL;

  m_BooleanOperationsWidget = new QmitkBooleanOperationsWidget(timeNavigationController, parent);

  m_MorphologicalOperationsWidget = new QmitkMorphologicalOperationsWidget(timeNavigationController, parent);

  m_SurfaceToImageWidget = new QmitkSurfaceToImageWidget(timeNavigationController, parent);

  m_ImageMaskingWidget = new QmitkImageMaskingWidget(timeNavigationController, parent);

  this->AddUtilityWidget(m_BooleanOperationsWidget, QIcon(":/MultiLabelSegmentationUtilities/BooleanOperations_48x48.png"), "Boolean Operations");

  this->AddUtilityWidget(m_MorphologicalOperationsWidget, QIcon(":/MultiLabelSegmentationUtilities/MorphologicalOperations_48x48.png"), "Morphological Operations");

  this->AddUtilityWidget(m_SurfaceToImageWidget, QIcon(":/MultiLabelSegmentationUtilities/SurfaceToImage_48x48.png"), "Surface To Image");

  this->AddUtilityWidget(m_ImageMaskingWidget, QIcon(":/MultiLabelSegmentationUtilities/ImageMasking_48x48.png"), "Image Masking");
}

void QmitkMultiLabelSegmentationUtilitiesView::AddUtilityWidget(QWidget* widget, const QIcon& icon, const QString& text)
{
  m_Controls.toolBox->addItem(widget, icon, text);
}

void QmitkMultiLabelSegmentationUtilitiesView::SetFocus()
{
  m_Controls.toolBox->setFocus();
}

void QmitkMultiLabelSegmentationUtilitiesView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
  mitk::SliceNavigationController* timeNavigationController = renderWindowPart->GetTimeNavigationController();

  m_BooleanOperationsWidget->SetTimeNavigationController(timeNavigationController);
  m_MorphologicalOperationsWidget->SetTimeNavigationController(timeNavigationController);
  m_SurfaceToImageWidget->SetTimeNavigationController(timeNavigationController);
  m_ImageMaskingWidget->SetTimeNavigationController(timeNavigationController);
}

void QmitkMultiLabelSegmentationUtilitiesView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*)
{
  m_BooleanOperationsWidget->SetTimeNavigationController(NULL);
  m_MorphologicalOperationsWidget->SetTimeNavigationController(NULL);
  m_SurfaceToImageWidget->SetTimeNavigationController(NULL);
  m_ImageMaskingWidget->SetTimeNavigationController(NULL);
}


text:
package org.apache.ambari.server.controller.metrics.timeline.cache;

import java.util.Set;

import org.apache.ambari.server.controller.spi.TemporalInfo;

/**
 * Cache contents represent metrics for an App / Cluster.
 * This is designed to work on the premise that a client makes same requests
 * over and over, so this caching strategy allows us to send a http request
 * for multiple metrics in the same query and ensure parallelization on the
 * metrics backend side as well.
 */
public class TimelineAppMetricCacheKey {
  private final Set<String> metricNames;
  private final String appId;
  private final String hostNames;
  private String spec;
  private TemporalInfo temporalInfo;

  public TimelineAppMetricCacheKey(Set<String> metricNames, String appId,
                                   String hostNames, TemporalInfo temporalInfo) {
    this.metricNames = metricNames;
    this.appId = appId;
    this.hostNames = hostNames;
    this.temporalInfo = temporalInfo;
  }

  public TimelineAppMetricCacheKey(Set<String> metricNames, String appId,
                                   TemporalInfo temporalInfo) {
    this(metricNames, appId, null, temporalInfo);
  }

  public Set<String> getMetricNames() {
    return metricNames;
  }

  /**
   * Temporal info is used to calculate the next query window,
   * it does not contribute to the key behavior.
   * @return @TemporalInfo
   */
  public TemporalInfo getTemporalInfo() {
    return temporalInfo;
  }

  /**
   * Set temporalInfo to new query window each time.
   * @param temporalInfo @TemporalInfo
   */
  public void setTemporalInfo(TemporalInfo temporalInfo) {
    this.temporalInfo = temporalInfo;
  }

  public String getAppId() {
    return appId;
  }

  public String getHostNames() {
    return hostNames;
  }

  /**
   * Actual http request Uri, this does not contribute to the key behavior,
   * it is used solely for interoperability between @AMSPropertyProvider.MetricsRequest
   * and the Cache.
   * @return Request Uri
   */
  public String getSpec() {
    return spec;
  }

  /**
   * Set spec string.
   * @param spec Request Uri
   */
  public void setSpec(String spec) {
    this.spec = spec;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    TimelineAppMetricCacheKey that = (TimelineAppMetricCacheKey) o;

    if (!metricNames.equals(that.metricNames)) return false;
    if (!appId.equals(that.appId)) return false;
    return !(hostNames != null ? !hostNames.equals(that.hostNames) : that.hostNames != null);

  }

  @Override
  public int hashCode() {
    int result = metricNames.hashCode();
    result = 31 * result + appId.hashCode();
    result = 31 * result + (hostNames != null ? hostNames.hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "TimelineAppMetricCacheKey{" +
      "metricNames=" + metricNames +
      ", appId='" + appId + '\'' +
      ", hostNames=" + hostNames +
      ", spec='" + spec + '\'' +
      '}';
  }
}


text:
package org.apache.camel.processor;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.camel.CamelExchangeException;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;

/**
 * @version
 */
public class SplitterParallelStopOnExceptionTest extends ContextTestSupport {

    public void testSplitParallelStopOnExceptionOk() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:split");
        mock.expectedBodiesReceivedInAnyOrder("Hello World", "Bye World");

        template.sendBody("direct:start", "Hello World,Bye World");

        assertMockEndpointsSatisfied();
    }

    public void testSplitParallelStopOnExceptionStop() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:split");
        mock.expectedMinimumMessageCount(0);
        mock.allMessages().body().isNotEqualTo("Kaboom");

        try {
            template.sendBody("direct:start", "Hello World,Goodday World,Kaboom,Bye World");
            fail("Should thrown an exception");
        } catch (CamelExecutionException e) {
            ExecutionException ee = assertIsInstanceOf(ExecutionException.class, e.getCause());
            CamelExchangeException cause = assertIsInstanceOf(CamelExchangeException.class, ee.getCause());
            assertTrue(cause.getMessage().startsWith("Parallel processing failed for number "));
            assertTrue(cause.getMessage().contains("Exchange[Message: Kaboom]"));
            assertEquals("Forced", cause.getCause().getMessage());
        }

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // use a pool with 2 concurrent tasks so we cannot run to fast
                ExecutorService service = Executors.newFixedThreadPool(2);

                from("direct:start")
                        .split(body().tokenize(",")).parallelProcessing().stopOnException().executorService(service)
                        .process(new Processor() {
                            public void process(Exchange exchange) throws Exception {
                                String body = exchange.getIn().getBody(String.class);
                                if ("Kaboom".equals(body)) {
                                    throw new IllegalArgumentException("Forced");
                                }
                            }
                        }).to("mock:split");
            }
        };
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/toolbar"/>

    <net.yanzm.mth.MaterialTabHost
        android:id="@+id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
package scala2ch.session

import org.scalatest.{MustMatchers, WordSpecLike}
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

class SessionTest extends WordSpecLike with MustMatchers {
  "Session" must {

    "get key-value pair" in {
      val session = SessionStore(Map("key" -> "value"))
      session.get("key") must be(Some("value"))
      session.get("unknown") must be(None)
    }

    "save and get key-value pair" in {
      val session = SessionStore(Map.empty[String, String])
      Await.result(session.save("key", "value"), 5 seconds)
      session.get("key") must be(Some("value"))
    }
  }
}


text:
module Admin
  class User < ActiveRecord::Base

    # build roles
    enum role: {user: 0, editor: 1, admin: 2}

    after_initialize :set_default_role, :if => :new_record?

    def set_default_role
      self.role ||= :user
    end

    def to_s
      email
    end

    # Adds `can_create?(resource)`, etc
    include Authority::UserAbilities

    # Adds `creatable_by?(user)`, etc
    include Authority::Abilities

    # Set authorizer class to UserAuthorizer
    self.authorizer_name = 'UserAuthorizer'

    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable, :validatable
  end
end


text:
import {useCallback, useEffect, useRef, useState} from 'react';
import * as React from 'react';
import {Payment, PaymentId} from '@pim/common';
import {getPayment, savePayment} from '../../services/server-api';
import {PrimaryButton, DefaultButton, Stack, TextField, Toggle, Spinner, ITextField} from '@fluentui/react'
import {PanelProps} from '../../common/panel.types';
import {CategoryDropdown} from './category-dropdown';
import {currencyRadioOptions, defaultCurrency} from '../currencies';
import {horizontalChoiceGroup, stackTokens, StyledChoiceGroup} from '../styles';
import {CurrencyInput} from '../currency-input';
import {formatDay} from '../../common/date.utils';

export const PaymentForm: React.FC<PanelProps<PaymentId>> = ({onClose, id}) => {
    const {
        payment,
        updatePayment,
        updateCurrency,
        updateCategory,
        submitForm,
        saveAndClose,
        showIncurredDates,
        setShowIncurredDates,
        formStartRef
    } = usePaymentForm(onClose, id);

    if (!payment) return <Spinner />;

    return (
      <form>
        <Stack tokens={stackTokens}>
            <Stack horizontal tokens={stackTokens}>
                <TextField
                   styles={{root: {flex: 1}}}
                   componentRef={formStartRef}
                   label={'Date'}
                   type="date"
                   onChange={updatePayment}
                   value={formatDay(payment.paidDate)}
                   name="paidDate"/>

                <Toggle
                    label={'Incurred'}
                    checked={showIncurredDates}
                    onChange={(_, val) => setShowIncurredDates(val)}/>
            </Stack>
            {
                showIncurredDates &&
                <>
                    <TextField
                        label={'Incurred Begin'}
                        type="date"
                        onChange={updatePayment}
                        value={payment.incurredBeginDate ? formatDay(payment.incurredBeginDate) : undefined}
                        name="incurredBeginDate"/>

                    <TextField
                        label={'Incurred End'}
                        type="date"
                        onChange={updatePayment}
                        value={payment.incurredEndDate ? formatDay(payment.incurredEndDate) : undefined}
                        name="incurredEndDate"/>
                </>
            }

            <TextField
                label="Counterparty"
                name="counterparty"
                value={payment.counterparty}
                onChange={updatePayment}
            />

            <StyledChoiceGroup
                selectedKey={payment.currency}
                label="Currency"
                styles={horizontalChoiceGroup}
                onChange={updateCurrency}
                options={currencyRadioOptions}/>

            <CurrencyInput
                amount={payment.amount}
                currency={payment.currency}
                name="amount"
                onChange={updatePayment}
            />

            <CategoryDropdown
                showLabel
                value={payment.categoryId}
                onChange={updateCategory}>
            </CategoryDropdown>

            <TextField
                label="Notes"
                name="note"
                value={payment.note}
                multiline
                onChange={updatePayment}/>

            <Stack horizontal tokens={stackTokens}>
                <PrimaryButton onClick={submitForm}>Save</PrimaryButton>
                {
                    !id &&
                    <PrimaryButton onClick={saveAndClose}>Save & Close</PrimaryButton>
                }

                <DefaultButton onClick={onClose}>Cancel</DefaultButton>
            </Stack>

        </Stack>
    </form>
  )
}

function usePaymentForm(onClose: () => void, paymentId?: PaymentId, ) {
    const [showIncurredDates, setShowIncurredDates] = useState<boolean>(false);
    const [payment, setPayment] = useState<Payment>(paymentId ? null : initializePayment())
    const formStartRef = useRef<ITextField>();

    useEffect(() => {
        if (paymentId) {
            getPayment(paymentId)
                .then(payment => {
                    if (payment.incurredBeginDate || payment.incurredEndDate) {
                        setShowIncurredDates(true);
                    }
                    return payment;
                })
                .then(setPayment)
            //TODO cleanup - if the panel is closed before the request finishes an error is thrown
        }
    }, [paymentId])

    const updateCurrency = useCallback((_, {key}) => {
        setPayment({
            ...payment,
            currency: key
        })
    }, [payment])

    const updateCategory = useCallback((categoryId) => {
        setPayment({
            ...payment,
            categoryId
        });
    }, [payment])

    const updatePayment = useCallback(({target}) => {
        setPayment({
            ...payment,
            [target.name]: target.value
        })
    }, [payment])

    const saveAndClose  = useCallback(async () => {
        await savePayment(preparePayment(payment, showIncurredDates))
        onClose();
    }, [payment, onClose, showIncurredDates])

    /**
     * submit changes its behavior depending on whether this is a new payment (form stays open, another payment is added)
     * or editing an existing payment (close the form).
     */
    const submitForm = useCallback(async () => {
        if (payment.id !== -1) {
            await saveAndClose();
        } else {
            await savePayment(preparePayment(payment, showIncurredDates))
            setShowIncurredDates(false)
            setPayment(initializePayment(payment.paidDate))
            formStartRef.current.focus();
        }
    }, [payment, saveAndClose, showIncurredDates])
    return {
        payment,
        updatePayment,
        updateCategory,
        updateCurrency,
        submitForm,
        saveAndClose,
        showIncurredDates,
        setShowIncurredDates,
        formStartRef
    };
}

const preparePayment = (payment: Payment, useIncurredDates: boolean): Payment => ({
    ...payment,
    incurredBeginDate: useIncurredDates ? payment.incurredBeginDate : null,
    incurredEndDate: useIncurredDates ? payment.incurredEndDate : null,
})

function initializePayment(paidDate = formatDay(new Date())): Payment {
  return {
    id: -1,
    paidDate,
    incurredBeginDate: paidDate,
    incurredEndDate: paidDate,
    categoryId: -1,
    amount: null,
    counterparty: '',
    currency: defaultCurrency,
    note: ''
  };
}


text:
<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <script src="require.js" data-main="scripts/main"></script>
    </body>
</html>


text:
package org.locationtech.geowave.analytic.mapreduce.operations;

import org.locationtech.geowave.core.cli.annotations.GeowaveOperation;
import org.locationtech.geowave.core.cli.api.DefaultOperation;
import org.locationtech.geowave.core.cli.operations.GeoWaveTopLevelSection;
import com.beust.jcommander.Parameters;

@GeowaveOperation(name = "analytic", parentOperation = GeoWaveTopLevelSection.class)
@Parameters(commandDescription = "Commands to run analytics on GeoWave data sets")
public class AnalyticSection extends DefaultOperation {
}


text:
[ci-image]: https://img.shields.io/github/workflow/status/webtorrent/torrent-piece/ci/master
[ci-url]: https://github.com/webtorrent/torrent-piece/actions
[npm-image]: https://img.shields.io/npm/v/torrent-piece.svg
[npm-url]: https://npmjs.org/package/torrent-piece
[downloads-image]: https://img.shields.io/npm/dm/torrent-piece.svg
[downloads-url]: https://npmjs.org/package/torrent-piece
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com

### Torrent piece abstraction

[![Sauce Test Status](https://saucelabs.com/browser-matrix/torrent-piece.svg)](https://saucelabs.com/u/torrent-piece)

Also works in the browser with [browserify](http://browserify.org/)! This module is used by [WebTorrent](http://webtorrent.io) and [torrent-stream](https://npmjs.com/package/torrent-stream).

## install

```
npm install torrent-piece
```

## usage

```js
const Piece = require('torrent-piece')

Piece.BLOCK_LENGTH // 16384

const pieceLength = Piece.BLOCK_LENGTH * 5
const piece = new Piece(pieceLength)
piece.missing // 81920

piece.reserve() // 0
piece.set(0, someBuffer0)

piece.reserve() // 1
piece.reserve() // 2
piece.reserve() // 3

piece.set(1, someBuffer1)
piece.set(2, someBuffer2)
piece.set(3, someBuffer3)

piece.reserve() // 4
piece.cancel(4) // cancel the reservation of a chunk

piece.reserve() // 4 (given out again)
piece.set(4, someBuffer4)

// handy functions
piece.chunkLength(0) // 16384
piece.chunkOffset(0) // 0

// eventually, when no more chunks left...

piece.reserve() // -1 (signal that all chunks are reserved)
piece.missing // 0

const pieceBuffer = piece.flush()
console.log(pieceBuffer)
```

## license

MIT. Copyright (c) [Feross Aboukhadijeh](https://feross.org) and [WebTorrent, LLC](https://webtorrent.io).


text:
apt_update 'update' if platform_family?('debian')

include_recipe 'apparmor::default'

apparmor_policy 'my_policy' do
  action :add
end


text:
class DoNothingYet < ActiveRecord::Migration
	def up
		puts "****** adding admin_users"
	end
	def down
	end
end