text:
package com.recitor.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.app.R;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by KLD on 3/26/15.
 */
public class TestDownload extends Activity implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener
{
    MediaPlayer mediaPlayer;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_download_mp3);
    }

    public void download(View v)
    {
        String[] targets = {"http://server12.mp3quran.net/bari/001.mp3","/sdcard/quran/bari001.mp3"};

        // execute this when the downloader must be fired
        final DownloadTask downloadTask = new DownloadTask(this);
        downloadTask.execute(targets);

       /* mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface dialog)
            {
                downloadTask.cancel(true);
            }

        });*/

    }

    public void playd(View v)
    {
        try
        {
        MediaPlayer mp = new MediaPlayer();

            FileDescriptor fd = new FileDescriptor();
            File baseDir = Environment.getExternalStorageDirectory();
            //String audioPath = baseDir.getAbsolutePath() + "/sdcard/bari001.mp3";

            FileInputStream fis = new FileInputStream("/sdcard/quran/bari001.mp3");
            fd = fis.getFD();
       // String filePath = "/sdcard/bari001.mp3";
        //mp = new  MediaPlayer();

        //mp.setDataSource(filePath);
        //mp.prepare();
       // int resID = this.getResources().getIdentifier("sample_test","raw",this.getPackageName());

        //mp = MediaPlayer.create(this, resID);
                /*
            if(mp==null)
                Toast.makeText(this, "it's null", Toast.LENGTH_LONG);

            if(!mp.isPlaying())
                Toast.makeText(this, "not plying", Toast.LENGTH_LONG);
                */

        mp.setDataSource(fd);
        mp.prepare();
        mp.start();
        Log.v("MAIN", "WEED");
    }
    catch (Exception e)
    {
        Log.v("MAIN", "error:"+e.toString());
    }

}

    public void stream(View v)
    {

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        try {
            mediaPlayer.setDataSource("http://server12.mp3quran.net/bari/001.mp3");
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.prepare(); // might take long! (for buffering, etc)   //@@
            mediaPlayer.prepareAsync();
        } catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        } catch (SecurityException e)
        {
            e.printStackTrace();
        } catch (IllegalStateException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    public void stop(View v)
    {
        if(mediaPlayer!=null)
        {
            if(mediaPlayer.isPlaying())
                mediaPlayer.stop();
        }
    }

    public void onPrepared(MediaPlayer mediaplayer)
    {
        if(!mediaPlayer.isPlaying()){
            mediaPlayer.start();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer)
    {
       /* //mediaPlayer.reset();
        songProgressBar.setProgress(0);
        songProgressBar.setSecondaryProgress(0);
        play.setVisibility(View.VISIBLE);
        stop.setVisibility(View.GONE);
        link = "http://server11.mp3quran.net/hawashi/002.mp3";
        playMp3(link);*/
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent)
    {
        //songProgressBar.setSecondaryProgress(percent);
/*
        if(percent==100)
        {
            Progressbar.setVisibility(View.INVISIBLE);

        }else if(percent > songProgressBar.getProgress())
        {
            Progressbar.setVisibility(View.INVISIBLE);
        }else
        {
            Progressbar.setVisibility(View.VISIBLE);
        }
        */
    }

}

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    ProgressDialog mProgressDialog;

    public DownloadTask(Context context)
    {
        this.context = context;
        // instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("A message");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface dialog)
            {
                DownloadTask.this.cancel(true);
            }
        });
    }

    @Override
    protected String doInBackground(String... sUrl)
    {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try
        {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            File dir = new File("sdcard/quran");

            if(!dir.exists())
            {
                dir.mkdir();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream(sUrl[1]);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1)
            {
                // allow canceling with back button
                if (isCancelled())
                {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        }
        catch (Exception e)
        {
            return e.toString();
        }
        finally
        {
            try
            {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            }
            catch (IOException ignored)
            {
                Log.v("TestDownload","IOException");
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress)
    {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result)
    {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    }

}
   // The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate and onPreExecute run on the UI thread, so there you can change the progress bar:
/*
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    }

*/


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="up" title="FatFs" href="../00index_e.html">
<link rel="stylesheet" href="../css_e.css" type="text/css" media="screen" title="ELM Default">
<title>FatFs - f_forward</title>

f_forward

The f_forward function reads the file data and forward it to the data streaming device.

FRESULT f_forward (
  FIL* FileObject,                 /* File object */
  UINT (*Func)(const BYTE*,UINT),  /* Data streaming function */
  UINT ByteToFwd,                  /* Number of bytes to forward */
  UINT* ByteFwd                    /* Number of bytes forwarded */
);

Parameters

FileObject

Pointer to the open file object.

Func

Pointer to the user-defined data streaming function. For details, refer to the sample code.

ByteToFwd

Number of bytes to forward in range of UINT.

ByteFwd

Pointer to the UINT variable to return number of bytes forwarded.

Return Values

FR_OK (0)

The function succeeded.

FR_DENIED

The function denied due to the file has been opened in non-read mode.

FR_DISK_ERR

The function failed due to an error in the disk function.

FR_INT_ERR

The function failed due to a wrong FAT structure or an internal error.

FR_NOT_READY

The disk drive cannot work due to no medium in the drive or any other reason.

FR_INVALID_OBJECT

The file object is invalid.

Description

The f_forward function reads the data from the file and forward it to the outgoing stream without data buffer. This is suitable for small memory system because it does not require any data buffer at application module. The file pointer of the file object increases in number of bytes forwarded. In case of <tt>*ByteFwd < ByteToFwd</tt> without error, it means the requested bytes could not be transferred due to end of file or stream goes busy during data transfer.

This function is available on <tt>_USE_FORWARD == 1</tt> and <tt>_FS_TINY == 1</tt>.

Example (Audio playback)

/*-----------------------------------------------------------------------*/
/* Sample code of data transfer function to be called from f_forward     */
/*-----------------------------------------------------------------------*/

UINT out_stream (   /* Returns number of bytes sent or stream status */
    const BYTE *p,  /* Pointer to the data block to be sent */
    UINT btf        /* >0: Transfer call (Number of bytes to be sent). 0: Sense call */
)
{
    UINT cnt = 0;

    if (btf == 0) {     /* Sense call */
        /* Return stream status (0: Busy, 1: Ready) */
        /* When once it returned ready to sense call, it must accept a byte at least */
        /* at subsequent transfer call, or f_forward will fail with FR_INT_ERROR. */
        if (FIFO_READY) cnt = 1;
    }
    else {              /* Transfer call */
        do {    /* Repeat while there is any data to be sent and the stream is ready */
            FIFO_PORT = *p++;
            cnt++;
        } while (cnt < btf && FIFO_READY);
    }

    return cnt;
}

/*-----------------------------------------------------------------------*/
/* Sample code using f_forward function                                  */
/*-----------------------------------------------------------------------*/

FRESULT play_file (
    char *fn        /* Pointer to the audio file name to be played */
)
{
    FRESULT rc;
    FIL fil;
    UINT dmy;

    /* Open the audio file in read only mode */
    rc = f_open(&fil, fn, FA_READ);

    /* Repeat until the file pointer reaches end of the file */
    while (rc == FR_OK && fil.fptr < fil.fsize) {

        /* any other processes... */

        /* Fill output stream periodicaly or on-demand */
        rc = f_forward(&fil, out_stream, 1000, &dmy);
    }

    /* The read-only file object may be discarded without close */
    return rc;
}

References

<tt>f_open, fgets, f_write, f_close, FIL</tt>

Return

redpajama_set_name: RedPajamaGithub


text:
<meta charset="UTF-8">
<title>RoomsGroup.createRoomButton - core</title>
<link rel="stylesheet" href="..\..\..\style.css">

core / com.erikcupal.theblackcatclient.gui / RoomsGroup / createRoomButton

createRoomButton

val createRoomButton: TextButton


text:
/*jslint node: true */
/*global global, module, require*/
'use strict';
var newCallback = require('./../construct/newCallback.js');
/**
 * This internal method is used to retrieve a variable from the global object.
 *
 * @function fetchGlobal
 * @memberof socioscapes
 * @param {string} name - A string that corresponds to a variable in the global object.
 * @return {Object} myGlobal - Returns the corresponding {@link ScapeObject} or undefined.
 */
function fetchGlobal(name) {
    var callback = newCallback(arguments),
        myGlobal;
    if (window) {
        myGlobal = window[name];
    } else if (global) {
        myGlobal = global[name];
    }
    callback(myGlobal);
    return myGlobal;
}
module.exports = fetchGlobal;


text:
PHP albaraam/php-gcm-apns library Change Log
===============================================

1.0.0 December 3, 2015
-------------------------

- Initial release.


text:
#ifndef __RTW_BTCOEX_H__
#define __RTW_BTCOEX_H__

#include <drv_types.h>

#define	PACKET_NORMAL			0
#define	PACKET_DHCP				1
#define	PACKET_ARP				2
#define	PACKET_EAPOL			3

void rtw_btcoex_Initialize(PADAPTER);
void rtw_btcoex_HAL_Initialize(PADAPTER padapter);
void rtw_btcoex_IpsNotify(PADAPTER, u8 type);
void rtw_btcoex_LpsNotify(PADAPTER, u8 type);
void rtw_btcoex_ScanNotify(PADAPTER, u8 type);
void rtw_btcoex_ConnectNotify(PADAPTER, u8 action);
void rtw_btcoex_MediaStatusNotify(PADAPTER, u8 mediaStatus);
void rtw_btcoex_SpecialPacketNotify(PADAPTER, u8 pktType);
void rtw_btcoex_BtInfoNotify(PADAPTER, u8 length, u8 *tmpBuf);
void rtw_btcoex_SuspendNotify(PADAPTER, u8 state);
void rtw_btcoex_HaltNotify(PADAPTER);
void rtw_btcoex_Switch(PADAPTER, u8 enable);
u8 rtw_btcoex_IsBtDisabled(PADAPTER);
void rtw_btcoex_Handler(PADAPTER);
s32 rtw_btcoex_IsBTCoexCtrlAMPDUSize(PADAPTER);
u32 rtw_btcoex_GetAMPDUSize(PADAPTER);
void rtw_btcoex_SetManualControl(PADAPTER, u8 bmanual);
u8 rtw_btcoex_1Ant(PADAPTER);
u8 rtw_btcoex_IsBtControlLps(PADAPTER);
u8 rtw_btcoex_IsLpsOn(PADAPTER);
u8 rtw_btcoex_RpwmVal(PADAPTER);
u8 rtw_btcoex_LpsVal(PADAPTER);
void rtw_btcoex_SetBTCoexist(PADAPTER, u8 bBtExist);
void rtw_btcoex_SetChipType(PADAPTER, u8 chipType);
void rtw_btcoex_SetPGAntNum(PADAPTER, u8 antNum);
u8 rtw_btcoex_GetPGAntNum(PADAPTER);
u32 rtw_btcoex_GetRaMask(PADAPTER);
void rtw_btcoex_RecordPwrMode(PADAPTER, u8 *pCmdBuf, u8 cmdLen);
void rtw_btcoex_DisplayBtCoexInfo(PADAPTER, u8 *pbuf, u32 bufsize);
void rtw_btcoex_SetDBG(PADAPTER, u32 *pDbgModule);
u32 rtw_btcoex_GetDBG(PADAPTER, u8 *pStrBuf, u32 bufSize);
u8 rtw_btcoex_IncreaseScanDeviceNum(PADAPTER);
u8 rtw_btcoex_IsBtLinkExist(PADAPTER);

// ==================================================
// Below Functions are called by BT-Coex
// ==================================================
void rtw_btcoex_RejectApAggregatedPacket(PADAPTER, u8 enable);
void rtw_btcoex_LPS_Enter(PADAPTER);
void rtw_btcoex_LPS_Leave(PADAPTER);

#endif // __RTW_BTCOEX_H__


text:
package com.db2eshop.persistence;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.db2eshop.model.Shipping;
import com.db2eshop.persistence.support.AbstractDao;

/**
 *
ShippingDao class.

 *
 * @author Denis Neuling (denisneuling@gmail.com)
 *
 */
@Repository
public class ShippingDao extends AbstractDao<Shipping> {

	/**
	 *
Constructor for ShippingDao.

	 *
	 * @param sessionFactory a {@link org.hibernate.SessionFactory} object.
	 */
	@Autowired
	public ShippingDao(SessionFactory sessionFactory) {
		super(sessionFactory, Shipping.class);
	}
}


text:
package me.jakemoritz.tasking_new.fragment;

import android.Manifest;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;

import com.google.api.services.tasks.model.Task;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.jakemoritz.tasking_new.R;
import me.jakemoritz.tasking_new.activity.MainActivity;
import me.jakemoritz.tasking_new.activity.MainActivity.PermissionRequired;
import me.jakemoritz.tasking_new.api.tasks.AddTaskResponse;
import me.jakemoritz.tasking_new.api.tasks.DeleteTasksResponse;
import me.jakemoritz.tasking_new.api.tasks.DeleteTasksTask;
import me.jakemoritz.tasking_new.api.tasks.EditTaskResponse;
import me.jakemoritz.tasking_new.api.tasks.EditTaskTask;
import me.jakemoritz.tasking_new.api.tasks.GetTasksResponse;
import me.jakemoritz.tasking_new.api.tasks.GetTasksTask;
import me.jakemoritz.tasking_new.api.tasks.SortTasklistResponse;
import me.jakemoritz.tasking_new.api.tasks.SortTasklistTask;
import me.jakemoritz.tasking_new.database.DatabaseHelper;
import me.jakemoritz.tasking_new.dialog.AddTaskDialogFragment;
import me.jakemoritz.tasking_new.dialog.EditTaskDialogFragment;
import me.jakemoritz.tasking_new.helper.PermissionHelper;
import me.jakemoritz.tasking_new.misc.App;
import me.jakemoritz.tasking_new.misc.CompareTaskDueDate;

public class TaskListFragment extends ListFragment implements GetTasksResponse, AddTaskResponse,
        DeleteTasksResponse, EditTaskResponse, SwipeRefreshLayout.OnRefreshListener, CheckBox.OnCheckedChangeListener,
        SortTasklistResponse, PermissionRequired {

    private static final String TAG = TaskListFragment.class.getSimpleName();

    private MainActivity mainActivity;

    // Views
    private AbsListView mListView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ProgressBar progressBar;

    private TaskAdapter mAdapter;

    // Data
    private List<Task> tasks;
    private SparseBooleanArray idsToDelete;
    private List<Task> savedTaskList;

    public TaskListFragment() {
    }

    public static TaskListFragment newInstance() {
        TaskListFragment taskListFragment = new TaskListFragment();
        taskListFragment.setRetainInstance(true);
        taskListFragment.setHasOptionsMenu(true);
        return taskListFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        tasks = new ArrayList<>();
        mAdapter = new TaskAdapter(getActivity(), this, R.layout.task_list_item, tasks);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tasklist, container, false);

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        swipeRefreshLayout.setOnRefreshListener(this);

        // Set the adapter
        mListView = (AbsListView) view.findViewById(android.R.id.list);
        mListView.setEmptyView(getActivity().findViewById(android.R.id.empty));
        mListView.setAdapter(mAdapter);

        // Set OnItemClickListener so we can be notified on item clicks
        mListView.setLongClickable(true);
        mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
        mListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                final int checkedCount = mListView.getCheckedItemCount();
                mode.setTitle(checkedCount + " Selected");
                mAdapter.toggleSelection(position);
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_delete:
                        SparseBooleanArray selected = mAdapter.getSelectedIds();

                        List<Task> tasksToDelete = new ArrayList<>();
                        for (int i = 0; i < selected.size(); i++) {
                            tasksToDelete.add(mAdapter.getItem(selected.keyAt(i)));
                        }

                        List<Task> tasksToKeep = new ArrayList<>();
                        for (Task task : mAdapter.getTaskList()) {
                            boolean mustKeep = true;
                            for (Task taskToDelete : tasksToDelete) {
                                if (task == taskToDelete) {
                                    mustKeep = false;
                                }
                            }
                            if (mustKeep) {
                                tasksToKeep.add(task);
                            }
                        }

                        onTasksDeleted(selected, mAdapter.getTaskList());

                        mAdapter.clear();
                        mAdapter.addAll(tasksToKeep);
                        mAdapter.notifyDataSetChanged();

                        DatabaseHelper databaseHelper = new DatabaseHelper(App.getInstance());
                        databaseHelper.saveTasksToDb(mAdapter.getTaskList());
                        databaseHelper.close();

                        mode.finish();
                        return true;
                    default:
                        return false;
                }
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                mAdapter.removeSelection();
            }
        });

        // Display active progress bar
        progressBar = (ProgressBar) view.findViewById(R.id.task_load_progress);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(true);

        // Initialize new task FAB
        FloatingActionButton newTaskFab = (FloatingActionButton) view.findViewById(R.id.fab);
        newTaskFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAddTaskDialog();
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        // Checks internet availability to choose task data source
        if (App.getInstance().isNetworkAvailable()) {
            if (PermissionHelper.getInstance().permissionGranted(getActivity(), Manifest.permission.GET_ACCOUNTS)) {
                GetTasksTask getTasksTask = new GetTasksTask(getActivity(), this);
                getTasksTask.execute();
            } else {
                PermissionHelper.getInstance().requestPermission(getActivity(), Manifest.permission.GET_ACCOUNTS);
            }
        } else {
            DatabaseHelper databaseHelper = new DatabaseHelper(App.getInstance());
            List<Task> tasks = databaseHelper.getTasksFromDb();
            databaseHelper.close();

            if (!tasks.isEmpty()) {
                mAdapter.clear();
                mAdapter.addAll(tasks);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void permissionGranted(String action) {
        switch (action) {
            case (PermissionRequired.ACTION_GET):
                GetTasksTask getTasksTask = new GetTasksTask(getActivity(), this);
                getTasksTask.execute();
                break;
            case (PermissionRequired.ACTION_DELETE):
                deleteTasks();
                break;
            case (PermissionRequired.ACTION_SORT):
                sortTasks();
                break;
        }

        this.mainActivity.setPermissionRequired(null, null);
    }

    @Override
    public void onStop() {
        super.onStop();

        DatabaseHelper databaseHelper = new DatabaseHelper(App.getInstance());
        databaseHelper.saveTasksToDb(mAdapter.getTaskList());
        databaseHelper.close();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (mainActivity.getSupportActionBar() != null) {
            mainActivity.getSupportActionBar().setTitle(getString(R.string.app_name));
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mainActivity = (MainActivity) context;
        this.mainActivity.setPermissionRequired(this, PermissionRequired.ACTION_GET);
    }

    @Override
    public void onRefresh() {
        getTasksFromServer();
        swipeRefreshLayout.setRefreshing(true);
    }

    // Task CRUD methods
    private void openAddTaskDialog() {
        AddTaskDialogFragment addTaskDialogFragment = AddTaskDialogFragment.newInstance(this);
        addTaskDialogFragment.show(getFragmentManager(), AddTaskDialogFragment.class.getSimpleName());

        this.mainActivity.setPermissionRequired(addTaskDialogFragment, PermissionRequired.ACTION_ADD);
    }

    private void editTask(int position) {
        Task task = mAdapter.getItem(position);
        EditTaskDialogFragment editTaskDialogFragment = EditTaskDialogFragment.newInstance(this, task);
        editTaskDialogFragment.show(getFragmentManager(), EditTaskDialogFragment.class.getSimpleName());

        this.mainActivity.setPermissionRequired(editTaskDialogFragment, PermissionRequired.ACTION_EDIT);
    }

    private void getTasksFromServer() {
        this.mainActivity.setPermissionRequired(this, PermissionRequired.ACTION_GET);

        if (PermissionHelper.getInstance().permissionGranted(getActivity(), Manifest.permission.GET_ACCOUNTS)) {
            mAdapter.notifyDataSetChanged();

            GetTasksTask getTasksTask = new GetTasksTask(getActivity(), this);
            getTasksTask.execute();
        } else {
            PermissionHelper.getInstance().requestPermission(getActivity(), Manifest.permission.GET_ACCOUNTS);
        }
    }

    private void sortTasks() {
        List<Task> taskList = new ArrayList<>();
        taskList.addAll(mAdapter.getTaskList());

        if (!taskList.isEmpty()) {
            Collections.sort(taskList, new CompareTaskDueDate());

            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();

            SortTasklistTask sortTasklistTask = new SortTasklistTask(getActivity(), this, mAdapter.getTaskList());
            sortTasklistTask.execute();
        }
    }

    private void sortTasksWithPermissionCheck() {
        this.mainActivity.setPermissionRequired(this, PermissionRequired.ACTION_SORT);

        if (PermissionHelper.getInstance().permissionGranted(getActivity(), Manifest.permission.GET_ACCOUNTS)) {
            sortTasks();
        } else {
            PermissionHelper.getInstance().requestPermission(getActivity(), Manifest.permission.GET_ACCOUNTS);
        }
    }

    // Task AsyncTask callbacks
    @Override
    public void tasksReceived(List<Task> taskList) {
        if (taskList != null) {
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();

            DatabaseHelper databaseHelper = new DatabaseHelper(App.getInstance());
            databaseHelper.saveTasksToDb(mAdapter.getTaskList());
            databaseHelper.close();

            // Disable updating views
            progressBar.setVisibility(View.INVISIBLE);
            swipeRefreshLayout.setRefreshing(false);
        }

        this.mainActivity.setPermissionRequired(null, null);
    }

    @Override
    public void taskAdded() {
        getTasksFromServer();
        this.mainActivity.setPermissionRequired(null, null);
    }

    @Override
    public void tasksDeleted() {
        getTasksFromServer();
        this.mainActivity.setPermissionRequired(null, null);
    }

    @Override
    public void taskEdited() {
        getTasksFromServer();
        this.mainActivity.setPermissionRequired(null, null);
    }

    @Override
    public void tasksSorted() {
        getTasksFromServer();
        this.mainActivity.setPermissionRequired(null, null);
    }

    // Handles batch task deletion
    private void onTasksDeleted(SparseBooleanArray mSelectedIds, List<Task> taskList) {
        this.idsToDelete = mSelectedIds.clone();
        this.savedTaskList = taskList;
        this.mainActivity.setPermissionRequired(this, PermissionRequired.ACTION_DELETE);

        if (PermissionHelper.getInstance().permissionGranted(getActivity(), Manifest.permission.GET_ACCOUNTS)) {
            deleteTasks();
        } else {
            PermissionHelper.getInstance().requestPermission(getActivity(), Manifest.permission.GET_ACCOUNTS);
        }
    }

    private void deleteTasks() {
        final TaskListFragment callback = this;

        final List<Task> oldTaskList = new ArrayList<>();
        oldTaskList.addAll(savedTaskList);

        if (getView() != null) {
            Snackbar snackbar = Snackbar.make(getView(), getString(R.string.task_deleted_snackbar_text), Snackbar.LENGTH_LONG);
            snackbar.setAction(getString(R.string.task_deleted_snackbar_undo), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAdapter.clear();
                    mAdapter.addAll(oldTaskList);
                    mAdapter.notifyDataSetChanged();
                }
            });

            // Adds Snackbar dismiss callback to allow user to undo task deletion
            snackbar.addCallback(new Snackbar.Callback() {
                @Override
                public void onDismissed(Snackbar snackbar, int event) {
                    super.onDismissed(snackbar, event);

                    if (event == DISMISS_EVENT_TIMEOUT) {
                        DeleteTasksTask deleteTasksTask = new DeleteTasksTask(getActivity(), callback, idsToDelete);
                        deleteTasksTask.execute();
                    }
                }
            });
            snackbar.show();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_sort) {
            PopupMenu popupMenu = new PopupMenu(getActivity(), getActivity().findViewById(R.id.action_sort));
            popupMenu.inflate(R.menu.sort_popup_menu);
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    sortTasksWithPermissionCheck();
                    return true;
                }
            });
            popupMenu.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        editTask(position);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int position = mListView.getPositionForView(buttonView);
        Task task = tasks.get(position);
        Task newTask = new Task();
        newTask.setId(task.getId());
        newTask.setTitle(task.getTitle());
        newTask.setNotes(task.getNotes());

        if (isChecked) {
            task.setStatus(getString(R.string.task_completed));
            task.setCompleted(task.getDue());
            newTask.setStatus(getString(R.string.task_completed));
            newTask.setDue(task.getDue());
            newTask.setCompleted(task.getDue());
        } else {
            task.setStatus(getString(R.string.task_needs_action));
            task.setDue(task.getCompleted());
            newTask.setStatus(getString(R.string.task_needs_action));
            newTask.setDue(task.getCompleted());
        }

        EditTaskTask editTaskTask = new EditTaskTask(getActivity(), this, newTask);
        editTaskTask.execute();
    }
}


text:
package viewModel

import java.net.URI
import com.thetestpeople.trt.model._
import com.thetestpeople.trt.model.jenkins._
import com.thetestpeople.trt.utils.http.Credentials

object EditableJenkinsConfiguration {

  def apply(fullConfig: FullJenkinsConfiguration): EditableJenkinsConfiguration =
    EditableJenkinsConfiguration(
      credentialsOpt = fullConfig.config.credentialsOpt,
      rerunJobUrlOpt = fullConfig.config.rerunJobUrlOpt,
      authenticationTokenOpt = fullConfig.config.authenticationTokenOpt,
      params = fullConfig.params)

}

case class EditableJenkinsConfiguration(
    credentialsOpt: Option[Credentials],
    rerunJobUrlOpt: Option[URI],
    authenticationTokenOpt: Option[String],
    params: Seq[JenkinsJobParam]) {

  def usernameOpt: Option[String] = credentialsOpt.map(_.username)

  def apiTokenOpt: Option[String] = credentialsOpt.map(_.password)

  def asJenkinsConfiguration =
    FullJenkinsConfiguration(
      config = JenkinsConfiguration(
        usernameOpt = usernameOpt,
        apiTokenOpt = apiTokenOpt,
        rerunJobUrlOpt = rerunJobUrlOpt,
        authenticationTokenOpt = authenticationTokenOpt),
      params = params)

  def duplicateParamNames: Seq[String] = params.groupBy(_.param).filter(_._2.size > 1).map(_._1).toSeq.sorted

}


text:
package com.blazemeter.jmeter.control;

import kg.apc.emulators.TestJMeterUtils;
import org.apache.jmeter.control.GenericController;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.TransactionController;
import org.apache.jmeter.gui.util.PowerTableModel;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.sampler.DebugSampler;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.samplers.SampleListener;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterThread;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.threads.ListenerNotifier;
import org.apache.jmeter.threads.TestCompiler;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jorphan.collections.ListedHashTree;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class WeightedSwitchControllerTest {

    @BeforeClass
    public static void setUpClass()
            throws Exception {
        TestJMeterUtils.createJmeterEnv();
    }

    private static final Logger log = LoggingManager.getLoggerForClass();

    @Test
    public void testGeneric() {
        WeightedSwitchController obj = new WeightedSwitchController();
        obj.addTestElement(getSampler("0"));
        obj.addTestElement(getSampler("1"));
        obj.addTestElement(getSampler("2"));
        obj.addTestElement(getSampler("5"));
        PowerTableModel mdl = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        mdl.addRow(new String[]{"0", "0"});
        mdl.addRow(new String[]{"1", "1"});
        mdl.addRow(new String[]{"2", "2"});
        mdl.addRow(new String[]{"5", "5"});
        obj.setData(mdl);

        for (int n = 0; n < 800; n++) {
            Sampler s = obj.next();
            log.info("Sampler: " + s.getName());
            Assert.assertNotNull(s);
            Assert.assertNull(obj.next());
            Assert.assertNotEquals(s.getName(), "0");
        }
    }

    private DebugSampler getSampler(String s) {
        DebugSampler debugSampler = new DebugSampler();
        debugSampler.setName(s);
        return debugSampler;
    }

    @Test
    public void testComb() {
        long[] sums = new long[]{0L, 0L};
        long[] prio = new long[]{2, 3};
        long[] choices = new long[]{0, 0};
        for (int i = 0; i < 100; i++) {
            // inc counts
            for (int k = 0; k < sums.length; k++) {
                sums[k] += prio[k];
            }

            if (sums[0] >= sums[1]) {
                // 2
                sums[0] -= prio[0];
                choices[0]++;
            } else {
                // 3
                sums[1] -= prio[1];
                choices[1]++;
            }

            // minimize nums
            long min;
            if (sums[0] >= sums[1]) {
                min = sums[1];
            } else {
                min = sums[0];
            }
            for (int z = 0; z < sums.length; z++) {
                sums[z] -= min;
            }

        }
        System.out.print(Arrays.toString(choices));
    }

    @Test
    public void testNestedWSC() throws Exception {
        JMeterContextService.getContext().setVariables(new JMeterVariables());

        TestSampleListener listener = new TestSampleListener();

        // top WSC
        WeightedSwitchController topWSC = new WeightedSwitchController();
        PowerTableModel topPTM = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        topPTM.addRow(new String[]{"wsc1", "2"});
        topPTM.addRow(new String[]{"wsc2", "2"});
        topPTM.addRow(new String[]{"D_#1", "1"});
        topPTM.addRow(new String[]{"D_#2", "1"});
        topWSC.setData(topPTM);

        DebugSampler d1 = new DebugSampler();
        d1.setName("D_#1");
        DebugSampler d2 = new DebugSampler();
        d2.setName("D_#2");

        // first child WSC of top WSC
        WeightedSwitchController childWSC1 = new WeightedSwitchController();
        childWSC1.setName("wsc1");
        PowerTableModel childPTM1 = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        childPTM1.addRow(new String[]{"D1_#1", "1"});
        childPTM1.addRow(new String[]{"D1_#2", "1"});
        childWSC1.setData(childPTM1);

        DebugSampler d1_1 = new DebugSampler();
        d1_1.setName("D1_#1");
        DebugSampler d1_2 = new DebugSampler();
        d1_2.setName("D1_#2");

        // second child WSC of top WSC
        WeightedSwitchController childWSC2 = new WeightedSwitchController();
        childWSC2.setName("wsc2");
        PowerTableModel childPTM2 = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        childPTM2.addRow(new String[]{"D2_#1", "1"});
        childPTM2.addRow(new String[]{"D2_#2", "1"});
        childWSC2.setData(childPTM2);

        DebugSampler d2_1 = new DebugSampler();
        d2_1.setName("D2_#1");
        DebugSampler d2_2 = new DebugSampler();
        d2_2.setName("D2_#2");

        // main loop
        LoopController loop = new LoopController();
        loop.setLoops(6);
        loop.setContinueForever(false);

        // test tree
        ListedHashTree hashTree = new ListedHashTree();
        hashTree.add(loop);
        hashTree.add(loop, topWSC);
        hashTree.add(topWSC, listener);
        hashTree.add(topWSC, childWSC1);
        hashTree.add(childWSC1, d1_1);
        hashTree.add(childWSC1, d1_2);
        hashTree.add(childWSC1, listener);
        hashTree.add(topWSC, childWSC2);
        hashTree.add(childWSC2, d2_1);
        hashTree.add(childWSC2, d2_2);
        hashTree.add(childWSC2, listener);
        hashTree.add(topWSC, d1);
        hashTree.add(topWSC, d2);

        TestCompiler compiler = new TestCompiler(hashTree);
        hashTree.traverse(compiler);

        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setNumThreads(1);

        ListenerNotifier notifier = new ListenerNotifier();

        JMeterThread thread = new JMeterThread(hashTree, threadGroup, notifier);
        thread.setThreadGroup(threadGroup);
        thread.setOnErrorStopThread(true);
        thread.run();

        assertEquals(6, listener.events.size());
        List<String> labels = new ArrayList<>();
        labels.add("D_#1");
        labels.add("D_#2");
        labels.add("D1_#1");
        labels.add("D1_#2");
        labels.add("D2_#1");
        labels.add("D2_#2");
        for (SampleEvent event : listener.events) {
            assertTrue(labels.contains(event.getResult().getSampleLabel()));
        }
    }

    // https://groups.google.com/forum/?hl=ru#!searchin/jmeter-plugins/Weighted$20Switch$20Controller|sort:relevance/jmeter-plugins/P9Nx9OqgWj4/aeC-RaNgCAAJ
    @Test
    public void testNestedSimpleControllers() throws Exception {
        JMeterContextService.getContext().setVariables(new JMeterVariables());

        TestSampleListener listener = new TestSampleListener();

        // top WSC
        WeightedSwitchController topWSC = new WeightedSwitchController();
        PowerTableModel topPTM = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        topPTM.addRow(new String[]{"ex1", "10"});
        topPTM.addRow(new String[]{"ex2", "20"});
        topWSC.setData(topPTM);

        // first child: simple controller
        GenericController ex1 = new GenericController();
        ex1.setName("ex1");
        DebugSampler example1_1 = new DebugSampler();
        example1_1.setName("example1_1");
        DebugSampler example1_2 = new DebugSampler();
        example1_2.setName("example1_2");

        // second child: simple controller
        GenericController ex2 = new GenericController();
        ex2.setName("ex2");
        DebugSampler example2_1 = new DebugSampler();
        example2_1.setName("example2_1");
        DebugSampler example2_2 = new DebugSampler();
        example2_2.setName("example2_2");

        // main loop
        LoopController loop = new LoopController();
        loop.setLoops(60);
        loop.setContinueForever(false);

        // test tree
        ListedHashTree hashTree = new ListedHashTree();
        hashTree.add(loop);
        hashTree.add(loop, topWSC);
        hashTree.add(topWSC, listener);
        hashTree.add(topWSC, ex1);
        hashTree.add(ex1, example1_1);
        hashTree.add(ex1, example1_2);
        hashTree.add(ex1, listener);
        hashTree.add(topWSC, ex2);
        hashTree.add(ex2, example2_1);
        hashTree.add(ex2, example2_2);
        hashTree.add(ex2, listener);

        TestCompiler compiler = new TestCompiler(hashTree);
        hashTree.traverse(compiler);

        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setNumThreads(1);

        ListenerNotifier notifier = new ListenerNotifier();

        JMeterThread thread = new JMeterThread(hashTree, threadGroup, notifier);
        thread.setThreadGroup(threadGroup);
        thread.setOnErrorStopThread(true);
        thread.run();

        Map<String, Integer> totalResults = new HashMap<>();
        for (SampleEvent event : listener.events) {
            String label = event.getResult().getSampleLabel();
            if (totalResults.containsKey(label)) {
                totalResults.put(label, totalResults.get(label) + 1);
            } else {
                totalResults.put(label, 1);
            }
        }

        assertEquals(120, listener.events.size());
        assertEquals(20, (int) totalResults.get("example1_1"));
        assertEquals(20, (int) totalResults.get("example1_2"));
        assertEquals(40, (int) totalResults.get("example2_1"));
        assertEquals(40, (int) totalResults.get("example2_2"));
    }

    @Test
    public void testNestedTransactionControllers() throws Exception {
        JMeterContextService.getContext().setVariables(new JMeterVariables());

        TestSampleListener listener = new TestSampleListener();

        // top WSC
        WeightedSwitchController topWSC = new WeightedSwitchController();
        PowerTableModel topPTM = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        topPTM.addRow(new String[]{"ex1", "10"});
        topPTM.addRow(new String[]{"ex2", "20"});
        topWSC.setData(topPTM);

        // first child: transaction controller
        TransactionController ex1 = new TransactionController();
        ex1.setName("ex1");
        DebugSampler example1_1 = new DebugSampler();
        example1_1.setName("example1_1");
        DebugSampler example1_2 = new DebugSampler();
        example1_2.setName("example1_2");

        // second child: transaction controller
        TransactionController ex2 = new TransactionController();
        ex2.setName("ex2");
        DebugSampler example2_1 = new DebugSampler();
        example2_1.setName("example2_1");
        DebugSampler example2_2 = new DebugSampler();
        example2_2.setName("example2_2");

        // main loop
        LoopController loop = new LoopController();
        loop.setLoops(60);
        loop.setContinueForever(false);

        // test tree
        ListedHashTree hashTree = new ListedHashTree();
        hashTree.add(loop);
        hashTree.add(loop, topWSC);
        hashTree.add(topWSC, listener);
        hashTree.add(topWSC, ex1);
        hashTree.add(ex1, example1_1);
        hashTree.add(ex1, example1_2);
        hashTree.add(ex1, listener);
        hashTree.add(topWSC, ex2);
        hashTree.add(ex2, example2_1);
        hashTree.add(ex2, example2_2);
        hashTree.add(ex2, listener);

        TestCompiler compiler = new TestCompiler(hashTree);
        hashTree.traverse(compiler);

        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setNumThreads(1);

        ListenerNotifier notifier = new ListenerNotifier();

        JMeterThread thread = new JMeterThread(hashTree, threadGroup, notifier);
        thread.setThreadGroup(threadGroup);
        thread.setOnErrorStopThread(true);
        thread.run();

        Map<String, Integer> totalResults = new HashMap<>();
        for (SampleEvent event : listener.events) {
            String label = event.getResult().getSampleLabel();
            if (totalResults.containsKey(label)) {
                totalResults.put(label, totalResults.get(label) + 1);
            } else {
                totalResults.put(label, 1);
            }
        }

        assertEquals(120, listener.events.size());
        assertEquals(20, (int) totalResults.get("example1_1"));
        assertEquals(40, (int) totalResults.get("example2_1"));
        assertEquals(20, (int) totalResults.get("ex1")); // transaction result
        assertEquals(40, (int) totalResults.get("ex2")); // transaction result
    }

    @Test
    public void testNestedDisableController() throws Exception {
        JMeterContextService.getContext().setVariables(new JMeterVariables());

        TestSampleListener listener = new TestSampleListener();

        // top WSC
        WeightedSwitchController topWSC = new WeightedSwitchController();
        PowerTableModel topPTM = new PowerTableModel(new String[]{"name", WeightedSwitchController.WEIGHTS}, new Class[]{String.class, String.class});
        topPTM.addRow(new String[]{"ex1", "10"});
        topPTM.addRow(new String[]{"ex2", "20"});
        topPTM.addRow(new String[]{"ex3", "30"});
        topWSC.setData(topPTM);

        // first child: transaction controller
        TransactionController ex1 = new TransactionController();
        ex1.setName("ex1");
        DebugSampler example1_1 = new DebugSampler();
        example1_1.setName("example1_1");
        DebugSampler example1_2 = new DebugSampler();
        example1_2.setName("example1_2");

        // second child: transaction controller
        TransactionController ex2 = new TransactionController();
        ex2.setName("ex2");
        ex2.setEnabled(false);
        DebugSampler example2_1 = new DebugSampler();
        example2_1.setName("example2_1");
        DebugSampler example2_2 = new DebugSampler();
        example2_2.setName("example2_2");

        // third child: transaction controller
        TransactionController ex3 = new TransactionController();
        ex3.setName("ex3");
        DebugSampler example3_1 = new DebugSampler();
        example3_1.setName("example3_1");
        DebugSampler example3_2 = new DebugSampler();
        example3_2.setName("example3_2");

        // main loop
        LoopController loop = new LoopController();
        loop.setLoops(80);
        loop.setContinueForever(false);

        // test tree
        ListedHashTree hashTree = new ListedHashTree();
        hashTree.add(loop);
        hashTree.add(loop, topWSC);
        hashTree.add(topWSC, listener);
        hashTree.add(topWSC, ex1);
        hashTree.add(ex1, example1_1);
        hashTree.add(ex1, example1_2);
        hashTree.add(ex1, listener);
        hashTree.add(topWSC, ex3);
        hashTree.add(ex3, example3_1);
        hashTree.add(ex3, example3_2);
        hashTree.add(ex3, listener);

        TestCompiler compiler = new TestCompiler(hashTree);
        hashTree.traverse(compiler);

        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setNumThreads(1);

        ListenerNotifier notifier = new ListenerNotifier();

        JMeterThread thread = new JMeterThread(hashTree, threadGroup, notifier);
        thread.setThreadGroup(threadGroup);
        thread.setOnErrorStopThread(true);
        thread.run();

        Map<String, Integer> totalResults = new HashMap<>();
        for (SampleEvent event : listener.events) {
            String label = event.getResult().getSampleLabel();
            if (totalResults.containsKey(label)) {
                totalResults.put(label, totalResults.get(label) + 1);
            } else {
                totalResults.put(label, 1);
            }
        }

        assertEquals(160, listener.events.size());
        assertEquals(20, (int) totalResults.get("example1_1"));
        assertEquals(60, (int) totalResults.get("example3_1"));
        assertEquals(20, (int) totalResults.get("ex1")); // transaction result
        assertEquals(60, (int) totalResults.get("ex3")); // transaction result
    }
    public class TestSampleListener extends ResultCollector implements SampleListener {
        public List<SampleEvent> events = new ArrayList<>();

        @Override
        public void sampleOccurred(SampleEvent e) {
            events.add(e);
        }

        @Override
        public void sampleStarted(SampleEvent e) {
            events.add(e);
        }

        @Override
        public void sampleStopped(SampleEvent e) {
            events.add(e);
        }
    }
}


text: This project has been moved to GitLab: https://gitlab.com/jdesodt/seneca-entity-crud


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>FOCUS_EVENT_RECORD</title>
<meta http-equiv="Content-Type" Content="text/html; charset=Windows-1251">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

FOCUS_EVENT_RECORD

main |
structures |
win32 structures |
INPUT_RECORD

The <dfn>FOCUS_EVENT_RECORD</dfn> structure is used to report focus events in a console
<dfn>INPUT_RECORD</dfn> structure. These events are used internally and should be ignored.

typedef struct _FOCUS_EVENT_RECORD {
    BOOL bSetFocus;
} FOCUS_EVENT_RECORD;

Members

bSetFocus

Reserved.

See also:

INPUT_RECORD


text:
require './spec/spec_helper'

describe Gusteau::Node do
  it "should raise if node yaml doesn't exist" do
    proc { Gusteau::Node.new('spec/nodes/void.yml') }.must_raise RuntimeError
  end

  describe "#dna" do
    let(:node) { Gusteau::Node.new('spec/nodes/production.yml') }

    let(:dna)         { node.send(:dna, include_all, recipes) }
    let(:include_all) { true }
    let(:recipes)     { [] }

    let(:path) { '/tmp/testdna.json' }
    let(:json) { JSON::parse(File.read dna[:path]) }

    it "should create a new dna file" do
      File.exists?(dna[:path]).must_equal true
    end

    it "should support ERB" do
      json['environment'].must_equal "production"
    end

    context "recipes not specified" do
      it "should contain a full run_list" do
        json['run_list'].must_equal ["role[redhat]", "recipe[rvm]", "recipe[ntp]", "recipe[rails::apps]"]
      end
    end

    context "recipes specified" do
      let(:include_all) { false }
      let(:recipes)     { ['rvm', 'rails::apps'] }

      it "should only include the specified item into run_list" do
        json['run_list'].must_equal ["recipe[rvm]", "recipe[rails::apps]"]
      end
    end
  end
end


text:
<md-input-container>
  <label ng-if="label"
         ng-bind="label"></label>

  <input  ng-if="!multiline"
          aria-manager
          id="{{model.uid}}"
          name="{{attribute}}"
          type="{{type}}"
          tabindex="{{tabIndex}}"
          ng-model="model.bindable"
          ng-disabled="disable || model.disabled"
          ng-click="onFocus()"
          ng-blur="onBlur()" />

  <textarea ng-if="multiline"
            aria-manageraria-manager
            id="{{model.uid}}"
            name="{{attribute}}"
            class="form-control"
            ng-disabled="disable || model.disabled"
            tabindex="{{tabIndex}}"
            rows="{{rows}}"
            ng-model="model.bindable"
            ng-click="onFocus()"
            ng-blur="onBlur()">
  </textarea>

  <field-error ng-messages
               uid="{{model.uid}}-error"
               error="model.error"></field-error>
</md-input-container>


text:
package com.github.thorbenkuck.netcom2.auto.annotations.processor;

import com.github.thorbenkuck.netcom2.auto.annotations.Register;
import com.github.thorbenkuck.netcom2.network.shared.Session;
import com.github.thorbenkuck.netcom2.network.shared.connections.ConnectionContext;
import com.google.auto.service.AutoService;

import javax.annotation.processing.Processor;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import java.lang.annotation.Annotation;
import java.util.List;

@AutoService(Processor.class)
public class RegisterAnnotationProcessor extends AnnotationProcessor {

	private TypeElement sessionElement;
	private TypeElement connectionContextElement;
	private ReceiveHandlerGenerator receiveHandlerGenerator;

	private VariableElement classify(List<? extends VariableElement> parameters) {
		VariableElement returnValue = null;

		if (parameters.size() > 3) {
			return null;
		}

		for (VariableElement variableElement : parameters) {
			System.out.println("checking " + variableElement.asType() + " against " + sessionElement + " and " + connectionContextElement);
			TypeMirror type = variableElement.asType();
			if (!type.equals(sessionElement.asType()) && !type.equals(connectionContextElement.asType())) {
				if (returnValue == null) {
					returnValue = variableElement;
				} else {
					return null;
				}
			} else {
				System.out.println("Is either Session or ConnectionContext");
			}
		}

		return returnValue;
	}

	@Override
	protected void pre() {
		sessionElement = elements.getTypeElement(Session.class.getCanonicalName());
		connectionContextElement = elements.getTypeElement(ConnectionContext.class.getCanonicalName());
		receiveHandlerGenerator = new ReceiveHandlerGenerator(filer);
	}

	@Override
	protected Class<? extends Annotation> supported() {
		return Register.class;
	}

	@Override
	protected boolean process(Element element) {
		if (!(element instanceof ExecutableElement)) {
			return false;
		}

		ExecutableElement method = (ExecutableElement) element;

		List<? extends VariableElement> parameters = method.getParameters();
		VariableElement type = classify(parameters);

		if (type == null) {
			logger.error("A method annotated with @Register has to have exactly one parameter that is not a Session nor a ConnectionContext", method);
			return false;
		}

		TypeElement typeElement = (TypeElement) method.getEnclosingElement();

		// At this point, all we need
		// to do is to generate the
		// corresponding implementation
		receiveHandlerGenerator.generate(method, typeElement, type);
		return true;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.hadoop.util.DataChecksum (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API)
</TITLE>

<META NAME="date" CONTENT="2011-03-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.hadoop.util.DataChecksum

Packages that use DataChecksum

org.apache.hadoop.util
Common utilities.

Uses of DataChecksum in org.apache.hadoop.util

Methods in org.apache.hadoop.util that return DataChecksum

static DataChecksum
DataChecksum.newDataChecksum(byte[] bytes,
                int offset)

          Creates a DataChecksum from HEADER_LEN bytes from arr[offset].

static DataChecksum
DataChecksum.newDataChecksum(java.io.DataInputStream in)

          This constructucts a DataChecksum by reading HEADER_LEN bytes from
 input stream in

static DataChecksum
DataChecksum.newDataChecksum(int type,
                int bytesPerChecksum)

Methods in org.apache.hadoop.util with parameters of type DataChecksum

static void
ChecksumUtil.updateChunkChecksum(byte[] buf,
                    int checksumOff,
                    int dataOff,
                    int dataLen,
                    DataChecksum checksum)

          updates the checksum for a buffer

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

This release is based on the Facebook's version of Hadoop.
Copyright © 2009 The Apache Software Foundation.


text:
<?php

  /**
   * Tickets on_user_cleanup event handler
   *
   * @package activeCollab.modules.tickets
   * @subpackage handlers
   */

  /**
   * Handle on_user_cleanup event
   *
   * @param array $cleanup
   * @return null
   */
  function tickets_handle_on_user_cleanup(&$cleanup) {
    if(!isset($cleanup['ticket_changes'])) {
      $cleanup['ticket_changes'] = array();
    } // if

    $cleanup['ticket_changes'][] = 'created_by';
  } // tickets_handle_on_user_cleanup

?>


text:
package commands

import (
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"github.com/projectcalico/felix/bpf/nat"
)

func init() {
	ctCommand.AddCommand(ctCleanupCmd)
	rootCmd.AddCommand(ctCommand)
}

var ctCleanupCmd = &cobra.Command{
	Use:   "clean",
	Short: "removes connect-time BPF programs",
	Run: func(cmd *cobra.Command, args []string) {
		if err := nat.RemoveConnectTimeLoadBalancer(""); err != nil {
			log.WithError(err).Error("Failed to clean up connect-time load balancer.")
		}
	},
}

// ctCommand represents the connect-time command
var ctCommand = &cobra.Command{
	Use:   "connect-time",
	Short: "Manipulates connect-time load balancing programs",
}


text:
package com.twitter.distributedlog.service;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.twitter.distributedlog.DistributedLogConfiguration;
import com.twitter.finagle.stats.NullStatsReceiver;
import com.twitter.finagle.stats.StatsReceiver;
import org.apache.bookkeeper.stats.NullStatsProvider;
import org.apache.bookkeeper.stats.StatsProvider;
import org.apache.bookkeeper.util.ReflectionUtils;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;

import static com.twitter.distributedlog.util.CommandLineUtils.*;

public class DistributedLogServerApp {

    static final Logger logger = LoggerFactory.getLogger(DistributedLogServerApp.class);

    private final static String USAGE = "DistributedLogServerApp [-u <uri>] [-c <conf>]";
    private final String[] args;
    private final Options options = new Options();

    private DistributedLogServerApp(String[] args) {
        this.args = args;

        // prepare options
        options.addOption("u", "uri", true, "DistributedLog URI");
        options.addOption("c", "conf", true, "DistributedLog Configuration File");
        options.addOption("sc", "stream-conf", true, "Per Stream Configuration Directory");
        options.addOption("p", "port", true, "DistributedLog Server Port");
        options.addOption("sp", "stats-port", true, "DistributedLog Stats Port");
        options.addOption("pd", "stats-provider", true, "DistributedLog Stats Provider");
        options.addOption("si", "shard-id", true, "DistributedLog Shard ID");
        options.addOption("a", "announce", false, "ServerSet Path to Announce");
        options.addOption("mx", "thriftmux", false, "Is thriftmux enabled");
    }

    private void printUsage() {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(USAGE, options);
    }

    private void run() {
        try {
            logger.info("Running distributedlog server : args = {}", Arrays.toString(args));
            BasicParser parser = new BasicParser();
            CommandLine cmdline = parser.parse(options, args);
            runCmd(cmdline);
        } catch (ParseException pe) {
            logger.error("Argument error : {}", pe.getMessage());
            printUsage();
            Runtime.getRuntime().exit(-1);
        } catch (IllegalArgumentException iae) {
            logger.error("Argument error : {}", iae.getMessage());
            printUsage();
            Runtime.getRuntime().exit(-1);
        } catch (ConfigurationException ce) {
            logger.error("Configuration error : {}", ce.getMessage());
            printUsage();
            Runtime.getRuntime().exit(-1);
        } catch (IOException ie) {
            logger.error("Failed to start distributedlog server : ", ie);
            Runtime.getRuntime().exit(-1);
        }
    }

    private void runCmd(CommandLine cmdline) throws IllegalArgumentException, IOException, ConfigurationException {
        final StatsReceiver statsReceiver = NullStatsReceiver.get();
        Optional<String> confOptional = getOptionalStringArg(cmdline, "c");
        DistributedLogConfiguration dlConf = new DistributedLogConfiguration();
        if (confOptional.isPresent()) {
            String configFile = confOptional.get();
            try {
                dlConf.loadConf(new File(configFile).toURI().toURL());
            } catch (ConfigurationException e) {
                throw new IllegalArgumentException("Failed to load distributedlog configuration from " + configFile + ".");
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Failed to load distributedlog configuration from malformed "
                        + configFile + ".");
            }
        }
        // load the stats provider
        final StatsProvider statsProvider = getOptionalStringArg(cmdline, "pd")
                .transform(new Function<String, StatsProvider>() {
                    @Nullable
                    @Override
                    public StatsProvider apply(@Nullable String name) {
                        return ReflectionUtils.newInstance(name, StatsProvider.class);
                    }
                }).or(new NullStatsProvider());

        final DistributedLogServer server = DistributedLogServer.runServer(
                getOptionalStringArg(cmdline, "u"),
                confOptional,
                getOptionalStringArg(cmdline, "sc"),
                getOptionalIntegerArg(cmdline, "p"),
                getOptionalIntegerArg(cmdline, "sp"),
                getOptionalIntegerArg(cmdline, "si"),
                getOptionalBooleanArg(cmdline, "a"),
                getOptionalBooleanArg(cmdline, "mx"),
                statsReceiver,
                statsProvider);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("Closing DistributedLog Server.");
                server.close();
                logger.info("Closed DistributedLog Server.");
                statsProvider.stop();
            }
        });

        try {
            server.join();
        } catch (InterruptedException e) {
            logger.warn("Interrupted when waiting distributedlog server to be finished : ", e);
        }

        logger.info("DistributedLog Service Interrupted.");
        server.close();
        logger.info("Closed DistributedLog Server.");
        statsProvider.stop();
    }

    public static void main(String[] args) {
        final DistributedLogServerApp launcher = new DistributedLogServerApp(args);
        launcher.run();
    }
}


text:
// Copyright (c) 2019 DHGMS Solutions and Contributors. All rights reserved.
// This file is licensed to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using Dhgms.GripeWithRoslyn.Analyzer.Analyzers.Abstractions;
using Dhgms.GripeWithRoslyn.Analyzer.CodeCracker.Extensions;
using Microsoft.CodeAnalysis;

namespace Dhgms.GripeWithRoslyn.Analyzer.Analyzers.Runtime
{
    /// <summary>
    /// Roslyn Analyzer for detecting the use of methods in the .NET remoting services namespace.
    /// </summary>
    [Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
    public sealed class RemotingServicesAnalyzer : BaseInvocationUsingNamespaceAnalyzer
    {
        private const string Title = ".NET remoting is legacy technology and should not be used. You should be using a newer technology.";

        private const string MessageFormat = Title;

        private const string Category = SupportedCategories.Maintainability;

        private const string Description =
            ".NET remoting is legacy technology and should not be used. You should be using a newer technology.";

        /// <summary>
        /// Initializes a new instance of the <see cref="RemotingServicesAnalyzer"/> class.
        /// </summary>
        public RemotingServicesAnalyzer()
            : base(
                DiagnosticIdsHelper.RemotingServicesAnalyzer,
                Title,
                MessageFormat,
                Category,
                Description,
                DiagnosticSeverity.Warning)
        {
        }

        /// <inheritdoc />
        protected override string Namespace => "System.Runtime.Remoting";
    }
}


text:
from flask import json

from horse.models import User

def test_user_registration(client):
    response = client.post('/users', data=json.dumps({
        'name': 'Kevin',
    }), content_type='application/json')
    assert response.status_code == 201

    response = client.get('/users')
    assert response.status_code == 200

    movies = json.loads(response.data)['items']
    names = [m['name'] for m in movies]

    assert 'Kevin' in names

def test_user_registration_400_error(client):
    response = client.post('/users', data=json.dumps({
        'name2': 'Kevin',
    }), content_type='application/json')
    assert response.status_code == 400

def test_user_can_follow_another_user(client, users_repo):
    eve = User(name='Eve')
    adam = User(name='Adam')
    users_repo.store(eve)
    users_repo.store(adam)

    response = client.post('/users/{}/follow'.format(eve.pk), data=json.dumps({
        'pk': adam.pk
    }), content_type='application/json')
    assert response.status_code == 200

    response = client.get('/users/{}'.format(eve.pk))
    assert response.status_code == 200

    followed_users = json.loads(response.data)['followed_users']
    followed_users_names = [u['name'] for u in followed_users]

    assert 'Adam' in followed_users_names

def test_user_can_unfollow_user(client, users_repo):
    eve = User(name='Eve')
    adam = User(name='Adam')
    eve.add_to_followed_users(adam)
    users_repo.store(eve)
    users_repo.store(adam)

    response = client.delete(
        '/users/{}/follow/{}'.format(eve.pk, adam.pk)
    )
    assert response.status_code == 204
    assert len(eve.get_followed_users()) == 0

def test_user_follow_another_user_400_error(client):
    response = client.post('/users/1/follow', data=json.dumps({
        'user_pk': '2',
    }), content_type='application/json')
    assert response.status_code == 400

def test_user_can_like_movie(client, movie, user, users_repo, movies_repo):
    url = '/users/{user_pk}/liked_movies'.format(
        user_pk=user.pk,
    )
    assert movie.likes == 0
    response = client.post(url, data=json.dumps({
        'pk': movie.pk,
    }), content_type='application/json')
    assert response.status_code == 200

    response = client.get('/users/{}'.format(user.pk))
    liked_movies = json.loads(response.data)['liked_movies']
    movie_titles = [m['title'] for m in liked_movies]

    assert movie.title in movie_titles
    assert movie.likes == 1

def test_user_can_like_movie_400_error(client, user):
    url = '/users/{user_pk}/liked_movies'.format(
        user_pk=user.pk,
    )
    response = client.post(
        url, data=json.dumps({}), content_type='application/json'
    )
    assert response.status_code == 400

def test_user_can_unlike_movie(client, movie, user, users_repo, movies_repo):
    user.add_to_liked_movies(movie)

    assert movie in user.get_liked_movies()
    assert movie.likes == 1

    response = client.delete(
        '/users/{}/liked_movies/{}'.format(user.pk, movie.pk)
    )
    assert response.status_code == 204

    assert len(user.get_liked_movies()) == 0
    assert movie.likes == 0


text:
#include "tensorflow_serving/batching/batching_session.h"

#include <gtest/gtest.h>
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/cc/saved_model/tag_constants.h"
#include "tensorflow/contrib/session_bundle/session_bundle.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow_serving/servables/tensorflow/serving_session.h"
#include "tensorflow_serving/test_util/test_util.h"

namespace tensorflow {
namespace serving {
namespace {

using ::testing::HasSubstr;
using ::testing::UnorderedElementsAre;

// A wrapper around a Session that captures the batch size.
class BatchSizeCapturingSession : public ServingSession {
 public:
  explicit BatchSizeCapturingSession(std::unique_ptr<Session> wrapped)
      : wrapped_(std::move(wrapped)) {}
  ~BatchSizeCapturingSession() override = default;

  Status Run(const std::vector<std::pair<string, Tensor>>& inputs,
             const std::vector<string>& output_tensor_names,
             const std::vector<string>& target_node_names,
             std::vector<Tensor>* outputs) override {
    RunMetadata run_metadata;
    return Run(RunOptions(), inputs, output_tensor_names, target_node_names,
               outputs, &run_metadata);
  }

  Status Run(const RunOptions& run_options,
             const std::vector<std::pair<string, Tensor>>& inputs,
             const std::vector<string>& output_tensor_names,
             const std::vector<string>& target_node_names,
             std::vector<Tensor>* outputs, RunMetadata* run_metadata) override {
    latest_batch_size_ = inputs[0].second.shape().dim_size(0);
    return wrapped_->Run(run_options, inputs, output_tensor_names,
                         target_node_names, outputs, run_metadata);
  }

  int latest_batch_size() const { return latest_batch_size_; }

 private:
  std::unique_ptr<Session> wrapped_;

  // The size of the batch most recently submitted to Run().
  int latest_batch_size_ = -1;

  TF_DISALLOW_COPY_AND_ASSIGN(BatchSizeCapturingSession);
};

// Creates a (non-batching) session with the half-plus-two model loaded.
std::unique_ptr<Session> CreateHalfPlusTwoSession() {
  tensorflow::SessionOptions session_options;
  tensorflow::RunOptions run_options;
  const string export_dir = test_util::TensorflowTestSrcDirPath(
      "cc/saved_model/testdata/half_plus_two/00000123");
  SavedModelBundle bundle;
  TF_CHECK_OK(LoadSavedModel(session_options, run_options, export_dir,
                             {kSavedModelTagServe}, &bundle));
  return std::move(bundle.session);
}

// Test that a session handles a single request for the half-plus-two model
// properly. The request has two input floats (size=2 for batching purposes).
void TestSingleRequest(float input_0, float input_1, Session* session) {
  Tensor input = test::AsTensor<float>({input_0, input_1}, {2});
  // Half plus two: each output should be input / 2 + 2.
  Tensor expected_output =
      test::AsTensor<float>({input_0 / 2 + 2, input_1 / 2 + 2}, {2});

  const std::vector<std::pair<string, Tensor>> inputs = {{"x", input}};
  std::vector<Tensor> outputs;
  TF_ASSERT_OK(session->Run(inputs, {"y"}, {} /* target nodes */, &outputs));
  ASSERT_EQ(1, outputs.size());
  test::ExpectTensorEqual<float>(expected_output, outputs[0]);
}

// Invoke Run() with the supplied arguments, and expect a particular error.
void ExpectError(const string& error_message,
                 const std::vector<std::pair<string, Tensor>>& inputs,
                 const std::vector<string>& output_tensor_names,
                 Session* session) {
  std::vector<Tensor> outputs;
  Status status = session->Run(inputs, output_tensor_names,
                               {} /* target nodes */, &outputs);
  ASSERT_FALSE(status.ok());
  EXPECT_EQ(error_message, status.error_message());
}

// Creates a SignatureDef from a TensorSignature.
SignatureDef CreateSignatureDef(const TensorSignature& tensor_signature) {
  SignatureDef signature_def;
  for (const string& input_tensor : tensor_signature.input_tensors) {
    TensorInfo input;
    input.set_name(input_tensor);
    (*signature_def.mutable_inputs())[input_tensor] = input;
  }
  for (const string& output_tensor : tensor_signature.output_tensors) {
    TensorInfo output;
    output.set_name(output_tensor);
    (*signature_def.mutable_outputs())[output_tensor] = output;
  }
  return signature_def;
}

TEST(BatchingSessionTest, TensorSignatureFromSignatureDef) {
  const SignatureDef signature_def =
      CreateSignatureDef({{"x0", "x1"}, {"y0", "y1"}});
  const TensorSignature tensor_signature =
      TensorSignatureFromSignatureDef(signature_def);
  EXPECT_THAT(tensor_signature.input_tensors, UnorderedElementsAre("x0", "x1"));
  EXPECT_THAT(tensor_signature.output_tensors,
              UnorderedElementsAre("y0", "y1"));
}

TEST(BatchingSessionTest, TensorSignatureFromSignatureDefs) {
  const SignatureDef signature_def_0 =
      CreateSignatureDef({{"x0", "x1"}, {"y0", "y1"}});
  const SignatureDef signature_def_1 =
      CreateSignatureDef({{"x1", "x2"}, {"y1", "y3"}});
  const TensorSignature tensor_signature =
      TensorSignatureFromSignatureDefs({signature_def_0, signature_def_1});
  EXPECT_THAT(tensor_signature.input_tensors,
              UnorderedElementsAre("x0", "x1", "x2"));
  EXPECT_THAT(tensor_signature.output_tensors,
              UnorderedElementsAre("y0", "y1", "y3"));
}

TEST(BatchingSessionTest, Basic) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 4;  // fits two 2-unit tasks
  schedule_options.batch_timeout_micros = 1 * 1000 * 1000;  // won't trigger
  schedule_options.num_batch_threads = 1;
  std::unique_ptr<Session> batching_session;
  BatchingSessionOptions batching_session_options;
  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options, {{"x"}, {"y"}},
      CreateHalfPlusTwoSession(), &batching_session));

  // Asynchronously send two requests whose total size is 4. The two requests in
  // conjunction should trigger a batch to be processed.
  std::unique_ptr<Thread> first_request_thread(Env::Default()->StartThread(
      ThreadOptions(), "first_request_thread", [&batching_session] {
        TestSingleRequest(100.0f, 42.0f, batching_session.get());
      }));
  std::unique_ptr<Thread> second_request_thread(Env::Default()->StartThread(
      ThreadOptions(), "second_request_thread", [&batching_session] {
        TestSingleRequest(71.5f, 18.3f, batching_session.get());
      }));
}

TEST(BatchingSessionTest, SingletonBatch) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 4;  // fits two 2-unit tasks
  schedule_options.batch_timeout_micros = 0;
  schedule_options.num_batch_threads = 1;
  std::unique_ptr<Session> batching_session;
  BatchingSessionOptions batching_session_options;
  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options, {{"x"}, {"y"}},
      CreateHalfPlusTwoSession(), &batching_session));
  TestSingleRequest(100.0f, 42.0f, batching_session.get());
}

TEST(BatchingSessionTest, RequestThatDoesntMatchSignatureGetsRunAnyway) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  // Set the batching parameters s.t. if the request is batched the test will
  // timeout.
  schedule_options.max_batch_size = 100;
  schedule_options.batch_timeout_micros = INT_MAX;
  std::unique_ptr<Session> batching_session;
  BatchingSessionOptions batching_session_options;
  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options, {{"x2"}, {"y3"}},
      CreateHalfPlusTwoSession(), &batching_session));
  // Issue a request using x/y, which doesn't match the x2/y3 signature.
  TestSingleRequest(100.0f, 42.0f, batching_session.get());
}

TEST(BatchingSessionTest, RequestWithIncompatibleInputTensorSizes) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  std::unique_ptr<Session> batching_session;
  BatchingSessionOptions batching_session_options;

  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options,
      {{"input_0", "input_1"}, {"output"}}, CreateHalfPlusTwoSession(),
      &batching_session));

  ExpectError(
      "Batching session Run() input tensors must have equal 0th-dimension size",
      {{"input_0", test::AsTensor<int>({3}, {1})},
       {"input_1", test::AsTensor<int>({5, 7}, {2})}},
      {"output"}, batching_session.get());
}

TEST(BatchingSessionTest, AllowedBatchSizesNoPaddingNeeded) {
  // Arrange to capture the batch size.
  std::unique_ptr<BatchSizeCapturingSession> batch_size_capturing_session(
      new BatchSizeCapturingSession(CreateHalfPlusTwoSession()));
  auto batch_size_capturing_session_raw = batch_size_capturing_session.get();

  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 4;
  schedule_options.batch_timeout_micros = 0;
  schedule_options.num_batch_threads = 1;
  BatchingSessionOptions batching_session_options;
  batching_session_options.allowed_batch_sizes = {2, 4};
  std::unique_ptr<Session> batching_session;
  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options, {{"x"}, {"y"}},
      std::move(batch_size_capturing_session), &batching_session));
  TestSingleRequest(100.0f, 42.0f, batching_session.get());

  // It should not add any padding, i.e. leave the batch size at 2.
  EXPECT_EQ(2, batch_size_capturing_session_raw->latest_batch_size());
}

TEST(BatchingSessionTest, AllowedBatchSizesRequirePadding) {
  // Arrange to capture the batch size.
  std::unique_ptr<BatchSizeCapturingSession> batch_size_capturing_session(
      new BatchSizeCapturingSession(CreateHalfPlusTwoSession()));
  auto batch_size_capturing_session_raw = batch_size_capturing_session.get();

  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 4;
  schedule_options.batch_timeout_micros = 0;
  schedule_options.num_batch_threads = 1;
  BatchingSessionOptions batching_session_options;
  batching_session_options.allowed_batch_sizes = {1, 3, 4};
  std::unique_ptr<Session> batching_session;
  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options, {{"x"}, {"y"}},
      std::move(batch_size_capturing_session), &batching_session));
  TestSingleRequest(100.0f, 42.0f, batching_session.get());

  // It should pad the batch size from 2 to 3.
  EXPECT_EQ(3, batch_size_capturing_session_raw->latest_batch_size());
}

TEST(BatchingSessionTest, UnsortedAllowedBatchSizesRejected) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 4;
  BatchingSessionOptions batching_session_options;
  batching_session_options.allowed_batch_sizes = {4, 2};  // Not sorted.
  std::unique_ptr<Session> batching_session;
  EXPECT_FALSE(CreateBasicBatchingSession(
                   schedule_options, batching_session_options, {{"x"}, {"y"}},
                   CreateHalfPlusTwoSession(), &batching_session)
                   .ok());
}

TEST(BatchingSessionTest,
     FinalAllowedBatchSizeDifferingFromMaxBatchSizeRejected) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 4;
  BatchingSessionOptions batching_session_options;
  batching_session_options.allowed_batch_sizes = {2, 8};  // Final entry != 4.
  std::unique_ptr<Session> batching_session;
  EXPECT_FALSE(CreateBasicBatchingSession(
                   schedule_options, batching_session_options, {{"x"}, {"y"}},
                   CreateHalfPlusTwoSession(), &batching_session)
                   .ok());
}

TEST(BatchingSessionTest, DifferentOrderForInputAndOutputTensors) {
  BasicBatchScheduler<BatchingSessionTask>::Options schedule_options;
  schedule_options.max_batch_size = 6;  // fits three 2-unit tasks
  schedule_options.batch_timeout_micros = 1 * 1000 * 1000;  // won't trigger
  schedule_options.num_batch_threads = 1;
  BatchingSessionOptions batching_session_options;
  std::unique_ptr<Session> batching_session;
  TF_ASSERT_OK(CreateBasicBatchingSession(
      schedule_options, batching_session_options, {{"x", "x2"}, {"y", "y3"}},
      CreateHalfPlusTwoSession(), &batching_session));

  const Tensor input0 = test::AsTensor<float>({8.0f, 6.0f}, {2});
  const Tensor expected_output0 = test::AsTensor<float>({6.0f, 5.0f}, {2});
  const Tensor input1 = test::AsTensor<float>({100.0f, 42.0f}, {2});
  const Tensor expected_output1 = test::AsTensor<float>({53.0f, 24.0f}, {2});

  std::unique_ptr<Thread> first_request_thread(
      Env::Default()->StartThread(ThreadOptions(), "first_request_thread", [&] {
        std::vector<Tensor> outputs;
        TF_ASSERT_OK(batching_session->Run({{"x", input0}, {"x2", input1}},
                                           {"y", "y3"} /* outputs */,
                                           {} /* target nodes */, &outputs));
        ASSERT_EQ(2, outputs.size());
        test::ExpectTensorEqual<float>(expected_output0, outputs[0]);
        test::ExpectTensorEqual<float>(expected_output1, outputs[1]);
      }));
  std::unique_ptr<Thread> second_request_thread(Env::Default()->StartThread(
      ThreadOptions(), "second_request_thread", [&] {
        std::vector<Tensor> outputs;
        TF_ASSERT_OK(batching_session->Run({{"x2", input1}, {"x", input0}},
                                           {"y3", "y"} /* outputs */,
                                           {} /* target nodes */, &outputs));
        ASSERT_EQ(2, outputs.size());
        test::ExpectTensorEqual<float>(expected_output1, outputs[0]);
        test::ExpectTensorEqual<float>(expected_output0, outputs[1]);
      }));
  std::unique_ptr<Thread> third_request_thread(
      Env::Default()->StartThread(ThreadOptions(), "third_request_thread", [&] {
        std::vector<Tensor> outputs;
        TF_ASSERT_OK(batching_session->Run({{"x2", input1}, {"x", input0}},
                                           {"y", "y3"} /* outputs */,
                                           {} /* target nodes */, &outputs));
        ASSERT_EQ(2, outputs.size());
        test::ExpectTensorEqual<float>(expected_output0, outputs[0]);
        test::ExpectTensorEqual<float>(expected_output1, outputs[1]);
      }));
}

TEST(BatchingSessionTest, MultipleSignatures) {
  std::vector<BatchScheduler<BatchingSessionTask>*> schedulers;
  auto create_scheduler = [&schedulers](
      std::function<void(std::unique_ptr<Batch<BatchingSessionTask>>)>
          process_batch_callback,
      std::unique_ptr<BatchScheduler<BatchingSessionTask>>* scheduler) {
    BasicBatchScheduler<BatchingSessionTask>::Options options;
    options.max_batch_size = 4;                      // fits two 2-unit tasks
    options.batch_timeout_micros = 1 * 1000 * 1000;  // won't trigger
    options.num_batch_threads = 1;
    std::unique_ptr<BasicBatchScheduler<BatchingSessionTask>> basic_scheduler;
    TF_RETURN_IF_ERROR(BasicBatchScheduler<BatchingSessionTask>::Create(
        options, process_batch_callback, &basic_scheduler));
    schedulers.push_back(basic_scheduler.get());
    *scheduler = std::move(basic_scheduler);
    return Status::OK();
  };
  BatchingSessionOptions batching_session_options;
  std::unique_ptr<Session> batching_session;
  TF_CHECK_OK(CreateBatchingSession(
      batching_session_options, {{{{"x"}, {"y"}}, create_scheduler},
                                 {{{"x2"}, {"y3"}}, create_scheduler}},
      CreateHalfPlusTwoSession(), &batching_session));
  ASSERT_EQ(2, schedulers.size());

  // Create lambdas for 2-unit inference requests to each signature.
  auto run_signature0_request = [&batching_session] {
    Tensor input = test::AsTensor<float>({100.0f, 42.0f}, {2});
    Tensor expected_output = test::AsTensor<float>({52.0f, 23.0f}, {2});
    std::vector<Tensor> outputs;
    TF_ASSERT_OK(batching_session->Run({{"x", input}}, {"y"} /* outputs */,
                                       {} /* target nodes */, &outputs));
    ASSERT_EQ(1, outputs.size());
    test::ExpectTensorEqual<float>(expected_output, outputs[0]);
  };
  auto run_signature1_request = [&batching_session] {
    Tensor input = test::AsTensor<float>({100.0f, 42.0f}, {2});
    Tensor expected_output = test::AsTensor<float>({53.0f, 24.0f}, {2});
    std::vector<Tensor> outputs;
    TF_ASSERT_OK(batching_session->Run({{"x2", input}}, {"y3"} /* outputs */,
                                       {} /* target nodes */, &outputs));
    ASSERT_EQ(1, outputs.size());
    test::ExpectTensorEqual<float>(expected_output, outputs[0]);
  };

  // Enqueue one request for each signature. Both should block because neither
  // batching queue will be full yet.
  std::unique_ptr<Thread> signature0_thread(Env::Default()->StartThread(
      ThreadOptions(), "signature0_thread", [&] { run_signature0_request(); }));
  std::unique_ptr<Thread> signature1_thread(Env::Default()->StartThread(
      ThreadOptions(), "signature1_thread", [&] { run_signature1_request(); }));
  while (schedulers[0]->NumEnqueuedTasks() != 1 &&
         schedulers[1]->NumEnqueuedTasks() != 1) {
    Env::Default()->SleepForMicroseconds(100);
  }

  // Enqueue a second request for each signature. This should fill both queues
  // and unblock all the processing.
  run_signature0_request();
  EXPECT_EQ(0, schedulers[0]->NumEnqueuedTasks());
  run_signature1_request();
  EXPECT_EQ(0, schedulers[1]->NumEnqueuedTasks());
}

TEST(BatchingSessionTest, EnqueuedLongerThanTimeout) {
  BatchScheduler<BatchingSessionTask>* scheduler = nullptr;
  auto create_scheduler = [&scheduler](
      std::function<void(std::unique_ptr<Batch<BatchingSessionTask>>)>
          process_batch_callback,
      std::unique_ptr<BatchScheduler<BatchingSessionTask>>* new_scheduler) {
    BasicBatchScheduler<BatchingSessionTask>::Options options;
    options.max_batch_size = 4;                      // fits two 2-unit tasks
    options.batch_timeout_micros = 1 * 1000 * 1000;  // won't trigger
    options.num_batch_threads = 1;
    std::unique_ptr<BasicBatchScheduler<BatchingSessionTask>> basic_scheduler;
    TF_RETURN_IF_ERROR(BasicBatchScheduler<BatchingSessionTask>::Create(
        options, process_batch_callback, &basic_scheduler));
    scheduler = basic_scheduler.get();
    *new_scheduler = std::move(basic_scheduler);
    return Status::OK();
  };
  BatchingSessionOptions batching_session_options;
  std::unique_ptr<Session> batching_session;
  TF_CHECK_OK(CreateBatchingSession(
      batching_session_options, {{{{"x"}, {"y"}}, create_scheduler}},
      CreateHalfPlusTwoSession(), &batching_session));
  ASSERT_FALSE(scheduler == nullptr);

  // Enqueue a request with a timeout specified via RunOptions.
  Notification request_returned;
  auto issue_request = [&batching_session, &request_returned] {
    Tensor input = test::AsTensor<float>({100.0f, 42.0f}, {2});
    RunOptions run_options;
    run_options.set_timeout_in_ms(1);
    std::vector<Tensor> outputs;
    RunMetadata run_metadata;
    const Status status =
        batching_session->Run(run_options, {{"x", input}}, {"y"} /* outputs */,
                              {} /* target nodes */, &outputs, &run_metadata);
    EXPECT_FALSE(status.ok());
    EXPECT_EQ(error::RESOURCE_EXHAUSTED, status.code());
    EXPECT_THAT(
        status.error_message(),
        HasSubstr("Run() timeout exceeded while waiting in batching queue"));
    request_returned.Notify();
  };
  std::unique_ptr<Thread> request_thread(Env::Default()->StartThread(
      ThreadOptions(), "request_thread", [&] { issue_request(); }));
  while (scheduler->NumEnqueuedTasks() != 1) {
    Env::Default()->SleepForMicroseconds(100);
  }
  // Sleep for longer than the request's timeout, so that when it does finally
  // get dequeued for batch processing it has already exceeded its timeout.
  Env::Default()->SleepForMicroseconds(10 * 1000);
  // Tear down the batcher, so that it schedules the pending batch.
  batching_session = nullptr;
  request_returned.WaitForNotification();
}

}  // namespace
}  // namespace serving
}  // namespace tensorflow


text:
BOOST_AUTO_TEST_SUITE(getarg_tests)

static void
ResetArgs(const std::string& strArg)
{
    std::vector<std::string> vecArg;
    boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);

    // Insert dummy executable name:
    vecArg.insert(vecArg.begin(), "testbitcoin");

    // Convert to char*:
    std::vector<const char*> vecChar;
    BOOST_FOREACH(std::string& s, vecArg)
        vecChar.push_back(s.c_str());

    ParseParameters(vecChar.size(), &vecChar[0]);
}

BOOST_AUTO_TEST_CASE(boolarg)
{
    ResetArgs("-FLC");
    BOOST_CHECK(GetBoolArg("-FLC"));
    BOOST_CHECK(GetBoolArg("-FLC", false));
    BOOST_CHECK(GetBoolArg("-FLC", true));

    BOOST_CHECK(!GetBoolArg("-fo"));
    BOOST_CHECK(!GetBoolArg("-fo", false));
    BOOST_CHECK(GetBoolArg("-fo", true));

    BOOST_CHECK(!GetBoolArg("-FLCo"));
    BOOST_CHECK(!GetBoolArg("-FLCo", false));
    BOOST_CHECK(GetBoolArg("-FLCo", true));

    ResetArgs("-FLC=0");
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", false));
    BOOST_CHECK(!GetBoolArg("-FLC", true));

    ResetArgs("-FLC=1");
    BOOST_CHECK(GetBoolArg("-FLC"));
    BOOST_CHECK(GetBoolArg("-FLC", false));
    BOOST_CHECK(GetBoolArg("-FLC", true));

    // New 0.6 feature: auto-map -nosomething to !-something:
    ResetArgs("-noFLC");
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", false));
    BOOST_CHECK(!GetBoolArg("-FLC", true));

    ResetArgs("-noFLC=1");
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", false));
    BOOST_CHECK(!GetBoolArg("-FLC", true));

    ResetArgs("-FLC -noFLC");  // -FLC should win
    BOOST_CHECK(GetBoolArg("-FLC"));
    BOOST_CHECK(GetBoolArg("-FLC", false));
    BOOST_CHECK(GetBoolArg("-FLC", true));

    ResetArgs("-FLC=1 -noFLC=1");  // -FLC should win
    BOOST_CHECK(GetBoolArg("-FLC"));
    BOOST_CHECK(GetBoolArg("-FLC", false));
    BOOST_CHECK(GetBoolArg("-FLC", true));

    ResetArgs("-FLC=0 -noFLC=0");  // -FLC should win
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", false));
    BOOST_CHECK(!GetBoolArg("-FLC", true));

    // New 0.6 feature: treat -- same as -:
    ResetArgs("--FLC=1");
    BOOST_CHECK(GetBoolArg("-FLC"));
    BOOST_CHECK(GetBoolArg("-FLC", false));
    BOOST_CHECK(GetBoolArg("-FLC", true));

    ResetArgs("--noFLC=1");
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", false));
    BOOST_CHECK(!GetBoolArg("-FLC", true));

}

BOOST_AUTO_TEST_CASE(stringarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-FLC", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-FLC", "eleven"), "eleven");

    ResetArgs("-FLC -bar");
    BOOST_CHECK_EQUAL(GetArg("-FLC", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-FLC", "eleven"), "");

    ResetArgs("-FLC=");
    BOOST_CHECK_EQUAL(GetArg("-FLC", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-FLC", "eleven"), "");

    ResetArgs("-FLC=11");
    BOOST_CHECK_EQUAL(GetArg("-FLC", ""), "11");
    BOOST_CHECK_EQUAL(GetArg("-FLC", "eleven"), "11");

    ResetArgs("-FLC=eleven");
    BOOST_CHECK_EQUAL(GetArg("-FLC", ""), "eleven");
    BOOST_CHECK_EQUAL(GetArg("-FLC", "eleven"), "eleven");

}

BOOST_AUTO_TEST_CASE(intarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-FLC", 11), 11);
    BOOST_CHECK_EQUAL(GetArg("-FLC", 0), 0);

    ResetArgs("-FLC -bar");
    BOOST_CHECK_EQUAL(GetArg("-FLC", 11), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);

    ResetArgs("-FLC=11 -bar=12");
    BOOST_CHECK_EQUAL(GetArg("-FLC", 0), 11);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);

    ResetArgs("-FLC=NaN -bar=NotANumber");
    BOOST_CHECK_EQUAL(GetArg("-FLC", 1), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
}

BOOST_AUTO_TEST_CASE(doubledash)
{
    ResetArgs("--FLC");
    BOOST_CHECK_EQUAL(GetBoolArg("-FLC"), true);

    ResetArgs("--FLC=verbose --bar=1");
    BOOST_CHECK_EQUAL(GetArg("-FLC", ""), "verbose");
    BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
}

BOOST_AUTO_TEST_CASE(boolargno)
{
    ResetArgs("-noFLC");
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", true));
    BOOST_CHECK(!GetBoolArg("-FLC", false));

    ResetArgs("-noFLC=1");
    BOOST_CHECK(!GetBoolArg("-FLC"));
    BOOST_CHECK(!GetBoolArg("-FLC", true));
    BOOST_CHECK(!GetBoolArg("-FLC", false));

    ResetArgs("-noFLC=0");
    BOOST_CHECK(GetBoolArg("-FLC"));
    BOOST_CHECK(GetBoolArg("-FLC", true));
    BOOST_CHECK(GetBoolArg("-FLC", false));

    ResetArgs("-FLC --noFLC");
    BOOST_CHECK(GetBoolArg("-FLC"));

    ResetArgs("-noFLC -FLC"); // FLC always wins:
    BOOST_CHECK(GetBoolArg("-FLC"));
}

BOOST_AUTO_TEST_SUITE_END()