text:
<?php
namespace Payum\Heartland;

use Buzz\Client\ClientInterface;
use Payum\Exception\Http\HttpException;
use Payum\Exception\InvalidArgumentException;
use Payum\Exception\LogicException;
use Payum\Heartland\Soap\Base\Credentials;
use Payum\Heartland\Soap\Base\MerchantCredentials;
use \SoapClient;

/**
 * @author Ton Sharp <Forma-PRO@66ton99.org.ua>
 */
class Api
{
    /**
     * @var array
     */
    protected $options = array(
        'env' => '',
        'application_id' => null,
        'username' => null,
        'password' => null,
    );

    /**
     * @var string
     */
    protected $soapClientClassName;

    /**
     * @var array
     */
    protected $soapOptions = array();

    /**
     * @var \Payum\Heartland\SoapClient
     */
    protected $soapClient = null;

    /**
     * @param array $options
     * @param string $soapClientClassName
     *
     * @throw InvalidArgumentException
     */
    public function __construct(array $options, $soapClientClassName = 'Payum\Heartland\SoapClient')
    {
        $this->options = array_replace($this->options, $options);
        $this->soapClientClassName = $soapClientClassName;

        if (empty($this->options['application_id'])) {
            throw new InvalidArgumentException('The application ID option must be set.');
        }
        if (empty($this->options['username'])) {
            throw new InvalidArgumentException('The username option must be set.');
        }
        if (empty($this->options['password'])) {
            throw new InvalidArgumentException('The password option must be set.');
        }
        if (!in_array($this->options['env'], array('', 'testing', 'staging'))) {
            throw new InvalidArgumentException(
                "The env option '{$this->options['env']}' is invalid, possible variants: " .
                    var_export($this->options['env'], true)
            );
        }
    }

    /**
     * @return string
     */
    protected function getApiEndpoint()
    {
        $host = 'heartlandpaymentservices.net/BillingDataManagement/v3/BillingDataManagementService.svc?wsdl';
        $env = empty($this->options['env'])?'':$this->options['env'].'.';

        return sprintf(
            'https://%s%s',
            $env,
            $host
        );
    }

    /**
     * @param array $options
     *
     * @return Api $this
     */
    public function setSoapOptions(array $options)
    {
        $this->soapOptions = $options;
        return $this;
    }

    /**
     * @return array
     */
    public function getSoapOptions()
    {
        return $this->soapOptions;
    }

    /**
     * @param Credentials $credential
     * @return Credentials
     */
    protected function fillCredential(Credentials $credential)
    {
        $credential->setApplicationID($this->options['application_id']);
        $credential->setUserName($this->options['username']);
        $credential->setPassword($this->options['password']);
        return $credential;
    }

    /**
     * @return Credentials
     */
    public function getCredentials()
    {
        $credential = new Credentials();
        return $this->fillCredential($credential);
    }

    /**
     * @param string $merchantName
     *
     * @return Credentials
     */
    public function getMerchantCredentials($merchantName)
    {
        $credential = new MerchantCredentials();
        $credential->setMerchantName($merchantName);
        return $this->fillCredential($credential);
    }

    /**
     * @return \Payum\Heartland\SoapClient
     */
    public function getSoapClient()
    {
        if (null === $this->soapClient) {
            $class = $this->soapClientClassName;
            $this->soapClient = new $class($this->getApiEndpoint(), $this->getSoapOptions());
        }
        if (!($this->soapClient instanceof SoapClient)) {
            throw new LogicException('Client should extend SoapClient class');
        }
        return $this->soapClient;
    }
}


text:
import React from 'react'
import { Field } from 'react-final-form'
import { InputField2 } from './InputField2'
import { validateTierEndDate } from '../../utils/validations'
import { DESCRIPTION, TEXT_FIELDS } from '../../utils/constants'

export const CrowdsaleEndTime = ({ index, ...props }) => (
  <Field
    component={InputField2}
    validate={props.disabled ? undefined : validateTierEndDate(index)}
    type="datetime-local"
    label={TEXT_FIELDS.END_TIME}
    description={DESCRIPTION.END_TIME}
    {...props}
  />
)

redpajama_set_name: RedPajamaGithub


text:
package tp2.tpalt.upmc.quizzforfriend;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

public class ListItemDetailActivity extends AppCompatActivity{

    //QuizzForFriend quizzy;
    Partie party;

    private ImageButton muteSoundBtn;
    private LinearLayout readeaySteadyGo;
    private RelativeLayout answlay;
    private TextView questionOverView, tfgans;
    private Button response1OverView,response2OverView,response3OverView,response4OverView;
    Animation animationSlideUp;
    TextView decompte, theme;
    Question q;

    // Toast...
    Toast toast;

    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.party_layout);
        mContentView = findViewById(R.id.prtlyt);

        muteSoundBtn = (ImageButton) findViewById(R.id.muteSound);
        readeaySteadyGo = (LinearLayout) findViewById(R.id.readeaySteadyGo);
        readeaySteadyGo.setVisibility(View.VISIBLE);
        decompte = (TextView)  findViewById(R.id.decompte);
        theme = (TextView)  findViewById(R.id.theme);

        answlay = (RelativeLayout) findViewById(R.id.answlay);
        tfgans = (TextView) findViewById(R.id.tfgans);

        questionOverView = (TextView) findViewById(R.id.questionOverView);

        response1OverView = (Button) findViewById(R.id.response1OverView);
        response2OverView = (Button) findViewById(R.id.response2OverView);
        response3OverView = (Button) findViewById(R.id.response3OverView);
        response4OverView = (Button) findViewById(R.id.response4OverView);

        // Toast...
        toast = new Toast(getApplicationContext());

        Intent intent = getIntent();
        int position = intent.getIntExtra("position", 0);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        QuizzForFriend.crossFade(getApplicationContext(), R.raw.countdown60s_wav_by_nsstudios_320771_2776777_lq, true);

        Questionnaire questionnaire = new Questionnaire(getApplicationContext(), QuizzForFriend.quizes[position]);

        party = new Partie(questionnaire);

        theme.setText("Theme : " + questionnaire.getTheme() + "\n" + questionnaire.getDescription());

    }

    public void toogleSound(View v){
        QuizzForFriend.toogleThemeSound(muteSoundBtn);
        QuizzForFriend.playToggleSound(getBaseContext());
    }

    public void playSelectPartySound(View v){
        QuizzForFriend.playSelectPartySound(getBaseContext());
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        animationSlideUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up);
        animationSlideUp.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                //Todo
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if(animation == animationSlideUp){
                    readeaySteadyGo.setVisibility(View.INVISIBLE);
                    questionOverView.setVisibility(View.VISIBLE);
                    response1OverView.setVisibility(View.VISIBLE);
                    response2OverView.setVisibility(View.VISIBLE);
                    response3OverView.setVisibility(View.VISIBLE);
                    response4OverView.setVisibility(View.VISIBLE);
                    answlay.setVisibility(View.VISIBLE);
                    tfgans.setVisibility(View.VISIBLE);
                    showQuestion();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO
            }
        });
        new CountDownTimer(5000, 1000) {

            public void onTick(long millisUntilFinished) {
                decompte.setText("On commence dans "+millisUntilFinished / 1000+" Secondes :)");
            }

            public void onFinish() {
                decompte.setText("GO !");
                readeaySteadyGo.startAnimation(animationSlideUp);

            }
        }.start();
        super.onPostCreate(savedInstanceState);
        delayedHide(0);
/*
        Intent myIntent = new Intent(getBaseContext(), ListItemDetailActivity.class);
        startActivityForResult(myIntent, 0);*/
    }

    private void toggle() {
        hide();
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mHideHandler.postDelayed(mHidePart2Runnable, 0);
    }

    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    @Override
    protected void onRestart() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        getSupportActionBar().hide();
        QuizzForFriend.playLoadingActivity(getBaseContext());
        super.onRestart();
    }

    @Override
    protected void onResume() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        getSupportActionBar().hide();
        QuizzForFriend.playLoadingActivity(getBaseContext());
        super.onResume();
    }

    @Override
    public void onBackPressed(){
        moveTaskToBack(false);
    }

    public void makeAchoice(View v){
        if(party.isFinish()) {
            Intent itnt = new Intent (getApplicationContext(), DisplayResultActivity.class);
            itnt.putExtra("nbBonnerep", party.getNbBonneReponse());
            itnt.putExtra("nbRep", party.getNbReponse());
            startActivity(itnt);
            return;
        }else {
            LayoutInflater inflater = getLayoutInflater();
            View layout;
            Button b = (Button)v;
            String resp = b.getText().toString();
            if (party.bonneReponse(resp)){
                QuizzForFriend.playGoodAnswerSound(getApplicationContext());
                layout = inflater.inflate(R.layout.bonneresponse_toast,
                        (ViewGroup) findViewById(R.id.custom_toast_layout_id));
            }else {
                QuizzForFriend.playBadAnswer(getApplicationContext());
                layout = inflater.inflate(R.layout.badresponse_toast,
                        (ViewGroup) findViewById(R.id.custom_toast_layout_id2));
            }
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
            showQuestion();
        }

    }

    public void showQuestion(){
        q = party.getNexQuestion();
        questionOverView.setText(q.getQuestion());
        JSONArray responses = q.getResponsesJsonArray();
        if(responses == null){
            Intent itnt = new Intent (getApplicationContext(), DisplayResultActivity.class);
            itnt.putExtra("nbBonnerep", party.getNbBonneReponse());
            itnt.putExtra("nbRep", party.getNbReponse());
            startActivity(itnt);
            return;
        }
        for (int u = 0; u < responses.length(); u++) {
            switch(u) {
                case 0 :
                    try {
                        response1OverView.setText(responses.getJSONObject(0).get("name").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break; // optional

                case 1 :
                    try {
                        response2OverView.setText(responses.getJSONObject(1).get("name").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break; // optional

                case 2 :
                    try {
                        response3OverView.setText(responses.getJSONObject(2).get("name").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break; // optional

                case 3 :
                    try {
                        response4OverView.setText(responses.getJSONObject(3).get("name").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break; // optional
            }
        }
    }
}


text:
/**
 * @author stefan eugster
 */

var WAKTOOLS = WAKTOOLS || {};

/**
 * match
 */

WAKTOOLS.match = function(regex, string) {
 	// extract amount
	if ( string && string.match(regex) && string.match(regex).length > 1) {
		return string.match(regex)[1]
	} else {
		return '';
	}
};

/**
 * convert nl into space
 */

WAKTOOLS.nl2space = function( str ) {
    var str = str || '';
    // replace line breaks with br tags
    str = str.replace(/\n/g, ', ');
    return str;
};

/**
 * convert nl into

 */

WAKTOOLS.nl2br = function( str ) {
    var str = str || '';
    // replace line breaks with br tags
    str = str.replace(/\n/g, '
');
    return str;
};

/**
 * delay throttle
 */

WAKTOOLS.delay = (function(){
  var timer = 0;
  return function(callback, ms) {
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

/**
 * destroy all existing CKEditors
 */

WAKTOOLS.destroyAllEditors = function() {
	// remove existing editors
	if (window.CKEDITOR && window.CKEDITOR.instances) {
    	for (var i in window.CKEDITOR.instances) {
    	    window.CKEDITOR.instances[i].destroy(false);
    	}
    }
}

/**
 * screen handler
 *
 * @param path {String} component path ex. '/components/public-page.waComponent'
 */

WAKTOOLS.screen = function(path) {
    // activate navigation item
	$('.mainNavItem').each(function(event) {
	    if ($(this).attr('data-component') == path) {
	        $(this).addClass('activeItem');
	    } else {
	        $(this).removeClass('activeItem');
	    }
	});
    // cache current component path
    localStorage.setItem('componentPath', path);
	// remove existing editors
	WAKTOOLS.destroyAllEditors();
	// show spinner
	WAKTOOLS.Spinner.show();
    // fade out
	$('#mainScreen').animate({opacity: 0}, 300, 'easeInOutQuart', function() {
        // load component
    	$$('mainScreen').loadComponent({
    		path: path,
    		onSuccess: function(event){
    		    // fade in
    		    $('#mainScreen').animate({opacity: 1}, 1200, 'easeInOutQuart', function() {
    		        // hide spinner
    		        WAKTOOLS.Spinner.hide();
    		    });
    		}
    	});
	});
};

/**
 * add navigation to header bar
 */

WAKTOOLS.navigation = function (callbackFn) {
	// add component to catalog
	ds.addToCatalog('Component', {
		onSuccess: function(event){
			// load navigation
		    ds.Component.getNavigation({
				onSuccess: function (event) {
		        	var $container = $('#navContainer'),
		        		templateSource = $('#navigationTemplate').html(),
		        		templateFn = Handlebars.compile(templateSource),
		        		data = event.result;

		            // apply template
		        	$container.html(templateFn(data));
		        	// callback function
		            callbackFn();
		        	// navigation cklick event
		        	$container.on('click', '.mainNavItem', function(event) {
		        		var $this = $(this),
		        		    linkName = $this.text();

		        		WAKTOOLS.screen($this.attr('data-component'));
		        	});
		        	// navigation mouseenter event
		        	$container.on('mouseenter', '.mainNavItem', function(event) {
		        		$(this).addClass('hoverItem');
		        	});
		        	// navigation mouseleave event
		        	$container.on('mouseleave', '.mainNavItem', function(event) {
		        		$(this).removeClass('hoverItem');
		        	});
				}
			});
		}
	});
};

/**
 * user login handler
 *
 * @param defaultComponentPath {String} default component path ex. '/components/public-message.waComponent'
 */

WAKTOOLS.login = function(defaultComponentPath) {
    var componentPath = localStorage.getItem('componentPath') ? localStorage.getItem('componentPath') : defaultComponentPath;

    // validate if user is not logged or logged as guest
	if (WAF.directory.currentUser() === null || (WAF.directory.currentUser() && WAF.directory.currentUser().userName === 'guest')) {
		// auto login as default guest user for passwort reset
		WAF.directory.loginByPassword('guest', 'guest');
        // show login wrapper
        $$('wrapperLogin').show()
	} else {
	    // hide login layer
	    $('#wrapperLogin').fadeOut({opacity: 0, duration: 300, easing: 'easeInOutQuart'});
	    // add navigation
	    WAKTOOLS.navigation(function(event) {
            // add login name to header bar
    		$('#loginName').text(WAF.directory.currentUser().fullName);
    	    // set default page if component path is not set
    	    if (componentPath) {
                // load component
                WAKTOOLS.screen(componentPath);
    	    }
	    });
		// idle timer (logout after 45 min inactivity)
		new WAKTOOLS.Idle(1000 * 60 * 45, WAKTOOLS.logout);
	}
};

/**
 * user logout handler
 */

WAKTOOLS.logout = function() {
	WAF.directory.logout({
		onSuccess: function() {
		    // reset component path
		    localStorage.setItem('componentPath', '');
		    // reload window
		    window.location.reload();
		}
	});
};

/**
 * user notifications
 *
 * @param message {Object}        message object
 * @param options {Object}        options object (message type)
 * @return        {Object/String} result
 */

WAKTOOLS.alert = function(message, options) {
	try {
	    var options = options || {};

	    // default type
	    options.type = options.type || 'success';
		// display message for debugging issues
		console.log(message);
	    // toastr default settings
		toastr.options = {
			closeButton: false,
			timeOut: '10000',
  			extendedTimeOut: '3000',
  			positionClass: 'toast-bottom-right'
		};
		// check if message is string
		if (Object.prototype.toString.call(message) === '[object String]' || Object.prototype.toString.call(message) === '[object Boolean]') {
		    // display message
			toastr[options.type]('' + message);

			return message;
		} else if (Object.prototype.toString.call(message) === '[object Array]') {
		    // loop array
		    for (var i = 0; i < message.length; i++) {
		        if (message[i].errCode == 100) {
			        return WAKTOOLS.alert(message[i], options);
			    }
    		};
		} else {
		    // validate if object
		    if (Object.prototype.toString.call(message) === '[object Object]') {
    			if ('result' in message) {
    				return WAKTOOLS.alert(message.result, options);
    			} else if ('message' in message) {
    				return WAKTOOLS.alert(message.message, options);
    			} else if ('successMessage' in message) {
    			    if (options.onSuccess) {
    			        options.onSuccess();
    			        options.onSuccess = null;
    			    }
    				return WAKTOOLS.alert(message.successMessage, options);
    			} else if ('errorMessage' in message) {
    			    options.type = 'error';
    			    if (options.onError) {
    			        options.onError();
    			        options.onError = null;
    			    }
    				return WAKTOOLS.alert(message.errorMessage, options);
    			} else if ('error' in message) {
    			    options.type = 'error';
    			    if (options.onError) {
    			        options.onError();
    			        options.onError = null;
    			    }
    				return WAKTOOLS.alert(message.error, options);
    			} else {
    				throw new Error('Unknown message object');
    			}
		    }
		}
	} catch (e) {
		toastr.error('Es ist ein Fehler aufgetreten. Bitte schliessen sie die Anwendung und versuchen Sie es erneut.');
		console.log(e);
	}
};

/**
 * modal component dialog
 *
 * @param options {Object} options opject
 */

WAKTOOLS.modal = function(options) {
	try {
		var options = options || {},
			width = options.width || 452,
			height = options.height || 250,
			componentPath = options.componentPath || '/components/modal-confirm.waComponent',
			dialog,
			dialogComponent;

		// dialog size
		switch(options.size) {
			case 'medium':
				width = 1024;
				height = 720;
				break;
			case 'full':
				width = window.innerWidth - 80;
				height = window.innerHeight - 80;
				break;
		}
		// component title
		waf.widgets.txtTitle.setValue(options.title);
		// get dialog
		dialog = waf.widgets.modalDialog;
		// set dialog size and position
		dialog.setWidth(width);
		dialog.setHeight(height);
		dialog.setLeft((window.innerWidth - width)/2);
		dialog.setBottom((window.innerHeight - height)/2);
		dialog.displayDialog();
		// get dialog component
		dialogComponent = waf.widgets.modalDialogComponent;
		// remove old web component
		dialogComponent.removeComponent();
		// load new web component
		dialogComponent.loadComponent({
			path: componentPath,
			userData: {
				onConfirm: options.onConfirm,
				onCancel: options.onCancel,
				isModal: true,
				message: options.message,
				value: options.value,
				selectedElementID: options.selectedElementID
			}
		});
	} catch (e) {
		console.log(e);
	}
}

/**
 * tooltip
 *
 * @param selector {String} jQuery selector
 */

WAKTOOLS.tooltip = function(selector) {
	try {
	    var offsetX = 20,
	        offsetY = 10,
	        timeout;

        // add on mouse enter
        $('body').on('mouseenter', selector, function(e) {
            var title = $(this).text();

            timeout = setTimeout(function(){
                $('

').text(title).appendTo('body').css({top: e.pageY + offsetY, left: e.pageX + offsetX}).fadeIn('slow');
            }, 400);
        });
        // remove on mouseleave
         $('body').on('mouseleave', selector, function() {
            clearTimeout(timeout);
            $('.tooltip').remove();
        });
        // set position on mouse move
        $('body').on('mousemove', selector, function(e) {
            $('.tooltip').css({top: e.pageY + offsetY, left: e.pageX + offsetX});
        });
        // remove on click
        $('body').on('click', selector, function() {
            clearTimeout(timeout);
            $('.tooltip').remove();
        });
	} catch (e) {
		console.log(e);
	}
}

/**
 * spinner (font awesome animated spinner icon)
 * http://fortawesome.github.io/Font-Awesome/examples/#animated
 */

WAKTOOLS.Spinner = WAKTOOLS.Spinner || {};

WAKTOOLS.Spinner.show = function () {
    // validate if spinner object exists
    if ($('div.awesome-spinner').length === 0) {
        // add spinner object
        $('

').appendTo('body');
    }
};

WAKTOOLS.Spinner.hide = function () {
    // hide spinner
    $('div.awesome-spinner').remove();
};

/**
 * idle timer
 *
 * @param  {Number}   time in milliseconds
 * @param  {Function} timeout functions
 */

WAKTOOLS.Idle = function(time, timeoutFn) {
	var _this = this;

	// idle time
	_this.idleTime = time;
	// timeout function
	_this.timeoutFn = timeoutFn;
	// add event listeners
    window.addEventListener("mousemove", function(){_this.reset()}, false);
    window.addEventListener("mousedown", function(){_this.reset()}, false);
    window.addEventListener("keypress", function(){_this.reset()}, false);
};

WAKTOOLS.Idle.prototype.startTimer = function() {
	var _this = this;

    // set timout function
    _this.timeoutID = window.setTimeout(function(){
    	_this.timeoutFn();
    }, _this.idleTime);
};

WAKTOOLS.Idle.prototype.reset = function() {
	var _this = this;

	// reset timout
    window.clearTimeout(_this.timeoutID);
    // restart timer
    _this.startTimer();
};


text:
<?php

namespace Drupal\Tests\quickedit\Functional\Jsonapi;

use Drupal\Tests\layout_builder\Functional\Jsonapi\LayoutBuilderEntityViewDisplayTest;

/**
 * JSON:API integration test for the "EntityViewDisplay" config entity type.
 *
 * @group jsonapi
 * @group layout_builder
 * @group quickedit
 */
class QuickEditLayoutBuilderEntityViewDisplayTest extends LayoutBuilderEntityViewDisplayTest {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['quickedit'];

}


text:
import PropTypes from 'prop-types';

import {
  ANCHOR_LEFT,
  ANCHOR_RIGHT,
} from '../dateConstants';

export default PropTypes.oneOf([ANCHOR_LEFT, ANCHOR_RIGHT]);


text:
import {Validate} from '../../util/Validate'
import {Ticklet} from '~/src/tickator/instance/Ticklet'

export class StringIterator extends Ticklet {

  static define(b) {
    b.klass(StringIterator)

    b.comment("Decompose string to characters")

    b.input(b=>{
      b.name("value")
      b.position('left', 0.7)
    })

    b.input(b=>{
      b.name("next")
      b.position('bottom', 0.5)
    })

    b.output(b=>{
      b.name("character")
      b.position('right', 0.7)
    })

    b.size(90, 70)
  }

  initialize() {
    this._shouldSend = true
  }

  tick() {
    this._value = this._value || ''

    if (this.in().value().isTriggering()) {
      this._value = this._value + this.in().value().get()
    }

    if (this.in().next().isTriggering() || this._shouldSend) {
      this._shouldSend = false

      if (this._value.length>0) {
        this.out().character().set(this._value[0])
        this._value = this._value.slice(1)
      } else {
        this._shouldSend = true
      }
    }
  }
}


text:
classdef CondCholFiniteOut < InstancesMapper & PrimitiveSerializable
    %CONDCHOLFINITEOUT Generic conditional mean embedding operator using incomplete
    %Cholesky for outputs using finite-dimensional feature maps.
    % C_{Z|X} where Z is the output, X is the input. This class supports
    % multiple inputs by considering them to be from a tensor product
    % space.
    properties (SetAccess=private)

        In; %X Instances
        Out; %Z matrix
        kfunc; % Kernel
        R; % Cholesky factor of kernel matrix on In
        regparam; %regularization parameter

        % R*R'. Needed in mapInstances()
%         RRT;

        % (Z-Out*R'(RR' + lambda*eye(ra))^-1 R)/lamb. Needed in mapInstances()
        ZOutR3;

    end

    methods

        function this = CondCholFiniteOut(R, In, Out, kfunc, lambda)
            % R = Cholesky factorization of the kernel matrix on the
            % inputs. Assume R is rxn.
            % In = Instances used to compute K with kfunc whose Cholesky
            % factorization is R'*R.
            % Out = dz x n data matrix of mapped (with finite-dimensional feature map)
            % output variable.
            % kfunc = a Kernel
            assert(isa(In, 'Instances'));
            assert(isnumeric(Out));
            assert(isnumeric(R));
            assert(size(R, 2)==size(Out, 2));
            assert(size(Out, 2)==In.count());
            assert(isa(kfunc, 'Kernel'));
            assert(isnumeric(lambda) && lambda >= 0);

            this.In = In;
            if ~all(isfinite(Out))
                error('Out contains non-finite entries');
            end
            this.Out = Out;
            this.kfunc = kfunc;
            this.R = R;
            this.regparam = lambda;

            % L, U factor for (this.RRT + lamb*eye(ra)).
            ra = size(R, 1);
            this.ZOutR3 = (Out - ( (Out*R')/(R*R'+lambda*eye(ra)) )*R)/lambda;
        end

        function Zout = mapInstances(this, Xin)
            % Map Instances in Xin to Zout with this operator.
            % The Instances Xin must be compatible with the Kernel kfunc.
            assert(isa(Xin, 'Instances'));
            R = this.R;
            In = this.In;
            Z = this.Out;
            kfunc = this.kfunc;
            % Generating Krs then multiply may take a lot of memory.
            % Chunk Xin into many subsets.
            %Krs = kfunc.eval(In.getAll(), Xin.getAll());
            %Zout = this.ZOutR3*Krs;

            nte=length(Xin);
            Zout=zeros(size(this.ZOutR3, 1), nte);
            % process (cols) instances at a time
            cols=400;
            fi=1;
            InAll=In.getAll();

            while fi<=nte
                ti=min(fi+cols-1, nte);
                I=fi:ti;
                subIn=Xin.get(I);
                Zout(:, I)=this.ZOutR3*kfunc.eval(InAll, subIn);

                fi=ti+1;
            end
%             B = (R*R' + lamb*eye(ra)) \ RKrs;
%             B = (this.RRT + lamb*eye(ra)) \ RKrs;
%             y = linsolve(this.L, this.P*RKrs, struct('LT', true));
%             B = linsolve(this.U, y, struct('UT', true));
%             Zout = (Z*Krs - (Z*R')*B)/lamb;
        end

        function s = shortSummary(this)
            s = sprintf('%s(r=%d)', mfilename, size(this.R, 1));
        end

        % from PrimitiveSerializable interface
        function s=toStruct(this)
            %In; %X Instances
            %Out; %Z matrix
            %kfunc; % Kernel
            %R; % Cholesky factor of kernel matrix on In
            %regparam; %regularization parameter

            %% (Z-Out*R'(RR' + lambda*eye(ra))^-1 R)/lamb. Needed in mapInstances()
            %ZOutR3;
            %
            s = struct();
            s.className=class(this);
            s.instances = this.In.toStruct();
            s.kfunc = this.kfunc.toStruct();
            % a matrix
            s.ZOutR3 = this.ZOutR3;
        end

    end %end methods

    methods (Static)

        function [Op, C] = learn_operator(In, Out,  op)
            assert(isa(In, 'Instances'));
            [ C] = cond_ho_finiteout( In, Out, op );
            ichol = C.bkernel_ichol;
            kfunc = C.bkernel;
            lambda = C.blambda;
            Op = CondCholFiniteOut(ichol.R, In, Out, kfunc, lambda);
        end

        function [Op, C] = learn_operator_cmaes(In, Out,  op)
            % Learn the ichol operator with blac-box optimization CMA-ES
            assert(isa(In, 'Instances'));
            [ C] = cond_ho_finiteout_cmaes( In, Out, op );
            ichol = C.bkernel_ichol;
            kfunc = C.bkernel;
            lambda = C.blambda;
            Op = CondCholFiniteOut(ichol.R, In, Out, kfunc, lambda);
        end

    end

end


text:
- [x] script tag
- [x] cache
- [x] adapt require api to add ready callback and adapt tests
- [x] remove require augment base object
- [x] finish foundation (more tests)
- [x] maybe rename 'moduler' to 'Modulerjs'
- [x] remove alias
- [x] script loader error handling
- [x] basic path @11th June
- [x] basic module config
- [ ] shim
- [ ] combo handler
- [ ] module blacklist ???needed???
- [ ] add a ready callback for define


text:
'use strict';
var weapons = require('./weapons');

var BOB_MAGNITUDE = 16;
var BOB_TIME = 1.0;
var LEVEL_EXIT_TIME = 0.5;
var LEVEL_ENTER_TIME = 0.5;

////////////////////////////////////////////////////////////////////////
// Door

function Door(level, sprite, info) {
	this.level = level;
	this.sprite = sprite;
	this.target = info.Target;
	if (!this.target) {
		console.warn('Door has no target');
	} else {
		level.gProps.doors[this.target] = this;
	}
	this.confirm = 0;
}
Door.prototype.markerOffset = 64;
Door.prototype.interact = function() {
	var target = this.target;
	if (!this.target) {
		game.sound.play('buzz');
		console.warn('Door has no target');
		return;
	}
	if (this.target === 'exit') {
		this.endGame();
		return;
	}
	if (!(this.target in PATH_MAP.levels)) {
		console.warn('Door goes to invalid level');
		return;
	}
	var level = this.level;
	this.sprite.frame = 1;
	level.setPaused(true);
	level.gProps.setTarget(null);
	game.sound.play('door');
	var timer = game.time.create(true);
	timer.add(
		LEVEL_EXIT_TIME * 1000, function() {
			var st = level.gState;
			st.report('door');
			st.changeLevel(target, 'door', st.level);
		});
	timer.start();
};
Door.prototype.spawnPlayer = function() {
	this.level.gPlayer.spawn(this.sprite.position);
	this.level.setPaused(true);
	this.sprite.frame = 1;
	var timer = game.time.create(true);
	timer.add(
		LEVEL_ENTER_TIME * 1000, function() {
			this.sprite.frame = 0;
			this.level.setPaused(false);
		}, this);
	timer.start();
};
Door.prototype.endGame = function() {
	var level = this.level;
	level.gState.report('end');
	var nweap = level.gState.weapons.length, msg = null;
	switch (nweap) {
	case 0:
		switch (this.confirm++) {
		case 0: msg = 'You just got here.'; break;
		case 1: msg = 'Go find a weapon.'; break;
		case 2: msg = 'Seriously, go explore.'; break;
		case 3: msg = 'Are you still here?'; break;
		case 4: msg = 'You can\'t be serious.'; break;
		case 5: msg = 'Are you a QUITTER?'; break;
		case 6: msg = 'Don\'t break my heart!'; break;
		case 7: msg = 'Last warning!!!!!'; break;
		}
		break;
	case 1:
		switch (this.confirm++) {
		case 0: msg = 'Are you done yet?'; break;
		case 1: msg = 'Really?'; break;
		case 2: msg = 'Okay, I warned you.'; break;
		}
		break;
	case 2:
		switch (this.confirm++) {
		case 0: msg = 'Are you sure?'; break;
		}
	}
	if (msg) {
		game.sound.play('buzz');
		level.alert(msg, false, true);
	} else {
		this.sprite.frame = 1;
		game.sound.play('door');
		var timer = game.time.create(true);
		timer.add(
			1000, function() {
				level.state.start('Final', true, false, level.gState);
			});
		timer.start();
	}
};

////////////////////////////////////////////////////////////////////////
// Chest

function Chest(level, sprite, info) {
	this.level = level;
	this.sprite = sprite;
	this.ident = parseInt(info.Id);
	this.object = info.Object;
	if (!isFinite(this.ident)) {
		console.warn('Chest has no Id / invalid Id', info.Id);
		sprite.name = null;
	} else {
		if (this.ident in level.gProps.chests) {
			console.warn('Duplicate chest:', this.ident);
		} else {
			level.gProps.chests[this.ident] = this;
		}
		if (level.gState.chests.indexOf(this.ident) >= 0) {
			sprite.frame += 4;
			sprite.name = null;
		}
	}
}
Chest.prototype.markerOffset = 48;
Chest.prototype.interact = function() {
	this.sprite.name = null;
	this.level.gState.chests.push(this.ident);

	var level = this.level;
	level.setPaused(true);
	level.gProps.setTarget(null);
	var tsprite, tframe, tfunc, weapon, message = null;
	switch (this.sprite.frame) {
	case 8:
		tsprite = 'hearts';
		tframe = 0;
		tfunc = function(player) { player.addHeart(); };
		break;
	case 9:
		weapon = this.level.gPlayer.getNextWeapon();
		if (weapon) {
			tsprite = 'icons';
			tframe = weapons[weapon].getFrame(true);
			tfunc = function(player) { player.addWeapon(weapon); };
			message = 'Got ' + weapons[weapon].name;
		} else {
			tsprite = 'hearts';
			tframe = 0;
			tfunc = function(player) { player.addHeart(); };
		}
		break;
	case 10:
		tsprite = 'hearts';
		tframe = 3;
		tfunc = function(player) { player.giveDoubleJump(); };
		message = 'Got Double Jump!';
		break;
	default:
		console.error('Bad chest sprite', this.sprite.frame);
		return;
	}
	this.sprite.frame += 4;
	var treasure = level.add.sprite(
		this.sprite.x,
		this.sprite.y - 24,
		tsprite,
		tframe);
	treasure.anchor.setTo(0.5, 0.5);
	var tpre = 0.25, tmove = 1.0;
	var tween = level.add.tween(treasure);
	tween.to(
		{y: this.sprite.y - 96}, tmove * 1000,
		Phaser.Easing.Sinusoidal.InOut,
		true, tpre * 1000, 0, false);
	game.sound.play('fanfare');
	tween.onComplete.addOnce(function() {
		tfunc(this.level.gPlayer);
		if (!message) {
			level.setPaused(false);
		}
		treasure.destroy();
	}, this);
	if (message) {
		level.alert(message, false, true);
	}
};

////////////////////////////////////////////////////////////////////////
// Save point

function SavePoint(level, sprite, info) {
	this.level = level;
	this.sprite = sprite;
	this.ident = info.Id;
	if (typeof this.ident == 'undefined') {
		console.warn('Save point has no Id');
	} else if (this.ident in level.gProps.savePoints) {
		console.warn('Duplicate save point:', this.ident);
	} else {
		level.gProps.savePoints[this.ident] = this;
	}
}
SavePoint.prototype.markerOffset = 48;
SavePoint.prototype.dead = false;
SavePoint.prototype.interact = function() {
	this.level.gPlayer.healFull();
	this.level.gState.save(this.ident);
	this.level.alert('Game saved.');
	game.sound.play('good');
};
SavePoint.prototype.spawnPlayer = function() {
	this.level.gPlayer.spawn(this.sprite.position);
};

////////////////////////////////////////////////////////////////////////
// Prop factories

var PROP_TYPES = {
	0: Door,
	4: SavePoint,
	8: Chest,
	9: Chest,
	10: Chest,
};

////////////////////////////////////////////////////////////////////////
// Prop manager

function Props(level) {
	this.level = level;
	this.group = level.add.group();
	this.objs = {};
	this.counter = 0;
	this.markerSprite = null;
	this.markerTarget = null;
	this.markerTween = null;
	this.doors = {};
	this.chests = {};
	this.savePoints = {};
}

// Spawn a prop from the map.
Props.prototype.spawn = function(index, info) {
	var Constructor = PROP_TYPES[index];
	var sprite = this.group.create(
		info.x + 32, info.y - 32,
		'props', index);
	sprite.anchor.set(0.5, 0.5);
	if (Constructor) {
		var name = 'Prop ' + this.counter;
		this.counter++;
		sprite.name = name;
		var obj = new Constructor(this.level, sprite, info.properties || {});
		game.physics.arcade.enable(sprite);
		this.objs[name] = obj;
	}
};

// Update all props.
Props.prototype.update = function(index, info) {
	var player = this.level.gPlayer.getInteractSprite();
	if (!player) {
		this.setTarget(null);
		return;
	}
	var best_dist = 32, best_sprite = null;
	this.group.forEachAlive(function(sprite) {
		if (!sprite.name) {
			return;
		}
		var u = player.position, v = sprite.position;
		var dist = Math.max(
			Math.abs(u.x - v.x),
			Math.abs(u.y - v.y));
		if (dist < best_dist) {
			best_dist = dist;
			best_sprite = sprite;
		}
	});
	this.setTarget(best_sprite);
};

// Set the interaction target.
Props.prototype.setTarget = function(sprite) {
	if (!sprite) {
		if (this.markerTarget) {
			this.markerSprite.kill();
			this.markerTarget = null;
			this.markerTween.stop();
			this.markerTween = null;
		}
		return;
	}
	var obj = this.objs[sprite.name];
	if (!obj) {
		console.error('Invalid interaction target:', sprite);
		return;
	}
	if (this.markerTarget === obj) {
		return;
	}
	this.markerTarget = obj;
	var tx = sprite.x;
	var ty0 = sprite.y - BOB_MAGNITUDE -obj.markerOffset;
	var ty1 = ty0 + BOB_MAGNITUDE * 2;
	if (!this.markerSprite) {
		this.markerSprite = this.group.create(tx, ty0, 'props', 6);
		this.markerSprite.anchor.setTo(0.5, 0.5);
	} else {
		this.markerSprite.reset(tx, ty0);
	}
	if (this.markerTween) {
		this.markerTween.stop();
		this.markerTween = null;
	}
	this.markerTween = game.add.tween(this.markerSprite);
	this.markerTween.to(
		{x: tx, y: ty1}, BOB_TIME * 500, Phaser.Easing.Sinusoidal.InOut,
		true, 0, -1, true);
};

// Try to interact with something, as the player.
Props.prototype.interact = function() {
	if (!this.markerTarget) {
		game.sound.play('buzz');
	} else {
		this.markerTarget.interact(this.level);
	}
};

// Spawn player from a door.
Props.prototype.spawnPlayerFromDoor = function(ident) {
	var obj = this.doors[ident];
	if (!obj) {
		console.warn('Missing door:', ident);
	} else {
		obj.spawnPlayer();
	}
};

// Spawn player from a save point.
Props.prototype.spawnPlayerFromSavePoint = function(ident) {
	var obj = this.savePoints[ident];
	if (!obj) {
		console.warn('Missing save point:', ident);
	} else {
		obj.spawnPlayer();
	}
};

////////////////////////////////////////////////////////////////////////
// Exports

module.exports = {
	Props: Props,
};


text:
<?php
	return "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
?>


text:
module OnStomp::Failover::Buffers
end

require 'onstomp/failover/buffers/base'
require 'onstomp/failover/buffers/written'
require 'onstomp/failover/buffers/receipts'


text:
import sys
import feed_helpers
import shlex

if len(sys.argv) != 4:
    sys.exit("""Incorrect Parameters! Exiting
                Usage:  consume_blog <input file> <output dir> <language>""")

inputfile = sys.argv[1]
outputdir = sys.argv[2]
language = sys.argv[3]
results = []
with open(inputfile) as f:
    lines = f.readlines()
    # Skip comment lines
    # Read in all others with the values:
    # URL  SITE SEX LANGUAGE
    for l in lines:
        if l[0] != "#":
            result = shlex.split(l)
            results.append(result)

# Now that we read in the results, let's pull down the files for each entry
# using the helper class
for r in results:
    feed_helpers.downloadFeedEntries(r[0], outputdir, "#" + r[0] + " " + r[1] +  " " + r[2] + " " + language + "\n")


text:
set -e
#  Takes 5 mandatory args -
# -e experiement name
# -f Forward Reads
# -r Reverse Reads
# -n number of strains
# -o organism name

# And 3 optional
# -p prokaryotes.txt file
# -g directory of genomes of interest
# -a existing assembly; skip the miniasembly
# hacky way to get the path tho the scripts dir
for prog in skesa pyani nucmer
do
    if hash $prog 2>/dev/null; then
        echo "$prog installed"
    else
        echo "$prog not installed! exiting"
	exit 1
    fi
done

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

PROKFILE=""
NSTRAINS=""
ASSEMBLY=""
ASSEMBLER="skesa"
RREADS=""
GENOMESDIR="./genomes_for_run_ANI/"
USAGE="USAGE:run_ani.sh  -e experiment_name -o 'Organism name' -n 5 -f path/to/reads_f.fastq -r path/to/reads_r.fastq"

# make sure we have enough args (10, because we have 5 flagged arguments)

if [ "$#" -lt 8 ]
then
    echo "Not enough arguments"
    echo $USAGE
    exit 1
fi

while getopts "e:o:n:f:r:p:g:a:s:" opt; do
    case $opt in
	e)
	    NAME=$OPTARG
	    echo "Experiment name: $OPTARG" >&2
	    ;;
	o)
	    ORGNAME=$OPTARG
	    echo "Organism name: $OPTARG" >&2
	    ;;
	n)
	    NSTRAINS=$OPTARG
	    echo "number of strains: $NSTRAINS" >&2
	    ;;
	f)
	    FREADS=$OPTARG
	    echo "file path F reads: $FREADS" >&2
	    ;;
	r)
	    RREADS=$OPTARG
	    echo "file path R reads: $RREADS" >&2
	    ;;
	p)
	    PROKFILE=$OPTARG
	    echo "path to prokaryotes.txt: $PROKFILE" >&2
	    ;;
	g)
	    GENOMESDIR=$OPTARG
	    echo "Genomes dir: $GENOMESDIR" >&2
	    ;;
	a)
	    ASSEMBLY=$OPTARG
	    echo "assembly: $ASSEMBLY" >&2
	    ;;
	s)
	    ASSEMBLER=$OPTARG
	    case "$ASSEMBLER" in
		skesa)
		    # Do stuff
		    ;;
		spades)

		    # Do stuff
		    ;;
		*)
		    echo "Error: assembler must be either spades or skesa"
		    exit 1
		    ;;
	    esac
	    echo "assembler: $ASSEMBLER" >&2
	    ;;
	\?)
	    echo "Invalid option: -$OPTARG" >&2
	    echo $USAGE
	    ;;
	:)
	    echo "Option -$OPTARG requires an argument." >&2
	    exit 1

  esac
done
OUTDIRBASE="./"
OUTDIR="${OUTDIRBASE}`date +%F`_ANI_${NAME}/"
MINIDIR=${OUTDIR}/mini_assembly/
LOGFILE="${OUTDIR}/log.txt"
PYANILOGFILE="${OUTDIR}/pyanilog.txt"
mkdir ${OUTDIR}
mkdir ${MINIDIR}

#############################   Run Mini Assembly  #########################
if [ -s $ASSEMBLY ]
then
    echo "Downsampling reads"  >> "${LOGFILE}"

    mkdir ${OUTDIR}/downsampled_reads/

    {
	echo "seqtk sample -s100 $FREADS 100000 > ${OUTDIR}/downsampled_reads/reads1.fq" >&2
	seqtk sample -s100 $FREADS 100000 > ${OUTDIR}/downsampled_reads/reads1.fq
    } || {
	echo "seqtk sample -s100 $FREADS .1    > ${OUTDIR}/downsampled_reads/reads1.fq" >&2
	seqtk sample -s100 $FREADS .1    > ${OUTDIR}/downsampled_reads/reads1.fq
    }
    if [ ! -s $RREADS ]
    then
	{
	    echo "seqtk sample -s100 $RREADS 100000   > ${OUTDIR}/downsampled_reads/reads1.fq" >&2
	    seqtk sample -s100 $RREADS 100000 > ${OUTDIR}/downsampled_reads/reads2.fq
	} || {
	    echo "seqtk sample -s100 $RREADS .1   > ${OUTDIR}/downsampled_reads/reads1.fq" >&2
	    seqtk sample -s100 $RREADS .1    > ${OUTDIR}/downsampled_reads/reads2.fq
	}
	SPADES_STRING="-1 ${OUTDIR}/downsampled_reads/reads1.fq -2 ${OUTDIR}/downsampled_reads/reads2.fq"
        SKESA_STRING="${OUTDIR}/downsampled_reads/reads1.fq ${OUTDIR}/downsampled_reads/reads2.fq"
    else
	SPADES_STRING="-s ${OUTDIR}/downsampled_reads/reads1.fq"
        SKESA_STRING="${OUTDIR}/downsampled_reads/reads1.fq"
    fi
    echo "running mini assembly"  >> "${LOGFILE}"
    echo "$SPADES_string"
    mkdir ${MINIDIR}/assembly/
    case "$ASSEMBLER" in
	skesa)
	    skesa --fastq $SKESA_STRING --contigs_out ${MINIDIR}/assembly/contigs.fasta
	    ;;
	spades)
	    spades.py $SPADES_STRING -o ${MINIDIR}/assembly/ -t 4 -m 64
	    ;;
    esac

    ASSEMBLY=${MINIDIR}/assembly/contigs.fasta
fi

if [ ! -d "$GENOMESDIR" ]
then
    #GENOMESDIR="${OUTDIR}/genomes_for_run_ANI"
    mkdir $GENOMESDIR
fi

if  [ -z "$(ls -A $GENOMESDIR)" ]
then
    ###################   Get potenetial close genomes  #########################
    echo "Get potenetial close genomes"  >> "${LOGFILE}"
    if [ ! -s "$PROKFILE" ]
    then
        PROKFILE="./prokaryotes.txt"  # default, so we dont pass empty args below
    fi
    echo "${SCRIPTPATH}/select_ref_by_ANI/get_n_random_complete_genomes.sh -o \"$ORGNAME\" -n $NSTRAINS -f $PROKFILE > ${OUTDIR}/accessions "
    ${SCRIPTPATH}/select_ref_by_ANI/get_n_random_complete_genomes.sh -o "$ORGNAME" -n $NSTRAINS -f $PROKFILE > ${OUTDIR}/accessions

    #######################   Download close genomes  ###########################
    echo "Downloading genomes"  >> "${LOGFILE}"

    while read accession
    do
	get_genomes.py -q $accession -o $GENOMESDIR   >> "${LOGFILE}"2>&1
    done < $OUTDIR/accessions
else
    echo "using existing genomes directory"   >> "${LOGFILE}"
    # delete any existing "conigs.fasta" file from the dir, as those would be from old runs.
    # probaly shoudl make this a try/catch thingy
    # {
    # 	rm "${GENOMESDIR}/contigs_*.*"
    # } || {
    # 	echo "no need to clean genomes dir" &>> "${LOGFILE}"
    # }
fi

echo "copy the mini_assembly result to the potential genomes dir"  >> "${LOGFILE}"
cp $ASSEMBLY $GENOMESDIR/contigs_${NAME}.fasta

##########################   Run ANI analysis  ###############################
echo "Running pyani index"   >> "${LOGFILE}"
if [ -f "$GENOMESDIR/labels.txt" ]
then
    rm $GENOMESDIR/labels.txt
fi
if [ -f "$GENOMESDIR/classes.txt" ]
then
    rm $GENOMESDIR/classes.txt
fi
echo "pyani index $GENOMESDIR -v -l $PYANILOGFILE"  >&2
pyani index $GENOMESDIR -v -l $PYANILOGFILE >> "${LOGFILE}" 2>&1
echo "recreating pyani labels"   >> "${LOGFILE}"
# then fix the columns; we dont care about the name
paste <(cut -f 1,2 $GENOMESDIR/classes.txt) <(cut -f 2 $GENOMESDIR/classes.txt) > tmp_classes
mv tmp_classes $GENOMESDIR/classes.txt
paste <(cut -f 1,2 $GENOMESDIR/labels.txt) <(cut -f 2 $GENOMESDIR/labels.txt) > tmp_labels
mv tmp_labels $GENOMESDIR/labels.txt

if [ -d .pyani ]
then
    echo "pyani db already exists" >> $PYANILOGFILE
else
    echo "pyani createdb"  >&2
    pyani createdb >> "${LOGFILE}" 2>&1
fi

echo "Running pyani anim"   >> "${LOGFILE}"
echo "pyani anim $GENOMESDIR $OUTDIR/pyani --workers 64  -v -l $PYANILOGFILE --labels $GENOMESDIR/labels.txt --classes $GENOMESDIR/classes.txt"  >&2
pyani anim $GENOMESDIR $OUTDIR/pyani --workers 64  -v -l $PYANILOGFILE --labels $GENOMESDIR/labels.txt --classes $GENOMESDIR/classes.txt >> "${LOGFILE}" 2>&1

echo "Generating report of pyani runs"   >> "${LOGFILE}"
echo "pyani report -v -l $PYANILOGFILE --runs $OUTDIR/pyani "  >&2
pyani report -v -l $PYANILOGFILE --runs $OUTDIR/pyani  >> "${LOGFILE}" 2>&1

echo "Getting name of most recent pyani run"   >> "${LOGFILE}"
this_run=$(tail -n 1 $OUTDIR/pyani/runs.tab | cut -f 1)

echo "Generating genome comparison matrix"   >> "${LOGFILE}"
echo "pyani report -v -l $PYANILOGFILE --run_matrices $this_run $OUTDIR/pyani "  >&2
pyani report -v -l $PYANILOGFILE --run_matrices $this_run $OUTDIR/pyani >> "${LOGFILE}" 2>&1

# average_nucleotide_identity.py -v -i $GENOMESDIR -g -o $OUTDIR/pyani  &>> "${LOGFILE}"

############# remove contigs from genomes dir if we plan on reusing   ########
# rm $GENOMESDIR/contigs.fasta
rm $GENOMESDIR/contigs_${NAME}.fasta
rm $GENOMESDIR/contigs_${NAME}.md5
# rm $GENOMESDIR/labels.txt
# rm $GENOMESDIR/classes.txt
# extract best hit
echo "extract best hit"  >> "${LOGFILE}"
echo "python ${SCRIPTPATH}/select_ref_by_ANI/parse_closest_ANI.py $OUTDIR/pyani/matrix_identity_${this_run}.tab > ${OUTDIR}/best_reference"  >&2
python ${SCRIPTPATH}/select_ref_by_ANI/parse_closest_ANI.py $OUTDIR/pyani/matrix_identity_${this_run}.tab > ${OUTDIR}/best_reference

bestref=$(cat ${OUTDIR}/best_reference)
# this should be the only line going to stdout
echo -e "${NAME}\t${bestref}"


text:
"""This example adds various types of targeting criteria to a given campaign.

To get campaigns, run get_campaigns.py.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

from googleads import adwords

CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
# Replace the value below with the ID of a feed that has been configured for
# location targeting, meaning it has an ENABLED FeedMapping with criterionType
# of 77. Feeds linked to a GMB account automatically have this FeedMapping.
# If you don't have such a feed, set this value to None.
LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE'

def main(client, campaign_id, location_feed_id=None):
  # Initialize appropriate service.
  campaign_criterion_service = client.GetService(
      'CampaignCriterionService', version='v201802')

  # Create locations. The IDs can be found in the documentation or retrieved
  # with the LocationCriterionService.
  california = {
      'xsi_type': 'Location',
      'id': '21137'
  }
  mexico = {
      'xsi_type': 'Location',
      'id': '2484'
  }

  # Create languages. The IDs can be found in the documentation or retrieved
  # with the ConstantDataService.
  english = {
      'xsi_type': 'Language',
      'id': '1000'
  }
  spanish = {
      'xsi_type': 'Language',
      'id': '1003'
  }

  # Create a negative campaign criterion operation.
  negative_campaign_criterion_operand = {
      'xsi_type': 'NegativeCampaignCriterion',
      'campaignId': campaign_id,
      'criterion': {
          'xsi_type': 'Keyword',
          'matchType': 'BROAD',
          'text': 'jupiter cruise'
      }
  }
  criteria = [california, mexico, english, spanish]
  if location_feed_id:
      # Distance targeting. Area of 10 miles around targets above.
    criteria.append({
        'xsi_type': 'LocationGroups',
        'feedId': location_feed_id,
        'matchingFunction': {
            'operator': 'IDENTITY',
            'lhsOperand': [{
                'xsi_type': 'LocationExtensionOperand',
                'radius': {
                    'xsi_type': 'ConstantOperand',
                    'type': 'DOUBLE',
                    'unit': 'MILES',
                    'doubleValue': 10
                }
            }]
        }
    })
  # Create operations
  operations = []
  for criterion in criteria:
    operations.append({
        'operator': 'ADD',
        'operand': {
            'campaignId': campaign_id,
            'criterion': criterion
        }
    })
  # Add the negative campaign criterion.
  operations.append({
      'operator': 'ADD',
      'operand': negative_campaign_criterion_operand
  })

  # Make the mutate request.
  result = campaign_criterion_service.mutate(operations)

  # Display the resulting campaign criteria.
  for campaign_criterion in result['value']:
    print ('Campaign criterion with campaign id "%s", criterion id "%s", '
           'and type "%s" was added.'
           % (campaign_criterion['campaignId'],
              campaign_criterion['criterion']['id'],
              campaign_criterion['criterion']['type']))

if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()

  main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID)


text:
package org.lpw.ranch.link;

import org.lpw.tephra.dao.orm.PageList;

import java.util.Map;
import java.util.Set;

/**
 * @author lpw
 */
interface LinkDao {
    PageList<LinkModel> query1(String type, String id1, int pageSize, int pageNum);

    PageList<LinkModel> query2(String type, String id2, int pageSize, int pageNum);

    PageList<LinkModel> query1(String type, Set<String> id1s, int pageSize, int pageNum);

    PageList<LinkModel> query2(String type, Set<String> id2s, int pageSize, int pageNum);

    int count(String type, String id1, String id2);

    Map<String, Integer> count1(String type, Set<String> id1s);

    Map<String, Integer> count2(String type, Set<String> id1s);

    LinkModel find(String type, String id1, String id2);

    void save(LinkModel link);

    void delete(String type, String id1, String id2);
}


text:
/**
 * Contains all tuple classes related to the graph grouping operator implementations.
 */
package org.gradoop.flink.model.impl.operators.grouping.tuples;


text:
module Pione
  module Package
    # PackageReader is a reader for packages.
    class PackageReader
      class << self
        # Read a pacakge from the location.
        def read(location)
          case PackageTypeClassifier.classify(location)
          when :directory
            DirectoryPackageReader.new(location).read
          when :git
            GitPackageReader.new(location).read
          when :archive
            ArchivePackageReader.new(location).read
          when :document
            SingleDocumentPackageReader.new(location).read
          end
        end
      end

      def initialize(location)
        @location = location
        @local = nil
        @package_info = read_package_info
      end

      def read
        raise NotImplementedError
      end

      private

      # Read informations from the package location.
      def read_package_info
        PackageInfo.load((@location + "pione-package.json").read)
      rescue Location::NotFound
        raise InvalidPackage.new(self, "pione-package.json not found in %s" % @location.uri)
      end

      #
      # @return [Package]
      #   the package
      def read_document
        opt = {package_name: "Anonymous", filename: @location.basename}
        context = Document.load(@location, opt)
        Package.new(info: {"PackageName" => "Anonymous"}, context: context)
      end

      # Find scenarios from the package location.
      #
      # @return [Array<PackageScenario>]
      #   scenarios
      def find_scenario_paths(scenarios)
        return [] if scenarios.nil?
        scenarios.select do |path|
          (@location + path + "scenario.yml").exist?
        end.uniq.compact
      end
    end

    # PackageTypeClassifier provides the function to distinguish package types.
    module PackageTypeClassifier
      class << self
        # Distinguish the type of package based on the location.
        #
        # @param [BasicLocation]
        #   location of the package
        # @return [Symbol]
        #   package type
        def classify(location)
          return :git if git?(location)
          return :archive if archive?(location)
          return :document if document?(location)
          return :directory
        end

        private

        # Return true if the location represents git package.
        def git?(location)
          location.location_type == :git_repository
        end

        # Return true if the location represents archive package.
        def archive?(location)
          location.file? and location.extname == ".ppg"
        end

        # Return true if the location represents document package.
        def document?(location)
          location.file? and location.extname == ".pione"
        end
      end
    end

    # DirectoryPackageReader reads package structure from directory based
    # package.
    class DirectoryPackageReader < PackageReader
      def initialize(location)
        @location = location
      end

      def read
        # copy to local
        local_location = make_local_location

        # cache
        digest = PackageCache.cache(local_location)

        PackageHandler.new(PackageCache.directory_cache(digest), digest: digest)
      end

      def make_local_location
        # make temporary directory
        local_location = Location[Temppath.create]

        # pione-package.json
        info = PackageInfo.read((@location + "pione-package.json").read)
        (@location + "pione-package.json").copy(local_location + "pione-package.json")

        # copy files
        (info.documents + info.bins + info.etcs).each do |path|
          (@location + path).copy(local_location + path)
        end

        # scenarios
        info.scenarios.each do |path|
          scenario_info = ScenarioInfo.read((@location + path + "pione-scenario.json").read)
          (@location + path + "pione-scenario.json").copy(local_location + path + "pione-scenario.json")
          (@location + path + "Scenario.pione").copy(local_location + path + "Scenario.pione")
          (scenario_info.inputs + scenario_info.outputs).each do |_path|
            (@location + path + _path).copy(local_location + path + _path)
          end
        end

        return local_location
      rescue Location::LocationError => e
        raise InvalidPackage.new("package \"%s\" is invalid: %s" % [@location.address, e.message])
      end
    end

    # GitPackageReader is a reader for git based package.
    class GitPackageReader < PackageReader
      def initialize(location)
        @location = location
      end

      def read
        local_location = make_local_location
        digest = PackageCache.cache(local_location)
        return PackageHandler.new(PackageCache.directory_cache(digest), digest: digest)
      end

      private

      def make_local_location
        # we should use local cloned repository, but currently export
        local_location = Location[Temppath.mkdir]
        @location.export(local_location)
        return local_location
      end
    end

    # ArchivePackageReader is a reader for PPG pakage.
    class ArchivePackageReader < PackageReader
      def initialize(location)
        @location = location # arbitrary data location
      end

      def read
        # copy to local, we cannot use Location::DataLocation#local in here
        # because the method don't keep filename
        local_location = Location[Temppath.mkdir] + @location.basename
        @location.copy(local_location)

        # cache the package
        digest = PackageCache.cache(local_location)

        return PackageHandler.new(PackageCache.directory_cache(digest), digest: digest)
      end
    end

    # SingleDocumentPackageReader is a reader for single document package.
    class SingleDocumentPackageReader < PackageReader
      def initialize(location)
        @location = location
      end

      def read
        # copy to local
        local_location = @location.local

        # make package info by scanning annotations
        info = PackageScanner.new(local_location).scan

        return PackageHandler.new(local_location.dirname, info: info)
      end
    end
  end
end


text:
package org.jbpm.workbench.ht.client.editors;

import java.util.function.Predicate;

import javax.enterprise.event.Event;
import javax.inject.Inject;

import org.jbpm.workbench.ht.model.events.AbstractTaskEvent;
import org.jbpm.workbench.ht.model.events.TaskSelectionEvent;
import org.uberfire.workbench.events.NotificationEvent;

public abstract class AbstractTaskPresenter {

    private Long taskId;
    private String serverTemplateId;
    private String containerId;

    private Event<NotificationEvent> notification;

    @Inject
    public void setNotification(final Event<NotificationEvent> notification) {
        this.notification = notification;
    }

    public void displayNotification(String text) {
        notification.fire(new NotificationEvent(text));
    }

    protected Predicate<AbstractTaskEvent> isSameTaskFromEvent() {
        return e -> e.getServerTemplateId().equals(serverTemplateId) && e.getContainerId().equals(containerId) && e.getTaskId().equals(taskId);
    }

    protected void setSelectedTask(final TaskSelectionEvent event){
        taskId = event.getTaskId();
        serverTemplateId = event.getServerTemplateId();
        containerId = event.getContainerId();
    }

    public Long getTaskId() {
        return taskId;
    }

    public String getContainerId() {
        return containerId;
    }

    public String getServerTemplateId() {
        return serverTemplateId;
    }
}


text:
package com.intirix.openmm.server.ui.html.pages.beans;

import org.simpleframework.xml.Default;

@Default
public class TvdbEpisodeBean
{

	private String id = "";

	private String name = "";

	private String rating = "";

	private String firstAired;

	private int seasonNumber;

	private int episodeNumber;

	private int dvdEpisodeNumber;

	private String description = "";

	private String banner = "";

	public String getId()
	{
		return id;
	}

	public void setId( String id )
	{
		if ( id != null )
		{
			this.id = id;
		}
	}

	public String getName()
	{
		return name;
	}

	public void setName( String name )
	{
		if ( name != null )
		{
			this.name = name;
		}
	}

	public String getRating()
	{
		return rating;
	}

	public void setRating( String rating )
	{
		if ( rating != null )
		{
			this.rating = rating;
		}
	}

	public String getFirstAired()
	{
		return firstAired;
	}

	public void setFirstAired( String firstAired )
	{
		this.firstAired = firstAired;
	}

	public int getSeasonNumber()
	{
		return seasonNumber;
	}

	public void setSeasonNumber( int seasonNumber )
	{
		this.seasonNumber = seasonNumber;
	}

	public int getEpisodeNumber()
	{
		return episodeNumber;
	}

	public void setEpisodeNumber( int episodeNumber )
	{
		this.episodeNumber = episodeNumber;
	}

	public int getDvdEpisodeNumber()
	{
		return dvdEpisodeNumber;
	}

	public void setDvdEpisodeNumber( int dvdEpisodeNumber )
	{
		this.dvdEpisodeNumber = dvdEpisodeNumber;
	}

	public String getDescription()
	{
		return description;
	}

	public void setDescription( String description )
	{
		if ( description != null )
		{
			this.description = description;
		}
	}

	public String getBanner()
	{
		return banner;
	}

	public void setBanner( String banner )
	{
		if ( banner != null )
		{
			this.banner = banner;
		}
	}

}


text:
const crossFetch = require('cross-fetch')
global.fetch = crossFetch
global.Response = crossFetch.Response
global.Headers = crossFetch.Headers
global.Request = crossFetch.Request

if (!Promise) {
  Promise = require('promise-polyfill')
} else if (!Promise.finally) {
  Promise.finally = require('promise-polyfill').finally
}

const ActualResponse = Response

function responseWrapper(body, init) {
  if (
    body &&
    typeof body.constructor === 'function' &&
    body.constructor.__isFallback
  ) {
    const response = new ActualResponse(null, init)
    response.body = body

    const actualClone = response.clone
    response.clone = () => {
      const clone = actualClone.call(response)
      const [body1, body2] = body.tee()
      response.body = body1
      clone.body = body2
      return clone
    }

    return response
  }

  return new ActualResponse(body, init)
}

function responseInit(resp, init) {
  if (typeof resp.init === 'object') {
    return resp.init
  } else {
    init = Object.assign({}, init || {})
    for (const field of ['status', 'statusText', 'headers', 'url']) {
      if (field in resp) {
        init[field] = resp[field]
      }
    }
    return init
  }
}

function requestMatches(urlOrPredicate) {
  const predicate =
    urlOrPredicate instanceof RegExp
      ? input => urlOrPredicate.test(input.url)
      : typeof urlOrPredicate === 'string'
      ? input => input.url === urlOrPredicate
      : urlOrPredicate
  return (input, reqInit) => {
    const req = normalizeRequest(input, reqInit)
    return [predicate(req), req]
  }
}

function requestNotMatches(urlOrPredicate) {
  const matches = requestMatches(urlOrPredicate)
  return input => {
    const result = matches(input)
    return [!result[0], result[1]]
  }
}

function staticMatches(value) {
  return (input, reqInit) => {
    return [value, normalizeRequest(input, reqInit)]
  }
}

const isFn = unknown => typeof unknown === 'function'

const isMocking = jest.fn(staticMatches(true))

const abortError = () =>
  new DOMException('The operation was aborted. ', 'AbortError')

const abort = () => {
  throw abortError()
}

const abortAsync = () => {
  return Promise.reject(abortError())
}

const normalizeResponse = (bodyOrFunction, init) => (input, reqInit) => {
  const [mocked, request] = isMocking(input, reqInit)
  return mocked
    ? isFn(bodyOrFunction)
      ? bodyOrFunction(request).then(resp => {
          if (request.signal && request.signal.aborted) {
            abort()
          }
          return typeof resp === 'string'
            ? responseWrapper(resp, init)
            : responseWrapper(resp.body, responseInit(resp, init))
        })
      : new Promise((resolve, reject) => {
          if (request.signal && request.signal.aborted) {
            reject(abortError())
            return
          }
          resolve(responseWrapper(bodyOrFunction, init))
        })
    : crossFetch.fetch(input, reqInit)
}

const normalizeRequest = (input, reqInit) => {
  if (input instanceof Request) {
    if (input.signal && input.signal.aborted) {
      abort()
    }
    return input
  } else if (typeof input === 'string') {
    if (reqInit && reqInit.signal && reqInit.signal.aborted) {
      abort()
    }
    return new Request(input, reqInit)
  } else {
    throw new TypeError('Unable to parse input as string or Request')
  }
}

const normalizeError = errorOrFunction =>
  isFn(errorOrFunction)
    ? errorOrFunction
    : () => Promise.reject(errorOrFunction)

const fetch = jest.fn(normalizeResponse(''))
fetch.Headers = Headers
fetch.Response = responseWrapper
fetch.Request = Request
fetch.mockResponse = (bodyOrFunction, init) =>
  fetch.mockImplementation(normalizeResponse(bodyOrFunction, init))

fetch.mockReject = errorOrFunction =>
  fetch.mockImplementation(normalizeError(errorOrFunction))

fetch.mockAbort = () => fetch.mockImplementation(abortAsync)
fetch.mockAbortOnce = () => fetch.mockImplementationOnce(abortAsync)

const mockResponseOnce = (bodyOrFunction, init) =>
  fetch.mockImplementationOnce(normalizeResponse(bodyOrFunction, init))

fetch.mockResponseOnce = mockResponseOnce

fetch.once = mockResponseOnce

fetch.mockRejectOnce = errorOrFunction =>
  fetch.mockImplementationOnce(normalizeError(errorOrFunction))

fetch.mockResponses = (...responses) => {
  responses.forEach(response => {
    if (Array.isArray(response)) {
      const [body, init] = response
      fetch.mockImplementationOnce(normalizeResponse(body, init))
    } else {
      fetch.mockImplementationOnce(normalizeResponse(response))
    }
  })
  return fetch
}

fetch.isMocking = (req, reqInit) => isMocking(req, reqInit)[0]

fetch.mockIf = fetch.doMockIf = (urlOrPredicate, bodyOrFunction, init) => {
  isMocking.mockImplementation(requestMatches(urlOrPredicate))
  if (bodyOrFunction) {
    fetch.mockResponse(bodyOrFunction, init)
  }
  return fetch
}

fetch.dontMockIf = (urlOrPredicate, bodyOrFunction, init) => {
  isMocking.mockImplementation(requestNotMatches(urlOrPredicate))
  if (bodyOrFunction) {
    fetch.mockResponse(bodyOrFunction, init)
  }
  return fetch
}

fetch.mockOnceIf = fetch.doMockOnceIf = (
  urlOrPredicate,
  bodyOrFunction,
  init
) => {
  isMocking.mockImplementationOnce(requestMatches(urlOrPredicate))
  if (bodyOrFunction) {
    mockResponseOnce(bodyOrFunction, init)
  }
  return fetch
}

fetch.dontMockOnceIf = (urlOrPredicate, bodyOrFunction, init) => {
  isMocking.mockImplementationOnce(requestNotMatches(urlOrPredicate))
  if (bodyOrFunction) {
    mockResponseOnce(bodyOrFunction, init)
  }
  return fetch
}

fetch.dontMock = () => {
  isMocking.mockImplementation(staticMatches(false))
  return fetch
}

fetch.dontMockOnce = () => {
  isMocking.mockImplementationOnce(staticMatches(false))
  return fetch
}

fetch.doMock = (bodyOrFunction, init) => {
  isMocking.mockImplementation(staticMatches(true))
  if (bodyOrFunction) {
    fetch.mockResponse(bodyOrFunction, init)
  }
  return fetch
}

fetch.mockOnce = fetch.doMockOnce = (bodyOrFunction, init) => {
  isMocking.mockImplementationOnce(staticMatches(true))
  if (bodyOrFunction) {
    mockResponseOnce(bodyOrFunction, init)
  }
  return fetch
}

fetch.resetMocks = () => {
  fetch.mockReset()
  isMocking.mockReset()

  // reset to default implementation with each reset
  fetch.mockImplementation(normalizeResponse(''))
  fetch.doMock()
  fetch.isMocking = isMocking
}

fetch.enableMocks = fetch.enableFetchMocks = () => {
  global.fetchMock = global.fetch = fetch
  try {
    jest.setMock('node-fetch', fetch)
  } catch (error) {
    //ignore
  }
}

fetch.disableMocks = fetch.disableFetchMocks = () => {
  global.fetch = crossFetch
  try {
    jest.dontMock('node-fetch')
  } catch (error) {
    //ignore
  }
}

module.exports = fetch.default = fetch


text:
#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
#include <xmmintrin.h>
#endif

#include <Kokkos_Macros.hpp>
#if defined( KOKKOS_ATOMIC_HPP ) && ! defined( KOKKOS_ATOMIC_COMPARE_EXCHANGE_STRONG_HPP )
#define KOKKOS_ATOMIC_COMPARE_EXCHANGE_STRONG_HPP

namespace Kokkos {

//----------------------------------------------------------------------------
// Cuda native CAS supports int, unsigned int, and unsigned long long int (non-standard type).
// Must cast-away 'volatile' for the CAS call.

#if defined( KOKKOS_ENABLE_CUDA )

#if defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND)
__inline__ __device__
int atomic_compare_exchange( volatile int * const dest, const int compare, const int val)
{ return atomicCAS((int*)dest,compare,val); }

__inline__ __device__
unsigned int atomic_compare_exchange( volatile unsigned int * const dest, const unsigned int compare, const unsigned int val)
{ return atomicCAS((unsigned int*)dest,compare,val); }

__inline__ __device__
unsigned long long int atomic_compare_exchange( volatile unsigned long long int * const dest ,
                                                const unsigned long long int compare ,
                                                const unsigned long long int val )
{ return atomicCAS((unsigned long long int*)dest,compare,val); }

template < typename T >
__inline__ __device__
T atomic_compare_exchange( volatile T * const dest , const T & compare ,
  typename Kokkos::Impl::enable_if< sizeof(T) == sizeof(int) , const T & >::type val )
{
  const int tmp = atomicCAS( (int*) dest , *((int*)&compare) , *((int*)&val) );
  return *((T*)&tmp);
}

template < typename T >
__inline__ __device__
T atomic_compare_exchange( volatile T * const dest , const T & compare ,
  typename Kokkos::Impl::enable_if< sizeof(T) != sizeof(int) &&
                                    sizeof(T) == sizeof(unsigned long long int) , const T & >::type val )
{
  typedef unsigned long long int type ;
  const type tmp = atomicCAS( (type*) dest , *((type*)&compare) , *((type*)&val) );
  return *((T*)&tmp);
}

template < typename T >
__inline__ __device__
T atomic_compare_exchange( volatile T * const dest , const T & compare ,
    typename Kokkos::Impl::enable_if<
                  ( sizeof(T) != 4 )
               && ( sizeof(T) != 8 )
             , const T >::type& val )
{
  T return_val;
  // This is a way to (hopefully) avoid dead lock in a warp
  int done = 0;
  unsigned int active = __ballot(1);
  unsigned int done_active = 0;
  while (active!=done_active) {
    if(!done) {
      if( Impl::lock_address_cuda_space( (void*) dest ) ) {
        return_val = *dest;
        if( return_val == compare )
          *dest = val;
        Impl::unlock_address_cuda_space( (void*) dest );
        done = 1;
      }
    }
    done_active = __ballot(done);
  }
  return return_val;
}
#endif
#endif

//----------------------------------------------------------------------------
// GCC native CAS supports int, long, unsigned int, unsigned long.
// Intel native CAS support int and long with the same interface as GCC.
#if !defined(KOKKOS_ENABLE_ROCM_ATOMICS)
#if !defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND)
#if defined(KOKKOS_ENABLE_GNU_ATOMICS) || defined(KOKKOS_ENABLE_INTEL_ATOMICS)

inline
int atomic_compare_exchange( volatile int * const dest, const int compare, const int val)
{
#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
  _mm_prefetch( (const char*) dest, _MM_HINT_ET0 );
#endif
  return __sync_val_compare_and_swap(dest,compare,val);
}

inline
long atomic_compare_exchange( volatile long * const dest, const long compare, const long val )
{
#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
  _mm_prefetch( (const char*) dest, _MM_HINT_ET0 );
#endif
  return __sync_val_compare_and_swap(dest,compare,val);
}

#if defined( KOKKOS_ENABLE_GNU_ATOMICS )

// GCC supports unsigned

inline
unsigned int atomic_compare_exchange( volatile unsigned int * const dest, const unsigned int compare, const unsigned int val )
{ return __sync_val_compare_and_swap(dest,compare,val); }

inline
unsigned long atomic_compare_exchange( volatile unsigned long * const dest ,
                                       const unsigned long compare ,
                                       const unsigned long val )
{ return __sync_val_compare_and_swap(dest,compare,val); }

#endif

template < typename T >
inline
T atomic_compare_exchange( volatile T * const dest, const T & compare,
  typename Kokkos::Impl::enable_if< sizeof(T) == sizeof(int) , const T & >::type val )
{
  union U {
    int i ;
    T t ;
    KOKKOS_INLINE_FUNCTION U() {};
  } tmp ;

#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
  _mm_prefetch( (const char*) dest, _MM_HINT_ET0 );
#endif

  tmp.i = __sync_val_compare_and_swap( (int*) dest , *((int*)&compare) , *((int*)&val) );
  return tmp.t ;
}

template < typename T >
inline
T atomic_compare_exchange( volatile T * const dest, const T & compare,
  typename Kokkos::Impl::enable_if< sizeof(T) != sizeof(int) &&
                                    sizeof(T) == sizeof(long) , const T & >::type val )
{
  union U {
    long i ;
    T t ;
    KOKKOS_INLINE_FUNCTION U() {};
  } tmp ;

#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
  _mm_prefetch( (const char*) dest, _MM_HINT_ET0 );
#endif

  tmp.i = __sync_val_compare_and_swap( (long*) dest , *((long*)&compare) , *((long*)&val) );
  return tmp.t ;
}

#if defined( KOKKOS_ENABLE_ASM) && defined ( KOKKOS_ENABLE_ISA_X86_64 )
template < typename T >
inline
T atomic_compare_exchange( volatile T * const dest, const T & compare,
  typename Kokkos::Impl::enable_if< sizeof(T) != sizeof(int) &&
                                    sizeof(T) != sizeof(long) &&
                                    sizeof(T) == sizeof(Impl::cas128_t), const T & >::type val )
{
  union U {
    Impl::cas128_t i ;
    T t ;
    KOKKOS_INLINE_FUNCTION U() {};
  } tmp ;

#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
  _mm_prefetch( (const char*) dest, _MM_HINT_ET0 );
#endif

  tmp.i = Impl::cas128( (Impl::cas128_t*) dest , *((Impl::cas128_t*)&compare) , *((Impl::cas128_t*)&val) );
  return tmp.t ;
}
#endif

template < typename T >
inline
T atomic_compare_exchange( volatile T * const dest , const T compare ,
    typename Kokkos::Impl::enable_if<
                  ( sizeof(T) != 4 )
               && ( sizeof(T) != 8 )
            #if defined(KOKKOS_ENABLE_ASM) && defined ( KOKKOS_ENABLE_ISA_X86_64 )
               && ( sizeof(T) != 16 )
            #endif
             , const T >::type& val )
{
#if defined( KOKKOS_ENABLE_RFO_PREFETCH )
  _mm_prefetch( (const char*) dest, _MM_HINT_ET0 );
#endif

  while( !Impl::lock_address_host_space( (void*) dest ) );
  T return_val = *dest;
  if( return_val == compare ) {
    // Don't use the following line of code here:
    //
    //const T tmp = *dest = val;
    //
    // Instead, put each assignment in its own statement.  This is
    // because the overload of T::operator= for volatile *this should
    // return void, not volatile T&.  See Kokkos #177:
    //
    // https://github.com/kokkos/kokkos/issues/177
    *dest = val;
    const T tmp = *dest;
    #ifndef KOKKOS_COMPILER_CLANG
    (void) tmp;
    #endif
  }
  Impl::unlock_address_host_space( (void*) dest );
  return return_val;
}
//----------------------------------------------------------------------------

#elif defined( KOKKOS_ENABLE_OPENMP_ATOMICS )

template< typename T >
KOKKOS_INLINE_FUNCTION
T atomic_compare_exchange( volatile T * const dest, const T compare, const T val )
{
  T retval;
#pragma omp critical
  {
    retval = dest[0];
    if ( retval == compare )
        dest[0] = val;
  }
  return retval;
}

#endif
#endif
#endif // !defined ROCM_ATOMICS

template <typename T>
KOKKOS_INLINE_FUNCTION
bool atomic_compare_exchange_strong(volatile T* const dest, const T compare, const T val)
{
  return compare == atomic_compare_exchange(dest, compare, val);
}
//----------------------------------------------------------------------------

} // namespace Kokkos

#endif


text:
import os
import fnmatch
import re

from tests.performance.query import Query
from tests.util.test_file_parser import parse_query_test_file

class Workload(object):
  """Represents a workload.

  A workload is the internal representation for the set of queries on a dataset. It
  consists of the dataset name, and a mapping of query names to query strings.

  Args:
    name (str): workload name. (Eg. tpch)
    query_name_filters (list of str): List of regular expressions used for matching query
      names

  Attributes:
    name (str): workload name (Eg. tpch)
    _query_map (dict): contains a query name -> string mapping; mapping of query name to
      section (ex. "TPCH-Q10" -> "select * from...")
  """

  WORKLOAD_DIR = os.environ['IMPALA_WORKLOAD_DIR']

  def __init__(self, name, query_name_filters=None):
    self._name = name
    self._query_map = dict()
    # Build the query name -> string mapping in the c'tor. We want to fail fast and early
    # if the user input is bad.
    self._validate_and_load(query_name_filters)

  @property
  def name(self):
    return self._name

  @property
  def query_map(self):
    return self._query_map

  def _validate_and_load(self, query_name_filters):
    """Validates that the Workload is legal."""
    query_name_filters = map(str.strip, query_name_filters) if query_name_filters else []
    self._base_dir = os.path.join(Workload.WORKLOAD_DIR, self._name, 'queries')
    # Check whether the workload name corresponds to an existing directory.
    if not os.path.isdir(self._base_dir):
      raise ValueError("Workload %s not found in %s" % (self._name, self._base_dir))
    sections = list()
    # Parse all queries files for the given workload.
    for file_name in self._list_query_files():
      sections.extend(parse_query_test_file(file_name))
    # If the user has specified query names, check whether all the user specified queries
    # exist in the query files.
    all_query_names = [s['QUERY_NAME'] for s in sections if s['QUERY_NAME'].strip()]
    regex = re.compile(r'|'.join(['^%s$' % n for n in query_name_filters]), re.I)
    matched_query_names = filter(lambda x: re.match(regex, x), all_query_names)
    assert len(matched_query_names) > 0, "No matching queries found for %s" % self._name
    # Filter the sections based on the queries the user wants.
    sections = filter(lambda x: x['QUERY_NAME'] in matched_query_names, sections)
    # Add the filtered queries to the query map
    for section in sections:
      self._query_map[section['QUERY_NAME']] = section['QUERY']

  def _list_query_files(self):
    """Return a list of all the .test files that contain queries"""
    query_files = list()
    for root, dirs, file_names in os.walk(self._base_dir):
      for file_name in fnmatch.filter(file_names, '*.test'):
        query_files.append(os.path.join(root, file_name))
    assert len(query_files) > 0, "No Query Files found in %s" % self._base_dir
    return query_files

  def construct_queries(self, test_vector, scale_factor):
    """Transform a query map into a list of query objects.

    Transform all the queries in the workload's query map to query objects based on the
    input test vector and scale factor.

    Args:
      test_vector (?): query vector
      scale_factor (str): eg. "300gb"

    Returns:
      (list of Query): these will be consumed by ?
    """

    queries = list()
    for query_name, query_str in self._query_map.iteritems():
      queries.append(Query(name=query_name,
                           query_str=query_str,
                           workload=self._name,
                           scale_factor=scale_factor,
                           test_vector=test_vector))
    return queries


text:
(function () {
  'use strict';
  angular.module('MyApp', ['ngMaterial']).controller('AppCtrl', function($scope) {

    $scope.date = new Date().getHours();

  });
})();


text:
/* Custom Styles for Bookstoregenie */

/*  Color Palatte

background: #f7fdff

light blue: #d7e6eb

dark blue: #49a0bd

genie blue: #9ae0f6

dark teal: #266c83

light grey: #4d4c4d

dark grey: #333333

assets/img/dropdown.png

*/

body{background: #f7fdff !important;}

.container{
	width: 960px;
}

/* Typography */

.money-green{
	display: inline;
	color: #4fa25e !important;
}
.dark-blue{
	color: #49a0bd !important;
}
.deep-red{
	font-size: 12px;
	color: #a26b51 !important;
}
.deep-red a{
	color: #a26b51 !important;
	text-decoration: underline;
}

.dark-teal{
	color: #266c83 !important;
	text-shadow: 0px 1px 2px #eee;
}

.dark-teal span{
	font-weight: 200 !important;
}

/* end type */

.navbar-inverse .navbar-inner {
	background-color: transparent!important;
  background: url("../images/classy_fabric.png")!important;
  border-bottom: 2px;
  border-color: #000;
}

.stepTwo{
	margin-top: 40px;
}

.navbar .nav {
	margin: 21px 10px 0 0;
}

.navbar-inverse .nav .active > a, .navbar-inverse .nav .active > a:hover, .navbar-inverse .nav .active > a:focus {
color: white;
background-color: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}

.droppy{
	margin: 26px 0 0 0;
	float: right;
}

.bsg-badge{
	background: #96c89f;
	border: 3px solid #2c2c2d;
	color: #26462b;
	text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
	top: 32px;
	padding: 3px 7px 4px;
	margin: -20px 0 0;
	position: absolute;
	-webkit-border-radius: 20px;
		 -moz-border-radius: 20px;
		 			border-radius: 20px;
}

.blue_well, .white_well, .white_well_home{
	-webkit-border-radius: 4px;
	   -moz-border-radius: 4px;
	   			border-radius: 4px;
}

.fixed-left{
	width: 300px;
	margin: 40px 0 0 0;
	position: fixed;
	top:100px;
}

.white_well{
	background: #fff;
	border: 1px solid #ddd;
	padding: 20px 35px;
	margin-top: 40px;
}

.white_well_home{
	width: 900px;
	background: #fff;
	border: 1px solid #266c83;
	padding: 20px 35px;
	margin: 40px 0 0;
}

.blue_well{
	background: #d7e6eb;
	border: 1px solid #49a0bd;
	padding: 12px;
}

.top-field{
	margin-top: 20px!important;
	margin-bottom: 0px!important;
}

.form-search .input-append .search-query {
	-webkit-border-radius: 20px 0 0 20px;
		 -moz-border-radius: 20px 0 0 20px;
		 			border-radius: 20px 0 0 20px;
}

.form-search .input-append .btn {
	-webkit-border-radius: 0 20px 20px 0;
		 -moz-border-radius: 0 20px 20px 0;
		 			border-radius: 0 20px 20px 0;
}

.remove{
	float: right;
	font-size: 12px;
	line-height: 12px;
	color: #F53;
}

.lead{
  font-size: 36px !important;
}

/* CUSTOMIZE THE NAVBAR
-------------------------------------------------- */

/* Carousel base class */
.banner {
	background: #9ae0f6;
  margin-bottom: 60px;
  border-bottom: 1px solid #49a0bd;
  border-top: 5px solid #fff;
}

.banner .container {
  position: absolute;
  right: 0;
  top: 30px;
  left: 0;
}

.banner .item {
	position: relative;
  height: 420px;
}

/* Carousel base class */
.carousel {
  margin-bottom: 60px;
}

.carousel .container {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
}

.carousel-control {
  background-color: #444;
  border: 0;
  font-size: 60px;
  margin-top: 0;
  text-shadow: 0 1px 1px rgba(0,0,0,.9);
  opacity: 1;
}

.carousel .item {
	background: #fff;
  height: 240px;
}
.carousel img {
  min-width: 100%;
  height: 500px;
}

.carousel-caption {
  background-color: transparent;
  position: static;
  max-width: 640px;
  padding: 0 20px;
  margin: 0 auto 80px auto;
  text-align: center;
}
.carousel-caption h1,
.carousel-caption .lead {
  margin: 0;
  line-height: 1.25;
  color: #444;
}
.carousel-caption .btn {
  margin-top: 10px;
}

/* RESPONSIVE CSS
-------------------------------------------------- */

@media (max-width: 979px) {

  .container.navbar-wrapper {
    margin-bottom: 0;
    width: auto;
  }
  .navbar-inner {
    border-radius: 0;
    margin: -20px 0;
  }

  .carousel .item {
    height: 500px;
  }
  .carousel img {
    width: auto;
    height: 500px;
  }

  .featurette {
    height: auto;
    padding: 0;
  }
  .featurette-image.pull-left,
  .featurette-image.pull-right {
    display: block;
    float: none;
    max-width: 40%;
    margin: 0 auto 20px;
  }
}

@media (max-width: 767px) {

  .navbar-inner {
    margin: -20px;
  }

  .carousel {
    margin-left: -20px;
    margin-right: -20px;
  }
  .carousel .container {

  }
  .carousel .item {
    height: 300px;
  }
  .carousel img {
    height: 300px;
  }
  .carousel-caption {
    width: 65%;
    padding: 0 70px;
    margin-bottom: 40px;
  }
  .carousel-caption h1 {
    font-size: 36px;
    font-weight: 200;
  }
  .carousel-caption .lead,
  .carousel-caption .btn {
    font-size: 18px;
  }

  .marketing .span4 + .span4 {
    margin-top: 40px;
  }

  .featurette-heading {
    font-size: 30px;
  }
  .featurette .lead {
    font-size: 18px;
    line-height: 1.5;
  }

}

.bsg-footer{
  background: #d7e6eb;
  border-top: 1px solid #49a0bd;
}
.bsg-content{
  min-height: 50px;
  padding: 20px 0 10px;
}

textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
	background-color: white;
	border: 1px solid #49a0bd;
	-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
	   -moz-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
	        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
}
.home-search input[type="text"]{
	background-color: white;
	border: 1px solid #444;
	-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
	   -moz-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
	        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
}
select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
	display: inline-block;
	height: 34px;
	padding: 4px 8px;
	margin-bottom: 17px;
	font-size: 14px;
	line-height: 20px;
	color: #333;
	-webkit-border-radius: 4px;
	-moz-border-radius: 4px;
	border-radius: 4px;
	vertical-align: middle;
}
input:-moz-placeholder,
textarea:-moz-placeholder {
  color: #4d4c4d;
  font-weight: 900;
}
input:-ms-input-placeholder,
textarea:-ms-input-placeholder {
  color: #4d4c4d;
  font-weight: 900;
}
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
  color: #4d4c4d;
  font-weight: 900;
}

.field-push-right{
	margin-right: 10px !important;
}

.has-js .label_check,
.has-js .label_radio { padding-left: 34px; }
.has-js .label_radio { background: url(../assets/radio-off.png) no-repeat; }
.has-js .label_check { background: url(../assets/check-off.png) no-repeat; }
.has-js label.c_on { background: url(../assets/check-on.png) no-repeat; }
.has-js label.r_on { background: url(../assets/radio-on.png) no-repeat; }
.has-js .label_check input,
.has-js .label_radio input { position: absolute; left: -9999px; }

.bsg-btn {
	-moz-box-shadow:inset 0px 1px 2px 0px #ffffff;
	-webkit-box-shadow:inset 0px 1px 2px 0px #ffffff;
	box-shadow:inset 0px 1px 2px 0px #ffffff;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #94def5), color-stop(1, #94def5) );
	background:-moz-linear-gradient( center top, #94def5 5%, #94def5 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#94def5', endColorstr='#94def5');
	background-color:#94def5;
	   -moz-border-radius:30px;
	-webkit-border-radius:30px;
	        border-radius:30px;
	border:1px solid #3f7c90;
	display:inline-block;
	color:#333333;
	font-family:arial;
	font-size:18px;
	font-weight:bold;
	padding:11px 18px;
	text-decoration:none;
	text-shadow:0px 0px 0px #ffffff;
}

.bsg-btn:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #94def5), color-stop(1, #94def5) );
	background:-moz-linear-gradient( center top, #94def5 5%, #94def5 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#94def5', endColorstr='#94def5');
	background-color:#94def5;
}

.bsg-btn:active {
	position:relative;
	top:1px;
}

/* trump bootstrap */

select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
display: inline-block;
height: 34px;
}

.btn {
display: inline-block;
padding: 11px 14px;
}

input.span7, textarea.span7, .uneditable-input.span7 {
width: 522px;
}

table {
  max-width: 100%;
  background-color: transparent;
  border-collapse: collapse;
  border-spacing: 0;
}
.table {
  width: 100%;
  margin-bottom: 20px;
}
.table th,
.table td {
  padding: 16px 12px;
  line-height: 16px;
  text-align: left;
  vertical-align: top;
  border-top: 1px solid #555;
}
.table th {
  font-weight: normal;
}
.table thead th {
  vertical-align: bottom;
}
.table caption + thead tr:first-child th,
.table caption + thead tr:first-child td,
.table colgroup + thead tr:first-child th,
.table colgroup + thead tr:first-child td,
.table thead:first-child tr:first-child th,
.table thead:first-child tr:first-child td {
  border-top: 0;
}
.table tbody + tbody {
  border-top: 2px solid #555;
}
.table-condensed th,
.table-condensed td {
  padding: 4px 5px;
}
.table-bordered {
  border: 1px solid #555;
  border-collapse: separate;
  *border-collapse: collapse;
  border-left: 0;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.table-bordered th,
.table-bordered td {
  border-left: 1px solid #555;
}


text:
class Enumeration < ApplicationRecord

  has_many :enumeration_values

  def self.merge_values(from_value_id, to_value_id, enumeration_name)
    enumeration = Enumeration.find_by_name(enumeration_name)
    from_value = EnumerationValue.find(from_value_id)
    to_value = EnumerationValue.find(to_value_id)
    if from_value && to_value && (to_value.enumeration_id == enumeration.id)
      case enumeration_name
      when 'researcher_type'
        records_to_update = User.where(researcher_type_id: from_value_id)
        attribute_name = :researcher_type_id
      when 'location_source'
        records_to_update = Location.where(source_id: from_value_id)
        attribute_name = :source_id
      when 'user_role'
        records_to_update = User.where(user_role_id: from_value_id)
        attribute_name = :user_role_id
      end

      records_to_update.each do |o|
        o.update_attributes(attribute_name => to_value_id)
      end
    end
  end

  def self.values_by_enumeration_name(enumeration_name)
    enumeration = Enumeration.find_by_name(enumeration_name)
    enumeration.enumeration_values
  end

  # Load custom concern if present - methods in concern override those in model
  begin
    include EnumerationCustom
  rescue
  end

end


text:
"""
A script to backup the sqlite database for my blog
Heavily influenced by http://codereview.stackexchange.com/questions/78643/create-sqlite-backups
CRON
Run at 2am every day
0 2 * * * /apps/blog/bin/python /apps/blog/blog/db_backup.py -db /apps/blog/blog/blog/db.db -b /apps/backups/

# Testing on stage
0 2 * * * /apps/stage/bin/python /apps/stage/blog/db_backup.py -db /apps/stage/blog/blog/db.db -b /apps/backups/stage

"""

import sqlite3
import shutil
from datetime import datetime
import os
import argparse
import sys
import logging.handlers
import logging
import hashlib

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

handler2 = logging.handlers.RotatingFileHandler(os.path.join(os.path.split(os.path.abspath(__file__))[0], 'db_backup.log'),
                                                maxBytes=10*1024*1024, backupCount=2)
handler2.setFormatter(formatter)
logger.addHandler(handler2)

parser = argparse.ArgumentParser()
parser.add_argument("-db", "--database", required=True)
parser.add_argument("-b", "--backup_dir", required=True)
parser.add_argument("-dt", "--datetime", default=None)

def get_hash(file_path):
    # http://stackoverflow.com/a/3431838/1391717
    hash_sha1 = hashlib.sha1()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_sha1.update(chunk)

    return hash_sha1.hexdigest()

def _file_to_date(file_name):
    return file_name.split('_', 1)[1][:-4]

def find_latest_backup(backup_dir):
    max = None
    last_backup = None
    for file_name in os.listdir(backup_dir):
        dt = _file_to_date(file_name)
        if max is None or dt > max:
            max = dt
            last_backup = file_name

    return last_backup

def get_args():
    args = parser.parse_args()
    if args.datetime is None:
        args.datetime = datetime.utcnow()

    return args

def backup(args):
    if not os.path.isdir(args.backup_dir):
        raise ValueError("Backup directory does not exist: {}".format(args.backup_dir))

    if not os.path.isfile(args.database):
        raise ValueError("Database file does not exist: {}".format(args.database))

    last_backup = find_latest_backup(args.backup_dir)

    backup_file = os.path.join(args.backup_dir, os.path.basename(args.database) + "_" + args.datetime.strftime("%Y-%m-%d_%H.%M.%S") + ".bck")

    connection = sqlite3.connect(args.database)
    try:
        cursor = connection.cursor()
        cursor.execute("begin immediate")

        last_backup_hash = None
        if last_backup is not None:
            last_backup_hash = get_hash(os.path.join(args.backup_dir, last_backup))

        db_hash = get_hash(args.database)

        if last_backup_hash != db_hash:
            shutil.copyfile(args.database, backup_file)
    except Exception:
        connection.rollback()
        raise

def main():
    args = get_args()
    logger.info(args)

    backup(args)

if __name__ == '__main__':
    try:
        main()
    except Exception as ex:
        logger.exception("Failed to backup: {}".format(ex))
        sys.exit(1)
    else:
        logger.info("Backup successful")
        sys.exit(0)


text:
@interface QYAutoHeightFrameModel : NSObject

@property (nonatomic, strong) QYAutoHeightModel *autoHeightModel;

@property (nonatomic, assign, readonly) CGFloat cellHeight;

@end