text:
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MathBarld;

namespace MathBarldTest
{
    /// <summary>
    /// Summary description for BreukenTests
    /// </summary>
    [TestClass]
    public class BreukenTests
    {
        public BreukenTests()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void BreukenPlusTest()
        {
            //let op getal wordt niet genormaliseerd
            Assert.AreEqual(new Breuk(1, 2) + new Breuk(1, 2), new Breuk(1, 2) + new Breuk(1, 2));
        }

        [TestMethod]
        public void BreukenMinTest()
        {

        }
    }
}


text:
using System;
using System.Data;

namespace Aoite.Data
{
    /// <summary>
    /// 表示一个数据库参数的值。
    /// </summary>
    [Serializable]
    public class DbValue : IDbValue
    {
        /// <summary>
        /// 获取或设置参数的值。
        /// </summary>
        public virtual object Value { get; set; }

        /// <summary>
        /// 获取或设置参数的 <see cref="DbType"/>。
        /// </summary>
        public virtual DbType? Type { get; set; }

        /// <summary>
        /// 获取或设置参数的长度。
        /// </summary>
        public virtual int? Size { get; set; }

        /// <summary>
        /// 获取或设置一个值,该值指示参数是只可输入、只可输出、双向还是存储过程返回值参数。
        /// </summary>
        public virtual ParameterDirection? Direction { get; set; }

        /// <summary>
        /// 获取或设置一个值数值参数的精度。
        /// </summary>
        public virtual byte? Precision { get; set; }

        /// <summary>
        /// 数值参数的小数位数。
        /// </summary>
        public virtual byte? Scale { get; set; }

        /// <summary>
        /// 将当前参数配置填充到指定 <see cref="IDbDataParameter"/> 的实例。
        /// </summary>
        /// <param name="parameter">一个 <see cref="IDbDataParameter"/> 的实例。</param>
        public virtual void Fill(IDbDataParameter parameter)
        {
            if(parameter == null) throw new ArgumentNullException(nameof(parameter));

            parameter.Value = this.Value;

            if(this.Type.HasValue) parameter.DbType = this.Type.Value;
            if(this.Size.HasValue) parameter.Size = this.Size.Value;
            if(this.Direction.HasValue) parameter.Direction = this.Direction.Value;
            if(this.Precision.HasValue) parameter.Precision = this.Precision.Value;
            if(this.Scale.HasValue) parameter.Scale = this.Scale.Value;
        }

        /// <summary>
        /// 初始化一个 <see cref="DbValue"/> 类的新实例。
        /// </summary>
        public DbValue() { }
        /// <summary>
        /// 初始化一个 <see cref="DbValue"/> 类的新实例。
        /// </summary>
        /// <param name="value">参数的值。</param>
        public DbValue(object value)
        {
            this.Value = value;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Go deeper */
@keyframes rightToCurrent {
  0%   { transform: translateX(100%); }
  100% { transform: translateX(0); }
}
@-webkit-keyframes rightToCurrent {
  0%   { -webkit-transform: translateX(100%); }
  100% { -webkit-transform: translateX(0); }
}

@keyframes currentToLeft {
  0%   { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}
@-webkit-keyframes currentToLeft {
  0%   { -webkit-transform: translateX(0); }
  100% { -webkit-transform: translateX(-100%); }
}

@keyframes currentToRight {
  0%   { transform: translateX(0); }
  100% { transform: translateX(100%); }
}
@-webkit-keyframes currentToRight {
  0%   { -webkit-transform: translateX(0); }
  100% { -webkit-transform: translateX(100%); }
}

@keyframes leftToCurrent {
  0%   { transform: translateX(-100%); }
  100% { transform: translateX(0); }
}
@-webkit-keyframes leftToCurrent {
  0%   { -webkit-transform: translateX(-100%); }
  100% { -webkit-transform: translateX(0); }
}


text: export Visible from './Visible';


text:
from __future__ import print_function

try:
    from cStringIO import StringIO
except ImportError:
    from io import StringIO
import os
import sys
import time
from xml.sax.saxutils import escape

from em import Interpreter

template_prefix_path = [os.path.abspath(os.path.dirname(__file__))]

interpreter = None
template_hooks = None

def get_template_path(template_name):
    global template_prefix_path
    for basepath in template_prefix_path:
        template_path = os.path.join(basepath, template_name)
        if os.path.exists(template_path):
            return template_path
    raise RuntimeError("Failed to find template '%s'" % template_name)

cached_tokens = {}

class CachingInterpreter(Interpreter):

    def parse(self, scanner, locals=None):
        global cached_tokens
        data = scanner.buffer
        # try to use cached tokens
        tokens = cached_tokens.get(data)
        if tokens is None:
            # collect tokens and cache them
            tokens = []
            while True:
                token = scanner.one()
                if token is None:
                    break
                tokens.append(token)
            cached_tokens[data] = tokens

        # reimplement the parse method using the (cached) tokens
        self.invoke('atParse', scanner=scanner, locals=locals)
        for token in tokens:
            self.invoke('atToken', token=token)
            token.run(self, locals)

def expand_template(template_name, data, options=None):
    global interpreter
    global template_hooks

    output = StringIO()
    try:
        interpreter = CachingInterpreter(output=output, options=options)
        for template_hook in template_hooks or []:
            interpreter.addHook(template_hook)
        template_path = get_template_path(template_name)
        # create copy before manipulating
        data = dict(data)
        # add some generic information to context
        data['template_name'] = template_name
        now = time.localtime()
        data['now_str'] = time.strftime(
            '%Y-%m-%d %H:%M:%S %z', now)
        data['today_str'] = time.strftime(
            '%Y-%m-%d (%z)', now)
        data['timezone'] = '%s%s%02d' % (
            time.tzname[0], '-' if time.timezone < 0 else '+',
            time.timezone / 60 / 60)
        data['wrapper_scripts'] = get_wrapper_scripts()

        _add_helper_functions(data)

        with open(template_path, 'r') as h:
            content = h.read()
            interpreter.invoke(
                'beforeFile', name=template_name, file=h, locals=data)
        interpreter.string(content, template_path, locals=data)
        interpreter.invoke('afterFile')

        value = output.getvalue()
        return value
    except Exception as e:
        print("%s processing template '%s'" %
              (e.__class__.__name__, template_name), file=sys.stderr)
        raise
    finally:
        interpreter.shutdown()
        interpreter = None

def _add_helper_functions(data):
    data['FILE'] = _get_file_content
    data['ESCAPE'] = _escape_value
    data['SNIPPET'] = _expand_snippet
    data['TEMPLATE'] = _expand_template

def _get_file_content(filename):
    path = get_template_path(filename)
    with open(path, 'r') as h:
        return h.read()

def _escape_value(value):
    if isinstance(value, list):
        value = [_escape_value(v) for v in value]
    elif isinstance(value, set):
        value = set([_escape_value(v) for v in value])
    elif isinstance(value, str):
        value = escape(value)
    return value

def _expand_snippet(snippet_name, **kwargs):
    template_name = 'snippet/%s.xml.em' % snippet_name
    _expand_template(template_name, **kwargs)

def _expand_template(template_name, **kwargs):
    global interpreter
    template_path = get_template_path(template_name)
    _add_helper_functions(kwargs)
    with open(template_path, 'r') as h:
        interpreter.invoke('beforeInclude', name=template_path, file=h, locals=kwargs)
        content = h.read()
    try:
        interpreter.string(content, template_path, kwargs)
    except Exception as e:
        print(
            "%s in template '%s': %s" %
            (e.__class__.__name__, template_name, str(e)), file=sys.stderr)
        sys.exit(1)
    interpreter.invoke('afterInclude')

def create_dockerfile(template_name, data, dockerfile_dir):
    data['template_name'] = template_name
    data['wrapper_scripts'] = get_wrapper_scripts()
    content = expand_template(template_name, data)
    dockerfile = os.path.join(dockerfile_dir, 'Dockerfile')
    print("Generating Dockerfile '%s':" % dockerfile)
    for line in content.splitlines():
        print(' ', line)
    with open(dockerfile, 'w') as h:
        h.write(content)

def get_wrapper_scripts():
    wrapper_scripts = {}
    for filename in ['apt.py', 'git.py']:
        wrapper_script_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), 'wrapper')
        abs_file_path = os.path.join(
            wrapper_script_path, filename)
        with open(abs_file_path, 'r') as h:
            content = h.read()
            wrapper_scripts[filename] = content
    return wrapper_scripts


text:
package org.apache.sling.validation.api;

import java.util.List;
import java.util.Set;

/**
 * A {@code ValidationModel} defines the validation rules that a resource tree has to pass.
 */
public interface ValidationModel {

    /**
     * Returns the properties validated by this model.
     *
     * @return the properties set
     */
    Set<ResourceProperty> getResourceProperties();

    /**
     * Returns the type of resource this model validates.
     *
     * @return the validated resource type
     */
    String getValidatedResourceType();

    /**
     * Returns the paths under which resources will be validated by this model.
     *
     * @return a path array
     */
    String[] getApplicablePaths();

    /**
     * Returns the expected children for a resource validated by this model.
     *
     * @return the children list (can be empty if there are no children)
     */
    List<ChildResource> getChildren();

}


text:
/*
 * Maintains a list of currently loaded DLLs (Dynamic Link Libraries)
 * and their associated handles. Library names are case-insensitive.
 */

#include <windows.h>
#include <stdio.h>
#include <string.h>

#include "hpi_impl.h"

#include "path_md.h"

/*
 * create a string for the JNI native function name by adding the
 * appropriate decorations.
 *
 * On Win32, "__stdcall" functions are exported differently, depending
 * on the compiler. In MSVC 4.0, they are decorated with a "_" in the
 * beginning, and @nnn in the end, where nnn is the number of bytes in
 * the arguments (in decimal). Borland C++ exports undecorated names.
 *
 * sysBuildFunName handles different encodings depending on the value
 * of encodingIndex. It returns 0 when handed an out-of-range
 * encodingIndex.
 */
int
sysBuildFunName(char *name, int nameMax, int args_size, int encodingIndex)
{
  if (encodingIndex == 0) {
    /* For Microsoft MSVC 4.0 */
    char suffix[6];    /* This is enough since Java never has more than
                           256 words of arguments. */
    int nameLen;
    int i;

    sprintf(suffix, "@%d", args_size * 4);

    nameLen = strlen(name);
    if (nameLen >= nameMax - 7)
        return 1;
    for(i = nameLen; i > 0; i--)
        name[i] = name[i-1];
    name[0] = '_';

    sprintf(name + nameLen + 1, "%s", suffix);
    return 1;
  } else if (encodingIndex == 1)
    /* For Borland, etc. */
    return 1;
  else
    return 0;
}

/*
 * Build a machine dependent library name out of a path and file name.
 */
void
sysBuildLibName(char *holder, int holderlen, char *pname, char *fname)
{
    const int pnamelen = pname ? strlen(pname) : 0;
    const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0;

    /* Quietly truncates on buffer overflow. Should be an error. */
    if (pnamelen + strlen(fname) + 10 > holderlen) {
        *holder = '\0';
        return;
    }

    if (pnamelen == 0) {
        sprintf(holder, "%s.dll", fname);
    } else if (c == ':' || c == '\\') {
        sprintf(holder, "%s%s.dll", pname, fname);
    } else {
        sprintf(holder, "%s\\%s.dll", pname, fname);
    }
}

void *
sysLoadLibrary(const char * name, char *err_buf, int err_buflen)
{
    void *result = LoadLibrary(name);
    if (result == NULL) {
        /* Error message is pretty lame, try to make a better guess. */
        long errcode = GetLastError();
        if (errcode == ERROR_MOD_NOT_FOUND) {
            strncpy(err_buf, "Can't find dependent libraries", err_buflen-2);
            err_buf[err_buflen-1] = '\0';
        } else {
            sysGetLastErrorString(err_buf, err_buflen);
        }
    }
    return result;
}

void sysUnloadLibrary(void *handle)
{
    FreeLibrary(handle);
}

void * sysFindLibraryEntry(void *handle, const char *name)
{
    return GetProcAddress(handle, name);
}


text:
DotNetDoodle.OpenIdConnect.Server
=================================

OpenID Connect 1.0 Server Implementation on top of OWIN


text:
package com.apwglobal.nice.client;

import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.login.Credentials;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.Configuration;
import pl.allegro.webapi.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static java.util.Collections.singletonList;

public class ClientService extends AbstractService {

    public ClientService(ServicePort allegro, Credentials cred, Configuration conf) {
        super(allegro, cred, conf);
    }

    public List<ItemPostBuyDataStruct> getClientsDate(String session, long itemId) {
        DoGetPostBuyDataRequest request = new DoGetPostBuyDataRequest();
        request.setSessionHandle(session);
        request.setItemsArray(new ArrayOfLong(singletonList(itemId)));
        DoGetPostBuyDataResponse response = AllegroExecutor.execute(() -> allegro.doGetPostBuyData(request));
        return response.getItemsPostBuyData().getItem();
    }

}


text:
package com.boilerplate.database.mysql.implementations;

import java.util.List;

import javax.xml.crypto.dsig.keyinfo.KeyValue;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boilerplate.exceptions.rest.NotFoundException;
import com.boilerplate.framework.HibernateUtility;
import com.boilerplate.java.collections.BoilerplateList;
import com.boilerplate.java.collections.BoilerplateMap;
import com.boilerplate.java.entities.ExternalFacingUser;

/**
 * This method is a base of data access layer
 * @author gaurav.verma.icloud
 *
 */
public class MySQLBaseDataAccessLayer {

	/**
	 * This method creates an object in the database
	 * @param t The object to be created
	 * @return The object as it stands after creation
	 */
	public <T> T create (T t){
		Session session =null;
		try{
			//open a session
			session = HibernateUtility.getSessionFactory().openSession();
			//get all the configurations from the DB as a list
			Transaction transaction = session.beginTransaction();
			session.save(t);
			//commit the transaction
			transaction.commit();
			return t;
		}
		finally{
			if(session !=null && session.isOpen()){
				session.close();
			}
		}

	}

	/**
	 * This method creates a list of objects in the database
	 * @param ts The list of object's to be created
	 * @return The object as it stands after creation
	 */
	public <T> List<T> create (List<T> ts){
		Session session =null;
		try{
			//open a session
			session = HibernateUtility.getSessionFactory().openSession();
			//get all the configurations from the DB as a list
			Transaction transaction = session.beginTransaction();
			for(T t :ts){
				session.save(t);
			}
			//commit the transaction
			transaction.commit();
			return ts;
		}
		finally{
			if(session !=null && session.isOpen()){
				session.close();
			}
		}

	}

	/**
	 * This method is used to update an item in the database
	 * @param t The item to be updated
	 * @return The item after update
	 */
	public <T> T update (T t){
		Session session =null;
		try{
			//open a session
			session = HibernateUtility.getSessionFactory().openSession();
			//get all the configurations from the DB as a list
			Transaction transaction = session.beginTransaction();
			session.saveOrUpdate(t);
			//commit the transaction
			transaction.commit();
			return t;
		}
		finally{
			if(session !=null && session.isOpen()){
				session.close();
			}
		}

	}

	/**
	 * This api deletes the object from database
	 * @param t The item to be deleted
	 */
	public <T> void delete(T t) {
		BoilerplateList<Object> objects = new BoilerplateList<Object> ();
		objects.add(t);
		this.delete(objects);
	}

	/**
	 * This method deletes a list of objects
	 * @param objects The objects to be deleted.
	 */
	public void delete(List<Object> objects){
		Session session =null;
		try{
			//open a session
			session = HibernateUtility.getSessionFactory().openSession();
			Transaction transaction = session.beginTransaction();
			//delete the object
			for(Object object :objects){
				session.delete(object);
			}
			//commit
			transaction.commit();
		}
		finally
		{
			if(session !=null && session.isOpen()){
				session.close();
			}
		}//end finally
	}

	/**
	 * This method executes a given query
	 * @param hSQLQuery The query to be executed
	 * @param queryParameters The query parameters
	 * @return result of query execution
	 */
	public <T> List<T> executeSelect(
			String hSQLQuery,
			BoilerplateMap<String, Object> queryParameters
			){
		Session session =null;
		try{
			//open a session
			session = HibernateUtility.getSessionFactory().openSession();
			//begin a transaction
			Transaction transaction = session.beginTransaction();
			//get the user using a hsql query
			Query query = session.createQuery(hSQLQuery);

			for(String key : queryParameters.keySet()){
				query.setParameter(key, queryParameters.get(key));
			}
			List<T> ts = query.list();
			transaction.commit();
			return ts;
		}
		finally
		{
			if(session !=null && session.isOpen()){
				session.close();
			}
		}//end finally
	}//end method

	public int executeUpdate(
			String hSQLQuery,
			BoilerplateMap<String, Object> queryParameters
			){
		Session session =null;
		try{
			//open a session
			session = HibernateUtility.getSessionFactory().openSession();
			//begin a transaction
			Transaction transaction = session.beginTransaction();
			//get the user using a hsql query
			Query query = session.createQuery(hSQLQuery);

			for(String key : queryParameters.keySet()){
				query.setParameter(key, queryParameters.get(key));
			}
			int rowsEffected = query.executeUpdate();
			transaction.commit();
			return rowsEffected;
		}
		finally
		{
			if(session !=null && session.isOpen()){
				session.close();
			}
		}//end finally
	}//end method
}


text:
namespace blink {

CompositionUnderlineRangeFilter::CompositionUnderlineRangeFilter(const Vector<CompositionUnderline>& underlines, size_t indexLo, size_t indexHi)
    : m_underlines(underlines)
    , m_indexLo(indexLo)
    , m_indexHi(indexHi)
    , m_theEnd(this, kNotFound) { }

size_t CompositionUnderlineRangeFilter::seekValidIndex(size_t index)
{
    if (index == kNotFound)
        return kNotFound;

    size_t numUnderlines = m_underlines.size();
    while (index < numUnderlines) {
        const CompositionUnderline& underline = m_underlines[index];

        if (underline.endOffset <= m_indexLo) {
            // |underline| lies  before the query range: keep on looking.
            ++index;
        } else if (underline.startOffset <= m_indexHi) {
            // |underline| intersects with the query range: valid, so return.
            return index;
        } else {
            // |underline| is completely after the query range: bail.
            break;
        }
    }
    return kNotFound;
}

} // namespace blink


text:
//
// Site / Base / Encode Escape
//

'use strict';

// Dependencies
var log = require('bows')('Encode Escape');

// App Initialization
// --------------------------------------------------

var Encode = {
    encode: function (value) {
        /*global escape */
        return escape(value);
    },

    decode: function (value) {
        /*global unescape */
        return unescape(value);
    },
};

// Exports
// --------------------------------------------------

module.exports = Encode;


text:
<?xml version="1.0" encoding="UTF-8"?>
<?testPIwithattrs attr="value"?>
<a/>


text:
package org.apache.storm.daemon;

public interface DaemonCommon {
    boolean isWaiting();
}


text:
<?php

class ImportController extends BaseController {

	protected $rules;

	public function __construct()
	{
		$this->rules = array(
			'fontsURL' => 'required|url',
			'graphicsURL' => 'required|url',
		);
	}

	/**
	 * Show main import form.
	 *
	 * @return Response
	 */
	public function showIndex()
	{
        return View::make('import.index');
	}

	/**
	 * Import graphic gallery from JSON
	 *
	 */
	public function importGraphics() {
		$input = Input::all();
		$v = Validator::make($input, $this->rules);

		if ($v->passes()) {
			$url = Input::get('graphicsURL');
			$json = file_get_contents($url);
			$data = json_decode($json);
			$atts = array('name','description','colors');
			foreach ($data->graphicsCategoriesList as $row) {
				$cat = new GraphicsCategory;
				$cat->name = $row->name;
				$cat->save();
				foreach ($row->graphicsList as $g) {
					$graphic = new GraphicsItem;
					$graphic->category = $cat;
					$graphic->name = $g->name;
					$graphic->description = $g->description;
					$graphic->thumb = $g->thumb;
					$graphic->image = $g->image;
					// optional atts block
					if (property_exists($g, 'colors')) {
						$graphic->colors = intval($g->colors);
					}
					if (property_exists($g, 'multicolor')) {
						$graphic->multicolor = $g->multicolor;
					}
					// "colorize": true - would be a synthesized att,
					// so we are not importing it
					$graphic->save();
					if (property_exists($g, 'colorizableElements')) {
						foreach ($g->colorizableElements as $ce) {
							$el = new ColorizableElement;
							$el->name = $ce->name;
							$el->css_id = $ce->id;
							$el->colorizable = $graphic;
							// if needed add colors import here
							$el->save();
						}
					}
				}
			}
			return Redirect::route('graphicsItems.index')->with('message','Gallery was imported!');
		}
		// TODO add error messages here when necessary
		return View::make('import.index');
	}

	/**
	 * Import fonts from JSON to DB
	 *
	 * @return redirects to imported data page
	 */
	public function importFonts()
	{
		$input = Input::all();
		$v = Validator::make($input, $this->rules);

		if ($v->passes()) {
			$url = Input::get('fontsURL');
			$json = file_get_contents($url);
			$data = json_decode($json);
			// atts to import
			$atts = array('name','fontFamily','ascent','vector','boldAllowed','italicAllowed');
			foreach ($data->fonts as $row) {
				$font = new Font;
				foreach ($atts as $att) {
					if (property_exists($row, $att)) {
						$font->$att = $row->$att;
					}
				}
				$font->save();
			}
			return Redirect::route('fonts.index')->with('message','Fonts were imported!');
		}
		// TODO add error messages here
		return View::make('import.index');
	}
}


text:
<?php

namespace common\models\base;

//use mootensai\behaviors\UUIDBehavior;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;

/**
 * This is the base model class for table "person".
 *
 * @property integer $id
 * @property string $firstname
 * @property string $lastname
 * @property string $secondname
 * @property string $date_new
 * @property string $date_edit
 * @property string $passport_ser
 * @property string $passport_num
 * @property string $contacts
 * @property string $other
 * @property integer $child
 * @property string $date_add
 * @property integer $created_by
 * @property integer $updated_by
 * @property integer $lock
 *
 * @property \common\models\BusReservationHasPerson[] $busReservationHasPeople
 * @property \common\models\BusReservation[] $busReservations
 * @property \common\models\SalOrderHasPerson[] $salOrderHasPeople
 * @property \common\models\SalOrder[] $salOrders
 */
class Person extends \yii\db\ActiveRecord
{
    use \mootensai\relation\RelationTrait;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['firstname', 'lastname', 'secondname'], 'required'],
            [['date_new', 'date_edit', 'birthday', 'date_add'], 'safe'],
            [['contacts', 'other'], 'string'],
            [['child', 'created_by', 'updated_by', 'lock'], 'integer'],
            [['firstname', 'lastname', 'secondname'], 'string', 'max' => 100],
            [['passport_ser'], 'string', 'max' => 10],
            [['passport_num'], 'string', 'max' => 15],
            [['lock'], 'default', 'value' => '0'],
            [['lock'], 'mootensai\components\OptimisticLockValidator'],
            [['gender_id'], 'exist', 'skipOnError' => true, 'targetClass' => \common\models\Gender::className(), 'targetAttribute' => ['gender_id' => 'id']]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'person';
    }

    /**
     *
     * @return string
     * overwrite function optimisticLock
     * return string name of field are used to stored optimistic lock
     *
     */
    public function optimisticLock()
    {
        return 'lock';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'firstname' => Yii::t('app', 'Firstname'),
            'lastname' => Yii::t('app', 'Lastname'),
            'secondname' => Yii::t('app', 'Secondname'),
            'date_new' => Yii::t('app', 'Date New'),
            'date_edit' => Yii::t('app', 'Date Edit'),
            'passport_ser' => Yii::t('app', 'Passport Ser'),
            'passport_num' => Yii::t('app', 'Passport Num'),
            'gender_id' => Yii::t('app', 'Gender ID'),
            'contacts' => Yii::t('app', 'Contacts'),
            'other' => Yii::t('app', 'Other'),
            'birthday' => Yii::t('app', 'Birthday'),
            'child' => Yii::t('app', 'Child'),
            'date_add' => Yii::t('app', 'Date Add'),
            'lock' => Yii::t('app', 'Lock'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBusReservationHasPeople()
    {
        return $this->hasMany(\common\models\BusReservationHasPerson::className(), ['person_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBusReservations()
    {
        return $this->hasMany(\common\models\BusReservation::className(), ['id' => 'bus_reservation_id'])->viaTable('bus_reservation_has_person', ['person_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGender()
    {
        return $this->hasOne(\common\models\Gender::className(), ['id' => 'gender_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSalOrderHasPeople()
    {
        return $this->hasMany(\common\models\SalOrderHasPerson::className(), ['person_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSalOrders()
    {
        return $this->hasMany(\common\models\SalOrder::className(), ['id' => 'sal_order_id'])->viaTable('sal_order_has_person', ['person_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'date_add',
                'updatedAtAttribute' => 'date_edit',
                'value' => new \yii\db\Expression('NOW()'),
            ],
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\PersonQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\PersonQuery(get_called_class());
    }
}


text:
<?php

class Google_Service_CloudSearch_ResultDisplayMetadata extends Google_Collection
{
  protected $collection_key = 'metalines';
  protected $metalinesType = 'Google_Service_CloudSearch_ResultDisplayLine';
  protected $metalinesDataType = 'array';
  public $objectTypeLabel;

  /**
   * @param Google_Service_CloudSearch_ResultDisplayLine
   */
  public function setMetalines($metalines)
  {
    $this->metalines = $metalines;
  }
  /**
   * @return Google_Service_CloudSearch_ResultDisplayLine
   */
  public function getMetalines()
  {
    return $this->metalines;
  }
  public function setObjectTypeLabel($objectTypeLabel)
  {
    $this->objectTypeLabel = $objectTypeLabel;
  }
  public function getObjectTypeLabel()
  {
    return $this->objectTypeLabel;
  }
}


text:
#include <aws/iot1click-projects/model/UpdateProjectRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::IoT1ClickProjects::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateProjectRequest::UpdateProjectRequest() :
    m_projectNameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_placementTemplateHasBeenSet(false)
{
}

Aws::String UpdateProjectRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_placementTemplateHasBeenSet)
  {
   payload.WithObject("placementTemplate", m_placementTemplate.Jsonize());

  }

  return payload.View().WriteReadable();
}


text:
layout: page
title: Pacheco Zone Networks Trade Fair
date: 2016-05-24
author: Patricia Lynn
tags: weekly links, java
status: published
summary: In sed ligula condimentum ligula.
banner: images/banner/people.jpg
booking:
  startDate: 11/22/2016
  endDate: 11/23/2016
  ctyhocn: PTTHXHX
  groupCode: PZNTF
published: true
---
Sed et rutrum diam. Proin lorem elit, placerat a consequat sit amet, lacinia nec sapien. Integer hendrerit aliquam lorem, sed sollicitudin tellus ullamcorper eget. Sed volutpat ipsum ut ipsum sodales, at molestie enim rutrum. Quisque et massa placerat ligula tincidunt venenatis. Morbi eget mi felis. Nam viverra nunc tellus, ac blandit nibh ullamcorper vitae.

* Praesent in magna interdum, hendrerit augue vitae, dignissim erat
* Nam facilisis enim eu feugiat auctor
* Nam eleifend lectus nec interdum rhoncus
* Curabitur vehicula lorem eu purus laoreet sodales
* Duis mattis felis eu neque facilisis tempus.

Maecenas varius rutrum semper. Vivamus eu consectetur ex. Nullam magna lacus, bibendum eget dictum non, rhoncus id enim. Curabitur non faucibus sapien, at eleifend sapien. Fusce interdum porttitor neque, vel euismod nisl aliquet in. Morbi vestibulum nunc a lectus varius ullamcorper. Etiam consectetur lorem ipsum. Fusce fringilla augue mi, at euismod velit consectetur ut. Quisque consectetur semper ante, et tempor urna vulputate ut. Cras ornare ac est elementum laoreet. Sed quis tempor purus, sit amet egestas nibh.
Ut magna lectus, blandit quis sapien vitae, porta tincidunt nisl. Proin quis tortor id diam varius sagittis. Aliquam sed convallis erat. Aliquam vel lacus at orci ullamcorper lobortis. Vestibulum rutrum ipsum id tellus aliquam, ac dapibus purus molestie. Curabitur et nibh massa. Integer rutrum metus sit amet odio aliquet, eget vehicula turpis scelerisque.


text:
package profileservice.component.confluence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import profileservice.component.person.PersonComponent;
import profileservice.component.project.ProjectComponent;
import profileservice.component.skill.SkillComponent;
import profileservice.domain.Person;
import profileservice.domain.Project;
import profileservice.domain.Skill;

@Component
class ConfluenceComponentImpl {

    @Scheduled(cron = "${syncteam.cron}")
    public void syncTeamDetails(){
        // call rest api for top of tree
        // recurse through each child page
        // get all labels
        // get page title

        if(isSyncTeamEnabled) {
            mockData();
        }
    }

    @Value("${syncteam.enable}")
    private boolean isSyncTeamEnabled;

    @Autowired
    private PersonComponent personComponent;

    @Autowired
    private SkillComponent skillComponent;

    @Autowired
    private ProjectComponent projectComponent;

    private void mockData(){
        skillComponent.deleteAll();
        Skill java = new Skill("Java");
        Skill python = new Skill("Python");
        Skill ruby = new Skill("Ruby");
        skillComponent.save(python);

        projectComponent.deleteAll();
        Project blue = new Project("Blue");
        Project red = new Project("Red");
        Project green = new Project("Green");
        Project yellow = new Project("Yellow");

        personComponent.deleteAll();
        Person greg = new Person("Greg", "Brown", "gbrown");
        greg.hasSkill(java);
        greg.hasSkill(ruby);
        greg.workedOn(blue);
        personComponent.save(greg);

        Person roy = new Person("Roy", "Blue", "rblue");
        roy.hasSkill(java);
        roy.workedOn(green);
        roy.workedOn(yellow);
        personComponent.save(roy);

        Person craig = new Person("Craig", "White", "cwhite");
        craig.hasSkill(ruby);
        craig.reviews(roy);
        craig.reviews(greg);
        personComponent.save(craig);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace AMing.Plugins.Core.Win32
{
    public class Window
    {
        [DllImport("user32")]
        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("user32")]
        public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwLong);

        public const int GWL_EXSTYLE = -20;
        public const int WS_EX_TRANSPARENT = 0x20;
        public const int WS_EX_LAYERED = 0x80000;
    }
}


text:
using IvmpDotNet.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace IvmpDotNet.Imports {
    public static class Vehicles {
        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_Create(Int32 iModelId, CVector3 vecPosition, CVector3 vecRotation, Int32 color1, Int32 color2, Int32 color3, Int32 color4, Int32 respawn_delay);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_Delete(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetCoordinates(ushort vehicleid, CVector3 vecPosition);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern CVector3 Vehicles_GetCoordinates(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetRotation(ushort vehicleId, CVector3 vecRotation);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetDirtLevel(ushort vehicleid, Single fLevel);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Single Vehicles_GetDirtLevel(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetSirenState(ushort vehicleId, Boolean sqbState);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_GetSirenState(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SoundHorn(ushort vehicleId, Int32 iDuration);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern CVector3 Vehicles_GetRotation(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_IsValid(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetColor(ushort vehicleid, IntPtr colors);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr Vehicles_GetColor(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_GetModel(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetHealth(ushort vehicleid, Int32 health);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_GetHealth(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetVelocity(ushort vehicleid, CVector3 vecMoveSpeed);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern CVector3 Vehicles_GetVelocity(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetAngularVelocity(ushort vehicleid, CVector3 vecTurnSpeed);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern CVector3 Vehicles_GetAngularVelocity(ushort vehicleid);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_Respawn(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_IsOccupied(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr Vehicles_GetOccupants(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetLocked(ushort vehicleId, Int32 iLocked);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_GetLocked(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetIndicators(ushort vehicleId, Boolean bFrontLeft, Boolean bFrontRight, Boolean bBackLeft, Boolean bBackRight);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr Vehicles_GetIndicators(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetComponent(ushort vehicleId, Int32 iSlot, Boolean bOn);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_ResetComponents(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr Vehicles_GetComponents(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetVariation(ushort vehicleId, Int32 iVariation);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_GetVariation(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetEngineStatus(ushort vehicleId, Boolean bEngineStatusx);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_GetEngineStatus(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SwitchTaxiLights(ushort vehicleId, Boolean check);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_ControlCarDoors(ushort vehicleId, Int32 door, Boolean door2, Single door3);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetLights(ushort vehicleId, Boolean bLights);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_GetLights(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_GetTaxiLights(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_RepairWheels(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_RepairWindows(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_Repair(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetDimension(ushort vehicleId, Int32 dimension);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_GetDimension(ushort vehicleId);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Boolean Vehicles_SetRespawnDelay(ushort vehicleId, Int32 respawn_delay);

        [DllImport(IvmpDotNet.Core.Imports.Common.ImportDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern Int32 Vehicles_GetRespawnDelay(ushort vehicleId);
    }
}


text:
@implementation MBURLSessionManager

-(NSURLSession *)getSessionWithConfiguration:(NSURLSessionConfiguration *)configuration
                               progressBlock:(ProgressBlock)progressBlock
                                  errorBlock:(ErrorBlock)errorBlock
                               completeBolck:(CompleteBlock)completeBlock
{
    _progressBlock = progressBlock;
    _errorBlock = errorBlock;
    _completeBlock = completeBlock;

    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    return session;
}

#pragma mark - delegate for download task <NSURLSessionDownloadDelegate>
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
#if DEBUG
    NSLog(@"Download Task : %@  progress : %lf", downloadTask, (double) totalBytesWritten/(double) totalBytesExpectedToWrite);
#endif

    if (_progressBlock) {
        NSString *destinationKey = [NSString stringWithFormat:@"%lu", (unsigned long)downloadTask.taskIdentifier];
        id identifier = [MBDownloadManager.defaultManager.userInfo objectForKey:destinationKey];

        dispatch_async(dispatch_get_main_queue(), ^{
            _progressBlock([downloadTask taskIdentifier], bytesWritten, totalBytesWritten, totalBytesExpectedToWrite, identifier);
        });
    }
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //NSURL *originalURL = [[downloadTask originalRequest] URL];  // Why???!!!
    NSError *errorCopy;

    NSString *destinationKey = [NSString stringWithFormat:@"%lu", (unsigned long)downloadTask.taskIdentifier];
    NSString *destinationPath = [MBDownloadManager.defaultManager.destinationList objectForKey:destinationKey];

    NSURL *destinationURL = nil;
    if (destinationPath) {
        destinationURL = [NSURL fileURLWithPath:destinationPath];
    }

    BOOL success = NO;

    if (destinationURL) {
        BOOL isDirectoryExist = YES;

        if (![fileManager isExecutableFileAtPath:[destinationURL.path stringByDeletingLastPathComponent]]) {

            NSError *anErr = nil;
            isDirectoryExist = [fileManager createDirectoryAtPath:[destinationURL.path stringByDeletingLastPathComponent]
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:&anErr];
        }

        if (isDirectoryExist) {
            [fileManager removeItemAtURL:destinationURL error:NULL];

            // Moving is faster than copying by neoroman on 31/10/2014
            //success = [fileManager copyItemAtURL:location toURL:destinationURL error:&errorCopy];
            success = [fileManager moveItemAtURL:location toURL:destinationURL error:&errorCopy];
        }
    }

    id identifier = [MBDownloadManager.defaultManager.userInfo objectForKey:destinationKey];
    if (success) {

        if (_completeBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _completeBlock([downloadTask taskIdentifier], success, [destinationURL absoluteString], identifier);

                if (MBDownloadManager.defaultManager.delegate
                    && [MBDownloadManager.defaultManager.delegate respondsToSelector:@selector(downloadTaskFinished:userInfo:)]) {
                    [MBDownloadManager.defaultManager.delegate performSelector:@selector(downloadTaskFinished:userInfo:) withObject:downloadTask withObject:identifier];
                }
            });
        }

    } else {

#if DEBUG
        NSLog(@"Error during the copy : %@", [errorCopy localizedDescription]);
        NSLog(@"Error during the copy : location.path => %@", location.path);
        NSLog(@"Error during the copy : destinationURL.path => %@", destinationURL.path);
        NSLog(@"Error during the copy : destinationURL.path executable? => %@", [fileManager isExecutableFileAtPath:[destinationURL.path stringByDeletingLastPathComponent]] ? @"YES" : @"NO");

#endif
        if (_errorBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _errorBlock([downloadTask taskIdentifier], errorCopy, identifier);
            });
        }
    }
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{

}

#pragma mark - delegate for session task <NSURLSessionTaskDelegate, NSURLSessionDelegate>
//-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
//{
//    if (error == nil) {
//        NSLog(@"Task ; %@  complete successfully", task);
//    } else {
//        NSLog(@"Task : %@  complete with error : %@", task, [error localizedDescription]);
//    }
//
//    double progress = (double) task.countOfBytesReceived/(double) task.countOfBytesExpectedToReceive;
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        _progressView.progress = progress;
//    });
//
//    _downloadTask = nil;
//}
//
//-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
//{
//    AppDelegate *appdelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
//
//    if (appdelegate.backgroundSessionCompletionHandler) {
//        void (^completionHAndler)() = appdelegate.backgroundSessionCompletionHandler;
//        appdelegate.backgroundSessionCompletionHandler = nil;
//        completionHAndler();
//    }
//
//    NSLog(@"Alltask are finished");
//}

@end


text:
/*
 * This file contains the logic to render the RDD DAG visualization in the UI.
 *
 * This DAG describes the relationships between
 *   (1) an RDD and its dependencies,
 *   (2) an RDD and its operation scopes, and
 *   (3) an RDD's operation scopes and the stage / job hierarchy
 *
 * An operation scope is a general, named code block that instantiates RDDs
 * (e.g. filter, textFile, reduceByKey). An operation scope can be nested inside
 * of other scopes if the corresponding RDD operation invokes other such operations
 * (for more detail, see o.a.s.rdd.RDDOperationScope).
 *
 * A stage may include one or more operation scopes if the RDD operations are
 * streamlined into one stage (e.g. rdd.map(...).filter(...).flatMap(...)).
 * On the flip side, an operation scope may also include one or many stages,
 * or even jobs if the RDD operation is higher level than Spark's scheduling
 * primitives (e.g. take, any SQL query).
 *
 * In the visualization, an RDD is expressed as a node, and its dependencies
 * as directed edges (from parent to child). Operation scopes, stages, and
 * jobs are expressed as clusters that may contain one or many nodes. These
 * clusters may be nested inside of each other in the scenarios described
 * above.
 *
 * The visualization is rendered in an SVG contained in "div#dag-viz-graph",
 * and its input data is expected to be populated in "div#dag-viz-metadata"
 * by Spark's UI code. This is currently used only on the stage page and on
 * the job page.
 *
 * This requires jQuery, d3, and dagre-d3. Note that we use a custom release
 * of dagre-d3 (http://github.com/andrewor14/dagre-d3) for some specific
 * functionality. For more detail, please track the changes in that project
 * since it was forked (commit 101503833a8ce5fe369547f6addf3e71172ce10b).
 */

var VizConstants = {
  svgMarginX: 16,
  svgMarginY: 16,
  stageSep: 40,
  graphPrefix: "graph_",
  nodePrefix: "node_",
  clusterPrefix: "cluster_"
};

var JobPageVizConstants = {
  clusterLabelSize: 12,
  stageClusterLabelSize: 14,
  rankSep: 40
};

var StagePageVizConstants = {
  clusterLabelSize: 14,
  stageClusterLabelSize: 14,
  rankSep: 40
};

/*
 * Return "expand-dag-viz-arrow-job" if forJob is true.
 * Otherwise, return "expand-dag-viz-arrow-stage".
 */
function expandDagVizArrowKey(forJob) {
  return forJob ? "expand-dag-viz-arrow-job" : "expand-dag-viz-arrow-stage";
}

/*
 * Show or hide the RDD DAG visualization.
 *
 * The graph is only rendered the first time this is called.
 * This is the narrow interface called from the Scala UI code.
 */
function toggleDagViz(forJob) {
  var status = window.localStorage.getItem(expandDagVizArrowKey(forJob)) == "true";
  status = !status;

  var arrowSelector = ".expand-dag-viz-arrow";
  $(arrowSelector).toggleClass('arrow-closed');
  $(arrowSelector).toggleClass('arrow-open');
  var shouldShow = $(arrowSelector).hasClass("arrow-open");
  if (shouldShow) {
    var shouldRender = graphContainer().select("*").empty();
    if (shouldRender) {
      renderDagViz(forJob);
    }
    graphContainer().style("display", "block");
  } else {
    // Save the graph for later so we don't have to render it again
    graphContainer().style("display", "none");
  }

  window.localStorage.setItem(expandDagVizArrowKey(forJob), "" + status);
}

$(function (){
  if ($("#stage-dag-viz").length &&
      window.localStorage.getItem(expandDagVizArrowKey(false)) == "true") {
    // Set it to false so that the click function can revert it
    window.localStorage.setItem(expandDagVizArrowKey(false), "false");
    toggleDagViz(false);
  } else if ($("#job-dag-viz").length &&
      window.localStorage.getItem(expandDagVizArrowKey(true)) == "true") {
    // Set it to false so that the click function can revert it
    window.localStorage.setItem(expandDagVizArrowKey(true), "false");
    toggleDagViz(true);
  }
});

/*
 * Render the RDD DAG visualization.
 *
 * Input DOM hierarchy:
 *   div#dag-viz-metadata >
 *   div.stage-metadata >
 *   div.[dot-file | incoming-edge | outgoing-edge]
 *
 * Output DOM hierarchy:
 *   div#dag-viz-graph >
 *   svg >
 *   g.cluster_stage_[stageId]
 *
 * Note that the input metadata is populated by o.a.s.ui.UIUtils.showDagViz.
 * Any changes in the input format here must be reflected there.
 */
function renderDagViz(forJob) {

  // If there is not a dot file to render, fail fast and report error
  var jobOrStage = forJob ? "job" : "stage";
  if (metadataContainer().empty() ||
      metadataContainer().selectAll("div").empty()) {
    var message =
      "No visualization information available for this " + jobOrStage + "!
" +
      "If this is an old " + jobOrStage + ", its visualization metadata may have been " +
      "cleaned up over time.
 You may consider increasing the value of ";
    if (forJob) {
      message += "spark.ui.retainedJobs and spark.ui.retainedStages.";
    } else {
      message += "spark.ui.retainedStages";
    }
    graphContainer().append("div").attr("id", "empty-dag-viz-message").html(message);
    return;
  }

  // Render
  var svg = graphContainer().append("svg").attr("class", jobOrStage);
  if (forJob) {
    renderDagVizForJob(svg);
  } else {
    renderDagVizForStage(svg);
  }

  // Find cached RDDs and mark them as such
  metadataContainer().selectAll(".cached-rdd").each(function(v) {
    var rddId = d3.select(this).text().trim();
    var nodeId = VizConstants.nodePrefix + rddId;
    svg.selectAll("g." + nodeId).classed("cached", true);
  });

  metadataContainer().selectAll(".barrier-rdd").each(function() {
    var rddId = d3.select(this).text().trim();
    var clusterId = VizConstants.clusterPrefix + rddId;
    svg.selectAll("g." + clusterId).classed("barrier", true)
  });

  resizeSvg(svg);
  interpretLineBreak(svg);
}

/* Render the RDD DAG visualization on the stage page. */
function renderDagVizForStage(svgContainer) {
  var metadata = metadataContainer().select(".stage-metadata");
  var dot = metadata.select(".dot-file").text().trim();
  var containerId = VizConstants.graphPrefix + metadata.attr("stage-id");
  var container = svgContainer.append("g").attr("id", containerId);
  renderDot(dot, container, false);

  // Round corners on rectangles
  svgContainer
    .selectAll("rect")
    .attr("rx", "5")
    .attr("ry", "5");
}

/*
 * Render the RDD DAG visualization on the job page.
 *
 * Due to limitations in dagre-d3, each stage is rendered independently so that
 * we have more control on how to position them. Unfortunately, this means we
 * cannot rely on dagre-d3 to render edges that cross stages and must render
 * these manually on our own.
 */
function renderDagVizForJob(svgContainer) {
  var crossStageEdges = [];

  // Each div.stage-metadata contains the information needed to generate the graph
  // for a stage. This includes the DOT file produced from the appropriate UI listener,
  // any incoming and outgoing edges, and any cached RDDs that belong to this stage.
  metadataContainer().selectAll(".stage-metadata").each(function(d, i) {
    var metadata = d3.select(this);
    var dot = metadata.select(".dot-file").text();
    var stageId = metadata.attr("stage-id");
    var containerId = VizConstants.graphPrefix + stageId;
    var isSkipped = metadata.attr("skipped") == "true";
    var container;
    if (isSkipped) {
      container = svgContainer
        .append("g")
        .attr("id", containerId)
        .attr("skipped", "true");
    } else {
      // Link each graph to the corresponding stage page (TODO: handle stage attempts)
      // Use the link from the stage table so it also works for the history server
      var attemptId = 0;
      var stageLink = d3.select("#stage-" + stageId + "-" + attemptId)
        .select("a.name-link")
        .attr("href");
      container = svgContainer
        .append("a")
        .attr("xlink:href", stageLink)
        .attr("onclick", "window.localStorage.setItem(expandDagVizArrowKey(false), true)")
        .append("g")
        .attr("id", containerId);
    }

    // Now we need to shift the container for this stage so it doesn't overlap with
    // existing ones, taking into account the position and width of the last stage's
    // container. We do not need to do this for the first stage of this job.
    if (i > 0) {
      var existingStages = svgContainer.selectAll("g.cluster.stage");
      if (!existingStages.empty()) {
        var lastStage = d3.select(existingStages[0].pop());
        var lastStageWidth = toFloat(lastStage.select("rect").attr("width"));
        var lastStagePosition = getAbsolutePosition(lastStage);
        var offset = lastStagePosition.x + lastStageWidth + VizConstants.stageSep;
        container.attr("transform", "translate(" + offset + ", 0)");
      }
    }

    // Actually render the stage
    renderDot(dot, container, true);

    // Mark elements as skipped if appropriate. Unfortunately we need to mark all
    // elements instead of the parent container because of CSS override rules.
    if (isSkipped) {
      container.selectAll("g").classed("skipped", true);
    }

    // Round corners on rectangles
    container
      .selectAll("rect")
      .attr("rx", "4")
      .attr("ry", "4");

    // If there are any incoming edges into this graph, keep track of them to render
    // them separately later. Note that we cannot draw them now because we need to
    // put these edges in a separate container that is on top of all stage graphs.
    metadata.selectAll(".incoming-edge").each(function(v) {
      var edge = d3.select(this).text().trim().split(","); // e.g. 3,4 => [3, 4]
      crossStageEdges.push(edge);
    });
  });

  addTooltipsForRDDs(svgContainer);
  drawCrossStageEdges(crossStageEdges, svgContainer);
}

/* Render the dot file as an SVG in the given container. */
function renderDot(dot, container, forJob) {
  var g = graphlibDot.read(dot);
  var renderer = new dagreD3.render();
  preprocessGraphLayout(g, forJob);
  renderer(container, g);

  // Find the stage cluster and mark it for styling and post-processing
  container.selectAll("g.cluster[name^=\"Stage \"]").classed("stage", true);
}

/* -------------------- *
 * | Helper functions | *
 * -------------------- */

// Helper d3 accessors
function graphContainer() { return d3.select("#dag-viz-graph"); }
function metadataContainer() { return d3.select("#dag-viz-metadata"); }

/*
 * Helper function to pre-process the graph layout.
 * This step is necessary for certain styles that affect the positioning
 * and sizes of graph elements, e.g. padding, font style, shape.
 */
function preprocessGraphLayout(g, forJob) {
  var nodes = g.nodes();
  for (var i = 0; i < nodes.length; i++) {
    var isCluster = g.children(nodes[i]).length > 0;
    if (!isCluster) {
      var node = g.node(nodes[i]);
      if (forJob) {
        // Do not display RDD name on job page
        node.shape = "circle";
        node.labelStyle = "font-size: 0px";
      } else {
        node.labelStyle = "font-size: 12px";
      }
      node.padding = "5";
    }
  }
  // Curve the edges
  var edges = g.edges();
  for (var j = 0; j < edges.length; j++) {
    var edge = g.edge(edges[j]);
    edge.lineInterpolate = "basis";
  }
  // Adjust vertical separation between nodes
  if (forJob) {
    g.graph().rankSep = JobPageVizConstants.rankSep;
  } else {
    g.graph().rankSep = StagePageVizConstants.rankSep;
  }
}

/*
 * Helper function to size the SVG appropriately such that all elements are displyed.
 * This assumes that all outermost elements are clusters (rectangles).
 */
function resizeSvg(svg) {
  var allClusters = svg.selectAll("g.cluster rect")[0];
  var startX = -VizConstants.svgMarginX +
    toFloat(d3.min(allClusters, function(e) {
      return getAbsolutePosition(d3.select(e)).x;
    }));
  var startY = -VizConstants.svgMarginY +
    toFloat(d3.min(allClusters, function(e) {
      return getAbsolutePosition(d3.select(e)).y;
    }));
  var endX = VizConstants.svgMarginX +
    toFloat(d3.max(allClusters, function(e) {
      var t = d3.select(e);
      return getAbsolutePosition(t).x + toFloat(t.attr("width"));
    }));
  var endY = VizConstants.svgMarginY +
    toFloat(d3.max(allClusters, function(e) {
      var t = d3.select(e);
      return getAbsolutePosition(t).y + toFloat(t.attr("height"));
    }));
  var width = endX - startX;
  var height = endY - startY;
  svg.attr("viewBox", startX + " " + startY + " " + width + " " + height)
     .attr("width", width)
     .attr("height", height);
}

/*
 * Helper function to interpret line break for tag 'tspan'.
 * For tag 'tspan', line break '/n' is display in UI as raw for both stage page and job page,
 * here this function is to enable line break.
 */
function interpretLineBreak(svg) {
  svg.selectAll("tspan").each(function() {
    var node = d3.select(this);
    var original = node[0][0].innerHTML;
    if (original.indexOf("\\n") != -1) {
      var arr = original.split("\\n");
      var newNode = this.cloneNode(this);

      node[0][0].innerHTML = arr[0];
      newNode.innerHTML = arr[1];

      this.parentNode.appendChild(newNode);
    }
  });
}

/*
 * (Job page only) Helper function to draw edges that cross stage boundaries.
 * We need to do this manually because we render each stage separately in dagre-d3.
 */
function drawCrossStageEdges(edges, svgContainer) {
  if (edges.length == 0) {
    return;
  }
  // Draw the paths first
  var edgesContainer = svgContainer.append("g").attr("id", "cross-stage-edges");
  for (var i = 0; i < edges.length; i++) {
    var fromRDDId = edges[i][0];
    var toRDDId = edges[i][1];
    connectRDDs(fromRDDId, toRDDId, edgesContainer, svgContainer);
  }
  // Now draw the arrows by borrowing the arrow marker generated by dagre-d3
  var dagreD3Marker = svgContainer.select("g.edgePaths marker");
  if (!dagreD3Marker.empty()) {
    svgContainer
      .append(function() { return dagreD3Marker.node().cloneNode(true); })
      .attr("id", "marker-arrow");
    svgContainer.selectAll("g > path").attr("marker-end", "url(#marker-arrow)");
    svgContainer.selectAll("g.edgePaths def").remove(); // We no longer need these
  }
}

/*
 * (Job page only) Helper function to compute the absolute
 * position of the specified element in our graph.
 */
function getAbsolutePosition(d3selection) {
  if (d3selection.empty()) {
    throw "Attempted to get absolute position of an empty selection.";
  }
  var obj = d3selection;
  var _x = toFloat(obj.attr("x")) || 0;
  var _y = toFloat(obj.attr("y")) || 0;
  while (!obj.empty()) {
    var transformText = obj.attr("transform");
    if (transformText) {
      var translate = d3.transform(transformText).translate;
      _x += toFloat(translate[0]);
      _y += toFloat(translate[1]);
    }
    // Climb upwards to find how our parents are translated
    obj = d3.select(obj.node().parentNode);
    // Stop when we've reached the graph container itself
    if (obj.node() == graphContainer().node()) {
      break;
    }
  }
  return { x: _x, y: _y };
}

/* (Job page only) Helper function to connect two RDDs with a curved edge. */
function connectRDDs(fromRDDId, toRDDId, edgesContainer, svgContainer) {
  var fromNodeId = VizConstants.nodePrefix + fromRDDId;
  var toNodeId = VizConstants.nodePrefix + toRDDId;
  var fromPos = getAbsolutePosition(svgContainer.select("g." + fromNodeId));
  var toPos = getAbsolutePosition(svgContainer.select("g." + toNodeId));

  // On the job page, RDDs are rendered as dots (circles). When rendering the path,
  // we need to account for the radii of these circles. Otherwise the arrow heads
  // will bleed into the circle itself.
  var delta = toFloat(svgContainer
    .select("g.node." + toNodeId)
    .select("circle")
    .attr("r"));
  if (fromPos.x < toPos.x) {
    fromPos.x += delta;
    toPos.x -= delta;
  } else if (fromPos.x > toPos.x) {
    fromPos.x -= delta;
    toPos.x += delta;
  }

  var points;
  if (fromPos.y == toPos.y) {
    // If they are on the same rank, curve the middle part of the edge
    // upward a little to avoid interference with things in between
    // e.g.       _______
    //      _____/       \_____
    points = [
      [fromPos.x, fromPos.y],
      [fromPos.x + (toPos.x - fromPos.x) * 0.2, fromPos.y],
      [fromPos.x + (toPos.x - fromPos.x) * 0.3, fromPos.y - 20],
      [fromPos.x + (toPos.x - fromPos.x) * 0.7, fromPos.y - 20],
      [fromPos.x + (toPos.x - fromPos.x) * 0.8, toPos.y],
      [toPos.x, toPos.y]
    ];
  } else {
    // Otherwise, draw a curved edge that flattens out on both ends
    // e.g.       _____
    //           /
    //          |
    //    _____/
    points = [
      [fromPos.x, fromPos.y],
      [fromPos.x + (toPos.x - fromPos.x) * 0.4, fromPos.y],
      [fromPos.x + (toPos.x - fromPos.x) * 0.6, toPos.y],
      [toPos.x, toPos.y]
    ];
  }

  var line = d3.svg.line().interpolate("basis");
  edgesContainer.append("path").datum(points).attr("d", line);
}

/* (Job page only) Helper function to add tooltips for RDDs. */
function addTooltipsForRDDs(svgContainer) {
  svgContainer.selectAll("g.node").each(function() {
    var node = d3.select(this);
    var tooltipText = node.attr("name");
    if (tooltipText) {
      node.select("circle")
        .attr("data-toggle", "tooltip")
        .attr("data-placement", "top")
        .attr("data-html", "true") // to interpret line break, tooltipText is showing <circle> title
        .attr("title", tooltipText);
    }
    // Link tooltips for all nodes that belong to the same RDD
    node.on("mouseenter", function() { triggerTooltipForRDD(node, true); });
    node.on("mouseleave", function() { triggerTooltipForRDD(node, false); });
  });

  $("[data-toggle=tooltip]")
    .filter("g.node circle")
    .tooltip({ container: "body", trigger: "manual" });
}

/*
 * (Job page only) Helper function to show or hide tooltips for all nodes
 * in the graph that refer to the same RDD the specified node represents.
 */
function triggerTooltipForRDD(d3node, show) {
  var classes = d3node.node().classList;
  for (var i = 0; i < classes.length; i++) {
    var clazz = classes[i];
    var isRDDClass = clazz.indexOf(VizConstants.nodePrefix) == 0;
    if (isRDDClass) {
      graphContainer().selectAll("g." + clazz).each(function() {
        var circle = d3.select(this).select("circle").node();
        var showOrHide = show ? "show" : "hide";
        $(circle).tooltip(showOrHide);
      });
    }
  }
}

/* Helper function to convert attributes to numeric values. */
function toFloat(f) {
  if (f) {
    return parseFloat(f.toString().replace(/px$/, ""));
  } else {
    return f;
  }
}


text:
  Chamant est
       un village
       situé dans le département de l'Oise en Picardie. On dénombrait 929 habitants en 2008.

Le parc de logements, à Chamant, était réparti en 2011 en 68 appartements et 361 maisons soit
 un marché relativement équilibré.

À Chamant, la valeur moyenne à la vente d'un appartement s'évalue à 3 125 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 285 € du m². À la location la valorisation moyenne se situe à 7,69 € du m² par mois.

La ville compte quelques  aménagements, elle dispose, entre autres, de un terrain de tennis et un centre d'équitation.

À coté de Chamant sont situées les villes de
Borest à 6 km, 339 habitants,
Montépilloy localisée à 6 km, 159 habitants,
Aumont-en-Halatte localisée à 4 km, 548 habitants,
Senlis située à 2 km, 16 452 habitants,
Villers-Saint-Frambourg localisée à 4 km, 603 habitants,
Avilly-Saint-Léonard située à 6 km, 983 habitants,
 entre autres. De plus, Chamant est située à seulement 26 km de Compiègne.

Si vous pensez emmenager à Chamant, vous pourrez facilement trouver une maison à vendre.


text: export * from './home/home';


text:
@implementation CDMSignInWindowController

#pragma mark - NSWindowController

- (NSString *)windowNibName {
	return @"SignIn";
}

- (void)windowDidLoad {
	[super windowDidLoad];

	[self.signUpButton setButtonColor:[NSColor cheddarSteelColor]];
	[self.signInButton setButtonColor:[NSColor cheddarOrangeColor]];

	NSColor *color = CDMSignInWindowControllerLabelTextColor;
	NSFont *font = CDMSignInWindowControllerFont;

	[self.usernameLabel setTextColor:color];
	[self.usernameLabel setFont:font];

	[self.passwordLabel setTextColor:color];
	[self.passwordLabel setFont:font];
}

#pragma mark - Actions

- (IBAction)signIn:(id)sender {
	if (self.usernameTextField.stringValue.length == 0 || self.passwordTextField.stringValue.length == 0) {
		CDMArchesWindow *archesWindow = (CDMArchesWindow *)self.window;
		[archesWindow shake:nil];
		return;
	}

	[[CDKHTTPClient sharedClient] signInWithLogin:self.usernameTextField.stringValue password:self.passwordTextField.stringValue success:^(AFJSONRequestOperation *operation, id responseObject) {
		dispatch_async(dispatch_get_main_queue(), ^{
			[self.usernameTextField becomeFirstResponder];
			[self close];
			self.usernameTextField.stringValue = @"";
			self.passwordTextField.stringValue = @"";
		});
	} failure:^(AFJSONRequestOperation *operation, NSError *error) {
		dispatch_async(dispatch_get_main_queue(), ^{
			CDMArchesWindow *archesWindow = (CDMArchesWindow *)self.window;
			[archesWindow shake:nil];
		});
    }];
}

- (IBAction)signUp:(id)sender {
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://cheddarapp.com/signup"]];
}

- (IBAction)forgotPassword:(id)sender {
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://cheddarapp.com/forgot"]];
}

@end


text:
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Tests for mutating expressions
 */

'use strict';

const assert = require('assert');

const babelTypes = require('@babel/types');
const sinon = require('sinon');

const common = require('../mutators/common.js');
const expressionMutator = require('../mutators/expression_mutator.js');
const helpers = require('./helpers.js');
const scriptMutator = require('../script_mutator.js');
const sourceHelpers = require('../source_helpers.js');
const random = require('../random.js');

const sandbox = sinon.createSandbox();

function testCloneSiblings(expected_file) {
  const source = helpers.loadTestData('mutate_expressions.js');

  const settings = scriptMutator.defaultSettings();
  settings['MUTATE_EXPRESSIONS'] = 1.0;

  const mutator = new expressionMutator.ExpressionMutator(settings);
  mutator.mutate(source);

  const mutated = sourceHelpers.generateCode(source);
  helpers.assertExpectedResult(expected_file, mutated);
}

describe('Mutate expressions', () => {
  beforeEach(() => {
    // Select the previous sibling.
    sandbox.stub(random, 'randInt').callsFake((a, b) => b);
    // This chooses cloning siblings.
    sandbox.stub(random, 'random').callsFake(() => 0.8);
  });

  afterEach(() => {
    sandbox.restore();
  });

  it('clones previous to current', () => {
    // Keep the order of [previous, current], select previous.
    sandbox.stub(random, 'shuffle').callsFake(a => a);
    // Insert after. Keep returning true for the MUTATE_EXPRESSIONS check.
    sandbox.stub(random, 'choose').callsFake(a => a === 1);

    testCloneSiblings('mutate_expressions_previous_expected.js');
  });

  it('clones current to previous', () => {
    // Switch the order of [previous, current], select current.
    sandbox.stub(random, 'shuffle').callsFake(a => [a[1], a[0]]);
    // Insert before.
    sandbox.stub(random, 'choose').callsFake(() => true);

    testCloneSiblings('mutate_expressions_current_expected.js');
  });
});

describe('Cloning', () => {
  // Ensure that the source location we add are not cloned.
  it('is not copying added state', () => {
    const source = helpers.loadTestData('mutate_expressions.js');
    common.setSourceLoc(source, 5, 10);
    const noopNode = source.ast.program.body[0];
    assert.equal(0.5, common.getSourceLoc(noopNode));
    const cloned = babelTypes.cloneDeep(noopNode);
    assert.equal(undefined, common.getSourceLoc(cloned));
  });
});


text:
package org.jruby.rack.fake;

import java.io.IOException;
import java.util.Enumeration;
import javax.el.ELContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.el.ExpressionEvaluator;
import javax.servlet.jsp.el.VariableResolver;

/**
 * Currently only used as a mock for testing.
 */
public class FakePageContext extends PageContext {
    private ServletContext context;
    private ServletRequest request;
    private ServletResponse response;
    private JspWriter out;

    public FakePageContext(ServletContext context, HttpServletRequest request, HttpServletResponse response, JspWriter out) {
        this.context = context;
        this.request = request;
        this.response = response;
        this.out = out;
    }
    @Override
    public Object findAttribute(String arg0) {
        throw new UnsupportedOperationException("Not supported yet. findAttribute");
    }

    @Override
    public void forward(String arg0) throws ServletException, IOException {
        throw new UnsupportedOperationException("Not supported yet. forward");
    }

    @Override
    public Object getAttribute(String arg0) {
        throw new UnsupportedOperationException("Not supported yet. getAttribute");
    }

    @Override
    public Object getAttribute(String arg0, int arg1) {
        throw new UnsupportedOperationException("Not supported yet. getAttribute2");
    }

    @Override
    public Enumeration<String> getAttributeNamesInScope(int arg0) {
        throw new UnsupportedOperationException("Not supported yet. getAttributeNamesInScope");
    }

    @Override
    public int getAttributesScope(String arg0) {
        throw new UnsupportedOperationException("Not supported yet. getAttributesScope");
    }

    @Override
    public Exception getException() {
        throw new UnsupportedOperationException("Not supported yet. getException");
    }

    @Override
    public JspWriter getOut() {
        return out;
    }

    @Override
    public Object getPage() {
        throw new UnsupportedOperationException("Not supported yet. getPage");
    }

    @Override
    public ServletRequest getRequest() {
        return request;
    }

    @Override
    public ServletResponse getResponse() {
        return response;
    }

    @Override
    public ServletConfig getServletConfig() {
        throw new UnsupportedOperationException("Not supported yet. getServletConfig");
    }

    @Override
    public ServletContext getServletContext() {
        return context;
    }

    @Override
    public HttpSession getSession() {
        throw new UnsupportedOperationException("Not supported yet. getSession");
    }

    @Override
    public void handlePageException(Exception arg0) throws ServletException, IOException {
        throw new UnsupportedOperationException("Not supported yet. handlePageException");
    }

    @Override
    public void handlePageException(Throwable arg0) throws ServletException, IOException {
        throw new UnsupportedOperationException("Not supported yet. handlePageException");
    }

    @Override
    public void include(String arg0) throws ServletException, IOException {
        throw new UnsupportedOperationException("Not supported yet. include");
    }

    @Override
    public void initialize(Servlet arg0, ServletRequest arg1, ServletResponse arg2, String arg3, boolean arg4, int arg5, boolean arg6) throws IOException, IllegalStateException, IllegalArgumentException {
        throw new UnsupportedOperationException("Not supported yet. initialize");
    }

    @Override
    public void release() {
        throw new UnsupportedOperationException("Not supported yet. release");
    }

    @Override
    public void removeAttribute(String arg0) {
        throw new UnsupportedOperationException("Not supported yet. removeAttribute");
    }

    @Override
    public void removeAttribute(String arg0, int arg1) {
        throw new UnsupportedOperationException("Not supported yet. removeAttribute");
    }

    @Override
    public void setAttribute(String arg0, Object arg1) {
        throw new UnsupportedOperationException("Not supported yet. setAttribute");
    }

    @Override
    public void setAttribute(String arg0, Object arg1, int arg2) {
        throw new UnsupportedOperationException("Not supported yet setAttribute");
    }

    @Override
    public void include(String arg0, boolean arg1) throws ServletException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ExpressionEvaluator getExpressionEvaluator() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public VariableResolver getVariableResolver() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ELContext getELContext() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}


text:
package org.apache.shardingsphere.shardingscaling.core.execute.engine;

import org.apache.shardingsphere.shardingscaling.core.execute.executor.ShardingScalingExecutor;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import lombok.RequiredArgsConstructor;

/**
 * Sharding scaling executor engine.
 */
public class ShardingScalingExecuteEngine {

    private final ListeningExecutorService executorService;

    public ShardingScalingExecuteEngine(final int maxWorkerNumber) {
        this.executorService = MoreExecutors.listeningDecorator(
            new ThreadPoolExecutor(maxWorkerNumber, maxWorkerNumber, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.AbortPolicy()));
    }

    /**
     * Submit a {@code ShardingScalingExecutor} without callback to execute.
     *
     * @param shardingScalingExecutor sharding scaling executor
     * @return execute future
     */
    public Future submit(final ShardingScalingExecutor shardingScalingExecutor) {
        return executorService.submit(shardingScalingExecutor);
    }

    /**
     * Submit a {@code ShardingScalingExecutor} with callback {@code ExecuteCallback} to execute.
     *
     * @param shardingScalingExecutor sharding scaling executor
     * @param executeCallback execute callback
     * @return execute future
     */
    public Future submit(final ShardingScalingExecutor shardingScalingExecutor, final ExecuteCallback executeCallback) {
        ListenableFuture result = executorService.submit(shardingScalingExecutor);
        Futures.addCallback(result, new ExecuteFutureCallback<>(executeCallback));
        return result;
    }

    /**
     * Submit a collection of {@code ShardingScalingExecutor} with callback {@code ExecuteCallback} to execute.
     *
     * @param shardingScalingExecutors sharding scaling executor
     * @param executeCallback execute callback
     * @return execute future of all
     */
    public Future submitAll(final Collection<? extends ShardingScalingExecutor> shardingScalingExecutors, final ExecuteCallback executeCallback) {
        Collection<ListenableFuture<Object>> listenableFutures = new ArrayList<>(shardingScalingExecutors.size());
        for (ShardingScalingExecutor each : shardingScalingExecutors) {
            ListenableFuture listenableFuture = executorService.submit(each);
            listenableFutures.add(listenableFuture);
        }
        ListenableFuture result = Futures.allAsList(listenableFutures);
        Futures.addCallback(result, new ExecuteFutureCallback<Collection<Object>>(executeCallback));
        return result;
    }

    @RequiredArgsConstructor
    private static class ExecuteFutureCallback<V> implements FutureCallback<V> {

        private final ExecuteCallback executeCallback;

        @Override
        public void onSuccess(final V result) {
            executeCallback.onSuccess();
        }

        @Override
        public void onFailure(final Throwable throwable) {
            executeCallback.onFailure(throwable);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.pengjieran.dao.AreaMapper" >
  <resultMap id="BaseResultMap" type="com.pengjieran.model.Area" >
    <id column="ID" property="id" jdbcType="INTEGER" />
    <result column="PARENT_ID" property="parentId" jdbcType="INTEGER" />
    <result column="NAME" property="name" jdbcType="VARCHAR" />
    <result column="SHORT_NAME" property="shortName" jdbcType="VARCHAR" />
    <result column="LONGITUDE" property="longitude" jdbcType="REAL" />
    <result column="LATITUDE" property="latitude" jdbcType="REAL" />
    <result column="LEVEL" property="level" jdbcType="INTEGER" />
    <result column="SORT" property="sort" jdbcType="INTEGER" />
    <result column="STATUS" property="status" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    ID, PARENT_ID, NAME, SHORT_NAME, LONGITUDE, LATITUDE, LEVEL, SORT, STATUS
  </sql>
  <select id="selectByParentId" resultMap="BaseResultMap" parameterType="java.lang.Integer">
  	select
    <include refid="Base_Column_List" />
    from area
    where PARENT_ID = #{parentId,jdbcType=INTEGER} order by SORT DESC
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from area
    where ID = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from area
    where ID = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.pengjieran.model.Area" >
    insert into area (ID, PARENT_ID, NAME,
      SHORT_NAME, LONGITUDE, LATITUDE,
      LEVEL, SORT, STATUS
      )
    values (#{id,jdbcType=INTEGER}, #{parentId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
      #{shortName,jdbcType=VARCHAR}, #{longitude,jdbcType=REAL}, #{latitude,jdbcType=REAL},
      #{level,jdbcType=INTEGER}, #{sort,jdbcType=INTEGER}, #{status,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.pengjieran.model.Area" >
    insert into area
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="parentId != null" >
        PARENT_ID,
      </if>
      <if test="name != null" >
        NAME,
      </if>
      <if test="shortName != null" >
        SHORT_NAME,
      </if>
      <if test="longitude != null" >
        LONGITUDE,
      </if>
      <if test="latitude != null" >
        LATITUDE,
      </if>
      <if test="level != null" >
        LEVEL,
      </if>
      <if test="sort != null" >
        SORT,
      </if>
      <if test="status != null" >
        STATUS,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="parentId != null" >
        #{parentId,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="shortName != null" >
        #{shortName,jdbcType=VARCHAR},
      </if>
      <if test="longitude != null" >
        #{longitude,jdbcType=REAL},
      </if>
      <if test="latitude != null" >
        #{latitude,jdbcType=REAL},
      </if>
      <if test="level != null" >
        #{level,jdbcType=INTEGER},
      </if>
      <if test="sort != null" >
        #{sort,jdbcType=INTEGER},
      </if>
      <if test="status != null" >
        #{status,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.pengjieran.model.Area" >
    update area
    <set >
      <if test="parentId != null" >
        PARENT_ID = #{parentId,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        NAME = #{name,jdbcType=VARCHAR},
      </if>
      <if test="shortName != null" >
        SHORT_NAME = #{shortName,jdbcType=VARCHAR},
      </if>
      <if test="longitude != null" >
        LONGITUDE = #{longitude,jdbcType=REAL},
      </if>
      <if test="latitude != null" >
        LATITUDE = #{latitude,jdbcType=REAL},
      </if>
      <if test="level != null" >
        LEVEL = #{level,jdbcType=INTEGER},
      </if>
      <if test="sort != null" >
        SORT = #{sort,jdbcType=INTEGER},
      </if>
      <if test="status != null" >
        STATUS = #{status,jdbcType=INTEGER},
      </if>
    </set>
    where ID = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.pengjieran.model.Area" >
    update area
    set PARENT_ID = #{parentId,jdbcType=INTEGER},
      NAME = #{name,jdbcType=VARCHAR},
      SHORT_NAME = #{shortName,jdbcType=VARCHAR},
      LONGITUDE = #{longitude,jdbcType=REAL},
      LATITUDE = #{latitude,jdbcType=REAL},
      LEVEL = #{level,jdbcType=INTEGER},
      SORT = #{sort,jdbcType=INTEGER},
      STATUS = #{status,jdbcType=INTEGER}
    where ID = #{id,jdbcType=INTEGER}
  </update>
</mapper>


text:
REDIS_INSTANCE_NAME=redis-server

if [ -z $REDIS_INSTANCE_NAME ]
then
	echo "ERROR: redis instance name wasn't specified."
fi

sudo /etc/init.d/$REDIS_INSTANCE_NAME stop
sudo update-rc.d -f $REDIS_INSTANCE_NAME remove
sudo rm /etc/init.d/$REDIS_INSTANCE_NAME

sudo rm /var/lib/$REDIS_INSTANCE_NAME -r
sudo rm /var/log/$REDIS_INSTANCE_NAME -r
sudo rm /usr/local/bin/$REDIS_INSTANCE_NAME
sudo rm /etc/$REDIS_INSTANCE_NAME -r


text:
//  Copyright 2015 Microsoft Corporation
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import <Foundation/Foundation.h>

typedef void(^ODURLSessionTaskCompletion)(id responseObject, NSURLResponse *response, NSError *error);

/**
 *  'ODURLSessionTaskDelegate' the delegate object for a given NSURLSessionTask
 */
@interface ODURLSessionTaskDelegate : NSObject

/**
 Creates an instance of an ODURLSessionTaskDelegate
 @param  progress an object reference to a progress
 @param  completion a completion handler to be called when the task completes
 */
- (instancetype)initWithProgressRef:(NSProgress * __autoreleasing *)progress
                        completion:(ODURLSessionTaskCompletion)completion;

/**
 Updates the progress object with the given bytes
 @param  sentBytes the number of bytes that have been sent currently, must not be nil.
 @param  expectedBytes the total number of bytes that are expected to be sent, must not be nil.
 */
- (void)updateProgressWithBytesSent:(int64_t)sentBytes expectedBytes:(int64_t)expectedBytes;

/**
 This method should be called when the NSURLSessionData task received any data
 @param  data the data that was received
 */
- (void)didReceiveData:(NSData *)data;

/**
 This method should be called when the task is completed
 @param  task the task that was completed
 @param  error any error that occurred during the task
 */
- (void)task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error;

/**
 This method should be called when the download task is completed
 @param task the task that was completed
 @param downloadLocation the location of the file that was downloaded
 */
- (void)task:(NSURLSessionTask *)task didCompleteDownload:(NSURL *)downloadLocation;

@end


text:
<?php

namespace Etu\Core\CoreBundle\Notification\Listener;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use Etu\Core\CoreBundle\Entity\Subscription;
use Etu\Core\CoreBundle\Framework\Twig\GlobalAccessorObject;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;

class NewNotifsListener
{
    /**
     * @var Registry
     */
    protected $doctrine;

    /**
     * @var TokenStorage
     */
    protected $tokenStorage;

    /**
     * @var AuthorizationChecker
     */
    protected $authorizationChecker;

    /**
     * @var GlobalAccessorObject
     */
    protected $globalAccessor;

    /**
     * @var \AppKernel
     */
    protected $kernel;

    /**
     * @param TokenStorage         $tokenStorage
     * @param AuthorizationChecker $authorizationChecker
     * @param Registry             $doctrine
     * @param GlobalAccessorObject $globalAccessor
     * @param \AppKernel           $kernel
     */
    public function __construct(TokenStorage $tokenStorage,
                                AuthorizationChecker $authorizationChecker,
                                Registry $doctrine,
                                GlobalAccessorObject $globalAccessor,
                                \AppKernel $kernel)
    {
        $this->doctrine = $doctrine;
        $this->tokenStorage = $tokenStorage;
        $this->authorizationChecker = $authorizationChecker;
        $this->globalAccessor = $globalAccessor;
        $this->kernel = $kernel;
    }

    /**
     * Event to find subscriptions on page laod.
     */
    public function onKernelRequest()
    {
        if (!$this->tokenStorage->getToken()) {
            return;
        }

        $user = $this->tokenStorage->getToken()->getUser();
        $subscriptions = [];

        if ($this->authorizationChecker->isGranted('ROLE_CORE_SUBSCRIBE')) {
            /** @var $em EntityManager */
            $em = $this->doctrine->getManager();
            $subscriptions = $em->getRepository('EtuCoreBundle:Subscription')->findBy(['user' => $user]);
        }

        $this->globalAccessor->set('notifs', new ArrayCollection());
        $this->globalAccessor->get('notifs')->set('subscriptions', $subscriptions);
        $this->globalAccessor->get('notifs')->set('new', []);
        $this->globalAccessor->get('notifs')->set('new_count', 0);
    }
}


text:
/**
 * Created by Andrey Gayvoronsky on 13/04/16.
 */
import moment from 'moment';
moment.locale('ru');
import Pagination from 'rc-pagination/lib/locale/ru_RU';
import DatePicker from '../date-picker/locale/ru_RU';
import TimePicker from '../time-picker/locale/ru_RU';
import Calendar from '../calendar/locale/ru_RU';
export default {
    locale: 'ru',
    Pagination,
    DatePicker,
    TimePicker,
    Calendar,
    Table: {
        filterTitle: 'Фильтр',
        filterConfirm: 'OK',
        filterReset: 'Сбросить',
        emptyText: 'Нет данных',
        selectAll: 'Выбрать всё',
        selectInvert: 'Инвертировать выбор',
    },
    Modal: {
        okText: 'OK',
        cancelText: 'Отмена',
        justOkText: 'OK',
    },
    Popconfirm: {
        okText: 'OK',
        cancelText: 'Отмена',
    },
    Transfer: {
        notFoundContent: 'Ничего не найдено',
        searchPlaceholder: 'Введите название для поиска',
        itemUnit: 'item',
        itemsUnit: 'items',
    },
    Select: {
        notFoundContent: 'Ничего не найдено',
    },
    Upload: {
        uploading: 'Закачиваю...',
        removeFile: 'Удалить файл',
        uploadError: 'Ошибка при закачке',
        previewFile: 'Предпросмотр файла',
    },
};


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { HomeComponent } from './home.component';

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should render content in a h2 tag', async(() => {
    const fixture = TestBed.createComponent(HomeComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h2').textContent).toContain('Home page.');
  }));
});


text:
<?php
/*
Template Name: Backdrop Template
*/

$fullscreenBG = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'original' );

if (isset($fullscreenBG) && $fullscreenBG[0] != '') {
  $style = "background-image: url('{$fullscreenBG[0]}')";
} else {
  $style = '';
}

?>

  <div class="content backdrop" style="<?php echo $style; ?>">

          <?php get_template_part('templates/content', 'page'); ?>


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    Vehicle *car = [[Vehicle alloc] init];
    car.make = @"Toyota";
    car.model = @"Corolla";
    car.engineSize = @"V12";

    Vehicle *car2 = [[Vehicle alloc] init];
    car2.make = @"Tesla";
    car2.model = @"Model S";
    car2.engineSize = @"Electric";

    NSArray *arr = [NSArray arrayWithObjects:car, car2, nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
package com.google.cloud.language.v1beta2.samples;

// [START language_v1beta2_generated_LanguageService_AnalyzeEntities_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.language.v1beta2.AnalyzeEntitiesRequest;
import com.google.cloud.language.v1beta2.AnalyzeEntitiesResponse;
import com.google.cloud.language.v1beta2.Document;
import com.google.cloud.language.v1beta2.EncodingType;
import com.google.cloud.language.v1beta2.LanguageServiceClient;

public class AsyncAnalyzeEntities {

  public static void main(String[] args) throws Exception {
    asyncAnalyzeEntities();
  }

  public static void asyncAnalyzeEntities() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
      AnalyzeEntitiesRequest request =
          AnalyzeEntitiesRequest.newBuilder()
              .setDocument(Document.newBuilder().build())
              .setEncodingType(EncodingType.forNumber(0))
              .build();
      ApiFuture<AnalyzeEntitiesResponse> future =
          languageServiceClient.analyzeEntitiesCallable().futureCall(request);
      // Do something.
      AnalyzeEntitiesResponse response = future.get();
    }
  }
}
// [END language_v1beta2_generated_LanguageService_AnalyzeEntities_async]