text:
package edu.berkeley.eecs.emission.cordova.tracker.location;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;

import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;

import java.util.LinkedList;
import java.util.List;

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

import edu.berkeley.eecs.emission.cordova.serversync.ServerSyncUtil;
import edu.berkeley.eecs.emission.cordova.tracker.ConfigManager;
import edu.berkeley.eecs.emission.cordova.tracker.verification.SensorControlBackgroundChecker;
import edu.berkeley.eecs.emission.cordova.tracker.ExplicitIntent;
import edu.berkeley.eecs.emission.cordova.tracker.sensors.BatteryUtils;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.NotificationHelper;
import edu.berkeley.eecs.emission.R;

import edu.berkeley.eecs.emission.cordova.tracker.location.actions.ActivityRecognitionActions;
import edu.berkeley.eecs.emission.cordova.tracker.location.actions.OPGeofenceExitActivityActions;
import edu.berkeley.eecs.emission.cordova.tracker.location.actions.GeofenceActions;
import edu.berkeley.eecs.emission.cordova.tracker.location.actions.LocationTrackingActions;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log;
import edu.berkeley.eecs.emission.cordova.usercache.UserCacheFactory;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.Transition;

/**
 * Created by shankari on 9/12/15.
 */

public class TripDiaryStateMachineService extends Service {
    public static String TAG = "TripDiaryStateMachineService";
    private static String OP_GEOFENCE_CFG = "OP_GEOFENCE_CFG";

    private static int STATE_IN_NUMBERS = 78283;

    private String mCurrState = null;
    private String mTransition = null;
    private SharedPreferences mPrefs = null;
    private ForegroundServiceComm mComm = null;
    private JSONObject opGeofenceCfg = null;

    public TripDiaryStateMachineService() {
        super();
    }

    @Override
    public void onCreate() {
        Log.i(this, TAG, "Service created. Initializing one-time variables!");
        mComm = new ForegroundServiceComm(this);
        /*
         * Need to initialize once per create.
         */
    }

    @Override
    public void onDestroy() {
        Log.i(this, TAG, "Service destroyed. So long, suckers!");
        mComm.unbind();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent,  int flags, int startId) {
        Log.d(this, TAG, "service started with flags = "+flags+" startId = "+startId
                +" action = "+intent.getAction());
        if (flags == Service.START_FLAG_REDELIVERY) {
            Log.d(this, TAG, "service restarted! need to check idempotency!");
        }
        mTransition = intent.getAction();

        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        mCurrState = mPrefs.getString(this.getString(R.string.curr_state_key),
            this.getString(R.string.state_start));
        Log.d(this, TAG, "after reading from the prefs, the current state is "+mCurrState);
        UserCacheFactory.getUserCache(this).putMessage(R.string.key_usercache_transition,
                new Transition(mCurrState, mTransition, ((double)System.currentTimeMillis())/1000));
        handleAction(this, mCurrState, mTransition);

        /*
         We are returning with START_REDELIVER_INTENT, so the process will be restarted with the
         same intent if it is killed. We need to think through the implications of this. If the
         process was killed before any of the actions were performed, then we are fine. If the
         process was killed after the actions were performed, then we are in trouble, because the
         actions are not necessarily idempotent.

         Some of the actions are clearly idempotent. For example, starting the activity recognition
         API. For example, deleting a geofence. It might be easiest to convert the actions to be
         idempotent, but that requires some careful work. TODO: Need to think through this carefully.
         */
        return START_REDELIVER_INTENT;
    }

    public static String getState(Context ctxt) {
        SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(ctxt);
        return sPrefs.getString(ctxt.getString(R.string.curr_state_key), ctxt.getString(R.string.state_start));
    }

    public void setNewState(String newState, boolean doChecks) {
        Log.d(this, TAG, "newState after handling action is "+newState);
        SharedPreferences.Editor prefsEditor =
                PreferenceManager.getDefaultSharedPreferences(this).edit();
        prefsEditor.putString(this.getString(R.string.curr_state_key), newState);
        prefsEditor.commit();
        Log.d(this, TAG, "newState saved in prefManager is "+
                PreferenceManager.getDefaultSharedPreferences(this).getString(
                        this.getString(R.string.curr_state_key), "not found"));
        mComm.setNewState(newState);
        // Let's check the location settings every time we change the state instead of only on failure
        // This makes the rest of the code much simpler, allows us to catch issues as quickly as possible,
        // and
        if (doChecks) {
            SensorControlBackgroundChecker.checkAppState(TripDiaryStateMachineService.this);
        }
        stopSelf();
    }

    /*
     * Handles the transition based on the current state.
     * Assumes that the API client is already connected.
     * TODO: It looks like the various actions are actually pretty similar - they invoke a
     * method on the API and then wait for a callback. It seems like it should be possible
     * to write a generic action that takes the google API call and the broadcast intent
     * as parameters, makes the call, and issues the broadcast in the callback
     */
    private void handleAction(Context ctxt, String currState, String actionString) {
        Log.d(this, TAG, "handleAction("+currState+", "+actionString+") called");
        assert(currState != null);
        // The current state is stored in the shared preferences, so on reboot, for example, we would
        // store that we are in ongoing_trip, but no listeners would be registered. We can have
        // the broadcast receiver generate an initialize transition, but the states other than
        // start don't handle initialize. So if we get an initialize, we manually call the start method.
        // This does not cover the case in which we get an initialize transition without a reboot, when
        // an earlier geofence or tracking might well be present.
        // TODO: Figure out how best to handle this and handle it. Options are:
        // - have a set state which allows the broadcast code and the test code to set the state to start
        // when restarting
        // - have initialize function as a reset, which stops any current stuff and starts the new one
        UserCacheFactory.getUserCache(ctxt).putSensorData(R.string.key_usercache_battery,
                BatteryUtils.getBatteryInfo(ctxt));
        try {
        this.opGeofenceCfg = UserCacheFactory.getUserCache(this).getLocalStorage(OP_GEOFENCE_CFG, false);
        } catch (JSONException e) {
            this.opGeofenceCfg = null;
        }
        if (opGeofenceCfg == null) {
            Log.i(this, TAG, "opGeofenceCfg == null, opGeofence disabled, "+
                " using only google geofence");
        } else {
            Log.i(this, TAG, "opGeofenceCfg != null, opGeofence enabled, "+
                " using both geofences");
        }
        if (actionString.equals(ctxt.getString(R.string.transition_initialize))) {
            handleStart(ctxt, actionString);
        } else if (currState.equals(ctxt.getString(R.string.state_start))) {
            handleStart(ctxt, actionString);
        } else if (currState.equals(ctxt.getString(R.string.state_waiting_for_trip_start))) {
            handleTripStart(ctxt, actionString);
        } else if (currState.equals(ctxt.getString(R.string.state_ongoing_trip))) {
            handleTripEnd(ctxt, actionString);
        } else if (currState.equals(ctxt.getString(R.string.state_tracking_stopped))) {
            handleTrackingStopped(ctxt, actionString);
        }
        Log.d(this, TAG, "handleAction("+currState+", "+actionString+") completed, waiting for async operations to complete");
    }

    private void handleStart(final Context ctxt, String actionString) {
        Log.d(this, TAG, "TripDiaryStateMachineReceiver handleStarted(" + actionString + ") called");

        // Get current location
        if (actionString.equals(ctxt.getString(R.string.transition_initialize)) &&
                !mCurrState.equals(ctxt.getString(R.string.state_tracking_stopped))) {
            // create the significant motion callback first since it is
            // synchronous and the geofence is not
            createGeofenceInThread(ctxt, actionString);
            /*
             * Since we currently have the opGeofence controlled by a config
             * option, we cannot assume that we only need to create a geofence
             * on re-initialize. If the initialize was triggered by the user
             * turning off the experimental geofence, we may need to delete the
             * existing op-geofence.
             */
            if (opGeofenceCfg == null) {
                new OPGeofenceExitActivityActions(ctxt).stop().addOnCompleteListener(task -> {
                    Log.e(ctxt, TAG, "removed opgeofence on initialize, result is "+task.getResult());
                });
            }
            return;
            // we will wait for async geofence creation to complete
        }

        // One would think that we don't need to deal with anything other than starting from the start
        // state, but we can be stuck in the start state for a while if it turns out that the geofence is
        // not created correctly. If the user forces us to stop tracking then, we still need to do it.
        if (actionString.equals(ctxt.getString(R.string.transition_stop_tracking))) {
            // Haven't started anything yet (that's why we are in the start state).
            // just move to the stop tracking state
            String newState = ctxt.getString(R.string.state_tracking_stopped);
            setNewState(newState, true);
            return;
        }

        if (actionString.equals(ctxt.getString(R.string.transition_tracking_error))) {
            /*
            NotificationHelper.createNotification(ctxt, Constants.TRACKING_ERROR_ID,
                    "Location tracking turned off. Please turn on for emission to work properly");
                    */
            Log.i(this, TAG, "Already in the start state, so going to stay there");
            setNewState(mCurrState, false);
            return;
        }

        // if we got here, this must be a transition that we don't handle
        Log.i(this, TAG, "Found unhandled transition "+actionString+" staying in current state ");
        boolean checkSettings = !mCurrState.equals(ctxt.getString(R.string.state_tracking_stopped));
        Log.i(this, TAG, "curr state = "+mCurrState+" checkSettings = "+checkSettings);
        setNewState(mCurrState, checkSettings);
    }

    public void handleTripStart(Context ctxt, final String actionString) {
        Log.d(this, TAG, "TripDiaryStateMachineReceiver handleTripStart(" + actionString + ") called");

        if (actionString.equals(ctxt.getString(R.string.transition_exited_geofence))) {
            // Delete geofence
            // we cannot add null elements to the token list.
            // the LocationTracking start action can now return null
            // so we need to handle it similar to the createGeofence in handleTripEnd
            final List<Task<Void>> tokenList = new LinkedList<Task<Void>>();
            tokenList.add(new GeofenceActions(ctxt).remove());
            if (opGeofenceCfg != null) {
                tokenList.add(new OPGeofenceExitActivityActions(ctxt).stop());
            }
            tokenList.add(new ActivityRecognitionActions(ctxt).start());
            Task<Void> locationTrackingResult = new LocationTrackingActions(ctxt).start();
            if (locationTrackingResult != null) {
              tokenList.add(locationTrackingResult);
            } else {
                // if we can't turn on the location tracking, we may as well not start the activity
                // recognition
                tokenList.remove(1);
            }
            final boolean locationTrackingPossible = locationTrackingResult != null;

            // TODO: How to pass in the token list?
            // Also, the callback is currently the same for all of them, but could potentially be
            // different in the future once we add in failure handling because we may want to do
            // different things based on the different failure cases. If we don't do that, we should
            // refactor the callback to a common class. and then we need to pass in the token list to it
            // since it can't use the final variable
            final Context fCtxt = ctxt;
            Tasks.whenAllComplete(tokenList).addOnCompleteListener(task -> {
              List<Task<?>> resultList = task.getResult();
                    String newState;
                    if (locationTrackingPossible) {
                        newState = fCtxt.getString(R.string.state_ongoing_trip);
                    } else {
                        // If we are not going to be able to start location tracking, then we don't
                        // want to go to ongoing_trip, because then we will never exit
                        // from it. Instead, we go to state_start so that we will try to get
                        // out of it at every sync.
                        newState = fCtxt.getString(R.string.state_start);
                    }
              if (TripDiaryStateMachineService.isAllSuccessful(resultList)) {
                        if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.success_moving_new_state, newState));
                        }
                        setNewState(newState, true);
                    } else {
                if (locationTrackingPossible && resultList.get(2).isSuccessful()) {
                                // the location tracking started successfully
                                setNewState(fCtxt.getString(R.string.state_ongoing_trip), true);
                            } else {
                                setNewState(fCtxt.getString(R.string.state_start), true);
                            }
                            // NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                            //         "Error " + batchResult.getStatus().getStatusCode()+" while creating geofence");
                            // this will perform some additional checks which we should wait for
                        }
                        if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.failed_moving_new_state,newState));
              } // both branches have called setState or are waiting for sth else
            }); // listener end
            return; // handled the transition, returning
        }

        if(actionString.equals(ctxt.getString(R.string.transition_stop_tracking))) {
            // Delete geofence
            deleteGeofence(ctxt, ctxt.getString(R.string.state_tracking_stopped));
            return;
            // when this completes, it should generate transitions and move to the final state
        }

        if (actionString.equals(ctxt.getString(R.string.transition_tracking_error))) {
            /*
            NotificationHelper.createNotification(ctxt, Constants.TRACKING_ERROR_ID,
                    "Location tracking turned off. Please turn on for emission to work properly");
                    */
            Log.i(this, TAG, "Got tracking_error moving to start state");
            deleteGeofence(ctxt, ctxt.getString(R.string.state_start));
            return;
            // when this completes, it should generate transitions and move to the final state
        }

        // if we got here, this must be a transition that we don't handle
        Log.i(this, TAG, "Found unhandled transition "+actionString+" staying in current state ");
        setNewState(mCurrState, true);
    }

    public void handleTripEnd(final Context ctxt, final String actionString) {
        Log.d(this, TAG, "TripDiaryStateMachineReceiver handleTripEnd(" + actionString + ") called");

        if (actionString.equals(ctxt.getString(R.string.transition_stopped_moving))) {
            // Stopping location tracking
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Running in new thread!!");
            final List<Task<Void>> tokenList = new LinkedList<Task<Void>>();
            tokenList.add(new LocationTrackingActions(ctxt).stop());
            tokenList.add(new ActivityRecognitionActions(ctxt).stop());
                    // TODO: change once we move to chained promises

            Task<Void> createGeofenceResult = new GeofenceActions(ctxt).create();
            if (createGeofenceResult != null) {
                tokenList.add(createGeofenceResult);
            }
            if (opGeofenceCfg != null) {
                tokenList.add(new OPGeofenceExitActivityActions(ctxt).start());
            }
                    final boolean geofenceCreationPossible = createGeofenceResult != null;
            final Context fCtxt = ctxt;
            Tasks.whenAllComplete(tokenList).addOnCompleteListener(task -> {
                List<Task<?>> resultList = task.getResult();
                            String newState;
                            if (geofenceCreationPossible) {
                                newState = fCtxt.getString(R.string.state_waiting_for_trip_start);
                            } else {
                                // If we are not going to be able to create a geofence, then we don't
                                // want to go to waiting_for_trip_state, because then we will never exit
                                // from it. Instead, we go to state_start so that we will try to get
                                // out of it at every sync.
                                newState = fCtxt.getString(R.string.state_start);
                            }
                if (TripDiaryStateMachineService.isAllSuccessful(resultList)) {
                        if (ConfigManager.getConfig(ctxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.success_moving_new_state, newState));
                        }
                        setNewState(newState, true);
                    } else {
                        if (!resultList.get(0).isSuccessful()) {
                                // the location tracking stop failed
                                setNewState(fCtxt.getString(R.string.state_ongoing_trip), true);
                            } else if (geofenceCreationPossible &&
                            resultList.get(2).isSuccessful()) {
                                setNewState(fCtxt.getString(R.string.state_waiting_for_trip_start), true);
                            } else {
                                // geofence creation is not possible or it failed but location tracking
                                // did successfully stop. Let's go to the start state
                                setNewState(fCtxt.getString(R.string.state_start), true);
                            }
                            // NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                            //        "Error " + batchResult.getStatus().getStatusCode()+" while creating geofence");
                            // let's mark this operation as done since the other one is static
                        // markOngoingOperationFinished();
                            SensorControlBackgroundChecker.checkAppState(TripDiaryStateMachineService.this);
                            // will wait for async call to complete
                        }
                        if (ConfigManager.getConfig(ctxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.failed_moving_new_state, newState));
                    }
            });

            // Sync data after trip end
            ServerSyncUtil.syncData(ctxt);
        }
            }).start();
            return;
        }

        if (actionString.equals(ctxt.getString(R.string.transition_stop_tracking))) {
            stopAll(ctxt, ctxt.getString(R.string.state_tracking_stopped));
            return;
            // will wait for stopAll to set the state
        }

        if (actionString.equals(ctxt.getString(R.string.transition_tracking_error))) {
            /*
            NotificationHelper.createNotification(ctxt, Constants.TRACKING_ERROR_ID,
                    "Location tracking turned off. Please turn on for emission to work properly");
                    */
            Log.i(this, TAG, "Got tracking_error moving to start state");
            // should I stop everything? maybe to be consistent with the start state
            stopAll(this, ctxt.getString(R.string.state_start));
            return;
            // ditto
        }

        // if we got here, this must be a transition that we don't handle
        Log.i(this, TAG, "Found unhandled transition "+actionString+" staying in current state ");
        setNewState(mCurrState, true);
    }

    private void handleTrackingStopped(final Context ctxt, String actionString) {
        Log.d(this, TAG, "TripDiaryStateMachineReceiver handleTrackingStopped(" + actionString + ") called");
        if (actionString.equals(ctxt.getString(R.string.transition_start_tracking))) {
            ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize));
            setNewState(ctxt.getString(R.string.state_start), true);
            return;
            // createGeofenceInThread(ctxt, apiClient, actionString);
        } else {
            // we should have stopped everything when we got to this state,
            // but let's just stop them all again anyway to make sure that
            // they are really stopped and to provide a backstop for any
            // error conditions
            stopAll(ctxt, ctxt.getString(R.string.state_tracking_stopped));
            if (actionString.equals(ctxt.getString(R.string.transition_tracking_error))) {
                Log.i(this, TAG, "Tracking manually turned off, no need to prompt for location");
            }
            return;
        }
    }

    /*
      * This is basically what we used to do as part of the initialize transition, but we now do it from initialize
      * or from start_tracking so let's refactor to avoid sending a broadcast while handling a previous broadcast.
      * This may help with the weird tracking issues we have seen, like
      *
     */

    private void createGeofenceInThread(final Context ctxt,
                                        String actionString) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Running in new thread!!");
                final Context fCtxt = ctxt;
                // TODO: Ideally, new GeofenceActions would return a chained pending result.
                // Then, we would just wait for the combined result callback and all would be well
                // But it looks like the pending result chaining is not supported in the current
                // version of the google play services API. We could chain callbacks here, but then
                // we won't be able to deal with the common case (last location present) and the
                // uncommon case (last location not present) in a unified fashion. We would need
                // one callback for the first and two for the second.
                // So for now, we punt and simply start the geofence creation in a separate
                // (non-UI thread). Revisit this later once chaining is supported.
                final List<Task<Void>> tokenList = new LinkedList<Task<Void>>();
                Task<Void> createGeofenceResult =
                        new GeofenceActions(ctxt).create();
                if (createGeofenceResult != null) {
                    tokenList.add(createGeofenceResult);
                } else {
                    // Geofence was not created properly. let's make an async call that will generate its
                    // own state change
                    // let's mark this operation as done since the other one is static
                    // markOngoingOperationFinished();
                    SensorControlBackgroundChecker.checkAppState(fCtxt);
                }
                if (opGeofenceCfg != null) {
                    tokenList.add(new OPGeofenceExitActivityActions(ctxt).start());
                }
                Tasks.whenAllComplete(tokenList).addOnCompleteListener(task -> {
                            String newState = fCtxt.getString(R.string.state_waiting_for_trip_start);
                            if (task.isSuccessful()) {
                                setNewState(newState, true);
                                if (ConfigManager.getConfig(ctxt).isSimulateUserInteraction()) {
                                    NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                            null, fCtxt.getString(R.string.success_moving_new_state, newState));
                                }
                            } else {
                                    Log.e(fCtxt, TAG, "error while creating geofence, staying in the current state");
                                    Log.exception(fCtxt, TAG, task.getException());
                                    setNewState(mCurrState, true);

                                    // NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                    //        "Error " + status.getStatusCode()+" while creating geofence");
                                    // let's mark this operation as done since the other one is static
                                    // markOngoingOperationFinished();
                                }
                                if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                                    NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                            null, fCtxt.getString(R.string.failed_moving_new_state, newState));
                                }
                    });
            }
        }).start();
    }

    private void deleteGeofence(Context ctxt, final String targetState) {
        final List<Task<Void>> tokenList = new LinkedList<Task<Void>>();
        tokenList.add(new GeofenceActions(ctxt).remove());
        if (opGeofenceCfg != null) {
            tokenList.add(new OPGeofenceExitActivityActions(ctxt).stop());
        }
            final Context fCtxt = ctxt;
            Tasks.whenAllComplete(tokenList).addOnCompleteListener(task -> {
              List<Task<?>> resultList = task.getResult();
                    String newState = targetState;
                    if (TripDiaryStateMachineService.isAllSuccessful(resultList)) {
                        setNewState(newState, true);
                    if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.success_moving_new_state, newState));
                        }
                    } else {
                            setNewState(mCurrState, true);
                        // markOngoingOperationFinished();
                        SensorControlBackgroundChecker.checkAppState(TripDiaryStateMachineService.this);
                    }
                    if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.failed_moving_new_state, newState));
                    }
            });
    }

    private void stopAll(Context ctxt, final String targetState) {
            // We don't really care about any other transitions, but if we are getting random transitions
            // in this state, may be good to turn everything off
            final List<Task<Void>> tokenList = new LinkedList<Task<Void>>();
            tokenList.add(new GeofenceActions(ctxt).remove());
            if (opGeofenceCfg != null) {
                tokenList.add(new OPGeofenceExitActivityActions(ctxt).stop());
            }
            tokenList.add(new LocationTrackingActions(ctxt).stop());
            tokenList.add(new ActivityRecognitionActions(ctxt).stop());
            final Context fCtxt = ctxt;
            Tasks.whenAllComplete(tokenList).addOnCompleteListener(task -> {
              List<Task<?>> resultList = task.getResult();
                    String newState = targetState;
                    if (TripDiaryStateMachineService.isAllSuccessful(resultList)) {
                    if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.success_moving_new_state, newState));
                        }
                        setNewState(newState, false);
                    } else {
                    if (ConfigManager.getConfig(fCtxt).isSimulateUserInteraction()) {
                        NotificationHelper.createNotification(fCtxt, STATE_IN_NUMBERS,
                                null, fCtxt.getString(R.string.failed_moving_new_state, newState));
                    }

                        if (!resultList.get(1).isSuccessful()) {
                            // the location tracking stop failed
                            setNewState(fCtxt.getString(R.string.state_ongoing_trip), false);
                        } else {
                            setNewState(newState, false);
                        }
                    }
            });
        }

    protected static boolean isAllSuccessful(List<Task<?>> taskList) {
      boolean result = true;
      for (Task t:taskList) {
        result = result & t.isSuccessful();
      }
      return result;
    }
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>Cat-Clicker Premium</title>
		<link rel="stylesheet" href="css/style.css">

List of Cats

Nicknames

redpajama_set_name: RedPajamaGithub


text:
import unittest
import numpy as np
import sys

sys.path.append("..")

import op_test
import paddle
import paddle.fluid as fluid
import paddle.fluid.framework as framework
import paddle.fluid.layers as layers

paddle.enable_static()
np.random.seed(2021)

class TestAssignValueNPUOp(op_test.OpTest):
    def setUp(self):
        self.set_npu()
        self.place = paddle.NPUPlace(0)

        self.op_type = "assign_value"
        self.inputs = {}
        self.attrs = {}
        self.init_data()

        self.attrs["shape"] = self.value.shape
        self.attrs["dtype"] = framework.convert_np_dtype_to_dtype_(
            self.value.dtype
        )
        self.outputs = {"Out": self.value}

    def set_npu(self):
        self.__class__.use_npu = True

    def init_data(self):
        self.value = np.random.random(size=(2, 5)).astype(np.float32)
        self.attrs["fp32_values"] = [float(v) for v in self.value.flat]

    def test_forward(self):
        self.check_output_with_place(self.place)

class TestAssignValueNPUOp2(TestAssignValueNPUOp):
    def init_data(self):
        self.value = np.random.random(size=(2, 5)).astype(np.int32)
        self.attrs["int32_values"] = [int(v) for v in self.value.flat]

class TestAssignValueNPUOp3(TestAssignValueNPUOp):
    def init_data(self):
        self.value = np.random.random(size=(2, 5)).astype(np.int64)
        self.attrs["int64_values"] = [int(v) for v in self.value.flat]

class TestAssignValueNPUOp4(TestAssignValueNPUOp):
    def init_data(self):
        self.value = np.random.choice(a=[False, True], size=(2, 5)).astype(
            np.bool
        )
        self.attrs["bool_values"] = [int(v) for v in self.value.flat]

class TestAssignApi(unittest.TestCase):
    def setUp(self):
        self.init_dtype()
        self.value = (-100 + 200 * np.random.random(size=(2, 5))).astype(
            self.dtype
        )
        self.place = (
            fluid.NPUPlace(0)
            if fluid.core.is_compiled_with_npu()
            else fluid.CPUPlace()
        )

    def init_dtype(self):
        self.dtype = "float32"

    def test_assign(self):
        main_program = fluid.Program()
        with fluid.program_guard(main_program):
            x = layers.create_tensor(dtype=self.dtype)
            layers.assign(input=self.value, output=x)

        exe = fluid.Executor(self.place)
        [fetched_x] = exe.run(main_program, feed={}, fetch_list=[x])
        np.testing.assert_allclose(fetched_x, self.value)
        self.assertEqual(fetched_x.dtype, self.value.dtype)

class TestAssignApi2(TestAssignApi):
    def init_dtype(self):
        self.dtype = "int32"

class TestAssignApi3(TestAssignApi):
    def init_dtype(self):
        self.dtype = "int64"

class TestAssignApi4(TestAssignApi):
    def setUp(self):
        self.init_dtype()
        self.value = np.random.choice(a=[False, True], size=(2, 5)).astype(
            np.bool
        )
        self.place = (
            fluid.NPUPlace(0)
            if fluid.core.is_compiled_with_npu()
            else fluid.CPUPlace()
        )

    def init_dtype(self):
        self.dtype = "bool"

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


text:
package cz.jenda.pidifrky.ui.api

import android.support.v4.view.GestureDetectorCompat
import android.support.v7.widget.RecyclerView
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.{MotionEvent, View}
import com.malinskiy.superrecyclerview.SuperRecyclerView

/**
 * @author Jenda Kolena, jendakolena@gmail.com
 */
class RecyclerViewItemClickListener(recyclerView: SuperRecyclerView, listener: OnItemClickListener)(implicit ctx: BasicActivity) extends RecyclerView.OnItemTouchListener {

  recyclerView.addOnItemTouchListener(this)

  protected val gestureDetector = new GestureDetectorCompat(ctx, new SimpleOnGestureListener {

    override def onLongPress(e: MotionEvent): Unit = {
      val rv = recyclerView.getRecyclerView
      val childView = rv.findChildViewUnder(e.getX, e.getY)

      if (childView != null) {
        listener.onLongClick(childView, rv.getChildAdapterPosition(childView))
      }
    }

    override def onSingleTapUp(e: MotionEvent): Boolean = true
  })

  override def onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean = {
    val childView = rv.findChildViewUnder(e.getX, e.getY)

    if (childView != null && gestureDetector.onTouchEvent(e)) {
      listener.onClick(childView, rv.getChildAdapterPosition(childView))
    }

    false
  }

  override def onTouchEvent(rv: RecyclerView, e: MotionEvent): Unit = {}

  override def onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean): Unit = {}

}

object RecyclerViewItemClickListener {
  def apply(recyclerView: SuperRecyclerView, listener: OnItemClickListener)(implicit ctx: BasicActivity): RecyclerViewItemClickListener = {
    new RecyclerViewItemClickListener(recyclerView, listener)
  }
}

trait OnItemClickListener {
  def onClick(view: View, position: Int)

  def onLongClick(view: View, position: Int)
}


text:
//
//  UIFont+JOExtend.h
//  JOProjectBaseSDK
//
//  Created by 刘维 on 16/6/23.
//  Copyright © 2016年 刘维. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "JOMacro.h"

@interface JOFont : NSObject {
@public
    NSString *name;
    UIColor *color;
    UIFont *font;
    CGFloat size;
}

@end

/**
 *  JOFont Make
 *
 *  @param font      字体.
 *  @param fontColor 字体的颜色.
 *
 *  @return JOFont.
 */
JO_STATIC_INLINE JOFont *JOFontMake(UIFont *font,UIColor *fontColor) {

    JOFont *Font = [JOFont new];
    Font -> name = font.fontName;
    Font -> color = fontColor;
    Font -> size = font.pointSize;
    Font -> font = font;
    return Font;
}

/**
 *  JOFont Make
 *
 *  @param fontName  字体的名字.
 *  @param fontSize  字体的大小.
 *  @param fontColor 字体的颜色.
 *
 *  @return JOFont.
 */
JO_STATIC_INLINE JOFont *JOCFontMake(NSString *fontName,CGFloat fontSize,UIColor *fontColor) {

    UIFont *font = [UIFont fontWithName:fontName size:fontSize];
    return JOFontMake(font, fontColor);
}

/**
 *  JOFont Make
 *
 *  @param weight    UIFontWeightLight  UIFontWeightRegular  UIFontWeightBold ...
 *  @param fontSize  字体的大小.
 *  @param fontColor 字体的颜色.
 *
 *  @return JOFont.
 */
JO_STATIC_INLINE JOFont *JOSFontMake(CGFloat weight,CGFloat fontSize,UIColor *fontColor) NS_AVAILABLE_IOS(8_2) {

    UIFont *font = [UIFont systemFontOfSize:fontSize weight:weight];
    return JOFontMake(font, fontColor);
}

/**
 *  JOFont Make 主要针对IOS7以及以下的系统. Blod的字体
 *
 *  @param fontSize  字体的大小.
 *  @param fontColor 字体的颜色.
 *
 *  @return JOFont.
 */
JO_STATIC_INLINE JOFont *JOSBlodFontMake(CGFloat fontSize,UIColor *fontColor) {

    UIFont *font = [UIFont boldSystemFontOfSize:fontSize];
    return JOFontMake(font, fontColor);
}

/**
 *  JOFont Make 主要针对IOS7以及以下的系统. 平常的字体
 *
 *  @param fontSize  字体的大小.
 *  @param fontColor 字体的颜色.
 *
 *  @return JOFont.
 */
JO_STATIC_INLINE JOFont *JOSNormalFontMake(CGFloat fontSize,UIColor *fontColor) {

    UIFont *font = [UIFont systemFontOfSize:fontSize];
    return JOFontMake(font, fontColor);
}

@interface UIFont(Extend)

@end


text:
{% for post in site.posts %}
{% category_links %}
{% category_list %}
{% tag_links %}
{% tag_list %}
{% endfor %}


text:
from django.contrib import admin

from blog.models import Post
from blog.models import Comment

admin.site.register(Post)
admin.site.register(Comment)


text:
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Test
{
	using std::chrono::duration_cast;
	using std::chrono::seconds;
	using std::chrono::microseconds;
	TEST_CLASS(FundTest)
	{
	public:

		TEST_METHOD(betTest)
		{
			Fund fund;
			Assert::IsTrue(fund.getBetTime() == seconds(0),
				wstrf("getBetTime() failed").c_str());
			Assert::IsTrue(fund.getOwnTime() == seconds(60 * 60),
				wstrf("getOwnTime() failed").c_str());
			Assert::IsTrue(fund.bet(seconds(60 * 15)),
				wstrf("bet() failed").c_str());
			Assert::IsTrue(fund.getBetTime() == seconds(60 * 15),
				wstrf("Invalid bet time").c_str());
			Assert::IsTrue(fund.getOwnTime() == seconds(60 * 45),
				wstrf("Invalid own time").c_str());
			Assert::IsFalse(fund.bet(seconds(60 * 15)), wstrf("Twice bet").c_str());
			Fund fund2;
			Assert::IsFalse(fund2.bet(seconds(60 * 61)), wstrf("Over bet").c_str());
			Assert::IsFalse(fund2.bet(seconds(0)), wstrf("Zero bet").c_str());
		}

		TEST_METHOD(updateTest)
		{
			auto _15min = seconds(60 * 15);
			auto _45min = seconds(60 * 45);
			Fund fund;
			fund.bet(_15min);
			Assert::IsTrue(fund.update(PokerHand::NoHand, 0.0f) == 0.0f,
				wstrf("Invalid result of update(NoHand)").c_str());
			Assert::IsTrue(fund.getBetTime() == seconds(0),
				wstrf("Bet time reset failed").c_str());
			Assert::IsTrue(fund.getOwnTime() == _45min,
				wstrf("Own time spending failed").c_str());

			for (auto i = 0u; i < UI(PokerHand::NumHands); ++i) {
				Fund fund;
				fund.bet(_15min);
				auto hand = static_cast<PokerHand>(i);
				auto rate = Fund::getPayoutRate(hand);
				auto expectf = 10.0f * rate;
				auto expect = duration_cast<seconds>(microseconds(UI(expectf * 1000 * 1000)));
				Assert::IsTrue(fund.update(hand, 10.0f) == expectf,
					wstrf("Invalid result of update(%d)", i).c_str());
				Assert::IsTrue(fund.getOwnTime() == expect + _45min,
					wstrf("increaseBy(%d) failed", i).c_str());
			}
		}
	};
}


text:
<?php
// Heading
$_['heading_title']    = 'Sagepay Direct Card Management';

$_['text_extension']   = 'Extensions';
$_['text_success']     = 'Success: You have modified Sagepay Direct Card Management module!';
$_['text_edit']        = 'Edit Sagepay Direct Card Management Module';

// Entry
$_['entry_status']     = 'Status';

// Error
$_['error_permission'] = 'Warning: You do not have permission to modify Sagepay Direct Card Management module!';


text:
from .base_urls import *
from django.urls import include, re_path

urlpatterns += [
    re_path(r'^support', include('userservice.urls')),
    re_path(r'^restclients/', include('rc_django.urls')),
    re_path(r'^persistent_message/', include('persistent_message.urls')),
    re_path(r'^logging/', include('django_client_logger.urls')),
    re_path(r'^', include('myuw.urls')),
]


text:
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :populate_ivars, only: [:show, :compare]

  def compare
    @result = game.compare
    @stack = game.stack
    @type = Type.find(params[:type])
  end

  def number_type_info
    @type = Type.find(params[:type])
    render :layout => "dialog"
  end

  private
  def game
    @game ||= Game.new(params)
  end

  def populate_ivars
    @stack = game.stack
    @me = game.me
    @you = game.you
  end

end


text:
'use strict';

module.exports = testMethodCall;

var algoliasearch = require('../../');
var fauxJax = require('faux-jax');
var parse = require('url-parse');

var wrapMethodCallback = require('./wrap-method-callback');

function testMethodCall(opts) {
  var assert = opts.assert;
  var testCase = opts.testCase;

  var client = algoliasearch(opts.applicationID, opts.searchOnlyAPIKey);
  var object;
  if (opts.object === 'index') {
    object = client.initIndex(opts.indexName);
  } else {
    object = client;
  }

  // we wrap and replace the method callback (index.search('query', cb))
  // so that we have our `checkMethodCallback` called when the callback occured
  // as callback are asynchronous, we cannot use synchronous testing
  wrapMethodCallback(testCase.callArguments, checkMethodCallback);

  // this needs to be done here to be as close as possible to the new XMLHttpRequest() call
  fauxJax.install({gzip: true});

  object[opts.methodName].apply(object, testCase.callArguments);

  fauxJax.once('request', function(req) {
    fauxJax.restore();

    var actualRequest = req;
    var expectedRequest = testCase.expectedRequest;

    actualRequest.respond(
      testCase.fakeResponse.statusCode,
      testCase.fakeResponse.headers,
      JSON.stringify(testCase.fakeResponse.body)
    );

    assert.equal(
      actualRequest.requestMethod,
      expectedRequest.method,
      'Request method matches'
    );

    var actualRequestURL = parse(actualRequest.requestURL, true);
    var expectedRequestURL = expectedRequest.URL;

    if (testCase.action === undefined) {
      assert.fail('No action (read/write) given in the test case');
    } else if (testCase.action === 'read') {
      assert.equal(
        actualRequestURL.host,
        opts.applicationID.toLowerCase() + '-dsn.algolia.net',
        'We used the first read host (DSN)'
      );
    } else if (testCase.action === 'write') {
      assert.equal(
        actualRequestURL.host,
        opts.applicationID.toLowerCase() + '.algolia.net',
        'We used the first write host (fault tolerant)'
      );
    } else {
      assert.fail('Unkown action (read/write) found in the test case (was: ' + testCase.action + ')');
    }

    assert.equal(
      actualRequestURL.pathname,
      expectedRequestURL.pathname,
      'URL.pathname matches'
    );

    assert.equal(
      actualRequestURL.protocol,
      expectedRequestURL.protocol,
      'URL.protocol matches'
    );

    assert.deepEqual(
      actualRequestURL.query,
      expectedRequestURL.query,
      'URL.query matches'
    );

    if (actualRequest.requestBody) {
      assert.deepEqual(
        JSON.parse(actualRequest.requestBody),
        expectedRequest.body,
        'Request body matches'
      );
    } else {
      assert.pass('No body set');
    }

    if (!process.browser) {
      // all these headers are handled by nodejs, sometimes
      // differently between versions, we do not care
      delete actualRequest.requestHeaders.connection;
      delete actualRequest.requestHeaders['transfer-encoding'];
      delete actualRequest.requestHeaders.host;
      delete actualRequest.requestHeaders['content-length'];
    }

    if (!process.browser || fauxJax.support.xhr.cors) {
      assert.deepEqual(
        actualRequest.requestHeaders,
        expectedRequest.headers,
        'Request headers matches'
      );
    } else {
      assert.pass('Cannot check requestHeaders, CORS not supported');
    }
  });

  function checkMethodCallback(methodCallback) {
    assert.ok(
      methodCallback.calledOnce,
      'Callback was called once'
    );

    var error = testCase.fakeResponse.statusCode === 200 ? null : Error;
    var args = methodCallback.getCall(0).args;

    if (error) {
      assert.ok(
        args[0] instanceof Error && args.length === 1,
        'We received an error and only an error'
      );
    } else {
      assert.deepEqual(
        methodCallback.getCall(0).args,
        error ? [error] : [error, testCase.fakeResponse.body],
        'Callback called with callback(err, res)'
      );
    }
  }
}

// we do 3 asserts per test
testMethodCall.assertCount = 9;


text:
package org.knowm.xchange.bitflyer.dto.account;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 * Object representing json returned from GET /v1/me/getaddresses
 *
 *
Example [ { "type": "NORMAL", "currency_code": "BTC", "address":
 * "3AYrDq8zhF82NJ2ZaLwBMPmaNziaKPaxa7" }, { "type": "NORMAL", "currency_code": "ETH", "address":
 * "0x7fbB2CC24a3C0cd3789a44e9073381Ca6470853f" } ]
 *
 * @author bryant_harris
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"type", "currency_code", "address"})
public class BitflyerAddress {
  @JsonProperty("type")
  private String type;

  @JsonProperty("currency_code")
  private String currencyCode;

  @JsonProperty("address")
  private String address;

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public String getCurrencyCode() {
    return currencyCode;
  }

  public void setCurrencyCode(String currency_code) {
    this.currencyCode = currency_code;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Override
  public String toString() {
    return "BitflyerAddress [type="
        + type
        + ", currency_code="
        + currencyCode
        + ", address="
        + address
        + "]";
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.UnitTests.Emit
{
    public class EmitBaselineTests
    {
        [Fact]
        public void CreateInitialBaseline_Errors()
        {
            var debugInfoProvider = new Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation>(_ => default);
            var localSigProvider = new Func<MethodDefinitionHandle, StandaloneSignatureHandle>(_ => default);
            var peModule = ModuleMetadata.CreateFromImage(TestResources.Basic.Members);
            var peReader = peModule.Module.PEReaderOpt;

            var mdBytes = peReader.GetMetadata().GetContent();
            var mdBytesHandle = GCHandle.Alloc(mdBytes.DangerousGetUnderlyingArray(), GCHandleType.Pinned);
            var mdModule = ModuleMetadata.CreateFromMetadata(mdBytesHandle.AddrOfPinnedObject(), mdBytes.Length);

            Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(null, debugInfoProvider));
            Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(peModule, null));
            Assert.Throws<ArgumentException>(() => EmitBaseline.CreateInitialBaseline(mdModule, debugInfoProvider));

            Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(null, debugInfoProvider, localSigProvider, true));
            Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(peModule, null, localSigProvider, true));
            Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(mdModule, debugInfoProvider, null, true));
            Assert.NotNull(EmitBaseline.CreateInitialBaseline(mdModule, debugInfoProvider, localSigProvider, true));
        }
    }
}


text:
	<md-content layout-fill flex class="md-padding page-content">
    <md-tabs md-selected="selectedIndex" md-border-bottom md-autoselect flex layout="column" layout-fill md-dynamic-height>
      <md-tab ng-repeat="place in wc.exampleLocations"
              label="{{place.name}}">

          <md-content class="md-padding" layout-xs="column" layout="row">

		      <md-card md-theme="default" md-theme-watch>
		        <md-card-title>
		          <md-card-title-text>
		            {{place.weather[0].main}}
		            {{place.weather[0].description}}
		            Wind
		            Speed - {{place.wind.speed}}
		            Degree - {{place.wind.deg}}
		          </md-card-title-text>
		          <md-card-title-media>

		          </md-card-title-media>
		        </md-card-title>
		        <md-card-actions layout="row" layout-align="start center">
		           Temp <md-button>{{place.main.temp}} ℃</md-button>
		           Pressure <md-button>{{place.main.pressure}}</md-button>
		           humidity <md-button>{{place.main.humidity}}</md-button>
		           Temp Max <md-button>{{place.main.temp_max}} ℃</md-button>
		           Temp Min <md-button>{{place.main.temp_min}} ℃</md-button>
		        </md-card-actions>
		      </md-card>

		    </md-content>

      </md-tab>
    </md-tabs>
  </md-content>
  <md-content layout-gt-sm="column" layout-padding layout-align="center center">

      <md-input-container>
        Place
        <input ng-model="wc.place">
      </md-input-container>

      <md-input-container>
        <md-button class="md-raised md-warn" ng-click="wc.getEachWeather(wc.place)">Get Weather</md-button>
      </md-input-container>

  </md-content>


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

	<changeSet id="create OO_HILO table" author="test">
		<createTable tableName="OO_HILO">
			<column name="NEXT_HI" type="INT"/>
		</createTable>
		<insert tableName="OO_HILO">
			<column name="NEXT_HI" value="0"/>
		</insert>
	</changeSet>

	<changeSet id="create OO_EXECUTION_STATES" author="engine">
		<createTable tableName="OO_EXECUTION_STATES">
			<column name="ID" type="bigint">
				<constraints primaryKey="true" nullable="false"/>
			</column>
			<column name="MSG_ID" type="varchar(255)">
				<constraints nullable="false"/>
			</column>
			<column name="PAYLOAD" type="blob">
				<constraints nullable="false"/>
			</column>
			<column name="CREATE_TIME" type="timestamp"/>
		</createTable>
	</changeSet>

	<changeSet id="create OO_EXECUTION_QUEUES" author="engine">
		<createTable tableName="OO_EXECUTION_QUEUES">
			<column name="ID" type="bigint"><constraints primaryKey="true" nullable="false"/></column>
			<column name="EXEC_STATE_ID" type="bigint"><constraints nullable="false"/></column>
			<column name="ASSIGNED_WORKER" type="varchar(40)"/>
			<column name="EXEC_GROUP" type="varchar(255)"><constraints nullable="false"/></column>
			<column name="STATUS" type="integer"/>
			<column name="MSG_SEQ_ID" type="integer"><constraints nullable="false"/></column>
			<column name="CREATE_TIME" type="timestamp"/>
			<column name="MSG_VERSION" type="BIGINT" />
		</createTable>

        <addUniqueConstraint constraintName="OO_EXECUTION_QUEUES_CONSTRAINT" columnNames="EXEC_STATE_ID, MSG_SEQ_ID" tableName="OO_EXECUTION_QUEUES"/>
	</changeSet>

	<changeSet id="add index to OO_EXECUTION_QUEUES tables" author="engine">
		<createIndex tableName="OO_EXECUTION_QUEUES" indexName="OO_Q_EXEC_STATE_1_IDX"><column name="EXEC_STATE_ID"/></createIndex>
		<createIndex tableName="OO_EXECUTION_QUEUES" indexName="OO_Q_CREATE_TIME_1_IDX"><column name="CREATE_TIME"/></createIndex>
	</changeSet>
</databaseChangeLog>


text:
class ChangeDefaultFeedbackEmail < ActiveRecord::Migration[4.2]
  def up
    change_column_default :sites, :feedback_email, '"Petitions: UK Government and Parliament" <petitionscommittee@parliament.uk>'
  end

  def down
    change_column_default :sites, :feedback_email, '"Petitions: UK Government and Parliament" <feedback@petition.parliament.uk>'
  end
end


text:
<?php

if (!defined('BASEPATH')) define('BASEPATH', '/z/codeigniter/system');
if (!defined('APPPATH')) define('APPPATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/app/front/');

require __DIR__.'/../../../vendor/adodb/adodb-php/adodb-exceptions.inc.php';
require __DIR__.'/../../../vendor/adodb/adodb-php/adodb.inc.php';

use Slider\Factory\SlideFactory;
use Slider\Persistence\SlideAdoDbPersistence AS SlidePersistence;
use Slider\Repository\SlideRepository;

/**
*
*/
class SlidePersistenceTest extends PHPUnit_Framework_TestCase
{
    private $db;
    private $stack;

    public function __construct()
    {
        parent::__construct();

        require APPPATH.'config/development/database.php';

        $this->db = NewADOConnection('mysql');
        $this->db->Connect($db['default']['hostname'], $db['default']['username'], $db['default']['password'], $db['default']['database']);

        $created = date('Y-m-d h:i:s');
        $upadted = $created;

        $this->stack[] = array(
                            'Title' => 'Titulo del slide',
                            'Description' => 'Descripcion del slide',
                            'Img' => 'imgTest.png',
                            'Link' => 'http://www.google.com.ar',
                            'CreatedAt' => $created,
                            'UpdatedAt' => $upadted);

        $this->stack[] = array(
                            'Title' => 'Titulo del slide 2',
                            'Description' => 'Descripcion del slide 2',
                            'Img' => 'imgTest2.png',
                            'Link' => 'http://www.asd.com.ar',
                            'CreatedAt' => $created,
                            'UpdatedAt' => $upadted);

        $this->stack[] = array(
                            'Title' => 'Titulo del slide 3',
                            'Description' => 'Descripcion del slide 3',
                            'Img' => 'imgTest3.png',
                            'Link' => 'http://www.lol.com.ar',
                            'CreatedAt' => $created,
                            'UpdatedAt' => $upadted);
    }

    public function testEnviaObjectoARepositorio()
    {
        $slideData = $this->stack[0];

        $factory = new SlideFactory();
        $slide = $factory->make($slideData);

        $persistence = new SlidePersistence();

        $repository = new SlideRepository($persistence);
        $repository->addSlide($slide);

        $slide2 = $repository->getLastSlide();

        $this->assertNotEmpty($slide2->getId());
        $this->assertEquals($slide->getTitle(), $slide2->getTitle());
        $this->assertEquals($slide->getDescription(), $slide2->getDescription());
        $this->assertEquals($slide->getImg(), $slide2->getImg());
        $this->assertEquals($slide->getLink(), $slide2->getLink());
        $this->assertEquals($slide->getCreatedAt(), $slide2->getCreatedAt());
        $this->assertEquals($slide->getUpdatedAt(), $slide2->getUpdatedAt());
    }
}


text:
package com.adobe.dp.fb2.convert;

import java.io.IOException;
import java.util.Hashtable;

import com.adobe.dp.css.CSSStylesheet;
import com.adobe.dp.css.CSSURL;
import com.adobe.dp.otf.ByteArrayFontInputStream;
import com.adobe.dp.otf.FontInputStream;
import com.adobe.dp.otf.FontLocator;
import com.adobe.dp.otf.FontProperties;

public class EmbeddedFontLocator extends FontLocator {

	Hashtable fontSrcs;

	CSSStylesheet stylesheet;

	FontLocator chained;

	public EmbeddedFontLocator(CSSStylesheet stylesheet, FontLocator chained) {
		this.stylesheet = stylesheet;
		this.chained = chained;
	}

	public FontInputStream locateFont(FontProperties key) throws IOException {
		CSSURL src = (CSSURL) fontSrcs.get(key);
		try {
			if (src != null) {
				return new ByteArrayFontInputStream(src.getData());
			}
		} catch (IOException e) {
		}
		return chained.locateFont(key);
	}

	public boolean hasFont(FontProperties key) {
		CSSURL src = (CSSURL) fontSrcs.get(key);
		try {
			if (src != null && src.getData() != null)
				return true;
		} catch (IOException e) {
		}
		return chained.hasFont(key);
	}

}


text:
package org.opensingular.form.decorator.action;

import org.opensingular.form.SIList;
import org.opensingular.form.SInstance;
import org.opensingular.form.SType;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.type.basic.AtrBasic;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * Provider para a ação de exibição do Help do campo.
 */
public class SInstanceHelpActionsProvider implements ISInstanceActionsProvider {

    private final List<String> renderedAsListField;

    public SInstanceHelpActionsProvider(List<String> renderedAsListField) {
        this.renderedAsListField = renderedAsListField;
    }

    @Override
    public Iterable<SInstanceAction> getActions(ISInstanceActionCapable target, SInstance instance) {
        if (renderedAsListField.contains(instance.getType().getPathFull())) {
            return Collections.emptyList();
        }

        return doHelpAction(instance.asAtr().getLabel(), instance.asAtr().getHelp());
    }

    @Override
    public List<SInstanceAction> getListFieldActions(ISInstanceActionCapable target, SIList<?> instance, String field) {
        final AtrBasic atr;
        if ((instance.getElementsType() instanceof STypeComposite<?>) && isNotBlank(field)) {
            STypeComposite<?> compositeType = (STypeComposite<?>) instance.getElementsType();
            SType<?>          foundField    = compositeType.getField(field);
            if (foundField != null) {
                atr = foundField.asAtr();
            } else {
                atr = instance.getElementsType().asAtr();
            }
        } else {
            atr = instance.getElementsType().asAtr();
        }
        return doHelpAction(atr.getLabel(), atr.getHelp());
    }

    private List<SInstanceAction> doHelpAction(String title, final String helpText) {
        return (isBlank(helpText))
                ? Collections.emptyList()
                : Arrays.asList(new SInstanceAction(SInstanceAction.ActionType.NORMAL)
                .setIcon(SIcon.resolve("question"))
                .setText("Ajuda")
                .setPosition(Integer.MIN_VALUE)
                .setImportant(true)
                .setPreview(new SInstanceAction.Preview()
                        .setTitle(title)
                        .setMessage(helpText)
                        .setFormat("HTML")));
    }
}


text:
class Specinfra::Command::Debian::V8::Service < Specinfra::Command::Debian::Base::Service
  class << self
    include Specinfra::Command::Module::Systemd
  end
end


text:
import fu from './libs/files-utils';
import pkg from '../package.json';
import c from './libs/config';

/**
 * Upgrade version inside package.json and web.config ([OPT-IN]) according semver.
 * This task could be called directly
 * @return {Promise} A Promise
 * @example <caption>run this on your terminal</caption>
 * node src/run bump
 */
async function bump() {
	const config = c().load();
	const versionRequest = process.argv[process.argv.length - 1];
	// update package.json and web.config(OPT-IN) in parallel
	await Promise.all([
		fu.updatePackageJson(versionRequest, pkg, config),
		fu.updateWebconfig(versionRequest, pkg, config),
	]);
}

export default bump;


text:
import List from "src/dataTypes/lists/List";
import Table from "src/dataTypes/lists/Table";
import NetworkEncodings from "src/operators/structures/NetworkEncodings";
import ListGenerators from "src/operators/lists/ListGenerators";
import ListConversions from "src/operators/lists/ListConversions";

/**
 * @classdesc Table Encodings
 *
 * @namespace
 * @category basics
 */
function TableEncodings() {}
export default TableEncodings;

TableEncodings.ENTER = String.fromCharCode(13);
TableEncodings.ENTER2 = String.fromCharCode(10);
TableEncodings.ENTER3 = String.fromCharCode(8232);

TableEncodings.SPACE = String.fromCharCode(32);
TableEncodings.SPACE2 = String.fromCharCode(160);

TableEncodings.TAB = "	";
TableEncodings.TAB2 = String.fromCharCode(9);

/**
 * Decode a String in format CSV into a Table
 * @param {String} csv CSV formatted text
 *
 * @param {Boolean} first_row_header first row is header (default: false)
 * @param {String} separator separator character (default: ",")
 * @param {Object} value_for_nulls Object to be placed instead of null values
 * @param {Boolean} listsToStringList if true (default value), converts lists that are not StringLists, NumberLists… (probably because they contain strings and numbers) into StringLists
 * @return {Table} resulting Table
 * tags:decoder
 */
TableEncodings.CSVtoTable = function(csvString, firstRowIsHeader, separator, valueForNulls, listsToStringList) {
  if(csvString==null) return null;
  valueForNulls = valueForNulls == null ? "" : valueForNulls;
  listsToStringList = listsToStringList==null?true:listsToStringList;

  var i, j;
  var _firstRowIsHeader = firstRowIsHeader == null ? false : firstRowIsHeader;

  if(csvString == null) return null;
  if(csvString === "") return new Table();

  csvString = csvString.replace(/\$/g, "");

  var blocks = csvString.split("\"");
  for(i = 1; blocks[i] != null; i += 2) {
    blocks[i] = blocks[i].replace(/\n/g, "*ENTER*");
  }
  csvString = blocks.join("\""); //TODO: create a general method for replacements inside "", apply it to chomas

  var enterChar = TableEncodings.ENTER2;
  var lines = csvString.split(enterChar);
  if(lines.length == 1) {
    enterChar = TableEncodings.ENTER;
    lines = csvString.split(enterChar);
    if(lines.length == 1) {
      enterChar = TableEncodings.ENTER3;
      lines = csvString.split(enterChar);
    }
  }

  var table = new Table();
  var comaCharacter = separator != undefined ? separator : ",";

  if(csvString == null || csvString === "" || csvString == " " || lines.length === 0) return null;

  var startIndex = 0;
  var headerContent;
  if(_firstRowIsHeader) {
    startIndex = 1;
    headerContent = lines[0].split(comaCharacter);
  }

  var element;
  var cellContent;
  var numberCandidate;
  for(i = startIndex; i < lines.length; i++) {
    if(lines[i].length < 2) continue;

    var cellContents = NetworkEncodings.replaceChomasInLine(lines[i], separator).split(comaCharacter); //TODO: will be obsolete (see previous TODO)

    for(j = 0; j < cellContents.length; j++) {
      table[j] = table[j] == null ? new List() : table[j];
      if(_firstRowIsHeader && i == 1) {
        table[j].name = ( headerContent[j] == null ? "" : TableEncodings._removeQuotes(headerContent[j]) ).trim();
      }
      var actualIndex = _firstRowIsHeader ? (i - 1) : i;

      cellContent = cellContents[j].replace(/\*CHOMA\*/g, separator).replace(/\*ENTER\*/g, "\n");

      cellContent = cellContent === '' ? valueForNulls : cellContent;

      cellContent = String(cellContent);

      numberCandidate = Number(cellContent.replace(',', '.'));

      element = (numberCandidate || (numberCandidate == 0 && cellContent !== '')) ? numberCandidate : cellContent;

      if(typeof element == 'string') element = TableEncodings._removeQuotes(element);

      table[j][actualIndex] = element;
    }
  }

  for(i = 0; table[i] != null; i++) {
    table[i] = table[i].getImproved();
    if(listsToStringList && table[i].type=="List") table[i] = ListConversions.toStringList(table[i]);
  }

  table = table.getImproved();

  return table;
};

/**
 * @ignore
 */
TableEncodings._removeQuotes = function(string) {
  if(string.length === 0) return string;
  if((string.charAt(0) == "\"" || string.charAt(0) == "'") && (string.charAt(string.length - 1) == "\"" || string.charAt(string.length - 1) == "'")) string = string.substr(1, string.length - 2);
  return string;
};

/**
 * Encode a Table into a String in format CSV
 * @param {Table} Table to be enconded
 *
 * @param {String} separator character (default: ",")
 * @param {Boolean} first row as List names (default: false)
 * @return {String} resulting String in CSV format
 * tags:encoder
 */
TableEncodings.TableToCSV = function(table, separator, namesAsHeaders) {
  separator = separator || ",";
  var i;
  var j;
  var list;
  var type;
  var lines = ListGenerators.createListWithSameElement(table[0].length, "");
  var addSeparator;
  for(i = 0; table[i] != null; i++) {
    list = table[i];
    type = list.type;
    addSeparator = i != table.length - 1;
    for(j = 0; list[j] != null; j++) {
      switch(type) {
        case 'NumberList':
          lines[j] += list[j];
          break;
        default:
          lines[j] += "\"" + list[j] + "\"";
          break;
      }
      if(addSeparator) lines[j] += separator;
    }
  }

  var headers = '';
  if(namesAsHeaders) {
    for(i = 0; table[i] != null; i++) {
      list = table[i];
      headers += "\"" + list.name + "\"";
      if(i != table.length - 1) headers += separator;
    }
    headers += '\n';
  }

  return headers + lines.getConcatenated("\n");
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>pocklington: 55 s 🏆</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / extra-dev

dev / pocklington - dev

            « Up

              pocklington

                dev
                55 s 🏆

📅  (2021-12-16 03:29:46 UTC)

Context

# Packages matching: installed
# Name                   # Installed # Synopsis
base-bigarray            base
base-threads             base
base-unix                base
conf-findutils           1           Virtual package relying on findutils
conf-gmp                 3           Virtual package relying on a GMP lib system installation
coq                      dev         Formal proof management system
dune                     2.9.1       Fast, portable, and opinionated build system
ocaml                    4.05.0      The OCaml compiler (virtual package)
ocaml-base-compiler      4.05.0      Official 4.05.0 release
ocaml-config             1           OCaml Switch Configuration
ocaml-secondary-compiler 4.08.1-1    OCaml 4.08.1 Secondary Switch Compiler
ocamlfind                1.9.1       A library manager for OCaml
ocamlfind-secondary      1.9.1       Adds support for ocaml-secondary-compiler to ocamlfind
zarith                   1.12        Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/coq-community/pocklington"
dev-repo: "git+https://github.com/coq-community/pocklington.git"
bug-reports: "https://github.com/coq-community/pocklington/issues"
license: "LGPL-2.1-or-later"
synopsis: "Pocklington's criterion for primality in Coq"
description: """
Coq formalization of Pocklington's criterion for checking primality of
large natural numbers. Includes a formal proof of Fermat's little theorem."""
build: ["dune" "build" "-p" name "-j" jobs]
depends: [
  "dune" {>= "2.5"}
  "coq" {>= "8.7"}
]
tags: [
  "category:Mathematics/Arithmetic and Number Theory/Number theory"
  "keyword:Pocklington"
  "keyword:number theory"
  "keyword:prime numbers"
  "keyword:primality"
  "keyword:Fermat's little theorem"
  "logpath:Pocklington"
]
authors: [
  "Olga Caprotti"
  "Martijn Oostdijk"
]
url {
  src: "git+https://github.com/coq-community/pocklington.git#master"
}

Lint

Command

true

Return code

0

Dry install 🏜

Dry install with the current Coq version:

Command

opam install -y --show-action coq-pocklington.dev coq.dev

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-pocklington.dev coq.dev

Return code

0

Duration

11 s

Install 🚀

Command

opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y coq-pocklington.dev coq.dev

Return code

0

Duration

55 s

Installation size

Total: 717 K

59 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/fermat.vo

57 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/list.vo

51 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/modulo.vo

50 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/divides.vo

39 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/lemmas.vo

38 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/gcd.vo

37 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/prime.vo

35 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/dec.vo

34 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/pock.vo

34 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/modprime.vo

31 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/natZ.vo

29 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/exp.vo

27 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/order.vo

26 K ../ocaml-base-compiler.4.05.0/doc/coq-pocklington/LICENSE

22 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/fermat.v

20 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/Pocklington.vo

18 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/list.v

17 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/modulo.v

15 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/divides.v

11 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/lemmas.v

10 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/dec.v

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/gcd.v

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/pock.v

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/prime.v

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/natZ.v

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/modprime.v

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/exp.v

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/order.v

3 K ../ocaml-base-compiler.4.05.0/doc/coq-pocklington/README.md

1 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Pocklington/Pocklington.v

1 K ../ocaml-base-compiler.4.05.0/lib/coq-pocklington/opam

1 K ../ocaml-base-compiler.4.05.0/lib/coq-pocklington/dune-package

0 K ../ocaml-base-compiler.4.05.0/lib/coq-pocklington/META

Uninstall 🧹

Command

opam remove -y coq-pocklington.dev

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub © Guillaume Claret 🐣


text:
const Path = require('path');
const Webpack = require('webpack');

module.exports = {
    devtool: 'cheap-module-eval-source-map',
    entry: [
        'eventsource-polyfill',
        'webpack-hot-middleware/client',
        './src/client'
    ],
    output: {
        path: Path.join(__dirname, 'public'),
        filename: 'bundle.js',
        publicPath: '/static/'
    },
    plugins: [
        new Webpack.HotModuleReplacementPlugin(),
        new Webpack.NoErrorsPlugin(),
        new Webpack.DefinePlugin({
            process: {
                env: {
                    BROWSER: true,
                    NODE_ENV: JSON.stringify(process.env.NODE_ENV)
                }
            }
        })
    ],
    module: {
        loaders: [
            {
                test: /\.jsx?/,
                loader: 'babel',
                include: [
                    Path.resolve(__dirname, 'src')
                ],
                query: {
                    presets: ['es2015', 'react', 'react-hmre']
                }
            }
        ]
    },
    resolve: {
        modulesDirectories: [
            'node_modules',
            'shared'
        ]
    }
};


text:
using System.ComponentModel;

namespace WickedSick.MVVM
{
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var obj = PropertyChanged;
            if (obj != null)
                obj(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


text:
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

package com.google.gerrit.server.project;

import com.google.gerrit.common.ProjectUtil;
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.GroupDescription;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.common.errors.ProjectCreationFailedException;
import com.google.gerrit.extensions.events.NewProjectCreatedListener;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.GroupBackend;
import com.google.gerrit.server.config.ProjectOwnerGroups;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.git.RepositoryCaseMismatchException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.RefUpdate.Result;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/** Common class that holds the code to create projects */
public class PerformCreateProject {
  private static final Logger log = LoggerFactory
      .getLogger(PerformCreateProject.class);

  public interface Factory {
    PerformCreateProject create(CreateProjectArgs createProjectArgs);
  }

  private final Set<AccountGroup.UUID> projectOwnerGroups;
  private final IdentifiedUser currentUser;
  private final GitRepositoryManager repoManager;
  private final GitReferenceUpdated referenceUpdated;
  private final DynamicSet<NewProjectCreatedListener> createdListener;
  private final PersonIdent serverIdent;
  private CreateProjectArgs createProjectArgs;
  private ProjectCache projectCache;
  private GroupBackend groupBackend;
  private MetaDataUpdate.User metaDataUpdateFactory;

  @Inject
  PerformCreateProject(@ProjectOwnerGroups Set<AccountGroup.UUID> pOwnerGroups,
      IdentifiedUser identifiedUser, GitRepositoryManager gitRepoManager,
      GitReferenceUpdated referenceUpdated,
      DynamicSet<NewProjectCreatedListener> createdListener,
      ReviewDb db,
      @GerritPersonIdent PersonIdent personIdent, GroupBackend groupBackend,
      MetaDataUpdate.User metaDataUpdateFactory,
      @Assisted CreateProjectArgs createPArgs, ProjectCache pCache) {
    this.projectOwnerGroups = pOwnerGroups;
    this.currentUser = identifiedUser;
    this.repoManager = gitRepoManager;
    this.referenceUpdated = referenceUpdated;
    this.createdListener = createdListener;
    this.serverIdent = personIdent;
    this.createProjectArgs = createPArgs;
    this.projectCache = pCache;
    this.groupBackend = groupBackend;
    this.metaDataUpdateFactory = metaDataUpdateFactory;
  }

  public void createProject() throws ProjectCreationFailedException {
    validateParameters();
    final Project.NameKey nameKey = createProjectArgs.getProject();
    try {
      final String head =
          createProjectArgs.permissionsOnly ? GitRepositoryManager.REF_CONFIG
              : createProjectArgs.branch.get(0);
      final Repository repo = repoManager.createRepository(nameKey);
      try {
        NewProjectCreatedListener.Event event = new NewProjectCreatedListener.Event() {
          @Override
          public String getProjectName() {
            return nameKey.get();
          }

          @Override
          public String getHeadName() {
            return head;
          }
        };
        for (NewProjectCreatedListener l : createdListener) {
          l.onNewProjectCreated(event);
        }

        final RefUpdate u = repo.updateRef(Constants.HEAD);
        u.disableRefLog();
        u.link(head);

        createProjectConfig();

        if (!createProjectArgs.permissionsOnly
            && createProjectArgs.createEmptyCommit) {
          createEmptyCommits(repo, nameKey, createProjectArgs.branch);
        }
      } finally {
        repo.close();
      }
    } catch (RepositoryCaseMismatchException e) {
      throw new ProjectCreationFailedException("Cannot create " + nameKey.get()
          + " because the name is already occupied by another project."
          + " The other project has the same name, only spelled in a"
          + " different case.", e);
    } catch (RepositoryNotFoundException badName) {
      throw new ProjectCreationFailedException("Cannot create " + nameKey, badName);
    } catch (IllegalStateException err) {
      try {
        final Repository repo = repoManager.openRepository(nameKey);
        try {
          if (repo.getObjectDatabase().exists()) {
            throw new ProjectCreationFailedException("project \"" + nameKey + "\" exists");
          }
        } finally {
          repo.close();
        }
      } catch (IOException ioErr) {
        final String msg = "Cannot create " + nameKey;
        log.error(msg, err);
        throw new ProjectCreationFailedException(msg, ioErr);
      }
    } catch (Exception e) {
      final String msg = "Cannot create " + nameKey;
      log.error(msg, e);
      throw new ProjectCreationFailedException(msg, e);
    }
  }

  private void createProjectConfig() throws IOException, ConfigInvalidException {
    final MetaDataUpdate md =
        metaDataUpdateFactory.create(createProjectArgs.getProject());
    try {
      final ProjectConfig config = ProjectConfig.read(md);
      config.load(md);

      Project newProject = config.getProject();
      newProject.setDescription(createProjectArgs.projectDescription);
      newProject.setSubmitType(createProjectArgs.submitType);
      newProject
          .setUseContributorAgreements(createProjectArgs.contributorAgreements);
      newProject.setUseSignedOffBy(createProjectArgs.signedOffBy);
      newProject.setUseContentMerge(createProjectArgs.contentMerge);
      newProject.setRequireChangeID(createProjectArgs.changeIdRequired);
      if (createProjectArgs.newParent != null) {
        newProject.setParentName(createProjectArgs.newParent.getProject()
            .getNameKey());
      }

      if (!createProjectArgs.ownerIds.isEmpty()) {
        final AccessSection all =
            config.getAccessSection(AccessSection.ALL, true);
        for (AccountGroup.UUID ownerId : createProjectArgs.ownerIds) {
          GroupDescription.Basic g = groupBackend.get(ownerId);
          if (g != null) {
            GroupReference group = config.resolve(GroupReference.forGroup(g));
            all.getPermission(Permission.OWNER, true).add(
                new PermissionRule(group));
          }
        }
      }

      md.setMessage("Created project\n");
      config.commit(md);
    } finally {
      md.close();
    }
    projectCache.onCreateProject(createProjectArgs.getProject());
    repoManager.setProjectDescription(createProjectArgs.getProject(),
        createProjectArgs.projectDescription);
  }

  private void validateParameters() throws ProjectCreationFailedException {
    if (createProjectArgs.getProjectName() == null
        || createProjectArgs.getProjectName().isEmpty()) {
      throw new ProjectCreationFailedException("Project name is required");
    }

    String nameWithoutSuffix = ProjectUtil.stripGitSuffix(createProjectArgs.getProjectName());
    createProjectArgs.setProjectName(nameWithoutSuffix);

    if (!currentUser.getCapabilities().canCreateProject()) {
      throw new ProjectCreationFailedException(String.format(
          "%s does not have \"Create Project\" capability.",
          currentUser.getUserName()));
    }

    if (createProjectArgs.ownerIds == null
        || createProjectArgs.ownerIds.isEmpty()) {
      createProjectArgs.ownerIds =
          new ArrayList<AccountGroup.UUID>(projectOwnerGroups);
    }

    List<String> transformedBranches = new ArrayList<String>();
    if (createProjectArgs.branch == null ||
        createProjectArgs.branch.isEmpty()) {
      createProjectArgs.branch = Collections.singletonList(Constants.MASTER);
    }
    for (String branch : createProjectArgs.branch) {
      while (branch.startsWith("/")) {
        branch = branch.substring(1);
      }
      if (!branch.startsWith(Constants.R_HEADS)) {
        branch = Constants.R_HEADS + branch;
      }
      if (!Repository.isValidRefName(branch)) {
        throw new ProjectCreationFailedException(String.format(
            "Branch \"%s\" is not a valid name.", branch));
      }
      if (!transformedBranches.contains(branch)) {
        transformedBranches.add(branch);
      }
    }
    createProjectArgs.branch = transformedBranches;
  }

  private void createEmptyCommits(final Repository repo,
      final Project.NameKey project, final List<String> refs)
      throws IOException {
    ObjectInserter oi = repo.newObjectInserter();
    try {
      CommitBuilder cb = new CommitBuilder();
      cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
      cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent());
      cb.setCommitter(serverIdent);
      cb.setMessage("Initial empty repository\n");

      ObjectId id = oi.insert(cb);
      oi.flush();

      for (String ref : refs) {
        RefUpdate ru = repo.updateRef(ref);
        ru.setNewObjectId(id);
        final Result result = ru.update();
        switch (result) {
          case NEW:
            referenceUpdated.fire(project, ru);
            break;
          default: {
            throw new IOException(String.format(
              "Failed to create ref \"%s\": %s", ref, result.name()));
          }
        }
      }
    } catch (IOException e) {
      log.error(
          "Cannot create empty commit for "
              + createProjectArgs.getProjectName(), e);
      throw e;
    } finally {
      oi.release();
    }
  }
}


text:
/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
 */
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */
export { async, ComponentFixture, resetFakeAsyncZone, fakeAsync, tick, flush, discardPeriodicTasks, flushMicrotasks, getTestBed, inject, withModule, TestComponentRenderer, ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, TestBed, InjectSetupWrapper, __core_private_testing_placeholder__, ɵTestingCompiler, ɵTestingCompilerFactory } from './src/testing';
// This file only reexports content of the `src` folder. Keep it that way.

//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2NvcmUvdGVzdGluZy9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7QUFlQSxzVkFBYyxlQUFlLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbi8vLyA8cmVmZXJlbmNlIHR5cGVzPVwiamFzbWluZVwiIC8+XG5cbi8qKlxuICogQG1vZHVsZVxuICogQGRlc2NyaXB0aW9uXG4gKiBFbnRyeSBwb2ludCBmb3IgYWxsIHB1YmxpYyBBUElzIG9mIHRoaXMgcGFja2FnZS5cbiAqL1xuZXhwb3J0ICogZnJvbSAnLi9zcmMvdGVzdGluZyc7XG5cbi8vIFRoaXMgZmlsZSBvbmx5IHJlZXhwb3J0cyBjb250ZW50IG9mIHRoZSBgc3JjYCBmb2xkZXIuIEtlZXAgaXQgdGhhdCB3YXkuXG4iXX0=


text:
using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using MahApps.Metro.Controls;

namespace MahApps.Metro.Actions
{
    public class CloseTabItemAction : TriggerAction<DependencyObject>
    {
        public static readonly DependencyProperty TabControlProperty =
            DependencyProperty.Register(
                nameof(TabControl),
                typeof(TabControl),
                typeof(CloseTabItemAction),
                new PropertyMetadata(default(TabControl)));

        public TabControl TabControl
        {
            get { return (TabControl)this.GetValue(TabControlProperty); }
            set { this.SetValue(TabControlProperty, value); }
        }

        public static readonly DependencyProperty TabItemProperty =
            DependencyProperty.Register(
                nameof(TabItem),
                typeof(TabItem),
                typeof(CloseTabItemAction),
                new PropertyMetadata(default(TabItem)));

        public TabItem TabItem
        {
            get { return (TabItem)this.GetValue(TabItemProperty); }
            set { this.SetValue(TabItemProperty, value); }
        }

        protected override void Invoke(object parameter)
        {
            var tabControl = this.TabControl;
            var tabItem = this.TabItem;
            if (tabControl == null || tabItem == null)
            {
                return;
            }

            var closeAction =
                new Action(
                    () =>
                        {
                            // TODO Raise a closing event to cancel this action

                            if (tabControl.ItemsSource == null)
                            {
                                // if the list is hard-coded (i.e. has no ItemsSource)
                                // then we remove the item from the collection
                                tabControl.Items.Remove(tabItem);
                            }
                            else
                            {
                                // if ItemsSource is something we cannot work with, bail out
                                var collection = tabControl.ItemsSource as IList;
                                if (collection == null)
                                {
                                    return;
                                }
                                // find the item and kill it (I mean, remove it)
                                var item2Remove = collection.OfType<object>().FirstOrDefault(item => tabItem == item || tabItem.DataContext == item);
                                if (item2Remove != null)
                                {
                                    collection.Remove(item2Remove);
                                }
                            }
                        });
            this.BeginInvoke(closeAction);
        }
    }
}


text:
<?php
namespace Model\Database\DynamicTypes;

use Exceptions\ValidationException;
use Model\Database\Model\ITable;

class URL extends String implements IDynamicValidate {
	function validate($value){
		$url = \Utility\Net\URL::fromURL($value);
		if(!$url)
			return false;
		return true;
	}
	function getUrl(){
		return \Utility\Net\URL::fromURL($this->value);
	}
}


text:
<?php

namespace OOUI;

/**
 * Multiple checkbox input widget. Intended to be used within a OO.ui.FormLayout.
 */
class CheckboxMultiselectInputWidget extends InputWidget {

	/* Static Properties */

	public static $supportsSimpleLabel = false;

	/* Properties */

	/**
	 * @var string|null
	 */
	protected $name = null;

	/**
	 * Input value.
	 *
	 * @var string[]
	 */
	protected $value = [];

	/**
	 * Layouts for this input, as FieldLayouts.
	 *
	 * @var array
	 */
	protected $fields = [];

	/**
	 * @param array $config Configuration options
	 * @param array[] $config['options'] Array of menu options in the format
	 *   `array( 'data' => …, 'label' => … )`
	 */
	public function __construct( array $config = [] ) {
		// Parent constructor
		parent::__construct( $config );

		if ( isset( $config['name'] ) ) {
			$this->name = $config['name'];
		}

		// Initialization
		$this->setOptions( isset( $config['options'] ) ? $config['options'] : [] );
		// Have to repeat this from parent, as we need options to be set up for this to make sense
		$this->setValue( isset( $config['value'] ) ? $config['value'] : null );
		$this->addClasses( [ 'oo-ui-checkboxMultiselectInputWidget' ] );
	}

	protected function getInputElement( $config ) {
		// Actually unused
		return new Tag( 'div' );
	}

	/**
	 * Set the value of the input.
	 *
	 * @param string[] $value New value
	 * @return $this
	 */
	public function setValue( $value ) {
		$this->value = $this->cleanUpValue( $value );
		// Deselect all options
		foreach ( $this->fields as $field ) {
			$field->getField()->setSelected( false );
		}
		// Select the requested ones
		foreach ( $this->value as $key ) {
			$this->fields[ $key ]->getField()->setSelected( true );
		}
		return $this;
	}

	/**
	 * Clean up incoming value.
	 *
	 * @param string[] $value Original value
	 * @return string[] Cleaned up value
	 */
	protected function cleanUpValue( $value ) {
		$cleanValue = [];
		if ( !is_array( $value ) ) {
			return $cleanValue;
		}
		foreach ( $value as $singleValue ) {
			$singleValue = parent::cleanUpValue( $singleValue );
			// Remove options that we don't have here
			if ( !isset( $this->fields[ $singleValue ] ) ) {
				continue;
			}
			$cleanValue[] = $singleValue;
		}
		return $cleanValue;
	}

	/**
	 * Set the options available for this input.
	 *
	 * @param array[] $options Array of menu options in the format
	 *   `array( 'data' => …, 'label' => … )`
	 * @return $this
	 */
	public function setOptions( $options ) {
		$this->fields = [];

		// Rebuild the checkboxes
		$this->clearContent();
		$name = $this->name;
		foreach ( $options as $opt ) {
			$optValue = parent::cleanUpValue( $opt['data'] );
			$field = new FieldLayout(
				new CheckboxInputWidget( [
					'name' => $name,
					'value' => $optValue,
					'disabled' => $this->isDisabled(),
				] ),
				[
					'label' => isset( $opt['label'] ) ? $opt['label'] : $optValue,
					'align' => 'inline',
				]
			);

			$this->fields[ $optValue ] = $field;
			$this->appendContent( $field );
		}

		// Re-set the value, checking the checkboxes as needed.
		// This will also get rid of any stale options that we just removed.
		$this->setValue( $this->getValue() );

		return $this;
	}

	public function setDisabled( $state ) {
		parent::setDisabled( $state );
		foreach ( $this->fields as $field ) {
			$field->getField()->setDisabled( $this->isDisabled() );
		}
		return $this;
	}

	public function getConfig( &$config ) {
		$o = [];
		foreach ( $this->fields as $field ) {
			$label = $field->getLabel();
			$data = $field->getField()->getValue();
			$o[] = [ 'data' => $data, 'label' => $label ];
		}
		$config['options'] = $o;
		return parent::getConfig( $config );
	}
}


text:
import employee from './schemes/employee.schema.js';
import project from './schemes/project.schema.js';
import task from './schemes/task.schema.js';

export { employee, project, task };


text:
package com.thoughtworks.go.plugin.activation;

import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.annotation.Load;
import com.thoughtworks.go.plugin.api.annotation.UnLoad;
import com.thoughtworks.go.plugin.api.info.PluginDescriptor;
import com.thoughtworks.go.plugin.api.info.PluginDescriptorAware;

@Extension
public class GoExtensionWithPublicLoadUnloadAnnotationWithArguments implements PluginDescriptorAware {
    public static int loadInvoked = 0;
    public static int unLoadInvoked = 0;

    @Load
    public void setupData1(int i) {
        loadInvoked++;
    }

    @Load
    public void parameterlessLoad() {
        loadInvoked++;
    }

    @UnLoad
    public void tearDownData1(int i) {
        unLoadInvoked++;
    }

    @UnLoad
    public void parameterlessLoadTeardown() {
        unLoadInvoked++;
    }

    @Override
    public void setPluginDescriptor(PluginDescriptor descriptor) {
    }
}