text:
package com.example.kevin.wear_where.AsyncTask;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;

import com.example.kevin.wear_where.Google.Distance.DistanceMatrixObject;
import com.example.kevin.wear_where.Google.TimeZone.TimeZoneObject;
import com.example.kevin.wear_where.MapInformation.MapInformation;
import com.example.kevin.wear_where.WundergroundData.HourlyForecast.HourlyItem;
import com.example.kevin.wear_where.WundergroundData.HourlyForecast.HourlyObject;
import com.example.kevin.wear_where.wear.Clothing;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

/**
 * Created by Hermes on 10/23/2016.
 */

public class IntervalInformationAST extends AsyncTask<Void, Void, MapInformation> {

    /* NOTE: For all arrays involving intervals, the order is as follows:
     * Index 0 = Starting Point
     * Index 1 = First interval after starting
     * Index 2 = Second interval after starting
     * ...
     * Index ArrayList<>.size() - 1 = Ending Point
     */

    // ArrayList to keep track of the intervals to get set up markers for
    private ArrayList<LatLng> intervals;

    // ArrayLists to keep information used for the ExpandableListView
    private ArrayList<String> intervalTitles, intervalDetails;

    // ArrayList of ArrayList to keep clothing suggestions for each interval
    private ArrayList<String> intervalTemperatures;

    // ArrayList to keep track of the markers for each interval
    private ArrayList<MarkerOptions> intervalInformation;

    // DistanceMatrixObject containing the information for the Google Distance Matrix API (distance between starting point and each interval)
    private DistanceMatrixObject distanceMatrixObject = null;

    // ArrayList to keep track of the Google Time Zone API information for each interval
    private ArrayList<TimeZoneObject> intervalTimeZones;

    // ArrayList to keep track of the Wunderground 10 Day Hourly API information for each interval
    private ArrayList<HourlyItem> mapsHourlyForecast;

    // Get the current UTC Epoch Time in milliseconds
    private Long currentTimeSeconds = System.currentTimeMillis() - ((new GregorianCalendar().getTimeZone().getRawOffset()) + new GregorianCalendar().getTimeZone().getDSTSavings());

    public IntervalInformationAST(final ArrayList<LatLng> intervals) {

        // Save parameter for future use
        this.intervals = intervals;

        // Initialize the ArrayLists for the AsyncTasks
        intervalInformation = new ArrayList<>();
        intervalTimeZones = new ArrayList<>();
        mapsHourlyForecast = new ArrayList<>();
        intervalTitles = new ArrayList<>();
        intervalDetails = new ArrayList<>();
        intervalTemperatures = new ArrayList<>();

        // Begin GoogleDistanceAST
        try {
            distanceMatrixObject = new GoogleDistanceAST(intervals).execute().get();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // Get indexes of each interval for retrieving weather info
        int[] hourlyIndices = new int[intervals.size()];
        for (int i = 0; i < intervals.size(); ++i) {

            // Get the duration for the current interval in milliseconds
            Long intervalDuration = Long.parseLong((distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDuration().getSeconds())) * 1000;

            // Add the index for getting the correct hourly information (the index is how many hours it takes to get to the current interval location)
            int index = (int) (intervalDuration / (3600 * 1000));

            if (index <= 239) {
                hourlyIndices[i] = index;
            }

            else {
                hourlyIndices[i] = -1;
            }
        }

        // For each object in the intervals ArrayList, get the corresponding HourlyObject
        for (int i = 0; i < intervals.size(); ++i) {
            try {
                mapsHourlyForecast.add(new MapsForecastAST(intervals.get(i), hourlyIndices[i]).execute().get());
            }

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

        // For each object in the intervals ArrayList, get the corresponding TimeZoneObject
        for (int i = 0; i < intervals.size(); ++i) {

            // Begin GoogleTimeZoneAST (if all goes well, the AsyncTasks will complete in the order they started)
            new GoogleTimeZoneAST(intervals.get(i), currentTimeSeconds/1000) {

                @Override
                protected void onPostExecute(TimeZoneObject item) {

                    // Add the TimeZoneObject returned to the mapsHourlyForecast (if all goes well, the order of objects added will correspond to the order of intervals)
                    intervalTimeZones.add(item);

                }

            }.execute();

        }

    }

    @Override
    protected MapInformation doInBackground(Void... params) throws IllegalStateException {

        // Don't proceed until we have all information for all intervals
        while (intervals.size() != mapsHourlyForecast.size() && intervals.size() != intervalTimeZones.size()) {
        }

        // Get the current UTC Epoch Time in milliseconds
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        Long currentTime = gregorianCalendar.getTimeInMillis() - gregorianCalendar.getTimeZone().getRawOffset();

        // Create the list of MarkerOptions to add to the map
        for (int i = 0; i < intervals.size(); ++i) {

            // Get the duration for the current interval in milliseconds
            Long intervalDuration = Long.parseLong((distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDuration().getSeconds())) * 1000;

            // Get the DST offset in milliseconds from the TimeZoneObject corresponding to the current object
            Long endingDSTOffset = Long.parseLong(intervalTimeZones.get(i).getDstOffset()) * 1000;

            // Get the Raw offset in milliseconds from the TimeZoneObject corresponding to the current object
            Long endingRawOffset = Long.parseLong(intervalTimeZones.get(i).getRawOffset()) * 1000;

            // Create the string representing the estimated time of arrival to the current interval point
            String estimatedTimeOfArrival = new java.text.SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").format(new java.util.Date(currentTime + intervalDuration + (endingDSTOffset + endingRawOffset))) + '\n' + intervalTimeZones.get(i).getTimeZoneName();

            // Declare the strings that will be used to represent the precipitation, temperature (in farenheit), and the iconURL
            String precipitation, temperatureF, iconURL;

            // If the index is within range of the 10 days, then initialize the strings to the correct information from the corresponding hourly object
            if (mapsHourlyForecast.get(i) != null) {
                precipitation = mapsHourlyForecast.get(i).getCondition();
                temperatureF = Integer.toString(mapsHourlyForecast.get(i).getTemperature().getTemperature()) + (char) 0x00B0 + " F";
                iconURL = mapsHourlyForecast.get(i).getIconURL();
            }

            // Else, tell the user that we cannot get information for this interval
            else {
                precipitation = "Cannot get hourly information more than 10 days ahead!";
                temperatureF = "";
                iconURL = "http://www.errorfixz.com/wp-content/uploads/2016/02/question_red.png";
            }

            // Declare bitmap variable to store the interval weather icon
            Bitmap bitmap;

            // Try and get the bitmap image from the icon url provided in the hourlyObject
            try {

                // Create a URL object with the link stored in iconURL
                URL request = new URL(iconURL);

                // Open a URL connection to link
                HttpURLConnection urlConnection = (HttpURLConnection) request.openConnection();

                // Set up the connection to take in the contents as input from the specified link in request
                urlConnection.setDoInput(true);

                // Connect to the link provided in request
                urlConnection.connect();

                // Store the input from the link provided in request
                InputStream input = urlConnection.getInputStream();

                // Create the bitmap from the input
                bitmap = BitmapFactory.decodeStream(input);

                // If we get a valid bitmap, then scale the bitmap according to screen density
                if (bitmap != null) {
                    bitmap = Bitmap.createScaledBitmap(bitmap, (int) (24 * Resources.getSystem().getDisplayMetrics().density), (int) (24 * Resources.getSystem().getDisplayMetrics().density), false);
                }

            }

            // If getting the image failed, return a null bitmap
            catch (Exception e) {
                return null;
            }

            // If i == 0, we are creating the marker for the starting point
            if (i == 0) {
                // Add the title string
                intervalTitles.add(distanceMatrixObject.getDestinationAddressesArray().getDestinationAddressesArrayItems().get(0));

                // Add the details string
                intervalDetails.add("Distance Travelled: " + distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDistance().getDistance() + '\n' +
                        "Time elapsed: " + distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDuration().getDuration() + "\n\n" +
                        "Time at beginning of trip: " + '\n' + estimatedTimeOfArrival + "\n\n" +
                        "Weather at beginning of trip: " + '\n' + precipitation + ", " + temperatureF + '\n');

                // Add the MarkerOption
                String parts[] = distanceMatrixObject.getDestinationAddressesArray().getDestinationAddressesArrayItems().get(0).split(", ", 2);
                intervalInformation.add(new MarkerOptions().position(intervals.get(0))
                        .title(parts[0] + "," + '\n' + parts[1])
                        .snippet("Time at beginning of trip: " + '\n' + estimatedTimeOfArrival + "\n\n" +
                                "Weather at beginning of trip: " + '\n' + precipitation + ", " + temperatureF)
                        .icon(BitmapDescriptorFactory.fromBitmap(bitmap)));

                // Add the temperature
                intervalTemperatures.add(Integer.toString(mapsHourlyForecast.get(i).getTemperature().getTemperature()));
            }

            // If i == interval.size() - 1, we are creating the marker for the ending point
            else if (i == intervals.size() - 1) {
                // Add the title string
                intervalTitles.add(distanceMatrixObject.getDestinationAddressesArray().getDestinationAddressesArrayItems().get(i));

                // Add the details string
                intervalDetails.add("Distance Travelled: " + distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDistance().getDistance() + '\n' +
                        "Time elapsed: " + distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDuration().getDuration() + "\n\n" +
                        "Estimated Arrival Time (ETA): " + '\n' + estimatedTimeOfArrival + "\n\n" +
                        "Weather at ETA: " + '\n' + precipitation + ", " + temperatureF + '\n');

                // Add the MarkerOption
                String parts[] = distanceMatrixObject.getDestinationAddressesArray().getDestinationAddressesArrayItems().get(i).split(", ", 2);
                intervalInformation.add(new MarkerOptions().position(intervals.get(i))
                        .title(parts[0] + "," + '\n' + parts[1])
                        .snippet("Estimated Arrival Time (ETA): " + '\n' + estimatedTimeOfArrival + "\n\n" +
                                "Weather at ETA: " + '\n' + precipitation + ", " + temperatureF)
                        .icon(BitmapDescriptorFactory.fromBitmap(bitmap)));

                // Add the temperature
                intervalTemperatures.add(Integer.toString(mapsHourlyForecast.get(i).getTemperature().getTemperature()));
            }

            // Else, we are creating a marker for an interval point
            else {
                // Add the title string
                intervalTitles.add(distanceMatrixObject.getDestinationAddressesArray().getDestinationAddressesArrayItems().get(i));

                // Add the details string
                intervalDetails.add("Distance Travelled: " + distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDistance().getDistance() + '\n' +
                        "Time elapsed: " + distanceMatrixObject.getRowsArray().getElementsArray().getElementsArrayItems().get(i).getDuration().getDuration() + "\n\n" +
                        "Estimated Arrival Time (ETA): " + '\n' + estimatedTimeOfArrival + "\n\n" +
                        "Weather at ETA: " + '\n' + precipitation + ", " + temperatureF + '\n');

                // Add the MarkerOption
                String parts[] = distanceMatrixObject.getDestinationAddressesArray().getDestinationAddressesArrayItems().get(i).split(", ", 2);
                intervalInformation.add(new MarkerOptions().position(intervals.get(i))
                        .title(parts[0] + "," + '\n' + parts[1])
                        .snippet("Estimated Arrival Time (ETA): " + '\n' + estimatedTimeOfArrival + "\n\n" +
                                "Weather at ETA: " + '\n' + precipitation + ", " + temperatureF)
                        .icon(BitmapDescriptorFactory.fromBitmap(bitmap)));

                // Add the temperature
                intervalTemperatures.add(Integer.toString(mapsHourlyForecast.get(i).getTemperature().getTemperature()));
            }
        }

        // Return the ArrayList of MarkerOptions
        return new MapInformation(intervalInformation, intervalTitles, intervalDetails, intervalTemperatures);
    }
}


text:
namespace DVLib
{
	namespace UnitTests
	{
		TEST_CLASS(PathUtilUnitTests)
		{
			TEST_METHOD( testGetFileDirectory );
			TEST_METHOD( testGetFileName );
			TEST_METHOD( testGetModuleDirectory );
			TEST_METHOD( testGetModuleFileName );
			TEST_METHOD( testDirectoryCombine );
			TEST_METHOD( testGetTemporaryDirectory );
			TEST_METHOD( testGetCurrentDirectory );
			TEST_METHOD( testGetSystemDirectory );
			TEST_METHOD( testGetWindowsDirectory );
			TEST_METHOD( testGetSystemWindowsDirectory );
			TEST_METHOD( testStripPathTerminator );
		};
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.xy.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class DistributeUtil {

	public static void splitParallelCompute(List<Long> taskList, int taskUnit) {
        if (taskList == null || taskList.isEmpty()) {
            return ;
        }
        if (taskUnit <= 0) {
            taskUnit = 1;
        }
        Map<Integer, List<Long>> groupTaskMapList = new HashMap<Integer, List<Long>>();
        // 分成几组
        int taskTotalSize = taskList.size();
        int groupCount = taskTotalSize % taskUnit == 0 ? taskTotalSize / taskUnit : taskTotalSize / taskUnit + 1;

        Long func = null;
        List<Long> groupList = null;
        for (int i = 0; i < groupCount; i++) {
            int groupIndex = i * taskUnit;
            groupList = new ArrayList<Long>();
            int j = 0;
            while (j < taskUnit && groupIndex < taskTotalSize) {
                func = taskList.get(groupIndex++);
                if (func == null) {
                    continue;
                }
                groupList.add(func);
                j++;
            }
            groupTaskMapList.put(i + 1, groupList);
        }

        // 分批次调用
        for (Entry<Integer, List<Long>> entry : groupTaskMapList.entrySet()) {
            System.out.println(entry.getValue());
        }

    }
public static void main(String[] args) {
	List<Long> ids = Arrays.asList(1L,3L,4L,5L,7L,9L,12L,23L,34L);
	splitParallelCompute(ids,1);
}

}


text:
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package org.mozc.android.inputmethod.japanese.preference;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;

import org.mozc.android.inputmethod.japanese.MozcUtil;
import org.mozc.android.inputmethod.japanese.preference.ClientSidePreference.KeyboardLayout;
import org.mozc.android.inputmethod.japanese.preference.PreferenceUtil.CurrentKeyboardLayoutPreferenceChangeListener;
import org.mozc.android.inputmethod.japanese.preference.PreferenceUtil.PreferenceManagerInterface;
import org.mozc.android.inputmethod.japanese.resources.R;
import org.mozc.android.inputmethod.japanese.testing.InstrumentationTestCaseWithMock;
import org.mozc.android.inputmethod.japanese.testing.Parameter;
import com.google.common.base.Optional;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceGroup;
import android.test.mock.MockContext;
import android.test.mock.MockResources;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Xml;

/**
 */
public class PreferenceUtilTest extends InstrumentationTestCaseWithMock {

  @Override
  protected void tearDown() throws Exception {
    MozcUtil.setDevChannel(Optional.<Boolean>absent());
    super.tearDown();
  }

  @SmallTest
  public void testInitializeSpecialPreference() {
    Context context = getInstrumentation().getTargetContext();
    Preference preference = createMockBuilder(Preference.class)
        .withConstructor(Context.class)
        .withArgs(context)
        .addMockedMethods("setEnabled", "getKey", "setOnPreferenceClickListener")
        .addMockedMethod("setSummary", CharSequence.class)
        .createMock();
    PreferenceManagerInterface preferenceManager = createMock(PreferenceManagerInterface.class);

    // PREF_OTHER_USAGE_STATS_KEY, devChannel==true
    MozcUtil.setDevChannel(Optional.of(true));

    expect(preferenceManager.findPreference(PreferenceUtil.PREF_OTHER_USAGE_STATS_KEY))
        .andStubReturn(preference);
    expect(preferenceManager.findPreference(isA(String.class))).andStubReturn(null);
    preference.setSummary(isA(String.class));
    preference.setEnabled(false);
    replayAll();

    PreferenceUtil.initializeSpecialPreferencesInternal(preferenceManager);

    verifyAll();

    // PREF_OTHER_USAGE_STATS_KEY, devChannel==false
    resetAll();
    MozcUtil.setDevChannel(Optional.of(false));

    expect(preferenceManager.findPreference(PreferenceUtil.PREF_OTHER_USAGE_STATS_KEY))
        .andStubReturn(preference);
    expect(preferenceManager.findPreference(isA(String.class))).andStubReturn(null);
    preference.setSummary(isA(String.class));
    preference.setEnabled(true);
    replayAll();

    PreferenceUtil.initializeSpecialPreferencesInternal(preferenceManager);

    verifyAll();

    // PREF_ABOUT_VERSION
    resetAll();
    expect(preferenceManager.findPreference(PreferenceUtil.PREF_ABOUT_VERSION))
        .andStubReturn(preference);
    expect(preferenceManager.findPreference(isA(String.class))).andStubReturn(null);
    preference.setSummary(isA(String.class));
    replayAll();

    PreferenceUtil.initializeSpecialPreferencesInternal(preferenceManager);

    verifyAll();

    // initializeLayoutAdjustmentPreference
    {
      resetAll();
      Preference prefPortrait = createMockBuilder(Preference.class)
          .withConstructor(Context.class)
          .withArgs(context)
          .createMock();
      Preference prefLandscape = createMockBuilder(Preference.class)
          .withConstructor(Context.class)
          .withArgs(context)
          .createMock();
      PreferenceGroup prefPortraitGroup = createMockBuilder(PreferenceGroup.class)
          .withConstructor(Context.class, AttributeSet.class)
          .withArgs(context, Xml.asAttributeSet(context.getResources().getXml(
              R.xml.pref_software_keyboard_advanced)))
          .createMock();
      PreferenceGroup prefLandscapeGroup = createMockBuilder(PreferenceGroup.class)
          .withConstructor(Context.class, AttributeSet.class)
          .withArgs(context, Xml.asAttributeSet(context.getResources().getXml(
              R.xml.pref_software_keyboard_advanced)))
          .createMock();

      expect(preferenceManager.findPreference(PreferenceUtil.PREF_PORTRAIT_LAYOUT_ADJUSTMENT_KEY))
          .andStubReturn(prefPortrait);
      expect(preferenceManager.findPreference(PreferenceUtil.PREF_LANDSCAPE_LAYOUT_ADJUSTMENT_KEY))
          .andStubReturn(prefLandscape);
      expect(preferenceManager.findPreference(PreferenceUtil
          .PREF_SOFTWARE_KEYBOARD_ADVANED_PORTRAIT_KEY))
          .andStubReturn(prefPortraitGroup);
      expect(preferenceManager.findPreference(PreferenceUtil
          .PREF_SOFTWARE_KEYBOARD_ADVANED_LANDSCAPE_KEY))
          .andStubReturn(prefLandscapeGroup);
      expect(preferenceManager.findPreference(isA(String.class))).andStubReturn(null);

      Context contextMock = createMock(MockContext.class);
      Resources resources = createMock(MockResources.class);
      expect(prefPortraitGroup.getContext()).andStubReturn(contextMock);
      expect(contextMock.getResources()).andStubReturn(resources);
      expect(resources.getDimensionPixelSize(R.dimen.ime_window_partial_width))
          .andStubReturn(100);
      expect(resources.getDimensionPixelSize(R.dimen.side_frame_width)).andStubReturn(50);
      DisplayMetrics displayMetrics = new DisplayMetrics();
      displayMetrics.widthPixels = 100;
      displayMetrics.heightPixels = 200;
      expect(resources.getDisplayMetrics()).andStubReturn(displayMetrics);

      expect(prefPortraitGroup.removePreference(prefPortrait)).andReturn(true);
      expect(prefLandscapeGroup.removePreference(prefLandscape)).andReturn(true);

      replayAll();
      PreferenceUtil.initializeLayoutAdjustmentPreference(preferenceManager);

      verifyAll();
    }
  }

  @SmallTest
  public void testCurrentKeyboardLayoutPreferenceChangeListener() {
    OnPreferenceChangeListener listener = new CurrentKeyboardLayoutPreferenceChangeListener();

    // TODO(hidehiko): Replace following test in a less side-effective way.
    final SharedPreferences sharedPreferences = createMock(SharedPreferences.class);
    Editor editor = createMock(Editor.class);
    Context context = getInstrumentation().getTargetContext();
    Preference preference = new Preference(context) {
      @Override
      public SharedPreferences getSharedPreferences() {
        return sharedPreferences;
      }
    };

    int originalOrientation = preference.getContext().getResources().getConfiguration().orientation;
    try {
      class TestData extends Parameter {
        final int orientation;
        final boolean usePortraitKeyboardSettingForLandscapeKey;
        final String expectKeyboardLayoutKey;
        TestData(int orientation,
                 boolean usePortraitKeyboardSettingForLandscapeKey,
                 String expectKeyboardLayoutKey) {
          this.orientation = orientation;
          this.usePortraitKeyboardSettingForLandscapeKey =
              usePortraitKeyboardSettingForLandscapeKey;
          this.expectKeyboardLayoutKey = expectKeyboardLayoutKey;
        }
      }

      @SuppressWarnings("deprecation")
      TestData[] testDataList = new TestData[] {
          new TestData(Configuration.ORIENTATION_PORTRAIT,
                       false,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_LANDSCAPE,
                       false,
                       PreferenceUtil.PREF_LANDSCAPE_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_SQUARE,
                       false,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_UNDEFINED,
                       false,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_PORTRAIT,
                       true,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_LANDSCAPE,
                       true,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_SQUARE,
                       true,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
          new TestData(Configuration.ORIENTATION_UNDEFINED,
                       true,
                       PreferenceUtil.PREF_PORTRAIT_KEYBOARD_LAYOUT_KEY),
      };

      for (TestData testData : testDataList) {
        resetAll();
        preference.getContext().getResources().getConfiguration().orientation =
            testData.orientation;
        expect(sharedPreferences.edit()).andStubReturn(editor);
        expect(sharedPreferences.getBoolean(
            PreferenceUtil.PREF_USE_PORTRAIT_KEYBOARD_SETTINGS_FOR_LANDSCAPE_KEY, true))
            .andStubReturn(testData.usePortraitKeyboardSettingForLandscapeKey);
        expect(editor.putString(testData.expectKeyboardLayoutKey,
                                KeyboardLayout.TWELVE_KEYS.name()))
            .andReturn(editor);
        expect(editor.commit()).andReturn(true);
        replayAll();

        listener.onPreferenceChange(preference, KeyboardLayout.TWELVE_KEYS);

        verifyAll();
      }
    } finally {
      preference.getContext().getResources().getConfiguration().orientation = originalOrientation;
    }
  }
}


text:
'use strict';

//Maps service used to communicate Maps REST endpoints
angular.module('maps').factory('Maps', ['$resource',
	function($resource) {
		return $resource('maps/:mapId', { mapId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
import numpy as np
from augment import *

# ----------------------- PARALLEL FUNCTION TO AUGMENT ----------------------- #
#
def get_pp_template(num_cpus=1, servers_list=('localhost',)):
	'''
	Method to set up the template.
	Parameters:
		num_cpus: number of CPUs to be used.
		servers_list: tuple containing the list of available servers.
	'''
	# Import PP library
	import pp

	# Start servers
	ppservers = (servers_list) # For more servers: ("localhost", "192.168.0.1", "192.168.0.2", "192.168.0.3")

	# Number of workers to be used
	if num_cpus > 1:
		job_server = pp.Server(num_cpus, ppservers=ppservers)
	else:
		job_server = pp.Server(ppservers=ppservers) # Create server with automatically detected num of workers
		ncpus = job_server.get_ncpus()

	print 'Starting PP with: ', job_server.get_ncpus(), "workers..."

	# Start template
	template = pp.Template(	job_server 	= job_server,
							func       	= augment_single_data_one_hot,
							depfuncs	= (	apply_random_transformations,
										apply_random_noise,
										apply_random_cropping,
										apply_random_vertical_flip,
										apply_random_horizontal_flip,
										crop),
							modules 	= ('numpy as np', 'random as rn', 'skimage.util', 'skimage.transform', 'scipy'))

	return template

#
def augment_dataset_parallel(dataset, labels, template, num_aug):
	'''
	Applies the template to augment dataset and labels in parallel.
	Labels must be in one-hot encoding.
	'''
	new_dataset = []
	new_labels  = []
	i = 0
	while (i < labels.shape[0]):
		jobs = []
		for c in range(template.job_server.get_ncpus()):
			jobs.append(template.submit(dataset[i,:,:,:], labels[i,:], num_aug))
			i += 1
			if (i == labels.shape[0]):
				break
		for c in range(len(jobs)):
			new_d, new_l = jobs[c]()
			new_dataset.extend(new_d)
			new_labels.extend(new_l)
	return np.asarray(new_dataset), np.asarray(new_labels)

#


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2018 .
  ~ This file is released under the Apache-2.0 license and part of the TimeTable repository located at:
  ~ https://github.com/greasemonk/android-timetable-core
  ~ See the "LICENSE" file at the root of the repository or go to the address below for the full license details.
  ~ https://github.com/GreaseMonk/android-timetable-core/blob/develop/LICENSE
  -->

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <TextView
            android:id="@+id/text1"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:paddingStart="8dp"
            android:paddingEnd="0dp"
            android:ellipsize="end"
            android:lines="1"
            android:text="Firstname Surname"
            android:gravity="start|top"/>

    <nl.greasemonk.timetable.PlanView
            android:layout_weight="8"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/plan_view"/>

</LinearLayout>


text:
package com.hazelcast.jet.impl.operation;

import com.hazelcast.jet.impl.execution.init.JetInitDataSerializerHook;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.spi.impl.AllowedDuringPassiveState;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class GetJobIdsByNameOperation
        extends AsyncOperation
        implements IdentifiedDataSerializable, AllowedDuringPassiveState {

    private String name;

    public GetJobIdsByNameOperation() {
    }

    public GetJobIdsByNameOperation(String name) {
        this.name = name;
    }

    @Override
    public CompletableFuture<List<Long>> doRun() {
        return getJobCoordinationService().getJobIds(name);
    }

    @Override
    public int getClassId() {
        return JetInitDataSerializerHook.GET_JOB_IDS_BY_NAME_OP;
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeUTF(name);
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        name = in.readUTF();
    }
}


text:
package io.vertx.ext.web.openapi.service;

import io.vertx.codegen.annotations.ProxyClose;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.api.service.ServiceRequest;
import io.vertx.ext.web.api.service.ServiceResponse;
import io.vertx.ext.web.api.service.WebApiServiceGen;
import io.vertx.ext.web.validation.RequestParameter;

@WebApiServiceGen
@VertxGen
public interface AnotherTestService {

  void testC(ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler);

  void testD(ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler);

  void testE(Integer id, JsonObject body, ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler);

  void testF(Integer id, RequestParameter body, ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler);

  void testDataObject(FilterData body, ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler);

  @ProxyClose
  void close();

  static AnotherTestService create(Vertx vertx) {
    return new AnotherTestServiceImpl(vertx);
  }

}


text:
require 'puppet/util/node_groups'

Puppet::Type.type(:puppet_environment).provide(:puppetclassify) do
  confine :feature => :puppetclassify

  def initialize(value={})
    super(value)
  end

  def self.classifier
    @classifier ||= initialize_client
  end

  def self.initialize_client
    Puppet::Util::Node_groups.new
  end
  # API will fail if disallowed-keys are passed
  def self.friendly_name
    {
      :name => 'name',
    }
  end

  def self.instances
    ngs = classifier.environments.get_environments
    ngs.collect do |env|
      ngs_hash = {}
      friendly_name.each do |property,friendly|
        ngs_hash[friendly.to_sym] = env[property.to_s]
      end
      ngs_hash[:ensure] = :present
      new(ngs_hash)
    end
  end

  def self.prefetch(resources)
    ngs = instances
    resources.keys.each do |env|
      if provider = ngs.find{ |g| g.name == env }
        resources[env].provider = provider
      end
    end
  end

  def exists?
    @property_hash[:ensure] == :present
  end

  mk_resource_methods

  def create
    resp = self.class.classifier.environments.create_environment(@resource[:name])
    # create_environment method doesn't have output
    # from puppetclassify method.  Only outputs if
    # there is an error.
    unless resp
      @resource.original_parameters.each_key do |k|
        if k == :ensure
          @property_hash[:ensure] = :present
        else
          @property_hash[k]       = @resource[k]
        end
      end
    else
      fail("puppetclassify was not able to create environment")
    end

    exists? ? (return true) : (return false)

  end

  def destroy
    begin
      self.class.classifier.delete_environment(@property_hash[:name])
    rescue Exception => e
      fail(e.message)
      debug(e.backtrace.inspect)
    else
      @property_hash.clear
    end
    exists? ? (return false) : (return true)
  end
end


text:
from __future__ import unicode_literals

from flask import jsonify, session
from werkzeug.exceptions import Forbidden, NotFound

from indico.modules.attachments.controllers.event_package import AttachmentPackageMixin
from indico.modules.attachments.controllers.management.base import (AddAttachmentFilesMixin, AddAttachmentLinkMixin,
                                                                    CreateFolderMixin, DeleteAttachmentMixin,
                                                                    DeleteFolderMixin, EditAttachmentMixin,
                                                                    EditFolderMixin, ManageAttachmentsMixin)
from indico.modules.attachments.util import can_manage_attachments
from indico.modules.attachments.views import WPEventAttachments, WPPackageEventAttachmentsManagement
from indico.modules.events.controllers.base import RHEventBase
from indico.modules.events.management.controllers import RHManageEventBase
from indico.modules.events.util import check_event_locked, get_object_from_args
from indico.web.flask.templating import get_template_module
from indico.web.rh import RHProtected

class RHEventAttachmentManagementBase(RHEventBase, RHProtected):
    normalize_url_spec = {
        'locators': {
            lambda self: self.object
        }
    }

    def _process_args(self):
        RHEventBase._process_args(self)
        self.object_type, self.base_object, self.object = get_object_from_args()
        if self.object is None:
            raise NotFound

    def _check_access(self):
        RHProtected._check_access(self)
        if not can_manage_attachments(self.object, session.user):
            raise Forbidden
        check_event_locked(self, self.event)

class RHManageEventAttachments(ManageAttachmentsMixin, RHEventAttachmentManagementBase):
    wp = WPEventAttachments

class RHAttachmentManagementInfoColumn(RHEventAttachmentManagementBase):
    def _process(self):
        tpl = get_template_module('attachments/_management_info_column.html')
        return jsonify(html=tpl.render_attachment_info(self.object))

class RHAddEventAttachmentFiles(AddAttachmentFilesMixin, RHEventAttachmentManagementBase):
    pass

class RHAddEventAttachmentLink(AddAttachmentLinkMixin, RHEventAttachmentManagementBase):
    pass

class RHEditEventAttachment(EditAttachmentMixin, RHEventAttachmentManagementBase):
    def _process_args(self):
        RHEventAttachmentManagementBase._process_args(self)
        EditAttachmentMixin._process_args(self)

class RHCreateEventFolder(CreateFolderMixin, RHEventAttachmentManagementBase):
    pass

class RHEditEventFolder(EditFolderMixin, RHEventAttachmentManagementBase):
    def _process_args(self):
        RHEventAttachmentManagementBase._process_args(self)
        EditFolderMixin._process_args(self)

class RHDeleteEventFolder(DeleteFolderMixin, RHEventAttachmentManagementBase):
    def _process_args(self):
        RHEventAttachmentManagementBase._process_args(self)
        DeleteFolderMixin._process_args(self)

class RHDeleteEventAttachment(DeleteAttachmentMixin, RHEventAttachmentManagementBase):
    def _process_args(self):
        RHEventAttachmentManagementBase._process_args(self)
        DeleteAttachmentMixin._process_args(self)

class RHPackageEventAttachmentsManagement(AttachmentPackageMixin, RHManageEventBase):
    wp = WPPackageEventAttachmentsManagement
    management = True
    ALLOW_LOCKED = True


text:
package com.intellij.openapi.vcs.changes;

import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;

public class DirtBuilder implements DirtBuilderReader {
  private final FileTypeManager myFileTypeManager = FileTypeManager.getInstance();

  private final MultiMap<AbstractVcs, FilePath> myFiles = MultiMap.createSet();
  private final MultiMap<AbstractVcs, FilePath> myDirs = MultiMap.createSet();
  private boolean myEverythingDirty = false;

  public DirtBuilder() {
  }

  public DirtBuilder(@NotNull DirtBuilder builder) {
    myDirs.putAllValues(builder.myDirs);
    myFiles.putAllValues(builder.myFiles);
    myEverythingDirty = builder.myEverythingDirty;
  }

  public void reset() {
    myFiles.clear();
    myDirs.clear();
    myEverythingDirty = false;
  }

  public void everythingDirty() {
    myEverythingDirty = true;
  }

  public void addDirtyFile(@NotNull AbstractVcs vcs, @NotNull FilePath file) {
    if (myFileTypeManager.isFileIgnored(file.getName())) return;
    myFiles.putValue(vcs, file);
  }

  public void addDirtyDirRecursively(@NotNull AbstractVcs vcs, @NotNull FilePath dir) {
    if (myFileTypeManager.isFileIgnored(dir.getName())) return;
    myDirs.putValue(vcs, dir);
  }

  @Override
  public boolean isEverythingDirty() {
    return myEverythingDirty;
  }

  @Override
  @NotNull
  public MultiMap<AbstractVcs, FilePath> getFilesForVcs() {
    return myFiles;
  }

  @Override
  @NotNull
  public MultiMap<AbstractVcs, FilePath> getDirsForVcs() {
    return myDirs;
  }

  @Override
  public boolean isEmpty() {
    return myFiles.isEmpty() && myDirs.isEmpty();
  }
}


text:
@implementation PiwigoButton

-(instancetype)init
{
	self = [super init];
	if(self)
	{
		self.backgroundColor = [UIColor piwigoOrange];
		self.layer.cornerRadius = 5.0;

		self.titleLabel.font = [UIFont piwigoFontButton];
		[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	}
	return self;
}

-(void)setHighlighted:(BOOL)highlighted
{
	[super setHighlighted:highlighted];
	if(highlighted) {
		self.backgroundColor = [UIColor piwigoOrangeSelected];
	} else {
		self.backgroundColor = [UIColor piwigoOrange];
	}
}

@end


text:
"""
    Talon.One API

    Use the Talon.One API to integrate with your application and to manage applications and campaigns:  - Use the operations in the [Integration API section](#integration-api) are used to integrate with our platform - Use the operation in the [Management API section](#management-api) to manage applications and campaigns.  ## Determining the base URL of the endpoints  The API is available at the same hostname as your Campaign Manager deployment. For example, if you are reading this page at `https://mycompany.talon.one/docs/api/`, the URL for the [updateCustomerSession](https://docs.talon.one/integration-api/#operation/updateCustomerSessionV2) endpoint is `https://mycompany.talon.one/v2/customer_sessions/{Id}`   # noqa: E501

    The version of the OpenAPI document: 1.0.0
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import

import unittest
import datetime

import talon_one
from talon_one.models.attribute import Attribute  # noqa: E501
from talon_one.rest import ApiException

class TestAttribute(unittest.TestCase):
    """Attribute unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def make_instance(self, include_optional):
        """Test Attribute
            include_option is a boolean, when False only required
            params are included, when True both required and
            optional params are included """
        # model = talon_one.models.attribute.Attribute()  # noqa: E501
        if include_optional :
            return Attribute(
                id = 6,
                created = '2020-06-10T09:05:27.993483Z',
                account_id = 3886,
                entity = 'Account',
                event_type = '0',
                name = 'a',
                title = 'a',
                type = 'string',
                description = '0',
                suggestions = [
                    '0'
                    ],
                has_allowed_list = True,
                restricted_by_suggestions = True,
                editable = True,
                subscribed_applications_ids = [
                    56
                    ],
                subscribed_catalogs_ids = [
                    56
                    ],
                allowed_subscriptions = [
                    'application'
                    ],
                event_type_id = 22
            )
        else :
            return Attribute(
                id = 6,
                created = '2020-06-10T09:05:27.993483Z',
                account_id = 3886,
                entity = 'Account',
                name = 'a',
                title = 'a',
                type = 'string',
                description = '0',
                suggestions = [
                    '0'
                    ],
                editable = True,
        )

    def testAttribute(self):
        """Test Attribute"""
        inst_req_only = self.make_instance(include_optional=False)
        inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
    unittest.main()


text:
int
main (int, char**)
{
    util::TAP::logger tap;

    // set aside a sizeable buffer. it has to be large enough to conceivably
    // satisfy a sane allocation request during testing, just in case the
    // underlying code actually decides to do something; we don't be touching
    // it ourselves.
    static char buffer[1024*1024];

    // pick an alignment that isn't likely to be satisfied by any likely
    // underlying allocator. if the allocation fulfills this alignment then
    // we're probably operating correctly.
    static constexpr std::size_t alignment = 3;

    util::alloc::raw::aligned<util::alloc::raw::linear> alloc (
        alignment, std::begin (buffer), std::end (buffer)
    );

    // allocate a range of values and make sure they all satisfy our alignment.
    // don't choose values which are likely to combine with the testing
    // alignment to produce a likely system alignment. eg, 3 + 5 == 8 which is
    // a power-of-2.
    uintptr_t result[4] = {
        (uintptr_t)alloc.allocate (9),     // just over a power of two
        (uintptr_t)alloc.allocate (1),     // a single byte
        (uintptr_t)alloc.allocate (64),    // a cache line
        (uintptr_t)alloc.allocate (250)    // multiple cache lines, but not a power of two
    };

    tap.expect (
        !(result[0] % alignment) &&
        !(result[1] % alignment) &&
        !(result[2] % alignment) &&
        !(result[3] % alignment),

        "allocations make alignment of %zu", alignment
    );

    return tap.status ();
}


text:
package csci432.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Blob class for keeping track of moving items
 **/
public class Blob {
    @JsonProperty("locations")
    /**
     * Locations is a map from image index (int) to the location of the blob in the image(Point)
     */
    private Map<Integer, Point> locations;

    @JsonCreator
    /**
     * Should never be used, it this is for deserialization of blob
     */
    public Blob(Map<Integer, Point> locations) {
        this.locations =locations;
    }

    /**
     * Creates a new Hashmap and the Blob object
     */
    public Blob() {
        locations = new HashMap<>();
    }

    /**
     * Chooses which hitbox is the correct one to move to:
     **/
    public HitBox resolveConflict(List<HitBox> overlaps) {
       return null;
    }

    /**
     * Returns if the blob is in a given picture
     *
     * @param picIndex the index to look at
     * @return True if the blob is in the given picture, false otherwise
     */
    public Boolean inPicture(Integer picIndex) {
        return locations.containsKey(picIndex);
    }

    /**
     * Adds the current index to the location
     *
     * @param picIndex index of the picture
     * @param location location of the blob
     */
    public void addLocation(Integer picIndex, Point location) {
        locations.put(picIndex, location);
    }

    /**
     * Returns the location of the blob in the given picture index
     *
     * @param picIndex index of the picture
     * @return the location of the blob, null if it isn't in the given picture
     */
    public Point getLocation(Integer picIndex) {
        return locations.get(picIndex);
    }

    /**
     * Returns the locations of the blobs in each picture
     *
     * @param start first index
     * @param end last index
     * @return a list of locations
     */
    public List<Point> getLocationsInRange(Integer start, Integer end) {
        List<Point> pointList = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            pointList.add(locations.get(i));
        }

        return pointList;
    }

    @Override
    public String toString() {
        return "Blob:"+ locations.toString();
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Blob && this.locations.equals(((Blob) o).locations);
    }

    /**
     * Returns the start index and end index of the pictures
     *
     * @return returns the start index and end index of the pictures
     */
    public List<Integer> getPictureRange() {
        if (isEmpty()) {
            return null;
        }

        List<Integer> points = new ArrayList<>(locations.keySet());
        Collections.sort(points);
        return Arrays.asList(points.get(0), points.get(points.size()-1));
    }

    /**
     * Returns if there are some locations
     *
     * @return True if some locations exist, false otherwise
     */
    public Boolean isEmpty() {
        return locations.isEmpty();
    }

    /**
     * Returns all the locations in order
     *
     * @return List of points, the locations of the blob
     */
    public List<Point> getAllLocations() {
        if (isEmpty()) {
            return null;
        }

        List<Integer> indexes = getPictureRange();
        return getLocationsInRange(indexes.get(0), indexes.get(1));
    }

    /**
     * Saves the blob as a JSON file
     *
     * @param fileName file to save object as
     */
    public void save(String fileName) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(new File(fileName), this);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Loads the blob from the JSON file
     *
     * @param fileName file to load object from
     * @return The loaded blob
     */
    public static Blob load(String fileName) {
        ObjectMapper mapper = new ObjectMapper();
        Blob blob = null;
        try {
            blob = mapper.readValue(new File(fileName), Blob.class);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            return blob;
        }
    }
}


text:
package org.ecg.refdata.utils;

import java.util.Locale;

/**
 * Interface for resoure boundles. Extension can accept parameter and put it
 * inside localized string instead {x}. Where x is number of parameter starting
 * from 0.
 *
 */
public interface IMessageBoundle {

    /**
     * Get localized string for key. Use default locale.
     *
     * @param key - message key
     * @param par - parameters to fill
     * @return localized string
     */
//    String getString(String key, Object... par);
    /**
     * Get localized string for key. Use passed locale.
     *
     * @param locale - locale where key should be serach
     * @param key - message key
     * @param par - parameters to fill
     * @return localized string
     */
    String getString(Locale locale, String key, Object... par);

}


text:
namespace {

// Populates |resource_data| with the address and size of the resource in
// |module| identified by |name_or_id| of type |type_name_or_id|, returning
// true on success.
bool DoLoad(HMODULE module,
            const wchar_t* name_or_id,
            const wchar_t* type_name_or_id,
            std::pair<const uint8_t*, DWORD>* resource_data) {
  bool loaded = false;
  HRSRC resource_info;

  resource_info = FindResource(module, name_or_id, type_name_or_id);
  if (resource_info != nullptr) {
    HGLOBAL loaded_resource;

    loaded_resource = LoadResource(module, resource_info);
    if (loaded_resource != nullptr) {
      resource_data->first =
          static_cast<const uint8_t*>(LockResource(loaded_resource));
      if (resource_data->first != nullptr) {
        resource_data->second = SizeofResource(module, resource_info);
        DPCHECK(resource_data->second != 0);
        loaded = true;
      } else {
        DPCHECK(false) << "LockResource failed";
      }
    } else {
      DPCHECK(false) << "LoadResource failed";
    }
  } else {
    DPLOG(INFO) << "FindResource failed";
  }

  return loaded;
}

}  // namespace

namespace upgrade_test {

ResourceLoader::ResourceLoader() : module_(nullptr) {}

ResourceLoader::~ResourceLoader() {
  if (module_ != nullptr) {
    BOOL result = FreeLibrary(module_);
    DPCHECK(result != 0) << "FreeLibrary failed";
  }
}

bool ResourceLoader::Initialize(const base::FilePath& pe_image_path) {
  DCHECK_EQ(module_, nullptr);
  module_ = LoadLibraryEx(
      pe_image_path.value().c_str(), nullptr,
      (LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE));
  DPLOG_IF(INFO, module_ == nullptr)
      << "Failed loading \"" << pe_image_path.value() << "\"";
  return module_ != nullptr;
}

bool ResourceLoader::Load(const std::wstring& name,
                          const std::wstring& type,
                          std::pair<const uint8_t*, DWORD>* resource_data) {
  DCHECK_NE(resource_data, nullptr);
  DCHECK_NE(module_, nullptr);

  return DoLoad(module_, name.c_str(), type.c_str(), resource_data);
}

bool ResourceLoader::Load(WORD id,
                          WORD type,
                          std::pair<const uint8_t*, DWORD>* resource_data) {
  DCHECK_NE(resource_data, nullptr);
  DCHECK_NE(module_, nullptr);

  return DoLoad(module_, MAKEINTRESOURCE(id), MAKEINTRESOURCE(type),
                resource_data);
}

}  // namespace upgrade_test


text:
<?php

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Core\Annotation\Property;
use ApiPlatform\Core\Annotation\Resource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Dummy.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 *
 * @Resource(attributes={"filters"={"my_dummy.search", "my_dummy.order", "my_dummy.date", "my_dummy.range"}})
 * @ORM\Entity
 */
class Dummy
{
    /**
     * @var int The id.
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string The dummy name.
     *
     * @ORM\Column
     * @Assert\NotBlank
     * @Property(iri="http://schema.org/name")
     */
    private $name;

    /**
     * @var string The dummy name alias.
     *
     * @ORM\Column(nullable=true)
     * @Property(iri="https://schema.org/alternateName")
     */
    private $alias;

    /**
     * @var array foo
     */
    private $foo;

    /**
     * @var string A short description of the item.
     *
     * @ORM\Column(nullable=true)
     * @Property(iri="https://schema.org/description")
     */
    public $description;

    /**
     * @var string A dummy.
     *
     * @ORM\Column(nullable=true)
     */
    public $dummy;

    /**
     * @var \DateTime A dummy date.
     *
     * @ORM\Column(type="datetime", nullable=true)
     * @Assert\DateTime
     */
    public $dummyDate;

    /**
     * @var string A dummy price.
     *
     * @ORM\Column(type="decimal", precision=10, scale=2, nullable=true)
     */
    public $dummyPrice;

    /**
     * @var RelatedDummy A related dummy.
     *
     * @ORM\ManyToOne(targetEntity="RelatedDummy")
     */
    public $relatedDummy;

    /**
     * @var ArrayCollection Several dummies.
     *
     * @ORM\ManyToMany(targetEntity="RelatedDummy")
     */
    public $relatedDummies;

    /**
     * @var array serialize data.
     *
     * @ORM\Column(type="json_array", nullable=true)
     */
    public $jsonData;

    /**
     * @var string
     *
     * @ORM\Column(nullable=true)
     */
    public $nameConverted;

    public function __construct()
    {
        $this->relatedDummies = new ArrayCollection();
        $this->jsonData = [];
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setAlias($alias)
    {
        $this->alias = $alias;
    }

    public function getAlias()
    {
        return $this->alias;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function hasRole($role)
    {
    }

    public function setFoo(array $foo = null)
    {
    }

    public function setDummyDate(\DateTime $dummyDate = null)
    {
        $this->dummyDate = $dummyDate;
    }

    public function getDummyDate()
    {
        return $this->dummyDate;
    }

    public function setDummyPrice($dummyPrice)
    {
        $this->dummyPrice = $dummyPrice;

        return $this;
    }

    public function getDummyPrice()
    {
        return $this->dummyPrice;
    }

    public function setJsonData($jsonData)
    {
        $this->jsonData = $jsonData;
    }

    public function getJsonData()
    {
        return $this->jsonData;
    }

    public function getRelatedDummy()
    {
        return $this->relatedDummy;
    }

    public function setRelatedDummy(RelatedDummy $relatedDummy)
    {
        $this->relatedDummy = $relatedDummy;
    }

    public function addRelatedDummy(RelatedDummy $relatedDummy)
    {
        $this->relatedDummies->add($relatedDummy);
    }
}


text:
\newcommand{\monhuge}[1]{\fontsize{20}{22pt}\selectfont{#1}}
\newcommand{\monlarge}[1]{\fontsize{12}{14pt}\selectfont{#1}}
\newcommand{\monnormalsize}[1]{\fontsize{10}{12pt}\selectfont{#1}}

\begin{center}
    \begin{tabular}{p{2cm}p{9.5cm}p{3cm}}
        \includegraphics[width=1.8cm]{logos/logo_uapv.pdf} &
						\vspace{-2.4cm}
            \begin{tabular}{p{9.5cm}}
								\textsl{\monlarge{ORANGE LABS} } \\\\\\
                \textsl{\monlarge{ACADÉMIE D'AIX-MARSEILLE} } \\
                \textsl{\monnormalsize{UNIVERSITÉ D'AVIGNON ET DES PAYS DE VAUCLUSE}}\\\\
           \end{tabular} &
				\includegraphics[width=2.5cm]{logos/logo_orange.pdf}
      \end{tabular}
      \rule{\textwidth}{0.5pt}
      \begin{center} \vspace{6mm} \monhuge{\textbf{PhD THESIS}} \end{center}
      \vspace{6mm}
      \monlarge{This dissertation is submitted for the degree of \textit{Doctor of Philosophy}}\\
      %\monlarge{Présentée pour obtenir le grade de Docteur en Sciences \\
      %de l'Université d'Avignon et des Pays de Vaucluse}\\
      \vspace{5mm}
      \textbf{SPECIALTY: } \textbf{{Computer Science}}\\
      \vspace{3mm}
      \monlarge{Doctoral School 380 \quotes{Sciences et Agronomie}}\\[1mm]
      \monlarge{Laboratoire d'Informatique (EA 931)}\\
      \vspace{11mm}
      %\shadowbox{
      %\begin{minipage}{\textwidth}
      %\centering
      %\vskip .5em
      \textit{\monhuge{Turn-taking Enhancement in Spoken Dialogue Systems with Reinforcement Learning}}
      %\vskip 1.5em
      %\end{minipage}
      %}
      \\[11mm]
      \monnormalsize{by} \\[1mm]
      \monlarge{\textbf{{Hatim KHOUZAIMI}}}\\[10mm]
      \monnormalsize{
      \textbf{Publicly defended on June 6$^{th}$ 2016 in front of a jury composed of:}\\[0.4cm]
      \begin{tabular}{@{}p{5mm}lll}
        \\
        Dr & Sophie ROSSET & LIMSI, Orsay & \textit{Rapporteur} \\
        Pr & David SCHLANGEN & Bielefeld University & \textit{Rapporteur} \\[0.1cm]
        McF & Bassam JABAIAN & CERI-LIA, Avignon University & \textit{Examiner} \\[0.1cm]
        McF & Filip JURCICEK & UFAL, Charles University, Prague & \textit{Examiner} \\
        Pr & Olivier PIETQUIN & Google DeepMind & \textit{Examiner} \\[0.1cm]
        Dr & Romain LAROCHE & NADIA Team, Orange Labs & \textit{Supervisor} \\
        Pr & Fabrice LEFEVRE & CERI-LIA, Avignon University & \textit{Supervisor} \\
        %   & & & \\
      \end{tabular}
      }\\[1cm]
      \vspace{5.5cm}
      \rule{\textwidth}{0.5pt}

\begin{tabular}{p{8.1cm}l}
\multirow{2}{*}{\includegraphics[width=1.5cm]{logos/logo_lia}} &
%\'Ecole Doctorale Science et Agronomie\\

\hspace{-1cm}Laboratoire Informatique d'Avignon
\\ &
\end{tabular}
\end{center}
\end{titlepage}


text:
{% extends "problems/base.html" %}
{% block problem_navbar_link_submissions %}active{% endblock %}
{% block problem_content %}

{{ _('problems.submissions.new') }}

<form method="POST" enctype="multipart/form-data" action="{{ url_for('problems.submissions', problem_id=problem.id) }}">
{{ _('common.compiler') }}
<select name="compiler" class="form-control" id="compiler">
{% for compiler in compilers %}
<option value="{{ compiler.id }}" {% if loop.index == 1 %}selected="selected"{% endif %}>{{ compiler.name }}</option>
{% endfor %}
</select>

{{ _('common.source') }}
<input type="file" id="source" name="source_file" />

<button type="submit" role="button" class="btn btn-primary">{{ _('common.submit') }}</button>
</form>

{% if g.user.is_admin(problem=problem) and attempted_users %}

{{ _('problems.submissions.attemptedusers') }}

{% for nuser in attempted_users %}

            {% if nuser.id == user.id %}
            {{ nuser.username }}
            {% else %}
            {{ nuser.username }}
            {% endif %}

        {{ problem.user_status(nuser, color=False)|safe }}

            {{ _('title.problem.submissions') }} »

{% endfor %}

{% endif %}
{% if show_belonging_caption %}

{{ _('problems.submissions.belonging', username=user.username) }}

{% endif %}

{{ rendered_subs|safe }}

{% endblock %}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>ontop</artifactId>
        <groupId>it.unibz.inf.ontop</groupId>
        <version>1.17.1</version>
        <relativePath>..</relativePath>
    </parent>

    <artifactId>ontop-protege</artifactId>
    <name>ontop-protege</name>
    <url>http://ontop.inf.unibz.it/</url>
    <description>Ontop OBDA plugin for protégé</description>
    <organization>
        <name>KRDB Research Centre for Knowledge and Data, Free University of Bozen-Bolzano</name>
        <url>http://www.inf.unibz.it/krdb/</url>
    </organization>

    <properties>
        <protege.version>5.0.0-beta-21</protege.version>
        <symbolic.name>it.unibz.inf.ontop.protege</symbolic.name>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- OBDA libraries -->

        <!-- These are dependencies to the OBDA related classes. -->

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-obdalib-core</artifactId>
            <version>${project.version}</version>
        </dependency>

        <!--Dependencies from the OBDA projects to include in the jar -->

        <!-- Reasoner libraries -->

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-reformulation-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-quest-owlapi</artifactId>
            <version>${project.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>net.sourceforge.owlapi</groupId>
                    <artifactId>owlapi-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>net.sourceforge.owlapi</groupId>
                    <artifactId>owlapi-apibinding</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-quest-db</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-obdalib-owlapi</artifactId>
            <version>${project.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>net.sourceforge.owlapi</groupId>
                    <artifactId>owlapi-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>net.sourceforge.owlapi</groupId>
                    <artifactId>owlapi-apibinding</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-obdalib-r2rml</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-obdalib-sesame</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ontop-quest-sesame</artifactId>
            <version>${project.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>net.sourceforge.owlapi</groupId>
                    <artifactId>owlapi-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>net.sourceforge.owlapi</groupId>
                    <artifactId>owlapi-apibinding</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.javabits.jgrapht</groupId>
            <artifactId>jgrapht-core</artifactId>
        </dependency>

        <dependency>
            <groupId>eu.optique-project</groupId>
            <artifactId>r2rml-api</artifactId>
        </dependency>
        <dependency>
            <groupId>eu.optique-project</groupId>
            <artifactId>r2rml-api-sesame-bridge</artifactId>
        </dependency>

        <!-- Protege and OWLAPI bundle dependencies -->

        <dependency>
            <groupId>edu.stanford.protege</groupId>
            <artifactId>protege-editor-core</artifactId>
            <version>${protege.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>edu.stanford.protege</groupId>
            <artifactId>protege-editor-owl</artifactId>
            <version>${protege.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- transitive dependencies -->
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr</artifactId>
        </dependency>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr-runtime</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>antlr</groupId>
                    <artifactId>antlr</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>stringtemplate</artifactId>
            <version>4.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-juli</artifactId>
        </dependency>

        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-model</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-query</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-queryalgebra-model</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-queryparser-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-queryparser-sparql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-queryresultio-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-queryresultio-text</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-repository-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-datatypes</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-languages</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-n3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-ntriples</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-rdfxml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-turtle</artifactId>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>${symbolic.name}-${project.version}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>

                <extensions>true</extensions>
                <configuration>

                    <!-- The following is the set of instructions of how pack the bundle and how to create the
                         MANIFEST.MF for the bundle. The configuration does 3 things.

                        1. It makes sure that the "tight" dependencies are not packed as jars, but as .class files
                           (inline). It makes sure that all the runtime dependencies are packed as jars.

                        2. It makes sure all the protege plugin resources are packed (plugin.xml, tabs*.xml, etc).

                        3. It makes sure the META-INF/MANIFEST.MF for OSGi bundles is created with the correct imports,
                           exports and classpath.
                    -->

                    <instructions>
                        <Bundle-RequiredExecutionEnvironment>JavaSE-1.8</Bundle-RequiredExecutionEnvironment>
                        <!-- This makes sure any dependency in the obdalib <dependency> dependencies are packed
                        as .classes (uncompressed, no jars) and the rest is packed as .jars -->
                        <Embed-Dependency>
                            *;groupId=it.unibz.inf.ontop.*;inline=true,*;groupId=it.unibz.krdb.obda.protege4.*;inline=true,*;groupId=!it.unibz.inf.ontop;scope=compile|runtime
                        </Embed-Dependency>

                        <!-- necessary for protege plugins -->
                        <Bundle-Category>protege</Bundle-Category>

                        <Bundle-ContactAddress>gh.xiao@gmail.com</Bundle-ContactAddress>
                        <Bundle-DocURL>${project.url}</Bundle-DocURL>
                        <Bundle-Name>Ontop OBDA Protégé plugin</Bundle-Name>
                        <Bundle-Description>${project.description}</Bundle-Description>
                        <Bundle-Vendor>${project.organization.name}</Bundle-Vendor>
                        <Implementation-Version>${project.version}</Implementation-Version>
                        <Update-Url>https://github.com/ontop/ontop/raw/master/ontop-protege/update.properties</Update-Url>

                        <Export-Package><!-- No need to export any package --></Export-Package>

                        <!--<Import-Package>!au.com.bytecode.opencsv*,!org.antlr.stringtemplate,*</Import-Package>-->

                        <Import-Package>!org.antlr.stringtemplate,*</Import-Package>

                        <!-- The name of the plugin for OSGi dependencies. It has to be singleton
                            or protege wont load it -->
                        <Bundle-SymbolicName>${symbolic.name};singleton:=true</Bundle-SymbolicName>

                        <Bundle-Activator>org.protege.osgi.jdbc.JdbcBundleActivator</Bundle-Activator>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>


text:
RSpec.describe 'Predicates: Filled' do
  include_context 'validator result'

  describe 'with key' do
    before do
      @validator = Class.new do
        include Hanami::Validations::Form

        validations do
          required(:foo) { filled? }
        end
      end
    end

    describe 'with valid input (array)' do
      let(:input) { { 'foo' => ['23'] } }

      it 'is successful' do
        expect_successful result
      end
    end

    describe 'with valid input (hash)' do
      let(:input) { { 'foo' => { 'bar' => '23' } } }

      it 'is successful' do
        expect_successful result
      end
    end

    describe 'with missing input' do
      let(:input) { {} }

      it 'is not successful' do
        expect_not_successful result, ['is missing']
      end
    end

    describe 'with nil input' do
      let(:input) { { 'foo' => nil } }

      it 'is not successful' do
        expect_not_successful result, ['must be filled']
      end
    end

    describe 'with blank input' do
      let(:input) { { 'foo' => '' } }

      it 'is not successful' do
        expect_not_successful result, ['must be filled']
      end
    end

    describe 'with invalid input' do
      let(:input) { { 'foo' => [] } }

      it 'is not successful' do
        expect_not_successful result, ['must be filled']
      end
    end
  end

  describe 'with optional' do
    before do
      @validator = Class.new do
        include Hanami::Validations::Form

        validations do
          optional(:foo) { filled? }
        end
      end
    end

    describe 'with valid input (array)' do
      let(:input) { { 'foo' => ['23'] } }

      it 'is successful' do
        expect_successful result
      end
    end

    describe 'with valid input (hash)' do
      let(:input) { { 'foo' => { 'bar' => '23' } } }

      it 'is successful' do
        expect_successful result
      end
    end

    describe 'with missing input' do
      let(:input) { {} }

      it 'is successful' do
        expect_successful result
      end
    end

    describe 'with nil input' do
      let(:input) { { 'foo' => nil } }

      it 'is not successful' do
        expect_not_successful result, ['must be filled']
      end
    end

    describe 'with blank input' do
      let(:input) { { 'foo' => '' } }

      it 'is not successful' do
        expect_not_successful result, ['must be filled']
      end
    end

    describe 'with invalid input' do
      let(:input) { { 'foo' => [] } }

      it 'is not successful' do
        expect_not_successful result, ['must be filled']
      end
    end
  end

  describe 'as macro' do
    describe 'with required' do
      describe 'with value' do
        before do
          @validator = Class.new do
            include Hanami::Validations::Form

            validations do
              required(:foo).value(:filled?)
            end
          end
        end

        describe 'with valid input (array)' do
          let(:input) { { 'foo' => ['23'] } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with valid input (hash)' do
          let(:input) { { 'foo' => { 'bar' => '23' } } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with missing input' do
          let(:input) { {} }

          it 'is not successful' do
            expect_not_successful result, ['is missing']
          end
        end

        describe 'with nil input' do
          let(:input) { { 'foo' => nil } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with blank input' do
          let(:input) { { 'foo' => '' } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with invalid input' do
          let(:input) { { 'foo' => [] } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end
      end

      describe 'with filled' do
        before do
          @validator = Class.new do
            include Hanami::Validations::Form

            validations do
              required(:foo).filled
            end
          end
        end

        describe 'with valid input (array)' do
          let(:input) { { 'foo' => ['23'] } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with valid input (hash)' do
          let(:input) { { 'foo' => { 'bar' => '23' } } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with missing input' do
          let(:input) { {} }

          it 'is not successful' do
            expect_not_successful result, ['is missing']
          end
        end

        describe 'with nil input' do
          let(:input) { { 'foo' => nil } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with blank input' do
          let(:input) { { 'foo' => '' } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with invalid input' do
          let(:input) { { 'foo' => [] } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end
      end

      describe 'with maybe' do
        before do
          @validator = Class.new do
            include Hanami::Validations::Form

            validations do
              required(:foo).maybe(:filled?)
            end
          end
        end

        describe 'with valid input (array)' do
          let(:input) { { 'foo' => ['23'] } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with valid input (hash)' do
          let(:input) { { 'foo' => { 'bar' => '23' } } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with missing input' do
          let(:input) { {} }

          it 'is not successful' do
            expect_not_successful result, ['is missing']
          end
        end

        describe 'with nil input' do
          let(:input) { { 'foo' => nil } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with blank input' do
          let(:input) { { 'foo' => '' } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with invalid input' do
          let(:input) { { 'foo' => [] } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end
      end
    end

    describe 'with optional' do
      describe 'with value' do
        before do
          @validator = Class.new do
            include Hanami::Validations::Form

            validations do
              optional(:foo).value(:filled?)
            end
          end
        end

        describe 'with valid input (array)' do
          let(:input) { { 'foo' => ['23'] } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with valid input (hash)' do
          let(:input) { { 'foo' => { 'bar' => '23' } } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with missing input' do
          let(:input) { {} }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with nil input' do
          let(:input) { { 'foo' => nil } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with blank input' do
          let(:input) { { 'foo' => '' } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with invalid input' do
          let(:input) { { 'foo' => [] } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end
      end

      describe 'with filled' do
        before do
          @validator = Class.new do
            include Hanami::Validations::Form

            validations do
              optional(:foo).filled
            end
          end
        end

        describe 'with valid input (array)' do
          let(:input) { { 'foo' => ['23'] } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with valid input (hash)' do
          let(:input) { { 'foo' => { 'bar' => '23' } } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with missing input' do
          let(:input) { {} }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with nil input' do
          let(:input) { { 'foo' => nil } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with blank input' do
          let(:input) { { 'foo' => '' } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end

        describe 'with invalid input' do
          let(:input) { { 'foo' => [] } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end
      end

      describe 'with maybe' do
        before do
          @validator = Class.new do
            include Hanami::Validations::Form

            validations do
              optional(:foo).maybe(:filled?)
            end
          end
        end

        describe 'with valid input (array)' do
          let(:input) { { 'foo' => ['23'] } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with valid input (hash)' do
          let(:input) { { 'foo' => { 'bar' => '23' } } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with missing input' do
          let(:input) { {} }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with nil input' do
          let(:input) { { 'foo' => nil } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with blank input' do
          let(:input) { { 'foo' => '' } }

          it 'is successful' do
            expect_successful result
          end
        end

        describe 'with invalid input' do
          let(:input) { { 'foo' => [] } }

          it 'is not successful' do
            expect_not_successful result, ['must be filled']
          end
        end
      end
    end
  end
end


text:
'use strict';

/**
 * @ngdoc overview
 * @name upstreamApp
 * @description
 * # upstreamApp
 *
 * Main module of the application.
 */
angular
  .module('upstreamApp', [
    'angularMoment',
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
	'ngFileUpload',
    'ngMaterial',
	'LocalStorageModule'
  ])
	.config(['localStorageServiceProvider', function(localStorageServiceProvider){
  localStorageServiceProvider.setPrefix('ls');
	}])
  .config(function ($routeProvider, $httpProvider, $mdThemingProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/stream.html',
        controller: 'StreamCtrl',
        controllerAs: 'stream',
        resolve: {
          authenticated: ['djangoAuth', function(djangoAuth){
            return djangoAuth.authenticationStatus(true);
          }],
        }
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl',
        controllerAs: 'about'
      })
      .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      })
      .when('/catch/:catchId', {
        templateUrl: 'views/catch.html',
        controller: 'CatchCtrl',
        controllerAs: 'vm',
        resolve: {
          authenticated: ['djangoAuth', function(djangoAuth){
            return djangoAuth.authenticationStatus(true);
          }],
        }
      })
      .when('/upload', {
        templateUrl: 'views/upload.html',
        controller: 'UploadCtrl',
        resolve: {
          authenticated: ['djangoAuth', function(djangoAuth){
            return djangoAuth.authenticationStatus(true);
          }],
        }
      })

      .when('/user/:userId', {
        templateUrl: 'views/user.html',
        controller: 'UserCtrl',
        resolve: {
          authenticated: ['djangoAuth', function(djangoAuth){
            return djangoAuth.authenticationStatus(true);
          }],
        }
      })
      .when('/search', {
        templateUrl: 'views/search.html',
        controller: 'SearchCtrl'
      })
      .when('/registration', {
        templateUrl: 'views/registration.html',
        controller: 'RegistrationCtrl'
      })
      .when('/userprofile', {
        templateUrl: 'views/userprofile.html',
        controller: 'UserprofileCtrl',
        resolve: {
          authenticated: ['djangoAuth', function(djangoAuth){
            return djangoAuth.authenticationStatus(true);
          }],
        }
      })
      .when('/stream', {
        templateUrl: 'views/stream.html',
        controller: 'StreamCtrl',
        controllerAs: 'stream',
        resolve: {
          authenticated: ['djangoAuth', function(djangoAuth){
            return djangoAuth.authenticationStatus(true);
          }],
        }
      })
      .otherwise({
        redirectTo: '/'
      });

    $mdThemingProvider.theme('default')
    .primaryPalette('grey', {
        'default': '900'
    })
    .accentPalette('light-green', {
        'default': '800'
    });
  })
	.run(function(djangoAuth){
    djangoAuth.initialize('//angler.online/api/rest-auth', false);
  });


text:
var log = require('winston')
  , Loggly = require('winston-loggly').Loggly
  , azureProviders = require('nitrogen-azure-providers')
  , localProviders = require('nitrogen-local-providers')
  , mongodbProviders = require('nitrogen-mongodb-providers')
  , redisProviders = require('nitrogen-redis-providers')
  , winston = require('winston');

var config = null;

//
// To enable proxies like NGINX, Nitrogen has internal and external ports.
//
// external_port defines the port that clients should use to access the service.
// internal_port defines the port that the service will listen to.
//

if (process.env.NODE_ENV === "production") {
    config = {
        internal_port: process.env.PORT || 8080,
        web_admin_uri: process.env.WEB_ADMIN_URI || "https://admin.nitrogen.io",
        protocol: process.env.PROTOCOL || "https"
    };

    if (!process.env.ACCESS_TOKEN_SIGNING_KEY) {
        console.log('FATAL ERROR: you must provide an ACCESS_TOKEN_SIGNING_KEY as an environmental variable.');
        process.exit(0);
    }

} else if (process.env.NODE_ENV === "test") {
    config = {
        external_port: 3051,
        internal_port: 3051,
        protocol: process.env.PROTOCOL || "http",
        mongodb_connection_string: "mongodb://localhost/nitrogen_test",
        web_admin_uri: "http://localhost:9000"
    };
} else {
    config = {
        external_port: 3031,
        protocol: process.env.PROTOCOL || "http",
        mongodb_connection_string: "mongodb://localhost/nitrogen_dev",
        web_admin_uri: "http://localhost:9000"
    };
}

config.internal_port = config.internal_port || 3031;
config.external_port = config.external_port || 443;
config.protocol = process.env.PROTOCOL || config.protocol || "https";
config.host = process.env.HOST_NAME || config.host || "localhost";
config.mongodb_connection_string = config.mongodb_connection_string || process.env.MONGODB_CONNECTION_STRING;

// Endpoint URI configuration

config.api_path = "/api/";
config.v1_api_path = config.api_path + "v1";

config.base_endpoint = config.protocol + "://" + config.host + ":" + config.external_port;
config.api_endpoint = config.base_endpoint + config.v1_api_path;

config.subscriptions_path = '/';
config.subscriptions_endpoint = config.base_endpoint + config.subscriptions_path;

config.api_keys_path = config.v1_api_path + "/api_keys";
config.api_keys_endpoint = config.base_endpoint + config.api_keys_path;

config.blobs_path = config.v1_api_path + "/blobs";
config.blobs_endpoint = config.base_endpoint + config.blobs_path;

config.headwaiter_path = config.v1_api_path + "/headwaiter";
config.headwaiter_uri = config.base_endpoint + config.headwaiter_path;

config.messages_path = config.v1_api_path + "/messages";
config.messages_endpoint = config.base_endpoint + config.messages_path;

config.ops_path = config.v1_api_path + "/ops";
config.ops_endpoint = config.base_endpoint + config.ops_path;

config.permissions_path = config.v1_api_path + "/permissions";
config.permissions_endpoint = config.base_endpoint + config.permissions_path;

config.principals_path = config.v1_api_path + "/principals";
config.principals_endpoint = config.base_endpoint + config.principals_path;

config.users_path = "/user";
config.users_endpoint = config.base_endpoint + config.users_path;

config.user_authorize_path = config.users_path + "/authorize";
config.user_change_password_path = config.users_path + "/changepassword";
config.user_create_path = config.users_path + "/create";
config.user_decision_path = config.users_path + "/decision";
config.user_delete_account_path = config.users_path + "/delete";
config.user_login_path = config.users_path + "/login";
config.user_logout_path = config.users_path + "/logout";
config.user_reset_password_path = config.users_path + "/resetpassword";

config.default_user_redirect = "http://admin.nitrogen.io";

config.user_session_secret = process.env.USER_SESSION_SECRET || "development";
config.user_session_timeout_seconds = 30 * 24 * 60 * 60; // seconds (30 days)

// Security configuration parameters.  Make sure you know what you are doing before changing
// any of these parameters.

config.password_hash_iterations = 10000;
config.password_hash_length = 128;
config.salt_length_bytes = 64;
config.reset_password_length = 10;
config.minimum_password_length = 8;

config.auth_code_bytes = 16;
config.api_key_bytes = 16;
config.unassigned_apikey_pool_size = 10;

config.nonce_bytes = 32;
config.nonce_lifetime_seconds = 5 * 60;
config.public_key_bits = 2048;
config.public_key_exponent = 65537;

config.auth_code_lifetime_seconds = 60 * 60; // seconds (default: 1 hour)

config.device_secret_bytes = 128;

config.access_token_bytes = 32;
config.access_token_lifetime = 7; // days
config.access_token_signing_key = process.env.ACCESS_TOKEN_SIGNING_KEY || '12345678901234567890123456789012';

config.blob_cache_lifetime = 2592000; // seconds

// # of days a message should be remain in indexed storage by default
config.default_message_indexed_lifetime = 7; // days

config.permissions_for_cache_lifetime_minutes = 24 * 60; // minutes
config.principals_cache_lifetime_minutes = 24 * 60; // minutes

// Provider configurations
config.flatten_messages = false;
config.archive_providers = [];

// when the token gets within 10% (default) of config.access_token_lifetime,
// refresh it with a new token via the response header.
config.refresh_token_threshold = 0.1;

config.redis_servers = {
    "n2-redis-1": {
        "host": process.env.REDIS_HOST || "localhost",
        "port": process.env.REDIS_PORT || 6379,
        "password": process.env.REDIS_PASSWORD
    }
};

if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_KEY) {
    console.log('archive_provider: using Azure Table storage.');

    var azureTableStorageProvider = new azureProviders.AzureTableStorageProvider(config, log);
    config.archive_providers.push(azureTableStorageProvider);
    config.primary_archive_provider = azureTableStorageProvider;

    console.log('blob_provider: using Azure Blob storage.');
    config.blob_provider = new azureProviders.AzureBlobProvider(config, log);

    config.images_endpoint = config.blob_provider.base_endpoint + "/images";

    // Eventhub configuration - add to archive providers for now.
    if (process.env.AZURE_SERVICE_BUS && process.env.AZURE_SAS_KEY_NAME && process.env.AZURE_SAS_KEY && process.env.AZURE_EVENTHUB_NAME) {
        config.archive_providers.push(new azureProviders.AzureEventHubProvider(config, log));
    }

    console.log('pubsub_provider: using Azure queues pubsub.');
    config.pubsub_provider = new azureProviders.AzureQueuesPubSubProvider(config, log);
} else {
    console.log('archive_provider: using local storage.');

    var nullArchiveProvider = new localProviders.NullArchiveProvider(config, log);
    config.archive_providers.push(nullArchiveProvider);
    config.primary_archive_provider = nullArchiveProvider;

    console.log('blob_provider: using local storage.');
    config.blob_storage_path = './storage';
    config.blob_provider = new localProviders.LocalBlobProvider(config, log);

    console.log('pubsub_provider: using Redis pubsub.');
    config.pubsub_provider = new redisProviders.RedisPubSubProvider(config, log);
}

console.log('cache_provider: Using redis cache provider.');
config.cache_provider = new redisProviders.RedisCacheProvider(config, log);

console.log('email_provider: using null provider.');
config.email_provider = new localProviders.NullEmailProvider(config, log);

// You can use Loggly's log service by specifying these 4 environmental variables

// if you'd like additional indexes applied to messages at the database layer, you can specify them here.
config.message_indexes = [
];

// Claim codes are what users use to claim devices they have added to the service when IP matching fails.
// Longer claim codes are more secure but less convienent for users.
config.claim_code_length = 8;

// run the janitor every minute
config.janitor_interval = 60 * 1000; // ms

// Validate all message schemas to conform to all core and installed schemas.
config.validate_schemas = true;

// Email address that the service should use for administrative emails.
config.service_email_address = "admin@nitrogen.io";

// Migration configuration
config.migrations_relative_path = "/node_modules/nitrogen-core/migrations/";

// Test fixture location configuration
config.blob_fixture_path = 'node_modules/nitrogen-core/test/fixtures/images/image.jpg';

module.exports = config;


text:
"""
Abstract Base Class for Handler
"""
from abc import ABCMeta

class BaseHandler(metaclass=ABCMeta):
    """
    Base event handler
    """
    session = None
    subscribe_topic = None
    publish_topic = None

    def set_session(self, session):
        """
        Setup session for publishing
        """
        self.session = session