text:
==========
JavaScript
==========

.. sectionauthor:: `jryannel <https://github.com/jryannel>`_

.. issues:: ch14

.. note::

    Last Build: |today|

    The source code for this chapter can be found in the `assets folder <../../assets>`_.

JavaScript is the lingua-franca on web client development. It also starts to get traction on web server development mainly by node js. As such it is well suited add an imperative language onto the side of declarative QML language. QML itself as a declarative language is used to express the user interface hierachy but is limited to express operational code. Sometimes you need a way to express operations, here JavaScript comes into play.

.. note::

  There is an open question in the Qt community about the right mixture about QML/JS/QtC++ in a modern Qt application. The commonly agreed recommended mixture is to limit the JS part of your application to a minimum and do your business logic inside QtC++ and the UI logic inside QML/JS.

  This book pushes the boundaries, which is not always the right mix for a product development and not for everyone. It is important to follow your team skills and your personal taste. In doubt follow the recommendation.

Here a short example how JS looks like, misxtured in QML::

  Button {
    width: 200
    height: 300
    property bool checked: false
    text: "Click to toggle"

    // JS function
    function doToggle() {
      checked = !checked
    }

    onTriggered: {
      // this is also JavaScript
      doToggle();
      console.log('checked: ' + checked)
    }
  }

So JavaScript can come in many places inside QML as a standalone JS function, as a JS module and it can be on every right side of a property binding.

::

  import "util.js" as Util // import a pure JS module

  Button {
    width: 200
    height: width*2 // JS on the right side of property binding

    // standalone function (not really useful)
    function log(msg) {
      console.log("Button> " + msg);
    }

    onTriggered: {
      // this is JavaScript
      log();
      Qt.quit();
    }
  }

Within QML you declare the user interface, with JavaScript you make it functional. So how much JavaScript should you write? It depends on your style and how familar you are with JS development. JS is a loosely typed language, which makes it difficult to spot typ defects. Also functions except all argument variations, which can be a very nasty bug to spot. The way to spot defects is rigorous unit testing or acceptance testing. So if you develop real logic (not some glue lines of code) in JS you should really start using the test-first approach. In general mixed teams (Qt/C++ and QML/JS) are very successfull when they minimize the amount of JS in the frontend as the domain logic and do the heavy lifting in Qt C++ in the backend. The backend should then be rigorous unut tested so that the frontend developers can trust thec ode and focus on all these little user interface requirements.

.. note::

  In general: backend developers are functional driven and frontend developers are user story driven.

Browser/HTML vs QtQuick/QML
===========================

The browser is the runtime to render HTML and execute the Javascript associated with the HTML. Nowadays modern web applications contain much more JavaScript then HTML. The Javascript inside the browser is a standard ECMAScript environment with some browser additions. A typical JS environment inside the browser knows the ``window`` object to access the browser window. There are also the basic DOM selectors which are used by jQuery to provide the CSS selectors. Additional the is a ``setTimeout`` function to call a function after a certain time. Besides these the JS is standard JavaScript environment similar to QML/JS.

What is also different is where JS can appear inside HTML and QML. in HTML you can only add JS on event handlers (e.g. page loaded, mouse pressed). For example your JS initializes normally in page load, which is comparable to ``Component.onCompleted`` in QML. For example you can not use JS for property bindings (at least not directly, AngularJS enhances the DOM tree to allow these, but this is far away from standard HTML).

So in QML JS is much more a fist-class citizen and much deeper integrated into the QML render tree. Which makes the syntax much more readable. Besides this people which have developed HTML/JS applications will feel at home inside QML/JS.

The Language
============

This chapter will not give you a general introducton to JavaScript. There are other books out there or for a general introduction ot JavaScript, please visit this great side on `Mozilla Developer Network <https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript>`_.

On the surface javascript is a very common language and not differs a lot from other languages::

  function countDown() {
    for(var i=0; i<10; i++) {
      console.log('index: ' + i)
    }
  }

  function countDown2() {
    var i=10;
    while( i>0 ) {
      i--;
    }
  }

But be warned JS has function scope and not block scope as in C++ (see `Functions and function scope <https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions_and_function_scope>`_).

The statements ``if ... else``, ``break``, ``continue`` also work as expected. The switch case can also switch about other types then just integer values::

  function getAge(name) {
    // switch over a string
    switch(name) {
    case "father":
      return 58;
    case "mother":
      return 56;
    }
    return unknown;
  }

JS knows several values which can be false, e.g. ``false``, 0, "", ``undefined``, ``null``). For example a function returns by default ``undefined``. To test for false use the '===' identity operator. The '==' equality operator will do type conversion to test for equality. If possible use the faster and better '===' strict equality operator which will test for identity (see `Comparison operators <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators>`_.

Under the hood javascript has its own ways of doing things. For example arrays::

  function doIt() {
    var a = [] // empty arrays
    a.push(10) // addend number on arrays
    a.push("Monkey") // append string on arrays
    console.log(a.length) // prints 2
    a[0] // returns 10
    a[1] // returns Monkey
    a[2] // returns undefined
    a[99] = "String" // a valid assignment
    console.log(a.length) // prints 100
    a[98] // contains the value undefined
  }

Also for people coming from C++ or Java which are used to a OO language JS just works different. JS is not purely an OO language it is a so called prototype based language. Each object has a prototype object. An object is created based on this prototype object. Please read more about this in the book `Javascript the Good Parts by Douglas Crockford <http://javascript.crockford.com>`_ or watch the video below.

.. youtube:: hQVTIJBZook

To test some small JS snippets you can use the online `JS Console <http://jsconsole.com>`_ or just build a little piece of QML code::

  import QtQuick 2.0

  Item {
    function runJS() {
      console.log("Your JS code goes here");
    }
    Component.onCompleted: {
      runJS();
    }
  }

JS Objects
==========

While working with JS there are some objects and methods which are more frequently used. This is a small collection of them.

* ``Math.floor(v)``, ``Math.ceil(v)``, ``Math.round(v)`` - largest, smallest, rounded integer from float
* ``Math.random()`` - create a random number between 0 and 1
* ``Object.keys(o)`` - get keys from object (including QObject)
* ``JSON.parse(s)``, ``JSON.stringify(o)`` - conversion between JS object and JSON string
* ``Number.toFixed(p)`` - fixed precision float
* ``Date`` - Date manipulation

You can find them also at: `JavaScript reference <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference>`_

Here some small and limited examples how to use JS with QML. They should give you an idea how you can use JS inside QML

.. rubric:: Print all keys from QML Item

::

  Item {
    id: root
    Component.onCompleted: {
      var keys = Object.keys(root);
      for(var i=0; i<keys.length; i++) {
        var key = keys[i];
        // prints all properties, signals, functions from object
        console.log(key + ' : ' + root[key]);
      }
    }
  }

.. rubric:: Parse an object to a JSON string and back

::

  Item {
    property var obj: {
      key: 'value'
    }

    Component.onCompleted: {
      var data = JSON.stringify(obj);
      console.log(data);
      var obj = JSON.parse(data);
      console.log(obj.key); // > 'value'
    }
  }

.. rubric:: Current Date

::

  Item {
    Timer {
      id: timeUpdater
      interval: 100
      running: true
      repeat: true
      onTriggered: {
        var d = new Date();
        console.log(d.getSeconds());
      }
    }
  }

.. rubric:: Call a function by name

::

  Item {
    id: root

    function doIt() {
      console.log("doIt()")
    }

    Component.onCompleted: {
      // Call using function execution
      root["doIt"]();
      var fn = root["doIt"];
      // Call using JS call method (could pass in a custom this object and arguments)
      fn.call()
    }
  }

Creating a JS Console
=====================

As a little example we will create a JS console. We need an input field where the user can enter its JS expressions and ideally a list of output results. As this should more look like a desktop application we use the QtQuick Controls module.

.. note::

  A JS console inside your next project can be really benefitical for testing. Enhanced with a Quake-Terminal effect it is also good to impress customers. To use it wisely you need to control the scope the JS console evaluates in, e.g. the current visible screen, the main data model, a singleton core object or all together.

.. image:: assets/jsconsole.png

We use Qt Creator to create a Qt Quick UI project using QtQuick controls. We call the project `JSConsole`. After the wizard has finished we have already a basic structure for the application with an application window and a menu to exit the application.

For the input we use a TextField and a Button to send the input for evaluation. The result of the expression evaluation is displayed using a ListView with a ListModel as the model and two labels to display the expression and the evaluated result.

::

  // part of JSConsole.qml
  ApplicationWindow {
    id: root

    ...

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 9
        RowLayout {
            Layout.fillWidth: true
            TextField {
                id: input
                Layout.fillWidth: true
                focus: true
                onAccepted: {
                    // call our evaluation function on root
                    root.jsCall(input.text)
                }
            }
            Button {
                text: qsTr("Send")
                onClicked: {
                    // call our evaluation function on root
                    root.jsCall(input.text)
                }
            }
        }
        Item {
            Layout.fillWidth: true
            Layout.fillHeight: true
            Rectangle {
                anchors.fill: parent
                color: '#333'
                border.color: Qt.darker(color)
                opacity: 0.2
                radius: 2
            }

            ScrollView {
                id: scrollView
                anchors.fill: parent
                anchors.margins: 9
                ListView {
                    id: resultView
                    model: ListModel {
                        id: outputModel
                    }
                    delegate: ColumnLayout {
                        width: ListView.view.width
                        Label {
                            Layout.fillWidth: true
                            color: 'green'
                            text: "> " + model.expression
                        }
                        Label {
                            Layout.fillWidth: true
                            color: 'blue'
                            text: "" + model.result
                        }
                        Rectangle {
                            height: 1
                            Layout.fillWidth: true
                            color: '#333'
                            opacity: 0.2
                        }
                    }
                }
            }
        }
    }
  }

The evaluation function ``jsCall`` does the evaluation not by itself this has been moved to a JS module (``jsconsole.js``) for clearer separation.

::

  // part of JSConsole.qml

  import "jsconsole.js" as Util

  ...

  ApplicationWindow {
    id: root

    ...

    function jsCall(exp) {
        var data = Util.call(exp);
        // insert the result at the beginning of the list
        outputModel.insert(0, data)
    }
  }

For safety we do not use the ``eval`` function from JS as this would allow the user to modify the local scope. We use the Function constructor to create a JS function on runtime and pass in our scope as this variable. As the function is created every time it does not act as a closure and stores its own scope, we need to use ``this.a = 10`` to store the value 10 in a inside the this scope of the function. The this scope is set by the script to the scope valriable.

::

  // jsconsole.js
  .pragma library

  var scope = {
    // our custom scope injected into our function evaluation
  }

  function call(msg) {
      var exp = msg.toString();
      console.log(exp)
      var data = {
          expression : msg
      }
      try {
          var fun = new Function('return (' + exp + ');');
          data.result = JSON.stringify(fun.call(scope), null, 2)
          console.log('scope: ' + JSON.stringify(scope, null, 2) + 'result: ' + result)
      } catch(e) {
          console.log(e.toString())
          data.error = e.toString();
      }
      return data;
  }

The data return from the call function is a JS object with a result, expression and error property: ``data: { expression: {}, result: {}, error: {} }``. We can use this JS object directly inside the ListModel and access it then from the delegate, e.g. ``model.expression`` gives us the input expression. For the simplicity of the example we ignore the error result.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `is_convertible` fn in crate `nalgebra`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, is_convertible">

    <title>nalgebra::is_convertible - Rust</title>

    <link rel="stylesheet" type="text/css" href="../normalize.css">
    <link rel="stylesheet" type="text/css" href="../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../main.css">

nalgebra

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Function nalgebra::<wbr>is_convertible

                       [−]

               [src]

pub fn is_convertible<From: SupersetOf<To>, To>(t: &From) -> bool

Indicates if ::try_convert will succeed without actually performing the conversion.

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)

redpajama_set_name: RedPajamaGithub


text:
package com.echopen.asso.echopen;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;

public class HelpActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.help_activity);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar().setTitle(R.string.toobar_title);

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    }

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    Intent main = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(main);
                    finish();
                    return true;
                case R.id.navigation_dashboard:
                    Intent files = new Intent(getApplicationContext(), FilesActivity.class);
                    startActivity(files);
                    finish();
                    return true;
                case R.id.navigation_notifications:
                    Intent search = new Intent(getApplicationContext(), ClientActivity.class);
                    startActivity(search);
                    finish();
                    return true;
                case R.id.navigation_help:
                    Intent help = new Intent(getApplicationContext(), HelpActivity.class);
                    startActivity(help);
                    finish();
                    return true;
            }
            return false;
        }

    };

}


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

    markdown.studio.config(function($stateProvider, $urlRouterProvider){
        $stateProvider.state('studio', {
          url: "/studio",
          templateUrl: "modules/studio/views/studio.html",
          controller: 'studio'
        });
    });
})();


text:
package com.github.tkocsis.vertx.graphql.utils;

import com.github.tkocsis.vertx.graphql.utils.impl.IDLSchemaParserImpl;

import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import io.vertx.core.Future;
import io.vertx.core.Vertx;

public interface IDLSchemaParser {

	public static IDLSchemaParser create(Vertx vertx) {
		return new IDLSchemaParserImpl(vertx);
	}

	public Future<GraphQLSchema> fromFile(String path, RuntimeWiring runtimeWiring);

	public GraphQLSchema fromString(String schemaString, RuntimeWiring runtimeWiring);
}


text:
from encoding.key import Key
from encoding.reader import FileReader

import os

def encode(file_path, out_path):

	if out_path == "":
		out_path = file_path + ".pi"

	print("Generating array from encryption key...")
	encryption_key = Key('data/pi.dat')

	CHUNK_SIZE = 1

	print("Reading file to encrypt...")
	file_reader = FileReader(file_path)

	print("Encrypting file...")
	pointer_array = []
	#  map(encryption_key.get_index, list(file_reader.read(CHUNK_SIZE)))
	counter = 0
	data_list = list(file_reader.read(CHUNK_SIZE))
	max_length = len(data_list)

	for item in data_list:

		pointer_array.append(encryption_key.get_index(item))

		if counter % 1000 == 0:
			print("{0}/{1}".format(counter, max_length))
		counter += 1

	print("Dumping encrypted file to {0}...".format(out_path))
	with open(out_path, 'a') as outfile:
		outfile.write(','.join(pointer_array))

	os.remove('cache.db')


text:
Using the Open-XML-SDK-Plugin for MvvmCross is quite simple. The plugin injects the IWordManager interface into the IoC container.
Each resolve to IWordManager from the Mvx.Resolve<IWordManager>() will create a new instance of the service.

### API

The API of IWordManager is very easy to understand and to use.

```c#
public interface IWordManager : IDisposable
{
	IDatabase Database { get; }
	bool CreateConnection(string workingFolderPath, string databaseName);
}
```
#### WordManager Open existing template

In order to open a template, call the OpenDocFromTemplate method
```c#

    var resourceName = "<Set full template file path here>"; // ex : C:\temp\template.dotx
    var finalFilePath = "<Set saved new document file path here>"; // ex : C:\temp\createdDoc.docx

    using (IWordManager word = Mvx.Resolve<IWordManager>())
    {
        word.OpenDocFromTemplate(resourceName, finalFilePath, true);

        word.SaveDoc();
        word.CloseDoc();
    }

```

#### WordManager Insert text on bookmark

Using the name of the database and the folder on the client device where to store database files:
```c#

    var resourceName = "<Set full template file path here>"; // ex : C:\temp\template.dotx
    var finalFilePath = "<Set saved new document file path here>"; // ex : C:\temp\createdDoc.docx

    using (IWordManager word = Mvx.Resolve<IWordManager>())
    {
        word.OpenDocFromTemplate(resourceName, finalFilePath, true);

        word.SaveDoc();
        word.CloseDoc();
    }

```

To be complete...


text:
package uk.co.real_logic.sbe.xml;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import uk.co.real_logic.sbe.PrimitiveType;
import uk.co.real_logic.sbe.PrimitiveValue;
import uk.co.real_logic.sbe.ir.Token;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static javax.xml.xpath.XPathConstants.NODESET;
import static uk.co.real_logic.sbe.PrimitiveType.*;
import static uk.co.real_logic.sbe.xml.XmlSchemaParser.getAttributeValue;
import static uk.co.real_logic.sbe.xml.XmlSchemaParser.getAttributeValueOrNull;

/**
 * SBE compositeType.
 */
public class CompositeType extends Type
{
    public static final String COMPOSITE_TYPE = "composite";
    public static final String SUB_TYPES_EXP = "type|enum|set|composite|ref";

    private final List<String> compositesPath = new ArrayList<>();
    private final Map<String, Type> containedTypeByNameMap = new LinkedHashMap<>();
    private final int sinceVersion;

    public CompositeType(final Node node) throws XPathExpressionException
    {
        this(node, null, new ArrayList<>());
    }

    /**
     * Construct a new compositeType from XML Schema.
     *
     * @param node           from the XML Schema Parsing
     * @param givenName      for this node.
     * @param compositesPath with the path of composites that represents the levels of composition.
     * @throws XPathExpressionException if the XPath is invalid.
     */
    public CompositeType(final Node node, final String givenName, final List<String> compositesPath)
        throws XPathExpressionException
    {
        super(node, givenName);

        this.compositesPath.addAll(compositesPath);
        this.compositesPath.add(getAttributeValue(node, "name"));

        sinceVersion = Integer.parseInt(XmlSchemaParser.getAttributeValue(node, "sinceVersion", "0"));
        final XPath xPath = XPathFactory.newInstance().newXPath();
        final NodeList list = (NodeList)xPath.compile(SUB_TYPES_EXP).evaluate(node, NODESET);

        for (int i = 0, size = list.getLength(); i < size; i++)
        {
            final Node subTypeNode = list.item(i);
            final String subTypeName = XmlSchemaParser.getAttributeValue(subTypeNode, "name");

            processType(subTypeNode, subTypeName, null);
        }

        checkForValidOffsets(node);
    }

    /**
     * Return the EncodedDataType within this composite with the given name
     *
     * @param name of the EncodedDataType to return
     * @return type requested
     */
    public Type getType(final String name)
    {
        return containedTypeByNameMap.get(name);
    }

    /**
     * The encodedLength (in octets) of the list of EncodedDataTypes
     *
     * @return encodedLength of the compositeType
     */
    public int encodedLength()
    {
        int offset = 0;

        for (final Type t : containedTypeByNameMap.values())
        {
            if (t.isVariableLength())
            {
                return Token.VARIABLE_LENGTH;
            }

            if (t.offsetAttribute() != -1)
            {
                offset = t.offsetAttribute();
            }

            offset += t.encodedLength();
        }

        return offset;
    }

    /**
     * Return the sinceVersion value of the {@link CompositeType}
     *
     * @return the sinceVersion of the {@link CompositeType}
     */
    public int sinceVersion()
    {
        return sinceVersion;
    }

    /**
     * Return list of the Type that compose this composite
     *
     * @return {@link List} that holds the types in this composite
     */
    public List<Type> getTypeList()
    {

        return new ArrayList<>(containedTypeByNameMap.values());
    }

    /**
     * Make this composite type, if it has a varData member, variable length
     * by making the EncodedDataType with the name "varData" be variable length.
     */
    public void makeDataFieldCompositeType()
    {
        final EncodedDataType edt = (EncodedDataType)containedTypeByNameMap.get("varData");
        if (edt != null)
        {
            edt.variableLength(true);
        }
    }

    /**
     * Check the composite for being a well formed group encodedLength encoding. This means
     * that there are the fields "blockLength" and "numInGroup" present.
     *
     * @param node of the XML for this composite
     */
    public void checkForWellFormedGroupSizeEncoding(final Node node)
    {
        final EncodedDataType blockLengthType = (EncodedDataType)containedTypeByNameMap.get("blockLength");
        final EncodedDataType numInGroupType = (EncodedDataType)containedTypeByNameMap.get("numInGroup");

        if (blockLengthType == null)
        {
            XmlSchemaParser.handleError(node, "composite for group encodedLength encoding must have \"blockLength\"");
        }
        else if (!isUnsigned(blockLengthType.primitiveType()))
        {
            XmlSchemaParser.handleError(node, "\"blockLength\" must be unsigned type");
        }

        if (numInGroupType == null)
        {
            XmlSchemaParser.handleError(node, "composite for group encodedLength encoding must have \"numInGroup\"");
        }
        else if (!isUnsigned(numInGroupType.primitiveType()))
        {
            XmlSchemaParser.handleError(node, "\"numInGroup\" must be unsigned type");
        }
        else if (numInGroupType.primitiveType() != UINT8 && numInGroupType.primitiveType() != UINT16)
        {
            XmlSchemaParser.handleWarning(node, "\"numInGroup\" should be UINT8 or UINT16");
        }
        else
        {
            final PrimitiveValue maxValue = numInGroupType.maxValue();
            validateMaxValue(node, numInGroupType.primitiveType(), maxValue);

            final PrimitiveValue minValue = numInGroupType.minValue();
            if (null != minValue)
            {
                final long max = maxValue != null ?
                    maxValue.longValue() : numInGroupType.primitiveType().maxValue().longValue();

                if (minValue.longValue() > max)
                {
                    XmlSchemaParser.handleError(node, String.format(
                        "\"numInGroup\" minValue=%s greater than maxValue=%d", minValue, max));
                }
            }
        }
    }

    /**
     * Check the composite for being a well formed variable length data encoding. This means
     * that there are the fields "length" and "varData" present.
     *
     * @param node of the XML for this composite
     */
    public void checkForWellFormedVariableLengthDataEncoding(final Node node)
    {
        final EncodedDataType lengthType = (EncodedDataType)containedTypeByNameMap.get("length");

        if (lengthType == null)
        {
            XmlSchemaParser.handleError(node, "composite for variable length data encoding must have \"length\"");
        }
        else
        {
            final PrimitiveType primitiveType = lengthType.primitiveType();
            if (!isUnsigned(primitiveType))
            {
                XmlSchemaParser.handleError(node, "\"length\" must be unsigned type");
            }
            else if (primitiveType != UINT8 && primitiveType != UINT16 && primitiveType != UINT32)
            {
                XmlSchemaParser.handleWarning(node, "\"length\" should be UINT8, UINT16, or UINT32");
            }

            validateMaxValue(node, primitiveType, lengthType.maxValue());
        }

        if ("optional".equals(getAttributeValueOrNull(node, "presence")))
        {
            XmlSchemaParser.handleError(node, "composite for variable length data encoding cannot have presence=\"optional\"");
        }

        if (containedTypeByNameMap.get("varData") == null)
        {
            XmlSchemaParser.handleError(node, "composite for variable length data encoding must have \"varData\"");
        }
    }

    private static void validateMaxValue(final Node node, final PrimitiveType primitiveType, final PrimitiveValue value)
    {
        if (null != value)
        {
            final long longValue = value.longValue();
            final long allowedValue = primitiveType.maxValue().longValue();
            if (longValue > allowedValue)
            {
                XmlSchemaParser.handleError(node, String.format(
                    "maxValue greater than allowed for type: maxValue=%d allowed=%d", longValue, allowedValue));
            }

            final long maxInt = INT32.maxValue().longValue();
            if (primitiveType == UINT32 && longValue > maxInt)
            {
                XmlSchemaParser.handleError(node, String.format(
                    "maxValue greater than allowed for type: maxValue=%d allowed=%d", longValue, maxInt));
            }
        }
        else if (primitiveType == UINT32)
        {
            final long maxInt = INT32.maxValue().longValue();
            XmlSchemaParser.handleError(node, String.format(
                "maxValue must be set for varData UINT32 type: max value allowed=%d", maxInt));
        }
    }

    /**
     * Check the composite for being a well formed message headerStructure encoding. This means
     * that there are the fields "blockLength", "templateId" and "version" present.
     *
     * @param node of the XML for this composite
     */
    public void checkForWellFormedMessageHeader(final Node node)
    {
        final EncodedDataType blockLengthType = (EncodedDataType)containedTypeByNameMap.get("blockLength");
        final EncodedDataType templateIdType = (EncodedDataType)containedTypeByNameMap.get("templateId");
        final EncodedDataType schemaIdType = (EncodedDataType)containedTypeByNameMap.get("schemaId");
        final EncodedDataType versionType = (EncodedDataType)containedTypeByNameMap.get("version");

        if (blockLengthType == null)
        {
            XmlSchemaParser.handleError(node, "composite for message header must have \"blockLength\"");
        }
        else if (!isUnsigned(blockLengthType.primitiveType()))
        {
            XmlSchemaParser.handleError(node, "\"blockLength\" must be unsigned");
        }
        else if (blockLengthType.primitiveType() != UINT16)
        {
            XmlSchemaParser.handleWarning(node, "\"blockLength\" should be UINT16");
        }

        if (templateIdType == null)
        {
            XmlSchemaParser.handleError(node, "composite for message header must have \"templateId\"");
        }
        else if (templateIdType.primitiveType() != UINT16)
        {
            XmlSchemaParser.handleError(node, "\"templateId\" must be UINT16");
        }

        if (schemaIdType == null)
        {
            XmlSchemaParser.handleError(node, "composite for message header must have \"schemaId\"");
        }
        else if (schemaIdType.primitiveType() != UINT16)
        {
            XmlSchemaParser.handleError(node, "\"schemaId\" must be UINT16");
        }

        if (versionType == null)
        {
            XmlSchemaParser.handleError(node, "composite for message header must have \"version\"");
        }
        else if (versionType.primitiveType() != UINT16)
        {
            XmlSchemaParser.handleError(node, "\"version\" must be UINT16");
        }
    }

    /**
     * Check the composite for any specified offsets and validate they are correctly specified.
     *
     * @param node of the XML for this composite
     */
    public void checkForValidOffsets(final Node node)
    {
        int offset = 0;

        for (final Type edt : containedTypeByNameMap.values())
        {
            final int offsetAttribute = edt.offsetAttribute();

            if (-1 != offsetAttribute)
            {
                if (offsetAttribute < offset)
                {
                    XmlSchemaParser.handleError(
                        node,
                        String.format("composite element \"%s\" has incorrect offset specified", edt.name()));
                }

                offset = offsetAttribute;
            }

            offset += edt.encodedLength();
        }
    }

    public boolean isVariableLength()
    {
        return false;
    }

    private Type processType(final Node subTypeNode, final String subTypeName, final String givenName)
        throws XPathExpressionException
    {
        final String nodeName = subTypeNode.getNodeName();
        Type type = null;

        switch (nodeName)
        {
            case "type":
                type = addType(subTypeNode, subTypeName, new EncodedDataType(subTypeNode, givenName));
                break;

            case "enum":
                type = addType(subTypeNode, subTypeName, new EnumType(subTypeNode, givenName));
                break;

            case "set":
                type = addType(subTypeNode, subTypeName, new SetType(subTypeNode, givenName));
                break;

            case "composite":
                type = addType(subTypeNode, subTypeName, new CompositeType(subTypeNode, givenName, compositesPath));
                break;

            case "ref":
            {
                final XPath xPath = XPathFactory.newInstance().newXPath();

                final String refName = XmlSchemaParser.getAttributeValue(subTypeNode, "name");
                final String refType = XmlSchemaParser.getAttributeValue(subTypeNode, "type");
                final int refOffset = Integer.parseInt(XmlSchemaParser.getAttributeValue(subTypeNode, "offset", "-1"));
                final Node refTypeNode = (Node)xPath.compile("/messageSchema/types/*[@name='" + refType + "']")
                    .evaluate(subTypeNode.getOwnerDocument(), XPathConstants.NODE);

                if (refTypeNode == null)
                {
                    XmlSchemaParser.handleError(subTypeNode, "ref type not found: " + refType);
                }
                else
                {
                    if (compositesPath.contains(refType))
                    {
                        XmlSchemaParser.handleError(refTypeNode, "ref types cannot create circular dependencies.");
                        throw new IllegalStateException("ref types cannot create circular dependencies");
                    }

                    type = processType(refTypeNode, refName, refName);

                    if (-1 != refOffset)
                    {
                        type.offsetAttribute(refOffset);
                    }
                }

                break;
            }

            default:
                throw new IllegalStateException("Unknown node type: name=" + nodeName);
        }

        return type;
    }

    private Type addType(final Node subTypeNode, final String name, final Type type)
    {
        if (containedTypeByNameMap.put(name, type) != null)
        {
            XmlSchemaParser.handleError(subTypeNode, "composite already contains a type named: " + name);
        }

        return type;
    }
}


text:
package org.apache.airavata.registry.core.repositories.appcatalog;

import org.apache.airavata.model.appcatalog.computeresource.BatchQueue;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionInterface;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionProtocol;
import org.apache.airavata.registry.core.entities.appcatalog.JobSubmissionInterfacePK;
import org.apache.airavata.registry.core.repositories.common.TestBase;
import org.apache.airavata.registry.cpi.AppCatalogException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JobSubmissionInterfaceRepositoryTest extends TestBase {
    private static final Logger logger = LoggerFactory.getLogger(ComputeResourceRepositoryTest.class);

    private JobSubmissionInterfaceRepository jobSubmissionInterfaceRepository;
    private ComputeResourceRepository computeResourceRepository;
    private String computeResourceId;

    public JobSubmissionInterfaceRepositoryTest() {
        super(Database.APP_CATALOG);
        jobSubmissionInterfaceRepository = new JobSubmissionInterfaceRepository();
        computeResourceRepository = new ComputeResourceRepository();
    }

    @Before
    public void createTestComputeResource() throws AppCatalogException {

        ComputeResourceDescription description = new ComputeResourceDescription();
        description.setHostName("localhost");
        description.addToBatchQueues(new BatchQueue("queue1"));
        description.addToBatchQueues(new BatchQueue("queue2"));
        computeResourceId = computeResourceRepository.addComputeResource(description);
    }

    @After
    public void removeTestComputeResource() throws AppCatalogException {

        computeResourceRepository.removeComputeResource(computeResourceId);
    }

    @Test
    public void testAddJobSubmissionInterface() throws AppCatalogException {

        JobSubmissionInterface jobSubmissionInterface = new JobSubmissionInterface();
        jobSubmissionInterface.setJobSubmissionInterfaceId("test");
        jobSubmissionInterface.setPriorityOrder(1);
        jobSubmissionInterface.setJobSubmissionProtocol(JobSubmissionProtocol.SSH);

        String jobSubmissionInterfaceId = jobSubmissionInterfaceRepository.addJobSubmission(computeResourceId, jobSubmissionInterface);

        JobSubmissionInterfacePK pk = new JobSubmissionInterfacePK();
        pk.setComputeResourceId(computeResourceId);
        pk.setJobSubmissionInterfaceId(jobSubmissionInterfaceId);

        JobSubmissionInterface retrievedJobSubmissionInterface = jobSubmissionInterfaceRepository.get(pk);
        Assert.assertEquals("test", retrievedJobSubmissionInterface.getJobSubmissionInterfaceId());
        Assert.assertEquals(1, retrievedJobSubmissionInterface.getPriorityOrder());
        Assert.assertEquals(JobSubmissionProtocol.SSH, retrievedJobSubmissionInterface.getJobSubmissionProtocol());

        jobSubmissionInterfaceRepository.delete(pk);
    }
}


text:
/* jshint ignore:start */
'use strict';

var testHelper = require('../../../common/tests/test-helper');
var setupFile = require('./decision-setup');

var dashboardPage = require('../pages/dashboard');
var definitionPage = require('../pages/decision-definition');
var instancePage = require('../pages/decision-instance');

describe('Cockpit Decision Instance Spec', function() {

  describe('page navigation', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
      });
    });

    it('should go to decision defintion view', function() {

      // given
      dashboardPage.deployedDecisionsList.decisionName(0).then(function(decisionName) {

        // when
        dashboardPage.deployedDecisionsList.selectDecision(0).then(function() {

          // then
          expect(definitionPage.pageHeader().getText()).to.eventually.match(new RegExp(decisionName));
          expect(definitionPage.pageHeader().getText()).to.eventually.match(/DECISION DEFINITION/);
        });
      })
    });

    it('should go to process instance view', function() {

      // given
      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {

        // when
        definitionPage.decisionInstancesTab.selectInstanceId(0).then(function() {

          // then
          expect(instancePage.pageHeaderDecisionInstanceId()).to.eventually.match(new RegExp(instanceId));
        });
      });
    });

  });

  describe('table interaction', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
      });
    });

    it('should display decision table', function() {

      // when
      dashboardPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.table.tableElement().isDisplayed()).to.eventually.be.true;
    });

    it('should highlight fired rules', function() {
      expect(instancePage.table.row(0).getAttribute('class')).to.eventually.contain('fired');
    });

    it('should show the inputs on the table', function() {
      expect(instancePage.table.labelRow().getInputText(0)).to.eventually.eql('Invoice Amount = 100');
      expect(instancePage.table.labelRow().getInputText(1)).to.eventually.eql('Invoice Category = travelExpenses');
    });

    it('should show the outputs on the table', function() {
      expect(instancePage.table.ruleRow(0).getCellText(3)).to.eventually.eql('"accounting" = accounting');
    });

  });

  describe('in-/outputs', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
      });
    });

    it('should go to decision instance view', function() {

      // when
      dashboardPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.pageHeader().getText()).to.eventually.match(/DECISION INSTANCE/);
    });

    it('show inputs for the decision instance', function() {

      // when
      instancePage.inputsTab.selectTab();

      // then
      expect(instancePage.inputsTab.variableValue(0)).to.eventually.eql('100');
    });

    it('show outputs for the decision instance', function() {

      // when
      instancePage.outputsTab.selectTab();

      // then
      expect(instancePage.outputsTab.variableValue(0)).to.eventually.eql('accounting');
    });

  });

  describe('in-/outputs without clause name', function() {

    before(function() {
      return testHelper(setupFile.setup3, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
      });
    });

    it('should go to decision instance view', function() {

      // when
      dashboardPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.pageHeader().getText()).to.eventually.match(/DECISION INSTANCE/);
    });

    it('show inputs clause id', function() {

      // when
      instancePage.inputsTab.selectTab();

      // then
      expect(instancePage.inputsTab.variableName(0)).to.eventually.eql('clause1');
    });

    it('show outputs clause id', function() {

      // when
      instancePage.outputsTab.selectTab();

      // then
      expect(instancePage.outputsTab.variableName(0)).to.eventually.eql('clause3');
    });

  });

  describe('actions', function() {

    describe('navigate to process instance', function () {

      before(function() {
        return testHelper(setupFile.setup1, function() {

          dashboardPage.navigateToWebapp('Cockpit');
          dashboardPage.authentication.userLogin('admin', 'admin');
        });
      });

      it('go to decision instance view', function() {

        // when
        dashboardPage.deployedDecisionsList.selectDecision(0);
        definitionPage.decisionInstancesTab.selectInstanceId(0);
      });

      it('go to the process instance page', function() {

        // when
        instancePage.gotoProcessInstanceAction.gotoProcessInstance();

        // then
        expect(browser.getCurrentUrl()).to.eventually.contain('#/process-instance/');
      });

    });

    describe('navigation action', function () {

      before(function() {
        return testHelper(setupFile.setup4, function() {

          dashboardPage.navigateToWebapp('Cockpit');
          dashboardPage.authentication.userLogin('admin', 'admin');
          dashboardPage.deployedDecisionsList.selectDecision(0);
          definitionPage.decisionInstancesTab.selectInstanceId(0);
        });
      });

      it('is not displayed', function() {

        // then
        expect(instancePage.gotoProcessInstanceAction.gotoProcessInstanceButton().isDisplayed()).to.eventually.eql(false);
      });

    });

  });

});


text:
import attr
from .function_dispatch import FunctionDispatch
from ._compat import singledispatch, lru_cache

@attr.s
class _DispatchNotFound(object):
    """ a dummy object to help signify a dispatch not found """

    pass

class MultiStrategyDispatch(object):
    """
    MultiStrategyDispatch uses a
    combination of FunctionDispatch and singledispatch.

    singledispatch is attempted first. If nothing is
    registered for singledispatch, or an exception occurs,
    the FunctionDispatch instance is then used.
    """

    __slots__ = ("_function_dispatch", "_single_dispatch", "dispatch")

    def __init__(self, fallback_func):
        self._function_dispatch = FunctionDispatch()
        self._function_dispatch.register(lambda cls: True, fallback_func)
        self._single_dispatch = singledispatch(_DispatchNotFound)
        self.dispatch = lru_cache(64)(self._dispatch)

    def _dispatch(self, cl):
        try:
            dispatch = self._single_dispatch.dispatch(cl)
            if dispatch is not _DispatchNotFound:
                return dispatch
        except Exception:
            pass
        return self._function_dispatch.dispatch(cl)

    def register_cls_list(self, cls_and_handler):
        """ register a class to singledispatch """
        for cls, handler in cls_and_handler:
            self._single_dispatch.register(cls, handler)
        self.dispatch.cache_clear()

    def register_func_list(self, func_and_handler):
        """ register a function to determine if the handle
            should be used for the type
        """
        for func, handler in func_and_handler:
            self._function_dispatch.register(func, handler)
        self.dispatch.cache_clear()


text:
* Kennenlernen des Tools ESLint
  * Zweck
  * Benutzung
  * Konfiguration

### Problem:
* Die Datei index.js besitzt
  * Fehler
  * Inkonsistente Formattierung

### Aufgaben:
* Ausführen von ESLint mittels

  ```sh
  npm run eslint
  ```

  in dem Verzeichnis mit dieser readme.md-Datei

* Konfiguration von ESLint, dass Semikolons am Zeilenende nötig sind
  * Die vorgegebene Konfiguration nutzt die Vorlage "eslint-config-standard". Diese verbietet die Nutzung von
    Semikolons am Zeilenende.
  * Wir wollen hier allerdings am Zeilenende Semikolons nutzen, daher muss eine Konfigurationseinstellung ergänzt
    werden, die die Vorlage an dieser Stelle überschreibt.
  * Bitte die Datei __.eslintrc__ anpassen
  * Hinweise zur Konfiguration:
    * Entweder:
      http://eslint.org/
      und dann oben nach __semicolon__ suchen
    * oder direkt:
      http://eslint.org/docs/rules/semi
* Die Datei index.js korrigieren, dass keine Fehler mehr von ESLint erkannt werden
  * ggf. kann hierfür `npm run eslint --fix` verwendet werden
* testen, dass index.js funktioniert:

  ```sh
  node index.js 5
  ```

### Hinweis:

Normalerweise müssen in package.json auch die benötigten Pakete (eslint, ...) angegeben werden.

Damit hier nicht für jede Übung diese Pakete heruntergeladen werden müssen (mittels __npm install --save-dev__), sind
bereits im übergeordneten Verzeichnis alle Pakete, die für die verschiedenen Übungen benötigt werden, in
__package.json__ eingetragen.

Wer möchte, kann im übergeordneten Verzeichnis das Verzeichnis __node_modules__ umbenennen (bitte nicht löschen) und
dann hier in diesem Verzeichnis die benötigten Pakete mittels __npm install PAKETNAME__ (oder __yarn add PAKETNAME__)
installieren.

In diesem Fall muss auch in __package.json__ der Pfad zu eslint gelöscht werden. D.h. die entsprechende Zeile muss dann
lauten:

```
"eslint": "eslint ."
```


text:
package gform

type EventArg struct {
	sender Controller
	data interface{}
}

func NewEventArg(sender Controller, data interface{}) *EventArg {
	ea := new(EventArg)
	ea.sender, ea.data = sender, data
	return ea
}

func (this *EventArg) Sender() Controller {
	return this.sender
}

func (this *EventArg) Data() interface{} {
	return this.data
}


text:
<?php

class Notebook extends PaperworkModel {
	use SoftDeletingTrait;
	protected $softDelete = true;
	protected $table = 'notebooks';
	protected $fillable = array('parent_id', 'type', 'title');

	public function users() {
		return $this->belongsToMany('User')->withTimestamps();
	}

	public function shortcuts() {
		return $this->hasMany('Shortcut');
	}

	public function notes() {
		return $this->hasMany('Note')->withTimestamps();
	}

	public function parents() {
		return $this->belongsTo('Notebook', 'parent_id', 'id');
	}

	public function children() {
		return $this->hasMany('Notebook', 'parent_id', 'id');
	}
}

?>


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

namespace JetBrains.ReSharper.Koans.Refactoring
{
    // Extract Method
    //
    // Creates a new method based on a selected code fragment
    //
    // Ctrl+R, M (VS)
    // Ctrl+Alt+M (IntelliJ)

    // Inline Method
    //
    // Replaces the call site of a method call with the contents of the method,
    // optionally removing the original method definition
    //
    // Ctrl+R, I (VS)
    // Ctrl+Alt+N (IntelliJ)

    public class ExtractMethod
    {
        public List<string> LongMethod(IEnumerable<string> items)
        {
            var results = new List<string>();
            foreach (var item in items)
            {
                // 1. Extract method, with parameters and return value
                //    Select the next two lines of code. Note that it uses "item" and creates the "result" variable
                //    Invoke Extract Method - confirm name, select return value, parameters, make static/virtual, etc.
                var result = item.ToUpperInvariant();
                result = new string(result.Reverse().ToArray());

                // Don't select this line
                results.Add(result);
            }
            return results;
        }
    }

    public class InlineMethod
    {
        private const string Name = "Fred";

        public void SayHello()
        {
            // 2. Inline Method
            //    Place the text caret on the method name
            //    Invoke Inline Method
            //    Confirm to inline all instances, and remove original method definition
            Console.WriteLine("Hello " + GetName());
            Console.WriteLine("Hi " + GetName());
        }

        public string GetName()
        {
            return Name;
        }
    }
}


text:
package com.odiago.flumebase.lang;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.odiago.flumebase.util.StringUtils;

/**
 * A representation of an abstract type which can be unified to a specific
 * concrete type on a per-expression basis.
 *
 *
This is used by functions to specify arguments and return values of
 * variable type. These are only valid as argument and return types of
 * FnCallExprs.

 *
 *
As an expression is typechecked, UniversalType instances will be
 * compared against the actual types of arguments to the function; constraints
 * generated by these comparisons will result in the UniversalType being
 * replaced in the official expression by a concrete type.

 *
 *
UniversalType instances may carry constraints that restrict the
 * set of concrete types to which they may be unified. Each constraint
 * is a promotesTo relationship. e.g., adding a constraint of
 * <tt>Type.TypeName.TYPECLASS_NUMERIC</tt> asserts that the final type
 * this takes on must promote to TYPECLASS_NUMERIC.

 *
 *
Note that the equals() method operates on the alias and the constraints;
 * if two instances of a UniversalType have the same alias and the same
 * constraints (or no constraints at all), they will be judged "equal;" if a
 * function has two unbound argument types that are unrelated, they should
 * be instantiated with different aliases, such as "'a" and "'b".
 *

 */
public class UniversalType extends Type {
  private static final Logger LOG = LoggerFactory.getLogger(
      UniversalType.class.getName());

  /**
   * The set of type(classes) which constrain the set of values this type can
   * take on.
   */
  private List<Type> mConstraints;

  /**
   * A human-readable alias to distinguish this from other type variables in an expression.
   */
  private String mAlias;

  public UniversalType(String alias) {
    super(TypeName.UNIVERSAL);
    mAlias = alias;
    mConstraints = new ArrayList<Type>();
  }

  /**
   * Adds a type to the list of constraints for this type variable.
   */
  public void addConstraint(Type t) {
    mConstraints.add(t);
  }

  @Override
  public TypeName getPrimitiveTypeName() {
    return null;
  }

  public List<Type> getConstraints() {
    return mConstraints;
  }

  /**
   * We are a primitive type iff one of our constraints forces us to be.
   */
  @Override
  public boolean isPrimitive() {
    for (Type t : mConstraints) {
      if (t.isPrimitive()) {
        return true;
      }
    }

    return false;
  }

  /**
   * We are a numeric type iff one of our constraints forces us to be.
   */
  @Override
  public boolean isNumeric() {
    for (Type t : mConstraints) {
      if (t.isNumeric()) {
        return true;
      }
    }

    return false;
  }

  /**
   * We are a nullable type iff one of our constraints forces us to be.
   */
  @Override
  public boolean isNullable() {
    for (Type t : mConstraints) {
      if (t.isNullable()) {
        return true;
      }
    }

    return false;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("var(");
    sb.append(mAlias);
    if (mConstraints.size() > 0) {
      sb.append(", constraints={");
      StringUtils.formatList(sb, mConstraints);
      sb.append("}");
    }
    sb.append(")");
    return sb.toString();
  }

  /**
   *
Given a set of constraints 'actualConstraints' imposed by a specific
   * expression context for this type variable, determine the narrowest
   * type that satisfies all of mConstraints and actualConstraints.

   *
All constraints in actualConstraints should be real types (e.g., INT)
   * and not abstract typeclasses, etc.

   *
   * @return the narrowest type to satisfy all such constraints.
   * @throws TypeCheckException if no such type can be found.
   */
  public Type getRuntimeType(List<Type> actualConstraints) throws TypeCheckException {
    if (actualConstraints.size() == 0) {
      // We need a real type to start with.
      throw new TypeCheckException("Cannot make a concrete type from a "
          + "type variable without a binding constraint");
    }

    // Get the narrowest type that satisfies all the actualConstraints.
    Type candidate = actualConstraints.get(0);
    for (int i = 1; i < actualConstraints.size(); i++) {
      candidate = Type.meet(candidate, actualConstraints.get(i));
    }

    if (candidate.equals(Type.getPrimitive(Type.TypeName.NULL))
        || candidate.equals(Type.getNullable(Type.TypeName.NULL))) {
      LOG.debug("Returning NULL-typed implicitly-nullable value (numActuals="
          + actualConstraints.size() + ")");

      if (!candidate.isNullable()) {
        LOG.warn("Returning non-nullable NULL-typed runtime type: numActuals="
            + actualConstraints.size() + "; actuals=["
            + StringUtils.listToStr(actualConstraints) + "]");
      }
      return candidate.asNullable();
    }

    // Ensure that a concrete candidate type exists.
    if (!candidate.isConcrete()) {
      // TODO(aaron): The most concrete example we might get is just a Nullable 'NULL',
      // if we are inferring type from a NULL ConstExpr. This needs to be ok too.
      throw new TypeCheckException("Actual constraints are incompatible.");
    }

    // Now that we've found the narrowest real type we can use,
    // make sure it handles all our built-in constraints. These may be real
    // or abstract types.
    for (Type constraint : mConstraints) {
      if (!candidate.promotesTo(constraint)) {
        throw new TypeCheckException("Candidate type " + candidate
            + " cannot satisfy constraint: " + constraint);
      }
    }

    // The candidate type passed all our tests.
    return candidate;
  }

  @Override
  public int hashCode() {
    int hash = mAlias.hashCode();
    for (Type constraint : mConstraints) {
      hash ^= constraint.hashCode();
    }

    return hash;
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) {
      return true;
    } else if (other == null) {
      return false;
    } else if (!other.getClass().equals(getClass())) {
      return false;
    }

    UniversalType otherType = (UniversalType) other;
    if (!mAlias.equals(otherType.mAlias)) {
      return false;
    }

    if (mConstraints.size() != otherType.mConstraints.size()) {
      return false;
    }

    for (int i = 0; i < mConstraints.size(); i++) {
      if (!mConstraints.get(i).equals(otherType.mConstraints.get(i))) {
        return false;
      }
    }

    return true;
  }

  /** {@inheritDoc} */
  @Override
  public Type replaceUniversal(Map<Type, Type> universalMapping) throws TypeCheckException {
    Type replacement = universalMapping.get(this);

    if (null == replacement) {
      throw new TypeCheckException("No runtime binding for universal type: " + this);
    }

    LOG.debug("Resolved arg type from " + this + " to " + replacement);
    return replacement;
  }
}


text:
package org.ejml.alg.dense.linsol.qr;

import org.ejml.alg.dense.decomposition.TriangularSolver;
import org.ejml.alg.dense.decomposition.qr.QRDecompositionHouseholderColumn_D64;
import org.ejml.alg.dense.decomposition.qr.QrHelperFunctions;
import org.ejml.alg.dense.linsol.LinearSolverAbstract;
import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.SpecializedOps;

/**
 *

 * QR decomposition can be used to solve for systems.  However, this is not as computationally efficient
 * as LU decomposition and costs about 3n2 flops.
 *

 *

 * It solve for x by first multiplying b by the transpose of Q then solving for the result.
 *

 * QRx=b

 * Rx=Q^T b

 *

 *
 *

 * A column major decomposition is used in this solver.
 *

 *
 * @author Peter Abeles
 */
public class LinearSolverQrHouseCol extends LinearSolverAbstract {

    private QRDecompositionHouseholderColumn_D64 decomposer;

    private DenseMatrix64F a = new DenseMatrix64F(1,1);
    private DenseMatrix64F temp = new DenseMatrix64F(1,1);

    protected int maxRows = -1;
    protected int maxCols = -1;

    private double[][] QR; // a column major QR matrix
    private DenseMatrix64F R = new DenseMatrix64F(1,1);
    private double gammas[];

    /**
     * Creates a linear solver that uses QR decomposition.
     */
    public LinearSolverQrHouseCol() {
        decomposer = new QRDecompositionHouseholderColumn_D64();
    }

    public void setMaxSize( int maxRows , int maxCols )
    {
        this.maxRows = maxRows; this.maxCols = maxCols;
    }

    /**
     * Performs QR decomposition on A
     *
     * @param A not modified.
     */
    @Override
    public boolean setA(DenseMatrix64F A) {
        if( A.numRows > maxRows || A.numCols > maxCols )
            setMaxSize(A.numRows,A.numCols);

        R.reshape(A.numCols,A.numCols);
        a.reshape(A.numRows,1);
        temp.reshape(A.numRows,1);

        _setA(A);
        if( !decomposer.decompose(A) )
            return false;

        gammas = decomposer.getGammas();
        QR = decomposer.getQR();
        decomposer.getR(R,true);
        return true;
    }

    @Override
    public double quality() {
        return SpecializedOps.qualityTriangular(true, R);
    }

    /**
     * Solves for X using the QR decomposition.
     *
     * @param B A matrix that is n by m.  Not modified.
     * @param X An n by m matrix where the solution is written to.  Modified.
     */
    @Override
    public void solve(DenseMatrix64F B, DenseMatrix64F X) {
        if( X.numRows != numCols )
            throw new IllegalArgumentException("Unexpected dimensions for X: X rows = "+X.numRows+" expected = "+numCols);
        else if( B.numRows != numRows || B.numCols != X.numCols )
            throw new IllegalArgumentException("Unexpected dimensions for B");

        int BnumCols = B.numCols;

        // solve each column one by one
        for( int colB = 0; colB < BnumCols; colB++ ) {

            // make a copy of this column in the vector
            for( int i = 0; i < numRows; i++ ) {
                a.data[i] = B.data[i*BnumCols + colB];
            }

            // Solve Qa=b
            // a = Q'b
            // a = Q_{n-1}...Q_2*Q_1*b
            //
            // Q_n*b = (I-gamma*u*u^T)*b = b - u*(gamma*U^T*b)
            for( int n = 0; n < numCols; n++ ) {
                double []u = QR[n];

                double vv = u[n];
                u[n] = 1;
                QrHelperFunctions.rank1UpdateMultR(a, u, gammas[n], 0, n, numRows, temp.data);
                u[n] = vv;
            }

            // solve for Rx = b using the standard upper triangular solver
            TriangularSolver.solveU(R.data,a.data,numCols);

            // save the results
            for( int i = 0; i < numCols; i++ ) {
                X.data[i*X.numCols+colB] = a.data[i];
            }
        }
    }

    @Override
    public boolean modifiesA() {
        return false;
    }

    @Override
    public boolean modifiesB() {
        return false;
    }
}


text:
using System;
using System.Net;
using System.Net.Http;
using Moq;
using Stranne.VasttrafikNET.Service;
using Stranne.VasttrafikNET.Tests.Helpers;
using Stranne.VasttrafikNET.Tests.Jsons;

namespace Stranne.VasttrafikNET.Tests
{
    public class BaseIntegrationTest
    {
        protected const string Key = "Key";
        protected const string Secret = "Secret";
        protected const string DeviceId = "Test";
        protected const string TokenAbsoluteUrlTemplate = "https://api.vasttrafik.se/token?grant_type=client_credentials&scope=device_{0}&format=json";

        protected string TokenAbsoluteUrl { get; set; } = string.Format(TokenAbsoluteUrlTemplate, DeviceId);

        private string AbsoluteUrl { get; set; }

        protected MockHttpMessageHandler HttpMessageHandler { get; set; }

        internal JourneyPlannerService GetJourneyPlannerService()
        {
            return new JourneyPlannerService(Key, Secret)
            {
                JourneyPlannerHandlingService = { NetworkService = CreateNetworkService() }
            };
        }

        internal CommuterParkingService GetCommuterParkingService()
        {
            return new CommuterParkingService(Key, Secret)
            {
                CommuterParkingHandlingService = { NetworkService = CreateNetworkService() }
            };
        }

        internal TrafficSituationsService GetTrafficSituationsService()
        {
            return new TrafficSituationsService(Key, Secret)
            {
                TrafficSituationsHandlingService = {NetworkService = CreateNetworkService()}
            };
        }

        private NetworkService CreateNetworkService() => new NetworkService(Key, Secret, DeviceId)
        {
            HttpClient = new HttpClient(HttpMessageHandler)
        };

        internal void VerifyNetworkMock()
        {
            HttpMessageHandler.VerifyRequest(AbsoluteUrl, HttpMethod.Get);
            HttpMessageHandler.VerifyRequest(TokenAbsoluteUrl, HttpMethod.Post, 0, 1);
        }

        internal Mock<NetworkService> SetUpNetworkServiceMock(string absoluteUrl)
        {
            return SetUpNetworkServiceMock(absoluteUrl, new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.NotFound
            });
        }

        internal Mock<NetworkService> SetUpNetworkServiceMock(string absoluteUrl, JsonFile jsonFile, string deviceId = DeviceId)
        {
            var json = FileHelper.GetJson(jsonFile);
            return SetUpNetworkServiceMock(absoluteUrl, json, deviceId);
        }

        internal Mock<NetworkService> SetUpNetworkServiceMock(string absoluteUrl, string json, string deviceId = DeviceId)
        {
            return SetUpNetworkServiceMock(absoluteUrl, new StringContent(json), deviceId);
        }

        internal Mock<NetworkService> SetUpNetworkServiceMock(string absoluteUrl, HttpContent mainContent, string deviceId = DeviceId)
        {
            return SetUpNetworkServiceMock(absoluteUrl, new HttpResponseMessage
            {
                Content = mainContent
            }, deviceId);
        }

        private Mock<NetworkService> SetUpNetworkServiceMock(string absoluteUrl, HttpResponseMessage mainResponseMessage, string deviceId = DeviceId)
        {
            AbsoluteUrl = absoluteUrl;

            HttpMessageHandler = new MockHttpMessageHandler
            {
                SendAsyncAction = (httpRequestMessage, cancellationToken) =>
                {
                    var uri = httpRequestMessage.RequestUri;
                    HttpResponseMessage responseMessage;
                    if (CompareUri(uri, TokenAbsoluteUrl) && httpRequestMessage.Method == HttpMethod.Post)
                        responseMessage = new HttpResponseMessage
                        {
                            Content = new StringContent(FileHelper.GetJson(JsonFile.DefaultToken))
                        };
                    else if (CompareUri(uri, absoluteUrl) && httpRequestMessage.Method == HttpMethod.Get)
                        responseMessage = mainResponseMessage;
                    else
                        throw new ArgumentException(
                            $"Incorrect url; expected: {absoluteUrl}, actual: {uri.AbsoluteUri}");

                    return responseMessage;
                }
            };

            var mockNetworkService = new Mock<NetworkService>(Key, Secret, deviceId);
            mockNetworkService.SetupProperty(networkService => networkService.HttpClient, new HttpClient(HttpMessageHandler));

            return mockNetworkService;
        }

        internal static bool CompareUri(Uri uri, string absoluteUrl)
        {
            return Uri.Compare(uri,
                       new Uri(absoluteUrl),
                       UriComponents.AbsoluteUri, UriFormat.SafeUnescaped,
                       StringComparison.OrdinalIgnoreCase) == 0;
        }
    }
}


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

<title>TransactionFactory (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.engine.transaction.spi

Interface TransactionFactory<T extends TransactionImplementor>

All Superinterfaces:

Serializable, Service

All Known Implementing Classes:

CMTTransactionFactory, JdbcTransactionFactory, JtaTransactionFactory

public interface TransactionFactory<T extends TransactionImplementor>
extends Service

Contract for transaction creation, as well as providing metadata and contextual information about that creation.

Method Summary

Methods

Modifier and Type
Method and Description

boolean
canBeDriver()

boolean
compatibleWithJtaSynchronization()

T
createTransaction(TransactionCoordinator coordinator)

ConnectionReleaseMode
getDefaultReleaseMode()

boolean
isJoinableJtaTransaction(TransactionCoordinator transactionCoordinator,
                        T transaction)

Method Detail

createTransaction

T createTransaction(TransactionCoordinator coordinator)

Construct a transaction instance compatible with this strategy.

Parameters:

coordinator - The coordinator for this transaction

Returns:

The appropriate transaction instance.

Throws:

HibernateException - Indicates a problem constructing the transaction.

canBeDriver

boolean canBeDriver()

Can the transactions created from this strategy act as the driver?  In other words can the user actually manage
transactions with this strategy?

Returns:

true if the transaction strategy represented by this factory can act as the driver callback;
false otherwise.

compatibleWithJtaSynchronization

boolean compatibleWithJtaSynchronization()

Should we attempt to register JTA transaction synchronizations.
<p/>
In other words, is this strategy JTA-based?

Returns:

true if the transaction strategy represented by this factory is compatible with registering
synchronizations; false otherwise.

isJoinableJtaTransaction

boolean isJoinableJtaTransaction(TransactionCoordinator transactionCoordinator,
                               T transaction)

Can the underlying transaction represented by the passed Hibernate TransactionImplementor be joined?

Parameters:

transactionCoordinator - The transaction coordinator

transaction - The current Hibernate transaction

Returns:

true is the transaction can be joined; false otherwise.

getDefaultReleaseMode

ConnectionReleaseMode getDefaultReleaseMode()

Get the default connection release mode.

Returns:

The default release mode associated with this strategy

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
function PartnerTrips(uber) {
  this._uber = uber;
  this.path = 'partners/trips';
  this.requiredScope = 'partner.trips';
}

module.exports = PartnerTrips;

PartnerTrips.prototype.getTrips = function getTrips(off, lim, from, to, callback) {
  var newOffset = off || 0;
  // ensure query limit is set. Maximum is 50. Default is 5.
  var newLimit = (lim)
    ? Math.min(lim, 50)
    : 5;

  var params = {
    offset: newOffset,
    limit: newLimit
  };

  if (parseInt(from, 10) > 0) {
    params['from_time'] = from;
  }

  if (parseInt(to, 10) > 0) {
    params['to_time'] = to;
  }

  return this._uber.get({
    url: this.path,
    version: 'v1',
    params: params,
    scope: this.requiredScope
  }, callback);
};


text:
require File.dirname(__FILE__) + '/../../../../../spec_helper'
include OpenEHR::AM::Archetype::ConstraintModel
include OpenEHR::AssumedLibraryTypes

describe CDefinedObject do
  before(:each) do
    occurrences = Interval.new(:lower => 0, :upper => 1)
    @c_defined_object = CDefinedObject.new(:path => '/event/[at0001]/',
                                           :rm_type_name => 'DV_TIME',
                                           :node_id => 'ac0001',
                                           :occurrences => occurrences,
                                           :assumed_value => 'ANY')
  end

  it 'should be an instance of CDefinedObject' do
    expect(@c_defined_object).to be_an_instance_of CDefinedObject
  end

  it 'should be assigned properly' do
    expect(@c_defined_object.assumed_value).to eq('ANY')
  end

  it 'has_assumed_value should be true' do
    expect(@c_defined_object).to have_assumed_value
  end

  it 'has_assumed_value should not be true' do
    @c_defined_object.assumed_value = nil
    expect(@c_defined_object).not_to have_assumed_value
  end

  it 'default_value should raise NotImplementedError' do
    expect {
      @c_defined_object.default_value
    }.to raise_error NotImplementedError
  end

  it 'valid_value should raise NotImplementedError' do
    expect {
      @c_defined_object.valid_value?(1)
    }.to raise_error NotImplementedError
  end

  it 'any_allowed should raise NotImplementedError' do
    expect {
      @c_defined_object.any_allowed?
    }.to raise_error NotImplementedError
  end
end


text:
import asyncio
import copy
import enum
import random
import re
import weakref
from slot.protocols.base import BaseProtocol
from slot.events import EventManager, subscription
from slot.message import IncomingMessage, Conversation, Person
import slot.http
from slot.http import ResponseFormat
from slot.utils import html_unescape

class VKException(Exception):
    def __init__(self, message, response):
        super().__init__(message)
        self.response = response

class LongPollEvent(enum.IntEnum):
    delete_message = 0
    replace_message_flags = 1
    install_message_flags = 2
    reset_message_flags = 3
    new_message = 4
    make_read_inbox = 6
    make_read_outbox = 7
    friend_is_online = 8
    friend_is_offline = 9
    conversation_setting_change = 51
    user_is_writing = 61
    user_in_conversation_is_writing = 62
    user_call = 70
    update_unread_counter = 80

class LongPollMessageFlag(enum.IntEnum):
    UNREAD = 1
    OUTBOX = 2
    REPLIED = 4
    IMPORTANT = 8
    CHAT = 16
    FRIENDS = 32
    SPAM = 64
    DELETED = 128
    FIXED = 256
    MEDIA = 512

class Attachment(object):
    def __init__(self, type, user, id):
        self.type = type
        self.user = user
        self.id = id

    def __repr__(self):
        return "Attachment(type={0!r}, user={1!r}, id={2!r})".format(self.type, self.user, self.id)

class RealAuthor(object):
    def __init__(self, user):
        self.user = user

    def __repr__(self):
        return "RealAuthor(user={0!r})".format(self.user)

class ForwardedMessage(object):
    def __init__(self, user, id, inner_messages=[]):
        self.user = user
        self.id = id
        self.inner_messages = inner_messages

    def __iter__(self):
        return self.inner_messages.__iter__()

    def __repr__(self):
        return "ForwardedMessage(user={0!r}, id={1!r}, inner_messages={2!r})".format(self.user, self.id,
                                                                                self.inner_messages)

class GEOInternal(object):
    def __init__(self, id, provider=None):
        self.id = id
        self.provider = provider

    def __repr__(self):
        return "GEOInternal(id={0!r}, provider={1!r})".format(self.id, self.provider)

class GEO(object):
    def __init__(self, vk, message_id):
        self.vk = vk
        self.message_id = message_id
        self.geo_data = None

    def get_geo_data(self):
        if self.geo_data is None:
            self.geo_data = self.vk.request("execute.getMessageGeo", id=self.message_id)
        return self.geo_data

    def __repr__(self):
        return "GEO(message_id={0!r}, geo_data={1!r})".format(self.message_id, self.geo_data)

class Sticker(object):
    def __init__(self, id):
        self.id = id

    def __repr__(self):
        return "Sticker(id={0!r})".format(self.id)

class VKConversation(Conversation):
    def __init__(self, protocol, title, id, is_user=True):
        if id > 2000000000:
            id -= 2000000000
        self.id = id
        self.is_user = is_user
        super().__init__(protocol, title)

    @asyncio.coroutine
    def send(self, msg):
        arguments = {}
        if self.is_user:
            arguments["user_id"] = self.id
        else:
            arguments["chat_id"] = self.id
        if len(msg.attachments) > 0:
            arguments["attachment"] = ",".join(msg.attachments)
        arguments["message"] = msg.text
        arguments["guid"] = random.randint(0, 2**32)
        yield from self.protocol().request("messages.send", **arguments)

class VKIncomingMessage(IncomingMessage):
    def __init__(self, id, flags, protocol, conversation, author, text, timestamp, attachments):
        self.id = id
        self.flags = flags
        super().__init__(protocol, conversation, author, text, timestamp, attachments)

class VKPerson(Person):
    def __init__(self, protocol, id):
        super().__init__(id, None)
        self.protocol = weakref.ref(protocol)

    @asyncio.coroutine
    def get_name(self):
        if self.name is None:
            self.name = (yield from self.protocol().get_name(self.id))
        return self.name

class VKProtocol(BaseProtocol):
    name = "VK"
    api_url = "https://api.vk.com/method/"
    my_id = None
    working = False
    main_loop_task = None

    def __init__(self, bot, config):
        super().__init__(bot, config)
        self.name_cache = {}

    @asyncio.coroutine
    def request(self, method, **args):
        url = self.api_url + method + "?access_token=" + self.config["access_token"]
        args_copy = copy.deepcopy(args)
        args_copy["https"] = 1
        args_copy["lang"] = "ru"
        result = yield from slot.http.post(url, fields=args_copy, format=ResponseFormat.json)
        if "error" in result:
            raise VKException(result["error"]["error_msg"], result)
        return result["response"]

    @asyncio.coroutine
    def get_longpoll_server(self):
        while self.working:
            try:
                return (yield from self.request("messages.getLongPollServer", use_ssl=1))
            except Exception:
                self.logger.exception("Can't get long poll server. Retrying in 5 seconds")
                yield from asyncio.sleep(5)
                continue

    @asyncio.coroutine
    def main_loop(self):
        self.working = True
        self.my_id = (yield from self.request("users.get"))[0]["uid"]
        longpoll_server = yield from self.get_longpoll_server()
        longpoll_url_format = "https://{0[server]}?act=a_check&key={0[key]}&ts={0[ts]}&wait=25&mode=2"
        while self.working:
            for i in range(3):
                try:
                    result = yield from slot.http.get(longpoll_url_format.format(longpoll_server),
                                                      format=ResponseFormat.json)
                    break
                except Exception:
                    self.logger.exception("Something is wrong with long poll server. Retrying in 5 seconds")
                    yield from asyncio.sleep(5)
            else:
                self.logger.warning("Can't connect to long poll server. Requesting a new one")
                longpoll_server = yield from self.get_longpoll_server()
                continue
            if "failed" in result:
                self.logger.debug("Long poll server sent \"failed\" message. Requesting a new server")
                longpoll_server = yield from self.get_longpoll_server()
                continue
            longpoll_server["ts"] = result["ts"]
            for event in result["updates"]:
                try:
                    event_type = LongPollEvent(event[0])
                except ValueError:
                    self.logger.debug("Unknown type of long poll event: {0}. Ignoring".format(event[0]))
                    continue
                if event_type == LongPollEvent.new_message:
                    our = event[2] & LongPollMessageFlag.OUTBOX
                    attachments = self.parse_longpoll_attachments(event[7])
                    for i in attachments:
                        if isinstance(i, RealAuthor):
                            conversation = VKConversation(self, event[5], event[3], False)
                            author = i.user
                            break
                    else:
                        conversation = VKConversation(self, event[5], event[3], True)
                        if our:
                            author = self.my_id
                        else:
                            author = event[3]
                    for i in attachments:
                        if isinstance(i, GEOInternal):
                            attachments.append(GEO(self, event[1]))
                    attachments = [x for x in attachments if not isinstance(x, (RealAuthor, GEOInternal))]
                    text = html_unescape(event[6])
                    msg = VKIncomingMessage(event[1], event[2], self, conversation, VKPerson(self, author), text,
                                            event[4], attachments)
                    if our:
                        self.emit("my_message", msg)
                    else:
                        self.emit("message", msg)

    def parse_longpoll_attachments(self, data):
        attachments = []
        try:
            for i in data:
                if i.endswith("_type"):
                    continue
                if i == "fwd":
                    type = "fwd"
                    attachments.extend(self.fwd_parser(data[i])[1])
                elif i == "from":
                    attachments.append(RealAuthor(data[i]))
                elif i == "geo":
                    attachments.append(GEOInternal(data["geo"], data.get("geo_provider", None)))
                elif i == "geo_provider":
                    continue
                else:
                    if "_" not in data[i]:
                        try:
                            int(data[i])
                        except ValueError:
                            self.logger.warning("Unknown attachment type: {0} {1}".format(i, data[i]))
                            continue
                        else:
                            attachments.append(Sticker(data[i]))
                    else:
                        user, id = data[i].split("_")
                        type = data[i + "_type"]
                        attachments.append(Attachment(type, user, id))
        except:
            self.logger.exception("Failed to parse attachments")
            return []
        return attachments

    def fwd_parser(self, fwd_string):
        messages = []
        inner = []
        prev_end = 0
        skip = 0
        for i, v in enumerate(fwd_string):
            if skip > 0:
                skip -= 1
                continue
            if v == "(":
                prev_end += 1
                continue
            if v == ")":
                user, id = fwd_string[prev_end:i].split(":")[0].split("_")
                messages.append(ForwardedMessage(user, id, inner))
                return i + 1, messages
            if v == ",":
                user, id = fwd_string[prev_end:i].split(":")[0].split("_")
                messages.append(ForwardedMessage(user, id, inner))
                inner = []
                prev_end = i + 1
            if v == ":":
                skip, inner = self.fwd_parser(fwd_string[i+1:])
        user, id = fwd_string[prev_end:i].split(":")[0].split("_")
        messages.append(ForwardedMessage(user, id, inner))
        return i, messages

    @asyncio.coroutine
    def start(self):
        if "access_token" not in self.config:
            self.logger.warning("VK protocol requires access_token parameter")
            return False
        self.main_loop_task = asyncio.async(self.main_loop())
        return True

    @asyncio.coroutine
    def stop(self):
        self.working = False
        yield from super().stop()
        yield from asyncio.wait_for(self.main_loop_task, timeout=None)

    def escape_unsafe(self, text):
        text = html_unescape(text)
        text = "".join(x for x in text if ord(x) >= 32 or ord(x) in {9, 10})
        return re.sub(r"(\S)\.(\S)", r"\1. \2", text)

    @asyncio.coroutine
    def get_name(self, id):
        if id not in self.name_cache:
            result = (yield from self.request("users.get", user_ids=id))[0]
            name = result["first_name"] + " " + result["last_name"]
            self.name_cache[id] = name
        return self.name_cache[id]

    @staticmethod
    @asyncio.coroutine
    def upload(url, data, field, filename):
        return (yield from slot.http.post(url, fields={field: (filename, data)},
                                          format=ResponseFormat.json))

    @asyncio.coroutine
    def upload_audio(self, artist, title, data):
        upload_url = (yield from self.request("audio.getUploadServer"))["upload_url"]
        result = yield from self.upload(upload_url, data, "file", "song.mp3")
        save_result = yield from self.request("audio.save",
                                              audio=result["audio"],
                                              server=result["server"],
                                              hash=result["hash"],
                                              artist=artist,
                                              title=title)
        return "audio{0}_{1}".format(save_result["owner_id"], save_result["aid"])

    @asyncio.coroutine
    def upload_wall_photo(self, data, where, is_group=False):
        arguments = {}
        if is_group:
            arguments["group_id"] = where
        upload_url = (yield from self.request("photos.getWallUploadServer", **arguments))["upload_url"]
        result = yield from self.upload(upload_url, data, "photo", "picture.jpg")
        arguments = {}
        if not is_group:
            arguments = {"user_id": where}
        save_result = (yield from self.request("photos.saveWallPhoto", photo=result["photo"], server=result["server"],
                                               hash=result["hash"], **arguments))[0]
        return save_result["id"]

    @asyncio.coroutine
    def upload_messages_photo(self, data):
        upload_url = (yield from self.request("photos.getMessagesUploadServer"))["upload_url"]
        result = yield from self.upload(upload_url, data, "photo", "picture.jpg")
        save_result = (yield from self.request("photos.saveMessagesPhoto", photo=result["photo"],
                                               server=result["server"], hash=result["hash"]))[0]
        return save_result["id"]


text:
package cn.oftenporter.porter.core.apt;

import cn.oftenporter.porter.core.annotation.PortInObj;
import cn.oftenporter.porter.core.init.PorterConf;

import java.lang.annotation.*;

/**
 * 加在接口上,可用于自动生成代码(当{@linkplain #value()}和{@linkplain #classValue()}都为默认值时),新生成的类与接口在同一包,名字为接口名加"AP"结尾。加注解{@linkplain
 * PortInObj.Nece
 * }或不加任何注解表示必需值,加{@linkplain PortInObj.UnNece}表示非必需值。
 * <br>
 * Created by https://github.com/CLovinr on 2016/9/8.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface AutoGen
{
    /**
     * 不为""的情况下,根据名称查找在{@linkplain PorterConf#getContextAutoGenImplMap()} (String, Class)}中添加的实现类
     *
     * @return
     */
    String value() default "";

    /**
     * 做为{@linkplain #value()}的补充,当其不为默认值时,则使用Class.getName()作为查找实现类的name。
     *
     * @return
     */
    Class<?> classValue() default AutoGen.class;
}


text:
<link rel="stylesheet" href="{$webroot}/codemirror/lib/codemirror.css">
<link rel="stylesheet" href="{$webroot}/codemirror/theme/ambiance.css">
<link rel="stylesheet" href="{$webroot}/codemirror/addon/dialog/dialog.css">

C

C++

Pascal

Language: C

            <textarea placeholder="C code goes here..." id="gcc-editor" name="gcc-editor"></textarea>

            <button onclick="save_code('gcc');" type="button" class="btn btn-success save-code" data-loading-text="Saving...">Save the C code</button>

Language: C++

            <textarea placeholder="C++ code goes here..." id="gpp-editor" name="gpp-editor"></textarea>

            <button onclick="save_code('gpp');" type="button" class="btn btn-success save-code" data-loading-text="Saving...">Save the C++ code</button>

Language: Pascal

            <textarea placeholder="Pascal code goes here..." id="fpc-editor" name="fpc-editor"></textarea>

            <button onclick="save_code('fpc');" type="button" class="btn btn-success save-code" data-loading-text="Saving...">Save the Pascal code</button>


text:
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkInEdgeIterator - Iterates through all incoming edges to a vertex.
//
// .SECTION Description
// vtkInEdgeIterator iterates through all edges whose target is a particular
// vertex. Instantiate this class directly and call Initialize() to traverse
// the vertex of a graph. Alternately, use GetInEdges() on the graph to
// initialize the iterator. it->Next() returns a vtkInEdgeType structure,
// which contains Id, the edge's id, and Source, the edge's source vertex.
//
// .SECTION See Also
// vtkGraph vtkOutEdgeIterator

#ifndef __vtkInEdgeIterator_h
#define __vtkInEdgeIterator_h

#include "vtkCommonDataModelExport.h" // For export macro
#include "vtkObject.h"

#include "vtkGraph.h" // For edge type definitions

class vtkGraphEdge;

class VTKCOMMONDATAMODEL_EXPORT vtkInEdgeIterator : public vtkObject
{
public:
  static vtkInEdgeIterator *New();
  vtkTypeMacro(vtkInEdgeIterator, vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Initialize the iterator with a graph and vertex.
  void Initialize(vtkGraph *g, vtkIdType v);

  // Description:
  // Get the graph and vertex associated with this iterator.
  vtkGetObjectMacro(Graph, vtkGraph);
  vtkGetMacro(Vertex, vtkIdType);

  //BTX
  // Description:
  // Returns the next edge in the graph.
  inline vtkInEdgeType Next()
  {
    vtkInEdgeType e = *this->Current;
    ++this->Current;
    return e;
  }
  //ETX

  // Description:
  // Just like Next(), but
  // returns heavy-weight vtkGraphEdge object instead of
  // the vtkEdgeType struct, for use with wrappers.
  // The graph edge is owned by this iterator, and changes
  // after each call to NextGraphEdge().
  vtkGraphEdge *NextGraphEdge();

  // Description:
  // Whether this iterator has more edges.
  bool HasNext()
  {
    return this->Current != this->End;
  }

protected:
  vtkInEdgeIterator();
  ~vtkInEdgeIterator();

  // Description:
  // Protected method for setting the graph used
  // by Initialize().
  virtual void SetGraph(vtkGraph *graph);

  vtkGraph           *Graph;
  const vtkInEdgeType *Current;
  const vtkInEdgeType *End;
  vtkIdType            Vertex;
  vtkGraphEdge       *GraphEdge;

private:
  vtkInEdgeIterator(const vtkInEdgeIterator&);  // Not implemented.
  void operator=(const vtkInEdgeIterator&);  // Not implemented.
};

#endif


text:
House

Home

House

Edit Room

Edit Your Room

                <?php
                    if (isset($error)) {
                        foreach ($error as $error) {
                        ?>

                            <?php echo $error; ?>

                        <?php
                        }
                    }
                ?>

            <form method="post" role="form" action="" name="roomFormEdit" enctype="multipart/form-data">

                        <input type="hidden" name="id_owner" value="<?php  echo $id_owner; ?>">

                            Nama Kamar:
                            <input type="text" name="room_name" class="form-control" value="<?php echo $edit_row['room_name']; ?>">

Ex. Kamar 01

                            Jenis Kelas:
                            <select name="id_class" class="form-control">
                                <option selected="selected">--Pilih Kelas--</option>
                                <?php echo $opsClass; ?>
                            </select>

                            Status:
                            <select name="status" class="form-control">
                                <option value="">--Pilih Status--</option>
                                <option value="Kosong">Kosong</option>
                                <option value="Penuh">Penuh</option>
                            </select>

                            Foto:

<img src="photo_rooms/<?php echo $edit_row['photo']; ?>" class="img-rounded" width="200px" height="115px">

                            <input type="file" name="photo" class="form-control input-group" accept="image/*">

                            <button type="submit" name="btn-save-room-update" class="btn btn-info form-control">Save</button>

            </form>


text:
using Microsoft.Win32;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;

namespace desklight
{
	// Shamelessly copied from https://stackoverflow.com/questions/8414635/how-do-i-change-my-windows-desktop-wallpaper-programatically
	// Kudos to the original creator.
    public class Wallpaper
    {
        public enum Style : int
        {
            Tiled,
            Centered,
            Stretched
        }

        [DllImport("user32.dll")]
        public static extern Int32 SystemParametersInfo(UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);

        public static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
        public static readonly UInt32 SPIF_UPDATEINIFILE = 0x01;
        public static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;

        public static bool Set(string filePath, Style style)
        {
            bool Success = false;
            try
            {
                Image i = System.Drawing.Image.FromFile(Path.GetFullPath(filePath));

                Set(i, style);

                Success = true;

            }
            catch //(Exception ex)
            {
                //ex.HandleException();
            }
            return Success;
        }

        public static bool Set(Image image, Style style)
        {
            bool Success = false;
            try
            {
                string TempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");

                image.Save(TempPath, ImageFormat.Bmp);

                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);

                switch (style)
                {
                    case Style.Stretched:
                        key.SetValue(@"WallpaperStyle", 2.ToString());

                        key.SetValue(@"TileWallpaper", 0.ToString());

                        break;

                    case Style.Centered:
                        key.SetValue(@"WallpaperStyle", 1.ToString());

                        key.SetValue(@"TileWallpaper", 0.ToString());

                        break;

                    default:
                    case Style.Tiled:
                        key.SetValue(@"WallpaperStyle", 1.ToString());

                        key.SetValue(@"TileWallpaper", 1.ToString());

                        break;

                }

                SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, TempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

                Success = true;

            }
            catch //(Exception ex)
            {
                //ex.HandleException();
            }
            return Success;
        }

    }

}