text:
.styleSans140.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 140.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans197.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 197.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans146.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 146.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans56.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 56.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 11.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 10.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans37.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 37.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 9.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans192.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 192.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans420.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 420.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans328.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 328.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans692.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 692.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans104.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 104.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 8.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans14.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 14.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 13.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 1.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 7.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 4.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans343.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 343.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 5.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans182.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 182.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans691.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 691.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans22.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 22.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 15.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans19.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 19.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans24.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 24.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans57.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 57.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 6.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans482.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 482.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans485.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 485.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans495.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 495.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans187.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 187.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans106.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 106.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans369.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 369.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans88.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 88.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans624.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 624.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans696.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 696.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans591.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 591.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans714.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 714.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans634.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 634.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans732.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 732.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 2.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans153.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 153.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans512.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 512.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans81.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 81.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans613.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 613.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans693.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 693.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans99.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 99.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 18.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans215.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 215.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans211.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 211.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans225.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 225.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans42.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 42.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans674.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 674.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}


text:
package org.zaproxy.zap.view.panelsearch;

public final class Generic {

    @SuppressWarnings({"unchecked"})
    public static <T> T uncheckedCast(Object component) {
        T casted;
        try {
            casted = (T) component;
        } catch (ClassCastException ex) {
            return null;
        }
        return casted;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""hug/introspect.py

Defines built in hug functions to aid in introspection

Copyright (C) 2016  Timothy Edmund Crosley

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

"""
from __future__ import absolute_import

import inspect
from types import MethodType

def is_method(function):
    """Returns True if the passed in function is identified as a method (NOT a function)"""
    return isinstance(function, MethodType)

def is_coroutine(function):
    """Returns True if the passed in function is a coroutine"""
    return function.__code__.co_flags & 0x0080 or getattr(function, "_is_coroutine", False)

def name(function):
    """Returns the name of a function"""
    return function.__name__

def arguments(function, extra_arguments=0):
    """Returns the name of all arguments a function takes"""
    if not hasattr(function, "__code__"):
        return ()

    return function.__code__.co_varnames[: function.__code__.co_argcount + extra_arguments]

def takes_kwargs(function):
    """Returns True if the supplied function takes keyword arguments"""
    return bool(function.__code__.co_flags & 0x08)

def takes_args(function):
    """Returns True if the supplied functions takes extra non-keyword arguments"""
    return bool(function.__code__.co_flags & 0x04)

def takes_arguments(function, *named_arguments):
    """Returns the arguments that a function takes from a list of requested arguments"""
    return set(named_arguments).intersection(arguments(function))

def takes_all_arguments(function, *named_arguments):
    """Returns True if all supplied arguments are found in the function"""
    return bool(takes_arguments(function, *named_arguments) == set(named_arguments))

def generate_accepted_kwargs(function, *named_arguments):
    """Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that's
       compatible with the supplied function
    """
    if hasattr(function, "__code__") and takes_kwargs(function):
        function_takes_kwargs = True
        function_takes_arguments = []
    else:
        function_takes_kwargs = False
        function_takes_arguments = takes_arguments(function, *named_arguments)

    def accepted_kwargs(kwargs):
        if function_takes_kwargs:
            return kwargs
        elif function_takes_arguments:
            return {key: value for key, value in kwargs.items() if key in function_takes_arguments}
        return {}

    return accepted_kwargs


text:
package com.cloudwick.avro.AvroWithoutCodeGenerator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;

public class AvroDeserializer {
	public static void main(String... args) throws IOException {
		Schema schema = new Schema.Parser().parse(new File(
				"src/main/resources/schema/schema.avsc"));
		GenericRecord record = new GenericData.Record(schema);

		File file = new File("output/serialized.avro");

		DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(
				schema);
		DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(
				file, datumReader);

		File file2 = new File("output/deserialized.txt");

		if (!file2.exists()) {
			file2.createNewFile();
		}

		FileWriter fileWriter = new FileWriter(file2.getAbsoluteFile());
		BufferedWriter writer = new BufferedWriter(fileWriter);

		while (dataFileReader.hasNext()) {
			record = dataFileReader.next();
			writer.write(record.toString() + "\n");
		}

		writer.close();
		dataFileReader.close();
	}
}


text:
const methodInput = document.getElementById('method')
const uriInput = document.getElementById('uri')
const hostInput = document.getElementById('host')

const queryKeys = document.getElementsByClassName('queryKey')
const queryValues = document.getElementsByClassName('queryValue')

const headerKeys = document.getElementsByClassName('headerKey')
const headerValues = document.getElementsByClassName('headerValue')

const bodyInput = document.getElementById('body')

const rawRequestDiv = document.getElementById('rawRequest')
const rawResponseDiv = document.getElementById('rawResponse')

const historySelect = document.getElementById('history')

const methods = [
  'GET',
  'POST'
]

populateHistorySelect()

function populateHistorySelect () {
  while (historySelect.hasChildNodes()) {
    historySelect.removeChild(historySelect.lastChild)
  }

  const labelOption = document.createElement('option')
  labelOption.value = -1
  labelOption.innerText = 'History'
  historySelect.appendChild(labelOption)

  const history = JSON.parse(localStorage.requests)

  history.forEach((request, index) => {
    const option = document.createElement('option')
    option.value = index
    option.innerText = `${request.method} ${request.host}${request.uri}`
    historySelect.appendChild(option)
  })
}

function remember () {
  const index = parseInt(historySelect.value)

  clearFields()

  if (index === -1) return

  const history = JSON.parse(localStorage.requests)
  const request = history[index]

  methodInput.value = request.method
  hostInput.value = request.host
  uriInput.value = request.uri

  if ('queries' in request) {
    request.queries.forEach((query, index) => {
      for (let key in query) {
        queryKeys[index].value = key
        queryValues[index].value = query[key]
      }
    })
  }

  if ('headers' in request) {
    request.headers.forEach((header, index) => {
      for (let key in header) {
        headerKeys[index].value = key
        headerValues[index].value = header[key]
      }
    })
  }

  if ('body' in request) {
    bodyInput.value = request.body
  }
}

function clearFields () {
  methodInput.value = null
  hostInput.value = null
  uriInput.value = null
  bodyInput.value = null

  Array.from(queryKeys).forEach((queryKey, index) => {
    queryKey.value = null
    queryValues[index].value = null
  })

  Array.from(headerKeys).forEach((headerKey, index) => {
    headerKey.value = null
    headerValues[index].value = null
  })
}

function build () {
  if (!methods.find(method => method === methodInput.value)) {
    alert(`You must enter one of these methods: ${methods.join(', ')}`)
    return
  }

  if (!hostInput.value) {
    alert('You must enter a host')
    return
  }

  if (!uriInput.value) {
    alert('You must enter a URI')
    return
  }

  rawResponseDiv.textContent = ''

  let request = `${methodInput.value} ${uriInput.value}`

  const requestObject = {
    method: methodInput.value,
    host: hostInput.value,
    uri: uriInput.value,
  }

  if (methodInput.value === 'GET') {
    const queryKeysArray = Array.from(queryKeys).map(input => input.value)
    const queryValuesArray = Array.from(queryValues).map(input => input.value)

    const queries = queryKeysArray.reduce((queries, key, index) => {
      if (key.length !== 0 && queryValuesArray[index].length !== 0) {
        queries.push(`${key}=${queryValuesArray[index]}`)
        if (!('queries' in requestObject)) {
          requestObject.queries = []
        }
        requestObject.queries.push({[key]: queryValuesArray[index]})
      }
      return queries
    }, [])

    if (queries.length !== 0) {
      request += `?${queries.join('&')}`
    }
  }

  request += ` HTTP/1.1\r\nHost: ${hostInput.value}\r\n`

  const headerKeysArray = Array.from(headerKeys).map(input => input.value)
  const headerValuesArray = Array.from(headerValues).map(input => input.value)

  const headers = headerKeysArray.reduce((headers, key, index) => {
    if (key.length !== 0 && headerValuesArray[index].length !== 0) {
      headers.push(`${key}: ${headerValuesArray[index]}`)
      if (!('headers' in requestObject)) {
        requestObject.headers = []
      }
      requestObject.headers.push({[key]: headerValuesArray[index]})
    }
    return headers
  }, [])

  if (bodyInput.value.length !== 0) {
    headers.push(`Content-Length: ${bodyInput.value.length}`)
    headers.push('Content-Type: text/plain')
    requestObject.body = bodyInput.value
  }

  if (headers.length !== 0) {
    request += `${headers.join('\r\n')}`
  }

  request += '\r\n\r\n'

  if (bodyInput.value.length !== 0) {
    request += bodyInput.value
  }

  rawRequestDiv.textContent = request

  const previousRequests = localStorage.requests
    ? JSON.parse(localStorage.requests)
    : []

  previousRequests.push(requestObject)

  localStorage.setItem('requests', JSON.stringify(previousRequests))

  populateHistorySelect()

  return request
}

function buildAndSend () {
  const requestString = build()

  const xhrRequest = new XMLHttpRequest()
  xhrRequest.open("POST", 'http://localhost:3001/sendRequest')

  xhrRequest.onload = function () {
    if (xhrRequest.readyState === xhrRequest.DONE) {
      rawResponseDiv.textContent = xhrRequest.response
    }
  }

  xhrRequest.send(requestString)
}


text:
"""
LossUtils is a collection of loss functions implemented in Tensorflow/Slim.
Created 7/12/17 at 7:48 PM.
"""
__author__ = "Alexander Ponamarev"
__email__ = "alex.ponamaryov@gmail.com"

from tensorflow.contrib.slim import flatten
from tensorflow import reduce_sum, reduce_mean, identity, variable_scope
import tensorflow as tf

smooth = 1.

def IOU_calc(y_true, y_pred):
    with variable_scope("IoU"):
        y_true_f = flatten(y_true)
        y_pred_f = flatten(y_pred)
        intersection = reduce_sum(y_true_f * y_pred_f, axis=-1, name="intersection")
        union = identity(reduce_sum(y_true_f + y_pred_f, axis=-1)-intersection, name="union")

        return reduce_mean((intersection + smooth) / (union + smooth), name="IoU_smoothed")

def IOU_calc_loss(y_true, y_pred):
    with variable_scope("IoU_Loss"):
        total_loss = identity(1.0-IOU_calc(y_true, y_pred), name="loss")
        return total_loss


text:
import React, {Component} from "react";
import gql from "graphql-tag.macro";
import {graphql, withApollo} from "react-apollo";
import {Container, Row, Col, Input, Button} from "helpers/reactstrap";
import SubscriptionHelper from "helpers/subscriptionHelper";
import "./style.scss";

export const SURVEY_FORM_CORE_SUB = gql`
  subscription SurveyFormsUpdate($simulatorId: ID) {
    surveyformUpdate(simulatorId: $simulatorId) {
      id
      form {
        id
        type
        title
        value
        options {
          id
          label
        }
        description
        min
        max
      }
      title
      results {
        name
        client
        station
        form {
          id
          value
        }
      }
    }
  }
`;

class SurveyCore extends Component {
  state = {};
  startSurvey = () => {
    const mutation = gql`
      mutation TriggerSurvey($simulatorId: ID!, $id: ID!) {
        triggerSurvey(simulatorId: $simulatorId, id: $id)
      }
    `;
    const variables = {
      simulatorId: this.props.simulator.id,
      id: this.state.survey,
    };
    this.props.client.mutate({
      mutation,
      variables,
    });
    this.setState({survey: null});
  };
  downloadResults = s => {
    // Map the results
    const results = [];
    results.push(
      ["Name", "Station", "Client"].concat(s.form.map(f => f.title)),
    );
    s.results
      .map(r =>
        [r.name, r.station, r.client].concat(
          r.form.map(f => {
            if (s.form.find(m => m.id === f.id)) {
              const option = s.form
                .find(m => m.id === f.id)
                .options.filter(o => f.value.split(",").includes(o.id))
                .map(o => o.label)
                .join("; ");
              if (option) {
                return option;
              }
            }
            if (parseInt(f.value, 10)) {
              return parseInt(f.value, 10);
            }
            return f.value;
          }),
        ),
      )
      .forEach(a => {
        results.push(a);
      });
    let csvContent = "data:text/csv;charset=utf-8,";
    results.forEach(function (rowArray) {
      let row = rowArray.join(",");
      csvContent += row + "\r\n";
    });
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.classList.add("hidden");
    link.setAttribute("download", `${s.title}.csv`);
    document.body.appendChild(link);

    link.click();
  };
  endSurvey = e => {};
  render() {
    const {
      data: {loading, surveyform, allForms},
    } = this.props;
    if (loading || !surveyform || !allForms) return null;
    return (
      <Container className="surveyForm-core">
        <SubscriptionHelper
          subscribe={() =>
            this.props.data.subscribeToMore({
              document: SURVEY_FORM_CORE_SUB,
              variables: {simulatorId: this.props.simulator.id},
              updateQuery: (previousResult, {subscriptionData}) => {
                return Object.assign({}, previousResult, {
                  surveyform: subscriptionData.data.surveyformUpdate,
                });
              },
            })
          }
        />
        <Row>
          <Col sm={12}>

              <Input
                type="select"
                value={this.state.survey || "nothing"}
                onChange={e => this.setState({survey: e.target.value})}
              >
                <option value="nothing" disabled>
                  Choose a new survey
                </option>
                {allForms.map(f => (
                  <option key={`${f.id}-all`} value={f.id}>
                    {f.title}
                  </option>
                ))}
              </Input>
              <Button
                disabled={!this.state.survey}
                size="sm"
                color="success"
                onClick={this.startSurvey}
              >
                Start
              </Button>

              Running Surveys:

            {surveyform.map(s => (
              <Row key={`${s.id}-running`}>
                <Col>

{s.title}

                </Col>
                <Col>

{s.results.length}

                </Col>
                <Col>
                  <Button
                    size="sm"
                    color="success"
                    onClick={() => this.downloadResults(s)}
                  >
                    Results (CSV)
                  </Button>
                </Col>
                {/* {<Col>
                  <Button size="sm" color="danger">
                    End
                  </Button>
                </Col>} */}
              </Row>
            ))}
          </Col>
        </Row>
      </Container>
    );
  }
}

export const SURVEY_FORM_CORE_QUERY = gql`
  query SurveyForms($simulatorId: ID!) {
    allForms: surveyform {
      id
      title
    }
    surveyform(simulatorId: $simulatorId) {
      id
      form {
        id
        type
        title
        value
        options {
          id
          label
        }
        description
        min
        max
      }
      title
      results {
        name
        client
        station
        form {
          id
          value
        }
      }
    }
  }
`;
export default graphql(SURVEY_FORM_CORE_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: {
      simulatorId: ownProps.simulator.id,
    },
  }),
})(withApollo(SurveyCore));


text:
#region

using System.Collections.ObjectModel;
using GTR.Core.Engine;
using GTR.Core.Game;
using GTR.Core.Model;
using GTR.Core.Model.CardCollections;

#endregion

namespace GTR.Universal.Design
{
    public class DesignGameTable : GameTable
    {
        public DesignGameTable() : base()
        {
            OrderDeck = new OrderDeck();
            JackDeck = new JackDeck();
            Players = new ObservableCollection<Player> {new DesignPlayer()};
            for (int i = 0; i < 50; i++)
            {
                string cardName = string.Format("Card #{0}", i);
                string description = "this is a fake description";
                RoleType role = RoleType.Architect;
                switch (i%4)
                {
                    case 0:
                        role = RoleType.Architect;
                        break;
                    case 1:
                        role = RoleType.Craftsman;
                        break;
                    case 2:
                        role = RoleType.Laborer;
                        break;
                    default:
                        role = RoleType.Legionnaire;
                        break;
                }
                OrderDeck.Add(new OrderCardModel(cardName, description, role));
            }

            for (int i = 0; i < 5; i++)
            {
                JackDeck.Add(new JackCardModel());
            }
        }
    }
}


text:
import {AmpStoryInteractive, InteractiveType} from './amp-story-interactive';
import {CSS} from '../../../build/amp-story-interactive-results-1.0.css';
import {StateProperty} from './amp-story-store-service';
import {htmlFor} from '../../../src/static-template';
import {setStyle} from '../../../src/style';

/**
 * @typedef {{
 *    category: string,
 * }}
 */
export let InteractiveResultsDef;

/**
 * Generates the template for the quiz.
 *
 * @param {!Element} element
 * @return {!Element}
 */
const buildResultsTemplate = (element) => {
  const html = htmlFor(element);
  return html`

  `;
};

/**
 * Processes the state and returns the condensed results.
 * @param {!Map<string, {option: ?./amp-story-interactive.OptionConfigType, interactiveId: string}>} interactiveState
 * @param {?Array<!./amp-story-interactive.OptionConfigType>} options needed to ensure the first options take precedence on ties
 * @return {InteractiveResultsDef} the results
 */
const processResults = (interactiveState, options) => {
  const categories = {};
  // Add options in order to prefer earlier categories before later ones.
  options.forEach((option) => {
    categories[option.resultscategory] = 0;
  });
  Object.values(interactiveState).forEach((e) => {
    if (e.option != null) {
      categories[e.option.resultscategory] += 1;
    }
  });
  return {
    category: Object.keys(categories).reduce((a, b) =>
      categories[a] >= categories[b] ? a : b
    ),
  };
};

export class AmpStoryInteractiveResults extends AmpStoryInteractive {
  /**
   * @param {!AmpElement} element
   */
  constructor(element) {
    super(element, InteractiveType.RESULTS, [2, 4]);
  }

  /** @override */
  buildCallback() {
    super.buildCallback(CSS);
  }

  /** @override */
  buildComponent() {
    this.rootEl_ = buildResultsTemplate(this.element);
    return this.rootEl_;
  }

  /** @override */
  layoutCallback() {
    if (this.element.hasAttribute('prompt-text')) {
      this.rootEl_.querySelector(
        '.i-amphtml-story-interactive-results-prompt'
      ).textContent = this.element.getAttribute('prompt-text');
    }
    this.storeService_.subscribe(
      StateProperty.INTERACTIVE_REACT_STATE,
      (data) => this.onInteractiveReactStateUpdate_(data),
      true
    );
  }

  /**
   * Receives state updates and fills up DOM with the result
   * @param {!Map<string, {option: ?./amp-story-interactive.OptionConfigType, interactiveId: string}>} interactiveState
   * @private
   */
  onInteractiveReactStateUpdate_(interactiveState) {
    const results = processResults(interactiveState, this.options_);
    this.options_.forEach((e) => {
      if (e.resultscategory === results.category) {
        this.mutateElement(() => {
          this.updateCategory_(e);
          this.updateToPostSelectionState_(null);
        });
      }
    });
  }

  /**
   * Updates the element with the correct category
   * @param {./amp-story-interactive.OptionConfigType} categorySelected
   * @private
   */
  updateCategory_(categorySelected) {
    setStyle(
      this.rootEl_.querySelector('.i-amphtml-story-interactive-results-image'),
      'background',
      'url(' + categorySelected.image + ')'
    );
    this.rootEl_.querySelector(
      '.i-amphtml-story-interactive-results-title'
    ).textContent = categorySelected.resultscategory;
    this.rootEl_.querySelector(
      '.i-amphtml-story-interactive-results-description'
    ).textContent = categorySelected.text || '';
  }

  /** @override */
  handleTap_(unusedEvent) {
    // Disallow click handler since there are no options.
  }

  /** @override */
  updateOptionPercentages_(unusedOptionsData) {
    // TODO(mszylkowski): Show percentages of categories if endpoint.
  }

  /** @override */
  updateStoryStoreState_(unusedOption) {
    // Prevent from updating the state.
  }
}


text:
    title: 响应
---

# Returning Responses

Part of the HTTP cycle is returning responses to clients. `ManaPHP\Http\Response` is the ManaPHP
component designed to achieve this task. HTTP responses are usually composed by headers and body. The following is an example of basic usage:

```php
    // Getting a response instance
    $response = new \ManaPHP\Http\Response();

    // Set status code
    $response->setStatusCode(404, "Not Found");

    // Set the content of the response
    $response->setContent("Sorry, the page doesn't exist");

    // Send response to the client
    $response->send();
```

If you are using the full MVC stack there is no need to create responses manually. However, if you need to return a response
directly from a controller's action follow this example:

```php
    class FeedController extends ManaPHP\Mvc\Controller
    {
        public function getAction()
        {
            // Set the content of the response and return the response
            return $this->response->setContent($feed->asString());
        }
    }
```

## Working with Headers

Headers are an important part of the HTTP response. It contains useful information about the response state like the HTTP status,
type of response and much more.

You can set headers in the following way:

```php
    // Setting a header by its name
    $response->setHeader("Content-Type", "application/pdf");
    $response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"');

    // Setting a raw header
    $response->setRawHeader("HTTP/1.1 200 OK");
```

A `ManaPHP\Http\Response\Headers` bag internally manages headers. This class
retrieves the headers before sending it to client:

```php
    // Get the headers bag
    $headers = $response->getHeaders();

    // Get a header by its name
    $contentType = $response->getHeaders()->get("Content-Type");
```

## Making Redirections

With `ManaPHP\Http\Response` you can also execute HTTP redirection:

```php
    // Redirect to the local base URI
    $response->redirect("posts/index");

    // Redirect to an external URL
    $response->redirect("http://en.wikipedia.org");

    // Redirect specifying the HTTP status code
    $response->redirect("http://www.example.com/new-location",301);
```

## HTTP Cache

One of the easiest ways to improve the performance in your applications and reduce the traffic is using HTTP Cache.
Most modern browsers support HTTP caching and is one of the reasons why many websites are currently fast.

HTTP Cache can be altered in the following header values sent by the application when serving a page for the first time:

* `Expires:` With this header the application can set a date in the future or the past telling the browser when the page must expire.
* `Cache-Control:` This header allows to specify how much time a page should be considered fresh in the browser.
* `Last-Modified:` This header tells the browser which was the last time the site was updated avoiding page re-loads
* `ETag:` An etag is a unique identifier that must be created including the modification timestamp of the current page

### Setting an Expiration Time

The expiration date is one of the easiest and most effective ways to cache a page in the client (browser).
Starting from the current date we add the amount of time the page will be stored
in the browser cache. Until this date expires no new content will be requested from the server:

```php
    $expireDate = new DateTime();
    $expireDate->modify('+2 months');

    $response->setExpires($expireDate);
```

The Response component automatically shows the date in GMT timezone as expected in an Expires header.

If we set this value to a date in the past the browser will always refresh the requested page:

```php
    $expireDate = new DateTime();
    $expireDate->modify('-10 minutes');

    $response->setExpires($expireDate);
```

Browsers rely on the client's clock to assess if this date has passed or not. The client clock can be modified to
make pages expire and this may represent a limitation for this cache mechanism.

### Cache-Control

This header provides a safer way to cache the pages served. We simply must specify a time in seconds telling the browser
how long it must keep the page in its cache:

```php
    // Starting from now, cache the page for one day
    $response->setHeader('Cache-Control', 'max-age=86400');
```

The opposite effect (avoid page caching) is achieved in this way:

```php
    // Never cache the served page
    $response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
```

### E-Tag

An "entity-tag" or "E-tag" is a unique identifier that helps the browser realize if the page has changed or not between two requests.
The identifier must be calculated taking into account that this must change if the previously served content has changed:

```php
    // Calculate the E-Tag based on the modification time of the latest news
    $recentDate = News::maximum(array('column' => 'created_at'));
    $eTag       = md5($recentDate);

    // Send an E-Tag header
    $response->setHeader('E-Tag', $eTag);
```


text:
<!DOCTYPE html>

    <title>SV Techsol : Solutions</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="normalize.css">
    <link rel="stylesheet" type="text/css" href="svtechsol.css">
    <link rel="icon" href="images/logos/favicon.ico" type="image/x-icon">

                            Home

                            Products

                            Solutions

                            Services

                            Company

Solutions

Our product design and engineering solutions range from simple filter fan units to the most demanding custom front-end modules and mini-environments in the industry. Our standard approach to solving your filtration requirements begins with a comprehensive review of your process, air flow requirements, size restrictions and contamination sources. After this review S.V. Techsol integrates its expertise which includes ergonomic compatibility, maintainability, and automation interface in its designs and manufacturing. This process gives our customers the confidence in knowing their contamination control issues are resolved, freeing them to address the other challenges in process tool development and manufacturing.

S.V. Techsol specializes in:

Airflow Management

Vibration Control

Noise Control

Temperature Control

Humidity Control

Chemical Filtration

Pressure Regulation

Particle Management

CFD modeling

ESD Control

Whatever challenges you face, S.V. Techsol can support you in all facets of designing solutions to improve your processes. With our expertise and knowledge we will assist from conceptual design to OEM manufacturing.

Quality Promise

S.V. Techsol is committed to designing, manufacturing and assembling quality products that meet your specifications. All products are quality inspected after they are assembled and then tested in our class 10 cleanroom and packaged appropriately to industry standards. We view quality as the value we deliver through our products and services, taking into account customers anticipated requirements as well as industry and market changes. We are dedicated to satisfying our customers by delivering solutions that meet requirements and exceed our customers' expectations.

More Information about Quality Promise

Design Capabilities

S.V. Techsol, Inc. prides itself in offering various design capabilities to meet your custom requirements and standards. Mechanical CAD, Data Management, Design Validation, Product Documentation, ...

More Information about our Design Capabilities

                        Contact
                          |
                        Employment

© 2016 SV Techsol   |
                    Terms Of Use

                        x

Terms of Use

Unless otherwise authorized to do so, visitors may not enter areas that are restricted to the authorized users of S.V. Techsol.

                        This website is provided as a service to its visitors, including the clients of S.V. Techsol. The following terms of use are the terms of a legal agreement between you and S.V. Techsol. By accessing, browsing and/or using this website, you acknowledge you have read, understand and agree to be bound by these terms of use and to comply with applicable laws and regulations including without limitation, United States export and re-export control laws and regulations.

                        Any visit to S.V. Techsol's website pages, or use of this website, constitutes an agreement by you to abide by these terms of use. S.V. Techsol reserves the right to delete, modify or supplement the content of this website at any time for any reason without notification. You are bound by any such revisions and should therefore periodically visit this page to review the then-current terms of use.

Copyrights & Trademarks

All information contained in the S.V. Techsol website, including all website design, images, text, graphics, the selection and arrangement thereof, and software, are owned or controlled by S.V. Techsol and protected by worldwide copyright laws.

                        All trademarks, service marks, trade names, trade dress and product names whether or not appearing on this website are protected in the United States and internationally. The following trademarks S.V. Techsol and the S.V. Techsol logo are trademarks of S.V. Techsol, Inc.

DISCLAIMER

THE INFORMATION ON THIS WEBSITE IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. ALTHOUGH SV TECHSOL WILL USE REASONABLE EFFORTS TO INCLUDE UP-TO-DATE AND ACCURATE INFORMATION ON THIS WEBSITE, SV TECHSOL MAKES NO REPRESENTATIONS, WARRANTIES OR ASSURANCES THAT THE INFORMATION ON THIS WEBSITE IS OR WILL BE TIMELY, ERROR-FREE OR COMPLETE.

                        NEITHER S.V. TECHSOL OR ANY OTHER PARTY INVOLVED IN CREATING THIS WEBSITE IS LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL OR EXEMPLARY DAMAGES (INCLUDING DAMAGES FOR LOSS OF BUSINESS, LOSS OF USE, LOSS OF PROFITS, LITIGATION OR THE LIKE) ARISING OUT OF YOUR ACCESS TO, INABILITY TO ACCESS OR USE OF THIS WEBSITE, OR FROM YOUR RELIANCE ON ANY INFORMATION PROVIDED ON THIS WEBSITE, INCLUDING BUT NOT LIMITED TO AS A RESULT OF ANY BUGS OR VIRUSES THAT MAY INFECT YOUR COMPUTER PROGRAMS OR EQUIPMENT. THE FOREGOING EXCLUSION OF LOSSES AND DAMAGES SHALL APPLY WHETHER A CLAIM IS BASED ON BREACH OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY OR OTHERWISE, AND EVEN IF S.V. TECHSOL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

Links to Other Sites

S.V. Techsol may make available to the visitor links to third party websites over which S.V. Techsol has no control. S.V. Techsol has not reviewed the sites that may be linked to this website, and does not endorse and is not responsible for the content of any other sites. Other sites may be inaccurate or contain discussions regarding unapproved uses of medical devices or other products. Your linking to such sites is at your own risk, and S.V. Techsol shall not be liable for any damage or injury arising from their content or your use thereof.


text: {{brandName}}


text:
require 'rubygems'
require 'wmq'

WMQ::QueueManager.connect(:q_mgr_name=>'REID') do |qmgr|
  qmgr.open_queue(:q_name=>'TEST.QUEUE', :mode=>:input) do |queue|
    queue.each(:wait=>60000, :sync=>true, :convert=>true) do |request|
      puts "Data Received:"
      puts request.data

      begin
        reply = WMQ::Message.new
        reply.data = 'Echo back:'+request.data

        qmgr.put_to_reply_q(:message=>reply,
                            :request_message=>request, # Only replies if message type is request
                            :sync=>true)

      rescue WMQ::WMQException => exc
        # Failed to send reply, put message to the Dead Letter Queue and add a dead letter header
        p exc
        puts "Failed to reply to sender, Put to dead letter queue"
        qmgr.put_to_dead_letter_q(:message=>request,
                                  :reason=>WMQ::MQRC_UNKNOWN_REMOTE_Q_MGR,
                                  :q_name=>queue.name,
                                  :sync=>true)
        # If it fails to put to the dead letter queue, this program will terminate and
        # the changes will be "backed out". E.g. Queue Full, ...
      end
      qmgr.commit
    end
  end
  puts 'No more messages found after 60 second wait interval'
end


text:
"""
    Grafeas API

    An API to insert and retrieve annotations on cloud artifacts.  # noqa: E501

    OpenAPI spec version: v1alpha1

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import unittest

import grafeas
from grafeas.models.api_list_notes_response import ApiListNotesResponse  # noqa: E501
from grafeas.rest import ApiException

class TestApiListNotesResponse(unittest.TestCase):
    """ApiListNotesResponse unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testApiListNotesResponse(self):
        """Test ApiListNotesResponse"""
        # FIXME: construct object with mandatory attributes with example values
        # model = grafeas.models.api_list_notes_response.ApiListNotesResponse()  # noqa: E501
        pass

if __name__ == '__main__':
    unittest.main()


text:
// Copyright 2012 Fan Shi
//
// This file is part of the VBF project.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Diagnostics;

namespace VBF.Compilers.Scanners
{
    class CacheQueue<T>
    {
        private T[] m_array;
        private int m_head;
        private int m_size;
        private int m_tail;

        public CacheQueue()
        {
            m_array = new T[4];
            m_head = 0;
            m_tail = 0;
            m_size = 0;
        }

        public int Count
        {
            get
            {
                return m_size;
            }
        }

        public T this[int index]
        {
            get
            {
                Debug.Assert(index >= 0 && index < m_size);
                int indexInArray = (m_head + index) % m_array.Length;

                return m_array[indexInArray];
            }
        }

        private void SetCapacity(int capacity)
        {
            T[] destinationArray = new T[capacity];
            if (m_size > 0)
            {
                if (m_head < m_tail)
                {
                    Array.Copy(m_array, m_head, destinationArray, 0, m_size);
                }
                else
                {
                    Array.Copy(m_array, m_head, destinationArray, 0, m_array.Length - m_head);
                    Array.Copy(m_array, 0, destinationArray, m_array.Length - m_head, m_tail);
                }
            }
            m_array = destinationArray;
            m_head = 0;
            m_tail = (m_size == capacity) ? 0 : m_size;
        }

        public void Enqueue(T item)
        {
            if (m_size == m_array.Length)
            {
                int newCapacity = m_size * 2;

                SetCapacity(newCapacity);
            }

            m_array[m_tail] = item;
            m_tail = (m_tail + 1) % m_array.Length;

            m_size++;
        }

        public T Dequeue()
        {
            Debug.Assert(m_size > 0);

            T item = m_array[m_head];

            //clear reference for GC to collect it
            m_array[m_head] = default(T);

            m_head = (m_head + 1) % m_array.Length;
            m_size--;

            return item;
        }
    }
}


text:
#ifndef _APPLICATION_H
#define _APPLICATION_H

#include "system/CThread.h"
#include "game/GameSound.h"
#include "trigmath.h"

class Application : public CThread
{
public:
    static Application * instance() {
        if(!applicationInstance)
            applicationInstance = new Application();
        return applicationInstance;
    }
    static void destroyInstance() {
        if(applicationInstance) {
            delete applicationInstance;
            applicationInstance = NULL;
        }
    }

    GameSound *getBgMusic(void) const {
        return bgMusic;
    }

	void playBGM(void);
	void stopBGM(void);

    int exec(void);

    void quit(int code) {
        exitCode = code;
        exitApplication = true;
    }

private:
    Application();
    virtual ~Application();

    static Application *applicationInstance;
    static bool exitApplication;

    void executeThread(void);

    GameSound *bgMusic;
    int exitCode;
};

#endif //_APPLICATION_H


text:
package at.plechinger.scrapeql.expression;

import at.plechinger.scrapeql.ScrapeQLException;
import at.plechinger.scrapeql.context.Context;
import at.plechinger.scrapeql.relation.Relation;
import at.plechinger.scrapeql.value.RelationValue;
import at.plechinger.scrapeql.value.Value;

/**
 * Created by lukas on 04.08.15.
 */
public class RelationValueExpression implements Expression {

    private String name;

    public RelationValueExpression(String name) {
        this.name = name;
    }

    @Override
    public Value<Relation<Value>> evaluate(Context ctx) throws ScrapeQLException {
        return new RelationValue(ctx.getRelation(name));
    }
}


text:
<?php
return array (
  'APC' => 'APC',
  'Cache Backend' => 'Cache de backend',
  'Default Expire Time (in seconds)' => 'Tempo por defeito para expiração (em segundos)',
  'File' => 'Ficheiro',
  'No caching (Testing only!)' => 'Não existe cache (Apenas a testar!)',
  'PHP APC Extension missing - Type not available!' => 'PHP APC Extension em falta - Tipo não disponível!',
);


text:
Because Dadagen runs on the JVM, and SilkPerformer can execute tests using the JVM, We can call on Dadagen to
generate our test data throughout the test cycle.

.. stay tuned for the instructions


text:
//
//  XMPPChatMessage.m
//  XMPP_Project
//
//  Created by Peter Lee on 14/10/8.
//  Copyright (c) 2014年 Peter Lee. All rights reserved.
//

#import "XMPPExtendMessageObject.h"
#import "XMPPFramework.h"
#import "XMPPLogging.h"
#import "XMPPDateTimeProfiles.h"
#import "NSData+XMPP.h"
#import "NSDate+NSString.h"
#import "NSString+NSDate.h"
#import <objc/runtime.h>

#if ! __has_feature(objc_arc)
#warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif

#if DEBUG
static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR;
#else
static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR;
#endif

#define MESSAGE_SENDER_ELEMENT_NAME             @"sender"

#define MESSAGE_ID_ATTRIBUTE_NAME               @"id"
#define MESSAGE_TYPE_ATTRIBUTE_NAME             @"type"

#define MESSAGE_TIME_ATTRIBUTE_NAME             @"timestamp"
#define MESSAGE_IS_GROUP_CHAT_ATTRIBUTE_NAME    @"groupChat"

#define EXTEND_MESSAGE_TO_USER_ATTRIBUTE_NAME       @"toUser"
#define EXTEND_MESSAGE_FROM_USER_ATTRIBUTE_NAME     @"fromUser"
#define EXTEND_MESSAGE_READ_STATUS_ATTRIBUTE_NAME       @"hasBeenRead"
#define EXTEND_MESSAGE_SEND_STATUS_ATTRIBUTE_NAME       @"sendFromMe"

@implementation XMPPExtendMessageObject

#pragma mark - Public Methods

#pragma mark - class methods
+ (void)initialize {
    // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement.
    // The size of the two classes is expected to be the same.
    //
    // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug.
    // This check is here to aid future developers who may make this mistake.
    //
    // For Fearless And Experienced Objective-C Developers:
    // It may be possible to support adding instance variables to this class if you seriously need it.
    // To do so, try realloc'ing self after altering the class, and then initialize your variables.

    size_t superSize = class_getInstanceSize([NSXMLElement class]);
    size_t ourSize   = class_getInstanceSize([XMPPExtendMessageObject class]);

    if (superSize != ourSize)
    {
        XMPPLogError(@"Adding instance variables to XMPPExtendMessageObject is not currently supported!");

        [DDLog flushLog];
        exit(15);
    }
}

+ (XMPPExtendMessageObject *)xmppExtendMessageObject
{
    NSXMLElement *xmppExtendMessageElement = [NSXMLElement elementWithName:XMPP_MESSAGE_EXTEND];
    return [XMPPExtendMessageObject xmppExtendMessageObjectFromElement:xmppExtendMessageElement];
}

+ (XMPPExtendMessageObject *)xmppExtendMessageObjectFromElement:(NSXMLElement *)element
{
    object_setClass(element, [XMPPExtendMessageObject class]);
    return (XMPPExtendMessageObject *)element;
}

+ (XMPPExtendMessageObject *)xmppExtendMessageObjectFromXMPPMessage:(XMPPMessage *)message
{
    XMPPExtendMessageObject *xmppExtendMessageObject = [XMPPExtendMessageObject xmppExtendMessageObject];
    [xmppExtendMessageObject fromXMPPMessage:message];
    return xmppExtendMessageObject;
}

+ (XMPPExtendMessageObject *)xmppExtendMessageObjectCopyFromMessage:(XMPPMessage *)message
{
    return [self xmppExtendMessageObjectFromXMPPMessage:[message copy]];
}

+ (XMPPExtendMessageObject *)xmppExtendMessageObjectWithXMPPMessageCoreDataStorageObject:(XMPPMessageCoreDataStorageObject *)xmppMessageCoreDataStorageObject
{
    XMPPExtendMessageObject *object = [XMPPExtendMessageObject xmppExtendMessageObject];

    [object setUpWithXMPPMessageCoreDataStorageObject:xmppMessageCoreDataStorageObject];

    return object;
}

#pragma mark - object class method

- (instancetype)init
{
    return [[XMPPExtendMessageObject alloc] initWithType:XMPPExtendMessageTextType];
}

- (instancetype)initWithType:(XMPPExtendMessageType)messageType
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        [self createMessageID];
        [self setMessageType:messageType];
    }
    return self;
}

- (instancetype)initWithDictionary:(NSMutableDictionary *)dictionary
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        [self fromDictionary:dictionary];
    }
    return self;
}

- (instancetype)initWithXMPPMessage:(XMPPMessage *)message
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        [self fromXMPPMessage:message];
    }
    return self;
}

- (instancetype)initWithXMPPMessage:(XMPPMessage *)message  sendFromMe:(BOOL)sendFromMe hasBeenRead:(BOOL)hasBeenRead
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        self.hasBeenRead = hasBeenRead;
        self.sendFromMe = sendFromMe;
        [self fromXMPPMessage:message];
    }
    return self;
}

- (instancetype)initWithDictionary:(NSMutableDictionary *)dictionary from:(NSString *)from to:(NSString *)to hasBeenRead:(BOOL)hasBeenRead
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        self.fromUser = from;
        self.toUser = to;
        self.hasBeenRead = hasBeenRead;
        [self fromDictionary:dictionary];
    }
    return self;
}

- (instancetype)initWithXMPPMessageCoreDataStorageObject:(XMPPMessageCoreDataStorageObject *)xmppMessageCoreDataStorageObject
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        [self setUpWithXMPPMessageCoreDataStorageObject:xmppMessageCoreDataStorageObject];
    }
    return self;
}
- (instancetype)initWithFromUser:(NSString *)fromUser toUser:(NSString *)toUser type:(XMPPExtendMessageType)type sendFromMe:(BOOL)sendFromMe hasBeenRead:(NSInteger)hasBeenRead groupChat:(BOOL)groupChat sender:(NSString *)sender time:(NSDate *)time subObject:(id)subObject
{
    self = [super initWithName:XMPP_MESSAGE_EXTEND];
    if (self) {
        [self createMessageID];
        [self setMessageType:type];
        [self setFromUser:fromUser];
        [self setToUser:self.toUser];
        [self setSendFromMe:sendFromMe];
        [self setIsGroupChat:groupChat];
        [self setHasBeenRead:hasBeenRead];
        [self setSender:sender];
        [self setMessageTime:time];

        if (subObject != nil) {

            if ([subObject isKindOfClass:[XMPPTextMessageObject class]]) {
                [self setText:subObject];
            }else if ([subObject isKindOfClass:[XMPPAudioMessageObject class]]){
                [self setAudio:subObject];
            }else if ([subObject isKindOfClass:[XMPPVideoMessageObject class]]) {
                [self setVideo:subObject];
            }else if ([subObject isKindOfClass:[XMPPPictureMessageObject class]]){
                [self setPicture:subObject];
            }else if ([subObject isKindOfClass:[XMPPLocationMessageObject class]]){
                [self setLocation:subObject];
            }
        }
    }
    return self;
}
#pragma mark - switch methods
- (XMPPMessage *)toXMPPMessage
{
    NSXMLElement *info = [[self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS] copy];

    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:[XMPPJID jidWithString:self.toUser] elementID:nil child:info];

    return message;
}

//This method has no Parameter hasBeenRead,sendFromMe...
- (void)fromXMPPMessage:(XMPPMessage *)message
{
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    //If this element is existed,we should remove it brefore
    if (infoElement) {
        [self removeChildAtIndex:[[self children] indexOfObject:infoElement]];
    }
    infoElement = [[message elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS] copy];
    [self addChild:infoElement];
    [self setFromUser:message.from.bare];
    [self setToUser:message.to.bare];

}

- (void)setUpWithXMPPMessageCoreDataStorageObject:(XMPPMessageCoreDataStorageObject *)xmppMessageCoreDataStorageObject
{
    BOOL sendfromme = [xmppMessageCoreDataStorageObject.sendFromMe boolValue];
    [self setFromUser:(sendfromme ? xmppMessageCoreDataStorageObject.streamBareJidStr: xmppMessageCoreDataStorageObject.bareJidStr)];
    [self setToUser:(sendfromme ? xmppMessageCoreDataStorageObject.bareJidStr: xmppMessageCoreDataStorageObject.streamBareJidStr)];
    [self setHasBeenRead:[xmppMessageCoreDataStorageObject.hasBeenRead integerValue]];
    [self setSendFromMe:sendfromme];
    [self setMessageType:[xmppMessageCoreDataStorageObject.messageType unsignedIntegerValue]];
    [self setMessageID:xmppMessageCoreDataStorageObject.messageID];
    [self setIsGroupChat:[xmppMessageCoreDataStorageObject.isGroupChat boolValue]];
    [self setMessageTime:xmppMessageCoreDataStorageObject.messageTime];

    if (self.isGroupChat) {
        [self setSender:xmppMessageCoreDataStorageObject.additionalMessage.groupUserJid];
    }

    switch (self.messageType) {
        case XMPPExtendMessageTextType:
            self.text = [XMPPTextMessageObject xmppTextMessageObjectWithText:xmppMessageCoreDataStorageObject.additionalMessage.messageText];
            break;
        case XMPPExtendMessageAudioType:
            self.audio = [XMPPAudioMessageObject xmppAudioMessageObjectWithFilePath:xmppMessageCoreDataStorageObject.additionalMessage.filePath fileData:xmppMessageCoreDataStorageObject.additionalMessage.fileData  time:xmppMessageCoreDataStorageObject.additionalMessage.timeLength];
            break;
        case XMPPExtendMessageVideoType:
            self.video = [XMPPVideoMessageObject xmppVideoMessageObjectWithFileName:xmppMessageCoreDataStorageObject.additionalMessage.fileName
                                                                           filePath:xmppMessageCoreDataStorageObject.additionalMessage.filePath
                                                                           fileData:xmppMessageCoreDataStorageObject.additionalMessage.fileData
                                                                               time:xmppMessageCoreDataStorageObject.additionalMessage.timeLength];
            break;
        case XMPPExtendMessagePictureType:
            self.picture = [XMPPPictureMessageObject xmppPictureMessageObjectWithFileName:xmppMessageCoreDataStorageObject.additionalMessage.fileName
                                                                                filePath:xmppMessageCoreDataStorageObject.additionalMessage.filePath
                                                                                fileData:xmppMessageCoreDataStorageObject.additionalMessage.fileData
                                                                              aspectRatio:xmppMessageCoreDataStorageObject.additionalMessage.aspectRatio];
            break;
        case XMPPExtendMessagePositionType:
            self.location = [XMPPLocationMessageObject xmppLocationMessageObjectWithLongitude:xmppMessageCoreDataStorageObject.additionalMessage.longitude
                                                                                latitude:xmppMessageCoreDataStorageObject.additionalMessage.latitude
                                                                                content:xmppMessageCoreDataStorageObject.additionalMessage.messageText];
            break;
        case XMPPExtendMessageControlType:

            break;
        case XMPPExtendMessageMediaRequestType:

            break;

        default:
            break;
    }

}

 -(NSMutableDictionary *)toDictionary
 {
     NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
     if (self.messageID)
         [dictionary setObject:self.messageID forKey:@"messageID"];
     if (self.messageTime)
         [dictionary setObject:self.messageTime forKey:@"messageTime"];
     if (self.sender) {
         [dictionary setObject:self.messageTime forKey:@"sender"];
     }
     if (self.fromUser) {
         [dictionary setObject:self.messageTime forKey:@"fromUser"];
     }
     if (self.toUser) {
         [dictionary setObject:self.messageTime forKey:@"toUser"];
     }
     if (self.audio) {
         [dictionary setObject:self.audio forKey:@"audio"];
     }
     if (self.text) {
         [dictionary setObject:self.text forKey:@"text"];
     }
     if (self.video) {
         [dictionary setObject:self.video forKey:@"video"];
     }
     if (self.picture) {
         [dictionary setObject:self.picture forKey:@"picture"];
     }
     if (self.location) {
         [dictionary setObject:self.location forKey:@"location"];
     }

     //TODO:text here
     [dictionary setObject:[NSNumber numberWithInteger:self.hasBeenRead] forKey:@"hasBeenRead"];
     [dictionary setObject:[NSNumber numberWithBool:self.sendFromMe] forKey:@"sendFromMe"];
     [dictionary setObject:[NSNumber numberWithBool:self.isGroupChat] forKey:@"isGroupChat"];
     [dictionary setObject:[NSNumber numberWithUnsignedInteger:self.messageType] forKey:@"messageType"];

     return dictionary;
}

-(void)fromDictionary:(NSMutableDictionary*)message
{
    self.messageID = [message objectForKey:@"messageID"];
    self.messageTime = [message objectForKey:@"sendTime"];
    self.sender = [message objectForKey:@"sender"];
    self.fromUser = [message objectForKey:@"fromUser"];
    self.toUser = [message objectForKey:@"toUser"];
    self.audio = [message objectForKey:@"audio"];
    self.text = [message objectForKey:@"text"];
    self.video = [message objectForKey:@"video"];
    self.picture = [message objectForKey:@"picture"];
    self.location = [message objectForKey:@"location"];

    self.hasBeenRead = [(NSNumber *)[message objectForKey:@"hasBeenRead"] integerValue];
    self.sendFromMe = [(NSNumber *)[message objectForKey:@"sendFromMe"] boolValue];
    self.isGroupChat = [(NSNumber *)[message objectForKey:@"isGroupChat"] boolValue];
    self.messageType = [(NSNumber *)[message objectForKey:@"messageType"] unsignedIntegerValue];
}

- (NSMutableDictionary *)toDictionaryWithActive:(BOOL)active
{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    NSString *bareJidStr = self.sendFromMe ? self.toUser:self.fromUser;
    NSNumber *unReadMessageCount = [NSNumber numberWithBool:(self.sendFromMe ? NO:!active)];//if read is 0(NO), unread is 1(YES)
    NSNumber *hasBeenRead = [NSNumber numberWithBool:(self.sendFromMe ? ([unReadMessageCount integerValue] > 0):!([unReadMessageCount integerValue] > 0))];
    NSNumber *isGroupChat = [NSNumber numberWithBool:self.isGroupChat];

    XMPPAdditionalCoreDataMessageObject *xmppAdditionalCoreDataMessageObject = [[XMPPAdditionalCoreDataMessageObject alloc] initWithInfoXMLElement:[self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS]];

    if (bareJidStr) [dictionary setObject:bareJidStr forKey:@"bareJidStr"];

    if (self.messageTime) [dictionary setObject:self.messageTime forKey:@"messageTime"];

    if (xmppAdditionalCoreDataMessageObject) [dictionary setObject:xmppAdditionalCoreDataMessageObject forKey:@"additionalMessage"];

    [dictionary setObject:[NSNumber numberWithBool:self.sendFromMe] forKey:@"sendFromMe"];
    [dictionary setObject:[NSNumber numberWithUnsignedInteger:self.messageType] forKey:@"messageType"];

    //The readed message's hasBeenRead is 1,unread is 0
    //When is sent from me,we should note that this message is been sent failed as default 0
    //After being sent succeed,we should modify this value into 1
    [dictionary setObject:hasBeenRead forKey:@"hasBeenRead"];

    //If the unread message count is equal to zero,we will know that this message has been readed
    [dictionary setObject:unReadMessageCount forKey:@"unReadMessageCount"];

    [dictionary setObject:self.messageID forKey:@"messageID"];
    [dictionary setObject:isGroupChat forKey:@"isGroupChat"];

    return dictionary;
}

#pragma mark - tools methods
-(void)createMessageID
{
    self.messageID = [self UUIDString];
    self.sendFromMe = YES;
}

/**
 *  Get the unique string in system
 *
 *  @return The unique string we want
 */
-(NSString *)UUIDString
{
    CFUUIDRef uuidRef =CFUUIDCreate(NULL);

    CFStringRef uuidStringRef =CFUUIDCreateString(NULL, uuidRef);

    CFRelease(uuidRef);

    return (__bridge NSString *)uuidStringRef;
}

#pragma mark - Setters and getters

- (NSString *)toUser
{
    return [self attributeStringValueForName:EXTEND_MESSAGE_TO_USER_ATTRIBUTE_NAME];
}

- (void)setToUser:(NSString *)toUser
{
    if (toUser) {
        [self addAttributeWithName:EXTEND_MESSAGE_TO_USER_ATTRIBUTE_NAME stringValue:toUser];
    }
}

- (NSString *)fromUser
{
    return [self attributeStringValueForName:EXTEND_MESSAGE_FROM_USER_ATTRIBUTE_NAME];
}

- (void)setFromUser:(NSString *)fromUser
{
    if (fromUser) {
        [self addAttributeWithName:EXTEND_MESSAGE_FROM_USER_ATTRIBUTE_NAME stringValue:fromUser];
    }
}

- (NSInteger)hasBeenRead
{
    return [self attributeIntegerValueForName:EXTEND_MESSAGE_READ_STATUS_ATTRIBUTE_NAME];
}

- (void)setHasBeenRead:(NSInteger)hasBeenRead
{
    [self addAttributeWithName:EXTEND_MESSAGE_READ_STATUS_ATTRIBUTE_NAME integerValue:hasBeenRead];
}

- (BOOL)sendFromMe
{
    return [self attributeBoolValueForName:EXTEND_MESSAGE_SEND_STATUS_ATTRIBUTE_NAME];
}

- (void)setSendFromMe:(BOOL)sendFromMe
{
    [self addAttributeWithName:EXTEND_MESSAGE_SEND_STATUS_ATTRIBUTE_NAME boolValue:sendFromMe];
}

//The info element
- (NSUInteger)messageType
{
    NSUInteger result = 0;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [infoElement attributeUnsignedIntegerValueForName:MESSAGE_TYPE_ATTRIBUTE_NAME];

    }

    return result;
}

- (void)setMessageType:(NSUInteger)messageType
{
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    //If the info element is already existed,wo should add the value to it
    if (infoElement) {
        [infoElement addAttributeWithName:MESSAGE_TYPE_ATTRIBUTE_NAME unsignedIntegerValue:messageType];
        return;
    }
    //Otherwise,we should create a new info element
    infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    [infoElement addAttributeWithName:MESSAGE_TYPE_ATTRIBUTE_NAME unsignedIntegerValue:messageType];
    [self addChild:infoElement];
}

- (NSString *)messageID
{
    NSString *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [infoElement attributeStringValueForName:MESSAGE_ID_ATTRIBUTE_NAME];
    }

    return result;
}

- (void)setMessageID:(NSString *)messageID
{
    if (messageID) {
        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
        //If the info element is already existed,wo should add the value to it
        if (infoElement) {
            [infoElement addAttributeWithName:MESSAGE_ID_ATTRIBUTE_NAME stringValue:messageID];
            return;
        }
        //Otherwise,we should create a new info element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
        [infoElement addAttributeWithName:MESSAGE_ID_ATTRIBUTE_NAME stringValue:messageID];
        [self addChild:infoElement];
    }
}

- (NSDate *)messageTime
{
    NSDate *result = nil;

    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [[infoElement attributeStringValueForName:MESSAGE_TIME_ATTRIBUTE_NAME] UTCStringToLocalDate];//UTCStringToLocalDate
    }

    return result;
}

//The messageTime must been a local time
- (void)setMessageTime:(NSDate *)messageTime
{
    if (messageTime) {
        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
        //If the info element is already existed,wo should add the value to it
        if (infoElement) {
            [infoElement addAttributeWithName:MESSAGE_TIME_ATTRIBUTE_NAME stringValue:[messageTime LocalDateToUTCString]];
            return;
        }
        //Otherwise,we should create a new info element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
        [infoElement addAttributeWithName:MESSAGE_ID_ATTRIBUTE_NAME stringValue:[messageTime DateToString]];
        [self addChild:infoElement];
    }
}

- (BOOL)isGroupChat
{
    BOOL result = NO;

    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [infoElement attributeBoolValueForName:MESSAGE_IS_GROUP_CHAT_ATTRIBUTE_NAME];
    }

    return result;
}

- (void)setIsGroupChat:(BOOL)isGroupChat
{
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    //If the info element is already existed,wo should add the value to it
    if (infoElement) {
        [infoElement addAttributeWithName:MESSAGE_IS_GROUP_CHAT_ATTRIBUTE_NAME boolValue:isGroupChat];
        return;
    }
    //Otherwise,we should create a new info element
    infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    [infoElement addAttributeWithName:MESSAGE_IS_GROUP_CHAT_ATTRIBUTE_NAME boolValue:isGroupChat];
    [self addChild:infoElement];
}

- (NSString *)sender
{
    NSString *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [[infoElement elementForName:MESSAGE_SENDER_ELEMENT_NAME] stringValue];
    }

    return result;
}

- (void)setSender:(NSString *)sender
{
    if (sender) {
        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
        //If the info element is already existed,wo should add the value to it
        if (infoElement) {

            NSXMLElement *senderElement = [infoElement elementForName:MESSAGE_SENDER_ELEMENT_NAME];
            if (senderElement) {
                [infoElement removeChildAtIndex:[[infoElement children] indexOfObject:senderElement]];
            }

            senderElement = [NSXMLElement elementWithName:MESSAGE_SENDER_ELEMENT_NAME];
            [senderElement setStringValue:sender];

            [infoElement addChild:senderElement];

            return;
        }
        //Otherwise,we should create a new info element
        //init a new info XML element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        //init a new sender xml element
        NSXMLElement *senderElement = [NSXMLElement elementWithName:MESSAGE_SENDER_ELEMENT_NAME];
        [senderElement setStringValue:sender];

        [infoElement addChild:senderElement];
        [self addChild:infoElement];
    }
}

- (XMPPAudioMessageObject *)audio
{
    XMPPAudioMessageObject *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [XMPPAudioMessageObject xmppAudioMessageObjectFromElement:[infoElement elementForName:AUDIO_ELEMENT_NAME]];
    }

    return result;
}

- (void)setAudio:(XMPPAudioMessageObject *)audio
{
    if (audio) {

        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        //If the info element is already existed,wo should add the value to it
        if (infoElement) {

            NSXMLElement *audioElement = [infoElement elementForName:AUDIO_ELEMENT_NAME];

            if (audioElement) {
                [infoElement removeChildAtIndex:[[infoElement children] indexOfObject:audioElement]];
            }

            [infoElement addChild:audio];

            return;
        }
        //Otherwise,we should create a new info element
        //init a new info XML element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        [infoElement addChild:audio];
        [self addChild:infoElement];
    }
}
- (XMPPTextMessageObject *)text
{
    XMPPTextMessageObject *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [XMPPTextMessageObject xmppTextMessageObjectFromElement:[infoElement elementForName:TEXT_ELEMENT_NAME]];
    }

    return result;
}

- (void)setText:(XMPPTextMessageObject *)text
{
    if (text) {

        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        //If the info element is already existed,wo should add the value to it
        if (infoElement) {

            NSXMLElement *textElement = [infoElement elementForName:TEXT_ELEMENT_NAME];

            if (textElement) {
                [infoElement removeChildAtIndex:[[infoElement children] indexOfObject:textElement]];
            }

            [infoElement addChild:text];

            return;
        }
        //Otherwise,we should create a new info element
        //init a new info XML element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        [infoElement addChild:text];
        [self addChild:infoElement];
    }
}

- (XMPPVideoMessageObject *)video
{
    XMPPVideoMessageObject *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [XMPPVideoMessageObject xmppVideoMessageObjectFromElement:[infoElement elementForName:VIDEO_ELEMENT_NAME]];
    }

    return result;
}

- (void)setVideo:(XMPPVideoMessageObject *)video
{
    if (video) {

        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        //If the info element is already existed,wo should add the value to it
        if (infoElement) {

            NSXMLElement *videoElement = [infoElement elementForName:VIDEO_ELEMENT_NAME];

            if (videoElement) {
                [infoElement removeChildAtIndex:[[infoElement children] indexOfObject:videoElement]];
            }

            [infoElement addChild:video];

            return;
        }
        //Otherwise,we should create a new info element
        //init a new info XML element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        [infoElement addChild:video];
        [self addChild:infoElement];
    }
}

- (XMPPPictureMessageObject *)picture
{
    XMPPPictureMessageObject *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [XMPPPictureMessageObject xmppPictureMessageObjectFromElement:[infoElement elementForName:PICTURE_ELEMENT_NAME]];
    }

    return result;
}

- (void)setPicture:(XMPPPictureMessageObject *)picture
{
    if (picture) {

        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        //If the info element is already existed,wo should add the value to it
        if (infoElement) {

            NSXMLElement *pictureElement = [infoElement elementForName:PICTURE_ELEMENT_NAME];

            if (pictureElement) {
                [infoElement removeChildAtIndex:[[infoElement children] indexOfObject:pictureElement]];
            }

            [infoElement addChild:picture];

            return;
        }
        //Otherwise,we should create a new info element
        //init a new info XML element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        [infoElement addChild:picture];
        [self addChild:infoElement];
    }
}

- (XMPPLocationMessageObject *)location
{
    XMPPLocationMessageObject *result = nil;
    NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];
    if (infoElement != nil) {

        result = [XMPPLocationMessageObject xmppLocationMessageObjectFromElement:[infoElement elementForName:LOCATION_ELEMENT_NAME]];
    }

    return result;
}

- (void)setLocation:(XMPPLocationMessageObject *)location
{
    if (location) {

        NSXMLElement *infoElement = [self elementForName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        //If the info element is already existed,wo should add the value to it
        if (infoElement) {

            NSXMLElement *locationElement = [infoElement elementForName:LOCATION_ELEMENT_NAME];

            if (locationElement) {
                [infoElement removeChildAtIndex:[[infoElement children] indexOfObject:locationElement]];
            }

            [infoElement addChild:location];

            return;
        }
        //Otherwise,we should create a new info element
        //init a new info XML element
        infoElement = [NSXMLElement elementWithName:MESSAGE_ELEMENT_NAME xmlns:MESSAGE_ELEMENT_XMLNS];

        [infoElement addChild:location];
        [self addChild:infoElement];
    }
}

@end


text:
"""Device, context and memory management on CuPy.

Chainer uses CuPy (with very thin wrapper) to exploit the speed of GPU
computation. Following modules and classes are imported to :mod:`cuda`
module for convenience (refer to this table when reading chainer's source
codes).

============================ =================================
 imported name                original name
============================ =================================
 ``chainer.cuda.cupy``        :mod:`cupy`
 ``chainer.cuda.ndarray``     :mod:`cupy.ndarray`
 ``chainer.cuda.cupy.cuda``   :mod:`cupy.cuda`
 ``chainer.cuda.Device``      :mod:`cupy.cuda.Device`
 ``chainer.cuda.Event``       :mod:`cupy.cuda.Event`
 ``chainer.cuda.Stream``      :mod:`cupy.cuda.Stream`
============================ =================================

Chainer replaces the default allocator of CuPy by its memory pool
implementation. It enables us to reuse the device memory over multiple
forward/backward computations, and temporary arrays for consecutive elementwise
operations.
"""

import functools
import os
import warnings

import numpy

available = False
cudnn_enabled = False

try:
    import cupy
    import cupy.cuda
    import cupy.cuda.cublas

    cuda = cupy.cuda
    cublas = cuda.cublas

    ndarray = cupy.ndarray
    Device = cuda.Device
    Event = cuda.Event
    Stream = cuda.Stream

    available = True
except Exception as e:
    _resolution_error = e

    class ndarray(object):
        pass  # for type testing

if available:
    try:
        import cupy.cudnn
        cudnn = cupy.cudnn
        cudnn_enabled = int(os.environ.get('CHAINER_CUDNN', '1')) != 0
    except Exception as e:
        _resolution_error = e

def _check_cuda_available():
    if not available:
        global _resolution_error
        msg = 'CUDA environment is not correctly set up.\n'
        msg += str(_resolution_error)
        raise RuntimeError(msg)

class DummyDeviceType(object):

    """Dummy device class that does nothing with cupy.cuda.Device interface.

    This class is used to represent CPU device.

    """
    def __int__(self):
        return -1

    def __enter__(self):
        return self

    def __exit__(self, *args):
        pass

    def use(self):
        pass

    def synchronize(self):
        pass

    def __eq__(self, other):
        return isinstance(other, DummyDevice)

    def __ne__(self, other):
        return not (self == other)

DummyDevice = DummyDeviceType()

# ------------------------------------------------------------------------------
# Global states
# ------------------------------------------------------------------------------
if available:
    cuda.set_allocator(cuda.MemoryPool().malloc)

# ------------------------------------------------------------------------------
# Global states
# ------------------------------------------------------------------------------
def get_device(*args):
    """Gets the device from an ID integer or an array object.

    This is a convenient utility to select a correct device if the type of
    ``arg`` is unknown (i.e., one can use this function on arrays that may be
    on CPU or GPU). The returned device object supports the context management
    protocol of Python for the *with* statement.

    Args:
        args: Values to specify a GPU device. :class:`numpy.ndarray` objects
            are skipped. If all arguments are numpy.ndarray objects, it returns
            a dummy device object. Otherwise, the first non-numpy object is
            used to select a device. If it is a :class:`cupy.ndarray` object,
            its device is returned. Otherwise, the argument is passed to the
            initializer of :class:`~cupy.cuda.Device` and it is returned.

    Returns:
        Device object specified by given ``args``.

    .. seealso::
       See :class:`cupy.cuda.Device` for the device selection not by arrays.

    """
    for arg in args:
        if arg is None:
            continue
        if not isinstance(arg, numpy.ndarray):
            _check_cuda_available()
            if isinstance(arg, cupy.ndarray):
                return arg.device
            else:
                return Device(arg)

    return DummyDevice

# ------------------------------------------------------------------------------
# cupy.ndarray allocation and copy
# ------------------------------------------------------------------------------

def to_gpu(array, device=None, stream=None):
    """Copies the given CPU array to specified device.

    Args:
        array: Array to be sent to GPU.
        device: Device specifier.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: Array on GPU.

        If ``array`` is already on GPU, then this function just returns
        ``array`` without performing any copy. Note that this function does not
        copy cupy.ndarray into specified device.

    """
    _check_cuda_available()
    assert stream is None  # TODO(beam2d): FIX IT
    with get_device(device):
        return cupy.asarray(array)

def to_cpu(array, stream=None):
    """Copies the given GPU array to host CPU.

    Args:
        array: Array to be sent to GPU.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        numpy.ndarray: Array on CPU.

        If given ``array`` is already on CPU, then this function just returns
        ``array`` without performing any copy.

    """
    assert stream is None  # TODO(beam2d): FIX IT
    if isinstance(array, ndarray):
        return array.get()
    else:
        return array

def empty(shape, dtype=numpy.float32):
    """Creates an uninitialized cupy.ndarray object.

    Args:
        shape (tuple of ints): The shape of array.
        dtype (numpy.dtype): Element type.

    Returns:
        cupy.ndarray: Uninitialized GPU array allocated by the memory pool.

    """
    warnings.warn(
        'chainer.cuda.empty is deprecated. Use cupy.empty instead.',
        DeprecationWarning)
    _check_cuda_available()
    return cupy.empty(shape, dtype)

def full(shape, fill_value, dtype=numpy.float32, stream=None):
    """Creates a constant-filled cupy.ndarray object.

    Args:
        shape (tuple of ints): The shape of array.
        fill_value: Constant to fill the array by.
        dtype (numpy.dtype): Element type.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: Constant-filled GPU array allocated by the memory pool.

    """
    warnings.warn(
        'chainer.cuda.full is deprecated. Use cupy.full instead.',
        DeprecationWarning)
    _check_cuda_available()
    assert stream is None
    return cupy.full(shape, fill_value, dtype=dtype)

def zeros(shape, dtype=numpy.float32, stream=None):
    """Creates a zero-filled cupy.ndarray object.

    This function is equivalent to ``full(shape, 0, dtype, stream)``.

    """
    warnings.warn(
        'chainer.cuda.zeros is deprecated. Use cupy.zeros instead.',
        DeprecationWarning)
    _check_cuda_available()
    assert stream is None
    return cupy.zeros(shape, dtype=dtype)

def ones(shape, dtype=numpy.float32, stream=None):
    """Creates a zero-filled cupy.ndarray object.

    This function is equivalent to ``full(shape, 1, dtype, stream)``.

    """
    warnings.warn(
        'chainer.cuda.ones is deprecated. Use cupy.ones instead.',
        DeprecationWarning)
    _check_cuda_available()
    assert stream is None
    return cupy.ones(shape, dtype=dtype)

def empty_like(array):
    """Creates an uninitialized GPU array like the given one.

    Args:
        array (cupy.ndarray or numpy.ndarray): Base array.

    Returns:
        cupy.ndarray: GPU array of the same shape and dtype as `array`.

    """
    warnings.warn(
        'chainer.cuda.empty_like is deprecated. Use cupy.empty_like instead.',
        DeprecationWarning)
    _check_cuda_available()
    if isinstance(array, cupy.ndarray):
        return cupy.empty_like(array)
    return cupy.empty(array.shape, dtype=array.dtype)

def full_like(array, fill_value, stream=None):
    """Creates a constant-filled cupy.ndarray object like the given array.

    Args:
        array (cupy.ndarray or numpy.ndarray): Base array.
        fill_value: Constant value to fill the array by.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: Constant-filled array.

    """
    warnings.warn(
        'chainer.cuda.full_like is deprecated. Use cupy.full_like instead.',
        DeprecationWarning)
    _check_cuda_available()
    assert stream is None
    if isinstance(array, cupy.ndarray):
        return cupy.full_like(array, fill_value)
    return cupy.full(array.shape, fill_value, dtype=array.dtype)

def zeros_like(array, stream=None):
    """Creates a zero-filled cupy.ndarray object like the given array.

    Args:
        array (cupy.ndarray or numpy.ndarray): Base array.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: Zero-filled array.

    """
    warnings.warn(
        'chainer.cuda.zeros_like is deprecated. Use cupy.zeros_like instead.',
        DeprecationWarning)
    _check_cuda_available()
    assert stream is None
    if isinstance(array, cupy.ndarray):
        return cupy.zeros_like(array)
    return cupy.zeros(array.shape, dtype=array.dtype)

def ones_like(array, stream=None):
    """Creates a one-filled cupy.ndarray object like the given array.

    Args:
        array (cupy.ndarray or numpy.ndarray): Base array.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: One-filled array.

    """
    warnings.warn(
        'chainer.cuda.ones_like is deprecated. Use cupy.ones_like instead.',
        DeprecationWarning)
    _check_cuda_available()
    assert stream is None
    if isinstance(array, cupy.ndarray):
        return cupy.ones_like(array)
    return cupy.ones(array.shape, dtype=array.dtype)

def copy(array, out=None, out_device=None, stream=None):
    """Copies a cupy.ndarray object using the default stream.

    This function can copy the device array to the destination array on another
    device.

    Args:
        array (cupy.ndarray): Array to be copied.
        out (cupy.ndarray): Destination array.
            If it is not ``None``, then ``out_device`` argument is ignored.
        out_device: Destination device specifier. Actual device object is
            obtained by passing this value to :func:`get_device`.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: Copied array.

        If ``out`` is not specified, then the array is allocated on the device
        specified by ``out_device`` argument.

    """
    _check_cuda_available()
    assert stream is None  # TODO(beam2d): FIX IT

    if out is None:
        if out_device is None:
            out_device = array
        with get_device(out_device):
            out = cupy.empty_like(array)

    with get_device(array):
        cupy.copyto(out, array)

    return out

# ------------------------------------------------------------------------------
# Function result memoization
# ------------------------------------------------------------------------------
def memoize(for_each_device=False):
    """Makes a function memoizing the result for each argument and device.

    This is a similar version of :func:`cupy.memoize`. The difference is that
    this function can be used in the global scope even if CUDA is not
    available. In such case, this function does nothing.

    .. note::
       This decorator acts as a dummy if CUDA is not available. It cannot be
       used for general purpose memoization even if ``for_each_device`` is set
       to False.

    """
    if available:
        return cupy.memoize(for_each_device)

    def dummy_decorator(f):
        @functools.wraps(f)
        def ret(*args, **kwargs):
            return f(*args, **kwargs)
        return ret
    return dummy_decorator

# ------------------------------------------------------------------------------
# Kernel definition utility
# ------------------------------------------------------------------------------
@memoize(for_each_device=True)
def elementwise(in_params, out_params, operation, name, **kwargs):
    """Creates an elementwise kernel function.

    This function uses :func:`~chainer.cuda.memoize` to cache the
    kernel object, i.e. the resulting kernel object is cached for each argument
    combination and CUDA device.

    The arguments are the same as those for
    :class:`cupy.ElementwiseKernel`, except that the ``name`` argument is
    mandatory.

    """
    _check_cuda_available()
    return cupy.ElementwiseKernel(
        in_params, out_params, operation, name, **kwargs)

@memoize(for_each_device=True)
def reduce(in_params, out_params, map_expr, reduce_expr, post_map_expr,
           identity, name,  **kwargs):
    """Creates a global reduction kernel function.

    This function uses :func:`~chainer.cuda.memoize` to cache the resulting
    kernel object, i.e. the resulting kernel object is cached for each argument
    combination and CUDA device.

    The arguments are the same as those for
    :class:`cupy.ReductionKernel`, except that the ``name`` argument is
    mandatory.

    """
    _check_cuda_available()
    return cupy.ReductionKernel(
        in_params, out_params, map_expr, reduce_expr, post_map_expr,
        identity, name, **kwargs)

# ------------------------------------------------------------------------------
# numpy/cupy compatible coding
# ------------------------------------------------------------------------------
def get_array_module(*args):
    """Gets an appropriate one from :mod:`numpy` or :mod:`cupy`.

    This is almost equivalent to :func:`cupy.get_array_module`. The only
    difference is that this function can be used even if CUDA is not available.

    Args:
        args: Values to determine whether NumPy or CuPy should be used.

    Returns:
        module: :mod:`cupy` or :mod:`numpy` is returned based on the types of
        the arguments.

    """
    if available:
        return cupy.get_array_module(*args)
    else:
        return numpy