text:
package org.camlistore;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.camlistore.UploadThread.CamputChunkUploadedMessage;
import org.camlistore.UploadThread.CamputStatsMessage;

import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

public class UploadService extends Service {
    private static final String TAG = "UploadService";

    private static int NOTIFY_ID_UPLOADING = 0x001;

    public static final String INTENT_POWER_CONNECTED = "POWER_CONNECTED";
    public static final String INTENT_POWER_DISCONNECTED = "POWER_DISCONNECTED";
    public static final String INTENT_UPLOAD_ALL = "UPLOAD_ALL";
    public static final String INTENT_NETWORK_WIFI = "WIFI_NOW";
    public static final String INTENT_NETWORK_NOT_WIFI = "NOT_WIFI_NOW";

    // Everything in this block guarded by 'this':
    private boolean mUploading = false; // user's desired state (notified
                                        // quickly)
    private UploadThread mUploadThread = null; // last thread created; null when
                                               // thread exits
    private Notification.Builder mNotificationBuilder; // null until upload is
                                                       // started/resumed
    private final Map<QueuedFile, Long> mFileBytesRemain = new HashMap<QueuedFile, Long>();
    private final LinkedList<QueuedFile> mQueueList = new LinkedList<QueuedFile>();
    private final Map<String, Long> mStatValue = new TreeMap<String, Long>();
    private IStatusCallback mCallback = DummyNullCallback.instance();
    private String mLastUploadStatusText = null; // single line
    private String mLastUploadStatsText = null; // multi-line stats
    private int mBytesInFlight = 0;
    private int mFilesInFlight = 0;

    // Stats, all guarded by 'this', and all reset to 0 on queue size transition
    // from 0 -> 1.
    private long mBytesTotal = 0;
    private long mBytesUploaded = 0;
    private int mFilesTotal = 0;
    private int mFilesUploaded = 0;

    // Effectively final, initialized in onCreate():
    PowerManager mPowerManager;
    WifiManager mWifiManager;
    NotificationManager mNotificationManager;
    Preferences mPrefs;

    // File Observers. Need to keep a reference to them, as there's no JNI
    // reference and their finalizers would run otherwise, stopping their
    // inotify.
    private final ArrayList<FileObserver> mObservers = new ArrayList<FileObserver>();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");

        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mPrefs = new Preferences(getSharedPreferences(Preferences.NAME, 0));

        updateBackgroundWatchers();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind intent=" + intent);
        return service;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        handleCommand(intent);
    }

    private void startUploadService() {
        startService(new Intent(UploadService.this, UploadService.class));
    }

    // This is @Override as of SDK version 5, but we're targetting 4 (Android
    // 1.6)
    private static final int START_STICKY = 1; // in SDK 5

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    private void handleCommand(Intent intent) {
        Log.d(TAG, "in handleCommand() for onStart() intent: " + intent);
        if (intent == null) {
            stopServiceIfEmpty();
            return;
        }

        String action = intent.getAction();
        if (Intent.ACTION_SEND.equals(action)) {
            handleSend(intent);
            stopServiceIfEmpty();
            return;
        }

        if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
            handleSendMultiple(intent);
            stopServiceIfEmpty();
            return;
        }

        if (INTENT_UPLOAD_ALL.equals(action)) {
            handleUploadAll();
            return;
        }

        try {
            if (mPrefs.autoUpload()) {
                boolean startAuto = false;
                boolean stopAuto = false;

                if (INTENT_POWER_CONNECTED.equals(action)) {
                    if (!mPrefs.autoRequiresWifi() || WifiPowerReceiver.onWifi(this)) {
                        startAuto = true;
                    }
                } else if (INTENT_NETWORK_WIFI.equals(action)) {
                    if (!mPrefs.autoRequiresPower() || WifiPowerReceiver.onPower(this)) {
                        String ssid = "";
                        String requiredSSID = mPrefs.autoRequiredWifiSSID();
                        if (intent.hasExtra("SSID")) {
                            ssid = intent.getStringExtra("SSID");
                        }
                        Log.d(TAG, "SSID: '" + ssid +"' / Required SSID: '" + requiredSSID + "'");
                        if (requiredSSID.equals("") || requiredSSID.equals(ssid)) {
                            startAuto = true;
                        }
                    }
                } else if (INTENT_POWER_DISCONNECTED.equals(action)) {
                    stopAuto = mPrefs.autoRequiresPower();
                } else if (INTENT_NETWORK_NOT_WIFI.equals(action)) {
                    stopAuto = mPrefs.autoRequiresWifi();
                }

                if (startAuto) {
                    Log.d(TAG, "Starting automatic uploads");
                    service.resume();
                    handleUploadAll();
                    return;
                }
                if (stopAuto) {
                    Log.d(TAG, "Stopping automatic uploads");
                    service.pause();
                    stopBackgroundWatchers();
                    stopServiceIfEmpty();
                    return;
                }
            }
        } catch (RemoteException e) {
            // Ignore.
        }
    }

    private void handleSend(Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras == null) {
            Log.w(TAG, "expected extras in handleSend");
            return;
        }

        extras.keySet(); // unparcel
        Log.d(TAG, "handleSend; extras=" + extras);

        Object streamValue = extras.get("android.intent.extra.STREAM");
        if (!(streamValue instanceof Uri)) {
            Log.w(TAG, "Expected URI for STREAM; got: " + streamValue);
            return;
        }

        final Uri uri = (Uri) streamValue;
        Util.runAsync(new Runnable() {
            @Override
            public void run() {
                try {
                    service.enqueueUpload(uri);
                } catch (RemoteException e) {
                } finally {
                    stopServiceIfEmpty();
                }
            }
        });
    }

    private void handleUploadAll() {
        startService(new Intent(UploadService.this, UploadService.class));
        final PowerManager.WakeLock wakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Camli Upload All");
        wakeLock.acquire();
        Util.runAsync(new Runnable() {
            @Override
            public void run() {
                try {
                    List<String> dirs = getBackupDirs();
                    List<Uri> filesToQueue = new ArrayList<Uri>();
                    for (String dirName : dirs) {
                        File dir = new File(dirName);
                        if (!dir.exists()) {
                            continue;
                        }
                        File[] files = dir.listFiles();
                        if (files != null) {
                            for (int i = 0; i < files.length; ++i) {
                                File f = files[i];
                                if (f.isDirectory()) {
                                    // Skip thumbnails directory.
                                    // TODO: are any interesting enough to recurse into?
                                    // Definitely don't need to upload thumbnails, but
                                    // but maybe some other app in the the future creates
                                    // sharded directories. Eye-Fi doesn't, though.
                                    continue;
                                }
                                filesToQueue.add(Uri.fromFile(f));
                            }
                        }
                    }
                    try {
                        service.enqueueUploadList(filesToQueue);
                    } catch (RemoteException e) {
                    } finally {
                        stopServiceIfEmpty();
                    }
                } finally {
                    wakeLock.release();
                }
            }
        });
    }

    private List<String> getBackupDirs() {
        ArrayList<String> dirs = new ArrayList<String>();
        if (mPrefs.autoDirPhotos()) {
            dirs.add(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
            dirs.add(Environment.getExternalStorageDirectory() + "/DCIM/100MEDIA");
            dirs.add(Environment.getExternalStorageDirectory() + "/DCIM/100ANDRO");
            dirs.add(Environment.getExternalStorageDirectory() + "/Eye-Fi");
        }
        if (mPrefs.autoDirMyTracks()) {
            dirs.add(Environment.getExternalStorageDirectory() + "/gpx");
            dirs.add(Environment.getExternalStorageDirectory() + "/kml");
        }
        return dirs;
    }

    private void handleSendMultiple(Intent intent) {
        ArrayList<Parcelable> items = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        ArrayList<Uri> uris = new ArrayList<Uri>(items.size());
        for (Parcelable p : items) {
            if (!(p instanceof Uri)) {
                Log.d(TAG, "uh, unknown thing " + p);
                continue;
            }
            uris.add((Uri) p);
        }
        final ArrayList<Uri> finalUris = uris;
        Util.runAsync(new Runnable() {
            @Override
            public void run() {
                try {
                    service.enqueueUploadList(finalUris);
                } catch (RemoteException e) {
                } finally {
                    stopServiceIfEmpty();
                }
            }
        });
    }

    private void stopBackgroundWatchers() {
        synchronized (UploadService.this) {
            if (mObservers.isEmpty()) {
                return;
            }
            Log.d(TAG, "Stopping background watchers...");
            for (FileObserver fo : mObservers) {
                fo.stopWatching();
            }
            mObservers.clear();
        }
    }

    private void updateBackgroundWatchers() {
        stopBackgroundWatchers();
        if (!mPrefs.autoUpload()) {
            return;
        }
        startBackgroundWatchers();
    }

    private void startBackgroundWatchers() {
        Log.d(TAG, "Starting background watchers...");
        synchronized (UploadService.this) {
            maybeAddObserver("DCIM/Camera");
            maybeAddObserver("DCIM/100MEDIA");
            maybeAddObserver("DCIM/100ANDRO");
            maybeAddObserver("Eye-Fi");
            maybeAddObserver("gpx");
        }
    }

    // Requires that UploadService.this is locked.
    private void maybeAddObserver(String suffix) {
        File f = new File(Environment.getExternalStorageDirectory(), suffix);
        if (f.exists()) {
            mObservers.add(new CamliFileObserver(service, f));
        }
    }

    @Override
    public void onDestroy() {
        synchronized (this) {
            Log.d(TAG, "onDestroy of camli UploadService; thread=" + mUploadThread + "; uploading=" + mUploading + "; queue size=" + mFileBytesRemain.size());
        }
        super.onDestroy();
        if (mUploadThread != null) {
            Log.e(TAG, "Unexpected onDestroy with active upload thread.  Killing it.");
            mUploadThread.interrupt();
            mUploadThread = null;
        }
    }

    // Called by UploadThread to get stuff to do. Caller owns the returned new
    // LinkedList. Doesn't return null.
    LinkedList<QueuedFile> uploadQueue() {
        synchronized (this) {
            LinkedList<QueuedFile> copy = new LinkedList<QueuedFile>();
            copy.addAll(mQueueList);
            return copy;
        }
    }

    void setUploadStatusText(String status) {
        IStatusCallback cb;
        synchronized (this) {
            mLastUploadStatusText = status;
            cb = mCallback;
        }
        try {
            cb.setUploadStatusText(status);
        } catch (RemoteException e) {
        }
    }

    void setInFlightBytes(int v) {
        synchronized (this) {
            mBytesInFlight = v;
        }
        broadcastByteStatus();
    }

    void broadcastByteStatus() {
        Notification notification = null;
        synchronized (this) {
            if (mNotificationBuilder != null) {
                int kBUploaded = (int)(mBytesUploaded / 1024L);
                int kBTotal = (int)(mBytesTotal / 1024L);

                mNotificationBuilder.setProgress(kBTotal, kBUploaded, false);
                notification = mNotificationBuilder.build();
            }
            try {
                mCallback.setByteStatus(mBytesUploaded, mBytesInFlight, mBytesTotal);
            } catch (RemoteException e) {
            }
        }

        if (notification != null) {
            mNotificationManager.notify(NOTIFY_ID_UPLOADING, notification);
        }
    }

    void broadcastFileStatus() {
        // TODO read mfiles/mcallback under lock and setfilestatus after lock
        synchronized (this) {
            try {
                mCallback.setFileStatus(mFilesUploaded, mFilesInFlight, mFilesTotal);
            } catch (RemoteException e) {
            }
        }
    }

    void broadcastAllState() {
        synchronized (this) {
            try {
                mCallback.setUploading(mUploading);
                mCallback.setUploadStatusText(mLastUploadStatusText);
                mCallback.setUploadStatsText(mLastUploadStatsText);
            } catch (RemoteException e) {
            }
        }
        broadcastFileStatus();
        broadcastByteStatus();
    }

    private void onUploadThreadEnded() {
        synchronized (this) {
            Log.d(TAG, "UploadThread ended");
            mNotificationManager.cancel(NOTIFY_ID_UPLOADING);
            mUploadThread = null;
            mUploading = false;
            try {
                mCallback.setUploading(false);
            } catch (RemoteException e) {
            }
        }
        stopServiceIfEmpty();
    }

    /**
     * Callback from the UploadThread to the service.
     *
     * @param qf
     *            the queued file that was successfully uploaded.
     */
    void onUploadComplete(QueuedFile qf) {
        Log.d(TAG, "onUploadComplete of " + qf);
        synchronized (this) {
            if (!mFileBytesRemain.containsKey(qf)) {
                Log.w(TAG, "onUploadComplete of un-queued file: " + qf);
                return;
            }
            incrBytes(qf, qf.getSize());
            mFileBytesRemain.remove(qf);
            if (mFileBytesRemain.isEmpty()) {
                // Fill up the percentage bars, since we could get
                // this event before the periodic stats event.
                // And at the end, we could kill camput between
                // getting the final "file uploaded" event and the final
                // stats event.
                mFilesUploaded = mFilesTotal;
                mBytesUploaded = mBytesTotal;
                mNotificationManager.cancel(NOTIFY_ID_UPLOADING);
                stopUploadThread();
            }
            mQueueList.remove(qf); // TODO: ghetto, linear scan
        }
        broadcastAllState();
        stopServiceIfEmpty();
    }

    // incrBytes notes that size bytes of qf have been uploaded
    // and updates mBytesUploaded.
    private void incrBytes(QueuedFile qf, long size) {
        synchronized (this) {
            Long remain = mFileBytesRemain.get(qf);
            if (remain != null) {
                long actual = Math.min(size, remain.longValue());
                mBytesUploaded += actual;
                mFileBytesRemain.put(qf, remain - actual);
            }
        }
    }

    private void stopServiceIfEmpty() {
        // Convenient place to drop this cache.
        synchronized (this) {
            if (mFileBytesRemain.isEmpty() && !mUploading && mUploadThread == null && !mPrefs.autoUpload()) {
                Log.d(TAG, "stopServiceIfEmpty; stopping");
                stopSelf();
            } else {
                Log.d(TAG, "stopServiceIfEmpty; NOT stopping; " + mFileBytesRemain.isEmpty() + "; " + mUploading + "; " + (mUploadThread != null));
                return;
            }
        }
    }

    ParcelFileDescriptor getFileDescriptor(Uri uri) {
        ContentResolver cr = getContentResolver();
        try {
            return cr.openFileDescriptor(uri, "r");
        } catch (FileNotFoundException e) {
            Log.w(TAG, "FileNotFound in getFileDescriptor() for " + uri);
            return null;
        }
    }

    private void incrementFilesToUpload(int size) throws RemoteException {
        synchronized (UploadService.this) {
            mFilesTotal += size;
        }
        broadcastFileStatus();
    }

    // pathOfURI tries to return the on-disk absolute path of uri.
    // It may return null if it fails.
    public String pathOfURI(Uri uri) {
        if (uri == null) {
            return null;
        }
        if ("file".equals(uri.getScheme())) {
            return uri.getPath();
        }
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(uri, proj, null, null, null);
            if (cursor == null) {
                return null;
            }
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(proj[0]);
            return cursor.getString(columnIndex); // might still be null
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private final IUploadService.Stub service = new IUploadService.Stub() {

        @Override
        public int enqueueUploadList(List<Uri> uriList) throws RemoteException {
            startService(new Intent(UploadService.this, UploadService.class));
            Log.d(TAG, "enqueuing list of " + uriList.size() + " URIs");
            incrementFilesToUpload(uriList.size());
            int goodCount = 0;
            for (Uri uri : uriList) {
                goodCount += enqueueSingleUri(uri) ? 1 : 0;
            }
            Log.d(TAG, "...goodCount = " + goodCount);
            return goodCount;
        }

        @Override
        public boolean enqueueUpload(Uri uri) throws RemoteException {
            startUploadService();
            incrementFilesToUpload(1);
            return enqueueSingleUri(uri);
        }

        private boolean enqueueSingleUri(Uri uri) throws RemoteException {
            long statSize = 0;
            {
                ParcelFileDescriptor pfd = getFileDescriptor(uri);
                if (pfd == null) {
                    incrementFilesToUpload(-1);
                    stopServiceIfEmpty();
                    return false;
                }

                try {
                    statSize = pfd.getStatSize();
                } finally {
                    try {
                        pfd.close();
                    } catch (IOException e) {
                    }
                }
            }

            String diskPath = pathOfURI(uri);
            if (diskPath == null) {
                Log.e(TAG, "failed to find pathOfURI(" + uri + ")");
                return false;
            }
            Log.d(TAG, "diskPath of " + uri + " = " + diskPath);

            QueuedFile qf = new QueuedFile(uri, statSize, diskPath);

            boolean needResume = false;
            synchronized (UploadService.this) {
                if (mFileBytesRemain.containsKey(qf)) {
                    Log.d(TAG, "Dup blob enqueue, ignoring " + qf);
                    stopServiceIfEmpty();
                    return false;
                }
                Log.d(TAG, "Enqueueing blob: " + qf);
                mFileBytesRemain.put(qf, qf.getSize());
                mQueueList.add(qf);

                if (mFileBytesRemain.size() == 1) {
                    mBytesTotal = 0;
                    mFilesTotal = 0;
                    mBytesUploaded = 0;
                    mFilesUploaded = 0;
                }
                mBytesTotal += qf.getSize();
                mFilesTotal += 1;
                needResume = !mUploading;

                if (mUploadThread != null) {
                    mUploadThread.enqueueFile(qf);
                }
            }
            broadcastFileStatus();
            broadcastByteStatus();
            if (needResume) {
                resume();
            }
            return true;
        }

        @Override
        public boolean isUploading() throws RemoteException {
            synchronized (UploadService.this) {
                return mUploading;
            }
        }

        @Override
        public void registerCallback(IStatusCallback cb) throws RemoteException {
            // TODO: permit multiple listeners? when need comes.
            synchronized (UploadService.this) {
                if (cb == null) {
                    cb = DummyNullCallback.instance();
                }
                mCallback = cb;
            }
            broadcastAllState();
        }

        @Override
        public void unregisterCallback(IStatusCallback cb) throws RemoteException {
            synchronized (UploadService.this) {
                mCallback = DummyNullCallback.instance();
            }
        }

        @Override
        public boolean resume() throws RemoteException {
            Log.d(TAG, "Resuming upload...");
            HostPort hp = mPrefs.hostPort();
            if (!hp.isValid()) {
                setUploadStatusText("Upload server not configured.");
                return false;
            }

            final PowerManager.WakeLock wakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Camli Upload");
            final WifiManager.WifiLock wifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "Camli Upload");

            synchronized (UploadService.this) {
                if (mUploadThread != null) {
                    Log.d(TAG, "Already uploading; aborting resume.");
                    return false;
                }

                wakeLock.acquire();
                wifiLock.acquire();

                mNotificationBuilder = new Notification.Builder(UploadService.this);
                mNotificationBuilder.setOngoing(true)
                    .setContentTitle("Uploading")
                    .setContentText("Camlistore uploader running")
                    .setSmallIcon(android.R.drawable.stat_sys_upload);
                mNotificationManager.notify(NOTIFY_ID_UPLOADING, mNotificationBuilder.build());

                mUploading = true;
                mUploadThread = new UploadThread(UploadService.this, hp, mPrefs.trustedCert(), mPrefs.username(), mPrefs.password());
                mUploadThread.start();

                // Start a thread to release the wakelock...
                final Thread threadToWatch = mUploadThread;
                new Thread("UploadThread-waiter") {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                threadToWatch.join(10000); // 10 seconds
                            } catch (InterruptedException e) {
                                Log.d(TAG, "Interrupt waiting for uploader thread.", e);
                            }
                            synchronized (UploadService.this) {
                                if (threadToWatch.getState() == Thread.State.TERMINATED) {
                                    break;
                                }
                                if (threadToWatch == mUploadThread) {
                                    Log.d(TAG, "UploadThread-waiter still waiting.");
                                    continue;
                                }
                            }
                            break;
                        }
                        Log.d(TAG, "UploadThread done; releasing the wakelock");
                        wakeLock.release();
                        wifiLock.release();
                        onUploadThreadEnded();
                    }
                }.start();
            }
            mCallback.setUploading(true);
            return true;
        }

        @Override
        public boolean pause() throws RemoteException {
            synchronized (UploadService.this) {
                if (mUploadThread != null) {
                    stopUploadThread();
                    return true;
                }
                return false;
            }
        }

        @Override
        public int queueSize() throws RemoteException {
            synchronized (UploadService.this) {
                return mQueueList.size();
            }
        }

        @Override
        public void stopEverything() throws RemoteException {
            synchronized (UploadService.this) {
                mNotificationManager.cancel(NOTIFY_ID_UPLOADING);
                mFileBytesRemain.clear();
                mQueueList.clear();
                mLastUploadStatusText = "Stopped";
                mBytesInFlight = 0;
                mFilesInFlight = 0;
                mBytesTotal = 0;
                mBytesUploaded = 0;
                mFilesTotal = 0;
                mFilesUploaded = 0;
                stopUploadThread(); // recursive lock: okay
            }
            broadcastAllState();
        }

        @Override
        public void setBackgroundWatchersEnabled(boolean enabled) throws RemoteException {
            if (enabled) {
                startUploadService();
                UploadService.this.stopBackgroundWatchers();
                UploadService.this.startBackgroundWatchers();
            } else {
                UploadService.this.stopBackgroundWatchers();
                stopServiceIfEmpty();
            }
        }
    };

    public void onChunkUploaded(CamputChunkUploadedMessage msg) {
        Log.d(TAG, "chunked uploaded for " + msg.queuedFile() + " with size " + msg.size());
        synchronized (UploadService.this) {
            incrBytes(msg.queuedFile(), msg.size());
        }
        broadcastAllState();
    }

    public void onStatReceived(String stat, long value) {
        String v;
        synchronized (UploadService.this) {
            if (stat == null) {
                mStatValue.clear();
            } else {
                mStatValue.put(stat, value);
            }
            StringBuilder sb = new StringBuilder();
            for (Entry<String, Long> ent : mStatValue.entrySet()) {
                sb.append(ent.getKey());
                sb.append(": ");
                sb.append(ent.getValue());
                sb.append("\n");
            }
            v = sb.toString();
            mLastUploadStatsText = v;
        }
        try {
            mCallback.setUploadStatsText(v);
        } catch (RemoteException e) {
        }
    }

    protected void stopUploadThread() {
        synchronized (UploadService.this) {
            mNotificationManager.cancel(NOTIFY_ID_UPLOADING);
            if (mUploadThread != null) {
                mUploadThread.stopUploads();
                mUploadThread = null;
                try {
                    mCallback.setUploading(false);
                } catch (RemoteException e) {
                }
            }
            mUploading = false;
        }
    }

    public void onStatsReceived(CamputStatsMessage msg) {
        synchronized (UploadService.this) {
            mBytesTotal = msg.totalBytes();
            mFilesTotal = (int) msg.totalFiles();
            mBytesUploaded = msg.skippedBytes() + msg.uploadedBytes();
            mFilesUploaded = (int) (msg.skippedFiles() + msg.uploadedFiles());
        }
        broadcastAllState();
    }
}


text:
package org.apache.pulsar.client.admin.internal;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.admin.Worker;
import org.apache.pulsar.client.api.Authentication;
import org.apache.pulsar.common.functions.WorkerInfo;
import org.apache.pulsar.common.policies.data.WorkerFunctionInstanceStats;
import org.apache.pulsar.common.stats.Metrics;

@Slf4j
public class WorkerImpl extends BaseResource implements Worker {

    private final WebTarget workerStats;
    private final WebTarget worker;

    public WorkerImpl(WebTarget web, Authentication auth, long readTimeoutMs) {
        super(auth, readTimeoutMs);
        this.worker = web.path("/admin/v2/worker");
        this.workerStats = web.path("/admin/v2/worker-stats");
    }

    @Override
    public List<WorkerFunctionInstanceStats> getFunctionsStats() throws PulsarAdminException {
        return sync(() -> getFunctionsStatsAsync());
    }

    @Override
    public CompletableFuture<List<WorkerFunctionInstanceStats>> getFunctionsStatsAsync() {
        WebTarget path = workerStats.path("functionsmetrics");
        return asyncGetRequest(path, new GenericType<List<WorkerFunctionInstanceStats>>() {});
    }

    @Override
    public Collection<Metrics> getMetrics() throws PulsarAdminException {
        return sync(() -> getMetricsAsync());
    }

    @Override
    public CompletableFuture<Collection<Metrics>> getMetricsAsync() {
        WebTarget path = workerStats.path("metrics");
        return asyncGetRequest(path, new GenericType<List<Metrics>>() {})
                .thenApply(list -> list);
    }

    @Override
    public List<WorkerInfo> getCluster() throws PulsarAdminException {
        return sync(() -> getClusterAsync());
    }

    @Override
    public CompletableFuture<List<WorkerInfo>> getClusterAsync() {
        WebTarget path = worker.path("cluster");
        return asyncGetRequest(path, new GenericType<List<WorkerInfo>>() {});
    }

    @Override
    public WorkerInfo getClusterLeader() throws PulsarAdminException {
        return sync(() -> getClusterLeaderAsync());
    }

    @Override
    public CompletableFuture<WorkerInfo> getClusterLeaderAsync() {
        WebTarget path = worker.path("cluster").path("leader");
        return asyncGetRequest(path, new GenericType<WorkerInfo>(){});
    }

    @Override
    public Map<String, Collection<String>> getAssignments() throws PulsarAdminException {
        return sync(() -> getAssignmentsAsync());
    }

    @Override
    public CompletableFuture<Map<String, Collection<String>>> getAssignmentsAsync() {
        WebTarget path = worker.path("assignments");
        return asyncGetRequest(path, new GenericType<Map<String, Collection<String>>>() {});
    }

    @Override
    public void rebalance() throws PulsarAdminException {
        sync(this::rebalanceAsync);
    }

    @Override
    public CompletableFuture<Void> rebalanceAsync() {
        final WebTarget path = worker.path("rebalance");
        return asyncPutRequest(path,  Entity.entity("", MediaType.APPLICATION_JSON));
    }
}

redpajama_set_name: RedPajamaGithub


text:
convert icon512.png -resize 96x96 res/drawable-xhdpi/icon.png
convert icon512.png -resize 72x72 res/drawable-hdpi/icon.png
convert icon512.png -resize 48x48 res/drawable-mdpi/icon.png
convert icon512.png -resize 36x36 res/drawable-ldpi/icon.png

#convert pins.png -resize 500x500 res/drawable-xhdpi/pins.png
convert res/drawable-xhdpi/pins.png -resize 375x375 res/drawable-hdpi/pins.png
convert res/drawable-xhdpi/pins.png -resize 250x250 res/drawable-mdpi/pins.png
convert res/drawable-xhdpi/pins.png -resize 180x180 res/drawable-ldpi/pins.png


text:
<?php

// $Id$

class WebServiceRequest {
	/** @var string */
	var $_url;

	/** @var array key value pairs */
	var $_params;

	/** @var string HTTP request method */
	var $_method;

	/**
	 * Constructor
	 */
	function WebServiceRequest($url, $params = array(), $method = 'GET') {
		$this->_url = $url;
		$this->_params = $params;
		$this->_method = $method;
	}

	//
	// Getters and Setters
	//
	/**
	 * Get the web service URL
	 * @return string
	 */
	function getUrl() {
		return $this->_url;
	}

	/**
	 * Set the web service URL
	 * @param $url string
	 */
	function setUrl($url) {
		$this->_url = $url;
	}

	/**
	 * Get the request parameters
	 * @return array
	 */
	function &getParams() {
		return $this->_params;
	}

	/**
	 * Set the request parameters
	 * @param $params array
	 */
	function setParams(&$params) {
		$this->_params =& $params;
	}

	/**
	 * Get the request method
	 * @return string
	 */
	function getMethod() {
		return $this->_method;
	}

	/**
	 * Set the request method
	 * @param $method string
	 */
	function setMethod($method) {
		$this->_method = $method;
	}
}
?>


text:
package nsq

const (
	StateInit = iota
	StateDisconnected
	StateConnected
	StateSubscribed
	// close has started. responses are ok, but no new messages will be sent
	StateClosing
)


text:
var setLed = function(On) {
    var controller = document.getElementById("controller").contentDocument;
    var ledLight = controller.getElementById("pin13led-light");
    ledLight.setAttributeNS(null, 'opacity', On ? '1' : '0');
}

Module["print"] = function(str) {
    console.log(str);

    // HACK: use a custom I/O backend instead, communicate via host-transport
    var tok = str.split(" ");
    if (tok.length > 3 && tok[2].indexOf("::DigitalWrite") !== -1) {
        var pin = tok[5].replace("pin=","").replace(",","");
        pin = parseInt(pin);
        var state = tok[6] === "value=ON";
        if (pin === 13) {
            setLed(state);
        }
    }
}

var onLoad = function() {
    console.log("onload");
    var microflo = require('microflo');

    // From Emscripten
    var runtime = Module['_emscripten_runtime_new']();
    setInterval(function() {
        Module['_emscripten_runtime_run'](runtime);
    }, 100);
}

window.addEventListener('load', onLoad, false);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hysterium emergens Fr.

### Remarks
null


text:
#region License

// Copyright © 2016 Tinkoff Bank
//
// 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.

#endregion

namespace Tinkoff.Acquiring.UI.Model
{
    interface ICardModel
    {
        ICardNumberField Number { get; }
        ICardModelField ExpiryDate { get; }
        ICardModelField SecurityCode { get; }
        PaymentSystem PaymentSystem { get; }
        bool IsValid { get; }
    }
}


text:
package com.action.shejizhichan.chapter12.dynamic;

/**
 * @Description TODO
 * @Author wuyunfeng
 * @Date 2020-05-24 17:31
 * @Version 1.0
 */
public class GamePlayer implements IGamePlayer {
    private String name = "";

    // 构造函数限制谁能创建对象,并同时传递姓名
    public GamePlayer(String name) {

        this.name = name;
    }

    @Override
    public void login(String user, String password) {
        System.out.println("登录名为" + user + "的用户" + this.name + "登录成功!");
    }

    @Override
    public void killBoos() {
        System.out.println(this.name + "在打怪");
    }

    @Override
    public void upgrade() {
        System.out.println(this.name + " 又升了一级");
    }
}


text:
using System;
using System.IO;
using System.Collections;

namespace GuruComponents.CodeEditor.CodeEditor.Syntax
{
	/// <summary>
	/// Language list class
	/// </summary>
	public class LanguageList
	{

		ArrayList mLanguages=null;

		/// <summary>
		///
		/// </summary>
		public LanguageList()
		{
			mLanguages=new ArrayList ();

			string[] files=Directory.GetFiles(".","*.syn");
			foreach (string file in files)
			{
				//try
				//{
					SyntaxLoader l=new SyntaxLoader ();
					mLanguages.Add (l.Load (file));
				//}
				//catch(System.Exception x)
				//{
				//	Console.WriteLine (x.Message);
				//}
			}

		}

        public void Add(Language lang)
        {
            mLanguages.Add(lang);
        }

		/// <summary>
		///
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public Language GetLanguageFromFile(string path)
		{
			string extension= System.IO.Path.GetExtension (path);
			foreach (GuruComponents.CodeEditor.CodeEditor.Syntax.Language lang in mLanguages)
			{
				foreach (GuruComponents.CodeEditor.CodeEditor.Syntax.FileType ft in lang.FileTypes)
				{
					if (extension.ToLower () == ft.Extension.ToLower ())
					{
						return lang;
					}
				}
			}
			return null;
		}

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		public ArrayList ListLanguages()
		{
			return mLanguages ;
		}
	}
}


text:
package com.xzxs.os.dao.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ImageInfoExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public ImageInfoExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andIdIsNull() {
            addCriterion("id is null");
            return (Criteria) this;
        }

        public Criteria andIdIsNotNull() {
            addCriterion("id is not null");
            return (Criteria) this;
        }

        public Criteria andIdEqualTo(Integer value) {
            addCriterion("id =", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotEqualTo(Integer value) {
            addCriterion("id <>", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThan(Integer value) {
            addCriterion("id >", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("id >=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThan(Integer value) {
            addCriterion("id <", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThanOrEqualTo(Integer value) {
            addCriterion("id <=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdIn(List<Integer> values) {
            addCriterion("id in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotIn(List<Integer> values) {
            addCriterion("id not in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdBetween(Integer value1, Integer value2) {
            addCriterion("id between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotBetween(Integer value1, Integer value2) {
            addCriterion("id not between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andImageNameIsNull() {
            addCriterion("image_name is null");
            return (Criteria) this;
        }

        public Criteria andImageNameIsNotNull() {
            addCriterion("image_name is not null");
            return (Criteria) this;
        }

        public Criteria andImageNameEqualTo(String value) {
            addCriterion("image_name =", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameNotEqualTo(String value) {
            addCriterion("image_name <>", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameGreaterThan(String value) {
            addCriterion("image_name >", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameGreaterThanOrEqualTo(String value) {
            addCriterion("image_name >=", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameLessThan(String value) {
            addCriterion("image_name <", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameLessThanOrEqualTo(String value) {
            addCriterion("image_name <=", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameLike(String value) {
            addCriterion("image_name like", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameNotLike(String value) {
            addCriterion("image_name not like", value, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameIn(List<String> values) {
            addCriterion("image_name in", values, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameNotIn(List<String> values) {
            addCriterion("image_name not in", values, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameBetween(String value1, String value2) {
            addCriterion("image_name between", value1, value2, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageNameNotBetween(String value1, String value2) {
            addCriterion("image_name not between", value1, value2, "imageName");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameIsNull() {
            addCriterion("image_originalname is null");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameIsNotNull() {
            addCriterion("image_originalname is not null");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameEqualTo(String value) {
            addCriterion("image_originalname =", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameNotEqualTo(String value) {
            addCriterion("image_originalname <>", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameGreaterThan(String value) {
            addCriterion("image_originalname >", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameGreaterThanOrEqualTo(String value) {
            addCriterion("image_originalname >=", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameLessThan(String value) {
            addCriterion("image_originalname <", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameLessThanOrEqualTo(String value) {
            addCriterion("image_originalname <=", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameLike(String value) {
            addCriterion("image_originalname like", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameNotLike(String value) {
            addCriterion("image_originalname not like", value, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameIn(List<String> values) {
            addCriterion("image_originalname in", values, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameNotIn(List<String> values) {
            addCriterion("image_originalname not in", values, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameBetween(String value1, String value2) {
            addCriterion("image_originalname between", value1, value2, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageOriginalnameNotBetween(String value1, String value2) {
            addCriterion("image_originalname not between", value1, value2, "imageOriginalname");
            return (Criteria) this;
        }

        public Criteria andImageUrlIsNull() {
            addCriterion("image_url is null");
            return (Criteria) this;
        }

        public Criteria andImageUrlIsNotNull() {
            addCriterion("image_url is not null");
            return (Criteria) this;
        }

        public Criteria andImageUrlEqualTo(String value) {
            addCriterion("image_url =", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlNotEqualTo(String value) {
            addCriterion("image_url <>", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlGreaterThan(String value) {
            addCriterion("image_url >", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlGreaterThanOrEqualTo(String value) {
            addCriterion("image_url >=", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlLessThan(String value) {
            addCriterion("image_url <", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlLessThanOrEqualTo(String value) {
            addCriterion("image_url <=", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlLike(String value) {
            addCriterion("image_url like", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlNotLike(String value) {
            addCriterion("image_url not like", value, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlIn(List<String> values) {
            addCriterion("image_url in", values, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlNotIn(List<String> values) {
            addCriterion("image_url not in", values, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlBetween(String value1, String value2) {
            addCriterion("image_url between", value1, value2, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andImageUrlNotBetween(String value1, String value2) {
            addCriterion("image_url not between", value1, value2, "imageUrl");
            return (Criteria) this;
        }

        public Criteria andCreateTimeIsNull() {
            addCriterion("create_time is null");
            return (Criteria) this;
        }

        public Criteria andCreateTimeIsNotNull() {
            addCriterion("create_time is not null");
            return (Criteria) this;
        }

        public Criteria andCreateTimeEqualTo(Date value) {
            addCriterion("create_time =", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeNotEqualTo(Date value) {
            addCriterion("create_time <>", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeGreaterThan(Date value) {
            addCriterion("create_time >", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
            addCriterion("create_time >=", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeLessThan(Date value) {
            addCriterion("create_time <", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
            addCriterion("create_time <=", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeIn(List<Date> values) {
            addCriterion("create_time in", values, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeNotIn(List<Date> values) {
            addCriterion("create_time not in", values, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeBetween(Date value1, Date value2) {
            addCriterion("create_time between", value1, value2, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
            addCriterion("create_time not between", value1, value2, "createTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeIsNull() {
            addCriterion("update_time is null");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeIsNotNull() {
            addCriterion("update_time is not null");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeEqualTo(Date value) {
            addCriterion("update_time =", value, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeNotEqualTo(Date value) {
            addCriterion("update_time <>", value, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeGreaterThan(Date value) {
            addCriterion("update_time >", value, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
            addCriterion("update_time >=", value, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeLessThan(Date value) {
            addCriterion("update_time <", value, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
            addCriterion("update_time <=", value, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeIn(List<Date> values) {
            addCriterion("update_time in", values, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeNotIn(List<Date> values) {
            addCriterion("update_time not in", values, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeBetween(Date value1, Date value2) {
            addCriterion("update_time between", value1, value2, "updateTime");
            return (Criteria) this;
        }

        public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
            addCriterion("update_time not between", value1, value2, "updateTime");
            return (Criteria) this;
        }

        public Criteria andStatusIsNull() {
            addCriterion("status is null");
            return (Criteria) this;
        }

        public Criteria andStatusIsNotNull() {
            addCriterion("status is not null");
            return (Criteria) this;
        }

        public Criteria andStatusEqualTo(Integer value) {
            addCriterion("status =", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusNotEqualTo(Integer value) {
            addCriterion("status <>", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusGreaterThan(Integer value) {
            addCriterion("status >", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusGreaterThanOrEqualTo(Integer value) {
            addCriterion("status >=", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusLessThan(Integer value) {
            addCriterion("status <", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusLessThanOrEqualTo(Integer value) {
            addCriterion("status <=", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusIn(List<Integer> values) {
            addCriterion("status in", values, "status");
            return (Criteria) this;
        }

        public Criteria andStatusNotIn(List<Integer> values) {
            addCriterion("status not in", values, "status");
            return (Criteria) this;
        }

        public Criteria andStatusBetween(Integer value1, Integer value2) {
            addCriterion("status between", value1, value2, "status");
            return (Criteria) this;
        }

        public Criteria andStatusNotBetween(Integer value1, Integer value2) {
            addCriterion("status not between", value1, value2, "status");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}


text:
let hw_init() -> void;

//-------------- JTAG pin i/o ------------------------------------------------//

// control JTAG inputs
let trst( bool out ) -> void;
let tck(  bool out ) -> void;
let tms(  bool out ) -> void;
let tdi(  bool out ) -> void;

// monitor JTAG output
let tdo() -> bool;
let rtck() -> bool;

let constexpr has_tdo = true;
let constexpr has_rtck = false;

//-------------- Debug hw config ---------------------------------------------//

constexpr u32 idcode_mask  = 0x0'ffff'fff;
constexpr u32 idcode_match = 0x0'b944'02f;

// initialization of icepick registers
constexpr u32 icepick_init_regs[] = {
	0x60'002000,  // assert cortex-a8 DBGEN
	0x2c'002100,  // link DAP into chain (takes effect at run)
};

// address of cortex-a8 debug regs on debug APB
constexpr u32 a8_debug = 0x800'01'000;


text:
//Problem 5. Order students
//Using the extension methods OrderBy() and ThenBy() with lambda expressions sort the students by first
//name and last name in descending order.
//Rewrite the same with LINQ.

namespace OrderStudents
{
    using System;
    using System.Linq;

    class LinqQuery
    {
        static void Main()
        {
            var students = new[]
            {
                new {FirstName = "Ivan" , LastName = "Goshov", Age = 15},
                new {FirstName = "Ivan" , LastName = "Penev", Age = 18},
                new {FirstName = "Aleksandur" , LastName = "Malinov", Age = 21},
                new {FirstName = "Gosho" , LastName = "Petkov", Age = 22},
                new {FirstName = "Gancho" , LastName = "Slavov", Age = 12},
                new {FirstName = "Ivan" , LastName = "Aleksiev", Age = 11},
                new {FirstName = "Gancho" , LastName = "Shishkov", Age = 14},
            };
            //With Lambda expression

            //var sorted = students.OrderByDescending(x => x.FirstName).ThenByDescending(y => y.LastName);

            //With Linq

            var sorted =
                from st in students
                orderby st.FirstName descending, st.LastName descending
                select st;

            foreach (var student in sorted)
            {
                Console.WriteLine(student.FirstName + " " + student.LastName);
            }
        }
    }
}


text:
'use strict';

var Node = require('../../lib/registry/Node'),
    NodeSlot = require('../../lib/registry/NodeSlot'),
    inherit = require('inherit'),
    nock = require('nock'),
    sinon = require('sinon'),
    expect = require('must'),
    q = require('q');

describe('registry/Node', function() {
    describe('new Node()', function() {
        describe('state just after creation', function() {
            before(function() {
                this.node = new Node({}, {
                    name: 'test node',
                    description: 'test node description',
                    capabilities: [{
                        seleniumProtocol: 'WebDriver',
                        platform: 'LINUX',
                        browserName: 'firefox',
                        version: '30',
                        maxInstances: 1
                    }],
                    configuration: {
                        host: '127.0.0.1',
                        port: 5590
                    }
                });
            });

            it('getId()', function() {
                expect(this.node.getId()).to.equal('http://127.0.0.1:5590');
            });

            it('getRemoteHost()', function() {
                expect(this.node.getRemoteHost()).to.equal('http://127.0.0.1:5590');
            });

            it('getTotal()', function() {
                expect(this.node.getTotal()).to.equal(1);
            });

            it('getTotalUsed()', function() {
                expect(this.node.getTotalUsed()).to.equal(0);
            });

            it('isBusy()', function() {
                expect(this.node.isBusy()).to.be.false();
            });

            it('isDown()', function() {
                expect(this.node.isDown()).to.be.false();
            });

            it('hasCapability()', function() {
                var caps = {platform: 'LINUX', browserName: 'firefox', version: '30'};
                expect(this.node.hasCapability(caps)).to.be.true();
            });

            it('toJSON()', function() {
                expect(this.node.toJSON()).to.eql({
                    id: 'http://127.0.0.1:5590',
                    name: 'test node',
                    description: 'test node description',
                    capabilities: [{
                        seleniumProtocol: 'WebDriver',
                        platform: 'LINUX',
                        browserName: 'firefox',
                        version: '30',
                        maxInstances: 1
                    }],
                    configuration: {
                        host: '127.0.0.1',
                        port: 5590
                    }
                });
            });
        });

        describe('json validation', function() {
            it('must fail on absent capabilities', function() {
                function create() {
                    return new Node({}, {});
                }
                expect(create).to.throw(Error);
            });

            it('must fail when capabilities property is not an array', function() {
                function create() {
                    return new Node({}, {capabilities: {}});
                }
                expect(create).to.throw(Error);
            });

            it('must fail when capabilities property is an empty array', function() {
                function create() {
                    return new Node({}, {capabilities: []});
                }
                expect(create).to.throw(Error);
            });

            it('must fail when there are no host & port, url or remoteHost properties', function() {
                function create() {
                    return new Node({}, {capabilities: [{}]});
                }
                expect(create).to.throw(Error);
            });
        });

        describe('custom node id', function() {
            before(function() {
                this.node = new Node({}, {
                    id: 'my-node',
                    capabilities: [{
                        seleniumProtocol: 'WebDriver',
                        platform: 'LINUX',
                        browserName: 'firefox',
                        version: '30',
                        maxInstances: 1
                    }],
                    configuration: {
                        remoteHost: 'http://127.0.0.1:5590'
                    }
                });
            });

            it('getId()', function() {
                expect(this.node.getId()).to.equal('my-node');
            });
        });

        describe('remote host for Selenium RC node version < 2.9', function() {
            before(function() {
                this.node = new Node({}, {
                    capabilities: [{
                        seleniumProtocol: 'Selenium',
                        platform: 'LINUX',
                        browserName: 'firefox',
                        version: '30',
                        maxInstances: 1
                    }],
                    configuration: {
                        url: 'http://127.0.0.1:5590/selenium-server/driver'
                    }
                });
            });

            it('getRemoteHost()', function() {
                expect(this.node.getRemoteHost()).to.equal('http://127.0.0.1:5590');
            });
        });

        describe('remote host for WebDriver node version < 2.9', function() {
            before(function() {
                this.node = new Node({}, {
                    capabilities: [{
                        seleniumProtocol: 'WebDriver',
                        platform: 'LINUX',
                        browserName: 'firefox',
                        version: '30',
                        maxInstances: 1
                    }],
                    configuration: {
                        url: 'http://127.0.0.1:5590/wd/hub'
                    }
                });
            });

            it('getRemoteHost()', function() {
                expect(this.node.getRemoteHost()).to.equal('http://127.0.0.1:5590');
            });
        });

        describe('remote host for WebDriver node version >= 2.9', function() {
            before(function() {
                this.node = new Node({}, {
                    capabilities: [{
                        seleniumProtocol: 'WebDriver',
                        platform: 'LINUX',
                        browserName: 'firefox',
                        version: '30',
                        maxInstances: 1
                    }],
                    configuration: {
                        remoteHost: 'http://127.0.0.1:5590'
                    }
                });
            });

            it('getRemoteHost()', function() {
                expect(this.node.getRemoteHost()).to.equal('http://127.0.0.1:5590');
            });
        });
    });

    describe('monitoring', function() {
        before(function() {
            nock.activate();
            this.scope = nock('http://127.0.0.1:5590');
        });

        after(function() {
            delete this.scope;
            nock.restore();
        });

        beforeEach(function() {
            nock.cleanAll();

            this.node = new Node({}, {
                capabilities: [{
                    seleniumProtocol: 'WebDriver',
                    platform: 'LINUX',
                    browserName: 'firefox',
                    version: '30',
                    maxInstances: 1
                }],
                configuration: {
                    host: '127.0.0.1',
                    port: 5590,
                    nodePolling: 100,
                    downPollingLimit: 1,
                    nodeStatusCheckTimeout: 100,
                    unregisterIfStillDownAfter: 0
                }
            });
        });

        describe('isAlive()', function() {
            it('must resolve to true for alive node', function() {
                this.scope
                    .get('/wd/hub/status')
                    .reply(200, {status: 0});

                return this.node.isAlive()
                    .then(function(res) {
                        expect(res).to.be.true();
                    });
            });

            it('must resolve to false for dead node', function() {
                this.scope
                    .get('/wd/hub/status')
                    .socketDelay(110)
                    .reply(200, {status: 0});

                return this.node.isAlive()
                    .then(function(res) {
                        expect(res).to.be.false();
                    });
            });
        });

        describe('monitor()', function() {
            it('must emit down and broken events for dead node', function() {
                this.scope
                    .get('/wd/hub/status')
                    .socketDelay(110)
                    .reply(200, {status: 0});

                var onDown = sinon.spy(),
                    onBroken = sinon.spy();

                this.node.on('down', onDown);
                this.node.on('broken', onBroken);

                return this.node.monitor()
                    .then(function() {
                        expect(onDown.calledOnce).to.be.true();
                        expect(onBroken.calledOnce).to.be.true();
                    });
            });
        });

        describe('integral monitoring tests', function() {
            var registry = {};
            beforeEach('register node', function() {
                this.node.emit('register', registry);
            });

            afterEach('unregister node', function() {
                this.node.emit('unregister', registry);
            });

            it('must check node status during nodePolling interval', function() {
                this.scope
                    .get('/wd/hub/status')
                    .times(5)
                    .reply(200, {status: 0});

                var self = this;
                // magic number 550 = nodePolling*5 + nodePolling/2
                return q.delay(550)
                    .then(function() {
                        return self.scope.done();
                    });
            });

            it('must check node status during nodePolling interval and fail when node stop responding', function() {
                this.scope
                    .get('/wd/hub/status')
                    .times(4)
                    .reply(200, {status: 0})
                    .get('/wd/hub/status')
                    .socketDelay(110)
                    .reply(200, {status: 0});

                var self = this,
                    onDown = sinon.spy(),
                    onBroken = sinon.stub();

                self.node.on('down', onDown);
                self.node.on('broken', function(err) {
                    self.node.emit('unregister', registry);
                    onBroken(err);
                });

                // magic number 600 = nodePolling*6
                return q.delay(600)
                    .then(function() {
                        expect(onDown.calledOnce).to.be.true();
                        expect(onBroken.calledOnce).to.be.true();
                        return self.scope.done();
                    });
            });
        });
    });

    describe('createNewSession()', function() {
        var NodeSlotStub = inherit(NodeSlot, {
                getNewSession: function(req) {
                    if (this.isLocked()) {
                        return null;
                    }
                    this.lock();
                    return new SessionStub(req.sessionId);
                }
            }),
            NodeForTest = inherit(Node, {
                createSlot: function(caps) {
                    return new NodeSlotStub(this, caps);
                }
            });

        beforeEach(function() {
            this.node = new NodeForTest({}, {
                capabilities: [{
                    seleniumProtocol: 'Selenium',
                    platform: 'LINUX',
                    browserName: 'firefox',
                    version: '30',
                    maxInstances: 1
                }],
                configuration: {
                    remoteHost: 'http://127.0.0.1:5590'
                }
            });
        });

        it('must return session', function() {
            return this.node.getNewSession({sessionId: 'my-session'})
                .then(function(session) {
                    expect(session).to.be.not.null();
                    expect(session.getId()).to.equal('my-session');
                });
        });

        it('must return null if there are no free slots', function() {
            var node = this.node;
            return node.getNewSession({sessionId: 'my-session1'})
                .then(function(session) {
                    expect(session).to.be.not.null();
                    expect(session.getId()).to.equal('my-session1');

                    return node.getNewSession({sessionId: 'my-session2'})
                        .then(function(session) {
                            expect(session).to.be.null();
                        });
                });
        });
    });
});

var SessionStub = inherit({
    __constructor: function(id) {
        this.id = id;
    },

    getId: function() {
        return this.id;
    }
});


text:
from org.gluu.model.custom.script.type.scope import DynamicScopeType
from org.gluu.oxauth.service import UserService
from org.gluu.util import StringHelper, ArrayHelper
from java.util import Arrays, ArrayList

import java

class DynamicScope(DynamicScopeType):
    def __init__(self, currentTimeMillis):
        self.currentTimeMillis = currentTimeMillis

    def init(self, configurationAttributes):
        print "Dynamic scope. Initialization"

        print "Dynamic scope. Initialized successfully"

        return True

    def destroy(self, configurationAttributes):
        print "Dynamic scope. Destroy"
        print "Dynamic scope. Destroyed successfully"
        return True

    # Update Json Web token before signing/encrypring it
    #   dynamicScopeContext is org.gluu.oxauth.service.external.context.DynamicScopeExternalContext
    #   configurationAttributes is java.util.Map<String, SimpleCustomProperty>
    def update(self, dynamicScopeContext, configurationAttributes):
        print "Dynamic scope. Update method"

        dynamicScopes = dynamicScopeContext.getDynamicScopes()
        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()
        user = dynamicScopeContext.getUser()
        jsonWebResponse = dynamicScopeContext.getJsonWebResponse()
        claims = jsonWebResponse.getClaims()

        # Add organization name if there is scope = org_name
        claims.setClaim("org_name", "Gluu, Inc.")

        return True

    def getSupportedClaims(self, configurationAttributes):
        return Arrays.asList("org_name")

    def getApiVersion(self):
        return 2


text:
function out = iszero( f )
%ISZERO   Check if a SEPARABLEAPPROX is identically zero on its domain.
%   OUT = ISZERO( F ) return 1 if the SEPARABLEAPPROX is exactly the zero function, and
%   0 otherwise.

% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Get data:
pivots = f.pivotValues;
cols = f.cols;
rows = f.rows;

% Trivial check: If all the pivots are zero, then the SEPARABLEAPPROX is zero:
if ( norm(1./pivots, inf) == 0 )
    out = 1;
    return
end

% Quick check: Evaluate on a meshgrid. If the matrix is nonzero then the
% SEPARABLEAPPROX is nonzero.
dom = f.domain;
x = linspace(dom(1), dom(2), 10);
y = linspace(dom(3), dom(4), 10);
vals = fevalm(f, x, y);
if ( norm( vals, inf ) > 0 )
   out = 0;
   return
end

% Slower check: A pivot may be positive, but the columns or rows may be zero:
rk = length( pivots );
out_cols = zeros( length( pivots ), 1 );
out_rows = zeros( length( pivots ), 1 );
for j = 1:rk
    out_cols( j ) = iszero( cols(:, j) );
    out_rows( j ) = iszero( rows(:, j) );
end
bolslices = ( all(out_cols) || all(out_rows) );
out = bolslices;

end


text:
/**
 * WOW関連<br/>
 */
@RequestMapping(value = "/wow")
package cn.clxy.ssm.wow;

import org.springframework.web.bind.annotation.RequestMapping;


text:
<?php

namespace Craft\LocationBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use FOS\CommentBundle\Document\Thread as BaseThread;

/**
 * @MongoDB\Document
 * @MongoDB\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 */
class Thread extends BaseThread
{

}


text:
[![Build Status](https://travis-ci.org/SEDARI/UPFROnt.svg?branch=master)](https://travis-ci.org/SEDARI/UPFROnt) [![Dependency Status](https://david-dm.org/SEDARI/UPFROnt.svg)](https://david-dm.org/SEDARI/UPFROnt)
# UPFROnt - ULock Policy FRamewOrk

## Installation

After cloning the repository run

```
npm install
```

In the example folder, we show the usage of the most important methods from PDP, PAP, and PEP


text:
package com.oneops.controller.workflow;

import static com.oneops.cms.dj.service.CmsDpmtProcessor.DPMT_STATE_ACTIVE;
import static com.oneops.cms.dj.service.CmsDpmtProcessor.DPMT_STATE_COMPLETE;
import static com.oneops.cms.dj.service.CmsDpmtProcessor.DPMT_STATE_FAILED;
import static com.oneops.cms.dj.service.CmsDpmtProcessor.DPMT_STATE_PAUSED;
import static com.oneops.cms.dj.service.CmsDpmtProcessor.DPMT_STATE_PENDING;
import static com.oneops.controller.cms.CMSClient.COMPLETE;
import static com.oneops.controller.cms.CMSClient.FAILED;
import static com.oneops.controller.cms.CMSClient.INPROGRESS;
import static com.oneops.controller.cms.CMSClient.ONEOPS_SYSTEM_USER;
import static com.oneops.controller.workflow.ExecutionType.DEPLOYMENT;

import com.oneops.cms.dj.domain.CmsDeployment;
import com.oneops.cms.dj.domain.CmsDpmtRecord;
import com.oneops.cms.dj.service.CmsDpmtProcessor;
import com.oneops.cms.domain.CmsWorkOrderSimpleBase;
import com.oneops.cms.exceptions.CmsBaseException;
import com.oneops.cms.simple.domain.CmsWorkOrderSimple;
import com.oneops.cms.util.CmsConstants;
import com.oneops.controller.cms.CMSClient;
import com.oneops.workflow.WorkflowMessage;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.JMSException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Deployer executes the deployment workflow from the deployment plan, the important aspects of this
 * workflow include

dispatching workorders to inductor queue

handling response
 * from inductor

proceeding to next step after converge

updating deployment
 * state

 */
@Component(value = "deployerImpl")
public class DeployerImpl extends Execution<CmsWorkOrderSimple> implements Deployer {

  @Value("${oo.controller.wo.assembler.pool.size:10}")
  private int woAssemblerPoolSize;

  @Value("${oo.controller.wo.async.threshold:300}")
  private int woAsyncDispatchThreshold;

  @Autowired
  private WoDispatcher woDispatcher;

  @Autowired
  private CmsDpmtProcessor dpmtProcessor;

  @Autowired
  private CMSClient cmsClient;

  private ThreadPoolExecutor woDispatchExecutor;

  static Logger logger = Logger.getLogger(DeployerImpl.class);

  @PostConstruct
  public void init() {
    woDispatchExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(woAssemblerPoolSize);
  }

  @Override
  @Transactional
  public DeploymentContext deploy(CmsDeployment dpmt) {
    DeploymentContext context = null;
    logger.info("Deployer started for dpmt : " + dpmt.getDeploymentId());
    if (!isComplete(dpmt)) {
      cmsClient.updateDeploymentAndNotify(dpmt, null, "Deployer");
    }
    if (isActive(dpmt)) {
      context = processWorkOrders(dpmt.getDeploymentId());
    }
    else {
        logger.info("deployment " + dpmt.getDeploymentId() + " is not active");
    }
    if (context == null) {
      context = new DeploymentContext(dpmt);
    }
    return context;
  }

  @Override
  @Transactional
  public DeploymentContext processWorkflow(WorkflowMessage wfMessage) {
    return processWorkOrders(wfMessage.getExecutionId());
  }

  DeploymentContext processWorkOrders(long dpmtId) {
    DeploymentContext dpmtContext = pendingWorkOrders(dpmtId);
    if (!dpmtContext.completed && dpmtContext.woList != null && !dpmtContext.woList.isEmpty()) {
      dispatchWorkOrders(dpmtContext);
    }
    return dpmtContext;
  }

  /**
   * retrieves pending workorders to be dispatched for the deployment by acquiring lock on dpmtId,
   * uses a separate executor for assembling and sending workorders
   *
   * Updates the deployment state in these cases 1. sets state to paused if we reach a step where
   * auto pause is enabled 2. sets state to complete/failed if all workorders are finished
   *
   * @param dpmtId deployment id
   */
  private DeploymentContext pendingWorkOrders(long dpmtId) {
    logger.info("pendingWorkOrders for deployment " + dpmtId);
    DeploymentContext context = getContext(dpmtId);
    CmsDeployment deployment = context.dpmt;
    if (isActive(deployment)) {
      pendingOrders(context);
    }
    return context;
  }

  protected DeploymentContext getContext(long dpmtId) {
    CmsDeployment deployment = dpmtProcessor.getDeployment(dpmtId);
    return new DeploymentContext(deployment);
  }

  @Override
  protected List<CmsWorkOrderSimple> getOrdersForStep(ExecutionContext context, int step) {
    return cmsClient.getWorkOrderIdsNoLimit(deployment(context), step);
  }

  private CmsDeployment deployment(ExecutionContext context) {
    return ((DeploymentContext) context).dpmt;
  }

  @Override
  protected void updateExecutionWithStep(ExecutionContext context, int newStep, List<CmsWorkOrderSimple> list) {
    CmsDeployment dpmt = deployment(context);
    logger.info("updating deployment " + dpmt.getDeploymentId() + " with current step " + newStep);
    if (dpmt.getCurrentStep() != newStep) {
      dpmt.setCurrentStep(newStep);
      dpmtProcessor.updateDeploymentStep(dpmt);
    }
    if (list != null && !list.isEmpty()) {
      dpmtProcessor.createDeploymentExec(dpmt.getDeploymentId(), newStep, INPROGRESS);
    }
    ((DeploymentContext)context).woList = list;
  }

  @Override
  protected void finishExecution(ExecutionContext context) {
    CmsDeployment dpmt = deployment(context);
    if (isActive(dpmt)) {
      cmsClient.updateDpmtState(dpmt, DPMT_STATE_COMPLETE);
    }
  }

  @Override
  protected boolean needsAutoPause(ExecutionContext context, int step) {
    CmsDeployment dpmt = deployment(context);
    Set<Integer> autoPauseExecOrders = dpmt.getAutoPauseExecOrders();
    return (autoPauseExecOrders != null && autoPauseExecOrders.contains(step));
  }

  @Override
  protected void autoPause(ExecutionContext context, int step) {
    CmsDeployment dpmt = deployment(context);
    updateExecutionWithStep(context, step, null);
    dpmt.setDeploymentState(DPMT_STATE_PAUSED);
    dpmt.setCurrentStep(step);
    dpmt.setUpdatedBy(ONEOPS_SYSTEM_USER);
    dpmt.setComments("deployment paused at step " + step + " on " + new Date());
    try {
      dpmtProcessor.updateDeployment(dpmt);
    } catch (CmsBaseException e) {
      logger.error("CmsBaseException in autoPauseIfRequired", e);
      throw e;
    }
  }

  private boolean isActive(CmsDeployment dpmt) {
    return (dpmt != null) && DPMT_STATE_ACTIVE.equals(dpmt.getDeploymentState());
  }

  private boolean isComplete(CmsDeployment dpmt) {
    return (dpmt != null) && DPMT_STATE_COMPLETE.equals(dpmt.getDeploymentState());
  }

  private boolean isPending(CmsDpmtRecord dpmtRecord) {
    return (dpmtRecord != null) && DPMT_STATE_PENDING.equals(dpmtRecord.getDpmtRecordState());
  }

  private void dispatchWorkOrders(DeploymentContext context) {
    CmsDeployment dpmt = context.dpmt;
    logger.info("dispatching wos - dpmtId : " + dpmt.getDeploymentId() + ", step " + dpmt.getCurrentStep() + " wo size " + context.woList);
    dispatchOrders(context, context.woList);
  }

  private void dispatchOrders(DeploymentContext context, List<CmsWorkOrderSimple> ordersList) {
    CountDownLatch latch = new CountDownLatch(ordersList.size());
    ordersList.forEach(o -> {
      dispatch(context, o, latch);
    });
    context.latch = latch;
  }

  @Override
  protected void dispatch(ExecutionContext context, CmsWorkOrderSimple wo, CountDownLatch latch) {
    woDispatchExecutor.submit(() -> assembleAndDispatchAsync(context, wo, latch));
  }

  private void assembleAndDispatchAsync(ExecutionContext context, CmsWorkOrderSimple wo, CountDownLatch latch) {
    CmsDeployment dpmt = deployment(context);
    WorkOrderContext woContext = new WorkOrderContext(wo, dpmt.getCurrentStep());
    CmsDpmtRecord dpmtRecord = dpmtProcessor.getDeploymentRecord(wo.getDpmtRecordId());
    if (isPending(dpmtRecord)) {
      logger.info(">>>>>>>>>>> dispatching workorder dpmtId : " + dpmt.getDeploymentId() + " rfc : "
          + dpmtRecord.getRfcId());
      woDispatcher.dispatchAndUpdate(dpmt, woContext);
    } else {
      logger.info(
          "workorder not in pending state dpmtId : " + dpmt.getDeploymentId() + " rfcId : " + wo
              .getRfcId() + " state : " + dpmtRecord.getDpmtRecordState());
    }
    latch.countDown();
  }

  /**
   * updates wo state based on inductor response, if the state is successful the rfc would be
   * promoted to ci, also checks if we need to move to next step
   */
  @Override
  @Transactional
  public void handleInductorResponse(CmsWorkOrderSimpleBase wo, Map<String, Object> params) {
    CmsWorkOrderSimple woResponse = (CmsWorkOrderSimple) wo;
    long dpmtId = woResponse.getDeploymentId();
    long rfcId = woResponse.getRfcId();
    String logPrefix = "dpmtId " + dpmtId + " rfc " + rfcId;
    logger.info(logPrefix + "<<<<<<<<<<< deployer handle inductor response");

    updateWoState(dpmtId, woResponse, params);
    logger.info(logPrefix + "ci updated from inductor response");

    logger.info(logPrefix + " inductor response processing finished");
  }

  @Override
  @Transactional
  public void convergeIfNeeded(CmsWorkOrderSimpleBase wo) throws JMSException {
    CmsWorkOrderSimple woResponse = (CmsWorkOrderSimple) wo;
    long dpmtId = woResponse.getDeploymentId();
    long rfcId = woResponse.getRfcId();
    int step = woResponse.rfcCi.getExecOrder();
    if (canConverge(dpmtId, rfcId, step)) {
      //send a jms message to controller.workflow queue to proceed to next step
      logger.info("dpmtId " + dpmtId + " rfc " + rfcId + ": inductor response converging to next step");
      sendMessageToProceed(DEPLOYMENT.getName(), dpmtId);
    }
  }

  /**
   * checks if step converge can happen [no workorders in pending/in-progress state for this step].
   */
  private boolean canConverge(long dpmtId, long rfcId, int step) {
    long startTs = System.currentTimeMillis();
    String logPrefix = "dpmtId:" + dpmtId + " step:" + step + " rfc:" + rfcId + " :: ";
    boolean canConverge = false;
    Map<String, Integer> woCountMap = dpmtProcessor.getWorkordersCountByState(dpmtId, step);
    logger.info(logPrefix + "workorders state count: " + woCountMap);
    if (anyPendingOrActiveOrder(woCountMap)) {
      logger.info(logPrefix + "can't converge as there are some workorders in pending/active state");
    }
    else {
      int updated = 0;
      if (anyFailed(woCountMap)) {
        logger.info(logPrefix + "trying to update step as failed");
        updated = dpmtProcessor.getAndUpdateStepState(dpmtId, step, FAILED);
        if (updated > 0) {
          CmsDeployment deployment = dpmtProcessor.getDeployment(dpmtId);
          if (!deployment.getContinueOnFailure()) {
            deployment.setDeploymentState(DPMT_STATE_FAILED);
            //if any of the wo has failed then update the deployment to failed
            dpmtProcessor.updateDeployment(deployment);
          }
          else {
            canConverge = true;
          }
        }
      }
      else if (!anyCancelled(woCountMap)) {
        logger.info(logPrefix + "trying to update step as complete");
        updated = dpmtProcessor.getAndUpdateStepState(dpmtId, step, COMPLETE);
        canConverge = updated > 0;
      }
      logger.info(logPrefix + "getAndUpdateStepState updated count " + updated);
    }
    logger.info(logPrefix + "canConverge took " + timeElapsed(startTs) + " ms");
    return canConverge;
  }

  public void updateWoState(long dpmtId, CmsWorkOrderSimple woResponse,
      Map<String, Object> params) {
    CmsDeployment dpmt = dpmtProcessor.getDeployment(dpmtId);
    String state = (String) params.get(CmsConstants.WORK_ORDER_STATE);
    logger.info(
        "updating workorder state dpmt " + dpmtId + " rfc " + woResponse.getRfcId() + " state "
            + state);
    cmsClient.updateWoState(dpmt, woResponse, state, null);
  }

  @PreDestroy
  public void destroy() {
    woDispatchExecutor.shutdown();
  }

  @Override
  protected String getType() {
    return DEPLOYMENT.getName();
  }

  public void setWoDispatcher(WoDispatcher woDispatcher) {
    this.woDispatcher = woDispatcher;
  }

  public void setDpmtProcessor(CmsDpmtProcessor dpmtProcessor) {
    this.dpmtProcessor = dpmtProcessor;
  }

  public void setCmsClient(CMSClient cmsClient) {
    this.cmsClient = cmsClient;
  }

  public void setWoDispatchExecutor(ThreadPoolExecutor woDispatchExecutor) {
    this.woDispatchExecutor = woDispatchExecutor;
  }

  public void setWoAssemblerPoolSize(int woAssemblerPoolSize) {
    this.woAssemblerPoolSize = woAssemblerPoolSize;
  }

  public void setWoAsyncDispatchThreshold(int woAsyncDispatchThreshold) {
    this.woAsyncDispatchThreshold = woAsyncDispatchThreshold;
  }

}


text:
.class public final Lq;
.super Ljava/lang/Object;

# interfaces
.implements Ljava/lang/Runnable;

# instance fields
.field final synthetic a:I

# direct methods
.method public constructor <init>(I)V
    .registers 2

    iput p1, p0, Lq;->a:I

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .registers 7

    iget v0, p0, Lq;->a:I

    invoke-static {v0}, Lcom/bugsense/trace/models/PingsMechanism;->getFlatLine(I)Ljava/lang/String;

    move-result-object v1

    const-string v0, "Ping_"

    iget v2, p0, Lq;->a:I

    const/4 v3, 0x1

    if-ne v2, v3, :cond_f

    const-string v0, "Gnip_"

    :cond_f
    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v2

    invoke-static {v2, v3}, Ljava/lang/String;->valueOf(J)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v2, "-"

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    new-instance v2, Ljava/util/Random;

    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v3

    invoke-direct {v2, v3, v4}, Ljava/util/Random;-><init>(J)V

    const v3, 0x1869f

    invoke-virtual {v2, v3}, Ljava/util/Random;->nextInt(I)I

    move-result v2

    invoke-static {v2}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    :try_start_46
    new-instance v2, Ljava/io/BufferedWriter;

    new-instance v3, Ljava/io/FileWriter;

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    sget-object v5, Lcom/bugsense/trace/G;->FILES_PATH:Ljava/lang/String;

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "/"

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-direct {v3, v0}, Ljava/io/FileWriter;-><init>(Ljava/lang/String;)V

    invoke-direct {v2, v3}, Ljava/io/BufferedWriter;-><init>(Ljava/io/Writer;)V

    invoke-virtual {v2, v1}, Ljava/io/BufferedWriter;->write(Ljava/lang/String;)V

    invoke-virtual {v2}, Ljava/io/BufferedWriter;->flush()V

    invoke-virtual {v2}, Ljava/io/BufferedWriter;->close()V
    :try_end_72
    .catch Ljava/io/IOException; {:try_start_46 .. :try_end_72} :catch_73

    :cond_72
    :goto_72
    return-void

    :catch_73
    move-exception v0

    sget-object v1, Lcom/bugsense/trace/G;->TAG:Ljava/lang/String;

    const-string v2, "Error saving ping data"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    sget-boolean v1, Lcom/bugsense/trace/BugSenseHandler;->I_WANT_TO_DEBUG:Z

    if-eqz v1, :cond_72

    invoke-virtual {v0}, Ljava/io/IOException;->printStackTrace()V

    goto :goto_72
.end method


text:
<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Parametros;
use app\models\Horarios;
use mPDF;
use kartik\mpdf\Pdf;
use app\classes\Security;

class PruebasController extends Controller
{
    public function actionPrueba1(){
        return $this->renderPartial('header');
    }
    public function actionPrueba2(){
        Yii::$app->session->set('variable','variableeeeeee');
    }

    public function actionRestartParametros(){

        $data = Parametros::find()->asArray()->indexBy('codigo_parametro')->all();

        Yii::$app->cache->set('parametros', $data);

        var_dump($data);
    }

    public function actionCreatepdf(){
        $mpdf=new mPDF();
        $mpdf->mPDF('utf-8','A4','','','15','15','40','18');
        $mpdf->SetHTMLHeader($this->renderPartial('header'));
        $mpdf->WriteHTML($this->renderPartial('pdf'));
        $mpdf->AddPage();
        $mpdf->WriteHTML($this->renderPartial('pdf'));
        $mpdf->Output();
        exit;
                //return $this->renderPartial('mpdf');
    }

    public function actionSamplePdf() {
        $mpdf = new mPDF;
        $mpdf->WriteHTML('Hallo World');

        $mpdf->Output();
        exit;
    }
    public function actionForceDownloadPdf(){
        $mpdf=new mPDF();
        $mpdf->WriteHTML($this->renderPartial('mpdf'));
        $mpdf->Output('MyPDF.pdf', 'D');
        exit;
    }

    public function actionTestEncryption(){
        $encrypt = Security::getInstance()->encrypt('juancho');
        $decrypt = Security::getInstance()->decrypt($encrypt);

        echo $encrypt. " " .$decrypt;

        return $this->render('estudiantes');
    }

    public function actionTestdata(){
        $request = Yii::$app->request;
        print_r($request->get());
    }
}