text:
#!/usr/bin/python
#

#####################################################################
# This script is designed to modify the call to the QEMU emulator
# to support userspace vhost when starting a guest machine through
# libvirt with vhost enabled. The steps to enable this are as follows
# and should be run as root:
#
# 1. Place this script in a libvirtd's binary search PATH ($PATH)
#    A good location would be in the same directory that the QEMU
#    binary is located
#
# 2. Ensure that the script has the same owner/group and file
#    permissions as the QEMU binary
#
# 3. Update the VM xml file using "virsh edit VM.xml"
#
#    3.a) Set the VM to use the launch script
#
#    	Set the emulator path contained in the
#		<emulator><emulator/> tags
#
#    	e.g replace <emulator>/usr/bin/qemu-kvm<emulator/>
#        with    <emulator>/usr/bin/qemu-wrap.py<emulator/>
#
#	 3.b) Set the VM's device's to use vhost-net offload
#
#		<interface type="network">
#       	<model type="virtio"/>
#       	<driver name="vhost"/>
#		<interface/>
#
# 4. Enable libvirt to access our userpace device file by adding it to
#    controllers cgroup for libvirtd using the following steps
#
#   4.a) In /etc/libvirt/qemu.conf add/edit the following lines:
#         1) cgroup_controllers = [ ... "devices", ... ]
#		  2) clear_emulator_capabilities = 0
#         3) user = "root"
#         4) group = "root"
#         5) cgroup_device_acl = [
#                "/dev/null", "/dev/full", "/dev/zero",
#                "/dev/random", "/dev/urandom",
#                "/dev/ptmx", "/dev/kvm", "/dev/kqemu",
#                "/dev/rtc", "/dev/hpet", "/dev/net/tun",
#                "/dev/<devbase-name>-<index>",
#            ]
#
#   4.b) Disable SELinux or set to permissive mode
#
#   4.c) Mount cgroup device controller
#        "mkdir /dev/cgroup"
#        "mount -t cgroup none /dev/cgroup -o devices"
#
#   4.d) Set hugetlbfs_mount variable - ( Optional )
#        VMs using userspace vhost must use hugepage backed
#        memory. This can be enabled in the libvirt XML
#        config by adding a memory backing section to the
#        XML config e.g.
#             <memoryBacking>
#             <hugepages/>
#             </memoryBacking>
#        This memory backing section should be added after the
#        <memory> and <currentMemory> sections. This will add
#        flags "-mem-prealloc -mem-path <path>" to the QEMU
#        command line. The hugetlbfs_mount variable can be used
#        to override the default <path> passed through by libvirt.
#
#        if "-mem-prealloc" or "-mem-path <path>" are not passed
#        through and a vhost device is detected then these options will
#        be automatically added by this script. This script will detect
#        the system hugetlbfs mount point to be used for <path>. The
#        default <path> for this script can be overidden by the
#        hugetlbfs_dir variable in the configuration section of this script.
#
#
#   4.e) Restart the libvirtd system process
#        e.g. on Fedora "systemctl restart libvirtd.service"
#
#
#   4.f) Edit the Configuration Parameters section of this script
#        to point to the correct emulator location and set any
#        addition options
#
# The script modifies the libvirtd Qemu call by modifying/adding
# options based on the configuration parameters below.
# NOTE:
#     emul_path and us_vhost_path must be set
#     All other parameters are optional
#####################################################################

#############################################
# Configuration Parameters
#############################################
#Path to QEMU binary
emul_path = "/usr/local/bin/qemu-system-x86_64"

#Path to userspace vhost device file
# This filename should match the --dev-basename --dev-index parameters of
# the command used to launch the userspace vhost sample application e.g.
# if the sample app lauch command is:
#    ./build/vhost-switch ..... --dev-basename usvhost --dev-index 1
# then this variable should be set to:
#   us_vhost_path = "/dev/usvhost-1"
us_vhost_path = "/dev/usvhost-1"

#List of additional user defined emulation options. These options will
#be added to all Qemu calls
emul_opts_user = []

#List of additional user defined emulation options for vhost only.
#These options will only be added to vhost enabled guests
emul_opts_user_vhost = []

#For all VHOST enabled VMs, the VM memory is preallocated from hugetlbfs
# Set this variable to one to enable this option for all VMs
use_huge_all = 0

#Instead of autodetecting, override the hugetlbfs directory by setting
#this variable
hugetlbfs_dir = ""

#############################################

#############################################
# ****** Do Not Modify Below this Line ******
#############################################

import sys, os, subprocess

#List of open userspace vhost file descriptors
fd_list = []

#additional virtio device flags when using userspace vhost
vhost_flags = [ "csum=off",
                "gso=off",
                "guest_tso4=off",
                "guest_tso6=off",
                "guest_ecn=off"
              ]

#############################################
# Find the system hugefile mount point.
# Note:
# if multiple hugetlbfs mount points exist
# then the first one found will be used
#############################################
def find_huge_mount():

    if (len(hugetlbfs_dir)):
        return hugetlbfs_dir

    huge_mount = ""

    if (os.access("/proc/mounts", os.F_OK)):
        f = open("/proc/mounts", "r")
        line = f.readline()
        while line:
            line_split = line.split(" ")
            if line_split[2] == 'hugetlbfs':
                huge_mount = line_split[1]
                break
            line = f.readline()
    else:
        print "/proc/mounts not found"
        exit (1)

    f.close
    if len(huge_mount) == 0:
        print "Failed to find hugetlbfs mount point"
        exit (1)

    return huge_mount

#############################################
# Get a userspace Vhost file descriptor
#############################################
def get_vhost_fd():

    if (os.access(us_vhost_path, os.F_OK)):
        fd = os.open( us_vhost_path, os.O_RDWR)
    else:
        print ("US-Vhost file %s not found" %us_vhost_path)
        exit (1)

    return fd

#############################################
# Check for vhostfd. if found then replace
# with our own vhost fd and append any vhost
# flags onto the end
#############################################
def modify_netdev_arg(arg):

    global fd_list
    vhost_in_use = 0
    s = ''
    new_opts = []
    netdev_opts = arg.split(",")

    for opt in netdev_opts:
        #check if vhost is used
        if "vhost" == opt[:5]:
            vhost_in_use = 1
        else:
            new_opts.append(opt)

    #if using vhost append vhost options
    if vhost_in_use == 1:
        #append vhost on option
        new_opts.append('vhost=on')
        #append vhostfd ption
        new_fd = get_vhost_fd()
        new_opts.append('vhostfd=' + str(new_fd))
        fd_list.append(new_fd)

    #concatenate all options
    for opt in new_opts:
        if len(s) > 0:
			s+=','

        s+=opt

    return s

#############################################
# Main
#############################################
def main():

    global fd_list
    global vhost_in_use
    new_args = []
    num_cmd_args = len(sys.argv)
    emul_call = ''
    mem_prealloc_set = 0
    mem_path_set = 0
    num = 0;

    #parse the parameters
    while (num < num_cmd_args):
        arg = sys.argv[num]

		#Check netdev +1 parameter for vhostfd
        if arg == '-netdev':
            num_vhost_devs = len(fd_list)
            new_args.append(arg)

            num+=1
            arg = sys.argv[num]
            mod_arg = modify_netdev_arg(arg)
            new_args.append(mod_arg)

            #append vhost flags if this is a vhost device
            # and -device is the next arg
            # i.e -device -opt1,-opt2,...,-opt3,%vhost
            if (num_vhost_devs < len(fd_list)):
                num+=1
                arg = sys.argv[num]
                if arg == '-device':
                    new_args.append(arg)
                    num+=1
                    new_arg = sys.argv[num]
                    for flag in vhost_flags:
                        new_arg = ''.join([new_arg,',',flag])
                    new_args.append(new_arg)
                else:
                    new_args.append(arg)
        elif arg == '-mem-prealloc':
            mem_prealloc_set = 1
            new_args.append(arg)
        elif arg == '-mem-path':
            mem_path_set = 1
            new_args.append(arg)

        else:
            new_args.append(arg)

        num+=1

    #Set Qemu binary location
    emul_call+=emul_path
    emul_call+=" "

    #Add prealloc mem options if using vhost and not already added
    if ((len(fd_list) > 0) and (mem_prealloc_set == 0)):
        emul_call += "-mem-prealloc "

    #Add mempath mem options if using vhost and not already added
    if ((len(fd_list) > 0) and (mem_path_set == 0)):
        #Detect and add hugetlbfs mount point
        mp = find_huge_mount()
        mp = "".join(["-mem-path ", mp])
        emul_call += mp
        emul_call += " "

    #add user options
    for opt in emul_opts_user:
        emul_call += opt
        emul_call += " "

    #Add add user vhost only options
    if len(fd_list) > 0:
        for opt in emul_opts_user_vhost:
            emul_call += opt
            emul_call += " "

    #Add updated libvirt options
    iter_args = iter(new_args)
    #skip 1st arg i.e. call to this script
    next(iter_args)
    for arg in iter_args:
        emul_call+=str(arg)
        emul_call+= " "

    #Call QEMU
    subprocess.call(emul_call, shell=True)

    #Close usvhost files
    for fd in fd_list:
        os.close(fd)

if __name__ == "__main__":
    main()


text:
import fetchJson from 'app/core/api/fetch-json'

/**
 * Updates a Tint in the database.
 * @async
 * @returns {Object} Tint object
 */
export const putTint = ({ data }, options = {}) => {
  if (!data) {
    throw new Error('Please pass in a data property.')
  }
  const slugOrId = data.id || data.slug
  if (!slugOrId) {
    throw new Error('You must pass either a slug or ObjectId')
  }
  return fetchJson(`/db/tint/${slugOrId}`, _.assign({}, options, {
    method: 'PUT',
    json: data
  }))
}

/**
 * Returns a list of all tint objects.
 * @async
 * @returns {Object[]} tints
 */
export const getAllTints = () => fetchJson('/db/tint/all')

redpajama_set_name: RedPajamaGithub


text:
"""Ops to use variables as resources."""

# pylint: disable=g-bad-name
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import gen_resource_variable_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resources
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_resource_variable_ops import *
# pylint: enable=wildcard-import

ops.RegisterShape("VarHandleOp")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("CreateVariableOp")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("ReadVariableOp")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("AssignVariableOp")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("AssignAddVariableOp")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("VarIsInitializedOp")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("ResourceGather")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("ResourceScatterAdd")(common_shapes.call_cpp_shape_fn)

def _register_variable_read(read, collections, trainable):
  """Helper function to put a read from a variable in the collections."""
  if collections is None:
    collections = []
  if (trainable and
      ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES not in collections):
    collections = (list(collections) +
                   [ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES])
    ops.add_to_collections(collections, read)

class ResourceVariable(object):
  """Variable based on resource handles.

  TODO(apassos): fill this out explaining the semantics and Variable
  compatibility when the API has settled more.

  """

  def __init__(self,
               initial_value=None,
               name=None,
               trainable=True,
               collections=None,
               dtype=None,
               shape=None):
    """Creates a variable.

    Args:
      initial_value: A `Tensor` or Python object convertible to a `Tensor`
        representing the initial value of this variable.
      name: The name of this variable. Automatically uniquified.
      trainable: Whether the global read of this variable will be used for
        training.
      collections: Additional collections to which the `read` operation for
        this variable is to be added. Defaults to [].
      dtype: The type of this variable. Can be omitted if it can be deduced
        from the initial_value. If different from the type of the initial
        value it will be cast to this type.
      shape: The shape of this variable. Only specify if there is no initial
        value but shape inference is desired.
    """
    if initial_value is not None:
      initial_value = ops.convert_to_tensor(initial_value)
    if dtype is None:
      assert initial_value is not None, ("Trying to create a resource variable "
                                         "with no dtype or initial value. At"
                                         " least one of these must be set.")
      dtype = initial_value.dtype
    elif initial_value is not None:
      initial_value = math_ops.cast(initial_value, dtype)
    if shape is None:
      if initial_value is not None:
        shape = initial_value.get_shape().as_proto()
      else:
        shape = tensor_shape.unknown_shape()
    else:
      shape = tensor_shape.as_shape(shape)

    self._dtype = dtype
    with ops.name_scope(name, "Variable", [initial_value]) as name:
      self._handle = gen_resource_variable_ops.var_handle_op(shared_name=name,
                                                             name=name,
                                                             dtype=dtype,
                                                             shape=shape)

      with ops.name_scope("IsInitialized"):
        self._is_initialized_op = (
            gen_resource_variable_ops.var_is_initialized_op(self._handle))
      if initial_value is not None:
        with ops.name_scope("Create"):
          self._initialize_op = gen_resource_variable_ops.create_variable_op(
              self._handle, initial_value)
        resources.register_resource(self._handle,
                                    self._initialize_op,
                                    self._is_initialized_op)

      with ops.name_scope("Read"):
        self._value = gen_resource_variable_ops.read_variable_op(
            self._handle, dtype=self._dtype)
      _register_variable_read(
          self._value, trainable=trainable, collections=collections)

  @property
  def dtype(self):
    """The dtype of this variable."""
    return self._dtype

  @property
  def create(self):
    """The op responsible for initializing this variable."""
    return self._initialize_op

  @property
  def handle(self):
    """The handle by which this variable can be accessed."""
    return self._handle

  @property
  def value(self):
    """A cached operation which reads the value of this variable."""
    return self._value

  @property
  def op(self):
    """The op which reads the value of this variable."""
    return self._value.op

  def eval(self, session=None):
    """Evaluates and returns the value of this variable."""
    return self._value.eval(session=session)

  def read_value(self, collections=None, trainable=True):
    """Constructs an op which reads the value of this variable.

    Should be used when there are multiple reads, or when it is desirable to
    read the value only after some condition is true.

    Args:
     collections: any collections in which this operation should be inserted.
     trainable: whether this read is to be used for training.

    Returns:
     the read operation.
    """
    with ops.name_scope("Read"):
      value = gen_resource_variable_ops.read_variable_op(
          self._handle, dtype=self._dtype)
    _register_variable_read(value, collections=collections, trainable=trainable)
    return value

  def sparse_read(self, indices, collections=None, trainable=True, name=None):
    with ops.name_scope("Gather" if name is None else name):
      value = gen_resource_variable_ops.resource_gather(
          self._handle, indices, Tparams=self._dtype)
    _register_variable_read(value, collections=collections, trainable=trainable)
    return value

# pylint: disable=unused-argument
def _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False):
  if dtype is not None and dtype != var.value.dtype:
    print("trying to switch the dtype to ", dtype, " from ", var.value.dtype)
    return NotImplemented
  return var.value

# Register a conversion function which reads the value of the variable,
# allowing instances of the class to be used as tensors.
ops.register_tensor_conversion_function(ResourceVariable, _dense_var_to_tensor)


text:
Visit this site on [https://lab.hackerchai.com](https://lab.hackerchai.com)

This site is to display the projects I have finished.
## Theme
----
Thanks to [@PeterCXY](https://github.com/PeterCXY).

This Material Theme is on [Github](https://github.com/hackerchai/jekyll-material-card).


text:
package org.aieonf.sketch.service;

import org.aieonf.commons.security.ISecureGenerator;
import org.aieonf.sketch.core.Dispatcher;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;

@Component
public class SecureGeneratorConsumer {

	private Dispatcher dispatcher = Dispatcher.getInstance();

	public SecureGeneratorConsumer() {}

	@Reference( cardinality = ReferenceCardinality.AT_LEAST_ONE,
			policy=ReferencePolicy.DYNAMIC)
	public synchronized void setProvider(ISecureGenerator  provider) {
		dispatcher.setGenerator(provider);
	}

	public synchronized void unsetProvider(ISecureGenerator provider) {
		dispatcher.setGenerator(null);
	}
}


text:
package gov.nasa.worldwind.formats.vpf;

import gov.nasa.worldwind.avlist.*;

import java.util.*;

/**
 * @author dcollins
 * @version $Id: GeoSymTable.java 12413 2009-08-05 18:43:56Z dcollins $
 */
public class GeoSymTable
{
    private GeoSymTableHeader header;
    private AVList[] records;
    private Map<Integer, Integer> indexOnId;

    public GeoSymTable(GeoSymTableHeader header)
    {
        this.header = header;
        this.indexOnId = new HashMap<Integer, Integer>();
    }

    public GeoSymTableHeader getHeader()
    {
        return header;
    }

    public AVList[] getRecords()
    {
        return this.records;
    }

    public void setRecords(AVList[] records)
    {
        this.records = records;
        this.buildRecordIndices();
    }

    public AVList getRecord(int id)
    {
        Integer index = this.indexOnId.get(id);
        return (index != null && index >= 0 && index < this.records.length) ? this.records[index] : null;
    }

    public static void selectMatchingRows(String columnName, Object value, boolean acceptNullValue,
        List<AVList> outRows)
    {
        Iterator<AVList> iter = outRows.iterator();
        if (!iter.hasNext())
            return;

        AVList record;
        while (iter.hasNext())
        {
            record = iter.next();
            if (record == null)
                continue;

            Object o = record.getValue(columnName);
            if ((o == null && !acceptNullValue) || (o != null && !o.equals(value)))
            {
                iter.remove();
            }
        }
    }

    public static void selectMatchingStringRows(String columnName, String value, boolean acceptNullValue,
        List<AVList> outRows)
    {
        Iterator<AVList> iter = outRows.iterator();
        if (!iter.hasNext())
            return;

        AVList record;
        while (iter.hasNext())
        {
            record = iter.next();
            if (record == null)
                continue;

            Object o = record.getValue(columnName);
            if (o == null || o instanceof String)
            {
                String s = (String) o;
                if (s == null || s.length() == 0)
                {
                    if (!acceptNullValue)
                        iter.remove();
                }
                else
                {
                    if (!s.equalsIgnoreCase(value))
                        iter.remove();
                }
            }
        }
    }

    protected void buildRecordIndices()
    {
        // Build index on record ids.
        this.indexOnId.clear();
        for (int i = 0; i < this.records.length; i++)
        {
            Integer id = AVListImpl.getIntegerValue(this.records[i], "id");
            if (id != null)
            {
                this.indexOnId.put(id, i);
            }
        }
    }
}


text:
/*
Template Name: BusyBusiness
File: Featured Slider CSS
Author: OS Templates
Author URI: http://www.os-templates.com/
Licence: Website Template Licence
*/

#featured_slide{
	padding:30px 0;
	/*font-family:Georgia, "Times New Roman", Times, serif;*/
	background-color: #eee;
	}

#featured_slide h2, #featured_slide ul, #featured_slide p, #featured_slide a{
	margin:0;
    padding:0;
	border:none;
	outline:none;
	list-style:none;
	line-height:normal;
	text-decoration:none;
	}

.preview_holder{
	display:block;
	position:relative;
	float:left;
	width:640px;
	height:270px;
	overflow:hidden;
	color:#FFFFFF;
	background-color:#000000;
	margin-left:20px;
	}

.preview_holder img{
	display:block;
	width:660px;
	height:270px;
	}

.preview_holder .text_holder{
	display:none;
	position:absolute;
	bottom:0;
	left:0;
	width:100%;
	}

.preview_holder .introtext{
	display:block;
	width:640px;
	margin:0;
	padding:10px;
	color:#FFFFFF;
	background:#333333;
	}

.selector{
	display:block;
	float:right;
	width:300px;
	}

.selector, .selector a{
	color:#666666;
	background:#F0F0F0;
	}

.selector li, .selector li.middle{
	display:block;
	width:250px;
	height:75px;
	margin:0;
	padding:15px 20px 0 30px;
	cursor:pointer;
	overflow:hidden;
	}

.selector li.middle{
	display:block;
	height:73px;
	border-top:1px solid #BFBFBF;
	border-bottom:1px solid #BFBFBF;
	}

.selector li.active, .selector li:hover{
	color:#666666;
	background:url("../images/active.gif") top left no-repeat #DDDDDD;
	}

.selector li.active a, .selector li:hover a{
	color:#333333;
	background:#DDDDDD;
	}

.selector li img{
	float:left;
	width:50px;
	height:50px;
	margin:0 15px 0 0;
	padding:4px;
	color:#333333;
	background:#FFFFFF;
	border:1px solid #000000;
	}

.selector p{visibility:hidden;}

p.title{
	font-size:20px;
	font-weight:bold;
	visibility:visible;
	}

#featured_slide .selector .introtext p.title{
	margin-top:6px;
	}

.preview_holder p.title a{
	font-size:16px;
	color:#C6CFD5;
	background:#333333;
	}


text:
using System;
using System.IO;
using System.Security.Cryptography;
using WebSignalR.Common.Interfaces;

namespace WebSignalR.Infrastructure
{
	public sealed class CommonCryptoHelper : ICrypto
	{
		private static Byte[] KEY_64 = System.Text.ASCIIEncoding.ASCII.GetBytes("39393939");
		private static Byte[] IV_64 = System.Text.ASCIIEncoding.ASCII.GetBytes("38383838");

		// returns DES encrypted string
		public string Encrypt(string palinText)
		{
			using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
			{
				using (MemoryStream ms = new MemoryStream())
				{
					CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), CryptoStreamMode.Write);
					StreamWriter sw = new StreamWriter(cs);

					sw.Write(palinText);
					sw.Flush();
					cs.FlushFinalBlock();
					ms.Flush();

					// convert back to a string
					return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
				}
			}
		}

		// returns DES decrypted string
		public string Decrypt(string payload)
		{
			payload = payload.Replace(" ", "+");

			while (payload.Length % 4 != 0)
			{
				payload += "=";
			}
			using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
			{
				Byte[] buffer = Convert.FromBase64String(payload);
				using (MemoryStream ms = new MemoryStream(buffer))
				{
					CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_64, IV_64), CryptoStreamMode.Read);
					StreamReader sr = new StreamReader(cs);

					return sr.ReadToEnd();
				}
			}
		}
	}
}


text:
package com.alexandru.developer.phoneplus;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

// Fake fragment used to define a container for the index fragment.
// I need this in order to replace correctly the index with the contacts list.

public class RootFragmentForCallsLog extends Fragment{

    private TextToSpeech tts;
    private ViewGroup rootFragment;

    public void setComponents(TextToSpeech tts){

        this.tts=tts;
    }

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container,
                              Bundle savedInstanceState){
        if(savedInstanceState!=null)
            return (ViewGroup)this.getFragmentManager().getFragment(savedInstanceState, "root_index").getView();

        rootFragment=(ViewGroup)inflater.inflate(R.layout.root_frame_for_calls_log, container, false);

        FragmentTransaction transaction=this.getFragmentManager().beginTransaction();

        CallsLogFragment callsLogFragment=new CallsLogFragment();
        callsLogFragment.setComponents(tts);

        transaction.replace(R.id.root_frame2, callsLogFragment);
        transaction.commit();

        return rootFragment;
    }

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

    }

    @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);

        //Save instance of fragment to use in onCreateView, in case onDestroyView was called
        this.getFragmentManager().putFragment(outState, "root_index", this);
    }

}


text:
<?php namespace Nord\Lumen\OAuth2\Exceptions;

class ScopeNotFound extends Exception
{
}


text:
<ng-template #EditorTabTourSaveDraft>

Save

When you're done making changes, be sure to save your work.

</ng-template>

      <button type="button" class="btn btn-light oppia-editor-publish-button e2e-test-publish-exploration"
              [ngClass]="{'btn-success': connectedToInternet && !isExplorationLockedForEditing() && !countWarnings()}"
              (click)="showPublishExplorationModal()"
              [disabled]="!connectedToInternet || isExplorationLockedForEditing() || countWarnings()">

          Publish

            <loading-dots [hidden]="!loadingDotsAreShown"></loading-dots>

            Publishing
            <loading-dots [hidden]="!loadingDotsAreShown"></loading-dots>

      </button>

      <button id="tutorialSaveButton"
              class="btn btn-light oppia-save-draft-button e2e-test-save-changes"
              [ngClass]="{'btn-success': connectedToInternet && isExplorationSaveable() && !isLockedByAdmin()}"
              (click)="saveChanges()" [disabled]="!connectedToInternet || !isExplorationSaveable() || isLockedByAdmin()">

            Save Draft
            ({{ getChangeListLength() }})

            Publish Changes
            ({{ getChangeListLength() }})

            Saving

            Publishing

          <loading-dots [hidden]="!loadingDotsAreShown"></loading-dots>

      </button>

      <button [matMenuTriggerFor]="discardButton" type="button" class="btn btn-light oppia-discard-button e2e-test-save-discard-toggle dropdown-toggle"
              [disabled]="!connectedToInternet || !getChangeListLength()" aria-label="Discard Draft">
      </button>

      <mat-menu #discardButton="matMenu" [ngStyle]="{ width: getChangeListLength() && !isPrivate() ? '150px' : '120px' }">
        <button mat-menu-item title="Discard all pending changes">Discard Draft</button>
      </mat-menu>


text:
"""Exceptions for generated client libraries."""

class Error(Exception):
    """Base class for all exceptions."""

class CommunicationError(Error):
    """Any communication error talking to an API server."""

class HttpError(CommunicationError):
    """Error making a request. Soon to be HttpError.

    :type response: dict
    :param response: headers from the response which returned the error

    :type content: bytes
    :param content: payload of the response which returned the error

    :type url: str
    :param url: URL of the response which returned the error
    """
    def __init__(self, response, content, url):
        super(HttpError, self).__init__()
        self.response = response
        self.content = content
        self.url = url

    def __str__(self):
        content = self.content.decode('ascii', 'replace')
        return 'HttpError accessing <%s>: response: <%s>, content <%s>' % (
            self.url, self.response, content)

    @property
    def status_code(self):
        """Status code for the response.

        :rtype: int
        :returns: the code
        """
        return int(self.response['status'])

    @classmethod
    def from_response(cls, http_response):
        """Factory:  construct an exception from a response.

        :type http_response: :class:`~.http_wrapper.Response`
        :param http_response: the response which returned the error

        :rtype: :class:`HttpError`
        :returns: The error created from the response.
        """
        return cls(http_response.info, http_response.content,
                   http_response.request_url)

class TransferError(CommunicationError):
    """Errors related to transfers."""

class TransferRetryError(TransferError):
    """Retryable errors related to transfers."""

class TransferInvalidError(TransferError):
    """The given transfer is invalid."""

class RequestError(CommunicationError):
    """The request was not successful."""

class RetryAfterError(HttpError):
    """The response contained a retry-after header.

    :type response: dict
    :param response: headers from the response which returned the error.

    :type content: bytes
    :param content: payload of the response which returned the error.

    :type url: str
    :param url: URL of the response which returned the error.

    :type retry_after: int
    :param retry_after: seconds to wait before retrying.
    """
    def __init__(self, response, content, url, retry_after):
        super(RetryAfterError, self).__init__(response, content, url)
        self.retry_after = int(retry_after)

    @classmethod
    def from_response(cls, http_response):
        """Factory:  construct an exception from a response.

        :type http_response: :class:`~.http_wrapper.Response`
        :param http_response: the response which returned the error.

        :rtype: :class:`RetryAfterError`
        :returns: The error created from the response.
        """
        return cls(http_response.info, http_response.content,
                   http_response.request_url, http_response.retry_after)

class BadStatusCodeError(HttpError):
    """The request completed but returned a bad status code."""


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage;
exports.LoneAnonymousOperation = LoneAnonymousOperation;

var _GraphQLError = require("../../error/GraphQLError");

var _kinds = require("../../language/kinds");

function anonOperationNotAloneMessage() {
  return 'This anonymous operation must be the only defined operation.';
}
/**
 * Lone anonymous operation
 *
 * A GraphQL document is only valid if when it contains an anonymous operation
 * (the query short-hand) that it contains only that one operation definition.
 */

function LoneAnonymousOperation(context) {
  var operationCount = 0;
  return {
    Document: function Document(node) {
      operationCount = node.definitions.filter(function (definition) {
        return definition.kind === _kinds.Kind.OPERATION_DEFINITION;
      }).length;
    },
    OperationDefinition: function OperationDefinition(node) {
      if (!node.name && operationCount > 1) {
        context.reportError(new _GraphQLError.GraphQLError(anonOperationNotAloneMessage(), node));
      }
    }
  };
}


text:
using System.Linq;
using System.Text;
using Akka.IO;
using FsCheck;
using Xunit;

namespace Akka.Tests.Util
{

    /// <summary>
    /// TODO: Should we use the FsCheck.XUnit integration when they upgrade to xUnit 2
    /// </summary>
    public class ByteStringSpec
    {
        class Generators
        {

            // TODO: Align with JVM Akka Generator
            public static Arbitrary<ByteString> ByteStrings()
            {
                return Arb.From(Arb.Generate<byte[]>().Select(ByteString.Create));
            }
        }

        public ByteStringSpec()
        {
            Arb.Register<Generators>();
        }

        [Fact]
        public void A_ByteString_must_have_correct_size_when_concatenating()
        {
            Prop.ForAll((ByteString a, ByteString b) => (a + b).Count == a.Count + b.Count)
                .QuickCheckThrowOnFailure();
        }

        [Fact]
        public void A_ByteString_must_have_correct_size_when_dropping()
        {
            Prop.ForAll((ByteString a, ByteString b) => (a + b).Drop(b.Count).Count == a.Count)
                .QuickCheckThrowOnFailure();
        }

        [Fact]
        public void A_ByteString_must_be_sequential_when_taking()
        {
            Prop.ForAll((ByteString a, ByteString b) => (a + b).Take(a.Count).SequenceEqual(a))
                .QuickCheckThrowOnFailure();
        }
        [Fact]
        public void A_ByteString_must_be_sequential_when_dropping()
        {
            Prop.ForAll((ByteString a, ByteString b) => (a + b).Drop(a.Count).SequenceEqual(b))
                .QuickCheckThrowOnFailure();
        }

        [Fact]
        public void A_ByteString_must_be_equal_to_the_original_when_compacting()
        {
            Prop.ForAll((ByteString xs) =>
            {
                var ys = xs.Compact();
                return xs.SequenceEqual(ys) && ys.IsCompact();
            }).QuickCheckThrowOnFailure();
        }
        [Fact]
        public void A_ByteString_must_be_equal_to_the_original_when_recombining()
        {
            Prop.ForAll((ByteString xs, int from, int until) =>
            {
                var tmp1 = xs.SplitAt(until);
                var tmp2 = tmp1.Item1.SplitAt(until);
                return (tmp2.Item1 + tmp2.Item2 + tmp1.Item2).SequenceEqual(xs);
            }).QuickCheckThrowOnFailure();
        }

        [Fact]
        public void A_ByteString_must_behave_as_expected_when_created_from_and_decoding_to_String()
        {
            Prop.ForAll((string s) => ByteString.FromString(s, Encoding.UTF8).DecodeString(Encoding.UTF8) == (s ?? "")) // TODO: What should we do with null string?
                .QuickCheckThrowOnFailure();
        }
        [Fact]
        public void A_ByteString_must_behave_as_expected_when_compacting()
        {
            Prop.ForAll((ByteString a) =>
            {
                var wasCompact = a.IsCompact();
                var b = a.Compact();
                return ((!wasCompact) || (b == a)) &&
                       b.SequenceEqual(a) &&
                       b.IsCompact() &&
                       b.Compact() == b;
            }).QuickCheckThrowOnFailure();
        }
    }
}


text:
"""Miscellaneous utility classes and functions."""

import ctypes
import fnmatch
import importlib
import inspect
import numpy as np
import os
import shutil
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import uuid

from distutils.util import strtobool
from typing import Any, List, Tuple, Union

# Util classes
# ------------------------------------------------------------------------------------------

class EasyDict(dict):
    """Convenience class that behaves like a dict but allows access with the attribute syntax."""

    def __getattr__(self, name: str) -> Any:
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name: str, value: Any) -> None:
        self[name] = value

    def __delattr__(self, name: str) -> None:
        del self[name]

class Logger(object):
    """Redirect stderr to stdout, optionally print stdout to a file, and optionally force flushing on both stdout and the file."""

    def __init__(self, file_name: str = None, file_mode: str = "w", should_flush: bool = True):
        self.file = None

        if file_name is not None:
            self.file = open(file_name, file_mode)

        self.should_flush = should_flush
        self.stdout = sys.stdout
        self.stderr = sys.stderr

        sys.stdout = self
        sys.stderr = self

    def __enter__(self) -> "Logger":
        return self

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        self.close()

    def write(self, text: str) -> None:
        """Write text to stdout (and a file) and optionally flush."""
        if len(text) == 0: # workaround for a bug in VSCode debugger: sys.stdout.write(''); sys.stdout.flush() => crash
            return

        if self.file is not None:
            self.file.write(text)

        self.stdout.write(text)

        if self.should_flush:
            self.flush()

    def flush(self) -> None:
        """Flush written text to both stdout and a file, if open."""
        if self.file is not None:
            self.file.flush()

        self.stdout.flush()

    def close(self) -> None:
        """Flush, close possible files, and remove stdout/stderr mirroring."""
        self.flush()

        # if using multiple loggers, prevent closing in wrong order
        if sys.stdout is self:
            sys.stdout = self.stdout
        if sys.stderr is self:
            sys.stderr = self.stderr

        if self.file is not None:
            self.file.close()

# Small util functions
# ------------------------------------------------------------------------------------------

def format_time(seconds: Union[int, float]) -> str:
    """Convert the seconds to human readable string with days, hours, minutes and seconds."""
    s = int(np.rint(seconds))

    if s < 60:
        return "{0}s".format(s)
    elif s < 60 * 60:
        return "{0}m {1:02}s".format(s // 60, s % 60)
    elif s < 24 * 60 * 60:
        return "{0}h {1:02}m {2:02}s".format(s // (60 * 60), (s // 60) % 60, s % 60)
    else:
        return "{0}d {1:02}h {2:02}m".format(s // (24 * 60 * 60), (s // (60 * 60)) % 24, (s // 60) % 60)

def ask_yes_no(question: str) -> bool:
    """Ask the user the question until the user inputs a valid answer."""
    while True:
        try:
            print("{0} [y/n]".format(question))
            return strtobool(input().lower())
        except ValueError:
            pass

def tuple_product(t: Tuple) -> Any:
    """Calculate the product of the tuple elements."""
    result = 1

    for v in t:
        result *= v

    return result

_str_to_ctype = {
    "uint8": ctypes.c_ubyte,
    "uint16": ctypes.c_uint16,
    "uint32": ctypes.c_uint32,
    "uint64": ctypes.c_uint64,
    "int8": ctypes.c_byte,
    "int16": ctypes.c_int16,
    "int32": ctypes.c_int32,
    "int64": ctypes.c_int64,
    "float32": ctypes.c_float,
    "float64": ctypes.c_double
}

def get_dtype_and_ctype(type_obj: Any) -> Tuple[np.dtype, Any]:
    """Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes."""
    type_str = None

    if isinstance(type_obj, str):
        type_str = type_obj
    elif hasattr(type_obj, "__name__"):
        type_str = type_obj.__name__
    elif hasattr(type_obj, "name"):
        type_str = type_obj.name
    else:
        raise RuntimeError("Cannot infer type name from input")

    assert type_str in _str_to_ctype.keys()

    my_dtype = np.dtype(type_str)
    my_ctype = _str_to_ctype[type_str]

    assert my_dtype.itemsize == ctypes.sizeof(my_ctype)

    return my_dtype, my_ctype

def is_pickleable(obj: Any) -> bool:
    try:
        with io.BytesIO() as stream:
            pickle.dump(obj, stream)
        return True
    except:
        return False

# Functionality to import modules/objects by name, and call functions by name
# ------------------------------------------------------------------------------------------

def get_module_from_obj_name(obj_name: str) -> Tuple[types.ModuleType, str]:
    """Searches for the underlying module behind the name to some python object.
    Returns the module and the object name (original name with module part removed)."""

    # allow convenience shorthands, substitute them by full names
    obj_name = re.sub("^np.", "numpy.", obj_name)
    obj_name = re.sub("^tf.", "tensorflow.", obj_name)

    # list alternatives for (module_name, local_obj_name)
    parts = obj_name.split(".")
    name_pairs = [(".".join(parts[:i]), ".".join(parts[i:])) for i in range(len(parts), 0, -1)]

    # try each alternative in turn
    for module_name, local_obj_name in name_pairs:
        try:
            module = importlib.import_module(module_name) # may raise ImportError
            get_obj_from_module(module, local_obj_name) # may raise AttributeError
            return module, local_obj_name
        except:
            pass

    # maybe some of the modules themselves contain errors?
    for module_name, _local_obj_name in name_pairs:
        try:
            importlib.import_module(module_name) # may raise ImportError
        except ImportError:
            if not str(sys.exc_info()[1]).startswith("No module named '" + module_name + "'"):
                raise

    # maybe the requested attribute is missing?
    for module_name, local_obj_name in name_pairs:
        try:
            module = importlib.import_module(module_name) # may raise ImportError
            get_obj_from_module(module, local_obj_name) # may raise AttributeError
        except ImportError:
            pass

    # we are out of luck, but we have no idea why
    raise ImportError(obj_name)

def get_obj_from_module(module: types.ModuleType, obj_name: str) -> Any:
    """Traverses the object name and returns the last (rightmost) python object."""
    if obj_name == '':
        return module
    obj = module
    for part in obj_name.split("."):
        obj = getattr(obj, part)
    return obj

def get_obj_by_name(name: str) -> Any:
    """Finds the python object with the given name."""
    module, obj_name = get_module_from_obj_name(name)
    return get_obj_from_module(module, obj_name)

def call_func_by_name(*args, func_name: str = None, **kwargs) -> Any:
    """Finds the python object with the given name and calls it as a function."""
    assert func_name is not None
    func_obj = get_obj_by_name(func_name)
    assert callable(func_obj)
    return func_obj(*args, **kwargs)

def get_module_dir_by_obj_name(obj_name: str) -> str:
    """Get the directory path of the module containing the given object name."""
    module, _ = get_module_from_obj_name(obj_name)
    return os.path.dirname(inspect.getfile(module))

def is_top_level_function(obj: Any) -> bool:
    """Determine whether the given object is a top-level function, i.e., defined at module scope using 'def'."""
    return callable(obj) and obj.__name__ in sys.modules[obj.__module__].__dict__

def get_top_level_function_name(obj: Any) -> str:
    """Return the fully-qualified name of a top-level function."""
    assert is_top_level_function(obj)
    return obj.__module__ + "." + obj.__name__

# File system helpers
# ------------------------------------------------------------------------------------------

def list_dir_recursively_with_ignore(dir_path: str, ignores: List[str] = None, add_base_to_relative: bool = False) -> List[Tuple[str, str]]:
    """List all files recursively in a given directory while ignoring given file and directory names.
    Returns list of tuples containing both absolute and relative paths."""
    assert os.path.isdir(dir_path)
    base_name = os.path.basename(os.path.normpath(dir_path))

    if ignores is None:
        ignores = []

    result = []

    for root, dirs, files in os.walk(dir_path, topdown=True):
        for ignore_ in ignores:
            dirs_to_remove = [d for d in dirs if fnmatch.fnmatch(d, ignore_)]

            # dirs need to be edited in-place
            for d in dirs_to_remove:
                dirs.remove(d)

            files = [f for f in files if not fnmatch.fnmatch(f, ignore_)]

        absolute_paths = [os.path.join(root, f) for f in files]
        relative_paths = [os.path.relpath(p, dir_path) for p in absolute_paths]

        if add_base_to_relative:
            relative_paths = [os.path.join(base_name, p) for p in relative_paths]

        assert len(absolute_paths) == len(relative_paths)
        result += zip(absolute_paths, relative_paths)

    return result

def copy_files_and_create_dirs(files: List[Tuple[str, str]]) -> None:
    """Takes in a list of tuples of (src, dst) paths and copies files.
    Will create all necessary directories."""
    for file in files:
        target_dir_name = os.path.dirname(file[1])

        # will create all intermediate-level directories
        if not os.path.exists(target_dir_name):
            os.makedirs(target_dir_name)

        shutil.copyfile(file[0], file[1])

# URL helpers
# ------------------------------------------------------------------------------------------

def is_url(obj: Any) -> bool:
    """Determine whether the given object is a valid URL string."""
    if not isinstance(obj, str) or not "://" in obj:
        return False
    try:
        res = requests.compat.urlparse(obj)
        if not res.scheme or not res.netloc or not "." in res.netloc:
            return False
        res = requests.compat.urlparse(requests.compat.urljoin(obj, "/"))
        if not res.scheme or not res.netloc or not "." in res.netloc:
            return False
    except:
        return False
    return True

def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True) -> Any:
    """Download the given URL and return a binary-mode file object to access the data."""
    assert is_url(url)
    assert num_attempts >= 1

    # Lookup from cache.
    url_md5 = hashlib.md5(url.encode("utf-8")).hexdigest()
    if cache_dir is not None:
        cache_files = glob.glob(os.path.join(cache_dir, url_md5 + "_*"))
        if len(cache_files) == 1:
            return open(cache_files[0], "rb")

    # Download.
    url_name = None
    url_data = None
    with requests.Session() as session:
        if verbose:
            print("Downloading %s ..." % url, end="", flush=True)
        for attempts_left in reversed(range(num_attempts)):
            try:
                with session.get(url) as res:
                    res.raise_for_status()
                    if len(res.content) == 0:
                        raise IOError("No data received")

                    if len(res.content) < 8192:
                        content_str = res.content.decode("utf-8")
                        if "download_warning" in res.headers.get("Set-Cookie", ""):
                            links = [html.unescape(link) for link in content_str.split('"') if "export=download" in link]
                            if len(links) == 1:
                                url = requests.compat.urljoin(url, links[0])
                                raise IOError("Google Drive virus checker nag")
                        if "Google Drive - Quota exceeded" in content_str:
                            raise IOError("Google Drive quota exceeded")

                    match = re.search(r'filename="([^"]*)"', res.headers.get("Content-Disposition", ""))
                    url_name = match[1] if match else url
                    url_data = res.content
                    if verbose:
                        print(" done")
                    break
            except:
                if not attempts_left:
                    if verbose:
                        print(" failed")
                    raise
                if verbose:
                    print(".", end="", flush=True)

    # Save to cache.
    if cache_dir is not None:
        safe_name = re.sub(r"[^0-9a-zA-Z-._]", "_", url_name)
        cache_file = os.path.join(cache_dir, url_md5 + "_" + safe_name)
        temp_file = os.path.join(cache_dir, "tmp_" + uuid.uuid4().hex + "_" + url_md5 + "_" + safe_name)
        os.makedirs(cache_dir, exist_ok=True)
        with open(temp_file, "wb") as f:
            f.write(url_data)
        os.replace(temp_file, cache_file) # atomic

    # Return data as file object.
    return io.BytesIO(url_data)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using PlayFab.Json.Utilities;

namespace PlayFab.Json.Serialization
{
  internal static class CachedAttributeGetter<T> where T : System.Attribute
  {
    private static readonly ThreadSafeStore<ICustomAttributeProvider, T> TypeAttributeCache = new ThreadSafeStore<ICustomAttributeProvider, T>(JsonTypeReflector.GetAttribute<T>);

    public static T GetAttribute(ICustomAttributeProvider type)
    {
      return TypeAttributeCache.Get(type);
    }
  }
}
#endif


text:
namespace Entitas {
    public partial class Entity {
        public FindTargetComponent findTarget { get { return (FindTargetComponent)GetComponent(ComponentIds.FindTarget); } }

        public bool hasFindTarget { get { return HasComponent(ComponentIds.FindTarget); } }

        public Entity AddFindTarget(int newTargetCollisionType) {
            var component = CreateComponent<FindTargetComponent>(ComponentIds.FindTarget);
            component.targetCollisionType = newTargetCollisionType;
            return AddComponent(ComponentIds.FindTarget, component);
        }

        public Entity ReplaceFindTarget(int newTargetCollisionType) {
            var component = CreateComponent<FindTargetComponent>(ComponentIds.FindTarget);
            component.targetCollisionType = newTargetCollisionType;
            ReplaceComponent(ComponentIds.FindTarget, component);
            return this;
        }

        public Entity RemoveFindTarget() {
            return RemoveComponent(ComponentIds.FindTarget);
        }
    }

    public partial class Matcher {
        static IMatcher _matcherFindTarget;

        public static IMatcher FindTarget {
            get {
                if (_matcherFindTarget == null) {
                    var matcher = (Matcher)Matcher.AllOf(ComponentIds.FindTarget);
                    matcher.componentNames = ComponentIds.componentNames;
                    _matcherFindTarget = matcher;
                }

                return _matcherFindTarget;
            }
        }
    }
}


text:
 * bin/check-deployment-status.rb

## Usage

## Installation

[Installation and Setup](http://sensu-plugins.io/docs/installation_instructions.html)

## Notes


text:
require 'net/http'
require 'uri'
require 'cgi'
require 'digest/md5'
require 'base64'
require 'fileutils'
require 'tmpdir'

require 'selenium/client/errors'
require 'selenium/client/protocol'
require 'selenium/client/legacy_driver'
require 'selenium/client/javascript_expression_builder'
require 'selenium/client/javascript_frameworks/prototype'
require 'selenium/client/javascript_frameworks/jquery'
require 'selenium/client/extensions'
require 'selenium/client/idiomatic'
require 'selenium/client/base'
require 'selenium/client/driver'
require 'selenium/client/selenium_helper'
require 'selenium/server'

module Selenium
  DEPRECATED_CONSTANTS = {
    :SeleniumDriver => Selenium::Client::Driver,
    :CommandError   => Selenium::Client::CommandError
  }

  def self.const_missing(name)
    if replacement = DEPRECATED_CONSTANTS[name.to_sym]
      warn "the Selenium::#{name} constant has been deprecated, please use #{replacement} instead"
      replacement
    else
      super
    end
  end

  autoload :Rake, 'selenium/rake/server_task'
end # Selenium


text:
<?php
namespace M6Web\Bundle\FirewallBundle\Firewall;

use Symfony\Component\HttpFoundation\Request;

/**
 * Class FirewallInterface
 *
 * @package M6Web\Bundle\FirewallBundle\Firewall
 */
interface FirewallInterface
{
    /**
     * Set the firewall provider
     *
     * @param Provider $provider Firewall manager
     *
     * @return $this
     */
    public function setProvider(Provider $provider);

    /**
     * Set the contextual request
     *
     * @param Request $request Symfony request
     *
     * @return $this
     */
    public function setRequest(Request $request);

    /**
     * Handle the current request
     *
     * @param callable $callBack Result handler
     *
     * @return boolean
     */
    public function handle(callable $callBack = null);

    /**
     * Get Client IP
     *
     * @return string
     */
    public function getIpAddress();

    /**
     * Add a list
     *
     * @param array        $list     List
     * @param string       $listName Identifier for the list
     * @param boolean|null $state    Whether the list is trusted or not
     *
     * @return $this
     */
    public function addList(array $list, $listName, $state);

    /**
     * Set default returned value
     *
     * @param boolean $state Default returned value
     *
     * @return $this
     */
    public function setDefaultState($state);

    /**
     * Set the error code
     *
     * @param integer $code Error code
     *
     * @return $this
     */
    public function setErrorCode($code);

    /**
     * Set the error message
     *
     * @param string $message Error message
     *
     * @return $this
     */
    public function setErrorMessage($message);

    /**
     * Activate/Disable the exception throw
     *
     * @param boolean $throw Throw or not an exception in error case
     *
     * @return $this
     */
    public function setThrowError($throw);
}


text:
package com.google.cloud.vmmigration.v1.samples;

// [START vmmigration_v1_generated_vmmigrationclient_cancelclonejob_lro_async]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vmmigration.v1.CancelCloneJobRequest;
import com.google.cloud.vmmigration.v1.CancelCloneJobResponse;
import com.google.cloud.vmmigration.v1.CloneJobName;
import com.google.cloud.vmmigration.v1.OperationMetadata;
import com.google.cloud.vmmigration.v1.VmMigrationClient;

public class AsyncCancelCloneJobLRO {

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

  public static void asyncCancelCloneJobLRO() 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 (VmMigrationClient vmMigrationClient = VmMigrationClient.create()) {
      CancelCloneJobRequest request =
          CancelCloneJobRequest.newBuilder()
              .setName(
                  CloneJobName.of(
                          "[PROJECT]", "[LOCATION]", "[SOURCE]", "[MIGRATING_VM]", "[CLONE_JOB]")
                      .toString())
              .build();
      OperationFuture<CancelCloneJobResponse, OperationMetadata> future =
          vmMigrationClient.cancelCloneJobOperationCallable().futureCall(request);
      // Do something.
      CancelCloneJobResponse response = future.get();
    }
  }
}
// [END vmmigration_v1_generated_vmmigrationclient_cancelclonejob_lro_async]


text:
(function() {
  "use strict";

  /*
    This is a demo controller and is not related to
    autocomplete directive.
  */
  angular.module("app.controllers.demo", [])
    .controller("Demo", DemoController);

  var STATIC_DEMO_DATA = [
    "berlin", "frankfurt", "amsterdam", "toronto",
    "ankara", "antalya", "vancouver", "belgrade",
    "stockholm", "london", "marmaris", "istanbul"
  ];

  function DemoController($http) {
    var vm = this;

    vm.ac1 = "";
    vm.ac2 = "Antalya";
    vm.staticSourceDemo = staticSourceDemo;
    vm.dynamicSourceDemo = dynamicSourceDemo;

    function staticSourceDemo(keyword) {
      var tbReturned = [];
      STATIC_DEMO_DATA.forEach(function(data) {
        if (data.indexOf(keyword) > -1) {
          tbReturned.push(data);
        }
      });
      // You can return array of strings right away!
      return tbReturned;
    }

    function dynamicSourceDemo(keyword) {
      /* You can return a promise, that'll resolve to array of strings
        eventually. Since we can do anything async, you can go any data
        source here.
      */
      return $http.jsonp("http://gd.geobytes.com/AutoCompleteCity", {
        params: {
          callback: "JSON_CALLBACK",
          q: keyword
        }
      }).then(function(data) {
        var tbReturned = [];
        data.data.forEach(function(aCity) {
          if (aCity.length > 0 && tbReturned.indexOf(aCity) < 0) {
            tbReturned.push(aCity);
          }
        });
        return tbReturned;
      });
    }
  }
})();


text:
@interface CDBCloudDocuments ()

@property (assign, nonatomic, readwrite) BOOL ubiquitosActive;
@property (assign, nonatomic, readonly) BOOL ubiquityContainerAccessible;

@property (copy, nonatomic) NSString * cloudPathComponent;
@property (copy, nonatomic) NSString * requestedFilesExtension;

@property (strong, nonatomic) CDBDocument * documentsDirectoryWatchdog;

@property (strong, nonatomic) NSMutableSet <NSURL *> * uniqueCloudDocumentURLs;

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

@property (strong, nonatomic) NSMetadataQuery * metadataQuery;
@property (strong, nonatomic, readonly) NSFileManager * fileManager;
@property (nonatomic, strong) NSURL * ubiquityContainerURL;

@property (strong, nonatomic) dispatch_queue_t serialQueue;

@end

@implementation CDBCloudDocuments
@synthesize localDocumentsURL = _localDocumentsURL;

#pragma mark - property -

- (NSURL *)presentedItemURL {
    return nil;
}

#pragma mark Getter

- (__strong dispatch_queue_t)serialQueue {
    if (_serialQueue == nil) {
        _serialQueue =  dispatch_queue_create("CDB.iCloudReady.CloudDocuments.GCD.queue.serial", DISPATCH_QUEUE_SERIAL);
    }
    return _serialQueue;
}

- (NSArray<NSURL *> *)cloudDocumentURLs {
    NSArray * result = self.uniqueCloudDocumentURLs.allObjects;
    return result;
}

- (NSURL *)currentDocumentsURL {
    NSURL * result = nil;
    if (self.ubiquitosActive) {
        result = self.ubiquityDocumentsURL;
    } else {
        result = self.localDocumentsURL;
    }
    return result;
}

- (BOOL)ubiquityContainerAccessible {
    BOOL result = self.ubiquityContainerURL != nil;
    return result;
}

- (NSURL *)ubiquityDocumentsURL {
    NSURL * result =
        [self.ubiquityContainerURL URLByAppendingPathComponent:self.cloudPathComponent
                                                   isDirectory:YES];
    return result;
}

- (NSFileManager *)fileManager {
    NSFileManager * result = [NSFileManager new];
    return result;
}

- (NSPredicate *)requestedFilesMetadataPredicate {
    NSString * format = [NSString stringWithFormat:@"%%K.pathExtension LIKE '%@'", self.requestedFilesExtension];
    NSPredicate * result = [NSPredicate predicateWithFormat:format, NSMetadataItemFSNameKey];
    return result;
}

- (NSError *)iCloudNotAcceessableError {
    NSString * errorDescription = @"iCloud not available";
    NSDictionary * userInfo = @{NSLocalizedDescriptionKey: errorDescription};
    NSError * result = [NSError errorWithDomain:NSStringFromClass([self class])
                                           code:0
                                       userInfo:userInfo];
    return result;
}

- (NSError *)fileNameCouldNotBeEmptyError {
    NSString * errorDescription = @"Could not process empty file name";
    NSDictionary * userInfo = @{NSLocalizedDescriptionKey: errorDescription};
    NSError * result = [NSError errorWithDomain:NSStringFromClass([self class])
                                           code:1
                                       userInfo:userInfo];
    return result;
}

- (NSError *)fileNameCouldNotBeDirectoryError {
    NSString * errorDescription = @"Could not process file name that represents directory";
    NSDictionary * userInfo = @{NSLocalizedDescriptionKey: errorDescription};
    NSError * result = [NSError errorWithDomain:NSStringFromClass([self class])
                                           code:1
                                       userInfo:userInfo];
    return result;
}

- (NSError *)directoryUnacceptableURLErrorUsingURL:(NSURL *)URL {
    NSString * errorDescription = [NSString stringWithFormat:@"Could not handle nil or empty URL: %@", URL];
    NSDictionary * userInfo = @{NSLocalizedDescriptionKey: errorDescription};
    NSError * result = [NSError errorWithDomain:NSStringFromClass([self class])
                                           code:2
                                       userInfo:userInfo];
    return result;
}

#pragma mark Setter

- (void)setLocalDocumentsURL:(NSURL *)localDocumentsURL {
    if ([_localDocumentsURL.path isEqualToString:localDocumentsURL.path]) {
        return;
    }

    [self synchronousEnsureThatDirectoryPresentsAtURL:localDocumentsURL
                                            comletion:^(NSError *error) {
        if (error != nil) {
            NSLog(@"[CDBCloudDocuments] could not resolve local documents URL %@\
                  \n failed with error: %@",
                  localDocumentsURL, error);
        } else {
            _localDocumentsURL = localDocumentsURL;
        }
    }];
}

#pragma mark Lazy loading

- (NSMutableSet<NSURL *> *)uniqueCloudDocumentURLs {
    if (_uniqueCloudDocumentURLs != nil) {
        return _uniqueCloudDocumentURLs;
    }

    _uniqueCloudDocumentURLs = [NSMutableSet set];
    return _uniqueCloudDocumentURLs;
}

- (NSURL *)localDocumentsURL {
    if (_localDocumentsURL == nil) {
        NSArray * URLs = [self.fileManager URLsForDirectory:NSDocumentDirectory
                                                  inDomains:NSUserDomainMask];
        _localDocumentsURL = [URLs lastObject];
    }
    return _localDocumentsURL;
}

- (NSMetadataQuery *)metadataQuery {
    if (_metadataQuery == nil) {
        _metadataQuery = [NSMetadataQuery new];
    }
    return _metadataQuery;
}

#pragma mark - life cycle -

- (void)initiateUsingCloudPathComponent:(NSString * _Nullable)pathComponent {
    if (pathComponent.length == 0) {
        self.cloudPathComponent = CDBiCloudDocumentsDirectoryPathComponent;
    } else {
        self.cloudPathComponent = pathComponent;
    }

    self.requestedFilesExtension = @"*";
}

#pragma mark - Notifications -

- (void)handleMetadataQueryDidUpdateNotification:(NSNotification *)notification {
    [self updateFilesWithCompletion:^{}];
    [self logMetadataQueryNotification:notification];
}

- (void)handleMetadataQueryDidFinishGatheringNotification:(NSNotification *)notification {
    [self updateFilesWithCompletion:^{}];
    [self logMetadataQueryNotification:notification];
}

#pragma mark - Protocols -

#pragma mark CDBDocumentDelegate

- (void)didAutoresolveConflictInCDBDocument:(CDBDocument *)document {
    [self notifyDelegateThatDocumentsDidAutoresolveConflictInCDBDocument:document];
}

- (void)CDBDocumentDirectory:(CDBDocument *)document
       didChangeSubitemAtURL:(NSURL *)URL {
    if (document != self.documentsDirectoryWatchdog) {
        return;
    }

    // correct path to foundation private on device
    NSURL * correctedURL = URL;
    NSString * path = URL.path;
    if (self.ubiquityContainerURL.path.length > 10
        && [[self.ubiquityContainerURL.path substringToIndex:9] isEqualToString:@"/private/"]
        && path.length > 6
        && [[path substringToIndex:5] isEqualToString:@"/var/"]) {
        correctedURL = [NSURL fileURLWithPath:[@"/private" stringByAppendingString:path]];
    }

    BOOL removed = [self.fileManager isUbiquitousItemAtURL:correctedURL] == NO;
    if (removed) {
        [self.uniqueCloudDocumentURLs removeObject:correctedURL];
        [self notifyDelegateThatDocumentsDidRemoveUbiquitosDocumentAtURL:correctedURL];

        return;
    }
    [self.uniqueCloudDocumentURLs addObject:correctedURL];
    [self notifyDelegateThatDocumentsDidChangeUbiquitosDocumentAtURL:correctedURL];
}

#pragma mark - Public -

#pragma mark Handle state changes

- (void)updateForUbiquityActive:(BOOL)active
      usingUbiquityContainerURL:(NSURL *)containerURL {

    BOOL shouldPostChangeNotificaton = [containerURL isEqual:self.ubiquityContainerURL] == NO
                                       && containerURL != nil;

    self.ubiquityContainerURL = containerURL;

    if (active
        && self.ubiquitosActive == NO) {
        [self ensureThatUbiquitousDocumentsDirectoryPresents];
        [self startSynchronizationWithCompletion:nil];
        self.ubiquitosActive = YES;
        shouldPostChangeNotificaton = YES;
    } else if (active == NO
               && self.ubiquitosActive == YES) {
        [self dissmissSynchronization];
        self.ubiquitosActive = NO;
        shouldPostChangeNotificaton = YES;
    }

    if (shouldPostChangeNotificaton) {
        DLogCDB(@"update for ubiquity available %@\
              \r with container %@",
              NSStringFromBool(active),
              self.ubiquityContainerURL);
        [self notifyDelegateThatDocumentsDidChangeState];
    }
}

- (NSArray *)URLsForItemsInsideUbiquitosDirectory:(NSURL *)directory {
    NSMutableArray * result = [NSMutableArray array];
    for (NSURL * URL in self.cloudDocumentURLs) {
        NSString * relativeURLString = [self relativeURLStringFromURL:URL
                                                         usingBaseURL:directory];
        if (relativeURLString == nil) {
            continue;
        }

        [result addObject:URL];
    }
    return [result copy];
}

- (NSString *)documentAliasUsingItURL:(NSURL *)URL {
    NSString * result = [self relativeURLStringFromURL:URL
                                          usingBaseURL:self.currentDocumentsURL];
    return result;
}

- (void)addDelegate:(id<CDBCloudDocumentsDelegate> _Nonnull)delegate {
    self.delegate = delegate;
}

- (void)removeDelegate:(id<CDBCloudDocumentsDelegate> _Nonnull)delegate {
    if (self.delegate != delegate) {
        return;
    }
    self.delegate = nil;
}

- (void)makeDocument:(CDBDocument * _Nonnull)document
          ubiquitous:(BOOL)ubiquitous
          completion:(CDBErrorCompletion _Nonnull)completion {
    if ([document isUbiquitous] == ubiquitous) {
        completion(nil);
        return;
    }

    void (^ handler)(BOOL success) = ^(BOOL success) {
        if (success == NO) {
            completion(document.iCloudDocumentNotOperableError);
            return;
        }

        [self makeClosedDocument:document
                      ubiquitous:ubiquitous
                      completion:completion];
    };

    if (document.isClosed) {
        handler(YES);
        return;
    }

    [document closeWithCompletionHandler:^(BOOL success) {
        handler(success);
    }];
}

- (CDBDocument *)localDocumentWithFileName:(NSString *)fileName
                                     error:(NSError *_Nullable __autoreleasing * _Nullable)error {
    if (fileName.length == 0) {
        *error = [self fileNameCouldNotBeEmptyError];
        return nil;
    }

    NSURL * fileURL = [self localDocumentFileURLUsingFileName:fileName];

    CDBDocument * result = [self documentWithAvailableFileURL:fileURL
                                                              error:error];
    return result;
}

- (CDBDocument *)ubiquitousDocumentWithFileName:(NSString *)fileName
                                                error:(NSError *_Nullable __autoreleasing * _Nullable)error; {
    if (fileName.length == 0) {
        *error = [self fileNameCouldNotBeEmptyError];
        return nil;
    }

    if (self.ubiquityContainerAccessible == NO) {
        *error = [self iCloudNotAcceessableError];
        return nil;
    }

    NSURL * fileURL = [self ubiquityDocumentFileURLUsingFileName:fileName];

    CDBDocument * result = [self documentWithAvailableFileURL:fileURL
                                                              error:error];
    return result;
}

- (void)createClosedLocalDocumentUsingFileName:(NSString * _Nonnull)fileName
                               documentContent:(NSData * _Nullable)content
                                    completion:(CDBiCloudDocumentCompletion _Nonnull)completion {
    if (fileName.length == 0) {
        completion(nil, [self fileNameCouldNotBeEmptyError]);
        return;
    }

    NSURL * fileURL = [self localDocumentFileURLUsingFileName:fileName];

    CDBDocument * result = [[CDBDocument alloc] initWithFileURL:fileURL];
    result.contents = content;

    BOOL directory = NO;
    BOOL exist = [self.fileManager fileExistsAtPath:result.fileURL.path
                                        isDirectory:&directory];

    if (directory) {
        completion (nil, [self fileNameCouldNotBeDirectoryError]);
        return;
    }

    UIDocumentSaveOperation operation = exist ? UIDocumentSaveForOverwriting
                                              : UIDocumentSaveForCreating;

    dispatch_async(self.serialQueue, ^(void) {
        [result saveToURL:result.fileURL
         forSaveOperation:operation
        completionHandler:^(BOOL success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    completion(result, nil);
                    return;
                }
                completion(nil, [result iCloudDocumentNotOperableError]);
            });
        }];
    });
}

- (void)readContentOfDocumentAtURL:(NSURL *)URL
                        completion:(void(^)(NSData * data, NSError * error))completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __block NSData *data = nil;
        __block NSError *error = nil;
        NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
        [coordinator coordinateReadingItemAtURL:URL
                                        options:0
                                          error:&error
                                     byAccessor:^(NSURL *newURL) {
                                         data = [NSData dataWithContentsOfURL:newURL];
                                     }];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(data, error);
            }
        });
    });
}

- (void)deleteDocument:(CDBDocument * _Nonnull)document
            completion:(CDBErrorCompletion _Nonnull)completion {
    if (document.isUbiquitous
        && self.ubiquityContainerAccessible == NO) {
        completion([self iCloudNotAcceessableError]);
        return;
    }

    void (^ handler)(BOOL success) = ^(BOOL success) {
        if (success == NO) {
            completion(document.iCloudDocumentNotOperableError);
            return;
        }
        [self deleteClosedDocument:document
                        completion:completion];
    };

    if (document.isClosed) {
        handler(YES);
        return;
    }

    [document closeWithCompletionHandler:^(BOOL success) {
        handler(success);
    }];
}

- (void)copyDocument:(CDBDocument * _Nonnull)document
               toURL:(NSURL * _Nonnull)destinationURL
             replace:(BOOL)replace
          completion:(CDBErrorCompletion _Nonnull)completion {

    if (destinationURL.path.length == 0) {
        completion([self fileNameCouldNotBeEmptyError]);
        return;
    }

    if (document.isUbiquitous
        && self.ubiquityContainerAccessible == NO) {
        completion([self iCloudNotAcceessableError]);
        return;
    }

    void (^ handler)(BOOL success) = ^(BOOL success) {
        if (success == NO) {
            completion(document.iCloudDocumentNotOperableError);
            return;
        }
        [self copyClosedDocument:document
                           toURL:destinationURL
                         replace:replace
                      completion:completion];
    };

    if (document.isClosed) {
        handler(YES);
        return;
    }

    [document closeWithCompletionHandler:^(BOOL success) {
        handler(success);
    }];
}

- (void)moveDocument:(CDBDocument * _Nonnull)document
               toURL:(NSURL * _Nonnull)destinationURL
          completion:(CDBErrorCompletion _Nonnull)completion {

    if (destinationURL.path.length == 0) {
        completion([self fileNameCouldNotBeEmptyError]);
        return;
    }

    if (document.isUbiquitous
        && self.ubiquityContainerAccessible == NO) {
        completion([self iCloudNotAcceessableError]);
        return;
    }

    void (^ handler)(BOOL success) = ^(BOOL success) {
        if (success == NO) {
            completion(document.iCloudDocumentNotOperableError);
            return;
        }
        [self moveClosedDocument:document
                           toURL:destinationURL
                      completion:completion];
    };

    if (document.isClosed) {
        handler(YES);
        return;
    }

    [document closeWithCompletionHandler:^(BOOL success) {
        handler(success);
    }];
}

#pragma mark document contents handling

- (void)processDocumentWithName:(NSString *)name
                          atURL:(NSURL *)URL
                processingBlock:(void(^) (NSData * documentData, NSError * error))processingBlock {
    if (processingBlock == nil
       || name.length == 0) {
        return;
    }

    dispatch_async(self.serialQueue, ^(void) {
        NSError * error = nil;
        NSDate * incomingDate = nil;
        [URL getResourceValue:&incomingDate
                       forKey:NSURLContentModificationDateKey
                        error:&error];

        if (error != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                processingBlock(nil, error);
            });
            return;
        }

        NSDate * lastProcessedDate = [self lastProcessedDateForDocumentWithName:name];
        BOOL should = lastProcessedDate == nil
                      || [lastProcessedDate compare:incomingDate] == NSOrderedAscending;
        if (should == NO) {
            return;
        }

        [self saveProcessedDate:incomingDate
            forDocumentWithName:name];

        [self readContentOfDocumentAtURL:URL
                              completion:^(NSData *data, NSError *error) {
            if (error != nil) {
                // restore processed date because we failed to process
                [self saveProcessedDate:lastProcessedDate
                    forDocumentWithName:name];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                processingBlock(data, error);
            });
        }];
    });
}

- (void)processStringsDocumentWithName:(NSString *)name
                                 atURL:(NSURL *)URL
               separationCharactersSet:(NSCharacterSet *)separators
                     onlyUniqueStrings:(BOOL)unique
                processingStringsBlock:(void(^) (NSArray * documentStrings, NSError * error))stringsProcessingBlock {
    if (stringsProcessingBlock == nil) {
        return;
    }

    [self processDocumentWithName:name
                            atURL:URL
                  processingBlock:^(NSData * documentData, NSError *error) {
        if (error != nil) {
            stringsProcessingBlock(nil, error);
            return;
        }

        NSString * content = [[NSString alloc] initWithData:documentData
                                                  encoding:NSUTF8StringEncoding];
        if (content == nil) {
            // preserve windows users
            content = [[NSString alloc] initWithData:documentData
                                            encoding:NSASCIIStringEncoding];
        }

        if (content == nil) {
            stringsProcessingBlock(nil, [NSError errorWithDomain:NSStringFromClass([self class])
                                                            code:0
                                                        userInfo:@{NSLocalizedDescriptionKey: @"Failed to convert file data to strings"}]);
            return;
        }

        NSArray * stringsToProcess = [content componentsSeparatedByCharactersInSet:separators];
        if (unique) {
            NSSet * uniqueStrings = [NSSet setWithArray:stringsToProcess];
            stringsToProcess = uniqueStrings.allObjects;
        }

        stringsProcessingBlock(stringsToProcess, nil);
    }];

}

#pragma mark - Private -

#pragma mark Safe working with files

- (void)deleteClosedDocument:(CDBDocument * _Nonnull)document
                  completion:(CDBErrorCompletion _Nonnull)completion {
    dispatch_async(self.serialQueue, ^(void) {
        __block NSError * deletetionError = nil;

        void (^accessor)(NSURL *) = ^(NSURL * newURL1) {
            [self.fileManager removeItemAtURL:newURL1
                                        error:&deletetionError];
        };

        // we need this error because coordinator makes variable nil and we lose result of a file operation
        __block NSError * coordinationError = nil;
        NSFileCoordinator * fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:document];
        [fileCoordinator coordinateWritingItemAtURL:document.fileURL
                                            options:NSFileCoordinatorWritingForDeleting
                                              error:&coordinationError
                                         byAccessor:accessor];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(coordinationError != nil ? coordinationError
                                             : deletetionError);
            }
        });
    });
}

- (void)makeClosedDocument:(CDBDocument * _Nonnull)document
                ubiquitous:(BOOL)ubiquitous
                completion:(CDBErrorCompletion _Nonnull)completion {

    if (document.isUbiquitous == ubiquitous) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    if (self.ubiquityContainerAccessible == NO) {
        if (completion != nil) {
            completion([self iCloudNotAcceessableError]);
        }
        return;
    }

    NSURL * destinationURL = ubiquitous ? [self ubiquityDocumentFileURLUsingLocalURL:document.fileURL]
                                        : [self localDocumentFileURLUsingUbiquityURL:document.fileURL];

    if ([document.fileURL isEqual:destinationURL]) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    dispatch_async(self.serialQueue, ^(void) {
        NSError * error = nil;
        [self.fileManager setUbiquitous:ubiquitous
                              itemAtURL:document.fileURL
                         destinationURL:destinationURL
                                  error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(error);
            }
        });
    });
}

- (void)moveClosedDocument:(CDBDocument *)document
                     toURL:(NSURL *)destinationURL
                completion:(CDBErrorCompletion)completion {
    dispatch_async(self.serialQueue, ^(void) {

        __block NSError * copyingError = nil;
        void (^accessor)(NSURL*, NSURL*) = ^(NSURL *newURL1, NSURL *newURL2) {
            [self.fileManager moveItemAtURL:newURL1
                                      toURL:newURL2
                                      error:&copyingError];
        };

        __block NSError * coordinationError = nil;
        NSFileCoordinator * coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:document];
        [coordinator coordinateWritingItemAtURL:document.fileURL
                                        options:NSFileCoordinatorWritingForMoving
                               writingItemAtURL:destinationURL
                                        options:NSFileCoordinatorWritingForReplacing
                                          error:&coordinationError
                                     byAccessor:accessor];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(coordinationError != nil ? coordinationError
                                                    : copyingError);
            }
        });
    });
}

- (void)copyClosedDocument:(CDBDocument *)document
                     toURL:(NSURL *)destinationURL
                   replace:(BOOL)replace
                completion:(CDBErrorCompletion)completion {
    dispatch_async(self.serialQueue, ^(void) {
        __block NSError * copyingError = nil;
        void (^accessor)(NSURL*, NSURL*) = ^(NSURL *newURL1, NSURL *newURL2) {
            if (replace) {
                [self.fileManager removeItemAtURL:newURL2
                                            error:nil];
            }
            [self.fileManager copyItemAtURL:newURL1
                                      toURL:newURL2
                                      error:&copyingError];
        };

        __block NSError * coordinationError = nil;
        NSFileCoordinator * coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:document];
        [coordinator coordinateReadingItemAtURL:document.fileURL
                                        options:NSFileCoordinatorReadingWithoutChanges
                               writingItemAtURL:destinationURL
                                        options:NSFileCoordinatorWritingForReplacing
                                          error:&coordinationError
                                     byAccessor:accessor];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(coordinationError != nil ? coordinationError
                                                    : copyingError);
            }
        });
    });
}

- (CDBDocument *)documentWithAvailableFileURL:(NSURL *)fileURL
                                        error:(NSError *__autoreleasing *)error {
    BOOL directory = NO;
    BOOL exist = [self.fileManager fileExistsAtPath:fileURL.path
                                        isDirectory:&directory];
    if (exist == NO || directory) {
        *error = [self directoryUnacceptableURLErrorUsingURL:fileURL];
        return nil;
    }

    CDBDocument * result = [[CDBDocument alloc] initWithFileURL:fileURL];
    return result;
}

#pragma mark Synchronize documents

- (void)startSynchronizationWithCompletion:(CDBErrorCompletion)completion {
    if (self.documentsDirectoryWatchdog == nil) {
        self.documentsDirectoryWatchdog = [CDBDocument documentWithFileURL:self.ubiquityDocumentsURL
                                                                  delegate:self];
        [NSFileCoordinator addFilePresenter:self.documentsDirectoryWatchdog];
    }

    [self.metadataQuery setSearchScopes:@[NSMetadataQueryUbiquitousDocumentsScope]];
    [self.metadataQuery setPredicate:[self requestedFilesMetadataPredicate]];

    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleMetadataQueryDidUpdateNotification:)
                                                     name:NSMetadataQueryDidUpdateNotification
                                                   object:self.metadataQuery];

        [[NSNotificationCenter defaultCenter]  addObserver:self
                                                  selector:@selector(handleMetadataQueryDidFinishGatheringNotification:)
                                                      name:NSMetadataQueryDidFinishGatheringNotification
                                                    object:self.metadataQuery];

        BOOL startedQuery = [self.metadataQuery startQuery];
        if (startedQuery == NO) {
            NSLog(@"[CDBCloudDocuments] Failed to start metadata query");
        }

        if (completion != nil) {
            completion(nil);
        }
    });
}

- (void)updateFilesWithCompletion:(CDBCompletion)completion {
    __weak typeof (self) wself = self;
    [self.metadataQuery disableUpdates];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSMutableArray * documentsURLs = [NSMutableArray array];
        NSMutableArray * documentNames = [NSMutableArray array];

        [wself.metadataQuery enumerateResultsUsingBlock:^(NSMetadataItem * item, NSUInteger idx, BOOL *stop) {
            NSURL * fileURL = [item valueForAttribute:NSMetadataItemURLKey];

            [documentsURLs addObject:fileURL];
            [documentNames addObject:fileURL.lastPathComponent];
        }];

        dispatch_async(dispatch_get_main_queue(), ^{
            wself.uniqueCloudDocumentURLs = [NSMutableSet setWithArray:documentsURLs];
            if (completion != nil) {
                completion();
            }
            [wself notifyDelegateThatUbiquitosDocumentsDidChangeQuery:self.metadataQuery];

            if (self.metadataQueryShouldStopAfterFinishGathering == NO) {
                [self.metadataQuery startQuery];
            }
        });
    });
}

- (void)dissmissSynchronization {
    if (self.documentsDirectoryWatchdog != nil) {
        [NSFileCoordinator removeFilePresenter:self.documentsDirectoryWatchdog];
        self.documentsDirectoryWatchdog = nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_metadataQuery stopQuery];
    _metadataQuery = nil;
}

- (void)startDownloadingDocumentWithURL:(NSURL *)fileURL
                                andName:(NSString *)name {
    NSError *error;
    BOOL downloading = [self.fileManager startDownloadingUbiquitousItemAtURL:fileURL
                                                                       error:&error];
    if (downloading == NO){
        NSLog(@"[CDBCloudDocuments] Ubiquitous item with name %@ \
              \nfailed to start downloading with error: %@", name, error);
    }
}

#pragma mark Directory checking

- (void)ensureThatUbiquitousDocumentsDirectoryPresents {
    [self synchronousEnsureThatDirectoryPresentsAtURL:self.ubiquityDocumentsURL
                                            comletion:^(NSError *error) {
        if (error == nil) {
            return;
        }
        NSLog(@"[CDBCloudDocuments] could not resolve ubiquituos documents directory URL %@\
              \n failed with error: %@",
              self.ubiquityDocumentsURL, error);
        NSLog(@"[CDBCloudDocuments] ubiquituos documents directory resolved to default path");
        self.cloudPathComponent = CDBiCloudDocumentsDirectoryPathComponent;
        [self synchronousEnsureThatDirectoryPresentsAtURL:self.ubiquityDocumentsURL
                                                comletion:^(NSError *error) {
            if (error == nil) {
                return;
            }
            NSLog(@"[CDBCloudDocuments] unpredicable error \
                  \ncould not resolve default ubiquituos documents directory URL %@\
                  \n failed with error: %@",
                  self.ubiquityDocumentsURL, error);
        }];
    }];
}

- (void)synchronousEnsureThatDirectoryPresentsAtURL:(NSURL *)URL
                                          comletion:(CDBErrorCompletion)completion {
    if (URL == nil) {
        if (completion != nil) {
            completion([self directoryUnacceptableURLErrorUsingURL:URL]);
        }
        return;
    }

    NSError * error = nil;

    NSString * directoryPath = [URL path];
    BOOL isDirectory = NO;
    BOOL exist = [self.fileManager fileExistsAtPath:directoryPath isDirectory:&isDirectory];

    if (exist == NO) {
        [self.fileManager createDirectoryAtURL:URL
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:&error];
        if (completion != nil) {
            completion(error);
        }
        return;
    }

    if (isDirectory) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    [self.fileManager removeItemAtPath:directoryPath
                                 error:&error];
    if (error != nil) {
        if (completion != nil) {
            completion(error);
        }
        return;
    }

    [self.fileManager createDirectoryAtURL:URL
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error];
    if (completion != nil) {
        completion(error);
    }
}

#pragma mark handle documents versioning

- (NSDate *)lastProcessedDateForDocumentWithName:(NSString *)documentName {
    NSString * processedKey = [self processedDateKeyForDocumentWithName:documentName];
    if (processedKey == nil) {
        return nil;
    }

    NSDate * result = [[NSUserDefaults standardUserDefaults] objectForKey:processedKey];
    return result;
}

- (void)saveProcessedDate:(NSDate *)processedDate
      forDocumentWithName:(NSString *)documentName {
    if (processedDate == nil) {
        return;
    }

    NSString * processedKey = [self processedDateKeyForDocumentWithName:documentName];
    if (processedKey == nil) {
        return;
    }

    [[NSUserDefaults standardUserDefaults] setObject:processedDate
                                              forKey:processedKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)processedDateKeyForDocumentWithName:(NSString *)documentName {
    if (documentName == nil) {
        return nil;
    }
    NSString * result = [NSString stringWithFormat:CDB_Documents_Processing_Last_Date_Format, documentName];
    return result;
}

#pragma mark Ubiquitios URL

- (NSURL *)ubiquityDocumentFileURLUsingFileName:(NSString *)fileName {

    NSURL * result = [self.ubiquityDocumentsURL URLByAppendingPathComponent:fileName
                                                                isDirectory:NO];
    return result;
}

- (NSURL *)localDocumentFileURLUsingFileName:(NSString *)fileName {
    NSURL * result = [self.localDocumentsURL URLByAppendingPathComponent:fileName
                                                             isDirectory:NO];
    return result;
}

- (NSURL *)ubiquityDocumentFileURLUsingLocalURL:(NSURL *)localURL {

    NSString * relativeURLString = [self relativeURLStringFromURL:localURL
                                                     usingBaseURL:self.localDocumentsURL];
    NSURL * result = nil;
    if (relativeURLString != nil) {
        result = [self.ubiquityDocumentsURL URLByAppendingPathComponent:relativeURLString];
    } else {
        result = [self ubiquityDocumentFileURLUsingFileName:localURL.lastPathComponent];
    }

    return result;
}

- (NSURL *)localDocumentFileURLUsingUbiquityURL:(NSURL *)ubiquitousURL {
    NSString * relativeURLString = [self relativeURLStringFromURL:ubiquitousURL
                                                     usingBaseURL:self.ubiquityDocumentsURL];
    NSURL * result = nil;
    if (relativeURLString != nil) {
        result = [self.localDocumentsURL URLByAppendingPathComponent:relativeURLString];
    } else {
        result = [self localDocumentFileURLUsingFileName:ubiquitousURL.lastPathComponent];
    }

    return result;
}

- (NSString *)relativeURLStringFromURL:(NSURL *)URL
                          usingBaseURL:(NSURL *)baseURL {
    NSRange baseRange = [URL.path rangeOfString:baseURL.path];
    NSInteger relativeURLstartIndex = NSMaxRange(baseRange)+1;
    if (baseRange.location == NSNotFound
    ||  relativeURLstartIndex >= URL.path.length) {
       return nil;
    }

    NSString * result = [URL.path substringFromIndex:relativeURLstartIndex];
    return result;
}

#pragma mark notify delegate

- (void)notifyDelegateThatDocumentsDidChangeState {
    __weak typeof (self) wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([wself.delegate respondsToSelector:@selector(didChangeCloudStateOfCDBCloudDocuments:)]) {
            [wself.delegate didChangeCloudStateOfCDBCloudDocuments:wself];
        }
    });
}

- (void)notifyDelegateThatUbiquitosDocumentsDidChangeQuery:(NSMetadataQuery *)query {
    if ([self.delegate respondsToSelector:@selector(CDBCloudDocuments:didChangeMetadataQuery:)]) {
        [self.delegate CDBCloudDocuments:self
                  didChangeMetadataQuery:query];
    }
}

- (void)notifyDelegateThatDocumentsDidAutoresolveConflictInCDBDocument:(CDBDocument * _Nonnull)document {
    __weak typeof(self) wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([wself.delegate respondsToSelector:@selector(CDBCloudDocuments: didAutoresolveConflictInCDBDocument:)]) {
            [wself.delegate CDBCloudDocuments:wself
          didAutoresolveConflictInCDBDocument:document];
        }
    });
}

- (void)notifyDelegateThatDocumentsDidChangeUbiquitosDocumentAtURL:(NSURL * _Nullable)URL {
    __weak typeof (self) wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([wself.delegate respondsToSelector:@selector(CDBCloudDocuments: didChangeUbiquitosDocumentAtURL:)]) {
            [wself.delegate CDBCloudDocuments:wself
             didChangeUbiquitosDocumentAtURL:URL];
        }
    });
}

- (void)notifyDelegateThatDocumentsDidRemoveUbiquitosDocumentAtURL:(NSURL * _Nullable)URL {
    __weak typeof (self) wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([wself.delegate respondsToSelector:@selector(CDBCloudDocuments: didRemoveUbiquitosDocumentAtURL:)]) {
            [wself.delegate CDBCloudDocuments:wself
             didRemoveUbiquitosDocumentAtURL:URL];
        }
    });
}

#pragma mark Logging

- (void)logMetadataQueryNotification:(NSNotification *)notification {
    if (self.verbose == NO) {
        return;
    }

    [notification.userInfo enumerateKeysAndObjectsUsingBlock:^(NSString *  _Nonnull change, NSArray *  _Nonnull metadataItems, BOOL * _Nonnull stop) {
        if (metadataItems.count == 0) {
            return;
        }
        NSLog(@"Change %@: ==============================\r", change);
        for (NSMetadataItem *metadataItem in metadataItems) {
            if ([metadataItem isKindOfClass:[NSMetadataItem class]] == NO) {
                continue;
            }

            [self logMetadataItem:metadataItem];
        }
    }];
}

- (void)logMetadataItem:(NSMetadataItem *)item {
    NSNumber *isUbiquitous = [item valueForAttribute:NSMetadataItemIsUbiquitousKey];
    NSNumber *hasUnresolvedConflicts = [item valueForAttribute:NSMetadataUbiquitousItemHasUnresolvedConflictsKey];
    NSString *isDownloaded = [item valueForAttribute:NSMetadataUbiquitousItemDownloadingStatusKey];
    NSNumber *isDownloading = [item valueForAttribute:NSMetadataUbiquitousItemIsDownloadingKey];
    NSNumber *isUploaded = [item valueForAttribute:NSMetadataUbiquitousItemIsUploadedKey];
    NSNumber *isUploading = [item valueForAttribute:NSMetadataUbiquitousItemIsUploadingKey];
    NSNumber *percentDownloaded = [item valueForAttribute:NSMetadataUbiquitousItemPercentDownloadedKey];
    NSNumber *percentUploaded = [item valueForAttribute:NSMetadataUbiquitousItemPercentUploadedKey];
    NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];

    BOOL documentExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];

    NSLog(@"documentExists:%i - %@\
          \r isUbiquitous:%@ hasUnresolvedConflicts:%@\
          \r isDownloaded:%@ isDownloading:%@ isUploaded:%@ isUploading:%@\
          \r %%downloaded:%@ %%uploaded:%@",
            documentExists, url,
            isUbiquitous,
            hasUnresolvedConflicts,
            isDownloaded,
            isDownloading,
            isUploaded,
            isUploading,
            percentDownloaded,
            percentUploaded);
}

@end