text:
package de.appplant.cordova.emailcomposer;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.net.Uri;
import android.text.Html;
import android.util.Base64;
import android.util.Log;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import static de.appplant.cordova.emailcomposer.EmailComposer.LOG_TAG;

/**
 * Implements the interface methods of the plugin.
 */
public class EmailComposerImpl {

    /**
     * The default mailto: scheme.
     */
    static private final String MAILTO_SCHEME = "mailto:";

    /**
     * Path where to put tmp the attachments.
     */
    static private final String ATTACHMENT_FOLDER = "/email_composer";

    /**
     * Cleans the attachment folder.
     *
     * @param ctx
     * The application context.
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    public void cleanupAttachmentFolder (Context ctx) {
        try {
            File dir = new File(ctx.getExternalCacheDir() + ATTACHMENT_FOLDER);

            if (!dir.isDirectory())
                return;

            File[] files = dir.listFiles();

            for (File file : files) { file.delete(); }
        } catch (Exception npe){
            Log.w(LOG_TAG, "Missing external cache dir");
        }
    }

    /**
     * Tells if the device has the capability to send emails.
     *
     * @param id
     * The app id.
     * @param ctx
     * The application context.
     */
    public boolean[] canSendMail (String id, Context ctx) {
        // is possible with specified app
        boolean withScheme = isAppInstalled(id, ctx);
        // is possible in general
        boolean isPossible = isEmailAccountConfigured(ctx);

        return new boolean[] { isPossible, withScheme };
    }

    /**
     * The intent with the containing email properties.
     *
     * @param params
     * The email properties like subject or body
     * @param ctx
     * The context of the application.
     * @return
     * The resulting intent.
     * @throws JSONException
     */
    public Intent getDraftWithProperties (JSONObject params, Context ctx)
            throws JSONException {

        Intent mail = getEmailIntent();
        String app  = params.optString("app", null);

        if (params.has("subject"))
            setSubject(params.getString("subject"), mail);
        if (params.has("body"))
            setBody(params.getString("body"), params.optBoolean("isHtml"), mail);
        if (params.has("to"))
            setRecipients(params.getJSONArray("to"), mail);
        if (params.has("cc"))
            setCcRecipients(params.getJSONArray("cc"), mail);
        if (params.has("bcc"))
            setBccRecipients(params.getJSONArray("bcc"), mail);
        if (params.has("attachments"))
            setAttachments(params.getJSONArray("attachments"), mail, ctx);

        if (!app.equals(MAILTO_SCHEME) && isAppInstalled(app, ctx)) {
            mail.setPackage(app);
        }

        return mail;
    }

    /**
     * Setter for the subject.
     *
     * @param subject
     * The subject of the email.
     * @param draft
     * The intent to send.
     */
    private void setSubject (String subject, Intent draft) {
        draft.putExtra(Intent.EXTRA_SUBJECT, subject);
    }

    /**
     * Setter for the body.
     *
     * @param body
     * The body of the email.
     * @param isHTML
     * Indicates the encoding (HTML or plain text).
     * @param draft
     * The intent to send.
     */
    private void setBody (String body, Boolean isHTML, Intent draft) {
        CharSequence text = isHTML ? Html.fromHtml(body) : body;

        draft.putExtra(Intent.EXTRA_TEXT, text);
    }

    /**
     * Setter for the recipients.
     *
     * @param recipients
     * List of email addresses.
     * @param draft
     * The intent to send.
     * @throws JSONException
     */
    private void setRecipients (JSONArray recipients, Intent draft) throws JSONException {
        String[] receivers = new String[recipients.length()];

        for (int i = 0; i < recipients.length(); i++) {
            receivers[i] = recipients.getString(i);
        }

        draft.putExtra(Intent.EXTRA_EMAIL, receivers);
    }

    /**
     * Setter for the cc recipients.
     *
     * @param recipients
     * List of email addresses.
     * @param draft
     * The intent to send.
     * @throws JSONException
     */
    private void setCcRecipients (JSONArray recipients, Intent draft) throws JSONException {
        String[] receivers = new String[recipients.length()];

        for (int i = 0; i < recipients.length(); i++) {
            receivers[i] = recipients.getString(i);
        }

        draft.putExtra(Intent.EXTRA_CC, receivers);
    }

    /**
     * Setter for the bcc recipients.
     *
     * @param recipients
     * List of email addresses.
     * @param draft
     * The intent to send.
     * @throws JSONException
     */
    private void setBccRecipients (JSONArray recipients, Intent draft) throws JSONException {
        String[] receivers = new String[recipients.length()];

        for (int i = 0; i < recipients.length(); i++) {
            receivers[i] = recipients.getString(i);
        }

        draft.putExtra(Intent.EXTRA_BCC, receivers);
    }

    /**
     * Setter for the attachments.
     *
     * @param attachments
     * List of URIs to attach.
     * @param draft
     * The intent to send.
     * @param ctx
     * The application context.
     * @throws JSONException
     */
    private void setAttachments (JSONArray attachments, Intent draft,
                                 Context ctx) throws JSONException {

        ArrayList<Uri> uris = new ArrayList<Uri>();

        for (int i = 0; i < attachments.length(); i++) {
            Uri uri = getUriForPath(attachments.getString(i), ctx);

            uris.add(uri);
        }

        if (uris.isEmpty())
            return;

        draft.setAction(Intent.ACTION_SEND_MULTIPLE)
             .setType("message/rfc822")
             .putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    }

    /**
     * The URI for an attachment path.
     *
     * @param path
     * The given path to the attachment.
     * @param ctx
     * The application context.
     * @return
     * The URI pointing to the given path.
     */
    private Uri getUriForPath (String path, Context ctx) {
        if (path.startsWith("res:")) {
            return getUriForResourcePath(path, ctx);
        } else if (path.startsWith("file:///")) {
            return getUriForAbsolutePath(path);
        } else if (path.startsWith("file://")) {
            return getUriForAssetPath(path, ctx);
        } else if (path.startsWith("base64:")) {
            return getUriForBase64Content(path, ctx);
        }

        return Uri.parse(path);
    }

    /**
     * The URI for a file.
     *
     * @param path
     * The given absolute path.
     * @return
     * The URI pointing to the given path.
     */
    private Uri getUriForAbsolutePath (String path) {
        String absPath = path.replaceFirst("file://", "");
        File file      = new File(absPath);

        if (!file.exists()) {
            Log.e(LOG_TAG, "File not found: " + file.getAbsolutePath());
        }

        return Uri.fromFile(file);
    }

    /**
     * The URI for an asset.
     *
     * @param path
     * The given asset path.
     * @param ctx
     * The application context.
     * @return
     * The URI pointing to the given path.
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private Uri getUriForAssetPath (String path, Context ctx) {
        String resPath  = path.replaceFirst("file:/", "www");
        String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
        File dir        = ctx.getExternalCacheDir();

        if (dir == null) {
            Log.e(LOG_TAG, "Missing external cache dir");
            return Uri.EMPTY;
        }

        String storage  = dir.toString() + ATTACHMENT_FOLDER;
        File file       = new File(storage, fileName);

        new File(storage).mkdir();

        FileOutputStream outStream = null;

        try {
            AssetManager assets = ctx.getAssets();

            outStream = new FileOutputStream(file);
            InputStream inputStream    = assets.open(resPath);

            copyFile(inputStream, outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            Log.e(LOG_TAG, "File not found: assets/" + resPath);
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                safeClose(outStream);
            }
        }

        return Uri.fromFile(file);
    }

    /**
     * The URI for a resource.
     *
     * @param path
     * The given relative path.
     * @param ctx
     * The application context.
     * @return
     * The URI pointing to the given path
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private Uri getUriForResourcePath (String path, Context ctx) {
        String resPath   = path.replaceFirst("res://", "");
        String fileName  = resPath.substring(resPath.lastIndexOf('/') + 1);
        String resName   = fileName.substring(0, fileName.lastIndexOf('.'));
        String extension = resPath.substring(resPath.lastIndexOf('.'));
        File dir         = ctx.getExternalCacheDir();

        if (dir == null) {
            Log.e(LOG_TAG, "Missing external cache dir");
            return Uri.EMPTY;
        }

        String storage   = dir.toString() + ATTACHMENT_FOLDER;
        int resId        = getResId(resPath, ctx);
        File file        = new File(storage, resName + extension);

        if (resId == 0) {
            Log.e(LOG_TAG, "File not found: " + resPath);
        }

        new File(storage).mkdir();

        FileOutputStream outStream = null;

        try {
            Resources res = ctx.getResources();
            outStream = new FileOutputStream(file);
            InputStream inputStream    = res.openRawResource(resId);

            copyFile(inputStream, outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                safeClose(outStream);
            }
        }

        return Uri.fromFile(file);
    }

    /**
     * The URI for a base64 encoded content.
     *
     * @param content
     * The given base64 encoded content.
     * @param ctx
     * The application context.
     * @return
     * The URI including the given content.
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private Uri getUriForBase64Content (String content, Context ctx) {
        String resName = content.substring(content.indexOf(":") + 1, content.indexOf("//"));
        String resData = content.substring(content.indexOf("//") + 2);
        File dir       = ctx.getExternalCacheDir();
        byte[] bytes;

        try {
            bytes = Base64.decode(resData, 0);
        } catch (Exception ignored) {
            Log.e(LOG_TAG, "Invalid Base64 string");
            return Uri.EMPTY;
        }

        if (dir == null) {
            Log.e(LOG_TAG, "Missing external cache dir");
            return Uri.EMPTY;
        }

        String storage = dir.toString() + ATTACHMENT_FOLDER;
        File file      = new File(storage, resName);

        new File(storage).mkdir();

        FileOutputStream outStream = null;

        try {
            outStream = new FileOutputStream(file);

            outStream.write(bytes);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                safeClose(outStream);
            }
        }

        return Uri.fromFile(file);
    }

    /**
     * Writes an InputStream to an OutputStream
     *
     * @param in
     * The input stream.
     * @param out
     * The output stream.
     */
    private void copyFile (InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;

        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }

    /**
     * Returns the resource ID for the given resource path.
     *
     * @param ctx
     * The application context.
     * @return
     * The resource ID for the given resource.
     */
    private int getResId (String resPath, Context ctx) {
        Resources res = ctx.getResources();
        int resId;

        String pkgName  = ctx.getPackageName();
        String dirName  = "drawable";
        String fileName = resPath;

        if (resPath.contains("/")) {
            dirName  = resPath.substring(0, resPath.lastIndexOf('/'));
            fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
        }

        String resName = fileName.substring(0, fileName.lastIndexOf('.'));

        resId = res.getIdentifier(resName, dirName, pkgName);

        if (resId == 0) {
            resId = res.getIdentifier(resName, "drawable", pkgName);
        }

        return resId;
    }

    /**
     * If email apps are available.
     *
     * @param ctx
     * The application context.
     * @return
     * true if available, otherwise false
     */
    private boolean isEmailAccountConfigured (Context ctx) {
        AccountManager am  = AccountManager.get(ctx);

        try {
            for (Account account : am.getAccounts()) {
                if (account.type.endsWith("mail")) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Missing GET_ACCOUNTS permission.");
            return true;
        }

        return false;
    }

    /**
     * Ask the package manager if the app is installed on the device.
     *
     * @param id
     * The app id.
     * @param ctx
     * The application context.
     * @return
     * true if yes otherwise false.
     */
    private boolean isAppInstalled (String id, Context ctx) {

        if (id.equalsIgnoreCase(MAILTO_SCHEME)) {
            Intent intent     = getEmailIntent();
            PackageManager pm = ctx.getPackageManager();
            int apps          = pm.queryIntentActivities(intent, 0).size();

            return (apps > 0);
        }

        try {
            ctx.getPackageManager().getPackageInfo(id, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * Setup an intent to send to email apps only.
     *
     * @return intent
     */
    private static Intent getEmailIntent() {
        Intent intent = new Intent(Intent.ACTION_SENDTO,
                Uri.parse(MAILTO_SCHEME));

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        return intent;
    }

    /**
     * Attempt to safely close the given stream.
     *
     * @param outStream
     * The stream to close.
     * @return
     * true if successful, false otherwise
     */
    private static boolean safeClose (final FileOutputStream outStream) {

        if (outStream != null) {
            try {
                outStream.close();
                return true;
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error attempting to safely close resource: " + e.getMessage());
            }
        }

        return false;
    }

}


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - postprocessing</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">
	</head>
	<body>

		<!-- Import maps polyfill -->
		<!-- Remove this when import maps will be widely supported -->
		<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.module.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

			import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
			import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
			import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';

			import { RGBShiftShader } from 'three/addons/shaders/RGBShiftShader.js';
			import { DotScreenShader } from 'three/addons/shaders/DotScreenShader.js';

			let camera, renderer, composer;
			let object;

			init();
			animate();

			function init() {

				renderer = new THREE.WebGLRenderer();
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				document.body.appendChild( renderer.domElement );

				//

				camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
				camera.position.z = 400;

				const scene = new THREE.Scene();
				scene.fog = new THREE.Fog( 0x000000, 1, 1000 );

				object = new THREE.Object3D();
				scene.add( object );

				const geometry = new THREE.SphereGeometry( 1, 4, 4 );
				const material = new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true } );

				for ( let i = 0; i < 100; i ++ ) {

					const mesh = new THREE.Mesh( geometry, material );
					mesh.position.set( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 ).normalize();
					mesh.position.multiplyScalar( Math.random() * 400 );
					mesh.rotation.set( Math.random() * 2, Math.random() * 2, Math.random() * 2 );
					mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50;
					object.add( mesh );

				}

				scene.add( new THREE.AmbientLight( 0x222222 ) );

				const light = new THREE.DirectionalLight( 0xffffff );
				light.position.set( 1, 1, 1 );
				scene.add( light );

				// postprocessing

				composer = new EffectComposer( renderer );
				composer.addPass( new RenderPass( scene, camera ) );

				const effect1 = new ShaderPass( DotScreenShader );
				effect1.uniforms[ 'scale' ].value = 4;
				composer.addPass( effect1 );

				const effect2 = new ShaderPass( RGBShiftShader );
				effect2.uniforms[ 'amount' ].value = 0.0015;
				composer.addPass( effect2 );

				//

				window.addEventListener( 'resize', onWindowResize );

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );
				composer.setSize( window.innerWidth, window.innerHeight );

			}

			function animate() {

				requestAnimationFrame( animate );

				object.rotation.x += 0.005;
				object.rotation.y += 0.01;

				composer.render();

			}

		</script>

	</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Antrag\View\Helper;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
 *
 * @package Antrag
 * @since   21.02.2016
 * @author  Stefan Meier <s.meier@citkomm.de>
 */
class KontaktForFormFactory implements FactoryInterface
{
    /**
     * Erstellt den ViewHelper und setzt alle notwendige Abhängigkeiten
     *
     * @param \Zend\ServiceManager\ServiceLocatorInterface $viewHelperManager
     * @return \Antrag\View\Helper\AntragForUebersicht
     */
    public function createService(ServiceLocatorInterface $viewHelperManager)
    {
        $serviceLocator = $viewHelperManager->getServiceLocator();

        $kontaktFieldset = new KontaktForForm();

        return $kontaktFieldset;
    }
}


text:
module('lively.presentation.tests.Builds').requires('lively.presentation.Builds', 'lively.morphic.tests.Helper').toRun(function() {

TestCase.subclass('lively.presentation.tests.Builds.Steps',
'running', {
    setUp: function() {
        var sut = this.sut = {applied: []};
        Trait('lively.presentation.Builds.BuildStepTrait').applyTo(sut);
        sut.applyBuildSteps = function(steps, revert) {
            sut.applied.push({steps: steps, reverted: !!revert});
        };
    }
},
"testing", {
    testInitMorphsFromAnimSpec: function()  {
        var steps = [
            {attributeName: "visibility",attributeValue: "visible",target: "id1",when: "on-click"},
            {attributeName: "visibility",attributeValue: "hidden",target: "id2",when: "with-previous"},
            {attributeName: "visibility", attributeValue: "visible",target: "id3",when: "on-click"}];
        var expectedInitSteps = [
            {attributeName: 'visibility', attributeValue: 'hidden', target: 'id1', when: 'initial'},
            {attributeName: 'visibility', attributeValue: 'visible', target: 'id2', when: 'initial'},
            {attributeName: 'visibility', attributeValue: 'hidden', target: 'id3', when: 'initial'}];
        this.sut.setBuildSteps(steps);
        this.sut.buildStepForward();
        this.assertEqualState([{steps: expectedInitSteps, reverted: false}], this.sut.applied, 'build step init');
    },
    testBuildForward: function()  {
        var steps = [
            {attributeName: "visibility",attributeValue: "visible",target: "id1",when: "on-click"},
            {attributeName: "visibility",attributeValue: "hidden",target: "id2",when: "with-previous"},
            {attributeName: "visibility", attributeValue: "visible",target: "id3",when: "on-click"}];
        this.sut.setBuildSteps(steps);
        this.sut.buildStepForward();
        this.sut.applied = [];
        var expected = [{
            steps: [{attributeName: "visibility",attributeValue: "visible",target: "id1",when: "on-click"},
                    {attributeName: "visibility",attributeValue: "hidden",target: "id2",when: "with-previous"}],
            reverted: false
        },{
            steps: [{attributeName: "visibility", attributeValue: "visible",target: "id3",when: "on-click"}],
            reverted: false
        }, {steps: [],reverted: false}];
        this.sut.buildStepForward();
        this.sut.buildStepForward();
        this.sut.buildStepForward();
        this.assertEqualState(expected, this.sut.applied, 'build step forward');
    },
    testBuildBackward: function()  {
        var steps = [
            {attributeName: "visibility",attributeValue: "visible",target: "id1",when: "on-click"},
            {attributeName: "visibility",attributeValue: "hidden",target: "id2",when: "with-previous"},
            {attributeName: "visibility", attributeValue: "visible",target: "id3",when: "on-click"}];
        this.sut.setBuildSteps(steps);
        this.sut.buildStepForward();
        this.sut.buildStepForward();
        this.sut.buildStepForward();
        this.sut.applied = [];
        var expected = [{
            steps: [{attributeName: "visibility", attributeValue: "visible",target: "id3",when: "on-click"}],
            reverted: true
        }, {
            steps: [{attributeName: "visibility",attributeValue: "hidden",target: "id2",when: "with-previous"},
                    {attributeName: "visibility",attributeValue: "visible",target: "id1",when: "on-click"}],
            reverted: true
        },{steps: [],reverted: true}];
        this.sut.buildStepBackward();
        this.sut.buildStepBackward();
        this.sut.buildStepBackward();
        this.assertEqualState(expected, this.sut.applied, 'build step backward');
    }

});

}) // end of module


text:
using namespace boost::intrusive;

                  //This is a base hook
class MyClass : public slist_base_hook<>
{
   int int_;

   public:
   //This is a member hook
   slist_member_hook<> member_hook_;

   MyClass(int i)
      :  int_(i)
   {}
};

//Define an slist that will store MyClass using the public base hook
typedef slist<MyClass> BaseList;

//Define an slist that will store MyClass using the public member hook
typedef member_hook<MyClass, slist_member_hook<>, &MyClass::member_hook_> MemberOption;
typedef slist<MyClass, MemberOption> MemberList;

int main()
{
   typedef std::vector<MyClass>::iterator VectIt;
   typedef std::vector<MyClass>::reverse_iterator VectRit;

   //Create several MyClass objects, each one with a different value
   std::vector<MyClass> values;
   for(int i = 0; i < 100; ++i)  values.push_back(MyClass(i));

   BaseList baselist;
   MemberList memberlist;

   //Now insert them in the reverse order in the base hook list
   for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it)
      baselist.push_front(*it);

   //Now insert them in the same order as in vector in the member hook list
   for(BaseList::iterator it(baselist.begin()), itend(baselist.end())
      ; it != itend; ++it){
      memberlist.push_front(*it);
   }

   //Now test lists
   {
      BaseList::iterator bit(baselist.begin()), bitend(baselist.end());
      MemberList::iterator mit(memberlist.begin()), mitend(memberlist.end());
      VectRit rit(values.rbegin()), ritend(values.rend());
      VectIt  it(values.begin()), itend(values.end());

      //Test the objects inserted in the base hook list
      for(; rit != ritend; ++rit, ++bit)
         if(&*bit != &*rit)   return 1;

      //Test the objects inserted in the member hook list
      for(; it != itend; ++it, ++mit)
         if(&*mit != &*it)    return 1;
   }

   return 0;
}
//]


text:
package hyweb.jo.fun;

import hyweb.jo.model.JOWPObject;
import java.util.HashMap;
import java.util.Map;
import org.mvel2.MVEL;

/**
 *
 * @author william
 */
public class mvel_before extends wp_base<Object> {

    @Override
    public Object exec(JOWPObject wp) throws Exception {
        String expression = wp.act().optString("$before");
        Map<String,Object> ret = (Map<String,Object>) MVEL.eval(expression, varPools(wp));
        wp.p().putAll(ret);
        return ret;
    }

    private Map<String, Object> varPools(JOWPObject wp) {
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("$", wp.p());
        m.put("$$", wp.pp());
        m.put("$ff", m);
        return m;
    }

}


text:
image-name = flexget
container-name = $(image-name)

flexget-path = /home/ake1/docker/docker-flexget
torrent-path = /mnt/big-sata/torrents

build:
	docker build -t $(image-name) .

run:
	docker run -d --name $(container-name) \
	-v $(flexget-path):/root/.flexget \
	-v $(torrent-path):/torrents \
	$(container-name)

clean:
	-docker stop $(container-name)
	-docker rm $(container-name)

peek:
	docker exec -it $(container-name) /bin/bash

iter: clean build run peek


text:
Startup
-------
mvn spring-boot:run

Datamodel
---------

curl -H "Content-Type: application/json" -d '{"benchmarkName":"datastaxBatchInsert", "seedNode":"internalIPOfSeedNodeInSameZone"}' http://127.0.0.1:8080/scenario/createDatamodel

curl -H "Content-Type: application/json" -d '{"benchmarkName":"astyanaxBatchInsert", "seedNode":"internalIPOfSeedNodeInSameZone"}' http://127.0.0.1:8080/scenario/createDatamodel

Execution
---------

curl -H "Content-Type: application/json" -d '{"benchmarkName":"datastaxBatchInsert", "seedNode":"internalIPOfSeedNodeInSameZone", "parameter": {"batchSize":"100", "rowCount": "100000"}}' http://127.0.0.1:8080/scenario/execute

curl -H "Content-Type: application/json" -d '{"benchmarkName":"astyanaxBatchInsert", "seedNode":"internalIPOfSeedNodeInSameZone", "parameter": {"batchSize":"100", "rowCount": "100000"}}' http://127.0.0.1:8080/scenario/execute


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CloudCompare.Web.FluentSecurity
{
    public interface ISecurityContext
    {
        dynamic Data { get; }
        bool CurrenUserAuthenticated();
        IEnumerable<object> CurrenUserRoles();
    }
}


text:
<?php

/**
 * Needed for error handling
 */
require_once 'PEAR.php';
require_once 'PEAR/Frontend.php';
require_once 'PEAR/XMLParser.php';

/**
 * List of commands and what classes they are implemented in.
 * @var array command => implementing class
 */
$GLOBALS['_PEAR_Command_commandlist'] = array();

/**
 * List of commands and their descriptions
 * @var array command => description
 */
$GLOBALS['_PEAR_Command_commanddesc'] = array();

/**
 * List of shortcuts to common commands.
 * @var array shortcut => command
 */
$GLOBALS['_PEAR_Command_shortcuts'] = array();

/**
 * Array of command objects
 * @var array class => object
 */
$GLOBALS['_PEAR_Command_objects'] = array();

/**
 * PEAR command class, a simple factory class for administrative
 * commands.
 *
 * How to implement command classes:
 *
 * - The class must be called PEAR_Command_Nnn, installed in the
 *   "PEAR/Common" subdir, with a method called getCommands() that
 *   returns an array of the commands implemented by the class (see
 *   PEAR/Command/Install.php for an example).
 *
 * - The class must implement a run() function that is called with three
 *   params:
 *
 *    (string) command name
 *    (array)  assoc array with options, freely defined by each
 *             command, for example:
 *             array('force' => true)
 *    (array)  list of the other parameters
 *
 *   The run() function returns a PEAR_CommandResponse object.  Use
 *   these methods to get information:
 *
 *    int getStatus()   Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL)
 *                      *_PARTIAL means that you need to issue at least
 *                      one more command to complete the operation
 *                      (used for example for validation steps).
 *
 *    string getMessage()  Returns a message for the user.  Remember,
 *                         no HTML or other interface-specific markup.
 *
 *   If something unexpected happens, run() returns a PEAR error.
 *
 * - DON'T OUTPUT ANYTHING! Return text for output instead.
 *
 * - DON'T USE HTML! The text you return will be used from both Gtk,
 *   web and command-line interfaces, so for now, keep everything to
 *   plain text.
 *
 * - DON'T USE EXIT OR DIE! Always use pear errors.  From static
 *   classes do PEAR::raiseError(), from other classes do
 *   $this->raiseError().
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2008 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: 1.7.2
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 0.1
 */
class PEAR_Command
{
    // {{{ factory()

    /**
     * Get the right object for executing a command.
     *
     * @param string $command The name of the command
     * @param object $config  Instance of PEAR_Config object
     *
     * @return object the command object or a PEAR error
     *
     * @access public
     * @static
     */
    function &factory($command, &$config)
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
            $a = PEAR::raiseError("unknown command `$command'");
            return $a;
        }
        $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
        if (!class_exists($class)) {
            require_once $GLOBALS['_PEAR_Command_objects'][$class];
        }
        if (!class_exists($class)) {
            $a = PEAR::raiseError("unknown command `$command'");
            return $a;
        }
        $ui =& PEAR_Command::getFrontendObject();
        $obj = &new $class($ui, $config);
        return $obj;
    }

    // }}}
    // {{{ & getObject()
    function &getObject($command)
    {
        $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
        if (!class_exists($class)) {
            require_once $GLOBALS['_PEAR_Command_objects'][$class];
        }
        if (!class_exists($class)) {
            return PEAR::raiseError("unknown command `$command'");
        }
        $ui =& PEAR_Command::getFrontendObject();
        $config = &PEAR_Config::singleton();
        $obj = &new $class($ui, $config);
        return $obj;
    }

    // }}}
    // {{{ & getFrontendObject()

    /**
     * Get instance of frontend object.
     *
     * @return object|PEAR_Error
     * @static
     */
    function &getFrontendObject()
    {
        $a = &PEAR_Frontend::singleton();
        return $a;
    }

    // }}}
    // {{{ & setFrontendClass()

    /**
     * Load current frontend class.
     *
     * @param string $uiclass Name of class implementing the frontend
     *
     * @return object the frontend object, or a PEAR error
     * @static
     */
    function &setFrontendClass($uiclass)
    {
        $a = &PEAR_Frontend::setFrontendClass($uiclass);
        return $a;
    }

    // }}}
    // {{{ setFrontendType()

    /**
     * Set current frontend.
     *
     * @param string $uitype Name of the frontend type (for example "CLI")
     *
     * @return object the frontend object, or a PEAR error
     * @static
     */
    function setFrontendType($uitype)
    {
        $uiclass = 'PEAR_Frontend_' . $uitype;
        return PEAR_Command::setFrontendClass($uiclass);
    }

    // }}}
    // {{{ registerCommands()

    /**
     * Scan through the Command directory looking for classes
     * and see what commands they implement.
     *
     * @param bool   (optional) if FALSE (default), the new list of
     *               commands should replace the current one.  If TRUE,
     *               new entries will be merged with old.
     *
     * @param string (optional) where (what directory) to look for
     *               classes, defaults to the Command subdirectory of
     *               the directory from where this file (__FILE__) is
     *               included.
     *
     * @return bool TRUE on success, a PEAR error on failure
     *
     * @access public
     * @static
     */
    function registerCommands($merge = false, $dir = null)
    {
        $parser = new PEAR_XMLParser;
        if ($dir === null) {
            $dir = dirname(__FILE__) . '/Command';
        }
        if (!is_dir($dir)) {
            return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory");
        }
        $dp = @opendir($dir);
        if (empty($dp)) {
            return PEAR::raiseError("registerCommands: opendir($dir) failed");
        }
        if (!$merge) {
            $GLOBALS['_PEAR_Command_commandlist'] = array();
        }
        while ($entry = readdir($dp)) {
            if ($entry{0} == '.' || substr($entry, -4) != '.xml') {
                continue;
            }
            $class = "PEAR_Command_".substr($entry, 0, -4);
            $file = "$dir/$entry";
            $parser->parse(file_get_contents($file));
            $implements = $parser->getData();
            // List of commands
            if (empty($GLOBALS['_PEAR_Command_objects'][$class])) {
                $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . substr($entry, 0, -4) .
                    '.php';
            }
            foreach ($implements as $command => $desc) {
                if ($command == 'attribs') {
                    continue;
                }
                if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
                    return PEAR::raiseError('Command "' . $command . '" already registered in ' .
                        'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
                }
                $GLOBALS['_PEAR_Command_commandlist'][$command] = $class;
                $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary'];
                if (isset($desc['shortcut'])) {
                    $shortcut = $desc['shortcut'];
                    if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) {
                        return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' .
                            'registered to command "' . $command . '" in class "' .
                            $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
                    }
                    $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command;
                }
                if (isset($desc['options']) && $desc['options']) {
                    foreach ($desc['options'] as $oname => $option) {
                        if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) {
                            return PEAR::raiseError('Option "' . $oname . '" short option "' .
                                $option['shortopt'] . '" must be ' .
                                'only 1 character in Command "' . $command . '" in class "' .
                                $class . '"');
                        }
                    }
                }
            }
        }
        ksort($GLOBALS['_PEAR_Command_shortcuts']);
        ksort($GLOBALS['_PEAR_Command_commandlist']);
        @closedir($dp);
        return true;
    }

    // }}}
    // {{{ getCommands()

    /**
     * Get the list of currently supported commands, and what
     * classes implement them.
     *
     * @return array command => implementing class
     *
     * @access public
     * @static
     */
    function getCommands()
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        return $GLOBALS['_PEAR_Command_commandlist'];
    }

    // }}}
    // {{{ getShortcuts()

    /**
     * Get the list of command shortcuts.
     *
     * @return array shortcut => command
     *
     * @access public
     * @static
     */
    function getShortcuts()
    {
        if (empty($GLOBALS['_PEAR_Command_shortcuts'])) {
            PEAR_Command::registerCommands();
        }
        return $GLOBALS['_PEAR_Command_shortcuts'];
    }

    // }}}
    // {{{ getGetoptArgs()

    /**
     * Compiles arguments for getopt.
     *
     * @param string $command     command to get optstring for
     * @param string $short_args  (reference) short getopt format
     * @param array  $long_args   (reference) long getopt format
     *
     * @return void
     *
     * @access public
     * @static
     */
    function getGetoptArgs($command, &$short_args, &$long_args)
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
            return null;
        }
        $obj = &PEAR_Command::getObject($command);
        return $obj->getGetoptArgs($command, $short_args, $long_args);
    }

    // }}}
    // {{{ getDescription()

    /**
     * Get description for a command.
     *
     * @param  string $command Name of the command
     *
     * @return string command description
     *
     * @access public
     * @static
     */
    function getDescription($command)
    {
        if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) {
            return null;
        }
        return $GLOBALS['_PEAR_Command_commanddesc'][$command];
    }

    // }}}
    // {{{ getHelp()

    /**
     * Get help for command.
     *
     * @param string $command Name of the command to return help for
     *
     * @access public
     * @static
     */
    function getHelp($command)
    {
        $cmds = PEAR_Command::getCommands();
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (isset($cmds[$command])) {
            $obj = &PEAR_Command::getObject($command);
            return $obj->getHelp($command);
        }
        return false;
    }
    // }}}
}

?>


text:
extern crate chrono;
extern crate rustc_serialize;

#[cfg(test)] extern crate rand;

use std::convert::From;
use std::fmt;
use std::collections::BTreeMap;

#[doc(hidden)]
pub enum Endpoint {
    Api,
    Content,
}

impl fmt::Display for Endpoint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Endpoint::Api => write!(f, "api"),
            Endpoint::Content => write!(f, "content"),
        }
    }
}

pub trait DropboxClient {
    fn access_token(&self) -> &str;
    fn request<T>(&self, endpoint: Endpoint, url: &str, headers: &mut BTreeMap<String, String>, body: Option<T>) -> Result<Response>
            where T: rustc_serialize::Encodable + Clone;

    fn api<T>(&self, url: &str, headers: &mut BTreeMap<String, String>, body: Option<T>) -> Result<Response>
            where T: rustc_serialize::Encodable + Clone
    {
        self.request(Endpoint::Api, url, headers, body)
    }

    fn content<T>(&self, url: &str, headers: &mut BTreeMap<String, String>, body: Option<T>) -> Result<Response>
            where T: rustc_serialize::Encodable + Clone
    {
        self.request(Endpoint::Content, url, headers, body)
    }
}

/// Collection of possible errors
#[derive(Debug, PartialEq, Clone)]
pub enum ApiError {
    AddFolderMemberError,
    ClientError,
    CreateFolderError,
    CreateSharedLinkError,
    DeleteError,
    DownloadError,
    GetAccountError,
    GetAccountBatchError,
    GetMetadataError,
    GetSharedLinksError,
    ListFolderError,
    ListFolderContinueError,
    ListFolderLongpollError,
    ListFolderMembersContinueError,
    ListFoldersContinueError,
    ListRevisionsError,
    MountFolderError,
    PollError,
    PreviewError,
    RelinquishFolderMembershipError,
    RelocationError,
    RemoveFolderMemberError,
    RestoreError,
    RevokeSharedLinkError,
    SearchError,
    ShareFolderError,
    SharedFolderAccessError,
    ThumbnailError,
    TokenError,
    TransferFolderError,
    UnmountFolderError,
    UnshareFolderError,
    UpdateFolderMemberError,
    UpdateFolderPolicyError,
    UploadError,
    UploadSessionLookupError,
    UploadSessionFinishError,
}

impl From<rustc_serialize::json::DecoderError> for ApiError {
    fn from(e: rustc_serialize::json::DecoderError) -> ApiError {
        ApiError::ClientError
    }
}

/// Simple abstraction of a HTTP response, to allow the HTTP client to be pluggable
///
/// TODO: overhaul this
#[derive(Debug, PartialEq, Clone)]
pub struct Response {
    pub status: u16,
    pub api_result: Option<String>,
    pub body: String,
}

pub type Result<T> = ::std::result::Result<T, ApiError>;

#[cfg(feature = "hyper-client")]
/// Default implementation of the Dropbox Client
pub mod client;
/// Module for performing operations on files in a dropbox account
pub mod files;
/// Module that holds definitions for dropbox data structures
pub mod structs;
/// TODO
pub mod sharing;
/// TODO
pub mod users;

#[cfg(test)]
mod tests {
    use super::client::Client;
    use super::files;
    use super::DropboxClient;
    use chrono::{DateTime, Local};
    use rand;
    use std::str;
    use std::env;
    use std::default::Default;
    use rustc_serialize::json;

    const ACCESS_TOKEN: &'static str = "DROPBOX_TOKEN";
    const MALFORMED_TOKEN: &'static str = "asdf";

    fn random_ascii_letters(len: usize) -> String {
        let mut rng = rand::thread_rng();
        let ascii_letters = (65..91).chain((97..123)).collect::<Vec<u8>>();
        let random_bytes = rand::sample(&mut rng, ascii_letters.into_iter(), len);
        let random_string = str::from_utf8(&random_bytes).unwrap();
        random_string.to_owned()
    }

    #[test]
    fn test_bad_auth() {
        if let Ok(_) = Client::new(MALFORMED_TOKEN) {
            panic!("Malformed token should not be accepted");
        }

        let valid_looking_token = vec!["z"; 62].join("");
        let client = Client::new(&valid_looking_token).unwrap();
        if let Ok(_) = files::list_folder(&client, "") {
            panic!("Valid-looking but invalid token should not be accepted");
        }
    }

    #[test]
    fn test_list_rpc() {
        let access_token = match env::var(ACCESS_TOKEN) {
            Ok(t) => t,
            Err(_) => panic!("No {} found", ACCESS_TOKEN),
        };
        let client = Client::new(&access_token).unwrap();
        assert!(files::create_folder(&client, "/testdir").is_ok());
        assert!(files::list_folder(&client, "/testdir").is_ok());
        assert!(files::delete(&client, "/testdir").is_ok());
    }

    #[test]
    fn test_files() {
        let access_token = match env::var(ACCESS_TOKEN) {
            Ok(t) => t,
            Err(_) => panic!("No {} found", ACCESS_TOKEN),
        };
        let random_filename = random_ascii_letters(15);
        let now: DateTime<Local> = Local::now();
        let now = format!("{}", now.timestamp());
        let random_dir = format!("/Test/{}", now);
        let random_path = format!("/Test/{}/{}", now, random_filename);
        let random_path_copy = format!("/Test/{}/{}copy", now, random_filename);
        let random_path_move = format!("/Test/{}/{}move", now, random_filename);
        let random_contents = random_ascii_letters(20);

        let client = Client::new(&access_token).unwrap();

        assert!(files::upload(&client, &random_contents, &random_path).is_ok());
        assert!(files::get_metadata(&client, &random_path, false).is_ok());

        assert!(files::copy_(&client, &random_path, &random_path_copy).is_ok());
        assert!(files::move_(&client, &random_path_copy, &random_path_move).is_ok());

        let (metadata, resp) = files::download(&client, &random_path).unwrap();
        let body: String = json::decode(&resp.body).unwrap();
        assert_eq!(&body, &random_contents);

        assert!(files::delete(&client, &random_path_move).is_ok());
        assert!(files::delete(&client, &random_path).is_ok());
        assert!(files::delete(&client, &random_dir).is_ok());
    }

}


text:
public class B {
  void publicMethod() {
    new A().invisibleMethod(2);
    new A().visibleMethod(2);
  }
}


text:
module.exports = function(bot, message) {
  var body = message.text.trim().split(' ').slice(1).join(' ');
  var words = body.split(' ').length;
  var letters = body.replace(/[^A-Z]/gi, "").length;
  var reply = '';

  reply += words + ' words\n';
  reply += letters + ' letters';

  bot.reply(message, reply);
};


text:
  <button type="button"
          class="close"
          data-ng-click="$dismiss()"
  >
    ×
    Close
  </button>

Набір

  <form name="vm.reqruitform" class="dt-form">

      Від:
      <input type="number"
             class="form-control"
             data-ng-model="vm.recruitFrom"
             id="recruit-from-input"
             data-ng-disabled="vm.fromUnlimited"
             data-ng-required="!vm.fromUnlimited"
      >
      <input type="checkbox"
             data-ng-model="vm.fromUnlimited"
             id="from-unlimited-check">
      Не Обмежено

      До:
      <input type="number"
             class="form-control"
             data-ng-model="vm.recruitTo"
             id="recruit-to-input"
             data-ng-disabled="vm.toUnlimited"
             data-ng-required="!vm.toUnlimited"
      >
      <input type="checkbox"
             data-ng-model="vm.toUnlimited"
             id="to-unlimited-check">
      Не Обмежено

  </form>
  <button class="btn btn-default" data-ng-click="vm.submit()">Зберегти</button>

  <button type="button" class="btn btn-sm btn-default" ng-click="$dismiss()">Close</button>


text:
module Imap; end

module Imap::Backup
  class Account
    DEFAULT_MULTI_FETCH_SIZE = 1

    attr_reader :username
    attr_reader :password
    attr_reader :local_path
    attr_reader :folders
    attr_reader :folder_blacklist
    attr_reader :mirror_mode
    attr_reader :server
    attr_reader :connection_options
    attr_reader :reset_seen_flags_after_fetch
    attr_reader :changes

    def initialize(options)
      @username = options[:username]
      @password = options[:password]
      @local_path = options[:local_path]
      @folders = options[:folders]
      @folder_blacklist = options[:folder_blacklist]
      @mirror_mode = options[:mirror_mode]
      @server = options[:server]
      @connection_options = options[:connection_options]
      @multi_fetch_size = options[:multi_fetch_size]
      @reset_seen_flags_after_fetch = options[:reset_seen_flags_after_fetch]
      @connection = nil
      @changes = {}
      @marked_for_deletion = false
    end

    def connection
      @connection ||= Account::Connection.new(self)
    end

    def valid?
      username && password ? true : false
    end

    def modified?
      changes.any?
    end

    def clear_changes
      @changes = {}
    end

    def mark_for_deletion
      @marked_for_deletion = true
    end

    def marked_for_deletion?
      @marked_for_deletion
    end

    def to_h
      h = {username: @username, password: @password}
      h[:local_path] = @local_path if @local_path
      h[:folders] = @folders if @folders
      h[:folder_blacklist] = true if @folder_blacklist
      h[:mirror_mode] = true if @mirror_mode
      h[:server] = @server if @server
      h[:connection_options] = @connection_options if @connection_options
      h[:multi_fetch_size] = multi_fetch_size if @multi_fetch_size
      if @reset_seen_flags_after_fetch
        h[:reset_seen_flags_after_fetch] = @reset_seen_flags_after_fetch
      end
      h
    end

    def username=(value)
      update(:username, value)
    end

    def password=(value)
      update(:password, value)
    end

    def local_path=(value)
      update(:local_path, value)
    end

    def folders=(value)
      raise "folders must be an Array" if !value.is_a?(Array)

      update(:folders, value)
    end

    def folder_blacklist=(value)
      update(:folder_blacklist, value)
    end

    def mirror_mode=(value)
      update(:mirror_mode, value)
    end

    def server=(value)
      update(:server, value)
    end

    def connection_options=(value)
      parsed =
        if value == ""
          nil
        else
          JSON.parse(value, symbolize_names: true)
        end
      update(:connection_options, parsed)
    end

    def multi_fetch_size
      int = @multi_fetch_size.to_i
      if int.positive?
        int
      else
        DEFAULT_MULTI_FETCH_SIZE
      end
    end

    def multi_fetch_size=(value)
      parsed = value.to_i
      parsed = DEFAULT_MULTI_FETCH_SIZE if !parsed.positive?
      update(:multi_fetch_size, parsed)
    end

    def reset_seen_flags_after_fetch=(value)
      update(:reset_seen_flags_after_fetch, value)
    end

    private

    def update(field, value)
      key = :"@#{field}"
      if changes[field]
        change = changes[field]
        if change[:from] == value
          changes.delete(field)
        else
          change[:to] = value
        end
      else
        current = instance_variable_get(key)
        changes[field] = {from: current, to: value} if value != current
      end

      @connection = nil
      instance_variable_set(key, value)
    end
  end
end


text:
//
//  APCProfileViewController.h
//  APCAppCore
//
// Copyright (c) 2015, Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1.  Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2.  Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3.  Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

#import "APCUserInfoViewController.h"

@class APCUser;

@protocol APCProfileViewControllerDelegate;

@interface APCProfileViewController : APCUserInfoViewController <APCPickerTableViewCellDelegate, APCTextFieldTableViewCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITextFieldDelegate, APCSwitchTableViewCellDelegate, APCSegmentedTableViewCellDelegate>

@property (nonatomic, strong) APCUser *user;

@property (weak, nonatomic) IBOutlet UIView *headerView;

@property (weak, nonatomic) IBOutlet UIButton *profileImageButton;

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

@property (weak, nonatomic) IBOutlet UILabel *emailTextField;

@property (weak, nonatomic) IBOutlet UILabel *editLabel;

@property (weak, nonatomic) IBOutlet UIView *footerView;

@property (weak, nonatomic) IBOutlet UILabel *footerTitleLabel;

@property (weak, nonatomic) IBOutlet UILabel *diseaseLabel;

@property (weak, nonatomic) IBOutlet UIButton *signOutButton;

@property (weak, nonatomic) IBOutlet UILabel *applicationNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *participationLabel;

@property (weak, nonatomic) IBOutlet UIButton *leaveStudyButton;

@property (weak, nonatomic) IBOutlet UIButton *pauseResumeStudyButton;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *rightBarButton;

@property (nonatomic, weak) id <APCProfileViewControllerDelegate> delegate;

@property (nonatomic, strong) UIImage *profileImage;

/*
 * If set to YES, birthdate will be a Date Picker Cell, and can be edited when isEditing is also set to YES
 * If set to NO, birthdate will be a Default Cell, with its value locked no matter what
 */
@property (nonatomic) BOOL canEditBirthDate;

/*
 * If set to YES, biological sex will be a Segment Cell, and can be edited when isEditing is also set to YES
 * If set to NO, biological sex will be a Default Cell, with its value locked no matter what
 */
@property (nonatomic) BOOL canEditBiologicalSex;

/*
 * If set to YES, name text field can be edited by the user when isEditing
 * If set to NO, name will not be enabled
 */
@property (nonatomic) BOOL canEditUsersName;

- (IBAction)leaveStudy:(id)sender;

- (IBAction)pauseStudy:(id)sender;

- (IBAction)changeProfileImage:(id)sender;

- (IBAction)editFields:(id)sender;

- (void)loadProfileValuesInModel;

- (void)setupDataFromJSONFile:(NSString *)jsonFileName;

- (NSArray *)prepareContent;

@end

@protocol APCProfileViewControllerDelegate <NSObject>
@optional

- (UITableViewCell *)decorateCell:(UITableViewCell *)cell atIndexPath: (NSIndexPath *)indexPath;

- (BOOL)willDisplayCell:(NSIndexPath *)indexPath;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInAdjustedSection:(NSInteger)section;

- (NSArray *)preparedContent:(NSArray *)array;

- (void)navigationController:(UINavigationController *)navigationController didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtAdjustedIndexPath:(NSIndexPath *)indexPath;

- (void)hasStartedEditing;

- (void)hasFinishedEditing;

/*
 * If canEditBirthDate or canEditBiologicalSex are set to YES,
 * This will be called if the user tries to edit either of them when we are
 * loading them from HealthKit, but writing to HealthKit is not valid
 * Dev should launch a dialog when this is called saying to change in the Health App
 */
- (void) editingFailedForHealthKitType:(NSString*) healthKitIdentifier;

@end


text:
[![Visualizers](https://github.com/DistrictDataLabs/yellowbrick/raw/develop/docs/images/readme/banner.png)](https://www.scikit-yb.org/)

Yellowbrick is a suite of visual analysis and diagnostic tools designed to facilitate machine learning with scikit-learn. The library implements a new core API object, the `Visualizer` that is an scikit-learn estimator — an object that learns from data. Similar to transformers or models, visualizers learn from data by creating a visual representation of the model selection workflow.

Visualizer allow users to steer the model selection process, building intuition around feature engineering, algorithm selection and hyperparameter tuning. For instance, they can help diagnose common problems surrounding model complexity and bias, heteroscedasticity, underfit and overtraining, or class balance issues. By applying visualizers to the model selection workflow, Yellowbrick allows you to steer predictive models toward more successful results, faster.

The full documentation can be found at [scikit-yb.org](https://scikit-yb.org/) and includes a [Quick Start Guide](https://www.scikit-yb.org/en/latest/quickstart.html) for new users.

## Visualizers

Visualizers are estimators — objects that learn from data — whose primary objective is to create visualizations that allow insight into the model selection process. In scikit-learn terms, they can be similar to transformers when visualizing the data space or wrap a model estimator similar to how the `ModelCV` (e.g. [`RidgeCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html), [`LassoCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html)) methods work. The primary goal of Yellowbrick is to create a sensical API similar to scikit-learn. Some of our most popular visualizers include:

### Classification Visualization

- **Classification Report**: a visual classification report that displays a model's precision, recall, and F1 per-class scores as a heatmap
- **Confusion Matrix**: a heatmap view of the confusion matrix of pairs of classes in multi-class classification
- **Discrimination Threshold**: a visualization of the precision, recall, F1-score, and queue rate with respect to the discrimination threshold of a binary classifier
- **Precision-Recall Curve**: plot the precision vs recall scores for different probability thresholds
- **ROCAUC**: graph the receiver operator characteristic (ROC) and area under the curve (AUC)

### Clustering Visualization

- **Intercluster Distance Maps**: visualize the relative distance and size of clusters
- **KElbow Visualizer**: visualize cluster according to the specified scoring function, looking for the "elbow" in the curve.
- **Silhouette Visualizer**: select `k` by visualizing the silhouette coefficient scores of each cluster in a single model

### Feature Visualization

- **Manifold Visualization**: high-dimensional visualization with manifold learning
- **Parallel Coordinates**: horizontal visualization of instances
- **PCA Projection**: projection of instances based on principal components
- **RadViz Visualizer**: separation of instances around a circular plot
- **Rank Features**: single or pairwise ranking of features to detect relationships

### Model Selection Visualization

- **Cross Validation Scores**: display the cross-validated scores as a bar chart with the average score plotted as a horizontal line
- **Feature Importances**: rank features based on their in-model performance
- **Learning Curve**: show if a model might benefit from more data or less complexity
- **Recursive Feature Elimination**: find the best subset of features based on importance
- **Validation Curve**: tune a model with respect to a single hyperparameter

### Regression Visualization

- **Alpha Selection**: show how the choice of alpha influences regularization
- **Cook's Distance**: show the influence of instances on linear regression
- **Prediction Error Plots**: find model breakdowns along the domain of the target
- **Residuals Plot**: show the difference in residuals of training and test data

### Target Visualization

- **Balanced Binning Reference**: generate a histogram with vertical lines showing the recommended value point to the bin data into evenly distributed bins
- **Class Balance**: show the relationship of the support for each class in both the training and test data by displaying how frequently each class occurs as a bar graph the frequency of the classes' representation in the dataset
- **Feature Correlation**: visualize the correlation between the dependent variables and the target

### Text Visualization

- **Dispersion Plot**: visualize how key terms are dispersed throughout a corpus
- **PosTag Visualizer**: plot the counts of different parts-of-speech throughout a tagged corpus
- **Token Frequency Distribution**: visualize the frequency distribution of terms in the corpus
- **t-SNE Corpus Visualization**: uses stochastic neighbor embedding to project documents
- **UMAP Corpus Visualization**: plot similar documents closer together to discover clusters

... and more! Yellowbrick is adding new visualizers all the time so be sure to check out our [examples gallery]https://github.com/DistrictDataLabs/yellowbrick/tree/develop/examples) — or even the [develop](https://github.com/districtdatalabs/yellowbrick/tree/develop) branch — and feel free to contribute your ideas for new Visualizers!

## Affiliations
[![District Data Labs](https://github.com/DistrictDataLabs/yellowbrick/raw/develop/docs/images/readme/affiliates_ddl.png)](https://www.districtdatalabs.com/) [![NumFOCUS Affiliated Project](https://github.com/DistrictDataLabs/yellowbrick/raw/develop/docs/images/readme/affiliates_numfocus.png)](https://numfocus.org/)


text:
name: Query Builder
sort: 6
---

# Query Builder

**QueryBuilder** provides an API for convenient and fluent construction of SQL queries. It consists of a set of methods enabling developers to easily construct SQL queries without compromising readability.

It serves as an alternative to ORM. ORM is more for simple CRUD operations, whereas QueryBuilder is for complex queries with subqueries and multi-joins.

Usage example:

```go
// User is a wrapper for result row in this example
type User struct {
	Name string
	Age  int
}
var users []User

// Get a QueryBuilder object. Takes DB driver name as parameter
// Second return value is error, ignored here
qb, _ := orm.NewQueryBuilder("mysql")

// Construct query object
qb.Select("user.name",
	"profile.age").
	From("user").
	InnerJoin("profile").On("user.id_user = profile.fk_user").
	Where("age > ?").
	OrderBy("name").Desc().
	Limit(10).Offset(0)

// export raw query string from QueryBuilder object
sql := qb.String()

// execute the raw query string
o := orm.NewOrm()
o.Raw(sql, 20).QueryRows(&users)
```

Full API interface:

```go
type QueryBuilder interface {
	Select(fields ...string) QueryBuilder
	From(tables ...string) QueryBuilder
	InnerJoin(table string) QueryBuilder
	LeftJoin(table string) QueryBuilder
	RightJoin(table string) QueryBuilder
	On(cond string) QueryBuilder
	Where(cond string) QueryBuilder
	And(cond string) QueryBuilder
	Or(cond string) QueryBuilder
	In(vals ...string) QueryBuilder
	OrderBy(fields ...string) QueryBuilder
	Asc() QueryBuilder
	Desc() QueryBuilder
	Limit(limit int) QueryBuilder
	Offset(offset int) QueryBuilder
	GroupBy(fields ...string) QueryBuilder
	Having(cond string) QueryBuilder
	Subquery(sub string, alias string) string
	String() string
}
```


text:
from openturns import *
from cmath import *

TESTPREAMBLE()
RandomGenerator.SetSeed(0)

try:
    # Instanciate one distribution object
    distribution = FisherSnedecor(5.5, 10.5)
    print "Distribution ", repr(distribution)
    print "Distribution ", distribution

    # Is this distribution elliptical ?
    print "Elliptical = ", distribution.isElliptical()

    # Is this distribution continuous ?
    print "Continuous = ", distribution.isContinuous()

    # Test for realization of distribution
    oneRealization = distribution.getRealization()
    print "oneRealization=", repr(oneRealization)

    # Test for sampling
    size = 10000
    oneSample = distribution.getSample(size)
    print "oneSample first=", repr(oneSample[0]), " last=", repr(oneSample[size - 1])
    print "mean=", repr(oneSample.computeMean())
    print "covariance=", repr(oneSample.computeCovariance())

    size = 100
    for i in range(2):
        msg = ''
        if FittingTest.Kolmogorov(distribution.getSample(size), distribution).getBinaryQualityMeasure():
            msg = "accepted"
        else:
            msg = "rejected"
        print "Kolmogorov test for the generator, sample size=", size, " is", msg
        size *= 10

    # Define a point
    point = NumericalPoint(distribution.getDimension(), 1.0)
    print "Point= ", repr(point)

    # Show PDF and CDF of point
    eps = 1e-5

    # derivative of PDF with regards its arguments
    DDF = distribution.computeDDF(point)
    # print "ddf     =" , repr(DDF)
    # by the finite difference technique
    # print "ddf (FD)=" ,repr(NumericalPoint(1, (distribution.computePDF(
    # point + NumericalPoint(1, eps) ) - distribution.computePDF( point  +
    # NumericalPoint(1, -eps) )) / (2.0 * eps)))

    # PDF value
    LPDF = distribution.computeLogPDF(point)
    print "log pdf=%.6f" % LPDF
    PDF = distribution.computePDF(point)
    print "pdf     =%.6f" % PDF
    # by the finite difference technique from CDF
    print "pdf (FD)=%.6f" % ((distribution.computeCDF(point + NumericalPoint(1, eps)) - distribution.computeCDF(point + NumericalPoint(1, -eps))) / (2.0 * eps))

    # derivative of the PDF with regards the parameters of the distribution
    CDF = distribution.computeCDF(point)
    print "cdf=%.6f" % CDF
    CCDF = distribution.computeComplementaryCDF(point)
    print "ccdf=%.6f" % CCDF
    CF = distribution.computeCharacteristicFunction(point[0])
    print "characteristic function=(%.6f+%.6fj)" % (CF.real, CF.imag)
    ## PDFgr = distribution.computePDFGradient( point )
    # print "pdf gradient     =" , repr(PDFgr)
    # by the finite difference technique
    ## PDFgrFD = NumericalPoint(2)
    ## PDFgrFD[0] = (FisherSnedecor(distribution.getLambda() + eps, distribution.getGamma()).computePDF(point) - FisherSnedecor(distribution.getLambda() - eps, distribution.getGamma()).computePDF(point)) / (2.0 * eps)
    ## PDFgrFD[1] = (FisherSnedecor(distribution.getLambda(), distribution.getGamma() + eps).computePDF(point) - FisherSnedecor(distribution.getLambda(), distribution.getGamma() - eps).computePDF(point)) / (2.0 * eps)
    # print "pdf gradient (FD)=" , repr(PDFgrFD)

    # derivative of the PDF with regards the parameters of the distribution
    ## CDFgr = distribution.computeCDFGradient( point )
    # print "cdf gradient     =" , repr(CDFgr)
    ## CDFgrFD = NumericalPoint(2)
    ## CDFgrFD[0] = (FisherSnedecor(distribution.getLambda() + eps, distribution.getGamma()).computeCDF(point) - FisherSnedecor(distribution.getLambda() - eps, distribution.getGamma()).computeCDF(point)) / (2.0 * eps)
    ## CDFgrFD[1] = (FisherSnedecor(distribution.getLambda(), distribution.getGamma() + eps).computeCDF(point) - FisherSnedecor(distribution.getLambda(), distribution.getGamma() - eps).computeCDF(point)) / (2.0 * eps)
    # print "cdf gradient (FD)=",  repr(CDFgrFD)

    # quantile
    quantile = distribution.computeQuantile(0.95)
    print "quantile=", repr(quantile)
    print "cdf(quantile)=%.6f" % distribution.computeCDF(quantile)
    mean = distribution.getMean()
    print "mean=", repr(mean)
    standardDeviation = distribution.getStandardDeviation()
    print "standard deviation=", repr(standardDeviation)
    skewness = distribution.getSkewness()
    print "skewness=", repr(skewness)
    kurtosis = distribution.getKurtosis()
    print "kurtosis=", repr(kurtosis)
    covariance = distribution.getCovariance()
    print "covariance=", repr(covariance)
    parameters = distribution.getParametersCollection()
    print "parameters=", repr(parameters)
    for i in range(6):
        print "standard moment n=", i, " value=", distribution.getStandardMoment(i)
    print "Standard representative=", distribution.getStandardRepresentative()

except:
    import sys
    print "t_FisherSnedecor_std.py", sys.exc_type, sys.exc_value


text:
layout: jurisdiction
title: Gauteng Provincial Gazettes
jurisdiction: ZA-GT
jurisdiction_name: Gauteng
provincial: true
---


text:
**strong** or __strong__

*emphasize* or _emphasize_

#### Blockquotes

> Right angle brackets > are used for block quotes.

#### Links and Email

An email <hanxvdovehx@gmail.com> link.韩旭

Simple inline link <http://github.com/superhx>, another inline link

Simple inline link <http://github.com/superhx>, another inline link [superhx](http://github.com/superhx), one more inline link with title [superhx](http://github.com/superhx "superhx's github").

A [reference style][superhx] link. Input id, then anywhere in the doc, define the link with corresponding id:

[superhx]: http://github.com/superhx "superhx's github"

Titles ( or called tool tips ) in the links are optional.

#### Images

An inline image, title is optional![Smaller icon](https://avatars2.githubusercontent.com/u/5719209?v=3&s=460 "Title here").

A reference style image ![Resize icon][2].

[2]: https://avatars2.githubusercontent.com/u/5719209?v=3&s=460 "Title here"

Control image style by youself.[](http://github.com/superhx)

#### Inline code and Block code

Inline code are surround by `backtick` key. To create a block code:

  Indent each line by at least 1 tab, 2 spaces or 4 spaces.
  var Mou = exactlyTheAppIwant;

####  Ordered Lists

Ordered lists are created using "1." + Space:

1. Ordered list item
2. Ordered list item
3. Ordered list item

#### Unordered Lists

Unordered list are created using "\*" + Space:

* Unordered list item
* Unordered list item
* Unordered list item

Or using "-" + Space:

- Unordered list item
- Unordered list item
- Unordered list item

#### Hard Linebreak

End a line with two or more spaces will create a hard linebreak, called `<br />` in HTML.
Above line ended with 2 spaces.

#### Horizontal Rules

Three or more asterisks or dashes:

***

---

-- - -

#### Headers

Setext-style:

This is H1
==========

This is H2
----------

atx-style:

# This is H1
## This is H2
### This is H3
#### This is H4
##### This is H5
###### This is H6

### Extra Syntax

#### Strikethrough

Wrap with 2 tilde characters:

~~Strikethrough~~

#### Fenced Code Blocks

Start with a line containing 3 or more backticks, and ends with the first line with the same number of backticks:

```
Fenced code blocks are like Stardard Markdown's regular code
blocks, except that they're not indented and instead rely on
a start and end fence lines to delimit the code block.
```

#### Tables

A simple table looks like this:

First Header | Second Header | Third Header
------------ | ------------- | ------------
Content Cell | Content Cell  | Content Cell
Content Cell | Content Cell  | Content Cell

If you wish, you can add a leading and tailing pipe to each line of the table:

| First Header | Second Header | Third Header |
| ------------ | ------------- | ------------ |
| Content Cell | Content Cell  | Content Cell |
| Content Cell | Content Cell  | Content Cell |

Specify alignment for each column by adding colons to separator lines:

First Header | Second Header | Third Header
:----------- | :-----------: | -----------:
Left         | Center        | Right
Left         | Center        | Right


text:
class C {
  //- @R defines/binding ClassR
  //- ClassR childof ClassC
  class R { };
};


text:
package main

import (
	"io/ioutil"
	"os"
	"strings"
	"testing"

	"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
)

func TestMain(t *testing.T) {
	tc := testutil.SystemTest(t)
	os.Setenv("GOOGLE_CLOUD_PROJECT", tc.ProjectID)

	oldStdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w

	main()

	w.Close()
	os.Stdout = oldStdout

	out, err := ioutil.ReadAll(r)
	if err != nil {
		t.Fatalf("Failed to read stdout: %v", err)
	}
	if got, want := string(out), "assets:"; !strings.Contains(got, want) && len(got) > 0 {
		t.Errorf("stdout returned %s, wanted either empty or contain %s", got, want)
	}
}


text:
import ACTIONS from './actionTypes/index';

/**
 * Initiate the workflow by making request for the button bars data.
 * @function
 * @return {action}
 */
export const fetchData = () => ({
  type: ACTIONS.BUTTON_BARS.FETCH
});

/**
 * Save the data into the store. This is a destructive operation.
 * @function
 * @param {{ buttons: [number], bars: [number] }} data - the data to store.
 * @return {action}
 */
export const saveData = data => ({
  type: ACTIONS.BUTTON_BARS.SAVE,
  value: data
});

/**
 * Update the given Bar by index, adding the given percentage to the value. This could be a negative number, decrementing the value.
 * @function
 * @param {{index:number,percentage:number}} data - the data to store.
 * @return {action}
 */
export const updateBar = (data) => ({
  type: ACTIONS.BUTTON_BARS.UPDATE,
  value: data
});


text:
#ifndef __OBJECT_FILE_HH__
#define __OBJECT_FILE_HH__

#include <limits>
#include <string>

#include "base/misc.hh"
#include "base/types.hh"

class PortProxy;
class SymbolTable;

class ObjectFile
{
  public:

    enum Arch {
        UnknownArch,
        Alpha,
        SPARC64,
        SPARC32,
        Mips,
        X86_64,
        I386,
        Arm64,
        Arm,
        Thumb,
        Power
    };

    enum OpSys {
        UnknownOpSys,
        Tru64,
        Linux,
        Solaris,
        LinuxArmOABI,
        FreeBSD
    };

  protected:
    const std::string filename;
    uint8_t *fileData;
    size_t len;

    Arch  arch;
    OpSys opSys;

    ObjectFile(const std::string &_filename, size_t _len, uint8_t *_data,
               Arch _arch, OpSys _opSys);

  public:
    virtual ~ObjectFile();

    static const Addr maxAddr = std::numeric_limits<Addr>::max();

    virtual bool loadSections(PortProxy& mem_proxy,
                              Addr mask = maxAddr, Addr offset = 0);

    virtual bool loadAllSymbols(SymbolTable *symtab, Addr base = 0,
                                Addr offset = 0, Addr mask = maxAddr) = 0;
    virtual bool loadGlobalSymbols(SymbolTable *symtab, Addr base = 0,
                                   Addr offset = 0, Addr mask = maxAddr) = 0;
    virtual bool loadLocalSymbols(SymbolTable *symtab, Addr base = 0,
                                  Addr offset = 0, Addr mask = maxAddr) = 0;
    virtual bool loadWeakSymbols(SymbolTable *symtab, Addr base = 0,
                                 Addr offset = 0, Addr mask = maxAddr)
    { return false; }

    virtual ObjectFile *getInterpreter() const { return nullptr; }
    virtual bool relocatable() const { return false; }
    virtual Addr mapSize() const
    { panic("mapSize() should only be called on relocatable objects\n"); }
    virtual void updateBias(Addr bias_addr)
    { panic("updateBias() should only be called on relocatable objects\n"); }
    virtual Addr bias() const { return 0; }

    virtual bool hasTLS() { return false; }

    Arch  getArch()  const { return arch; }
    OpSys getOpSys() const { return opSys; }

  protected:

    struct Section {
        Addr     baseAddr;
        uint8_t *fileImage;
        size_t   size;
    };

    Addr entry;
    Addr globalPtr;

    Section text;
    Section data;
    Section bss;

    bool loadSection(Section *sec, PortProxy& mem_proxy, Addr mask,
                     Addr offset = 0);
    void setGlobalPointer(Addr global_ptr) { globalPtr = global_ptr; }

  public:
    Addr entryPoint() const { return entry; }

    Addr globalPointer() const { return globalPtr; }

    Addr textBase() const { return text.baseAddr; }
    Addr dataBase() const { return data.baseAddr; }
    Addr bssBase() const { return bss.baseAddr; }

    size_t textSize() const { return text.size; }
    size_t dataSize() const { return data.size; }
    size_t bssSize() const { return bss.size; }

    /* This function allows you to override the base address where
     * a binary is going to be loaded or set it if the binary is just a
     * blob that doesn't include an object header.
     * @param a address to load the binary/text section at
     */
    void setTextBase(Addr a) { text.baseAddr = a; }
};

ObjectFile *createObjectFile(const std::string &fname, bool raw = false);

#endif // __OBJECT_FILE_HH__


text:
using System;
using System.Globalization;
using QuantConnect.Configuration;
using QuantConnect.Logging;

namespace QuantConnect.ToolBox.QuandlBitfinexDownloader
{
    class Program
    {
        /// <summary>
        /// Quandl Bitfinex Toolbox Project For LEAN Algorithmic Trading Engine.
        /// </summary>
        static void Main(string[] args)
        {

            if (args.Length != 2)
            {
                Console.WriteLine("Usage: Downloader FROMDATE APIKEY");
                Console.WriteLine("FROMDATE = yyyymmdd");
                //Environment.Exit(1);
                //todo: remove default args
                args = new string[] { "20140101", "vAhfNvBxVe3Ev66cjbTY" };
            }

            try
            {
                // Load settings from config.json
                var dataDirectory = Config.Get("data-directory", "../../../Data");

                // Create an instance of the downloader
                const string market = Market.Bitcoin;
                var downloader = new QuandlBitfinexDownloader(args[1]);

                // Download the data
                var symbol = Symbol.Create("BTCUSD", SecurityType.Forex, market);
                var data = downloader.Get(symbol, Resolution.Daily, DateTime.ParseExact(args[0], "yyyyMMdd", CultureInfo.CurrentCulture), DateTime.UtcNow);

                // Save the data
                var writer = new LeanDataWriter(SecurityType.Forex, Resolution.Daily, symbol, dataDirectory, market);
                writer.Write(data);

            }
            catch (Exception err)
            {
                Log.Error(err);
            }
        }
    }
}


text:
<?php

namespace app\modules\blog\controllers\admin;

use app\modules\blog\models\Blog;
use app\modules\blog\models\BlogSearch;
use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\core\models\TagRel;
use yii\helpers\ArrayHelper;

/**
 * DefaultController implements the CRUD actions for Task model.
 */
class ProfileController extends \app\core\web\ProfileController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'pl-upload' => [
                'class' => 'app\core\web\PluploadAction',
            ],
            'ue-upload' => [
                'class' => 'app\core\widgets\Ueditor\UploadAction',
            ],
            'album-upload' => [
                'class' => 'app\core\web\AlbumUploadAction',
                'type' =>'blog_album'
            ]
        ];
    }

    /**
     * Lists all Task models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BlogSearch();
        $params = Yii::$app->request->queryParams;
        $params['BlogSearch']['created_by'] = Yii::$app->user->id;

        $dataProvider = $searchModel->search($params);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionView($id)
    {
        $tags = TagRel::getTagsByRes('blog', $id);
        $tags = implode(',', ArrayHelper::getColumn($tags, 'tag_name')) ;
        return $this->renderAjax('view', [
            'model' => $this->findModel($id),
            'tags' => $tags
        ]);
    }

    public function actionCreate()
    {
        $model = new Blog();

        if ($model->load(Yii::$app->request->post()) ) {

            $model->is_customer = Yii::$app->user->identity->isStaff() ? 0 : 1;
            $model->ip = Yii::$app->request->getUserIP();
            $model->status = Yii::$app->params['blog']['blogInitStatus'];
            $model->created_by = Yii::$app->user->id;

            if ($model->save() !== false) {
                if ($model->tags) {
                    $this->tagCreate($model->tags, $model->id);
                }
                Yii::$app->session->setFlash('success', '添加博客成功');
            } else {
                Yii::$app->session->setFlash('error', '添加博客失败,请重试或联系管理员');
            }

            return $this->redirect(['index']);
        }

        $model->type = Blog::TYPE_TEXT;
        $model->privacy = Blog::PRIVACY_PUBLIC;
        return $this->renderAjax('create', [
            'model' => $model,
            'tags' => ''
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($model->tags) {
                $this->tagCreate($model->tags, $model->id);
            }
            return $this->redirect(['index']);
        }

        $tags = TagRel::getTagsByRes('blog', $id);
        $tags = implode(',', ArrayHelper::getColumn($tags, 'tag_name')) ;

        return $this->renderAjax('update', [
            'model' => $model,
            'tags' => $tags
        ]);

    }

    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->status = Blog::STATUS_DELETE;
        $model->save();

        return $this->redirect(['index']);
    }

    private function tagCreate($str, $id)
    {
        $str = str_replace(',', ',', $str);
        $tags = explode(',', $str);
        TagRel::addTagRel($tags, 'blog', $id);
    }

    protected function findModel($id)
    {
        if (($model = Blog::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
package main

import (
	"fmt"
	"log"

	"github.com/wzzlYwzzl/httpdatabase/client"
	"github.com/wzzlYwzzl/httpdatabase/resource/user"
)

func TestBasic() {
	clientConf := client.HttpDBClient{Host: "localhost:9080"}
	user := &user.User{Name: "test-zjw", Password: "test-zjw", Cpus: 10, Memory: 500, CpusUse: 8, MemoryUse: 123}

	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	//test 1
	b, err := clientConf.JudgeName("admin", "admin123")
	if err != nil {
		fmt.Println("judegeName Error")
		return
	}
	if b == true {
		fmt.Println("JudgeName work well")
	} else {
		fmt.Println("JudgeName doesn't work")
	}

	//test2
	b, err = clientConf.CreateNS("admin", "admin_namespace_test")
	if err != nil {
		fmt.Println("CreateNS Error")
		return
	}
	if b == true {
		fmt.Println("CreateNS work well")
	} else {
		fmt.Println("CreateNS doesn't work")
	}

	//test3
	ns, err := clientConf.GetNS("admin")
	if err != nil {
		fmt.Println("GetNS Error")
		return
	}
	if len(ns) != 0 {
		fmt.Println("GetNS work well")
		fmt.Println(ns)
	} else {
		fmt.Println("GetNS doesn't work")
	}

	//test4
	ns, err = clientConf.GetNSAll("admin")
	if err != nil {
		fmt.Println("GetNSAll Error")
		return
	}
	if len(ns) != 0 {
		fmt.Println("GetNSAll work well")
		fmt.Println(ns)
	} else {
		fmt.Println("GetNSAll doesn't work")
	}

	//test5
	us, err := clientConf.GetAllInfo("admin")
	if err != nil {
		fmt.Println("GetAllInfo Error")
		return
	}
	if len(ns) != 0 {
		fmt.Println("GetAllInfo work well")
		fmt.Println(us)
	} else {
		fmt.Println("GetAllInfo doesn't work")
	}

	//test6
	b, err = clientConf.CreateUser(user)
	if err != nil {
		fmt.Println("CreateUser Error")
		return
	}
	if b == true {
		fmt.Println("CreateUser work well")
	} else {
		fmt.Println("CreateUser doesn't work")
	}

	// //test7
	// b, err = clientConf.DeleteUser("test-zjw")
	// if err != nil {
	// 	fmt.Println("DeleteUser Error")
	// 	return
	// }
	// if b == true {
	// 	fmt.Println("DeleteUser work well")
	// } else {
	// 	fmt.Println("DeleteUser doesn't work")
	// }

	//test8
	b, err = clientConf.UpdateResource(user)
	if err != nil {
		fmt.Println("UpdateResource Error")
		return
	}
	if b == true {
		fmt.Println("UpdateResource work well")
	} else {
		fmt.Println("UpdateResource doesn't work")
	}

	//test9
	userlist, err := clientConf.GetAllUserInfo()
	if err != nil {
		fmt.Println("GetAllUserInfo Error")
		return
	} else {
		fmt.Println(userlist)
	}

}


text:
from django.core.management.base import BaseCommand
from services.models import ServiceModel

class Command(BaseCommand):
    help = 'Pings all services and updates their history'
    args = '<should_force_ping>'

    def handle(self, *args, **options):
        """
        Executes the ``python manage.py pingservices`` command.
        To force a ping of all services use ``python manage.py pingservices forceping``
        """
        force_ping = False
        if args:
            force_ping = True

        will_be_pinging_all = 'Will' if force_ping else 'Will not'
        self.stdout.write(will_be_pinging_all + ' be force ping of all services.')
        self.stdout.write('Current Status:')

        for service in ServiceModel.objects.all():
            service.ping(force_ping)
            is_up = 'up.' if service.is_up else 'down.'
            self.stdout.write('    ' + service.name + ' in group ' + service.service_group.name + ' is ' + is_up)

        self.stdout.write('Finished checking the health of services.')


text:
<?php

namespace Symfony\Component\Finder\Tests\Iterator;

abstract class RealIteratorTestCase extends IteratorTestCase
{
    protected static $tmpDir;
    protected static $files;

    public static function setUpBeforeClass()
    {
        self::$tmpDir = realpath(sys_get_temp_dir()) . DIRECTORY_SEPARATOR . 'symfony_finder';

        self::$files = array(
            '.git/',
            '.foo/',
            '.foo/.bar',
            '.foo/bar',
            '.bar',
            'test.py',
            'foo/',
            'foo/bar.tmp',
            'test.php',
            'toto/',
            'foo bar',
        );

        self::$files = self::toAbsolute(self::$files);

        if (is_dir(self::$tmpDir)) {
            self::tearDownAfterClass();
        } else {
            mkdir(self::$tmpDir);
        }

        foreach (self::$files as $file) {
            if (DIRECTORY_SEPARATOR === $file[strlen($file) - 1]) {
                mkdir($file);
            } else {
                touch($file);
            }
        }

        file_put_contents(self::toAbsolute('test.php'), str_repeat(' ', 800));
        file_put_contents(self::toAbsolute('test.py'), str_repeat(' ', 2000));

        touch(self::toAbsolute('foo/bar.tmp'), strtotime('2005-10-15'));
        touch(self::toAbsolute('test.php'), strtotime('2005-10-15'));
    }

    public static function tearDownAfterClass()
    {
        foreach (array_reverse(self::$files) as $file) {
            if (DIRECTORY_SEPARATOR === $file[strlen($file) - 1]) {
                @rmdir($file);
            } else {
                @unlink($file);
            }
        }
    }

    protected static function toAbsolute($files = null)
    {
        /*
         * Without the call to setUpBeforeClass() property can be null.
         */
        if (!self::$tmpDir) {
            self::$tmpDir = realpath(sys_get_temp_dir()) . DIRECTORY_SEPARATOR . 'symfony_finder';
        }

        if (is_array($files)) {
            $f = array();
            foreach ($files as $file) {
                if (is_array($file)) {
                    $f[] = self::toAbsolute($file);
                } else {
                    $f[] = self::$tmpDir . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $file);
                }
            }

            return $f;
        }

        if (is_string($files)) {
            return self::$tmpDir . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $files);
        }

        return self::$tmpDir;
    }

    protected static function toAbsoluteFixtures($files)
    {
        $f = array();
        foreach ($files as $file) {
            $f[] = realpath(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . $file);
        }

        return $f;
    }
}


text:
package org.apache.logging.log4j.web;

import java.util.AbstractMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import jakarta.servlet.ServletContext;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.impl.ContextAnchor;

/**
 * Convenience methods for retrieving the {@link org.apache.logging.log4j.core.LoggerContext} associated with a
 * particular ServletContext. These methods are most particularly useful for asynchronous servlets where the
 * Thread Context ClassLoader (TCCL) is potentially different from the TCCL used by the
 * Servlet container that bootstrapped Log4j.
 *
 * @since 2.0.1
 */
public final class WebLoggerContextUtils {
    private WebLoggerContextUtils() {
    }

    private static final Lock WEB_SUPPORT_LOOKUP = new ReentrantLock();
    private static final String SERVLET_CONTEXT = "__SERVLET_CONTEXT__";

    /**
     * Finds the main {@link org.apache.logging.log4j.core.LoggerContext} configured for the given ServletContext.
     *
     * @param servletContext the ServletContext to locate a LoggerContext for
     * @return the LoggerContext for the given ServletContext
     * @since 2.0.1
     */
    public static LoggerContext getWebLoggerContext(final ServletContext servletContext) {
        return (LoggerContext) servletContext.getAttribute(Log4jWebSupport.CONTEXT_ATTRIBUTE);
    }

    /**
     * Finds the main {@link org.apache.logging.log4j.core.LoggerContext} configured for the given ServletContext.
     *
     * @param servletContext the ServletContext to locate a LoggerContext for
     * @return the LoggerContext for the given ServletContext or {@code null} if none was set
     * @throws java.lang.IllegalStateException if no LoggerContext could be found on the given ServletContext
     * @since 2.0.1
     */
    public static LoggerContext getRequiredWebLoggerContext(final ServletContext servletContext) {
        final LoggerContext loggerContext = getWebLoggerContext(servletContext);
        if (loggerContext == null) {
            throw new IllegalStateException(
                "No LoggerContext found in ServletContext attribute " + Log4jWebSupport.CONTEXT_ATTRIBUTE);
        }
        return loggerContext;
    }

    /**
     * Finds or initializes the {@link org.apache.logging.log4j.web.Log4jWebLifeCycle} singleton for the given
     * ServletContext.
     *
     * @param servletContext the ServletContext to get the Log4jWebLifeCycle for
     * @return the Log4jWebLifeCycle for the given ServletContext
     * @since 2.0.1
     */
    public static Log4jWebLifeCycle getWebLifeCycle(final ServletContext servletContext) {
        WEB_SUPPORT_LOOKUP.lock();
        try {
            Log4jWebLifeCycle webLifeCycle = (Log4jWebLifeCycle) servletContext.getAttribute(
                Log4jWebSupport.SUPPORT_ATTRIBUTE);
            if (webLifeCycle == null) {
                webLifeCycle = Log4jWebInitializerImpl.initialize(servletContext);
            }
            return webLifeCycle;
        } finally {
            WEB_SUPPORT_LOOKUP.unlock();
        }
    }

    /**
     * Wraps a Runnable instance by setting its thread context {@link org.apache.logging.log4j.core.LoggerContext}
     * before execution and clearing it after execution.
     *
     * @param servletContext the ServletContext to locate a LoggerContext for
     * @param runnable       the Runnable to wrap execution for
     * @return a wrapped Runnable
     * @since 2.0.1
     */
    public static Runnable wrapExecutionContext(final ServletContext servletContext, final Runnable runnable) {
        return () -> {
            final Log4jWebSupport webSupport = getWebLifeCycle(servletContext);
            webSupport.setLoggerContext();
            try {
                runnable.run();
            } finally {
                webSupport.clearLoggerContext();
            }
        };
    }

    public static Map.Entry<String, Object> createExternalEntry(ServletContext servletContext) {
        return new AbstractMap.SimpleEntry<>(SERVLET_CONTEXT, servletContext);
    }

    public static void setServletContext(LoggerContext lc, ServletContext servletContext) {
        if (lc != null) {
            lc.putObject(SERVLET_CONTEXT, servletContext);
        }
    }

    /**
     * Gets the current {@link ServletContext} if it has already been assigned to a LoggerContext's external context.
     *
     * @return the current ServletContext attached to a LoggerContext or {@code null} if none could be found
     * @since 2.1
     */
    public static ServletContext getServletContext() {
        org.apache.logging.log4j.spi.LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
        if (lc == null) {
            lc = LogManager.getContext(false);
        }

        Object obj = lc != null ? lc.getObject(SERVLET_CONTEXT) : null;
        if (obj instanceof ServletContext) {
            return (ServletContext) obj;
        }
        return null;
    }
}


text:
<?php

namespace App\Model;

/**
 * Description of Permissions
 *
 * @author JDC
 */
class Permissions extends \Nette\Security\Permission {

	public function __construct() {

		//Roles
		$this->addRole("guest");
		$this->addRole("user", "guest");
		$this->addRole("revizor", "user");
		$this->addRole("asistent", "revizor");
		$this->addRole("manager", "asistent");
		$this->addRole("admin"); //Superuser

		//Admin areas
		$this->addResource("admin");
		$this->addResource("system");
		$this->addResource("content");
		$this->addResource("songator");
		$this->addResource("account");

		//Front areas
		$this->addResource("song");
		$this->addResource("interpret");
		$this->addResource("wip");
		$this->addResource("ucp");
		$this->addResource("sign");
		$this->addResource("privateMsg");
		$this->addResource("genre");
		$this->addResource("events");

		//Privileges
		$this->deny(array("guest", "user"), "system"); //Security

		$this->allow("guest", "song", array("draft", "view", "play"));
		$this->allow("guest", "interpret", array("draft", "view"));

		$this->allow("user", "song", array("like"));
		$this->allow("user", "ucp", array("view", "save"));
		$this->allow("user", "privateMsg", "add");

		$this->allow("revizor", "song", array("approve", "reject"));
		$this->allow("revizor", "wip", array("switch"));
		$this->allow("revizor", "privateMsg", "view");

		$this->allow("asistent", "admin", "view");
		$this->allow("asistent", "song", array("manage", "add", "edit", "remove"));
		$this->allow("asistent", "interpret", array("manage", "add", "edit", "remove", "assoc", "approve"));
		$this->allow("asistent", "genre", array("edit", "remove"));

		$this->allow("manager", "content", array("manage", "add", "edit", "remove"));
		$this->allow("manager", "songator", "edit");
		$this->allow("manager", "events", self::ALL);

		$this->allow("admin", self::ALL, self::ALL); //Admin can all
	}

	public function getRoles() {
		$roles = parent::getRoles();
		return array_combine($roles, $roles);
	}

}


text:
/**
 * @file crypto.c
 *
 * Wrapper for the monocypher crypto
 *
 */

#include <inttypes.h>
#include <stdbool.h>

#include <px4_platform_common/crypto_backend.h>
#include <lib/crypto/monocypher/src/optional/monocypher-ed25519.h>

/* room for 16 keys */
#define KEY_CACHE_LEN 16

#ifndef SECMEM_ALLOC
#define SECMEM_ALLOC malloc
#endif

#ifndef SECMEM_FREE
#define SECMEM_FREE free
#endif

/*
 * For now, this is just a dummy up/down counter for tracking open/close calls
 */
static int crypto_open_count = 0;

typedef struct {
	size_t key_size;
	uint8_t *key;
} volatile_key_t;

static volatile_key_t key_cache[KEY_CACHE_LEN];

/* Clear key cache */
static void clear_key_cache(void)
{
	for (int i = 0; i < KEY_CACHE_LEN ; i++) {
		SECMEM_FREE(key_cache[i].key);
		key_cache[i].key = NULL;
		key_cache[i].key_size = 0;
	}
}

/* Retrieve a direct pointer to the cached temporary/public key */
static const uint8_t *crypto_get_key_ptr(keystore_session_handle_t handle, uint8_t key_idx,
		size_t *len)
{
	uint8_t *ret;

	if (key_idx >= KEY_CACHE_LEN) {
		*len = 0;
		return NULL;
	}

	ret = key_cache[key_idx].key;

	/* if the key doesn't exist in the key cache, try to read it in there from keystore */
	if (ret == NULL) {

		/* First check if the key exists in the keystore and retrieve its length */
		*len = keystore_get_key(handle, key_idx, NULL, 0);

		if (*len > 0) {

			/* Allocate memory for the key in the cache */
			ret = SECMEM_ALLOC(*len);

			/* Retrieve the key from the keystore */
			if (ret) {
				if (keystore_get_key(handle, key_idx, ret, *len) > 0) {
					/* Success, store the key in cache */
					key_cache[key_idx].key_size = *len;
					key_cache[key_idx].key = ret;

				} else {
					/* key retrieval failed, free the memory */
					SECMEM_FREE(ret);
				}
			}
		}
	}

	*len = key_cache[key_idx].key_size;

	return ret;
}

void crypto_init()
{
	keystore_init();
	clear_key_cache();
}

crypto_session_handle_t crypto_open(px4_crypto_algorithm_t algorithm)
{
	crypto_session_handle_t ret;
	ret.algorithm = algorithm;
	ret.keystore_handle = keystore_open();

	if (keystore_session_handle_valid(ret.keystore_handle)) {
		ret.handle = ++crypto_open_count;

	} else {
		ret.handle = 0;
	}

	return ret;
}

void crypto_close(crypto_session_handle_t *handle)
{
	crypto_open_count--;
	handle->handle = 0;
	keystore_close(&handle->keystore_handle);
}

bool crypto_signature_check(crypto_session_handle_t handle,
			    uint8_t  key_index,
			    const uint8_t  *signature,
			    const uint8_t *message,
			    size_t message_size)
{
	bool ret = false;
	size_t keylen = 0;
	const uint8_t *public_key;

	if (crypto_session_handle_valid(handle)) {
		public_key = crypto_get_key_ptr(handle.keystore_handle, key_index, &keylen);
	}

	if (keylen == 0) {
		return false;
	}

	switch (handle.algorithm) {
	case CRYPTO_ED25519:
		ret = crypto_ed25519_check(signature, public_key, message, message_size) == 0;
		break;

	default:
		ret = false;
	}

	return ret;
}