text:
package com.batyanko.strokeratecoach.sync;

import static com.batyanko.strokeratecoach.WaveActivity.CUSTOM_SOUND;
import static com.batyanko.strokeratecoach.WaveActivity.CUSTOM_SOUND_PATH;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.batyanko.strokeratecoach.R;
import com.batyanko.strokeratecoach.Speed.CLocation;
import com.batyanko.strokeratecoach.Speed.IBaseGpsListener;
import com.batyanko.strokeratecoach.Utils.NotificationUtils;
import com.batyanko.strokeratecoach.Utils.SpmUtilities;
import com.batyanko.strokeratecoach.WaveActivity;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by batyanko on 9/4/17.
 */

public class BeeperTasks {

    public static final String EXTRA_WORKOUT_SPP = "workout_spp";   //Units per phase
    public static final String EXTRA_WORKOUT_GEARS = "workout_gears";
    public static final String EXTRA_WORKOUT_SPP_TYPE = "workout-spp-type";
    public static final String ACTION_START_BEEP = "start-beep";
    public static final String ACTION_STOP_BEEP = "stop-beep";
    public static final String ACTION_CHECK_SERVICE = "check-service";
    public static final String ACTION_JUST_BIND = "just-bind";
    public static final String ACTION_START_WARNING = "start-warning";
    public static final String ACTION_STOP_WARNING = "stop-warning";

    //SPP (strokes or stuff per phase) unit types
    public static final int SPP_TYPE_STROKES = 0;
    public static final int SPP_TYPE_METERS = 1;
    public static final int SPP_TYPE_SECONDS = 2;

    //VALUES FROM WaveActivity

    /* Global spm setting to hold current spm */
    public static int spm = 22;
    //Variables used in beeping workoutTimer setup
    private static long strokeDuration;
    public static String spmString;

    private static MediaPlayer player;
    private static ToneGenerator workoutToneGen;
    private static ToneGenerator countdownToneGen;
    private static ToneGenerator warningToneGen;

    private static Timer workoutTimer;
    private static TimerTask workoutTimerTask;

    private static Timer timeTimer;
    private static TimerTask timeTimerTask;

    private static Timer countdownTimer;
    private static TimerTask countdownTimerTask;

    private static TimerTask speedLimitTimerTask;

    private static Timer speedLimitTimer;
    //autoWave values
    private static int workoutRunning;     //0=off, 1=wave(depreciated), 2=interval, 3=simple 9=lastPhase
    private static int countdownRunning;    //0=off, 1=on
    private static int totalWorkoutCount;
    private static int phaseTrigger;
    private static int phase;    //phase = 0 = wave not running
    private static int phasesTotal;
    private static int color;
    private static int phaseProgress;
    private static int workoutProgress;
    private static int workoutLength;       //Length (in strokes, meters or seconds)

    private int mSppType;

    private static int[] sppSettings;

    private static int[] gearSettings;

    private static SharedPreferences pref;

    //END OF COPIED VALUES

    private static CLocation currentLocation;

    private static CLocation startingPhaseLocation;

    //TODO > 20 for emulator testing, < 5 for practical use
    public static final float ACCEPTABLE_ACCURACY_DEFAULT = 5;
    public static float acceptableAccuracy = ACCEPTABLE_ACCURACY_DEFAULT;
    private static float locationAccuracy;
    private static float currentSpeed;

    private static CLocation[] locationPool;

    private static float averageSpeed;  //In m/s

    private static int locCycleCount;
    //TODO add preference for sample count
    private static final int SPEED_SAMPLE_COUNT_DEFAULT = 10;
    private static int speedSampleCount = SPEED_SAMPLE_COUNT_DEFAULT;

    private static boolean locationPoolIsFull;

    private static int prevPhasesDistance;

    //TODO make static?
    private long phaseStartTime;
    private long workoutStartTime;
    private int timeTimerPhaseProgress;
    private int countdownCyclesTotal;
    private int countdownCyclesElapsed;
    private int countdownCycleDuration;
    private int countdownDuration;

    private static int oldWorkoutProgress;

    private static int beeps;
    private static int warns;
    private static boolean warningIsRunning = false;

    void executeTask(BeeperService beeperService, String action,
                     int[] sppSettings, int[] gearSettings, int sppType) {
        if (action.equals(ACTION_START_BEEP)) {
            NotificationUtils.showWorkoutNotification(beeperService);
            mSppType = sppType;
            initBeeper(beeperService);
            initLocation(beeperService);

            if (mSppType == SPP_TYPE_METERS) {
                pref.edit().putBoolean(WaveActivity.GPS_LOCKING, true).apply();
//                initLocation(beeperService);
            }
            if (mSppType == SPP_TYPE_SECONDS) {
                startTimeTimerTask();
            }

            if (gearSettings != null) {
                if (sppSettings == null) {  //Manual SPM setting
                    //TODO show speed?
                    workoutRunning = WaveActivity.WORKOUT_SIMPLE;
                    flushUI();
                    spm = gearSettings[0];
                    startTheTempo(beeperService);
                } else {                    //Preset workout
                    workoutRunning = WaveActivity.WORKOUT_INTERVAL;
                    pref.edit().putInt(WaveActivity.OPERATION_SETTING, workoutRunning).apply();
                    BeeperTasks.sppSettings = sppSettings;
                    BeeperTasks.gearSettings = gearSettings;
                    workoutLength = 0;
                    for (int i : sppSettings) {
                        workoutLength += i;     //Be it strokes, metres or seconds
                    }
                    pref.edit().putInt(WaveActivity.WORKOUT_LENGTH, workoutLength).apply();
                    startCountdown(beeperService);
                }
            }
        } else if (action.equals(ACTION_STOP_BEEP)) {
            endWorkout(beeperService);
        } else if (action.equals(ACTION_CHECK_SERVICE)) {
            if (pref == null) {
                pref = PreferenceManager.getDefaultSharedPreferences(beeperService);
            }
            pref.edit().putInt(WaveActivity.OPERATION_SETTING, workoutRunning).apply();
        } else if (action.equals(ACTION_START_WARNING)) {
//            cancelTimer(speedLimitTimer, speedLimitTimerTask);
            if (speedLimitTimer == null || speedLimitTimerTask == null || warningIsRunning == false) {
                startSpeedLimit(beeperService);
                warningIsRunning = true;
            }
        } else if (action.equals(ACTION_STOP_WARNING)) {
            cancelTimer(speedLimitTimer, speedLimitTimerTask);
            warningIsRunning = false;
        }
    }

    private void initBeeper(BeeperService beeperService) {
        resetVariables(beeperService);

        workoutToneGen = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
        countdownToneGen = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
        warningToneGen = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);

        if (pref.getBoolean(CUSTOM_SOUND, false)) {
            String sndUri = pref.getString(CUSTOM_SOUND_PATH, "");
            if (sndUri.equals("")) {
                pref.edit().putBoolean(CUSTOM_SOUND, false).apply();
            } else {
                pref.edit().putBoolean(CUSTOM_SOUND, true).apply();
                try {
                    Uri beepURI = Uri.parse(sndUri);
                    Log.d("LE BEEP URI: ", "" + beepURI);
                    player = new MediaPlayer();

                    player.setDataSource(beeperService, beepURI);
                    player.prepare();
//            player.start();

                } catch (IOException e) {
                    pref.edit().putBoolean(CUSTOM_SOUND, false).apply();
                    e.printStackTrace();
                }
            }
        }

    }

    private void resetVariables(BeeperService beeperService) {
        pref = PreferenceManager.getDefaultSharedPreferences(beeperService);

        workoutRunning = WaveActivity.WORKOUT_STOP;
        countdownRunning = 0;
        phaseProgress = 0;
        workoutProgress = 0;
        oldWorkoutProgress = 0;
        totalWorkoutCount = 0;
        phaseTrigger = 0;
        phase = 0;
        phasesTotal = 0;
        color = 0;
        beeps = 0;
        warns = 0;
        locCycleCount = 0;
        locationPoolIsFull = false;
        prevPhasesDistance = 0;
        averageSpeed = 0;
        //Remove sensitive data?
        currentLocation = null;
        startingPhaseLocation = null;
        acceptableAccuracy = Float.valueOf(pref.getString(WaveActivity.LOCATION_ACCURACY_ACCEPTABLE, acceptableAccuracy + ""));
        if (acceptableAccuracy <= .0001f) {
            acceptableAccuracy = .0001f;
        }
        speedSampleCount = Integer.valueOf(pref.getString(WaveActivity.SPEED_SAMPLE_COUNT, speedSampleCount + ""));
        if (speedSampleCount < 3) {
            speedSampleCount = 3;
        }
        locationPool = new CLocation[speedSampleCount];

        cancelTimer(workoutTimer, workoutTimerTask);
        cancelTimer(timeTimer, timeTimerTask);
        cancelTimer(countdownTimer, countdownTimerTask);
        cancelTimer(speedLimitTimer, speedLimitTimerTask);

        countdownCyclesElapsed = 0;
        //TODO add setting for countdown cycle length / frequency?
        countdownDuration = pref.getInt(WaveActivity.COUNTDOWN_DURATION, 3000);
        countdownCycleDuration = 100;
        countdownCyclesTotal = countdownDuration / countdownCycleDuration;

        //Init speed unit setting if necessary
        String speedUnit = pref.getString(WaveActivity.SPEED_UNIT, "");
        if (!speedUnit.equals(WaveActivity.SPEED_500M_SETTING) && !speedUnit.equals(WaveActivity.SPEED_MS_SETTING)) {
            pref.edit().putString(WaveActivity.SPEED_UNIT, WaveActivity.SPEED_MS_SETTING).apply();
        }
        pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, workoutProgress).apply();
        pref.edit().putBoolean(WaveActivity.GPS_LOCKING, false).apply();
        flushUI();

        phaseProgress = 0;
        locationAccuracy = 500;     //Init to extremely inaccurate value, i.e. no accuracy
        pref.edit().putFloat(WaveActivity.LOCATION_ACCURACY, locationAccuracy).apply();

        phaseStartTime = System.currentTimeMillis();
        flushUI();
    }

    private void flushUI() {
        pref.edit().putInt(WaveActivity.OPERATION_SETTING, workoutRunning).apply();
        pref.edit().putInt(WaveActivity.COUNTDOWN_DURATION_LEFT, countdownRunning).apply();
        pref.edit().putFloat(WaveActivity.CURRENT_SPEED, averageSpeed).apply();
        Boolean bool = pref.getBoolean(WaveActivity.SWITCH_SETTING, true);
        pref.edit().putBoolean(WaveActivity.SWITCH_SETTING, !bool).apply();
    }

    private void startTheTempo(final BeeperService beeperService) {
        pref.edit().putInt(WaveActivity.SPM_SETTING, spm).apply();
        phaseProgress = 0;

        strokeDuration = SpmUtilities.spmToMilis(spm);

        cancelTimer(workoutTimer, workoutTimerTask);
        if (mSppType == SPP_TYPE_SECONDS) {
            timeTimerPhaseProgress = 0;
            cancelTimer(timeTimer, timeTimerTask);
            startTimeTimerTask();
            timeTimer = new Timer();
            timeTimer.scheduleAtFixedRate(timeTimerTask, 1, 1000);
        }

        //TODO create Task just once?
        workoutTimerTask = new TimerTask() {
            @Override
            public void run() {

                //Abort if OPERATION set to WORKOUT_STOP. Avoid zombie service in the background?
                if (pref.getInt(WaveActivity.OPERATION_SETTING, WaveActivity.WORKOUT_STOP)
                        == WaveActivity.WORKOUT_STOP) {
                    endWorkout(beeperService);
                } else if (workoutRunning == WaveActivity.WORKOUT_INTERVAL
                        || workoutRunning == WaveActivity.WORKOUT_LAST) {

                    switch (mSppType) {
                        //Handle stroke-based workouts
                        case SPP_TYPE_STROKES: {
                            if (phaseProgress >= phaseTrigger) {
                                phaseProgress = 0;
                                switch (workoutRunning) {
                                    case WaveActivity.WORKOUT_INTERVAL: {
                                        phaseProgress++;
//                                        pref.edit().putInt(WaveActivity.PHASE_PROGRESS, 1).apply();
//                                        pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, ++workoutProgress).apply();
                                        autoProgress(beeperService);
                                        break;
                                    }
                                    default:
                                        endWorkout(beeperService);
                                }
                            } else {
                                phaseProgress++;
                                workoutProgress++;
                                pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, workoutProgress).apply();
                                pref.edit().putInt(WaveActivity.PHASE_PROGRESS, phaseProgress).apply();
                            }
                            break;
                        }
                        //Handle distance-based workouts
                        case SPP_TYPE_METERS: {
                            if (phaseProgress >= phaseTrigger) {
                                cancel();
                                startingPhaseLocation = currentLocation;
                                prevPhasesDistance += phaseTrigger;
                                workoutProgress = prevPhasesDistance;
                                pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, workoutProgress).apply();
                                phaseProgress = 0;
                                switch (workoutRunning) {
                                    case WaveActivity.WORKOUT_INTERVAL:
                                        autoProgress(beeperService);
                                        break;
                                    default:
                                        endWorkout(beeperService);
                                }
                            } else {
                                workoutProgress = prevPhasesDistance + phaseProgress;
                                pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, workoutProgress).apply();
                                pref.edit().putInt(WaveActivity.PHASE_PROGRESS, phaseProgress).apply();
                            }
                            break;
                        }
                        //Time-based workout. Phase length = seconds + remainder to complete last stroke
                        case SPP_TYPE_SECONDS: {
                            long currentTime = System.currentTimeMillis();
                            phaseProgress = (int) (currentTime - phaseStartTime);
                            if (phaseProgress >= phaseTrigger * 1000) {

                                //adjust for incomplete seconds in a phase
                                workoutProgress = oldWorkoutProgress + phaseTrigger;
                                oldWorkoutProgress = workoutProgress;
                                pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, workoutProgress).apply();

                                cancel();
                                phaseStartTime = currentTime;
                                phaseProgress = 0;

                                switch (workoutRunning) {
                                    case WaveActivity.WORKOUT_INTERVAL:
                                        autoProgress(beeperService);

                                        break;
                                    default:
                                        endWorkout(beeperService);
                                }
                            } else {
                                if (timeTimer == null) {
                                }
                                if (timeTimerTask == null) {

                                }
                                //pref.edit().putInt(WaveActivity.PHASE_PROGRESS, phaseProgress/1000).apply();
                            }
                            break;
                        }
                        default: {
                            break;
                        }
                    }
                }

                Log.d("CUSTOM_SOUND", pref.getBoolean(CUSTOM_SOUND, false) + "");
                if (!pref.getBoolean(CUSTOM_SOUND, false)) {
                    workoutToneGen.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK, 150);
                } else if (player.isPlaying()) {
                    player.seekTo(0);
                } else {
                    player.start();
                }

                // Register OnErrorListener
                pref.edit().putInt(WaveActivity.BEEP, ++beeps).apply();

            }
        };
        workoutTimer = new Timer();
        workoutTimer.scheduleAtFixedRate(workoutTimerTask, 1, strokeDuration);
    }

    //TimerTask for time-based workouts
    private void startTimeTimerTask() {
        timeTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (phase != 0 && timeTimerPhaseProgress == 0) workoutProgress--;
//                workoutProgress = (int) (System.currentTimeMillis() - workoutStartTime)/1000;
                pref.edit().putInt(WaveActivity.WORKOUT_PROGRESS, ++workoutProgress).apply();
                pref.edit().putInt(WaveActivity.PHASE_PROGRESS, timeTimerPhaseProgress++).apply();
            }
        };
    }

    private void startSpeedLimit(final BeeperService beeperService) {
        speedLimitTimerTask = new TimerTask() {
            @Override
            public void run() {
                //TODO check SpeedLimit prefs to avoid zombie beepers?
                pref.edit().putInt(WaveActivity.WARN, ++warns).apply();
//                warningToneGen.startTone(ToneGenerator.TONE_CDMA_ABBR_REORDER, 100);
                warningToneGen.startTone(ToneGenerator.TONE_CDMA_ANSWER, 50);
            }
        };
        speedLimitTimer = new Timer();
        speedLimitTimer.scheduleAtFixedRate(speedLimitTimerTask, 1, 1000);
    }

    //TODO cancel countdown on interrupt
    private void startCountdown(final BeeperService beeperService) {

//        pref.edit().putInt(WaveActivity.COUNTDOWN_RUNNING, 1).apply();

        countdownTimerTask = new TimerTask() {

            @Override
            public void run() {
                //Wait if locking distance location
                if (pref.getBoolean(WaveActivity.GPS_LOCKING, false)) return;

                if (countdownCyclesElapsed % 10 == 0) {
                    pref.edit().putInt(
                                    WaveActivity.COUNTDOWN_DURATION_LEFT,
                                    countdownDuration - countdownCyclesElapsed * 100)
                            .apply();
                }
                if (++countdownCyclesElapsed >= countdownCyclesTotal) {
                    pref.edit().putInt(WaveActivity.COUNTDOWN_DURATION_LEFT, 0).apply();
                    //workoutStartTime = System.currentTimeMillis();
                    autoProgress(beeperService);
                    cancelTimer(countdownTimer, this);
                } else
                    countdownToneGen.startTone(ToneGenerator.TONE_CDMA_INTERCEPT, 100);
            }
        };

        countdownTimer = new Timer();
        countdownTimer.scheduleAtFixedRate(countdownTimerTask, 1, countdownCycleDuration);
    }

    //Initialize workout phase
    private void autoProgress(BeeperService beeperService) {

        //Set exercise to autoProgress;
        workoutRunning = WaveActivity.WORKOUT_INTERVAL;

        phasesTotal = gearSettings.length;

        final int[] COLOR_PROGRESSION = new int[]{
                Color.GREEN, Color.YELLOW
        };

        //Phase number starts from 1
        phase++;

        if (phase == phasesTotal) {
            workoutRunning = WaveActivity.WORKOUT_STOP;
        }

        if ((phase & 1) == 1) {
            color = COLOR_PROGRESSION[0];
        } else {
            color = COLOR_PROGRESSION[1];
        }

        startPhase(
                sppSettings[phase - 1],
                gearSettings[phase - 1],
                beeperService
        );
    }

    //Start phase
    private void startPhase(int lengthTrigger, int tempo, BeeperService beeperService) {
        //Init starting time for time-based workouts
        phaseStartTime = System.currentTimeMillis();

        phaseTrigger = lengthTrigger;
        spm = tempo;

        if (phase == phasesTotal) {
            workoutRunning = WaveActivity.WORKOUT_LAST;
        }

        pref.edit().putInt(WaveActivity.OPERATION_SETTING, workoutRunning).apply();

        pref.edit().putInt(WaveActivity.CURRENT_COLOR, color).apply();

        pref.edit().putInt(WaveActivity.PHASE_LENGTH, sppSettings[phase - 1]).apply();

        Boolean bool = pref.getBoolean(WaveActivity.SWITCH_SETTING, true);
        pref.edit().putBoolean(WaveActivity.SWITCH_SETTING, !bool).apply();

        startTheTempo(beeperService);
    }

    /**
     * Helper method to cancel running Timer, if any
     */
    private void cancelTimer(Timer timer, TimerTask timerTask) {
        try {
            timer.cancel();
            timerTask.cancel();
        } catch (IllegalStateException e) {
        } catch (NullPointerException e) {
        }
    }

    /**
     * Reset the current workout and stop beeping.
     */
    private void endWorkout(BeeperService beeperService) {
        if (player != null && pref.getBoolean(CUSTOM_SOUND, false)) {
            player.release();
        }

        resetVariables(beeperService);
        cancelTimer(workoutTimer, workoutTimerTask);
        cancelTimer(timeTimer, timeTimerTask);
        cancelTimer(countdownTimer, countdownTimerTask);
        cancelTimer(speedLimitTimer, speedLimitTimerTask);

//        pref = PreferenceManager.getDefaultSharedPreferences(beeperService);
        pref.edit().putInt(WaveActivity.SPM_SETTING, 0).apply();
        NotificationUtils.clearAllNotifications(beeperService);

        flushUI();

        if (beeperService.locationManager != null) {
            beeperService.locationManager.removeUpdates(beeperService.locListener);
            beeperService.locationManager = null;
        }

        beeperService.stopSelf();
    }

    private void initLocation(BeeperService beeperService) {

        PackageManager manager = beeperService.getPackageManager();
        int permission = manager.checkPermission("android.permission.ACCESS_FINE_LOCATION", "com.batyanko.strokeratecoach");
        boolean hasPermission = (permission == PackageManager.PERMISSION_GRANTED);

        if (!hasPermission) {
            return;
        }

        beeperService.locationManager = (LocationManager) beeperService.getSystemService(Context.LOCATION_SERVICE);
        beeperService.locListener = new TehLocListener(beeperService);
        beeperService.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 200, 1, beeperService.locListener);
    }

    private void updateAverageSpeed() {
        if (currentLocation == null) return;
        locationPool[locCycleCount] = currentLocation;

        if (locCycleCount == speedSampleCount - 1) {
            locCycleCount = 0;
            locationPoolIsFull = true;
        } else locCycleCount++;
        if (locationPoolIsFull && locationPool[locCycleCount] != null) {
            long timeDiffMillis;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                timeDiffMillis =
                        (currentLocation.getElapsedRealtimeNanos() - locationPool[locCycleCount].getElapsedRealtimeNanos()) / 1000000;

            } else {
                timeDiffMillis =
                        currentLocation.getTime() - locationPool[locCycleCount].getTime();
            }
            averageSpeed = (currentLocation.distanceTo(locationPool[locCycleCount]) / (((float) timeDiffMillis) / 1000));

/*            float z = 0;
            for(float x : averageSpeedPool) {
                z+=x;
                Log.d("SPEEDCYCLE TEHZ", "" + z);
            }
            z/=10;
            Log.d("SPEEDCYCLE TEHZfinal(", "" + z);*/
            pref.edit().putFloat(WaveActivity.CURRENT_SPEED, averageSpeed).apply();
//            pref.edit().putFloat(WaveActivity.CURRENT_SPEED_TIMESTAMP, currentLocation.getTime()).apply();
        }
    }

    public class TehLocListener implements IBaseGpsListener {

        Context context;

        Location location;

        private TehLocListener(Context context) {
            this.context = context;
        }

        private void updateLocation(CLocation location) {
            location.setUseMetricunits(true);
            currentLocation = location;

            if (mSppType == SPP_TYPE_METERS) {

                locationAccuracy = location.getAccuracy();
                pref.edit().putFloat(WaveActivity.LOCATION_ACCURACY, locationAccuracy).apply();

                if (startingPhaseLocation == null &&
                        locationAccuracy <= acceptableAccuracy) {

                    long timeDiffMillis;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        timeDiffMillis =
                                (SystemClock.elapsedRealtimeNanos() - location.getElapsedRealtimeNanos()) / 1000000;

                    } else {
                        timeDiffMillis =
                                System.currentTimeMillis() - location.getTime();
                    }

                    //TESTING
                   /* long getNanos = 0;
                    long gettime = location.getTime();
                    long currNanoTime = 0;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        getNanos = location.getElapsedRealtimeNanos();
                        currNanoTime = SystemClock.elapsedRealtimeNanos();
                    }
                    long currTime = System.currentTimeMillis();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US);
                    SimpleDateFormat sdfSimple = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
                    ParsePosition pp = new ParsePosition(0);
                    Date dtCurr = new Date(currTime);
                    Date dtLoc = new Date(gettime);
                    Log.d("SPEEDCYCLE TIMEACC", "--------------------");
                    Log.d("SPEEDCYCLE TIMEACC", "currtime: " + currTime + " " + sdf.format(dtCurr));
                    Log.d("SPEEDCYCLE TIMEACC", "currnanotime: " + currNanoTime);
                    Log.d("SPEEDCYCLE TIMEACC", "gettime: " + gettime + " " + sdf.format(dtLoc));
                    Log.d("SPEEDCYCLE TIMEACC", "gettimeDIF: " + (currTime - gettime));
                    Log.d("SPEEDCYCLE TIMEACC", "getNanos: " + getNanos);
                    Log.d("SPEEDCYCLE TIMEACC", "nanosDIF: " + (currNanoTime - getNanos));*/

                    completeLocking();

                } else if (startingPhaseLocation != null) {
                    phaseProgress = (int) location.distanceTo(startingPhaseLocation);
                }
            }
        }

        private boolean useMetricUnits() {
//        CheckBox chkUseMetricUnits = (CheckBox) this.findViewById(R.id.chkMetricUnits);
            return true;
        }

        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                CLocation myLocation = new CLocation(location, this.useMetricUnits());
                this.updateLocation(myLocation);
                updateAverageSpeed();
            }
        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            /*if (status == LocationProvider.AVAILABLE) {
                if (startingPhaseLocation == null) {
                    startingPhaseLocation
                }
            }*/
        }

        @Override
        public void onGpsStatusChanged(int event) {

        }
    }

    public static void completeLocking() {
        pref.edit().putBoolean(WaveActivity.GPS_LOCKING, false).apply();
        startingPhaseLocation = currentLocation;
    }
}


text:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    # If a user is signed in then he is trying to link a new account
    if user_signed_in?
      auth = request.env["omniauth.auth"]
      if current_user && current_user.persisted? && current_user.update_external_account(auth)
        flash[:success] = "Your facebook account has been linked to this user account successfully."
      else
        flash[:error] = "The Facebook account has been linked with another user."
      end
      redirect_to edit_user_path(current_user)
    else
      @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
      if @user.persisted?
        # save fb access token in the session
        session[:fb_access_token] = request.env["omniauth.auth"]["credentials"]["token"]
        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
        set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
      else
        session["devise.facebook_data"] = request.env["omniauth.auth"]
        redirect_to new_user_registration_url
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2020 Google LLC
//
// 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.

/**
 * This application demonstrates how to perform basic operations on buckets with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket') {
  // [START storage_disable_uniform_bucket_level_access]
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The ID of your GCS bucket
  // const bucketName = 'your-unique-bucket-name';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();
  async function disableUniformBucketLevelAccess() {
    // Disables uniform bucket-level access for the bucket
    await storage.bucket(bucketName).setMetadata({
      iamConfiguration: {
        uniformBucketLevelAccess: {
          enabled: false,
        },
      },
    });

    console.log(`Uniform bucket-level access was disabled for ${bucketName}.`);
  }

  disableUniformBucketLevelAccess().catch(console.error);
  // [END storage_disable_uniform_bucket_level_access]
}
main(...process.argv.slice(2));


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>aposentar-se-por-razao-de-invalidez</id>
    <dbId>48</dbId>
    <nome>Aposentar-se por razão de invalidez.</nome>
    <sigla></sigla>
    <nomes-populares>
        <item id="1516">Aposentadoria por Invalidez.</item>
        <item id="1517">Ser encostado pelo INSS</item>
    </nomes-populares>
    <descricao>A aposentadoria por invalidez é um benefício financeiro mensal recebido pelo trabalhador incapaz de trabalhar em sua profissão e de ser reabilitado em outra profissão. O benefício pode ser reavaliado a cada dois anos, a critério do INSS.</descricao>
    <contato>Central de Atendimento do INSS, através do telefone 135.</contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="2279">
            <tipo>Segurado Especial</tipo>
            <requisitos>&nbsp;
Trabalhador rural que exerce sua atividade individualmente ou com a ajuda da família, assim como trabalhadores com atividades afins, como pescadores artesanais e indígenas, que:

&nbsp;

* Tenha contribuído pelo menos 12 meses (exceto em casos de acidente de trabalho ou doenças previstas em lei);
* Comprove ter doença ou outro problema de saúde que o torne incapaz de trabalhar;
* Esteja afastado do trabalho há pelo menos 15 dias corridos, ou 15 dias intercalados em um espaço de 60 dias.</requisitos>
        </solicitante>
        <solicitante id="2278">
            <tipo>Segurado Regular</tipo>
            <requisitos>&nbsp;
Trabalhador de entidades privadas, associado ao INSS e com as parcelas em dia, que:

&nbsp;

* Tenha realizado ao menos 12 contribuições mensais (exceto em casos de acidente de trabalho ou doenças previstas em lei);
* Comprove ter doença ou outro impedimento físico por motivo de saúde que o torne incapaz de trabalhar;
* Estar afastado do trabalho há pelo menos 15 dias corridos, ou 15 dias intercalados em um espaço de 60 dias.</requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <em-media max="3" unidade="meses"/>
        <descricao>Dependendo do fluxo de procura e do local de atendimento do requerente, o processo pode demorar até um ano.</descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="4601">
            <titulo>Agendar perícia médica e entrega dos documentos em agência do INSS</titulo>
            <descricao>Você irá acessar o portal do INSS, preencher os dados necessários, agendar sua perícia para o dia desejado na agência disponível desejada e imprimir o comprovante de agendamento.</descricao>
            <documentos>
                <default>
                    <item id="1591">Número do PIS/PASEP;</item>
                    <item id="1592">Nome completo da sua mãe;</item>
                    <item id="1593">Sua data de nascimento;</item>
                    <item id="1594">Dados funcionais;</item>
                    <item id="1595">CID, se souber.</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="2274" tipo="web-agendar">
                        <descricao>http://www2.dataprev.gov.br/sabiweb/agendamento/inicio.view#sabiweb</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="4602">
            <titulo>Comparecer à Agência do INSS do dia e horário agendados</titulo>
            <descricao>Você irá à agência do INSS escolhida na data e horário definidos na etapa anterior, para realizar a perícia e entregar os documentos necessários ao pedido.</descricao>
            <documentos>
                <default>
                    <item id="1598">Documento de identificação válido e oficial com foto;</item>
                    <item id="1599">Cadastro de Pessoa Física - CPF;</item>
                    <item id="1600">Carteira de trabalho, carnês de contribuição e outros documentos que comprovem pagamento ao INSS;</item>
                    <item id="1601">Documentos médicos que comprovem a causa do problema de saúde, o tratamento médico indicado e a incapacidade de trabalhar;</item>
                    <item id="1602">•	Caso o motivo da incapacitação for acidente de trabalho, a Comunicação de Acidente de Trabalho (CAT); e</item>
                </default>
                <caso id="278" descricao="Segurado Especial">
                    <documento>
                        <id>1596</id>
                        <descricao>Documentos que comprovem sua situação (declaração de sindicato, contratos de arrendamento, documentos onde conste a ocupação, etc.)</descricao>
                    </documento>
                </caso>
                <caso id="279" descricao="Segurado Regular">
                    <documento>
                        <id>1597</id>
                        <descricao>Declaração carimbada e assinada do empregador, informando último dia trabalhado (se precisar, imprima o requerimento no site do INSS).</descricao>
                    </documento>
                </caso>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="2275" tipo="presencial">
                        <descricao>Agência do INSS próxima à sua residência e escolhida na etapa anterior.</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="4603">
            <titulo>Saber o resultado do pedido e, caso seja aceito, começar a receber o benefício.</titulo>
            <descricao>Você poderá acompanhar o processo de pedido pela página do INSS ou visitando a agência do INSS onde o pedido foi feito, até que saia o resultado. Caso seu pedido seja aprovado, o cidadão começará a receber o benefício no mês seguinte.</descricao>
            <documentos>
                <default>
                    <item id="1603">Número do benefício ou do requerimento;</item>
                    <item id="1604">Data de Nascimento;</item>
                    <item id="1605">Documento de Identificação válido, original e com foto;</item>
                    <item id="1606">Cadastro de Pessoa Física - CPF;</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="2276" tipo="web">
                        <descricao>http://www2.dataprev.gov.br/sabiweb/relatorio/imprimirCRER.view?acao=imprimir_CRER</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="2277" tipo="presencial">
                        <descricao>Na agência do INSS onde foi atendido</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/1934" dbId="36802">
        <nomeOrgao>Instituto Nacional do Seguro Social (INSS)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="1" idServicoSegmento="4684">Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Previdência Social</item>
        <item>Proteção e Benefícios ao Trabalhador</item>
        <item>Trabalho</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="8576">aposentadoria</item>
        <item id="8577">invalidez</item>
        <item id="8578">readptação</item>
    </palavras-chave>
    <legislacoes>
        <item id="2062">DECRETO-LEI Nº 5.452, DE 1º DE MAIO DE 1943</item>
    </legislacoes>
    <servicos-relacionados>
        <item>47</item>
        <item>46</item>
        <item>49</item>
    </servicos-relacionados>
</servico>


text:
A set of SVG badges to mark your modules with the
[Node stability index](http://nodejs.org/api/documentation.html#documentation_stability_index).

### Stability: 0 - Deprecated ###

[![deprecated](http://badges.github.io/stability-badges/dist/deprecated.svg)](http://github.com/badges/stability-badges)

``` markdown
[![deprecated](http://badges.github.io/stability-badges/dist/deprecated.svg)](http://github.com/badges/stability-badges)
```

### Stability: 1 - Experimental ###

[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)

``` markdown
[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)
```

### Stability: 2 - Unstable ###

[![unstable](http://badges.github.io/stability-badges/dist/unstable.svg)](http://github.com/badges/stability-badges)

``` markdown
[![unstable](http://badges.github.io/stability-badges/dist/unstable.svg)](http://github.com/badges/stability-badges)
```

### Stability: 3 - Stable ###

[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges)

``` markdown
[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges)
```

### Stability: 4 - Frozen ###

[![frozen](http://badges.github.io/stability-badges/dist/frozen.svg)](http://github.com/badges/stability-badges)

``` markdown
[![frozen](http://badges.github.io/stability-badges/dist/frozen.svg)](http://github.com/badges/stability-badges)
```

### Stability: 5 - Locked ###

[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges)

``` markdown
[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges)
```


text:
package info.novatec.testit.webtester.utils.converters;

import org.openqa.selenium.By;

import info.novatec.testit.webtester.api.pageobjects.ByConverter;

/**
 * Using the ID Attribute (should be unique on the whole page).
 *
 * @since 0.9.9
 */
public class IdByConverter implements ByConverter {

    @Override
    public By toBy(String value) {
        return By.id(value);
    }

    @Override
    public String getValueFormat() {
        return "ID";
    }

}


text:
package oncue.worker;

import static akka.pattern.Patterns.ask;

import java.util.concurrent.TimeoutException;

import oncue.common.messages.CleanupJobs;
import oncue.common.messages.Job;

import org.joda.time.Duration;

import scala.concurrent.Await;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.util.Timeout;

/**
 * This job will clean up complete and failed runs from the backing store.
 * You'll probably want to run this as a timed job on a schedule.
 */
public class MaintenanceWorker extends AbstractWorker {

	private static final String EXPIRATION_AGE = "expiration-age";
	private static final String INCLUDE_FAILED_JOBS = "include-failed-jobs";
	private LoggingAdapter log = Logging.getLogger(getContext().system(), this);

	@Override
	public void doWork(Job job) throws Exception {
		processJob();
	}

	private void processJob() throws Exception {

		boolean includeFailedJobs = false;
		if (job.getParams().containsKey(INCLUDE_FAILED_JOBS))
			includeFailedJobs = new Boolean(job.getParams().get(INCLUDE_FAILED_JOBS));

		if (!job.getParams().containsKey(EXPIRATION_AGE))
			throw new IllegalArgumentException(
					"You must define the 'expiration-age' parameter in the configuration of a maintenance worker");

		Duration expirationAge = Duration.millis(scala.concurrent.duration.Duration.create(
				job.getParams().get(EXPIRATION_AGE)).toMillis());
		CleanupJobs cleanupJobs = new CleanupJobs(includeFailedJobs, expirationAge);

		try {
			Object object = Await.result(
					ask(getContext().actorFor(settings.SCHEDULER_PATH), cleanupJobs, new Timeout(
							settings.SCHEDULER_TIMEOUT)), settings.SCHEDULER_TIMEOUT);
			log.info(object.toString());
		} catch (TimeoutException e) {
			throw new RuntimeException("Timeout waiting for scheduler to clean up jobs", e);
		}
	}

	@Override
	protected void redoWork(Job job) throws Exception {
		processJob();
	}
}


text:
package org.apache.aries.blueprint.spring;

import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class SpringNamespaceHandler implements org.springframework.beans.factory.xml.NamespaceHandler {

    private final NamespaceHandler handler;
    private final ParserContext parserContext;

    public SpringNamespaceHandler(ParserContext parserContext, NamespaceHandler handler) {
        this.parserContext = parserContext;
        this.handler = handler;
    }

    @Override
    public void init() {
    }

    @Override
    public BeanDefinition parse(Element element, org.springframework.beans.factory.xml.ParserContext parserContext) {
        Metadata metadata = handler.parse(element, this.parserContext);
        if (metadata instanceof ComponentMetadata) {
            this.parserContext.getComponentDefinitionRegistry().registerComponentDefinition(
                    (ComponentMetadata) metadata);
        }
        return null;
    }

    @Override
    public BeanDefinitionHolder decorate(Node source, BeanDefinitionHolder definition, org.springframework.beans.factory.xml.ParserContext parserContext) {
        return definition;
    }
}


text:
<?php

/**
 * ezcSearchQuerySolr implements the find query for searching documents.
 *
 * @package Search
 * @version 1.0.9
 */
class ezcSearchDeleteQuerySolr implements ezcSearchDeleteQuery
{
    /**
     * Holds all the search clauses that will be used to create the search query.
     *
     * @var array(string)
     */
    public $whereClauses;

    /**
     * Holds the search handler for which this query is built.
     *
     * @var ezcSearchHandler
     */
    private $handler;

    /**
     * Contains the document definition for which this query is built.
     *
     * @param ezcSearchDocumentDefinition $definition
     */
    private $definition;

    /**
     * Constructs a new ezcSearchQuerySolr object for the handler $handler
     *
     * The handler implements mapping field names and values based on the
     * document $definition.
     *
     * @param ezcSearchHandler $handler
     * @param ezcSearchDocumentDefinition $definition
     */
    public function __construct( ezcSearchHandler $handler, ezcSearchDocumentDefinition $definition )
    {
        $this->handler = $handler;
        $this->definition = $definition;
        $this->reset();
    }

    /**
     * Resets all the internal query values to their defaults.
     */
    public function reset()
    {
        $this->whereClauses = array();
    }

    /**
     * Returns the definition that belongs to this query
     *
     * @return ezcSearchDocumentDefinition
     */
    function getDefinition()
    {
        return $this->definition;
    }

    /**
     * Returns the query as a string for debugging purposes
     *
     * @return string
     * @ignore
     */
    public function getQuery()
    {
        return $this->handler->getDeleteQuery( $this );
    }

    /**
     * Checks whether the field $field exists in the definition.
     *
     * @param string $field
     * @throws ezcSearchFieldNotDefinedException if the field is not defined.
     */
    private function checkIfFieldExists( $field )
    {
        if ( !isset( $this->definition->fields[$field] ) )
        {
            throw new ezcSearchFieldNotDefinedException( $this->definition->documentType, $field );
        }
    }

    /**
     * Adds a select/filter statement to the query
     *
     * @param string $clause
     * @return ezcSearchQuerySolr
     */
    public function where( $clause )
    {
        $this->whereClauses[] = $clause;
        return $this;
    }

    /**
     * Returns a string containing a field/value specifier, and an optional boost value.
     *
     * The method uses the document definition field type to map the fieldname
     * to a solr fieldname, and the $fieldType argument to escape the $value
     * correctly. If a definition is set, the $fieldType will be overridden
     * with the type from the definition.
     *
     * @param string $field
     * @param mixed $value
     *
     * @return string
     */
    public function eq( $field, $value )
    {
        $field = trim( $field );

        $this->checkIfFieldExists( $field );
        $fieldType = $this->definition->fields[$field]->type;
        $value = $this->handler->mapFieldValueForSearch( $fieldType, $value );
        $fieldName = $this->handler->mapFieldType( $field, $this->definition->fields[$field]->type );

        $ret = "$fieldName:$value";

        return $ret;
    }

    /**
     * Returns a string containing a field/value specifier, and an optional boost value.
     *
     * The method uses the document definition field type to map the fieldname
     * to a solr fieldname, and the $fieldType argument to escape the values
     * correctly.
     *
     * @param string $field
     * @param mixed $value1
     * @param mixed $value2
     *
     * @return string
     */
    public function between( $field, $value1, $value2 )
    {
        $field = trim( $field );

        $this->checkIfFieldExists( $field );
        $fieldType = $this->definition->fields[$field]->type;
        $value1 = $this->handler->mapFieldValueForSearch( $fieldType, $value1 );
        $value2 = $this->handler->mapFieldValueForSearch( $fieldType, $value2 );
        $fieldName = $this->handler->mapFieldType( $field, $this->definition->fields[$field]->type );

        $ret = "$fieldName:[$value1 TO $value2]";

        if ( $this->definition->fields[$field]->boost != 1 )
        {
            $ret .= "^{$this->definition->fields[$field]->boost}";
        }
        return $ret;
    }

    /**
     * Creates an OR clause
     *
     * This method accepts either an array of fieldnames, but can also accept
     * multiple parameters as field names.
     *
     * @param mixed $...
     * @return string
     */
    public function lOr()
    {
        $args = func_get_args();
        if ( count( $args ) < 1 )
        {
            throw new ezcSearchQueryVariableParameterException( 'lOr', count( $args ), 1 );
        }

        $elements = ezcSearchQueryTools::arrayFlatten( $args );
        if ( count( $elements ) == 1 )
        {
            return $elements[0];
        }
        else
        {
            return '( ' . join( ' OR ', $elements ) . ' )';
        }
    }

    /**
     * Creates an AND clause
     *
     * This method accepts either an array of fieldnames, but can also accept
     * multiple parameters as field names.
     *
     * @param mixed $...
     * @return string
     */
    public function lAnd()
    {
        $args = func_get_args();
        if ( count( $args ) < 1 )
        {
            throw new ezcSearchQueryVariableParameterException( 'lAnd', count( $args ), 1 );
        }

        $elements = ezcSearchQueryTools::arrayFlatten( $args );
        if ( count( $elements ) == 1 )
        {
            return $elements[0];
        }
        else
        {
            return '( ' . join( ' AND ', $elements ) . ' )';
        }
    }

    /**
     * Creates a NOT clause
     *
     * This method accepts a clause and negates it.
     *
     * @param string $clause
     * @return string
     */
    public function not( $clause )
    {
        return "!$clause";
    }
}
?>


text:
/**
 * @author Nikos Arechiga
 * @author Anuradha Vakil
 * Toyota InfoTechnology Center, USA
 * 465 N Bernardo Ave, Mountain View, CA 94043
 */
package dl.syntax;

import dl.semantics.*;
import dl.parser.*;
import dl.nnfParser.*;

import java.util.*;
import java.io.*;

public abstract class dLStructure {

	public boolean debug = true;
	public Operator operator;
	public ArrayList<dLStructure> arguments;

// Constructors
	public dLStructure() {
		operator = null;
		arguments = null;
	}

	public dLStructure( String operator ) {
		this.operator = new Operator( operator );
		arguments = null;
	}

	public dLStructure( Operator operator ) {
		this.operator = operator;
		arguments = null;
	}

	public dLStructure( Operator operator, ArrayList<dLStructure> arguments ) {
		this.operator = operator;
		this.arguments = arguments;
	}

	public dLStructure( String operator, ArrayList<dLStructure> arguments ) {
		this.operator = new Operator( operator );
		this.arguments = arguments;
	}

// Getters and setters
	public Operator getOperator() {
		return this.operator;
	}

	public dLStructure getArgument( int index ) {
		if ( arguments != null ) {
			return arguments.get( index );
		} else {
			return null;
		}
	}

	public List<dLStructure> getArguments() {
		return arguments;
	}

	public Iterator<dLStructure> getArgumentIterator() {
		return getArguments().iterator();
	}

	public boolean setArgument( int index, dLStructure newArgument ) {
		if ( arguments != null ) {
			arguments.set( index, newArgument );
			return true;
		} else {
			return false;
		}
	}

	public boolean addArgument( dLStructure newArgument ) {
		if ( arguments != null ) {
			arguments.add( newArgument );
			return true;
		} else {
			return false;
		}
	}

	public boolean addArguments( List<? extends dLStructure> newArgumentList ) {
		if ( arguments != null ) {
			arguments.addAll( newArgumentList );
			return true;
		} else {
			return false;
		}
	}

	public void spawnArguments() {
		arguments = new ArrayList<dLStructure>();
	}

	public boolean operatorEquals( Operator thisOperator ) {
		return getOperator().equals( thisOperator );
	}

	public boolean operatorEquals( String thisOperatorString ) {
		return getOperator().equals( new Operator( thisOperatorString ) );
	}

// clone all the arguments!
	public ArrayList<dLStructure> cloneArguments() {
		ArrayList<dLStructure> newArguments = new ArrayList<>();

		Iterator<dLStructure> argIterator = getArgumentIterator();
		while( argIterator.hasNext() ) {
			newArguments.add( (argIterator.next()).clone() );
		}

		return newArguments;
	}

// equals
	public boolean equals( Object otherObject ) {
		if ( otherObject.getClass() == this.getClass() ) {

			if ( !(this.getOperator().equals( ((dLStructure)otherObject).getOperator()) )  ){
				return false;
			}

			List<dLStructure> theseArguments = getArguments();
			List<dLStructure> thoseArguments = ((dLStructure)otherObject).getArguments();

			return theseArguments.equals( thoseArguments );

		} else {
			return false;
		}
	}

// Parse a dLStructure from a string
	public static dLStructure parseStructure( String structureString ) {
		// returns the dLStructure that exists in the string
		StringReader thisReader = new StringReader( structureString );
		dLLexer thisdLLexer = new dLLexer( thisReader );
		dLParser thisParser = new dLParser( thisdLLexer );

		try {
			thisParser.parse();
		} catch (Exception e) {
			//e.printStackTrace();
			throw new dLStructureFormatException("Problem parsing: " + structureString );
		}
		return thisParser.parsedStructure;
	}

	public static dLStructure parseNNFStructure( String structureString ) {
		// returns the dLStructure that exists in the string
		StringReader thisReader = new StringReader( structureString );
		NNFdLLexer thisdLLexer = new NNFdLLexer( thisReader );
		NNFdLParser thisParser = new NNFdLParser( thisdLLexer );

		try {
			thisParser.parse();
		} catch (Exception e) {
			//e.printStackTrace();
			throw new dLStructureFormatException("Problem parsing: " + structureString );
		}
		return thisParser.parsedStructure;
	}

// Extract assorted bits and pieces
// --- 1. getVariables -- DEPRECATED
// 2. getBoundVariables
// 3. getFreeVariables
// 4. getDynamicVariables
// 5. containsAnyFreeVariables
// 6. extractContinuousBlocks
// 7. extractFirstHybridProgram

	//public Set<RealVariable> getVariables () {
	//	Set<RealVariable> myVariables = new HashSet<RealVariable>();

	//	if ( this instanceof RealVariable ) {
	//		myVariables.add( (RealVariable)this );
	//	} else if ( arguments != null ) {
	//		Iterator<dLStructure> childIterator = arguments.iterator();

	//		while ( childIterator.hasNext() ) {
	//			myVariables.addAll( childIterator.next().getVariables() );
	//		}

	//	}

	//	return myVariables;
	//}

	public Set<RealVariable> getBoundVariables() {
		return new HashSet<RealVariable>();
	}

	public Set<RealVariable> getFreeVariables() {
		return new HashSet<>();
	}

	public boolean containsAnyFreeVariables( ArrayList<RealVariable> variables ) {
		Set<RealVariable> freeVars = getFreeVariables();
		int freeVarsCardinality = freeVars.size();
		freeVars.removeAll( variables );

		if ( freeVars.size() < freeVarsCardinality ) {
			return true;
		} else {
			return false;
		}
	}

	public Set<RealVariable> getDynamicVariables() {
		return new HashSet<>();
	}

	public ArrayList<ContinuousProgram> extractContinuousBlocks() {

		ArrayList<ContinuousProgram> continuousBlocks = new ArrayList<ContinuousProgram>();

		if ( getClass().equals( ContinuousProgram.class ) ) {
			continuousBlocks.add( (ContinuousProgram)this );

		} else if ( arguments != null ) {

			Iterator<dLStructure> argumentsIterator = arguments.iterator();

			dLStructure thisArgument;
			while ( argumentsIterator.hasNext() ) {
				thisArgument = argumentsIterator.next();

				if ( thisArgument.arguments != null ) {
					continuousBlocks.addAll( thisArgument.extractContinuousBlocks() );
				}
			}
		}

		return continuousBlocks;
	}

	public HybridProgram extractFirstHybridProgram() {
		HybridProgram myProgram = null;

		if ( this instanceof HybridProgram ) {
			return (HybridProgram)this;
		} else if ( arguments!= null ) {

			Iterator<dLStructure> argumentsIterator = arguments.iterator();
			dLStructure thisArgument;
			while ( argumentsIterator.hasNext() ) {
				thisArgument = argumentsIterator.next();

				if ( thisArgument.extractFirstHybridProgram() != null ) {
					myProgram = thisArgument.extractFirstHybridProgram();
				}
			}
		}

		return myProgram;
	}

	public List<HybridProgram> extractHybridPrograms() {
		List<HybridProgram> hybridPrograms = new ArrayList<>();

		if ( this instanceof HybridProgram ) {
			hybridPrograms.add( (HybridProgram)this );

		} else if ( getArguments() != null ) {

			for ( dLStructure thisArgument : getArguments() ) {
				hybridPrograms.addAll( thisArgument.extractHybridPrograms() );
			}
		}

		return hybridPrograms;

	}

// Export toString methods

	public String toString() {
		throw new RuntimeException("KeYmaera string is undefined for this structure: " + this.getClass().toString() );
	}

//	public String toMathematicaString() {
//		throw new RuntimeException("Mathematica string is undefined for this structure: " + this.getClass().toString() );
//	}
//
//	public String toManticoreString() {
//		throw new RuntimeException("Manticore string is undefined for this structure: " + this.getClass().toString() );
//	}

	public String todRealString() {
		throw new RuntimeException("dReal string is undefined for this structure: " + this.getClass().toString() );
	}

	public String toMatlabString() {
		throw new RuntimeException("Matlab string is undefined for this structure: " + this.getClass().toString() );
	}

	public abstract dLStructure clone();

// Convenience functions
	public boolean isANumber() {
		return false;
	}

	public boolean isAVariable() {
		return false;
	}

}


text:
function initializeDebugger()
{
   echo(" % - Initializing Debugger");

   // Load the scripts.
   exec("./Scripts/debugger.ed.cs");

   // And the guis.
   exec("./Gui/breakConditionDlg.ed.gui");
   exec("./Gui/connectDlg.ed.gui");
   exec("./Gui/editWatchDlg.ed.gui");
   exec("./Gui/findDlg.ed.gui");
   exec("./Gui/debugger.ed.gui");
   exec("./Gui/watchDlg.ed.gui");
}

function destroyDebugger()
{
   if (isObject(TCPDebugger))
      TCPDebugger.delete();
}

function startDebugger()
{
   // Clean up first.
   destroyDebugger();

   // Create a TCP object named TCPDebugger.
   new TCPObject(TCPDebugger);

   // Used to get unique IDs for breakpoints and watch expressions.
   $DbgBreakId = 0;
   $DbgWatchSeq = 1;

   // Set up the GUI.
   DebuggerConsoleView.setActive(false);
   Canvas.pushDialog(DebuggerGui);
}


text:
<?php

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;

$collection = new RouteCollection();

$collection->add('security.login', new Route('/login', array(
    '_controller' => 'UserBundle:Security:login'
)));

$collection->add('security.logout', new Route('/logout', array(
    '_controller' => 'UserBundle:Security:logout'
)));

$collection->add('security.check', new Route('/login_check', array()));

$collection->add('security.accessdenied', new Route('/accessdenied', array(
    '_controller' => 'UserBundle:Security:accessDenied'
)));

$collection->add('user.list', new Route('/admin/user', array(
    '_controller' => 'UserBundle:User:list'
)));

$collection->add('user.add', new Route('/admin/user/add', array(
    '_controller' => 'UserBundle:User:add'
)));

$collection->add('user.edit', new Route('/admin/user/edit/{id}', array(
    '_controller' => 'UserBundle:User:edit'
)));

return $collection;


text:
import threading
import numpy as np
import re
import sys
import time
import math

#Detector de leitura (Elmadjian, 2015)
#------------------------------------

class Detector (threading.Thread):

    def __init__(self, thresh, cv):
        threading.Thread.__init__(self)
        self.next_x = None
        self.next_y = None
        self.thresh = thresh
        self.state = 0
        self.stop = False
        self.cv = cv
        self.elapsed = time.time()

        self.cnt_yes = 0
        self.cnt_no  = 0
        self.cnt_total = 0

    def run(self):
        self.detect(self.cv)

    def storeValues(self, next_point):
        self.next_x = next_point[0]
        self.next_y = next_point[1]

    def changeState(self, changeValue):
        self.state += changeValue
        if self.state > 100:
            self.state = 100
        elif self.state < -60:
            self.state = -60

    def changePercentage(self, var, value):
        var += value
        if var > 100:
            var = 100
        elif var < 15:
            var = 15
        return var

    def checkCombination(self, buff):
        if buff[0] and buff[1] and buff[2]:
            return True
        if buff[0] and buff[1] and not buff[2]:
            return True
        if buff[0] and not buff[1] and buff[2]:
            return True
        if not buff[0] and buff[1] and buff[2]:
            return True
        return False

    def detect(self, cv):
        prev_x = 0
        prev_y = 0
        reading_buff  = []
        yaxs_mov = np.array([])
        xaxs_mov = np.array([])
        finite_diff = 0.1
        short_mov = 0
        reading = 50
        skimming = 50

        while True:
            with cv:
                cv.wait()
            if self.stop:
                break
            dx = (self.next_x - prev_x) / finite_diff
            dy = (self.next_y - prev_y) / finite_diff
            yaxs_mov = np.append(yaxs_mov, [prev_y])
            xaxs_mov = np.append(xaxs_mov, [prev_x])

            #read forward
            if 0.15 < dx <1.5 and -0.5 < dy < 0.5:
                reading_buff.append(True)
                short_mov += 1

            #regression
            elif dx < -2.0 and -1.0 < dy < 0.0:
                reading_buff.append(False)
                if len(yaxs_mov) > 1 and short_mov >= 1:
                    criteria = np.ptp(xaxs_mov) * short_mov
                    xaxs_mov = np.array([])
                    yaxs_mov = np.array([])
                    short_mov = 0
                    if criteria < 2:
                        skimming = self.changePercentage(skimming, 10)
                        reading  = self.changePercentage(reading, -10)
                    else:
                        skimming = self.changePercentage(skimming, -10)
                        reading  = self.changePercentage(reading, 10)

            #fixations
            elif -0.15 < dx < 0.15 and -0.2 < dy < 0.2:
                pass

            #unrelated pattern
            else:
                self.changeState(-5)

            #validating window
            if len(reading_buff) == 3:
                if self.checkCombination(reading_buff):
                    self.changeState(15)
                else:
                    self.changeState(-15)
                reading_buff.pop(0)

            #detection triggering
            if self.state >= self.thresh:
                print("\rreading detected!", self.state, "reading:", reading, "skimming:", skimming,"#", end="")
                self.cnt_yes += 1
            else:
                #print("\rwaiting...", self.state, time.time() - self.elapsed, end="")
                self.cnt_no += 1
            prev_x = self.next_x
            prev_y = self.next_y
            self.cnt_total += 1

#Lê o arquivo de entrada
#-----------------------
class FileReader:

    def __init__(self, filename):
        self.x = []
        self.y = []
        self.time = []
        self.values = []
        self.readFile(filename)

    def readFile(self, filename):
        pattern = re.compile("\d+.?\d+")
        with open(filename, 'r') as sample:
            for line in sample:
                group = pattern.findall(line)
                if group:
                    x = float(group[0])
                    y = float(group[1])
                    t = float(group[2])
                    self.x.append(x)
                    self.y.append(y)
                    self.time.append(t)
                    self.values.append([x,y,t])

#------------------------
if __name__ == '__main__':
    fr = FileReader(sys.argv[1])
    cv = threading.Condition()
    detector = Detector(30, cv)
    detector.start()
    #for i in fr.x:
    for i in range(len(fr.values) - 1):
        detector.storeValues(fr.values.pop(0))
        with cv:
            cv.notify_all()
        time.sleep(0.001)
        #fr.plota()

    detector.stop = True
    print("\ntotal:", detector.cnt_total)
    print("found:", detector.cnt_yes)
    print("not found:", detector.cnt_no)
    with cv:
        cv.notify_all()
    detector.join()


text:
    <button class="btn btn-default">Action</button>

        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownKebabRight9" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

        </button>

Go to Application

Revoke Grant

Logout Session(s)

Something else here

Separated link

                {{app.name}}

                {{app.description}}

                8 Hosts

                6 Clusters

                10 Nodes

                8 Images


text:
<!--
Copyright 2015 - Tomasz Cichocinski <tomaszcichocinski@gmail.com>
Released under the MIT License - https://github.com/Baransu/mendela-pl-p
-->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>21</title>
    </head>
    <body>
        <script type="text/javascript">
            alert("nic tu po tobie!")
            if(window.history.length > 1) {
                window.history.back();
            } else {
                window.location.href = "https://duckduckgo.com/";
            }
        </script>
    </body>
</html>


text:
package com.atlassian.jira.plugins.dvcs.spi.github;

import com.atlassian.jira.bc.user.UserService;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.springframework.stereotype.Component;

@Component
public class UserServiceFactory
{
    public org.eclipse.egit.github.core.service.UserService createUserService(GitHubClient gitHubClient){
        return new org.eclipse.egit.github.core.service.UserService(gitHubClient);
    }

}


text:
package top.ningg.java.queue;

import java.util.concurrent.BlockingQueue;

/**
 * Created by guoning on 15/9/4.
 */
public class Consumer implements Runnable {

    private BlockingQueue<Message> queue;

    public Consumer(BlockingQueue<Message> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        String msg;
        try {
            while ("Exited".equals(msg = queue.take().getMsg())) {
                Thread.sleep(10);
                System.out.println("Msg consumed: " + msg);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}