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

<title>UserInterface</title>
<meta name="date" content="2015-09-30">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

user

Interface UserInterface

All Known Implementing Classes:

User

public interface UserInterface

User½Ó¿Ú

Author:

Geurney

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
host

host

static java.lang.String
STATE_ABORT

ÖÕÖ¹ÏûÏ¢Flag

static java.lang.String
STATE_BLOGINFO

²©¿ÍÐÅÏ¢ÏûÏ¢Flag

static java.lang.String
STATE_DONE

Íê³ÉÏûÏ¢Flag

static java.lang.String
STATE_PROFILE

Óû§Í·ÏñÏûÏ¢Flag

static java.lang.String
STATE_PROGRESS

½ø¶ÈÏûÏ¢Flag

static java.lang.String
STATE_SYSTEM

ϵͳÏûÏ¢Flag

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

boolean
crawlBlog(java.lang.String category,
         java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String> link)

ÅÀÈ¡ÎÄÕÂÄÚÈÝ

java.util.List<java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String>>
crawlCategory(java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String> category)

ÅÀÈ¡·ÖÀàϵÄÎÄÕÂÁ´½Ó

void
createIndex()

´´½¨ÎÄÕÂË÷Òý

boolean
profile()

ÅÀÈ¡Ê×Ò³²©¿ÍÐÅÏ¢¡¢Óû§Í·ÏñºÍÎÄÕ·ÖÀà¡£

Field Detail

host

static final java.lang.String host

host

See Also:

Constant Field Values

STATE_BLOGINFO

static final java.lang.String STATE_BLOGINFO

²©¿ÍÐÅÏ¢ÏûÏ¢Flag

See Also:

Constant Field Values

STATE_PROFILE

static final java.lang.String STATE_PROFILE

Óû§Í·ÏñÏûÏ¢Flag

See Also:

Constant Field Values

STATE_SYSTEM

static final java.lang.String STATE_SYSTEM

ϵͳÏûÏ¢Flag

See Also:

Constant Field Values

STATE_DONE

static final java.lang.String STATE_DONE

Íê³ÉÏûÏ¢Flag

See Also:

Constant Field Values

STATE_PROGRESS

static final java.lang.String STATE_PROGRESS

½ø¶ÈÏûÏ¢Flag

See Also:

Constant Field Values

STATE_ABORT

static final java.lang.String STATE_ABORT

ÖÕÖ¹ÏûÏ¢Flag

See Also:

Constant Field Values

Method Detail

profile

boolean profile()

ÅÀÈ¡Ê×Ò³²©¿ÍÐÅÏ¢¡¢Óû§Í·ÏñºÍÎÄÕ·ÖÀà¡£

Returns:

True ÅÀÈ¡³É¹¦¡£False ÅÀȡʧ°Ü

crawlCategory

java.util.List<java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String>> crawlCategory(java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String> category)

ÅÀÈ¡·ÖÀàϵÄÎÄÕÂÁ´½Ó

Parameters:

category - ÎÄÕÂÀàÃû

Returns:

·ÖÀàϵÄËùÓÐÎÄÕÂÁ´½Ó

crawlBlog

boolean crawlBlog(java.lang.String category,
                  java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String> link)

ÅÀÈ¡ÎÄÕÂÄÚÈÝ

Parameters:

category - ÎÄÕÂÀàÃû

link - ÎÄÕ±êÌâºÍurlµØÖ·

Returns:

True ÅÀÈ¡³É¹¦¡£False ÅÀȡʧ°Ü

createIndex

void createIndex()
          throws java.io.IOException

´´½¨ÎÄÕÂË÷Òý

Throws:

java.io.IOException - ´´½¨Ë÷Òýʧ°Ü

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.zenvv.live.demo;

import android.app.Activity;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.zenvv.live.LivePusher;
import com.zenvv.live.LiveStateListener;
import com.zenvv.livepusher.R;

public class MainActivity extends Activity implements OnClickListener,
		Callback, LiveStateListener {
	private final static String TAG = "MainActivity";

	private Button mStartBtn;
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private boolean isStart;
	private LivePusher livePusher;

	private final Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -100:
				Toast.makeText(MainActivity.this, R.string.video_preview_failure, 0).show();
				livePusher.stopPusher();
				break;
			case -101:
				Toast.makeText(MainActivity.this, R.string.audio_record_failure, 0).show();
				livePusher.stopPusher();
				break;
			case -102:
				Toast.makeText(MainActivity.this, R.string.audio_config_failure, 0).show();
				livePusher.stopPusher();
				break;
			case -103:
				Toast.makeText(MainActivity.this, R.string.video_config_failure, 0).show();
				livePusher.stopPusher();
				break;
			case -104:
				Toast.makeText(MainActivity.this, R.string.net_streaming_failure, 0).show();
				livePusher.stopPusher();
				break;
			}
			mStartBtn.setText(R.string.stop);
			isStart = false;
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		mStartBtn = (Button) findViewById(R.id.button_start);
		mStartBtn.setOnClickListener(this);
		findViewById(R.id.button_switch).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						livePusher.switchCamera();
					}
				});

		mSurfaceView = (SurfaceView) this.findViewById(R.id.surface);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);

		livePusher = new LivePusher(this, 640, 480, 768*1024, 15,
				CameraInfo.CAMERA_FACING_FRONT);
		livePusher.setLiveStateListener(this);
		livePusher.prepare(mSurfaceHolder);
	}

	// @Override
	// public void onRequestPermissionsResult(int requestCode,
	// String[] permissions, int[] grantResults) {
	// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	// }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		livePusher.relase();
	}

	@Override
	public void onClick(View v) {
		if (isStart) {
			mStartBtn.setText(R.string.start);
			isStart = false;
			livePusher.stopPusher();
		} else {
			mStartBtn.setText(R.string.stop);
			isStart = true;
			livePusher.startPusher("rtmp://10.11.40.4/app/live");

		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.d(TAG, "surfaceCreated");
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		Log.d(TAG, "surfaceChanged, width=" + width + ", height=" + height);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.d(TAG, "surfaceDestroyed");
	}

	/**
	 * may run in child-thread
	 */
	@Override
	public void onErrorPusher(int code) {
		Log.d(TAG, "onErrorPusher code:" + code);
		mHandler.sendEmptyMessage(code);
	}

	/**
	 * may run in child-thread
	 */
	@Override
	public void onStartPusher() {
		Log.d(TAG, "start push streaming");
	}

	/**
	 * may run in child-thread
	 */
	@Override
	public void onStopPusher() {
		Log.d(TAG, "stop push streaming");
	}

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gma.server;

import d88.core.network.D88ClientConnection;
import d88.core.network.D88ServerNetwork;
import d88.core.object.D88SObject;
import gma.common.GMAConstants;
import gma.common.GMAShare;
import gma.object.GMAClient;
import gma.object.GMAObject;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;

/**
 *
 * @author dungnt
 */

public class GMAServer implements D88ServerNetwork.D88NetworkDelegate{

    private boolean enbablerReconect = false;

    public GMAServer() {

        D88ServerNetwork d88ServerNetwork = new D88ServerNetwork(GMAConstants.SERVER_LISTEN_PORT, GMAConstants.SERVER_TIME_OUT_CONNECTION, Executors.newCachedThreadPool(), this);
    }

    @Override
    public void onD88NetworkError(String message) {
    }

    @Override
    public void ServerConnectionDidStart() {
        System.out.println("SERVER DID START");
    }

    @Override
    public void ServerConnectionStartFailure(String message) {
    }

    @Override
    public void ServerConnectionDidEnd() {

    }

    @Override
    public void ServerConnectionDidEndFailure(String message) {
    }

    @Override
    public void ServerConnectionClientDidConnect(D88ClientConnection client) {
        try {
            // nếu client chưa được thiết lập session hỏi client xem là thiết lập mới hay không
            GMAShare.getInstance().onAddClient(new GMAClient(client));
//                if(client.getTokenSession().isEmpty()){
//                    // hỏi client xem có phải kết nối mới hay là reconect
//                    GMAObject gmaReconect = new GMAObject("gr");
//                    client.sendMessage(gmaReconect.getMessage());
//                }
//                else{
//
//                }
        } catch (Exception ex) {
            Logger.getLogger(GMAServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void ServerConnectionClientConnectFailure(String message) {
    }

    @Override
    public void clientdidReceiveMessage(byte[] message, D88ClientConnection formClient) {
        try {
            D88SObject d88SObject = new D88SObject(message);
            if(d88SObject != null){
                if("gr".equals(d88SObject.getCmd())){
                    System.out.println(formClient.getClientName());
                    System.out.println("reconect " + d88SObject.getBooleanForKey("re"));
                }
            }
        } catch (DataFormatException ex) {
            System.out.println(ex.getLocalizedMessage());
        } catch (Exception ex) {
            System.out.println(ex.getLocalizedMessage());
        }
    }

    @Override
    public void clientConnectionLost(D88ClientConnection client) {
        // save temp info client
        GMAClient onRemoveClient = GMAShare.getInstance().onRemoveClient(client.getClientName());
        GMAShare.getInstance().onAddClientLost(onRemoveClient);

    }

    @Override
    public void clientConnectionTimeout(D88ClientConnection client) {
        // save temp info client
        GMAClient onRemoveClient = GMAShare.getInstance().onRemoveClient(client.getClientName());
        GMAShare.getInstance().onAddClientTimeOut(onRemoveClient);
    }

    @Override
    public void clientdidDisconnect(D88ClientConnection client) {
    }

    @Override
    public void clientDidSendMessage(byte[] message, D88ClientConnection client) {
    }

    @Override
    public void clientdidSendMessageFailer(D88ClientConnection client, String message) {
    }

    // SET GET

    public boolean isEnbablerReconect() {
        return enbablerReconect;
    }

    public void setEnbablerReconect(boolean enbablerReconect) {
        this.enbablerReconect = enbablerReconect;
    }

}


text:
<?php

namespace PragmaRX\Sdk\Services\Redirect\Service;

use Illuminate\Support\ServiceProvider;

class Provider extends ServiceProvider {

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton('redirect', function($app)
		{
			$redirector = new Redirect($app['url']);

			// If the session is set on the application instance, we'll inject it into
			// the redirector instance. This allows the redirect responses to allow
			// for the quite convenient "with" methods that flash to the session.
			if (isset($app['session.store']))
			{
				$redirector->setSession($app['session.store']);
			}

			return $redirector;
		});
	}

}


text:
import React from 'react';
import { render } from 'react-dom';
import axios from 'axios';

class FinishQuiz extends React.Component {

    constructor(props) {
        super(props);
    }

    clickAnswer(answer, key){
        let elem = $("#"+key);
        $('.answers div').removeClass('answer_clicked');
        if(elem.hasClass('answer_clicked')){
            elem.removeClass('answer_clicked');
        }else{
            elem.addClass('answer_clicked');
        }
        this.props.addPoint(answer);
    }

    render() {

        return (

You finished a quiz

You have {this.props.points} points of {this.props.total_points}

        );
    }
}
export default FinishQuiz;


text:
// This class has been generated, DO NOT EDIT!

package org.tensorflow.op.core;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.family.TNumber;
import org.tensorflow.types.family.TType;

/**
 * Computes element-wise minimum.
 *
 * @param <T> data type for {@code output_ref} output
 */
@OpMetadata(
    opType = ScatterNdMin.OP_NAME,
    inputsClass = ScatterNdMin.Inputs.class
)
public final class ScatterNdMin<T extends TType> extends RawOp implements Operand<T> {
  /**
   * The name of this op, as known by TensorFlow core engine
   */
  public static final String OP_NAME = "ScatterNdMin";

  private Output<T> outputRef;

  public ScatterNdMin(Operation operation) {
    super(operation, OP_NAME);
    int outputIdx = 0;
    outputRef = operation.output(outputIdx++);
  }

  /**
   * Factory method to create a class wrapping a new ScatterNdMin operation.
   *
   * @param scope current scope
   * @param ref A mutable Tensor. Should be from a Variable node.
   * @param indices A Tensor. Must be one of the following types: int32, int64.
   * A tensor of indices into ref.
   * @param updates A Tensor. Must have the same type as ref. A tensor of updated values
   * to add to ref.
   * @param options carries optional attribute values
   * @param <T> data type for {@code ScatterNdMin} output and operands
   * @return a new instance of ScatterNdMin
   */
  @Endpoint(
      describeByClass = true
  )
  public static <T extends TType> ScatterNdMin<T> create(Scope scope, Operand<T> ref,
      Operand<? extends TNumber> indices, Operand<T> updates, Options... options) {
    OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "ScatterNdMin");
    opBuilder.addInput(ref.asOutput());
    opBuilder.addInput(indices.asOutput());
    opBuilder.addInput(updates.asOutput());
    if (options != null) {
      for (Options opts : options) {
        if (opts.useLocking != null) {
          opBuilder.setAttr("use_locking", opts.useLocking);
        }
      }
    }
    return new ScatterNdMin<>(opBuilder.build());
  }

  /**
   * Sets the useLocking option.
   *
   * @param useLocking An optional bool. Defaults to True. If True, the assignment will
   * be protected by a lock; otherwise the behavior is undefined,
   * but may exhibit less contention.
   * @return this Options instance.
   */
  public static Options useLocking(Boolean useLocking) {
    return new Options().useLocking(useLocking);
  }

  /**
   * Gets outputRef.
   * Same as ref. Returned as a convenience for operations that want
   * to use the updated values after the update is done.
   * @return outputRef.
   */
  public Output<T> outputRef() {
    return outputRef;
  }

  @Override
  public Output<T> asOutput() {
    return outputRef;
  }

  /**
   * Optional attributes for {@link org.tensorflow.op.core.ScatterNdMin}
   */
  public static class Options {
    private Boolean useLocking;

    private Options() {
    }

    /**
     * Sets the useLocking option.
     *
     * @param useLocking An optional bool. Defaults to True. If True, the assignment will
     * be protected by a lock; otherwise the behavior is undefined,
     * but may exhibit less contention.
     * @return this Options instance.
     */
    public Options useLocking(Boolean useLocking) {
      this.useLocking = useLocking;
      return this;
    }
  }

  @OpInputsMetadata(
      outputsClass = ScatterNdMin.class
  )
  public static class Inputs<T extends TType> extends RawOpInputs<ScatterNdMin<T>> {
    /**
     * A mutable Tensor. Should be from a Variable node.
     */
    public final Operand<T> ref;

    /**
     * A Tensor. Must be one of the following types: int32, int64.
     * A tensor of indices into ref.
     */
    public final Operand<? extends TNumber> indices;

    /**
     * A Tensor. Must have the same type as ref. A tensor of updated values
     * to add to ref.
     */
    public final Operand<T> updates;

    /**
     * The T attribute
     */
    public final DataType T;

    /**
     * The Tindices attribute
     */
    public final DataType Tindices;

    /**
     * An optional bool. Defaults to True. If True, the assignment will
     * be protected by a lock; otherwise the behavior is undefined,
     * but may exhibit less contention.
     */
    public final boolean useLocking;

    public Inputs(GraphOperation op) {
      super(new ScatterNdMin<>(op), op, Arrays.asList("T", "Tindices", "use_locking"));
      int inputIndex = 0;
      ref = (Operand<T>) op.input(inputIndex++);
      indices = (Operand<? extends TNumber>) op.input(inputIndex++);
      updates = (Operand<T>) op.input(inputIndex++);
      T = op.attributes().getAttrType("T");
      Tindices = op.attributes().getAttrType("Tindices");
      useLocking = op.attributes().getAttrBool("use_locking");
    }
  }
}


text:
package org.finra.herd.swaggergen;

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

import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;

import com.google.common.io.Files;
import org.apache.maven.plugin.MojoExecutionException;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

public class SwaggerGenMojoTest extends AbstractTest
{
    @Test
    public void test_1() throws Exception
    {
        File tempDir = Files.createTempDir();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        ReflectionTestUtils.setField(swaggerGenMojo, "schemeParameters", Arrays.asList("http", "https"));
        swaggerGenMojo.execute();

        assertEquals(getResourceAsString("/yaml4.yaml"), getFileAsString(Paths.get(tempDir.getAbsolutePath(), outputFileName)));
    }

    @Test
    public void test_2() throws Exception
    {
        File tempDir = Files.createTempDir();
        tempDir = Paths.get(tempDir.toURI()).resolve("non_existent").toFile();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        ReflectionTestUtils.setField(swaggerGenMojo, "schemeParameters", Arrays.asList("http", "https"));
        swaggerGenMojo.execute();

        assertEquals(getResourceAsString("/yaml4.yaml"), getFileAsString(Paths.get(tempDir.getAbsolutePath(), outputFileName)));
    }

    @Test
    public void test_3() throws Exception
    {
        File tempDir = Files.createTempDir();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        swaggerGenMojo.execute();

        assertEquals(getResourceAsString("/yaml5.yaml"), getFileAsString(Paths.get(tempDir.getAbsolutePath(), outputFileName)));
    }

    @Test
    public void test_4() throws Exception
    {
        File tempDir = Files.createTempDir();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        ReflectionTestUtils.setField(swaggerGenMojo, "schemeParameters", Arrays.asList("http", null));
        try
        {
            swaggerGenMojo.execute();
            fail();
        }
        catch (Exception e)
        {
            assertEquals(MojoExecutionException.class, e.getClass());
            assertEquals("Invalid scheme specified: null", e.getMessage());
        }
    }

    @Test
    public void test_5() throws Exception
    {
        File tempDir = Files.createTempDir();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        ReflectionTestUtils.setField(swaggerGenMojo, "schemeParameters", Arrays.asList("http", "https"));
        ReflectionTestUtils.setField(swaggerGenMojo, "xsdName", "xsd3.xsd");
        swaggerGenMojo.execute();

        assertEquals(getResourceAsString("/yaml6.yaml"), getFileAsString(Paths.get(tempDir.getAbsolutePath(), outputFileName)));
    }

    @Test
    public void test_GetOperationsFilterShouldBeApplied() throws Exception
    {
        File tempDir = Files.createTempDir();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        ReflectionTestUtils.setField(swaggerGenMojo, "schemeParameters", Arrays.asList("http", "https"));
        ReflectionTestUtils.setField(swaggerGenMojo, "applyOperationsFilter", true);
        ReflectionTestUtils.setField(swaggerGenMojo, "includeOperations", new String[] {"Person.get"});

        swaggerGenMojo.execute();

        assertEquals(getResourceAsString("/yaml_GetOperationsFilter.yaml"), getFileAsString(Paths.get(tempDir.getAbsolutePath(), outputFileName)));
    }

    @Test
    public void test_MultiAuthTypes() throws Exception
    {
        File tempDir = Files.createTempDir();
        String outputFileName = "swagger.yaml";

        SwaggerGenMojo swaggerGenMojo = new SwaggerGenMojo();
        ReflectionTestUtils.setField(swaggerGenMojo, "outputDirectory", tempDir);
        ReflectionTestUtils.setField(swaggerGenMojo, "outputFilename", outputFileName);
        ReflectionTestUtils.setField(swaggerGenMojo, "restJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.rest");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelJavaPackage", "org.finra.herd.swaggergen.test.swaggerGenMojo.model");
        ReflectionTestUtils.setField(swaggerGenMojo, "modelErrorClassName", "ErrorResponse");
        ReflectionTestUtils.setField(swaggerGenMojo, "tagPatternParameter", "(?<tag>.+?)RestController");
        ReflectionTestUtils.setField(swaggerGenMojo, "title", "test_title");
        ReflectionTestUtils.setField(swaggerGenMojo, "version", "test_version");
        ReflectionTestUtils.setField(swaggerGenMojo, "basePath", "/test_basePath");
        ReflectionTestUtils.setField(swaggerGenMojo, "schemeParameters", Arrays.asList("http", "https"));
        ReflectionTestUtils.setField(swaggerGenMojo, "authTypes", new String[]{"basic", "oauth2"});

        swaggerGenMojo.execute();

        assertEquals(getResourceAsString("/yaml_MultiAuthTypes.yaml"), getFileAsString(Paths.get(tempDir.getAbsolutePath(), outputFileName)));
    }
}


text:
/**
 * PlayerList.cpp
 *
 *  Created on: Oct 25, 2013
 *      Author: Christopher J. Cunniff
 */

#include "PlayerList.h"
#include "PlayerNode.h"
#include <iostream>

#define NUMBER_OF_PLAYERS 8

PlayerList::PlayerList() {
	head = NULL;
	tail = NULL;
	length = 0;
	current = NULL;
	button = NULL;

}

PlayerList::~PlayerList() {

}

Player * PlayerList::getCurrentPlayer() {
	if (current == NULL)
		return NULL;
	else
		return current->getPlayer();
}

void PlayerList::next() {
	do {
		if (current->next == NULL)
			current = head;
		else
			current = current->next;
	} while (!(current->getPlayer()->inRound()));	//skip folded players
}

/*
 * reset folded status
 * advance dealer
 * remove players without enough money from game
 */
int PlayerList::purge(int minBet) {

	// variables
	int leftover = 0;
	Player * p;

	//advanceButton();

	// iterate through entire list
	current = head;
	do {
		p = current->getPlayer();
		p->unFold();
		if (p->getMoney() <= minBet) {
			leftover += p->getMoney();
			remove();
		} else
			next();
	} while (current->next != NULL);

	// advance button and set current player
	current = button;
	next();

	return leftover;
}

void PlayerList::advanceButton() {
	cout << endl << "Advancing button" << endl;
	if (button->next == NULL){
		button = head;
	}
	else{
		button = button->next;
	}
	cout << endl;
}

Player * PlayerList::getButton() {
	if (button != NULL)
		return button->getPlayer();
	else
		return NULL;
}

void PlayerList::addPlayer(Player* player) {
	if (head == NULL)
		head = tail = new PlayerNode(player);
	else {
		PlayerNode* newNode = new PlayerNode(player);
		tail->next = newNode;
		newNode->prev = tail;
		tail = newNode;
		tail->next = NULL;
		head->prev = NULL;
	}
	button = head;
	if (head->next != NULL) {
		current = head->next;
	} else
		current = head;
	length++;
}

void PlayerList::remove() {
	cout << "Removing: ";
	current->print();
	PlayerNode * pNode = current;

	if (pNode == button && length > 1) {
		advanceButton();
	}
	if (length == 0) {
		length++;
	} else if (length == 1) {
		cout << "Removing the last node: ";
		current = head = tail = button = NULL;
	} else if (pNode == head) {

		cout << "Removing head: ";
		head = head->next;
		current = head;
		head->prev = NULL;

	} else if (pNode == tail) {

		cout << "Removing tail: ";
		tail = tail->prev;
		tail->next = NULL;
		current = head;

	} else {
		cout << "Removing node: ";
		current = current->next;
		pNode->prev->next = pNode->next;
	}
	length--;
	delete pNode;
}

int PlayerList::getSize() {
	return length;
}

void PlayerList::reset(){
	current = head;
	cout << "Reset" << endl;
}

void PlayerList::print() {
	// print each node
	cout << endl << "Playerlist: ";
	for (int i = 0; i < length; i++) {
		if (current != NULL)
			current->print();
		next();
	}

	// print the head
	cout << endl << "Head: ";
	if (head != NULL)
		head->print();
	cout << endl;

	// print the tail
	cout << "Tail: ";
	if (tail != NULL)
		tail->print();
	cout << endl;

	// print the button
	cout << "Button: ";
	if (button != NULL)
		button->print();
	cout << endl;

	// print the length
	cout << "Length: " << length << endl;
}

void PlayerList::removeAll() {
	while (length > 0) {
		remove();
	}
}


text:
struct EscapeOptions;
class Settings;
class Tool;

class NinjaToolchainWriter {
 public:
  // Takes the settings for the toolchain, as well as the list of all targets
  // associated with the toolchain.
  static bool RunAndWriteFile(
      const Settings* settings,
      const Toolchain* toolchain,
      const std::vector<NinjaWriter::TargetRulePair>& rules);

 private:
  FRIEND_TEST_ALL_PREFIXES(NinjaToolchainWriter, WriteToolRule);
  FRIEND_TEST_ALL_PREFIXES(NinjaToolchainWriter, WriteToolRuleWithLauncher);

  NinjaToolchainWriter(const Settings* settings,
                       const Toolchain* toolchain,
                       std::ostream& out);
  ~NinjaToolchainWriter();

  void Run(const std::vector<NinjaWriter::TargetRulePair>& extra_rules);

  void WriteRules();
  void WriteToolRule(Tool* tool, const std::string& rule_prefix);
  void WriteRulePattern(const char* name,
                        const SubstitutionPattern& pattern,
                        const EscapeOptions& options);
  void WriteCommandRulePattern(const char* name,
                               const std::string& launcher,
                               const SubstitutionPattern& command,
                               const EscapeOptions& options);

  const Settings* settings_;
  const Toolchain* toolchain_;
  std::ostream& out_;
  PathOutput path_output_;

  NinjaToolchainWriter(const NinjaToolchainWriter&) = delete;
  NinjaToolchainWriter& operator=(const NinjaToolchainWriter&) = delete;
};

#endif  // TOOLS_GN_NINJA_TOOLCHAIN_WRITER_H_


text:
Texapi = {};
Texapi.analyzeText = function(url) {
    if (!Meteor.settings.texapi) throw new Meteor.Error(500, 'Please provide a Texapi token in Meteor.settings');
    var response = Meteor.http.post("http://texapi.jbl2024.com/api/v1/text/analyze/", {
        timeout: 5000,
        params: {
            "url": url,
        },
        headers: {
            'Authorization': 'Token ' + Meteor.settings.texapi
        }
    });
    if (response.statusCode === 200) {
        var id = response.data.id
        return id;
    } else {
        throw new Meteor.Error(500, "Texapi call failed with error: " + response.status_txt);
    }
};
Texapi.getText = function(id) {
    if (!Meteor.settings.texapi) throw new Meteor.Error(500, 'Please provide a Texapi token in Meteor.settings');
    var response = Meteor.http.get("http://texapi.jbl2024.com/api/v1/text/" + id + "/", {
        timeout: 5000,
        headers: {
            'Authorization': 'Token ' + Meteor.settings.texapi
        }
    });
    if (response.statusCode === 200) {

        options = {
          allowedTags: [ 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ],
          allowedAttributes: {
            a: [ 'href', 'name', 'target' ],
            // We don't currently allow img itself by default, but this
            // would make sense if we did
            img: [ 'src' ]
          },
          // Lots of these won't come up by default because we don't allow them
          selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ],
          // URL schemes we permit
          allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ]
        };

        return {
            id: response.data.id,
            status: response.data.status,
            text: response.data.summary,
            tags: response.data.tags,
            title: response.data.title,
            readable: sanitizeHtml(response.data.readable, options),
        };
    } else {
        throw new Meteor.Error(500, "Texapi call failed with error: " + response.status_txt);
    }
};
Meteor.methods({
    'analyzeText': function(url) {
        return Texapi.analyzeText(url);
    },
    'getText': function(id) {
        return Texapi.getText(id);
    }
});


text:
# fxt

`npm install fxt --save`

```javascript
var fxt = require('fxt');

var txt = fxt(function() {/*

    free text per sneaky use of function
    ------------------------------------

    There's no use trying to describe either Unthahorsten or his
    surroundings, because, for one thing, a good many million
    years had passed since 1942 Anno Domini and, for another,
    Unthahorsten wasn't on Earth, technically speaking.

    He was doing the equivalent of standing in the equivalent
    of a laboratory.

    He was preparing to test his time machi...

*/});

console.log(txt);

```


text:
#Задача 10. Вариант 35.
#1-50. Напишите программу "Генератор персонажей" для игры. Пользователю должно быть предоставлено 30 пунктов, которые можно распределить между четырьмя характеристиками: Сила, Здоровье, Мудрость и Ловкость. Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего "пула", но и возвращать их туда из характеристик, которым он решил присвоить другие значения.

#Машаева А.Ю
#29.05.2016

points = 30
character = {"Сила":"0","Здоровье":"0","Мудрость":"0","Ловкость":"0"}
shmoints = 0
menu = None
while menu != 0:
    print("0 - Выход\n1 - Добавить пункты к характеристике\n2 - Уменьшить пункты характеристики\n3 - Просмотр характеристик")
    menu = int(input("Выберите пункт меню: "))
    if menu == 1:
        print("\nДоступно", len(character), "характеристики для увеличения пунктов:")
        for item in character:
            print(item)
        char = str(input("Введите характеристику: "))
        char = char.title()
        while char not in character:
            char = str(input("Такой характеристики нет, повторите ввод: "))
            char = char.title()
        else:
            print("У вас", points, "свободных пунктов.")
            shmoints = int(input("Введите количество пунктов: "))
            while shmoints > points or shmoints < 0:
                print("Вы не можете назначить такое количество пунктов.", "Доступно", points, "свободных пунктов.")
                shmoints = int(input("Повторите ввод: "))
        character[char] = shmoints
        print(shmoints, "пунктов было добавлено к", char)
        points -= shmoints
    elif menu == 2:
        print("\nДоступно", len(character), "характеристики для уменьшения пунктов:")
        for item in character:
            print(item)
        char = str(input("Введите характеристику: "))
        char = char.title()
        while char not in character:
             char = str(input("Такой характеристики нет, повторите ввод: "))
             char = char.title()
        else:
            print("Доступно", character[char], "пунктов.")
            shmoints = int(input("Введите количество пунктов: "))
            while shmoints > int(character[char]) or shmoints < 0:
                print("Невозможно удалить такое количество пунктов. Доступно", character[char], "пунктов.")
                shmoints = int(input("Повторите ввод:"))
        character[char] = shmoints
        print(shmoints, "пунктов было удалено.")
        points += shmoints
    elif menu == 3:
        print("\nХарактеристики Вашего героя")
        for item in character:
            print(item, "\t\t", character[item])
    elif menu == 0:
        print("Закрываю генератор...")
input ("\nНажмите Enter для выхода.")


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

namespace CarService.Web.ViewModels
{
    public class CarDetails : CarInRepairDocumentDetails
    {
        [Display(Name = "Repair documents")]
        public IEnumerable<RepairDocumentDetails> RepairDocuments { get; set; }
    }
}


text:
describe package('wget') do
  it { should be_installed }
end

# downloads directory exists
describe directory('/.downloads') do
  it { should be_directory }
end

# 7days user exists
describe user('7days') do
  it { should exist }
  its('group') { should eq '7days' }
  its('home') { should eq '/home/7days' }
  its('shell') { should eq '/bin/bash' }
end

# 7days user exists
describe group('7days') do
  it { should exist }
end

# /home/7days directory exists
describe directory('/home/7days') do
  it { should be_directory }
end

# screen is installed
describe package('screen') do
  it { should be_installed }
end

# steamcmd package exists
describe file('/.downloads/steamcmd_linux.tar.gz') do
  it { should be_file }
end

# glibc.i686 is installed
describe command('yum list glibc.i686') do
  its('stdout') { should match('glibc\.i686') }
end

# libstdc++.i686 is installed
describe command('yum list libstdc++.i686') do
  its('stdout') { should match('libstdc\+\+\.i686') }
end

# steamcmd directory exists
describe directory('/home/7days/steamcmd') do
  it { should be_directory }
  it { should be_owned_by '7days' }
  it { should be_grouped_into '7days' }
end

# steamcmd opened package exists
describe file('/home/7days/steamcmd/steamcmd.sh') do
  it { should be_file }
  it { should be_owned_by '7days' }
  it { should be_grouped_into '7days' }
end

# 7daysded directory exists
describe directory('/home/7days/steamcmd/7daysded') do
  it { should be_directory }
  it { should be_owned_by '7days' }
  it { should be_grouped_into '7days' }
end

# startserver.sh script exists
describe file('/home/7days/steamcmd/7daysded/startserver.sh') do
  it { should be_file }
  it { should be_owned_by '7days' }
  it { should be_grouped_into '7days' }
end

# serverconfig.xml file exists
describe file('/home/7days/steamcmd/7daysded/serverconfig.xml') do
  it { should be_file }
  it { should be_owned_by '7days' }
  it { should be_grouped_into '7days' }
  its('content') { should match '<property name=\"ServerIsPublic\".*value=\"false\"' }
  its('content') { should match '<property name=\"TelnetEnabled\".*value=\"false\"' }
  its('content') { should match '<property name=\"ServerPassword\".*value=\"testpw\"' }
end

# startserver.sh process is running
describe processes('startserver.sh') do
  its('states') { should eq ['Ss+'] }
  its('users') { should eq ['7days'] }
end

describe port(26_900) do
  it { should be_listening }
end


text:
<?
include_once($PagePrefix.'includes/connection.inc.php');

function TranslateDescription($table,$id,$description='Description')
{
	Connect();

 	$rsData = mysql_query("Select $description from $table where Id = $id");

	if ($rsData && mysql_num_rows($rsData))
		list($IdDescription) = mysql_fetch_row($rsData);
	else
		$IdDescription = "$table $id";

	mysql_free_result($rsData);

	Disconnect();

	return $IdDescription;
}

function TranslateQuery($table,$description='Description')
{
	Connect();
	$rs = mysql_query("select Id, $description from $table order by 2");
	Disconnect();
	return $rs;
}

?>


text:
#ifndef CDSLIB_CONTAINER_FELDMAN_HASHSET_DHP_H
#define CDSLIB_CONTAINER_FELDMAN_HASHSET_DHP_H

#include <cds/container/impl/feldman_hashset.h>
#include <cds/gc/dhp.h>

#endif // #ifndef CDSLIB_CONTAINER_FELDMAN_HASHSET_DHP_H


text:
<?xml version='1.0' encoding="utf-8"?>

<toc version="2.0">
<!-- First tocitem specifies top level in Help browser Contents pane -->
<!-- This can be a roadmap page, as shown below, or a content page -->
    <tocitem target="README.html">slp_sqp Toolbox
        <!-- Nest tocitems to create hierarchical entries in  Contents-->
        <!-- To include icons, use the following syntax for tocitems: -->
        <!-- <tocitem target="foo.html" image="HelpIcon.NAME"> -->
        <!-- Title-of-Section </tocitem> -->
        <!-- where NAME is one of the following (use capital letters): -->
        <!-- FUNCTION, USER_GUIDE, EXAMPLES, BLOCK, GETTING_STARTED, -->
        <!-- DEMOS, RELEASE_NOTES -->
        <!-- Icon images used for these entries are also stored in -->
        <!-- matlabroot/toolbox/matlab/icons -->
        <!-- A Getting Started Guide usually comes first -->
        <tocitem target="README.html" image="HelpIcon.GETTING_STARTED">
            Getting Started with the slp_sqp Toolbox
            <tocitem target="Contents.html">Contents
            </tocitem>
        </tocitem>
        <!-- User Guide comes next -->
        <tocitem target="README.html"
            image="HelpIcon.USER_GUIDE">slp-SQP User Guide
        </tocitem>
        <!-- Function reference next -->
        <!-- First item is page describing function categories, if any -->
        <tocitem target="functionlist.html"
                 image="HelpIcon.FUNCTION">Function Reference
            <!-- First category, with link to anchor in above page -->
        </tocitem>
        <!-- Optional List of Examples, with hyperlinks to examples in other files -->
        <tocitem target="runBeamGVslp.html"
                 image="HelpIcon.HelpIcon.EXAMPLES">slp_trust Example
        </tocitem>
    </tocitem>
</toc>


text:
//#ifdef includeSmsFeature

package br.unicamp.ic.sed.mobilemedia.sms.spec.req;

import javax.microedition.midlet.MIDlet;

public interface IMobileResources {

	/**
	 * Get the Midlet
	 * @return
	 */
	public MIDlet getMainMIDlet();

}
//#endif


text:
   #pragma warning (push)
   #pragma warning (disable : 4275) // non DLL-interface classkey "identifier" used as base for DLL-interface classkey "identifier"
   #pragma warning (disable : 4251) // "identifier" : class "type" needs to have dll-interface to be used by clients of class "type2"
   #pragma warning (disable : 4675) // "method" should be declared "static" and have exactly one parameter
   #pragma warning (disable : 4996) // "function": was declared deprecated
   #pragma warning (disable : 4503) // "identifier" : decorated name length exceeded, name was truncated
   #pragma warning (disable : 4284) // odd return type for operator->
   #pragma warning (disable : 4244) // possible loss of data
   #pragma warning (disable : 4521) ////Disable "multiple copy constructors specified"
   #pragma warning (disable : 4127) //conditional expression is constant
   #pragma warning (disable : 4146) // unary minus operator applied to unsigned type, result still unsigned
   #pragma warning (disable : 4267) //conversion from 'X' to 'Y', possible loss of data
   #pragma warning (disable : 4541) //'typeid' used on polymorphic type 'lslboost::exception' with /GR-
   #pragma warning (disable : 4512) //'typeid' used on polymorphic type 'lslboost::exception' with /GR-
   #pragma warning (disable : 4522) // "class" : multiple assignment operators specified
   #pragma warning (disable : 4706) //assignment within conditional expression
   #pragma warning (disable : 4710) // function not inlined
   #pragma warning (disable : 4714) // "function": marked as __forceinline not inlined
   #pragma warning (disable : 4711) // function selected for automatic inline expansion
   #pragma warning (disable : 4786) // identifier truncated in debug info
   #pragma warning (disable : 4996) // "function": was declared deprecated
#endif

//#define BOOST_INTRUSIVE_USE_ITERATOR_FACADE
//#define BOOST_INTRUSIVE_USE_ITERATOR_ENABLE_IF_CONVERTIBLE


text:
namespace cloud_devices {

template <class Option, class Traits>
ListCapability<Option, Traits>::ListCapability() {
  Reset();
}

template <class Option, class Traits>
ListCapability<Option, Traits>::~ListCapability() {
}

template <class Option, class Traits>
bool ListCapability<Option, Traits>::IsValid() const {
  if (empty())
    return false;  // This type of capabilities can't be empty.
  for (size_t i = 0; i < options_.size(); ++i) {
    if (!Traits::IsValid(options_[i]))
      return false;
  }
  return true;
}

template <class Option, class Traits>
bool ListCapability<Option, Traits>::LoadFrom(
    const CloudDeviceDescription& description) {
  Reset();
  const base::ListValue* options =
      description.GetListItem(Traits::GetCapabilityPath());
  if (!options)
    return false;
  for (size_t i = 0; i < options->GetSize(); ++i) {
    const base::DictionaryValue* option_value = NULL;
    if (!options->GetDictionary(i, &option_value))
      return false;  // Every entry must be a dictionary.
    Option option;
    if (!Traits::Load(*option_value, &option))
      return false;
    AddOption(option);
  }
  return IsValid();
}

template <class Option, class Traits>
void ListCapability<Option, Traits>::SaveTo(
    CloudDeviceDescription* description) const {
  DCHECK(IsValid());
  base::ListValue* options_list =
      description->CreateListItem(Traits::GetCapabilityPath());
  for (size_t i = 0; i < options_.size(); ++i) {
    base::DictionaryValue* option_value = new base::DictionaryValue;
    options_list->Append(option_value);
    Traits::Save(options_[i], option_value);
  }
}

template <class Option, class Traits>
SelectionCapability<Option, Traits>::SelectionCapability() {
  Reset();
}

template <class Option, class Traits>
SelectionCapability<Option, Traits>::~SelectionCapability() {
}

template <class Option, class Traits>
bool SelectionCapability<Option, Traits>::IsValid() const {
  if (empty())
    return false;  // This type of capabilities can't be empty
  for (size_t i = 0; i < options_.size(); ++i) {
    if (!Traits::IsValid(options_[i]))
      return false;
  }
  return default_idx_ >= 0 && default_idx_ < base::checked_cast<int>(size());
}

template <class Option, class Traits>
bool SelectionCapability<Option, Traits>::LoadFrom(
    const CloudDeviceDescription& description) {
  Reset();
  const base::DictionaryValue* item =
      description.GetItem(Traits::GetCapabilityPath());
  if (!item)
    return false;
  const base::ListValue* options = NULL;
  if (!item->GetList(json::kKeyOption, &options))
    return false;
  for (size_t i = 0; i < options->GetSize(); ++i) {
    const base::DictionaryValue* option_value = NULL;
    if (!options->GetDictionary(i, &option_value))
      return false;  // Every entry must be a dictionary.
    Option option;
    if (!Traits::Load(*option_value, &option))
      return false;
    bool is_default = false;
    option_value->GetBoolean(json::kKeyIsDefault, &is_default);
    if (is_default && default_idx_ >= 0) {
      return false;  // Multiple defaults.
    }
    AddDefaultOption(option, is_default);
  }
  return IsValid();
}

template <class Option, class Traits>
void SelectionCapability<Option, Traits>::SaveTo(
    CloudDeviceDescription* description) const {
  DCHECK(IsValid());
  base::ListValue* options_list = new base::ListValue;
  description->CreateItem(Traits::GetCapabilityPath())
      ->Set(json::kKeyOption, options_list);
  for (size_t i = 0; i < options_.size(); ++i) {
    base::DictionaryValue* option_value = new base::DictionaryValue;
    options_list->Append(option_value);
    if (base::checked_cast<int>(i) == default_idx_)
      option_value->SetBoolean(json::kKeyIsDefault, true);
    Traits::Save(options_[i], option_value);
  }
}

template <class Traits>
BooleanCapability<Traits>::BooleanCapability() {
  Reset();
}

template <class Traits>
BooleanCapability<Traits>::~BooleanCapability() {
}

template <class Traits>
bool BooleanCapability<Traits>::LoadFrom(
    const CloudDeviceDescription& description) {
  Reset();
  const base::DictionaryValue* dict =
      description.GetItem(Traits::GetCapabilityPath());
  if (!dict)
    return false;
  default_value_ = Traits::kDefault;
  dict->GetBoolean(json::kKeyDefault, &default_value_);
  return true;
}

template <class Traits>
void BooleanCapability<Traits>::SaveTo(
    CloudDeviceDescription* description) const {
  base::DictionaryValue* dict =
      description->CreateItem(Traits::GetCapabilityPath());
  if (default_value_ != Traits::kDefault)
    dict->SetBoolean(json::kKeyDefault, default_value_);
}

template <class Traits>
bool EmptyCapability<Traits>::LoadFrom(
    const CloudDeviceDescription& description) {
  return description.GetItem(Traits::GetCapabilityPath()) != NULL;
}

template <class Traits>
void EmptyCapability<Traits>::SaveTo(
    CloudDeviceDescription* description) const {
  description->CreateItem(Traits::GetCapabilityPath());
}

template <class Option, class Traits>
ValueCapability<Option, Traits>::ValueCapability() {
  Reset();
}

template <class Option, class Traits>
ValueCapability<Option, Traits>::~ValueCapability() {
}

template <class Option, class Traits>
bool ValueCapability<Option, Traits>::IsValid() const {
  return Traits::IsValid(value());
}

template <class Option, class Traits>
bool ValueCapability<Option, Traits>::LoadFrom(
    const CloudDeviceDescription& description) {
  Reset();
  const base::DictionaryValue* option_value =
      description.GetItem(Traits::GetCapabilityPath());
  if (!option_value)
    return false;
  Option option;
  if (!Traits::Load(*option_value, &option))
    return false;
  set_value(option);
  return IsValid();
}

template <class Option, class Traits>
void ValueCapability<Option, Traits>::SaveTo(
    CloudDeviceDescription* description) const {
  DCHECK(IsValid());
  Traits::Save(value(), description->CreateItem(Traits::GetCapabilityPath()));
}

template <class Option, class Traits>
TicketItem<Option, Traits>::TicketItem() {
  Reset();
}

template <class Option, class Traits>
TicketItem<Option, Traits>::~TicketItem() {
}

template <class Option, class Traits>
bool TicketItem<Option, Traits>::IsValid() const {
  return Traits::IsValid(value());
}

template <class Option, class Traits>
bool TicketItem<Option, Traits>::LoadFrom(
    const CloudDeviceDescription& description) {
  Reset();
  const base::DictionaryValue* option_value =
      description.GetItem(Traits::GetTicketItemPath());
  if (!option_value)
    return false;
  Option option;
  if (!Traits::Load(*option_value, &option))
    return false;
  set_value(option);
  return IsValid();
}

template <class Option, class Traits>
void TicketItem<Option, Traits>::SaveTo(
    CloudDeviceDescription* description) const {
  DCHECK(IsValid());
  Traits::Save(value(), description->CreateItem(Traits::GetTicketItemPath()));
}

}  // namespace cloud_devices

#endif  // COMPONENTS_CLOUD_DEVICES_COMMON_DESCRIPTION_DESCRIPTION_ITEMS_INL_H_


text:
<network>
    <node address="A" x="1.0" y="1.0">
        <application type="RoutingGenerator"/>
        <application type="PacketReceiver"/>
        <application type="RTableRouter"/>
    </node>

    <node address="B" x="3.0" y="1.0">
        <application type="PacketGenerator" rate="400.0">
            <destination address="D"/>
            <destination address="C"/>
            <destination address="A"/>
        </application>
        <application type="RoutingGenerator"/>
        <application type="PacketReceiver"/>
        <application type="RTableRouter"/>
    </node>

    <node address="C" x="5.0" y="1.0">
        <application type="RoutingGenerator"/>
        <application type="PacketReceiver"/>
        <application type="RTableRouter"/>
    </node>

    <node address="D" x="2.0" y="3.0">
        <application type="RoutingGenerator"/>
        <application type="PacketReceiver"/>
        <application type="RTableRouter"/>
    </node>

    <node address="E" x="4.0" y="3.0">
        <application type="RoutingGenerator"/>
        <application type="PacketReceiver"/>
        <application type="RTableRouter"/>
    </node>

    <node address="F" x="3.0" y="5.0">
        <application type="RoutingGenerator"/>
        <application type="PacketReceiver"/>
        <application type="RTableRouter"/>
    </node>

    <link source="A" destination="B" directed="false" speed="1.0" delay="100.0" weight="1.0"/>
    <link source="B" destination="C" directed="false" speed="2.0" delay="100.0" weight="1.0"/>
    <link source="D" destination="E" directed="false" speed="3.0" delay="100.0" weight="1.0"/>

    <link source="A" destination="D" directed="false" speed="2.0" delay="100.0" weight="1.0"/>
    <link source="D" destination="F" directed="false" speed="4.0" delay="100.0" weight="1.0"/>
    <link source="C" destination="E" directed="false" speed="8.0" delay="100.0" weight="1.0"/>
    <link source="E" destination="F" directed="false" speed="16.0" delay="100.0" weight="1.0"/>

    <link source="B" destination="D" directed="false" speed="1.0" delay="100.0" weight="1.0"/>
    <link source="B" destination="E" directed="false" speed="1.0" delay="100.0" weight="1.0"/>

    <packet/>
</network>


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         verbose="true">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
        </whitelist>
    </filter>
    <logging>
        <log type="coverage-text" target="php://stdout" showUncoveredFiles="true"/>
        <log type="coverage-html" target="coverage" showUncoveredFiles="true"/>
        <log type="coverage-clover" target="coverage.xml" showUncoveredFiles="true"/>
    </logging>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="test" />
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</phpunit>


text:
<?php
/**
 * @package PayPal
 */

/**
 * Make sure our parent class is defined.
 */
require_once 'PayPal/Type/XSDSimpleType.php';

/**
 * BankAccountDetailsType
 *
 * BankAccountDetailsType
 *
 * @package PayPal
 */
class BankAccountDetailsType extends XSDSimpleType
{
    /**
     * Name of bank
     */
    var $Name;

    /**
     * Type of bank account: Checking or Savings
     */
    var $Type;

    /**
     * Merchant 's bank routing number
     */
    var $RoutingNumber;

    /**
     * Merchant 's bank account number
     */
    var $AccountNumber;

    function BankAccountDetailsType()
    {
        parent::XSDSimpleType();
        $this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
        $this->_elements = array_merge($this->_elements,
            array (
              'Name' =>
              array (
                'required' => true,
                'type' => 'string',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'Type' =>
              array (
                'required' => true,
                'type' => 'BankAccountTypeType',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'RoutingNumber' =>
              array (
                'required' => true,
                'type' => 'string',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'AccountNumber' =>
              array (
                'required' => true,
                'type' => 'string',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
            ));
    }

    function getName()
    {
        return $this->Name;
    }
    function setName($Name, $charset = 'iso-8859-1')
    {
        $this->Name = $Name;
        $this->_elements['Name']['charset'] = $charset;
    }
    function getType()
    {
        return $this->Type;
    }
    function setType($Type, $charset = 'iso-8859-1')
    {
        $this->Type = $Type;
        $this->_elements['Type']['charset'] = $charset;
    }
    function getRoutingNumber()
    {
        return $this->RoutingNumber;
    }
    function setRoutingNumber($RoutingNumber, $charset = 'iso-8859-1')
    {
        $this->RoutingNumber = $RoutingNumber;
        $this->_elements['RoutingNumber']['charset'] = $charset;
    }
    function getAccountNumber()
    {
        return $this->AccountNumber;
    }
    function setAccountNumber($AccountNumber, $charset = 'iso-8859-1')
    {
        $this->AccountNumber = $AccountNumber;
        $this->_elements['AccountNumber']['charset'] = $charset;
    }
}


text:
"""Core functions of Iphigen package."""

from __future__ import division
import time
import numpy as np
import compoda.core as coda
from scipy.ndimage import gaussian_filter
from iphigen.utils import truncate_range, set_range
np.seterr(divide='ignore', invalid='ignore')

def multi_scale_retinex(image, scales=None, verbose=True):
    """Multi scale retinex (MSR).

    Parameters
    ----------
    image : 2d or 3d numpy array

    scales : list
        Standard deviations for Gaussian kernels. For futher
        information see [1]. More or less than 3 values can be given.
        Disscussion of how to determine/optimize the scale values can
        be found in [2].
    verbose: bool
        Print intermediate information. Useful to track progress when
        processing large images.

    Returns
    -------
    msr: 3d numpy array
        Corrected image.

    References
    ----------
    [1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.gaussian_filter.html

    [2] Jobson, D. J., Rahman, Z. U., & Woodell, G. A. (1997).
    A multiscale retinex for bridging the gap between color images and
    the human observation of scenes. IEEE Transactions on Image
    Processing, 6(7), 965-976. DOI: 10.1109/83.597272

    """
    if scales is None:  # default parameters
        scales = [1, 5, 10]

    start = time.time()
    if verbose:
        print('Applying multi-scale retinex...')
    scales = np.array(scales)  # sigma values
    msr = np.zeros(image.shape + (scales.size,))

    for i, sigma in enumerate(scales):
        if verbose:
            print('  Processing scale {} (sigma={})...'.format(i+1, sigma))
        temp = gaussian_filter(image, sigma, mode="reflect")
        msr[..., i] = np.log(image + 1) - np.log(temp + 1)
    temp = None

    # remove nans
    msr = np.nan_to_num(msr)
    # average
    msr = np.mean(msr, axis=-1)
    msr = np.nan_to_num(msr)
    # return from logarithmic space
    msr = np.exp(msr - 1)

    duration = time.time() - start
    print('  Took {0:.1f} seconds.'.format(duration))

    return msr

def scale_approx(new_image, old_image):
    """Scale new data approximately to original dynamic range.

    TODO: replace percentile with gradient based percentile
    """
    opmin, opmax = np.nanpercentile(old_image, [2.5, 97.5])
    npmin, npmax = np.nanpercentile(new_image, [2.5, 97.5])
    # print('old:{} {}'.format(opmin, opmax))
    # print('new:{} {}'.format(npmin, npmax))
    scale_factor = opmax - opmin / (npmax - npmin)
    new_image *= scale_factor
    return new_image

def simplest_color_balance(image, pmin=1., pmax=99.):
    """Simplest color balance.

    Parameters
    ----------
    image: ndim numpy array
        Last dimension should contain channels (eg. RGB)
    pmin: float
        Percent minimum.
    pmax: float
        Percent maximum.

    Reference
    ---------
    Limare, N., Lisani, J., Morel, J., Petro, A. B., & Sbert, C. (2011).
    Simplest Color Balance. Image Processing On Line, 1(1), 125-133.
    http://doi.org/10.5201/ipol.2011.llmps-scb

    """
    dims = image.shape
    for d in range(dims[-1]):
        image[..., d] = truncate_range(image[..., d], pmin=pmin, pmax=pmax)
        image[..., d] = set_range(image[..., d], zero_to=255)
    return image

def simplex_color_balance(bary, center=True, standardize=False,
                          trunc_max=False):
    """Compositional data based method for color balance.

    Highly experimental!

    Parameters
    ----------
    bary: numpy.ndarray
        Barycentric coordinates. Sum of all channels should add up to 1
        (closed).
    center: bool
        Center barycentric coordinates (similar to de-meaning). Single-hue
        dominated images will be balanced to cover all hues.
    standardize: bool
        Standardize barycentric coordinates. Standardized compositions make
        better use of the simplex space dynamic range.
    trunc_max: bool
        Truncate maximum barycentric coordinates to eliminate extreme hues that
        are not prevalent in the image.

    Returns
    -------
    bary: numpy.ndarray
        Processed composition.

    """
    dims = bary.shape
    bary = bary.reshape([np.prod(dims[:-1]), dims[-1]])
    bary = np.nan_to_num(bary)

    # Do not consider values <= 0
    mask = np.prod(bary, axis=-1)
    mask = mask > 0
    temp = bary[mask]

    # Interpretation of centering: Compositions cover the simplex space more
    # balanced across components. Similar to de-mean data.
    if center:
        sample_center = coda.sample_center(temp)
        temp2 = np.full(temp.shape, sample_center)
        temp = coda.perturb(temp, temp2**-1.)
        temp2 = None

    # Interpretation of standardization: Centered compositions cover the
    # dynamic range of simplex space more.
    if standardize:  # Standardize
        totvar = coda.sample_total_variance(temp, sample_center)
        temp = coda.power(temp, np.power(totvar, -1./2.))

    # Interpretation of max truncation: Pull the exterme compositions to
    # threshold distance by using scaling. Scaling factor is determined for
    # each outlier composition to pull more extreme compositions more strongly.
    if trunc_max:
        # Use Aitchison norm and powering to truncate extreme compositions
        anorm = coda.aitchison_norm(temp)
        anorm_thr_min, anorm_thr_max = np.percentile(anorm, [1., 99.])
        # Max truncate
        idx_trunc = anorm > anorm_thr_max
        truncation_power = anorm[idx_trunc] / anorm_thr_max
        correction = np.ones(anorm.shape)
        correction[idx_trunc] = truncation_power
        temp = coda.power(temp, correction[:, None])
        # min truncate
        idx_trunc = anorm < anorm_thr_min
        truncation_power = anorm[idx_trunc] / anorm_thr_min
        correction = np.ones(anorm.shape)
        correction[idx_trunc] = truncation_power
        temp = coda.power(temp, correction[:, None])
    # TODO: Implement this similar to truncate and scpe function but for
    # simplex space. Proportion of dynamic range to the distance of between
    # aitchison norm percentiles gives the global scaling factor. This should
    # be done after truncation though.

    # Put back processed composition
    bary[mask] = temp
    return bary.reshape(dims)


text:
using namespace std;

void usage()
{
    std::cerr << R"(
Usage: spicy-config [options]

== General options.

    --distbase              Print path of the Spicy source distribution.
    --prefix                Print path of installation (TODO: same as --distbase currently)
    --version               Print Spicy version.
    --help                  Print this usage summary

== Options controlling what to include in output.

    --compiler              Output flags for integrating the C++ compilers into host applications.
    --runtime               Output flags for integrating the C runtime libraries into host applications.

    --debug                 Output flags for working with debugging versions.

== Compiler and linker flags

    --cflags                Print flags for C compiler (--runtime only).
    --cxxflags              Print flags for C++ compiler.
    --ldflags               Print flags for linker.
    --libs                  Print libraries for linker.
    --libs-shared           Print shared libraries for linker.
    --libfiles-static       Print fully qualified paths to all static libraries.

== Options for running the command-line compilers.

    --spicyc-binary       Print the full path to the spicyc binary.
    --spicyc-libdirs      Print standard Spicy library directories.
    --spicyc-runtime-libs Print the full path of the Spicy run-time library.

Example: spicy-config --compiler --cxxflags --debug

)";
}

void printList(stringstream& out, const std::list<string>& l)
{
    out << util::strjoin(l, " ") << " ";
}

void appendList(std::list<string>* dst, const std::list<string>& l, const string& prefix = "")
{
    for ( auto i : l )
        dst->push_back(prefix + i);
}

void appendList(std::list<string>* dst, const string& s, const string& prefix = "")
{
    dst->push_back(prefix + s);
}

void appendListFile(std::list<string>* dst, const string& s, const std::list<string>& search_paths,
                    const string& prefix = "", const string& postfix = "")
{
    auto base = prefix + s + postfix;

    auto path = ::util::findInPaths(base, search_paths);

    if ( path.size() == 0 ) {
        std::cerr << "warning: cannot find library " << s << std::endl;
        return;
    }

    dst->push_back(path);
}

void appendListFile(std::list<string>* dst, const std::list<string>& l,
                    const std::list<string>& search_paths, const string& prefix = "",
                    const string& postfix = "")
{
    for ( auto i : l )
        appendListFile(dst, i, search_paths, prefix, postfix);
}

int main(int argc, char** argv)
{
    bool want_compiler = false;
    bool want_runtime = false;
    bool want_debug = false;

    std::list<string> cflags;
    std::list<string> cxxflags;
    std::list<string> ldflags;
    std::list<string> libs;
    std::list<string> libs_shared;
    std::list<string> libfiles_static;

    std::list<string> options;

    // First pass over arguments: look for control options.

    for ( int i = 1; i < argc; i++ ) {
        string opt = argv[i];

        if ( opt == "--help" || opt == "-h" ) {
            usage();
            return 0;
        }

        if ( opt == "--compiler" ) {
            want_compiler = true;
            continue;
        }

        if ( opt == "--runtime" ) {
            want_runtime = true;
            continue;
        }

        if ( opt == "--debug" ) {
            want_debug = true;
            continue;
        }

        options.push_back(opt);
    }

    auto spicy_config = spicy::configuration();

    if ( want_compiler ) {
        appendList(&cflags, spicy_config.compiler_include_dirs, "-I");
        appendList(&cflags, spicy_config.compiler_cflags);
        appendList(&cxxflags, spicy_config.compiler_include_dirs, "-I");
        appendList(&cxxflags, spicy_config.compiler_cxxflags);
        appendList(&ldflags, spicy_config.compiler_ldflags);
        appendList(&libs, spicy_config.compiler_static_libraries, "-l");
        appendList(&libs, spicy_config.compiler_shared_libraries, "-l");
        appendList(&libs_shared, spicy_config.compiler_shared_libraries, "-l");
        appendListFile(&libfiles_static, spicy_config.compiler_static_libraries,
                       spicy_config.compiler_library_dirs, "lib", ".a");
    }

    if ( want_runtime ) {
        appendList(&cflags, spicy_config.runtime_cflags);
        appendList(&cflags, spicy_config.runtime_include_dirs, "-I");
        appendList(&cxxflags, spicy_config.runtime_cxxflags);
        appendList(&cxxflags, spicy_config.runtime_include_dirs, "-I");
        appendList(&ldflags, spicy_config.runtime_ldflags);

        if ( want_debug ) {
            appendList(&libs, spicy_config.runtime_library_bca_dbg);
            appendList(&libfiles_static, spicy_config.runtime_library_bca_dbg);
        }

        else {
            appendList(&libs, spicy_config.runtime_library_bca);
            appendList(&libfiles_static, spicy_config.runtime_library_bca);
        }

        appendList(&libs, spicy_config.runtime_shared_libraries, "-l");
        appendList(&libs_shared, spicy_config.runtime_shared_libraries, "-l");
    }

    bool need_component = false;
    stringstream out;
    stringstream lout;

    for ( auto opt : options ) {
        if ( opt == "--distbase" ) {
            out << spicy_config.distbase << std::endl;
            continue;
        }

        if ( opt == "--prefix" ) {
            out << spicy_config.prefix << std::endl;
            continue;
        }

        if ( opt == "--version" ) {
            out << "Spicy " << spicy_config.version << std::endl;
            continue;
        }

        if ( opt == "--cflags" ) {
            need_component = true;
            printList(lout, cflags);
            continue;
        }

        if ( opt == "--cxxflags" ) {
            need_component = true;
            printList(lout, cxxflags);
            continue;
        }

        if ( opt == "--ldflags" ) {
            need_component = true;
            printList(lout, ldflags);
            continue;
        }

        if ( opt == "--libs" ) {
            need_component = true;
            printList(lout, libs);
            continue;
        }

        if ( opt == "--libs-shared" ) {
            need_component = true;
            printList(lout, libs_shared);
            continue;
        }

        if ( opt == "--libfiles-static" ) {
            need_component = true;
            printList(lout, libfiles_static);
            continue;
        }

        if ( opt == "--spicyc-binary" ) {
            out << spicy_config.path_spicy << std::endl;
            continue;
        }

        if ( opt == "--spicyc-libdirs" ) {
            printList(lout, spicy_config.spicy_library_dirs);
            continue;
        }

        if ( opt == "--spicyc-runtime-libs" ) {
            if ( want_debug )
                out << spicy_config.runtime_library_bca_dbg << std::endl;
            else
                out << spicy_config.runtime_library_bca << std::endl;
            continue;
        }

        std::cerr << "spicy-config: unknown option " << opt << "; use --help to see list."
                  << std::endl;
        return 1;
    }

    if ( need_component && ! (want_compiler || want_runtime) ) {
        cerr << "spicy-config: Either --compiler or --runtime (or both) must be given when "
                "printing flags."
             << std::endl;
        return 1;
    }

    cout << out.str();

    if ( lout.str().size() )
        cout << lout.str() << std::endl;

    return 0;
}


text:
package sh.komet.gui.manifold;

public class WindowManifold {
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// Closed\References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll

#endregion

using System;

//
// Summary:
//     This attribute allows managed concord component to opt-in reporting of non-fatal
//     exception to watson.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class DkmReportNonFatalWatsonExceptionAttribute : Attribute
{
    public DkmReportNonFatalWatsonExceptionAttribute() { }

    //
    // Summary:
    //     Specify the type of exception to exclude from reporting
    public Type ExcludeExceptionType { get; set; }
}


text:
require 'aruba/processes/spawn_process'

RSpec.describe Aruba::Processes::SpawnProcess do
  subject(:process) { described_class.new(command, exit_timeout, io_wait, working_directory, environment, main_class) }

  let(:command) { 'echo "yo"' }
  let(:exit_timeout) { 1 }
  let(:io_wait) { 1 }
  let(:working_directory) { Dir.getwd }
  let(:environment) { ENV.to_hash.dup }
  let(:main_class) { nil }

  describe "#stdout" do
    before(:each) { process.run! }

    context 'when invoked once' do
      it { expect(process.stdout).to eq "yo\n" }
    end

    context 'when invoked twice' do
      it { 2.times { expect(process.stdout).to eq "yo\n" } }
    end
  end

  describe "#stderr" do
    let(:command) { 'fixtures/spawn_process/stderr.sh yo' }

    before(:each) { process.run! }

    context 'when invoked once' do
      it { expect(process.stderr).to eq "yo\n" }
    end

    context 'when invoked twice' do
      it { 2.times { expect(process.stderr).to eq "yo\n" } }
    end
  end

  describe "#stop" do
    let(:reader) { instance_double('Aruba::Announcer') }

    before(:each) { process.run! }

    before :each do
      expect(reader).to receive(:announce).with(:stdout, "yo\n")
      allow(reader).to receive(:announce)
    end

    context 'when stopped successfully' do
      it { process.stop(reader) }
    end
  end

  describe "#run!" do
    context "when process run succeeds" do
      it { expect { process.run! }.not_to raise_error }
    end

    context "when process run fails" do
      let(:command) { 'does_not_exists' }

      it { expect {process.run!}.to raise_error Aruba::LaunchError }
    end
  end
end


text:
from lib.command_constants import CommandConstants
from lib.common import show_cmd_stack

class CommandBuilder(object):

    """docstring for CommandExtractor"""

    def __init__(self, threads):
        super(CommandBuilder, self).__init__()
        self.threads = threads

    def is_complete(self, thread=0):
        return self.threads.complete(thread), False

    def build_command(self, new_command, thread=0):

        # Ignore any commands that are in the forget stack. When something
        # is forgotten, whether it is a command, constant, symbol, it is
        # really forgotten.
        self.debug(11, "Building command. State: %s, complete: %s" % \
                (self.threads.command_state(thread), self.threads.complete(thread)),
                thread=thread, ip=self.threads.ip(thread))
        self.debug(11, "Current command stack: %r" % self.threads.command(thread),
                thread=thread, ip=self.threads.ip(thread))
        if new_command.command in self.threads.forget_stack(thread):
            self.debug(4, "Forgot about " % new_command, msg_type="DBG", thread=thread,
                    ip=self.threads.ip(thread))
            return

        is_command = CommandConstants.is_command(new_command)
        self.debug(11, "%s is command: %s" % (new_command, is_command), thread=thread,
                ip=self.threads.ip(thread))
        if is_command and self.threads.command_state(thread) == 0:
            self.debug(11, "Changing to state 1", thread=thread,
                    ip=self.threads.ip(thread))
            self.threads.set_command_state(1, thread=thread)
        elif not is_command and self.threads.command_state(thread) == 1:
            self.debug(11, "Changing to state 2 and marking complete", thread=thread,
                    ip=self.threads.ip(thread))
            self.threads.set_command_state(2, thread=thread)
            self.threads.set_complete(complete=True, thread=thread)
        else:
            self.debug(11, "Adding %s with no state change" % new_command, thread=thread,
                    ip=self.threads.ip(thread))
        self.threads.command(thread).append(new_command)
        self.debug(11, "New command stack: %r" % self.threads.command(thread),
                thread=thread, ip=self.threads.ip(thread))

    def new(self, thread=0):
        self.debug(11, "Starting new command")
        self.threads.set_command_state(0, thread)
        self.threads.set_command([], thread)
        self.threads.set_complete(False, thread)


text:
 __In place sorting__: Sorting algorithm that doesn't require extra space (new arrays) to sort the input (Bubble sort is an example).

 __Not-in-place sorting__: Sorting algorithm that requires extra space to perform the sorting (Merge sort is an example).

 __Stable sorting__: Sorting algorithm that keeps the similar input elements order.

 __Unstable sorting__: Sorting algorithm that changes the sequence of similar content in which they appear. (Quick sort).

 __Adaptative sorting__: Sorting algorithm that takes advantage of already 'sorted' elements in the list that is to be sorted.

 __Non adaptative sorting__: Sorting algorithm that does not take into account the elements which are already sorted.

## Bubble sort

**Comparison-based** algorithm in which each pair of adjacent elements is compared and **the elements are swapped** if they are not in order.

|Complexity| Stable? | In place ? | Adaptative? |
| ---- | ---- | ---- | ----- |
| O(n^2) | :white_check_mark: | :white_check_mark: | :x: |

```java
public static int[] bubbleSort(int[] input) {
    for (int j = 0; j < input.length - 1; j++) {
        boolean swapped = false;
        for (int i = 0; i < input.length - 1; i++) {
            if (input[i + 1] < input[i]) {
                int before = input[i + 1];
                input[i + 1] = input[i];
                input[i] = before;
                swapped = true;
            }
        }
        if (!swapped) {
            break;
        }
    }
    return input;
}
```

## Insertion sort

**Comparison-based** algorithm that maintains a **sorted sub list** within the input array, and each element of the unsorted part has to find its place in the sorted sub list.

|Complexity| Stable? | In place ? | Adaptative? |
| ---- | ---- | ---- | ----- |
| O(n^2) | :white_check_mark: | :white_check_mark: | :x: |

```java
public static int[] insertionSort(int[] input){
    for(int i =1;i<=input.length-1;i++){
        int valueToInsert = input[i];
        int holePosition=i;
        while(holePosition>0 && input[holePosition-1]>valueToInsert)
        {
            input[holePosition]=input[holePosition-1];
            holePosition=holePosition-1;
        }
        input[holePosition]=valueToInsert;
    }
    return input;
 }
```

## Selection sort

**Comparison-based** algorithm that splits the input into two parts, the left sorted one and the right unsorted part.
The smallest element of the unsorted part is **selected** and swapped with the leftmost element, and that element becomes the last and greatest element of the sorted part.

|Complexity| Stable? | In place ? | Adaptative? |
| ---- | ---- | ---- | ----- |
| O(n^2) | :white_check_mark: | :white_check_mark: | :x: |

```java
public static int[] selectionSort(int[] input){
    for(int j = 0;j < input.length-1;j++){
        for(int i=j+1;i< input.length;i++){
            if(input[i]<input[j]) {
                int selected=input[i];
                input[i] = input[j];
                input[j] =selected;
            }
        }
    }
    return input;
}
```

## Merge sort

**Divide and conquer technique** based algorithm that divides the input into two equal parts and then merges them in a sorted way.

|Complexity| Stable? | In place ? | Adaptative? |
| ---- | ---- | ---- | ----- |
| O(n log n) | :x: | :x: | :x: |

``` java
public static int[] mergeSort(int[] input) {
 if (input.length <= 1) {
     return input;
 }
 // split the input into two arrays :
 int[] first = new int[input.length / 2];
 int[] second = new int[input.length - first.length];
 System.arraycopy(input, 0, first, 0, first.length);
 System.arraycopy(input, first.length, second, 0, second.length);
 mergeSort(first);
 mergeSort(second);
 merge(first, second, input);
 return input;
}

private static void merge(int[] first, int[] second, int[] input) {
 int iFirst = 0;
 int iSecond = 0;
 int iMerged = 0;
 while (iFirst < first.length && iSecond < second.length) {
     if (first[iFirst] < second[iSecond]) {
         input[iMerged] = first[iFirst];
         iFirst++;
     } else {
         input[iMerged] = second[iSecond];
         iSecond++;
     }
     iMerged++;
 }
 //copy remaining elements from both halves - each half will have already sorted elements
 System.arraycopy(first, iFirst, input, iMerged, first.length - iFirst);
 System.arraycopy(second, iSecond, input, iMerged, second.length - iSecond);
}
```


text:
angular.module('pmkr.pristineOriginal', [])

.directive('pmkrPristineOriginal', [
  function() {

    var directive = {
      restrict : 'A',
      require : 'ngModel',
      link: function($scope, $element, $attrs, $ngModel) {

        var defaults = {
          caseSensitive: true
        };
        var opts = $scope.$eval($attrs.pmkrPristineOriginal);
        opts = angular.extend(defaults, opts);

        var pristineVal = null;

        $scope.$watch(function() {
          return $ngModel.$viewValue;
        }, function(val) {

          // set pristineVal to newVal the first time this function runs
          if (pristineVal === null) {
            pristineVal = $ngModel.$isEmpty(val) ? '' : val.toString();
          }

          // determine/set $pristine state
          var shouldBePristine;
          if (pristineVal === val) {
            shouldBePristine = true;
          } else if (!opts.caseSensitive && pristineVal.toLowerCase() === val.toLowerCase()) {
            shouldBePristine = true;
          }
          shouldBePristine && $ngModel.$setPristine();

        });

      }
    };

    return directive;

  }
])

;


text:
<?php

declare(strict_types=1);

namespace Documents;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/** @ODM\EmbeddedDocument */
class Phonenumber
{
    /**
     * @ODM\Field(type="string")
     *
     * @var string|null
     */
    private $phonenumber;

    /**
     * @ODM\ReferenceOne(targetDocument=User::class, cascade={"persist"})
     *
     * @var User|null
     */
    private $lastCalledBy;

    public function __construct(?string $phonenumber = null, ?User $lastCalledBy = null)
    {
        $this->phonenumber  = $phonenumber;
        $this->lastCalledBy = $lastCalledBy;
    }

    public function getPhonenumber(): ?string
    {
        return $this->phonenumber;
    }

    public function setPhonenumber(string $phonenumber): void
    {
        $this->phonenumber = $phonenumber;
    }

    public function getLastCalledBy(): ?User
    {
        return $this->lastCalledBy;
    }

    public function setLastCalledBy(?User $lastCalledBy = null): void
    {
        $this->lastCalledBy = $lastCalledBy;
    }
}


text:
package org.andengine.util;

import org.andengine.util.exception.AndEngineRuntimeException;

/**
 * (c) Zynga 2012
 *
 * @author Nicolas Gramlich <ngramlich@zynga.com>
 * @since 00:45:48 - 17.01.2012
 */
public interface IDisposable {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	public boolean isDisposed();

	public void dispose() throws AlreadyDisposedException;

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================

	public class AlreadyDisposedException extends AndEngineRuntimeException {
		// ===========================================================
		// Constants
		// ===========================================================

		private static final long serialVersionUID = 5796912098160771249L;

		// ===========================================================
		// Fields
		// ===========================================================

		// ===========================================================
		// Constructors
		// ===========================================================

		public AlreadyDisposedException() {

		}

		public AlreadyDisposedException(String pMessage) {
			super(pMessage);
		}

		public AlreadyDisposedException(Throwable pThrowable) {
			super(pThrowable);
		}

		public AlreadyDisposedException(String pMessage, Throwable pThrowable) {
			super(pMessage, pThrowable);
		}

		// ===========================================================
		// Getter & Setter
		// ===========================================================

		// ===========================================================
		// Methods for/from SuperClass/Interfaces
		// ===========================================================

		// ===========================================================
		// Methods
		// ===========================================================

		// ===========================================================
		// Inner and Anonymous Classes
		// ===========================================================
	}
}


text:
(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define([ '../hub/Hub', './iframe/IframeWidget', './inline/InlineWidget' ], factory);
	}
	else {
		root.WidgetLoader = factory(root.Hub, root.IframeWidget, root.InlineWidget);
	}
}(this, function(Hub, IframeWidget, InlineWidget) {

	'use strict';

	function WidgetLoader() {
	}

	WidgetLoader.prototype = {};

	return WidgetLoader;

}));


text:
package org.odata4j.command;

public interface Command<TContext extends CommandContext> {

  CommandResult execute(TContext context) throws Exception;

}


text:
// ReSharper disable InconsistentNaming

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using EasyNetQ.Consumer;
using EasyNetQ.SystemMessages;
using FluentAssertions;
using NSubstitute;
using RabbitMQ.Client;
using Xunit;

namespace EasyNetQ.Tests.Integration
{
    public class DefaultConsumerErrorStrategyTests
    {
        private DefaultConsumerErrorStrategy consumerErrorStrategy;
        private IConnectionFactory connectionFactory;
        private ISerializer serializer;
        private IConventions conventions;

        public DefaultConsumerErrorStrategyTests()
        {
            var configuration = new ConnectionConfiguration
            {
                Hosts = new List<HostConfiguration>
                {
                    new HostConfiguration { Host = "localhost", Port = 5672 }
                },
                UserName = "guest",
                Password = "guest"
            };

            configuration.Validate();

            var typeNameSerializer = new DefaultTypeNameSerializer();
            var errorMessageSerializer = new DefaultErrorMessageSerializer();
            connectionFactory = new ConnectionFactoryWrapper(configuration, new RandomClusterHostSelectionStrategy<ConnectionFactoryInfo>());
            serializer = new JsonSerializer();
            conventions = new Conventions(typeNameSerializer);
            consumerErrorStrategy = new DefaultConsumerErrorStrategy(
                connectionFactory,
                serializer,
                conventions,
                typeNameSerializer,
                errorMessageSerializer
            );
        }

        /// <summary>
        /// NOTE: Make sure the error queue is empty before running this test.
        /// </summary>
        [Fact][Explicit("Requires a RabbitMQ instance on localhost")]
        public void Should_handle_an_exception_by_writing_to_the_error_queue()
        {
            const string originalMessage = "{ Text:\"Hello World\"}";
            var originalMessageBody = Encoding.UTF8.GetBytes(originalMessage);

            var exception = new Exception("I just threw!");

            var context = new ConsumerExecutionContext(
                (bytes, properties, arg3) => null,
                new MessageReceivedInfo("consumertag", 0, false, "orginalExchange", "originalRoutingKey", "queue"),
                new MessageProperties
                {
                    CorrelationId = "123",
                    AppId = "456"
                },
                originalMessageBody
            );

            consumerErrorStrategy.HandleConsumerError(context, exception);

            Thread.Sleep(100);

            // Now get the error message off the error queue and assert its properties
            using(var connection = connectionFactory.CreateConnection())
            using(var model = connection.CreateModel())
            {
                var getArgs = model.BasicGet(conventions.ErrorQueueNamingConvention(new MessageReceivedInfo()), true);
                if (getArgs == null)
                {
                    Assert.True(false, "Nothing on the error queue");
                }
                else
                {
                    var message = (Error)serializer.BytesToMessage(typeof(Error), getArgs.Body.ToArray());

                    message.RoutingKey.Should().Be(context.Info.RoutingKey);
                    message.Exchange.Should().Be(context.Info.Exchange);
                    message.Message.Should().Be(originalMessage);
                    message.Exception.Should().Be("System.Exception: I just threw!");
                    message.DateTime.Date.Should().Be(DateTime.UtcNow.Date);
                    message.BasicProperties.CorrelationId.Should().Be(context.Properties.CorrelationId);
                    message.BasicProperties.AppId.Should().Be(context.Properties.AppId);
                }
            }
        }

        [Fact]
        public void Should_not_reconnect_if_has_been_disposed()
        {
            const string originalMessage = "{ Text:\"Hello World\"}";
            var originalMessageBody = Encoding.UTF8.GetBytes(originalMessage);

            var exception = new Exception("I just threw!");

            var context = new ConsumerExecutionContext(
                (bytes, properties, arg3) => null,
                new MessageReceivedInfo("consumertag", 0, false, "orginalExchange", "originalRoutingKey", "queue"),
                new MessageProperties
                {
                    CorrelationId = "123",
                    AppId = "456"
                },
                originalMessageBody
            );

            connectionFactory = Substitute.For<IConnectionFactory>();

            consumerErrorStrategy = new DefaultConsumerErrorStrategy(
                connectionFactory,
                Substitute.For<ISerializer>(),
                Substitute.For<IConventions>(),
                Substitute.For<ITypeNameSerializer>(),
                Substitute.For<IErrorMessageSerializer>());

            consumerErrorStrategy.Dispose();

            var ackStrategy = consumerErrorStrategy.HandleConsumerError(context, exception);

            connectionFactory.DidNotReceive().CreateConnection();

            Assert.Equal(AckStrategies.NackWithRequeue, ackStrategy);
        }
    }
}

// ReSharper restore InconsistentNaming


text:
__author__ = 'Warlock'

import config
from flask.ext.script import Command
from domain.model import db

class ClearDatabase(Command):
    """
    Remove all rows from database
    """

    def _clear(self, collection):
        print u"Clear collection '{0}'".format(collection.__collection__)
        collection.drop()

    def run(self):
        print u'*** Run cleaning database\n'

        db.drop_database(config.DATABASE['db_name'])

        print u"\ndone"


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

namespace Org.Apache.REEF.Utilities.Runtime.Yarn
{
    public static class HttpConfig
    {
        public static readonly string HttpOnlyPolicy = "HTTP_ONLY";
        public static readonly string HttpsOnlyPolicy = "HTTPS_ONLY";
        public static readonly string HttpAndHttpsPolicy = "HTTP_AND_HTTPS";
    }
}