text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>dummy_threading module — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="index.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

dummy_threading module

           View page source

dummy_threading module¶

Faux threading version using dummy_thread instead of thread.

The module _dummy_threading is added to sys.modules in order
to not have threading considered imported.  Had threading been
directly imported it would have made all subsequent imports succeed
regardless of whether _thread was available which is not desired.

dummy_threading.active_count()[source]¶

Return the number of Thread objects currently alive.

The returned count is equal to the length of the list returned by
enumerate().

class dummy_threading.Condition(lock=None)[source]¶

Bases: object

Class that implements a condition variable.

A condition variable allows one or more threads to wait until they are
notified by another thread.

If the lock argument is given and not None, it must be a Lock or RLock
object, and it is used as the underlying lock. Otherwise, a new RLock object
is created and used as the underlying lock.

notify(n=1)[source]¶

Wake up one or more threads waiting on this condition, if any.

If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.

This method wakes up at most n of the threads waiting for the condition
variable; it is a no-op if no threads are waiting.

notifyAll()¶

Wake up all threads waiting on this condition.

If the calling thread has not acquired the lock when this method
is called, a RuntimeError is raised.

notify_all()[source]¶

Wake up all threads waiting on this condition.

If the calling thread has not acquired the lock when this method
is called, a RuntimeError is raised.

wait(timeout=None)[source]¶

Wait until notified or until a timeout occurs.

If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.

This method releases the underlying lock, and then blocks until it is
awakened by a notify() or notify_all() call for the same condition
variable in another thread, or until the optional timeout occurs. Once
awakened or timed out, it re-acquires the lock and returns.

When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).

When the underlying lock is an RLock, it is not released using its
release() method, since this may not actually unlock the lock when it
was acquired multiple times recursively. Instead, an internal interface
of the RLock class is used, which really unlocks it even when it has
been recursively acquired several times. Another internal interface is
then used to restore the recursion level when the lock is reacquired.

wait_for(predicate, timeout=None)[source]¶

Wait until a condition evaluates to True.

predicate should be a callable which result will be interpreted as a
boolean value.  A timeout may be provided giving the maximum time to
wait.

dummy_threading.current_thread()[source]¶

Return the current Thread object, corresponding to the caller’s thread of control.

If the caller’s thread of control was not created through the threading
module, a dummy thread object with limited functionality is returned.

dummy_threading.enumerate()[source]¶

Return a list of all Thread objects currently alive.

The list includes daemonic threads, dummy thread objects created by
current_thread(), and the main thread. It excludes terminated threads and
threads that have not yet been started.

class dummy_threading.Event[source]¶

Bases: object

Class implementing event objects.

Events manage a flag that can be set to true with the set() method and reset
to false with the clear() method. The wait() method blocks until the flag is
true.  The flag is initially false.

clear()[source]¶

Reset the internal flag to false.

Subsequently, threads calling wait() will block until set() is called to
set the internal flag to true again.

isSet()¶

Return true if and only if the internal flag is true.

is_set()[source]¶

Return true if and only if the internal flag is true.

set()[source]¶

Set the internal flag to true.

All threads waiting for it to become true are awakened. Threads
that call wait() once the flag is true will not block at all.

wait(timeout=None)[source]¶

Block until the internal flag is true.

If the internal flag is true on entry, return immediately. Otherwise,
block until another thread calls set() to set the flag to true, or until
the optional timeout occurs.

When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).

This method returns the internal flag on exit, so it will always return
True except if a timeout is given and the operation times out.

dummy_threading.Lock()¶

Dummy implementation of _thread.allocate_lock().

dummy_threading.RLock(*args, **kwargs)[source]¶

Factory function that returns a new reentrant lock.

A reentrant lock must be released by the thread that acquired it. Once a
thread has acquired a reentrant lock, the same thread may acquire it again
without blocking; the thread must release it once for each time it has
acquired it.

class dummy_threading.Semaphore(value=1)[source]¶

Bases: object

This class implements semaphore objects.

Semaphores manage a counter representing the number of release() calls minus
the number of acquire() calls, plus an initial value. The acquire() method
blocks if necessary until it can return without making the counter
negative. If not given, value defaults to 1.

acquire(blocking=True, timeout=None)[source]¶

Acquire a semaphore, decrementing the internal counter by one.

When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.

When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.

When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.

When invoked with a timeout other than None, it will block for at
most timeout seconds.  If acquire does not complete successfully in
that interval, return false.  Return true otherwise.

release()[source]¶

Release a semaphore, incrementing the internal counter by one.

When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.

class dummy_threading.BoundedSemaphore(value=1)[source]¶

Bases: threading.Semaphore

Implements a bounded semaphore.

A bounded semaphore checks to make sure its current value doesn’t exceed its
initial value. If it does, ValueError is raised. In most situations
semaphores are used to guard resources with limited capacity.

If the semaphore is released too many times it’s a sign of a bug. If not
given, value defaults to 1.

Like regular semaphores, bounded semaphores manage a counter representing
the number of release() calls minus the number of acquire() calls, plus an
initial value. The acquire() method blocks if necessary until it can return
without making the counter negative. If not given, value defaults to 1.

release()[source]¶

Release a semaphore, incrementing the internal counter by one.

When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.

If the number of releases exceeds the number of acquires,
raise a ValueError.

class dummy_threading.Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)[source]¶

Bases: object

A class that represents a thread of control.

This class can be safely subclassed in a limited fashion. There are two ways
to specify the activity: by passing a callable object to the constructor, or
by overriding the run() method in a subclass.

daemon¶

A boolean value indicating whether this thread is a daemon thread.

This must be set before start() is called, otherwise RuntimeError is
raised. Its initial value is inherited from the creating thread; the
main thread is not a daemon thread and therefore all threads created in
the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are
left.

getName()[source]¶

ident¶

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the thread.get_ident() function. Thread
identifiers may be recycled when a thread exits and another thread is
created. The identifier is available even after the thread has exited.

isAlive()¶

Return whether the thread is alive.

This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.

isDaemon()[source]¶

is_alive()[source]¶

Return whether the thread is alive.

This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.

join(timeout=None)[source]¶

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is
called terminates – either normally or through an unhandled exception
or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As join() always returns None, you must call
isAlive() after join() to decide whether a timeout happened – if the
thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will
block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current
thread as that would cause a deadlock. It is also an error to join() a
thread before it has been started and attempts to do so raises the same
exception.

name¶

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The
initial name is set by the constructor.

run()[source]¶

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object’s constructor as the
target argument, if any, with sequential and keyword arguments taken
from the args and kwargs arguments, respectively.

setDaemon(daemonic)[source]¶

setName(name)[source]¶

start()[source]¶

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the
object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the
same thread object.

class dummy_threading.Barrier(parties, action=None, timeout=None)[source]¶

Bases: object

Implements a Barrier.

Useful for synchronizing a fixed number of threads at known synchronization
points.  Threads block on ‘wait()’ and are simultaneously once they have all
made that call.

abort()[source]¶

Place the barrier into a ‘broken’ state.

Useful in case of error.  Any currently waiting threads and threads
attempting to ‘wait()’ will have BrokenBarrierError raised.

broken¶

Return True if the barrier is in a broken state.

n_waiting¶

Return the number of threads currently waiting at the barrier.

parties¶

Return the number of threads required to trip the barrier.

reset()[source]¶

Reset the barrier to the initial state.

Any threads currently waiting will get the BrokenBarrier exception
raised.

wait(timeout=None)[source]¶

Wait for the barrier.

When the specified number of threads have started waiting, they are all
simultaneously awoken. If an ‘action’ was provided for the barrier, one
of the threads will have executed that callback prior to returning.
Returns an individual index number from 0 to ‘parties-1’.

class dummy_threading.Timer(interval, function, args=None, kwargs=None)[source]¶

Bases: threading.Thread

Call a function after a specified number of seconds:

t = Timer(30.0, f, args=None, kwargs=None)
t.start()
t.cancel()     # stop the timer’s action if it’s still waiting

cancel()[source]¶

Stop the timer if it hasn’t finished yet.

run()[source]¶

dummy_threading.ThreadError¶

alias of RuntimeError

dummy_threading.setprofile(func)[source]¶

Set a profile function for all threads started from the threading module.

The func will be passed to sys.setprofile() for each thread, before its
run() method is called.

dummy_threading.settrace(func)[source]¶

Set a trace function for all threads started from the threading module.

The func will be passed to sys.settrace() for each thread, before its run()
method is called.

class dummy_threading.local[source]¶

Bases: object

dummy_threading.stack_size(size=None)[source]¶

Dummy implementation of _thread.stack_size().

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
import type { StatusBarProps } from 'react-native';
import type { CustomProps } from '../../../components/types';

export interface InterfaceStatusBarProps extends StatusBarProps {}
export type IStatusBarProps = InterfaceStatusBarProps &
  CustomProps<'StatusBar'>;

export type IStatusBarComponentType = (props: IStatusBarProps) => JSX.Element;

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('COT_CODE') or die('Wrong URL.');

/**
 * Plugin Config
 */
$L['cfg_mrh_login'] = array('Логин в Робокассе');
$L['cfg_mrh_pass1'] = array('Пароль #1 в Робокассе');
$L['cfg_mrh_pass2'] = array('Пароль #2 в Робокассе');
$L['cfg_testmode'] = array('Тестовый режим');
$L['cfg_enablepost'] = array('Enable POST');
$L['cfg_rate'] = array('Exchange rate');

$L['roboxbilling_title'] = 'Robokassa';

$L['roboxbilling_error_paid'] = 'Payment was successful. In the near future the service will be activated!';
$L['roboxbilling_error_done'] = 'Payment was successful.';
$L['roboxbilling_error_incorrect'] = 'The signature is incorrect!';
$L['roboxbilling_error_otkaz'] = 'Failure to pay.';
$L['roboxbilling_error_title'] = 'Result of the operation of payment';
$L['roboxbilling_error_fail'] = 'Payment is not made! Please try again. If the problem persists, contact your site administrator';

?>


text:
package org.wikidata.wdtk.datamodel.implementation;

import static java.util.stream.Collectors.toList;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.helpers.Equality;
import org.wikidata.wdtk.datamodel.helpers.Hash;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormUpdate;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Jackson implementation of {@link FormUpdate}.
 */
public class FormUpdateImpl extends StatementDocumentUpdateImpl implements FormUpdate {

	@JsonIgnore
	private final TermUpdate representations;
	@JsonIgnore
	private final Set<ItemIdValue> grammaticalFeatures;

	/**
	 * Initializes new form update.
	 *
	 * @param entityId
	 *            ID of the form that is to be updated
	 * @param revisionId
	 *            base form revision to be updated or zero if not available
	 * @param representations
	 *            changes in form representations, possibly empty
	 * @param grammaticalFeatures
	 *            new grammatical features of the form or {@code null} for no change
	 * @param statements
	 *            changes in entity statements, possibly empty
	 * @throws NullPointerException
	 *             if any required parameter is {@code null}
	 * @throws IllegalArgumentException
	 *             if any parameters or their combination is invalid
	 */
	public FormUpdateImpl(
			FormIdValue entityId,
			long revisionId,
			TermUpdate representations,
			Collection<ItemIdValue> grammaticalFeatures,
			StatementUpdate statements) {
		super(entityId, revisionId, statements);
		Objects.requireNonNull(representations, "Representation update cannot be null.");
		if (grammaticalFeatures != null) {
			for (ItemIdValue feature : grammaticalFeatures) {
				Objects.requireNonNull(feature, "Grammatical feature cannot be null.");
				Validate.isTrue(!feature.isPlaceholder(), "Grammatical feature cannot be a placeholder ID.");
			}
			Validate.isTrue(
					grammaticalFeatures.stream().distinct().count() == grammaticalFeatures.size(),
					"Grammatical features must be unique.");
		}
		this.representations = representations;
		this.grammaticalFeatures = grammaticalFeatures != null
				? Collections.unmodifiableSet(new HashSet<>(grammaticalFeatures))
				: null;
	}

	@JsonIgnore
	@Override
	public FormIdValue getEntityId() {
		return (FormIdValue) super.getEntityId();
	}

	@JsonIgnore
	@Override
	public boolean isEmpty() {
		return super.isEmpty() && representations.isEmpty() && grammaticalFeatures == null;
	}

	@JsonIgnore
	@Override
	public TermUpdate getRepresentations() {
		return representations;
	}

	@JsonProperty("representations")
	@JsonInclude(Include.NON_NULL)
	TermUpdate getJsonRepresentations() {
		return representations.isEmpty() ? null : representations;
	}

	@JsonIgnore
	@Override
	public Optional<Set<ItemIdValue>> getGrammaticalFeatures() {
		return Optional.ofNullable(grammaticalFeatures);
	}

	@JsonProperty("grammaticalFeatures")
	@JsonInclude(Include.NON_NULL)
	List<String> getJsonGrammaticalFeatures() {
		if (grammaticalFeatures == null)
			return null;
		return grammaticalFeatures.stream().map(f -> f.getId()).collect(toList());
	}

	@Override
	public boolean equals(Object obj) {
		return Equality.equalsFormUpdate(this, obj);
	}

	@Override
	public int hashCode() {
		return Hash.hashCode(this);
	}

}


text:
double R744_rho_fit_supercrit(double T, double P);
double R744_h_fit_supercrit(double T, double P);
double R744_s_fit_supercrit(double T, double P);
double R744_u_fit_supercrit(double T, double P);
double R744_cv_fit_supercrit(double T, double P);

double R744_rho_fit_subcrit(double T, double P);
double R744_h_fit_subcrit(double T, double P);
double R744_s_fit_subcrit(double T, double P);
double R744_u_fit_subcrit(double T, double P);
double R744_cv_fit_subcrit(double T, double P);


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/board_list"
    android:name="by.iot.nucleo.spectre.getyoursensors.BoardListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="by.iot.nucleo.spectre.getyoursensors.BoardListActivity"
    tools:listitem="@layout/board_list_content" />


text:
#include <decof/scgi/response.h>
#include <map>
#include <sstream>

namespace {

using decof::scgi::response;

static std::map<response::status_code, const char*> http_response_texts = {
    {response::status_code::ok, "OK"},
    {response::status_code::created, "Created"},
    {response::status_code::accepted, "Accepted"},
    {response::status_code::no_content, "No Content"},
    {response::status_code::partial_content, "Partial Content"},
    {response::status_code::multiple_choices, "Multiple Choices"},
    {response::status_code::moved_permanently, "Moved Permanently"},
    {response::status_code::moved_temporarily, "Moved Temporarily"},
    {response::status_code::not_modified, "Not Modified"},
    {response::status_code::bad_request, "Bad Request"},
    {response::status_code::unauthorized, "Unauthorized"},
    {response::status_code::forbidden, "Fobidden"},
    {response::status_code::not_found, "Not Found"},
    {response::status_code::not_supported, "Not Supported"},
    {response::status_code::not_acceptable, "Not Acceptable"},
    {response::status_code::request_timeout, "Request Timeout"},
    {response::status_code::precondition_failed, "Precondition Failed"},
    {response::status_code::unsatisfiable_range, "Requested Range Not Satisfiable"},
    {response::status_code::internal_server_error, "Internal Server Error"},
    {response::status_code::not_implemented, "Not Implemented"},
    {response::status_code::bad_gateway, "Bad Gateway"},
    {response::status_code::service_unavailable, "Service Unavailable"},
    {response::status_code::space_unavailable, "Insufficient Space to Store Resource"}};

} // Anonymous namespace

namespace decof {

namespace scgi {

std::string response::status_text() const
{
    return http_response_texts.at(status);
}

response response::stock_response(response::status_code status)
{
    response resp;
    resp.status = status;
    return resp;
}

} // namespace scgi

} // namespace decof


text:
stand
=====

Spokane Timetable App for Nearby Departures


text:
In Mongolid a reference is made by storing the `_id` of the referenced object.

Referencing provides more flexibility than embedding;
however, to resolve the references, client-side applications must issue follow-up queries.
In other words, using references requires more roundtrips to the server.

In general, use references when embedding would result in duplication of data and would not provide sufficient
read performance advantages to outweigh the implications of the duplication.
Read [MongoDB - Relationships with Document References](https://docs.mongodb.org/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/)
to learn more how to take advantage of referencing in MongoDB.

:::info
MongoDB **relationships doesn't work like in a Relational database**.
In MongoDB, data modeling decisions involve determining how to structure the documents to model the data effectively.
:::
:::caution
If you try to create references between documents like you would do in a relational database you will end up with _"n+1 problem"_ and poor performance.
:::

[Legacy References](docs/legacy/references.md) *For compatibility with version 2.x*

---

## References One

### Defining A References One Relation

```php
    class Post extends \Mongolid\Model\AbstractModel {
        protected $collection = 'posts';

        public function author()
        {
            // highlight-next-line
            return $this->referencesOne(User::class, 'author');
        }

    }

    class User extends \Mongolid\Model\AbstractModel {
        protected $collection = 'users';
    }
```

The first argument passed to the `referencesOne` method is the name of the related model,
the second argument is the attribute where the referenced model `_id` will be stored.
Once the relationship is defined, we may retrieve it using the following method:

```php
    $user = Post::find('4af9f23d8ead0e1d32000000')->author()->get();
```

:::info Explanation:
- Query for the post with the `_id` _'4af9f23d8ead0e1d32000000'_
- Query for the user with the `_id` equals to the _author_ attribute of the post that returns relationship object
- Get method to return the Author model filled
:::

In order to set a reference to a document:
```php
    // The object that will be embedded
    $user = new User();
    $user->name = 'John';
    $user->save() // This will populate the $user->_id

    // The object that will contain the user
    $post = Post::first('4af9f23d8ead0e1d32000000');

    // This method will attach the $phone _id into the phone attribute of the user
    // highlight-next-line
    $post->author()->attach($user);

    $post->save();

    $post->author()->get(); // Will return a User object
```

:::info
When using Mongolid models you will need to call the `save()` method after embedding or attaching objects.
The changes will only persist after you call the 'save()' method.
:::

## References Many

In Mongolid a _References Many_ is made by storing the `_id`s of the referenced objects.

### Defining A References Many Relation

```php
    class User extends \Mongolid\Model\AbstractModel {
        protected $collection = 'users';

        public function questions()
        {
            // highlight-next-line
            return $this->referencesMany(Question::class, 'questions');
        }

    }

    class Question extends \Mongolid\Model\AbstractModel {
        protected $collection = 'questions';
    }
```

The first argument passed to the `referencesMany` method is the name of the related model,
the second argument is the attribute where the `_id`s will be stored.
Once the relationship is defined, we may retrieve it using the following method:

```php
    $posts = User::find('4af9f23d8ead0e1d32000000')->posts()->get();
```

:::info Explanation:
- Query for the user with the `_id` _'4af9f23d8ead0e1d32000000'_
- Query for all the posts with the `_id` in the user's _posts_ attribute and return a relationship object
- Method `get()` will return the [`Mongolid\Cursor\Cursor`](docs/cursor.md) with the related posts
:::

In order to set a reference to a document use the `attach` method. For example:

```php
    $postA = new Post();
    $postA->title = 'Nice post';

    $postB = new Post();
    $postB->title = 'Nicer post';

    $user = User::first('4af9f23d8ead0e1d32000000');

    // To attach a document
    $user->posts()->attach($postA);

    // To attach many documents
    $user->posts()->attachMany([$postA, $postB]);

    // To replace the current documents
    $user->posts()->replace([$postA, $postB]);

    // To detach a single document
    $user->posts()->detach($postA);

    // To detach all documents
    $user->posts()->detachAll();

    $user->save();
```

:::info
When using Mongolid models you will need to call the `save()` method after embedding or attaching objects.
The changes will only persist after you call the 'save()' method.
:::


text:
/**
 * Browser Update Notifier - async (http://browser-update.org/update.js)
 */
var $bu = {};
$bu.ol = window.onload;
window.onload = function() {
    try {
        if ($bu.ol) $bu.ol();
    }catch (e) {}
    var e = document.createElement("script");
    e.setAttribute("type", "text/javascript");
    e.setAttribute("src", "/tools/webinterface/assets/js/browser-update.js");
    document.body.appendChild(e);

    setCurrentPageActiveInMainMenu();
    enableTooltips();
    handlePHPExtensionsForm();

    onModalHideResetRemoteUrl();

    lazyBindModalSubmitActionToFormUrl();
}

/**
 * Allow Modal Content to be fetched from the new remote URL:
 * by destroying the old modal and removing its remote URL.
 */
function onModalHideResetRemoteUrl() {
    $('body').on('hidden.bs.modal', '.modal', function () {
      $(this).removeData('bs.modal');
    });
}

/**
 * override native alert() function with a call to bootstrap3 modal
 */
/*
window.alert = function () {
  var msg = arguments[0];
  var alert = '
' + msg.replace(/\n/g, "
") + '
';
  $('#myModal .modal-title').html('ALERT');
  $('#myModal .modal-body').html(alert);
  $('#myModal button[type="submit"]').hide();
  $("#myModal").modal('show');
};*/

/**
 * Highlights the current page in the headline main menu
 */
function setCurrentPageActiveInMainMenu() {
    var location = window.location.href.toString().split(window.location.host)[1];
    $(".main_menu li a").removeClass("active");
    $(".main_menu li a[href='" + location  + "']").addClass("active");
    // special cases
    if(location.indexOf("update") >= 0) {
       $("a.dropdown-toggle:contains('Tools')").addClass("active");
    }
}

/**
 * Enable Twitter Bootstrap Tooltips
 * Usage:
 *
 */
function enableTooltips() {
    $('[rel=tooltip]').tooltip();
}

jQuery.fn.extend({
    // Pulsate
    // Usage: http://jsfiddle.net/nick_craver/HHWBv/
    pulsate: function() {
        var obj = $(this);
        // 3 times
        for(var i=0; i<2; i++) {
          obj.animate({opacity: 0.2}, 1000, 'linear')
           .animate({opacity: 1}, 1000, 'linear');
        }
        // 1 more with hide
        obj.animate({opacity: 0.2}, 1000, 'linear')
           .animate({opacity: 1}, 1000, 'linear', function() {
               obj.hide();
        });
    return obj;
    }
});

// wait for the DOM to be loaded
function handlePHPExtensionsForm() {
    var options = {
        delegation:    true,  // the form we are binding, does not exist, yet (load via ajax)
        target:        '#ajax-status',   // target element(s) to be updated with server response
        beforeSubmit:  showRequest,  // pre-submit callback
        success:       showResponse,  // post-submit callback

        // other available options:
        //url:       url         // override for form's 'action' attribute
        //type:      type        // 'get' or 'post', override for form's 'method' attribute
        dataType:    'json'      // 'xml', 'script', or 'json' (expected server response type)
        //clearForm: true        // clear all form fields after successful submit
        //resetForm: true        // reset the form after successful submit

        // $.ajax options can be used here too, for example:
        //timeout:   3000
    };

    // delegation binding of the form using 'ajaxForm'
    $('#phpExtensionsForm').ajaxForm(options);

    // pre-submit callback
    function showRequest(formData, jqForm, options) {
        // formData is an array; here we use $.param to convert it to a string to display it
        // but the form plugin does this for you automatically when it submits the data
        var queryString = $.param(formData);

        // jqForm is a jQuery object encapsulating the form element.  To access the
        // DOM element for the form do this:
        // var formElement = jqForm[0];

        /*alert('About to submit: \n\n' + queryString);*/

        // here we could return false to prevent the form from being submitted;
        // returning anything other than false will allow the form submit to continue
        // return false;

        return true;
    }

    // post-submit callback
    function showResponse(responseText, statusText, xhr, $form)  {
        // for normal html responses, the first argument to the success callback
        // is the XMLHttpRequest object's responseText property

        // if the ajaxForm method was passed an Options Object with the dataType
        // property set to 'xml' then the first argument to the success callback
        // is the XMLHttpRequest object's responseXML property

        // if the ajaxForm method was passed an Options Object with the dataType
        // property set to 'json' then the first argument to the success callback
        // is the json data object returned by the server

        // how to update page using json data
        // ==================================
        // * iterate over each property/value combination in the JSON object
        // * look for an element in the DOM that matches the property name
        //   o first, look for an element with a matching id attribute
        //   o if no element with a matching ID is found, look for input,
        //     select or textarea elements with a matching name attribute
        // * update the value, contents or selection of the matched element(s) based on the value in the JSON object

        var jsonData = responseText;

        // after a change to php ini, we are indicating the change and the PHP daemon restart
        // by showing the ajax status
        $('#ajax-status').html(jsonData.responseText).removeClass('hide').show().pulsate();

        // restart the php daemon
        $.get("index.php?page=daemon&action=restart&daemon=php");

        // there might be a change in the on/off state of extensions.
        // fetch their state as HTML checkbox display
        var updatePHPExtensionsForm = function() {
            $.ajax({ url: "index.php?page=config&action=renderPHPExtensionsFormContent",
                success: function(data, textStatus, XMLHttpRequest) {
                    $("#phpExtensionsFormContent").html(data);
                    $('#ajax-status').hide().addClass('hide');
            }});
        }

        // delay this call, because the php daemon needs to startup again
        setTimeout(updatePHPExtensionsForm, 2200);
    }
}; // END of handlePHPExtensionsForm()

function ajaxGET(url, success) {
    $.ajax({
        url: url,
        method: "GET",
        success: success
    });
}

function lazyBindModalSubmitActionToFormUrl() {
  // bind submit action
  $('#myModal').on("click", 'input[type="submit"], button[type="submit"]', function (event) {
      var form = $("#myModal .modal-body form");

      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serializeArray(),
        cache: false
      })
      .done(function(data, textStatus, jqXHR) {
        $('#myModal .modal-body').html(data);
        //$('#myModal .modal-body').html("success");
      })
      .fail(function() {
        $('#myModal .modal-body').html("error");
      });

      // cancel the default action (submit)
      event.preventDefault();
  });

}


text:
module MiqAeMethodService
  class MiqAeServiceContainerProject < MiqAeServiceModelBase
    expose :ext_management_system,  :association => true
    expose :container_groups,       :association => true
  end
end


text:
import * as Sequelize from "sequelize"
import * as path from 'path'

var seq = new Sequelize("db", "", "", {
	dialect: "sqlite",
	storage: path.join(__dirname, "../..", "db.sqlite3")
});

var Post = seq.define('Post', {
	ID: {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
	slug: { type: Sequelize.TEXT, unique: true, },
	title: Sequelize.TEXT,
	content: Sequelize.TEXT,
	publish: Sequelize.DATE,
	category_id: Sequelize.INTEGER,
	user_id: Sequelize.INTEGER,
}).sync()

var Category = seq.define('Category', {
	ID: {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
	slug: { type: Sequelize.TEXT, unique: true, },
	title: Sequelize.TEXT,
}).sync()

var Tag = seq.define('Tag', {
	ID: {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
	slug: { type: Sequelize.TEXT, unique: true, },
	title: Sequelize.TEXT,
}).sync()

var PostTag = seq.define('PostTag', {
	ID: {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
	post_id: Sequelize.INTEGER,
	tag_id: Sequelize.INTEGER,
}).sync()

var User = seq.define('User', {
	ID: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
	username: Sequelize.STRING(50),
	email: { type: Sequelize.STRING(255), unique: true },
	password: Sequelize.BLOB,
	signupDate: Sequelize.DATE,
}).sync()

export {
	Post,
	Category,
	Tag,
	PostTag,
	User,
}

export function upsert(db, model) {
	return model.ID ? db.update(model, { where: {ID: model.ID}}) : db.create(model)
}


text:
function is = init_struct(keys, defaults, varargin)

% init_struct is a function that takes in key-value pairs, a list of keys,
% and a list of corresponding defaults, and returns a struct containing
% fields named by the keys.

if length(defaults) ~= length(keys)

    display(sprintf(['The first two arguments of init_struct must be matched 1-D cell arrays\n',...
        'containing keys and their corresponding default values.']))

end

is = struct();

for k = 1:length(keys)

    is.(keys{k}) = defaults{k};

end

if nargin > 2

    if mod(nargin, 2)

        display(sprintf(['The first two arguments of init_struct must be matched 1-D cell arrays\n',...
            'containing keys and their corresponding default values.',...
            'Following the first two arguments, the arguments of init_struct must be\n',...
            'key-value pairs giving non-default parameter values.']));

    end

    for a = 1:(floor(nargin/2) - 1)

        % is.(varargin{2*a - 1}) = varargin{2*a};

        if any(strcmp(varargin{2*a - 1}, keys))

            display(sprintf('Replacing default %s.', varargin{2*a - 1}))

            is.(keys{strcmp(varargin{2*a - 1}, keys)}) = varargin{2*a};

        else

            is.(varargin{2*a - 1}) = varargin{2*a};

        end

    end

end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto

package com.google.cloud.securitycenter.v1beta1;

public interface ListFindingsResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.securitycenter.v1beta1.ListFindingsResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Findings matching the list request.
   *

   *
   * repeated .google.cloud.securitycenter.v1beta1.Finding findings = 1;
   */
  java.util.List<com.google.cloud.securitycenter.v1beta1.Finding> getFindingsList();
  /**
   *
   *
   *

   * Findings matching the list request.
   *

   *
   * repeated .google.cloud.securitycenter.v1beta1.Finding findings = 1;
   */
  com.google.cloud.securitycenter.v1beta1.Finding getFindings(int index);
  /**
   *
   *
   *

   * Findings matching the list request.
   *

   *
   * repeated .google.cloud.securitycenter.v1beta1.Finding findings = 1;
   */
  int getFindingsCount();
  /**
   *
   *
   *

   * Findings matching the list request.
   *

   *
   * repeated .google.cloud.securitycenter.v1beta1.Finding findings = 1;
   */
  java.util.List<? extends com.google.cloud.securitycenter.v1beta1.FindingOrBuilder>
      getFindingsOrBuilderList();
  /**
   *
   *
   *

   * Findings matching the list request.
   *

   *
   * repeated .google.cloud.securitycenter.v1beta1.Finding findings = 1;
   */
  com.google.cloud.securitycenter.v1beta1.FindingOrBuilder getFindingsOrBuilder(int index);

  /**
   *
   *
   *

   * Time used for executing the list request.
   *

   *
   * .google.protobuf.Timestamp read_time = 2;
   *
   * @return Whether the readTime field is set.
   */
  boolean hasReadTime();
  /**
   *
   *
   *

   * Time used for executing the list request.
   *

   *
   * .google.protobuf.Timestamp read_time = 2;
   *
   * @return The readTime.
   */
  com.google.protobuf.Timestamp getReadTime();
  /**
   *
   *
   *

   * Time used for executing the list request.
   *

   *
   * .google.protobuf.Timestamp read_time = 2;
   */
  com.google.protobuf.TimestampOrBuilder getReadTimeOrBuilder();

  /**
   *
   *
   *

   * Token to retrieve the next page of results, or empty if there are no more
   * results.
   *

   *
   * string next_page_token = 3;
   *
   * @return The nextPageToken.
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * Token to retrieve the next page of results, or empty if there are no more
   * results.
   *

   *
   * string next_page_token = 3;
   *
   * @return The bytes for nextPageToken.
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();

  /**
   *
   *
   *

   * The total number of findings matching the query.
   *

   *
   * int32 total_size = 4;
   *
   * @return The totalSize.
   */
  int getTotalSize();
}


text:
using boost::tuple;
using namespace std;
using namespace std::tr1;

namespace Hack {

struct Candidate;
typedef SmallVectorInt JVector;
typedef vector<Candidate*> CandidateHeap;
typedef vector<Candidate*> CandidateList;

// life cycle: candidates are created, placed on the heap
// and retrieved by their estimated cost, when they're
// retrieved, they're incorporated into the +LM hypergraph
// where they also know the head node index they are
// attached to.  After they are added to the +LM hypergraph
// inside_prob_ and est_prob_ fields may be updated as better
// derivations are found (this happens since the successor's
// of derivation d may have a better score- they are
// explored lazily).  However, the updates don't happen
// when a candidate is in the heap so maintaining the heap
// property is not an issue.
struct Candidate {
  int node_index_;                     // -1 until incorporated
                                       // into the +LM forest
  const Hypergraph::Edge* in_edge_;    // in -LM forest
  Hypergraph::Edge out_edge_;
  vector<WordID> state_;
  const JVector j_;
  prob_t inside_prob_;            // these are fixed until the cand
                               // is popped, then they may be updated
  prob_t est_prob_;

  Candidate(const Hypergraph::Edge& e,
            const JVector& j,
            const vector<CandidateList>& D,
            bool is_goal) :
      node_index_(-1),
      in_edge_(&e),
      j_(j) {
    InitializeCandidate(D, is_goal);
  }

  // used to query uniqueness
  Candidate(const Hypergraph::Edge& e,
            const JVector& j) : in_edge_(&e), j_(j) {}

  bool IsIncorporatedIntoHypergraph() const {
    return node_index_ >= 0;
  }

  void InitializeCandidate(const vector<vector<Candidate*> >& D,
                           const bool is_goal) {
    const Hypergraph::Edge& in_edge = *in_edge_;
    out_edge_.rule_ = in_edge.rule_;
    out_edge_.feature_values_ = in_edge.feature_values_;
    Hypergraph::TailNodeVector& tail = out_edge_.tail_nodes_;
    tail.resize(j_.size());
    prob_t p = prob_t::One();
    // cerr << "\nEstimating application of " << in_edge.rule_->AsString() << endl;
    vector<const vector<WordID>* > ants(tail.size());
    for (unsigned i = 0; i < tail.size(); ++i) {
      const Candidate& ant = *D[in_edge.tail_nodes_[i]][j_[i]];
      ants[i] = &ant.state_;
      assert(ant.IsIncorporatedIntoHypergraph());
      tail[i] = ant.node_index_;
      p *= ant.inside_prob_;
    }
    prob_t edge_estimate = prob_t::One();
    if (is_goal) {
      assert(tail.size() == 1);
      out_edge_.edge_prob_ = in_edge.edge_prob_;
    } else {
      in_edge.rule_->ESubstitute(ants, &state_);
      out_edge_.edge_prob_ = in_edge.edge_prob_;
    }
    inside_prob_ = out_edge_.edge_prob_ * p;
    est_prob_ = inside_prob_ * edge_estimate;
  }
};

ostream& operator<<(ostream& os, const Candidate& cand) {
  os << "CAND[";
  if (!cand.IsIncorporatedIntoHypergraph()) { os << "PENDING "; }
  else { os << "+LM_node=" << cand.node_index_; }
  os << " edge=" << cand.in_edge_->id_;
  os << " j=<";
  for (unsigned i = 0; i < cand.j_.size(); ++i)
    os << (i==0 ? "" : " ") << cand.j_[i];
  os << "> vit=" << log(cand.inside_prob_);
  os << " est=" << log(cand.est_prob_);
  return os << ']';
}

struct HeapCandCompare {
  bool operator()(const Candidate* l, const Candidate* r) const {
    return l->est_prob_ < r->est_prob_;
  }
};

struct EstProbSorter {
  bool operator()(const Candidate* l, const Candidate* r) const {
    return l->est_prob_ > r->est_prob_;
  }
};

// the same candidate <edge, j> can be added multiple times if
// j is multidimensional (if you're going NW in Manhattan, you
// can first go north, then west, or you can go west then north)
// this is a hash function on the relevant variables from
// Candidate to enforce this.
struct CandidateUniquenessHash {
  size_t operator()(const Candidate* c) const {
    size_t x = 5381;
    x = ((x << 5) + x) ^ c->in_edge_->id_;
    for (unsigned i = 0; i < c->j_.size(); ++i)
      x = ((x << 5) + x) ^ c->j_[i];
    return x;
  }
};

struct CandidateUniquenessEquals {
  bool operator()(const Candidate* a, const Candidate* b) const {
    return (a->in_edge_ == b->in_edge_) && (a->j_ == b->j_);
  }
};

typedef unordered_set<const Candidate*, CandidateUniquenessHash, CandidateUniquenessEquals> UniqueCandidateSet;
typedef unordered_map<vector<WordID>, Candidate*, boost::hash<vector<WordID> > > State2Node;

class MaxTransBeamSearch {

public:
  MaxTransBeamSearch(const Hypergraph& i, int pop_limit, Hypergraph* o) :
      in(i),
      out(*o),
      D(in.nodes_.size()),
      pop_limit_(pop_limit) {
    cerr << "  Finding max translation (cube pruning, pop_limit = " << pop_limit_ << ')' << endl;
  }

  void Apply() {
    const unsigned num_nodes = in.nodes_.size();
    const unsigned goal_id = num_nodes - 1;
    const unsigned pregoal = goal_id - 1;
    assert(in.nodes_[pregoal].out_edges_.size() == 1);
    cerr << "    ";
    for (unsigned i = 0; i < in.nodes_.size(); ++i) {
      cerr << '.';
      KBest(i, i == goal_id);
    }
    cerr << endl;
    int best_node = D[goal_id].front()->in_edge_->tail_nodes_.front();
    Candidate& best = *D[best_node].front();
    cerr << "  Best path: " << log(best.inside_prob_)
         << "\t" << log(best.est_prob_) << endl;
    cout << TD::GetString(D[best_node].front()->state_) << endl;
    FreeAll();
  }

 private:
  void FreeAll() {
    for (unsigned i = 0; i < D.size(); ++i) {
      CandidateList& D_i = D[i];
      for (unsigned j = 0; j < D_i.size(); ++j)
        delete D_i[j];
    }
    D.clear();
  }

  void IncorporateIntoPlusLMForest(Candidate* item, State2Node* s2n, CandidateList* freelist) {
    Hypergraph::Edge* new_edge = out.AddEdge(item->out_edge_.rule_, item->out_edge_.tail_nodes_);
    new_edge->feature_values_ = item->out_edge_.feature_values_;
    new_edge->edge_prob_ = item->out_edge_.edge_prob_;
    Candidate*& o_item = (*s2n)[item->state_];
    if (!o_item) o_item = item;

    int& node_id = o_item->node_index_;
    if (node_id < 0) {
      Hypergraph::Node* new_node = out.AddNode(in.nodes_[item->in_edge_->head_node_].cat_);
      node_id = new_node->id_;
    }
    Hypergraph::Node* node = &out.nodes_[node_id];
    out.ConnectEdgeToHeadNode(new_edge, node);

    if (item != o_item) {
      assert(o_item->state_ == item->state_);    // sanity check!
      o_item->est_prob_ += item->est_prob_;
      o_item->inside_prob_ += item->inside_prob_;
      freelist->push_back(item);
    }
  }

  void KBest(const int vert_index, const bool is_goal) {
    // cerr << "KBest(" << vert_index << ")\n";
    CandidateList& D_v = D[vert_index];
    assert(D_v.empty());
    const Hypergraph::Node& v = in.nodes_[vert_index];
    // cerr << "  has " << v.in_edges_.size() << " in-coming edges\n";
    const vector<int>& in_edges = v.in_edges_;
    CandidateHeap cand;
    CandidateList freelist;
    cand.reserve(in_edges.size());
    UniqueCandidateSet unique_cands;
    for (unsigned i = 0; i < in_edges.size(); ++i) {
      const Hypergraph::Edge& edge = in.edges_[in_edges[i]];
      const JVector j(edge.tail_nodes_.size(), 0);
      cand.push_back(new Candidate(edge, j, D, is_goal));
      assert(unique_cands.insert(cand.back()).second);  // these should all be unique!
    }
//    cerr << "  making heap of " << cand.size() << " candidates\n";
    make_heap(cand.begin(), cand.end(), HeapCandCompare());
    State2Node state2node;   // "buf" in Figure 2
    int pops = 0;
    while(!cand.empty() && pops < pop_limit_) {
      pop_heap(cand.begin(), cand.end(), HeapCandCompare());
      Candidate* item = cand.back();
      cand.pop_back();
      // cerr << "POPPED: " << *item << endl;
      PushSucc(*item, is_goal, &cand, &unique_cands);
      IncorporateIntoPlusLMForest(item, &state2node, &freelist);
      ++pops;
    }
    D_v.resize(state2node.size());
    int c = 0;
    for (State2Node::iterator i = state2node.begin(); i != state2node.end(); ++i)
      D_v[c++] = i->second;
    sort(D_v.begin(), D_v.end(), EstProbSorter());
    // cerr << "  expanded to " << D_v.size() << " nodes\n";

    for (unsigned i = 0; i < cand.size(); ++i)
      delete cand[i];
    // freelist is necessary since even after an item merged, it still stays in
    // the unique set so it can't be deleted til now
    for (unsigned i = 0; i < freelist.size(); ++i)
      delete freelist[i];
  }

  void PushSucc(const Candidate& item, const bool is_goal, CandidateHeap* pcand, UniqueCandidateSet* cs) {
    CandidateHeap& cand = *pcand;
    for (unsigned i = 0; i < item.j_.size(); ++i) {
      JVector j = item.j_;
      ++j[i];
      if (static_cast<unsigned>(j[i]) < D[item.in_edge_->tail_nodes_[i]].size()) {
        Candidate query_unique(*item.in_edge_, j);
        if (cs->count(&query_unique) == 0) {
          Candidate* new_cand = new Candidate(*item.in_edge_, j, D, is_goal);
          cand.push_back(new_cand);
          push_heap(cand.begin(), cand.end(), HeapCandCompare());
          assert(cs->insert(new_cand).second);  // insert into uniqueness set, sanity check
        }
      }
    }
  }

  const Hypergraph& in;
  Hypergraph& out;

  vector<CandidateList> D;   // maps nodes in in-HG to the
                                   // equivalent nodes (many due to state
                                   // splits) in the out-HG.
  const int pop_limit_;
};

// each node in the graph has one of these, it keeps track of
void MaxTrans(const Hypergraph& in,
              int beam_size) {
  Hypergraph out;
  MaxTransBeamSearch ma(in, beam_size, &out);
  ma.Apply();
}

}


text:
"""This module handles the whole auto smart completion sublime-rainmeter has to offer."""

# python libs
import re

# st libs
import sublime

# own libs
from .. import logger
from .skin.rainmeter_section import SkinRainmeterSectionAutoComplete
from .skin.metadata_section import SkinMetadataSectionAutoComplete
from .section import SkinSectionAutoCompleter

class ContextSensAutoCompletion(object):
    """
    This represents the internal implementation for the contextual auto completion.

    It uses smart environmental information like section, key, values etc
    to provide smarter auto completion suggestions.
    """

    # only show our completion list because nothing else makes sense in this context
    flags = sublime.INHIBIT_EXPLICIT_COMPLETIONS | sublime.INHIBIT_WORD_COMPLETIONS

    section = None
    skin_rainmeter_section = None
    skin_metadata_section = None

    scope = "source.rainmeter"

    # comments are specified by ';'
    comment_exp = re.compile(r'^\s*;.*')

    # enable searching for [] in multiline environment
    bracket_expression = re.compile(r'^\s*(\[.+\])\s*$', re.MULTILINE)
    section_expression = re.compile(r'^\s*\[(.+)\]\s*$', re.I)
    key_expression = re.compile(r'^\s*(.+)\s*=?\s*(.*?)\s*$', re.MULTILINE)
    key_value_expression = re.compile(r'^\s*(.+?)\s*=\s*(.*?)\s*$', re.MULTILINE)

    def __init__(self):
        """Initialize the different completer components."""
        self.section = SkinSectionAutoCompleter()
        self.skin_rainmeter_section = SkinRainmeterSectionAutoComplete()
        self.skin_metadata_section = SkinMetadataSectionAutoComplete()

    def get_lines_of_section_on_cursor(self, view, location):
        """Determine content of current section."""
        size = view.size()
        start_content = view.substr(sublime.Region(0, location))
        end_content = view.substr(sublime.Region(location, size))

        start_index = self.get_start_index_of_section(start_content)
        end_index = self.get_end_index_of_section(end_content, location, size)

        section = view.substr(sublime.Region(start_index, end_index))
        lines = section.splitlines()

        return start_index, lines

    def get_start_index_of_section(self, start_content):
        """
        Return the index of the section.

        If no section is found the first index (0) is returned
        """
        matches = list(self.bracket_expression.finditer(start_content))

        if len(matches) > 0:
            last_match = matches[-1]
            return last_match.start()

        # no previous section found, hardly legal but who cares
        else:
            return 0

    def get_end_index_of_section(self, end_content, offset, end_index):
        """
        Return the index of the next section.

        If no next section is found the last index is returned given through the param end_index
        """
        matches = list(self.bracket_expression.finditer(end_content))
        if len(matches) > 0:
            first_match = matches[0]
            return first_match.start() + offset

        # no next section found
        else:
            return end_index

    def get_key_value(self, line_content):
        """
        Extract the key and/or value in a line if existing.

        This is used if a specific completion is only shown
        on special conditions like only show X on measures.

        If nothing is given return (None, None)
        """
        key_value_match = self.key_value_expression.search(line_content)
        if key_value_match:
            key_match = key_value_match.group(1)
            value_match = key_value_match.group(2)
            logger.info(
                "key/value found in '" + line_content +
                "' with ('" + key_match + "', '" + value_match + "')"
            )

            return key_match, value_match

        key_only_match = self.key_expression.search(line_content)
        if key_only_match:
            logger.info("potential key found in '" + line_content + "'")
            return key_only_match.group(1), None

        return None, None

    def get_key_values(self, lines):
        """Extract all key values in the given lines."""
        key_values = []

        for line in lines:
            key, value = self.get_key_value(line)
            if key:
                key_values.append((key, value))

        return key_values

    def __autocomplete_value(self, line_content, section):
        key_match, value_match = self.get_key_value(line_content)

        if value_match == "":
            logger.info("auto-completing value: cursor after equal trigger in '" + line_content + "'")
            # value trigger
            return self.skin_rainmeter_section.get_value_context_completion(
                section,
                key_match
            )

    def __autocomplete_key(self, line_content, prefix, section, key_values):
        # only do key completion if we are in the key are
        # that means in front of the equal or no equal at all
        logger.info("before equal trigger in '" + line_content + "'")
        key_result = self.skin_rainmeter_section.get_key_context_completion(
            prefix,
            line_content,
            section,
            key_values
        )

        return key_result

    @classmethod
    def __autocomplete_default(cls):
        return None

    def on_query_completions(self, view, prefix, locations):
        """
        Execute if a auto completion is requested.

        can be either via typing or manual invoked with ctrl+space.

        This provides general variable extractions which are then
        passed to the domain specific worker completions.
        """
        for location in locations:
            # ignore non scope
            if not view.match_selector(location, self.scope):
                return None

            # ignore on comment lines
            cursor_line = view.line(location)
            line_content = view.substr(cursor_line)
            if self.comment_exp.search(line_content):
                logger.info("found comment")
                return None

            # find last occurance of the [] to determine the ini sections
            section_start_index, section_lines = self.get_lines_of_section_on_cursor(view, location)

            # determine auto completions of sections on double newline
            line_start_coord = cursor_line.begin()
            row, _ = view.rowcol(line_start_coord)
            section_start = view.rowcol(section_start_index)
            section_start_row, _ = section_start

            if row > 2:
                line_above_empty = section_lines[row - section_start_row - 1] == ''
                line_aabove_empty = section_lines[row - section_start_row - 2] == ''

                if line_above_empty and line_aabove_empty:
                    size = view.size()
                    content = view.substr(sublime.Region(0, size))
                    sections = self.bracket_expression.findall(content)

                    return self.section.get_key_context_completion(prefix, line_content, sections)

            # filter empty lines
            section_lines = [section_line for section_line in section_lines if section_line]
            # filter comments
            section_lines = [line for line in section_lines if not self.comment_exp.search(line)]

            if not section_lines:
                logger.info("section is empty")
                size = view.size()
                content = view.substr(sublime.Region(0, size))
                sections = self.bracket_expression.findall(content)

                return self.section.get_key_context_completion(prefix, line_content, sections)

            # extract section
            first_line = section_lines[0]
            match = self.section_expression.search(first_line)

            section = match.group(1)
            key_values = self.get_key_values(section_lines)

            return self.__autocomplete_value(line_content, section) or \
                self.__autocomplete_key(line_content, prefix, section, key_values) or \
                self.__autocomplete_default()


text:
package org.minijs.core.ast;

import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.Test;

import java.util.List;

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

public class ExpressionStatementTest extends BaseParserTest {

    @Test
    public void testExpressionStatement() {
        String[] statements = {
                "1 + 1;",
                "a + b;",
                "-a;",
        };

        for (int i = 0; i < statements.length; i++) {
            initParser(statements[i]);
            ParseTree tree = mParser.program();
            Node node = mVisitor.visit(tree);

            assertTrue(node instanceof BlockStatement);
            List<Statement> statementList = ((BlockStatement) node).getSubStatementList();
            assertEquals(1, statementList.size());
            assertEquals(ExpressionStatement.class, statementList.get(0).getClass());
        }
    }
}


text:
#import "FBSimulatorScale.h"

#pragma mark Scales

@implementation FBSimulatorScale_25

- (NSString *)scaleString
{
  return @"0.25";
}

@end

@implementation FBSimulatorScale_50

- (NSString *)scaleString
{
  return @"0.50";
}

@end

@implementation FBSimulatorScale_75

- (NSString *)scaleString
{
  return @"0.75";
}

@end

@implementation FBSimulatorScale_100

- (NSString *)scaleString
{
  return @"1.00";
}

@end


text:
% Date: 23.10.2004
%:- if(\+ current_module(consult_server)).

:- module(consult_server,[
	consult_server/1,
	consult_server/2,
	get_var_names/2
	]).

%:-debug(consult_server(startup)).
%:-debug(consult_server(shutdown)).
%:-debug(consult_server(accept_loop)).
%:-debug(consult_server(handler)).
%:-debug(handle_command).

:- use_module(library(socket)).
:- use_module(library(lists)).
:- use_module(library(readutil)).
:- use_module(library(charsio)).
:- use_module(library(debug)).

option_default(interprete_lists,true).
option_default(canonical,false).

:- dynamic option_value/2.
:- thread_local option_value/2.
option(Name,Value):-
    option_value(Name,AValue),
    !,
    Value=AValue.
option(Name,Value):-
	option_default(Name,Value).

set_option(Name,Value):-
	retractall(option_value(Name,_)),
	assert(option_value(Name,Value)).

unset_option(Name):-
	retractall(option_value(Name,_)).

clear_options:-
	retractall(option_value(_,_)).

create_lock_file(Filename):-
  delete_lock_file(Filename),
	(	exists_file(Filename)
	->	debug(consult_server(init), 'Found existing lock file ~w.~n Shutting down...~n', [Filename]),
		dmsg(thread_signal(main,halt))
	;	open(Filename, write, Stream),
		call_cleanup(
			(	write(Stream,Filename),
				nl(Stream)
			),
			close(Stream)
		)
	).

delete_lock_file(Filename):-
	(	exists_file(Filename)
	->	delete_file(Filename)
	;	true
	).

:- multifile process_shutdown_hook/0.
:- dynamic process_shutdown_hook/0.

process_shutdown_hook.

call_shutdown_hook:-
    forall(process_shutdown_hook,true).

do_shutdown:-
   	debug(consult_server(shutdown), 'begin shutdown ~n', []),
   	call_shutdown_hook,
    %join any thread that is not main.
    (	current_thread(Id,_),
	    do_shutdown_X(Id),
       	fail
	;	debug(consult_server(shutdown), 'shutdown complete~n',[]),
		threads,
		dmsg(halt)
	).
do_shutdown_X(Id):-
    Id\==main,
    debug(consult_server(shutdown), 'joining ~w~n',[Id]),
    thread_join(Id,Status),
    debug(consult_server(shutdown), 'successfully joined ~w, status: ~w ~n', [Id,Status]).

consult_server(Port):-
	tcp_socket(ServerSocket),
	tcp_setopt(ServerSocket, reuseaddr),
	tcp_bind(ServerSocket, Port),
	tcp_listen(ServerSocket, 5),
	atomic_list_concat([consult_server,'@',Port],Alias),
	recordz(process_flag,port(Port),_),
	thread_create(accept_loop(ServerSocket), _,[alias(Alias)]).

consult_server(Port,Lockfile):-
	consult_server(Port),
	create_lock_file(Lockfile).

accept_loop(ServerSocket):-
	catch(
		accept_loop_impl(ServerSocket),
		Error,
		(
			debug(consult_server(accept_loop), 'accept loop encountered an error:~w~n. Shutting down...~n',[Error]),
			thread_signal(main,halt)
		)
	),
	debug(consult_server(shutdown), 'signaling main to shutdown... ~n',[]),
	thread_signal(main,do_shutdown),
	debug(consult_server(shutdown), 'shutdown signal send, exit current thread. ~n',[]).

accept_loop_impl(ServerSocket) :-
	debug(consult_server(accept_loop), 'enter accept_loop_impl~n', []),
	tcp_accept(ServerSocket, Slave, Peer),
	debug(consult_server(accept_loop),'accepted inbound connection~n',[]),
	debug(consult_server(accept_loop),'connect from host ~w~n',[Peer]),
	accept_loop_impl_X(ServerSocket,Slave).

accept_loop_impl_X(ServerSocket,Slave):-
    debug(consult_server(shutdown),'Checking for shutdown flag. ~n',[]),
    recorded(process_flag,shutdown,_),
    !,
    debug(consult_server(shutdown),'Shutdown flag is set. We are closing down. ~n',[]),
    tcp_close_socket(Slave),
    tcp_close_socket(ServerSocket).

accept_loop_impl_X(ServerSocket,Slave):-
	debug(consult_server(accept_loop),'enter accept_loop_impl_X~n',[]),
	tcp_open_socket(Slave, InStream, OutStream),
	debug(consult_server(accept_loop),'socket opened~n',[]),
	unused_thread_name(handle_client,'',Alias),
	debug(consult_server(accept_loop),'handler thread alias: ~w~n',[Alias]),
	garbage_collect,
	debug(consult_server(accept_loop),'garbage collected~n',[]),
	debug(consult_server(accept_loop),'creating thread ~w.~n',[Alias]),
	thread_create(handle_client(InStream, OutStream), _ , [alias(Alias),detached(true)]),
	debug(consult_server(accept_loop),'successfully created thread ~w.~n',[Alias]),
	accept_loop_impl(ServerSocket).

handler_at_exit(InStream,OutStream):-
	debug(consult_server(handler),'Thread is exiting. Trying to close the connection...~n',[]),
	catch(
		(	byebye(InStream,OutStream),
			debug(consult_server(handler),'Connection closed successfully. ~n',[])
		),
		E,
		debug(consult_server(handler),'Error encountered while closing the connection: ~w.~n',[E])
	).

handle_client(InStream, OutStream):-
	thread_at_exit(handler_at_exit(InStream,OutStream)),
    set_stream(InStream,encoding(utf8)),
    set_stream(OutStream,encoding(utf8)),
	repeat,
		debug(consult_server(handler),'start hanlde_client~n',[]),
		catch(
			handle_client_impl(InStream,OutStream),
			Error,
			(	handle_exception(InStream,OutStream,Error,Action),
				!,
				Action==stop
			)
		),
	!,
	debug(consult_server(handler),'Thread exiting...~n',[]).

handle_client_impl(InStream, OutStream):-
    repeat,
		request_line(InStream,OutStream,'GIVE_COMMAND',Command),
		( handle_command(InStream,OutStream,Command,Next)
		->report_ok(OutStream)
		;	%report_error(OutStream, 'failed, sorry.'),
			Next=continue
		),
	Next==stop,
	!.

handle_command(_,_,'BYE',stop) :-
	!.
handle_command(_,_,'SHUTDOWN',stop):-
	!,
	% stop accept loop:
	% we set the shutdown flag (which is read by the accept loop)
	% then we have to kick the accept loop out of the tcp_accept/3 call.
	% we do this by simply opening a connection to the listen port.

	recordz(process_flag,shutdown,_),
	recorded(process_flag,port(Port),_),
	tcp_socket(Socket),
	tcp_connect(Socket,localhost:Port),
	tcp_close_socket(Socket).
handle_command(_,_,'',continue):-
	!,
	clear_options.
handle_command(_,OutStream,'PING',continue):-
	!,
	current_prolog_flag(pid,Pid),
    thread_self(Alias),
	my_format(OutStream,'PONG ~w:~w~n',[Pid,Alias]).
handle_command(InStream,OutStream,'ENTER_BATCH',continue):-
	!,
	my_format(OutStream,'GO_AHEAD~n',[]),
	repeat,
		handle_batch_messages(OutStream),
		my_read_command(InStream,Term),
		handle_batch_command(Term,InStream,OutStream),
		Term=end_of_batch,!.
handle_command(InStream,OutStream,'QUERY',continue):-
	!,
	debug('handle_command', 'before my_format', []),
	my_format(OutStream,'GIVE_TERM~n',[]),
	debug('handle_command', 'after my_format', []),
	call_save(OutStream,my_read_term(InStream,Term,[variable_names(Vars)/*,double_quotes(string)*/])),
	(
	(debug('handle_command', 'before iterate_solutions ~w', [Term]),
	iterate_solutions(InStream,OutStream,Term,Vars),
	debug('handle_command', 'after iterate_solutions ~w', [Term]))
	; true
	).
handle_command(InStream,OutStream,'QUERY_ALL',continue):-
	!,
	my_format(OutStream,'GIVE_TERM~n',[]),
	call_save(OutStream,my_read_term(InStream,Term,[variable_names(Vars)/*,double_quotes(string)*/])),
	(
		all_solutions(OutStream,Term,Vars)
	;
		true
	).
handle_command(InStream,OutStream,'SET_OPTION',continue):-
	!,
	request_line(InStream,OutStream,'GIVE_SYMBOL',Symbol),
	request_line(InStream,OutStream,'GIVE_TERM',Term),
	call_save(OutStream,set_option(Symbol,Term)).
handle_command(InStream,OutStream,'GET_OPTION',continue):-
	!,
	request_line(InStream,OutStream,'GIVE_SYMBOL',Symbol),
	call_save(OutStream,
		(	option(Symbol,Term),
			my_format(OutStream,'~w~n',[Term])
		)
	).

my_read_command(InStream,Term):-
    my_read_term(InStream,Term,[]).

my_read_goal(InStream,Term,Vars):-
    my_read_term(InStream,Term,[variable_names(Vars)]).

handle_batch_messages(OutStream):-
    repeat,
    (	thread_peek_message(batch_message(Message)),
    	debug(consult_server(handler),'recieved message: ~w~n',[Message]),
    	handle_batch_message(Message, OutStream)
    ->	thread_get_message(batch_message(Message)),
		debug(consult_server(handler),'dequeued message: ~w~n',[Message]),
    	fail
    ;	true
    ),
    !.

%note on aborts: an abort request is complete if BOTH the async abort message aswell as the
%sync abort marker have been recieved. I originally assumed that the async message would always
%preceed the marker, but it seems to be more tricky. So i will now handle this symetrically.

record_abort_request(Type,Id):-
    thread_self(Thread),
    (	recorded(process_batch_abort,request(Thread,Type,Id),_)
    ->	true
    ;	recordz(process_batch_abort,request(Thread,Type,Id),_)
    ).

erase_abort_request(Type,Id):-
    thread_self(Thread),
    (	recorded(process_batch_abort,request(Thread,Type,Id),Ref)
    ->	erase(Ref)
    ;	true
    ).

abort_requested(Type,Id):-
	thread_self(Thread),
	recorded(process_batch_abort,request(Thread,Type,Id),_).

aborting:-
    abort_requested(async,_).

send_abort_complete(Id,OutStream):-
   	my_format(OutStream, 'ABORT_COMPLETE: ~w~n',[Id]).

handle_batch_message(abort(Id),OutStream):-
	debug(consult_server,'recieved abort (async, id=~w)~n',[Id]),
	(	abort_requested(sync,Id)
	->	erase_abort_request(sync,Id),
		send_abort_complete(Id,OutStream)
	;	record_abort_request(async,Id),
		debug(consult_server(handler),'recorded abort (async, id=~w)~n',[Id])
	).
handle_batch_command(set_option(Option,Value),_,OutStream):-
	call_save(OutStream,set_option(Option,Value)).
handle_batch_command(abort(Id),_,OutStream):-
    debug(consult_server(handler),'recieved abort (sync, id=~w)~n',[Id]),
	(	abort_requested(async,Id)
	->	erase_abort_request(async,Id),
		send_abort_complete(Id,OutStream)
	;	record_abort_request(sync,Id),
	    debug(consult_server(handler),'recorded abort (sync, id=~w)~n',[Id])
	).
handle_batch_command(join(Id),_,OutStream):-
	my_format(OutStream, 'JOIN_COMPLETE: ~w~n',[Id]).
handle_batch_command(end_of_batch,InStream,OutStream):-
	forall(abort_requested(async,Id),handle_batch_command(abort(Id),InStream,OutStream)),
	forall(abort_requested(sync,Id),handle_batch_message(abort(Id),OutStream)),
	my_format(OutStream, 'END_OF_BATCH_COMPLETE~n',[]).
handle_batch_command(query_once(Id),InStream,OutStream):-
	aborting,
    !,
    my_read_goal(InStream,_,_),
    my_format(OutStream, 'SKIPPING_QUERY: ~w~n',[Id]).
handle_batch_command(query_all(Id),InStream,OutStream):-
    aborting,
    !,
    my_read_goal(InStream,_,_),
    my_format(OutStream, 'SKIPPING_QUERY: ~w~n',[Id]).

handle_batch_command(query_once(Id),InStream,OutStream):-
    my_format(OutStream, 'RESULTS_FOR_QUERY: ~w~n',[Id]),
    call_save(OutStream,(
    		my_read_goal(InStream,Goal,Vars),
    		one_solution(OutStream,Goal,Vars)
    		)
    	).
handle_batch_command(query_all(Id),InStream,OutStream):-
    my_format(OutStream, 'RESULTS_FOR_QUERY: ~w~n',[Id]),
    call_save(OutStream,(
    		my_read_goal(InStream,Goal,Vars),
    		solutions_weak_until_cut(OutStream,Goal,Vars)
    		)
    	).

call_save(OutStream, Goal):-
    catch(Goal,
	    Error,
    		report_error(OutStream,Error)
    	).

solutions_weak_until_cut(OutStream,Term,Vars):-
	(	solutions_until_cut(OutStream,Term,Vars)
	->	my_format(OutStream, 'CUT~n',[])
	;	solutions_yes_or_no(OutStream)
	).

solutions_until_cut(OutStream,Term,Vars):-
	user:Term,
	nb_setval(hasSolutions,1),
	print_solution(OutStream,Vars),
	goal_was_cut(OutStream),!.

goal_was_cut(OutStream):-
	handle_batch_messages(OutStream),
	aborting.

solutions_yes_or_no(OutStream):-
	(	nb_current(hasSolutions,1)
	->	my_format(OutStream,'YES~n',[]),
		nb_delete(hasSolutions)
	; 	my_format(OutStream,'NO~n',[])
	).

one_solution(OutStream,Term,Vars):-
	( 	user:Term
	->	consult_server:print_solution(OutStream,Vars),
		my_format(OutStream,'YES~n',[])
	; 	my_format(OutStream,'NO~n',[])
	).

all_solutions(OutStream,Term,Vars):-
	user:forall(
		catch(Term,E,throw(wrapped(E))),
		(
			consult_server:print_solution(OutStream,Vars),
			nb_setval(hasSolutions,1)
		)
	),
	(	nb_current(hasSolutions,1)
	->	my_format(OutStream,'YES~n',[]),
		nb_delete(hasSolutions)
	;	my_format(OutStream,'NO~n',[])
	).

iterate_solutions(InStream,OutStream,Term,Vars):-
	( user:forall(
			catch(Term,E,throw(wrapped(E))),
			(
				consult_server:print_solution(OutStream,Vars),
				consult_server:request_line(InStream,OutStream,'MORE?','YES')
			)
		)
	->my_format(OutStream,'NO~n',[])
	; my_format(OutStream,'YES~n',[])
	).

print_solution(OutStream,Vars):-
	forall(
		(member(Key=Val,Vars), filter_variable(Val)),
		print_binding(OutStream,Key,Val,Vars)
	),
	my_format(OutStream,'END_OF_SOLUTION~n',[]).

filter_variable(_) :-
	option(unbound_variables,true), !.

filter_variable(Val) :-
	nonvar(Val).

print_binding(Out,Key,Val,Vars):-
		my_write(Out,'<'),
		write(Out,Key),
		my_write(Out, '>'),
		print_value(Out,Val,Vars),
		nl(Out).

print_values([],_,_).
print_values([Head|Tail],Out,Vars):-
	print_value(Out,Head,Vars),
	print_values(Tail,Out,Vars).

print_value(Out,Val,Vars):-
	option(canonical,true),
	!,
	my_write(Out,'<'),
	(write_escaped(Out,Val,Vars);true),
	my_write(Out, '>').
print_value(Out,Val,Vars):-
	( 	is_list(Val), option(interprete_lists,true)
 	->	my_write(Out,'{'),
		print_values(Val,Out,Vars),
		my_write(Out, '}')
	;	my_write(Out,'<'),
		write_escaped(Out,Val,Vars),
		my_write(Out, '>')
	).

handle_exception(InStream,OutStream,Error,Action):-
    debug(consult_server(handler), 'handle_excpetion (pre): Up:~w, Down:~w, Error:~w~n',[InStream,OutStream,Error]),
    handle_exception_X(InStream,OutStream,Error,Action),
    debug(consult_server(handler), 'handle_excpetion (post): Action:~w~n',[Action]).

handle_exception_X(InStream,OutStream,Error,Action):-
	var(Error),
	!,
	handle_exception(InStream,OutStream,unbound_error_term,Action).

handle_exception_X(_InStream,OutStream,peer_reset,continue):-
	catch(
		(
			my_format(OutStream,'RESET~n',[]),
			report_ok(OutStream)
		),
		_,(
		%	shut_down(InStream,OutStream),
			fail
			)
	),
	!.

handle_exception_X(_InStream,OutStream,wrapped(Error),continue):-
	catch(
		report_error(OutStream,Error),
		_,(
%			shut_down(InStream,OutStream),
			fail
			)
	),
	!.

handle_exception_X(_InStream,OutStream,fatal_read_term_error(Error),stop):-
	catch(
		report_error(OutStream,Error),
		_,(
%			shut_down(InStream,OutStream),
			fail
			)
	),
	!.

handle_exception_X(_InStream,_OutStream,Error,stop):-
	debug(consult_server(handler),'Unhandled Exception :~w~n Trying to shut down...~n',[Error]).

report_ok(OutStream):-
	my_format(OutStream,'OK~n',[]).

report_error(OutStream, Error):-
	(	var(Error)
	->	my_format(OutStream,'ERROR: unbound error term~n',[])
	;	my_format(OutStream,'ERROR: ~w~n',[Error])
	).

byebye(InStream,OutStream):-
	debug(consult_server,'byebye called~n',[]),
	(	is_stream(OutStream)
	->	debug(consult_server(handler),'Downstream is a stream: ~w~n',[OutStream]),
		debug(consult_server(handler),'sending BYE downstream: ~w~n',[OutStream]),
		my_format(OutStream,'BYE~n',[]),
		debug(consult_server(handler),'closing downstream: ~w~n',[OutStream]),
		catch(close(OutStream),E,
			debug(consult_server(handler),'Problem closing downstream: ~w~n',[E])
		)
	;	debug(consult_server(handler),'Downstream is no stream: ~w~n',[OutStream])
	),
	(	is_stream(InStream)
	->	debug(consult_server(handler),'Upstream is a stream: ~w~n',[InStream]),
		debug(consult_server(handler),'closing upstream: ~w~n',[InStream]),
		catch(close(InStream),E,
			debug(consult_server(handler),'Problem closing upstream: ~w~n',[E])
		)
	;	debug(consult_server(handler),'Upstream is no stream: ~w~n',[InStream])
	).

codes_or_eof_to_atom(end_of_file,_):-
	throw(end_of_file).

codes_or_eof_to_atom(Codes,Atom):-
	atom_codes(Atom,Codes).

count_thread(Prefix,Count):-
	findall(A,
		(	my_current_thread(A),
			atom_concat(Prefix,_,A),
			debug(consult_server(handler),'There is e.g. a thread named ~w~n',[A])
		),
		Bag
	),
	length(Bag,Count).

unused_thread_name(Prefix,Suffix,Name):-
	unused_thread_name(Prefix,Suffix,0,Name).

unused_thread_name(Prefix,Suffix,Try,Name):-
	atomic_list_concat([Prefix,Try,Suffix],A),
	(	my_current_thread(A)
	->	plus(Try,1,Next),
		unused_thread_name(Prefix,Suffix,Next,Name)
	;	Name=A
	).

my_current_thread(A) :-
  catch(thread_property(A,status(_)), error(existence_error(thread, _), _), fail).

request_line(InStream, OutStream, Prompt, Line):-
	my_format(OutStream,'~w~n',[Prompt]),
	with_interrupts(5,read_line_to_codes(InStream,LineCodes)),
	codes_or_eof_to_atom(LineCodes,Line),
	debug(consult_server(traffic),'(Up:~w, read_line_to_codes)<<< ~w~n',[InStream,Line]).

my_read_term(InStream,Term,Options):-
	with_interrupts(5,read_term(InStream,Term,Options)),
	debug(consult_server(traffic),'(Up:~w read_term) <<<~w~n',[InStream,Term]).

my_write_term(OutStream,Elm,Options):-
	debug(consult_server(traffic),'(Down:~w write_term) >>>~w~n',[OutStream,Elm]),
	write_term(OutStream,Elm,Options),
	nl(OutStream).
my_write(OutStream,Term):-
	debug(consult_server(traffic),'(Down:~w, write)>>>~w~n',[OutStream,Term]),
	write(OutStream,Term).

my_format(OutStream,Format,Args):-
	atom_concat('(Down:~w, format) >>>',Format,Format2),
	atom_concat(Format2,'~n',Format3),
	debug(consult_server(traffic),Format3,[OutStream|Args]),
	format(OutStream,Format,Args),
	flush_output(OutStream).

my_format(Format,Args):-
    debug(consult_server,Format,Args).

write_escaped(Out,Term,Vars):-
	with_output_to(
		atom(Atom),
		(	current_output(O),
			write_term(O, Term, [ignore_ops(true),quoted(true),variable_names(Vars)])
		)
	),
    escape_chars_in_atom(Atom, EscapedAtom),
    my_write(Out,EscapedAtom).

escape_chars_in_atom(Atom, EscapedAtom) :-
	atom_chars(Atom, List),
	escape_chars_impl(List, EscapedList),
	atom_chars(EscapedAtom, EscapedList).

escape_chars_impl([], []) :- !.

% '<' --> '<'
escape_chars_impl(['<'|Tail], ['&', 'l', 't', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% '>' --> '>'
escape_chars_impl(['>'|Tail], ['&', 'g', 't', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% '{' --> '&cbo;'
escape_chars_impl(['{'|Tail], ['&', 'c', 'b', 'o', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% '}' --> '&cbc;'
escape_chars_impl(['}'|Tail], ['&', 'c', 'b', 'c', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% '&' --> '&'
escape_chars_impl(['&'|Tail], ['&', 'a', 'm', 'p', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% '"' --> '"'
escape_chars_impl(['"'|Tail], ['&', 'q', 'u', 'o', 't', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% '\'' --> '''
escape_chars_impl(['\''|Tail], ['&', 'a', 'p', 'o', 's', ';'|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

% other chars don't need to be translated
escape_chars_impl([Char|Tail], [Char|NewTail]) :-
	escape_chars_impl(Tail, NewTail).

write_term_to_memfile(Term,Memfile,Vars):-
	new_memory_file(Memfile),
	open_memory_file(Memfile,write,Stream),
	call_cleanup(
		/*(	option(canonical,true)
		->	write_canonical(Stream,Term)
		;	write(Stream,Term)
		),*/
		write_term(Stream,Term,[ignore_ops(true),quoted(true),variable_names(Vars)]),
		close(Stream)
	).

escape_stream(In,Out):-
    repeat,
    (	at_end_of_stream(In)
    ->	!
    ;   get_char(In,Char),
	    write_escaped_char(Char,Out),
	    fail
	).

write_escaped_char('<',Out):-
	!,
	write(Out,'<').
write_escaped_char('>',Out):-
	!,
	write(Out,'>').
write_escaped_char('{',Out):-
	!,
	write(Out,'&cbo;').
write_escaped_char('}',Out):-
	!,
	write(Out,'&cbc;').
write_escaped_char('&',Out):-
	!,
	write(Out,'&').
write_escaped_char('"',Out):-
	!,
	write(Out,'"').
write_escaped_char('\'',Out):-
	!,
	write(Out,''').
write_escaped_char(C,Out):-
	put_char(Out,C).
/*
with_interrupts(S,Goal):-
	repeat,
	    catch(
	    	(	call_with_time_limit(S,Goal)
	    	->	true
	    	;	!, fail
	    	),
	    	time_limit_exceeded,
	    	fail
	    ),
   !.
*/
with_interrupts(_,Goal):-Goal.
/*
user:prolog_exception_hook(In,_Out,_Frame,CFrame):-
	(	CFrame == none
	->	format("uncaught exception: ~w~n",[In]),
		backtrace(50),
		fail
	;
	)
	*/

:- use_module(library(apply)).

get_var_names(Goal, _) :-
    not(atomic(Goal)),
    !,
    throw('first argument has to be atomic').

get_var_names(Goal, VarNames) :-
    format(atom(Query), '~w.', [Goal]),
    open_chars_stream(Query,Stream),
    read_term(Stream,_,[variable_names(VarNameList)]),
    maplist(extract_var_name, VarNameList, ExtractedList),
    list_2_comma_separated_list(ExtractedList,VarNames).

extract_var_name(=(VarName, _), VarName) :- !.
extract_var_name(VarName, VarName) :- !.

list_2_comma_separated_list([],'') :- !.
list_2_comma_separated_list([Element],Element) :- !.
list_2_comma_separated_list([Element|[H|T]],ElementComma) :-
	list_2_comma_separated_list([H|T],RestAtom),
	format(atom(ElementComma),'~w,~w',[Element,RestAtom]).

%:- endif.


text:
class GroveCompass
{
public:
    GroveCompass(int pinsda, int pinscl);
	bool write_setup(void);
    bool read_compass_xyz(float *cx, float *cy, float *cz);
    bool read_compass_heading(float *heading);

private:
    I2C_T *i2c;
};

#endif


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""

from resource_management import *
import sys

def hive(name=None):
  import params

  if name == 'metastore' or name == 'hiveserver2':
    hive_config_dir = params.hive_server_conf_dir
    config_file_mode = 0600
    jdbc_connector()
  else:
    hive_config_dir = params.hive_conf_dir
    config_file_mode = 0644

  Directory(hive_config_dir,
            owner=params.hive_user,
            group=params.user_group,
            create_parents = True
  )

  XmlConfig("hive-site.xml",
            conf_dir=hive_config_dir,
            configurations=params.config['configurations']['hive-site'],
            configuration_attributes=params.config['configuration_attributes']['hive-site'],
            owner=params.hive_user,
            group=params.user_group,
            mode=config_file_mode
  )

  cmd = format("/bin/sh -c 'cd /usr/lib/ambari-agent/ && curl -kf --retry 5 "
               "{jdk_location}{check_db_connection_jar_name} -o {check_db_connection_jar_name}'")

  Execute(cmd,
          not_if=format("[ -f {check_db_connection_jar_name}]"))

  if name == 'metastore':
    File(params.start_metastore_path,
         mode=0755,
         content=StaticFile('startMetastore.sh')
    )

  elif name == 'hiveserver2':
    File(params.start_hiveserver2_path,
         mode=0755,
         content=StaticFile('startHiveserver2.sh')
    )

  if name != "client":
    crt_directory(params.hive_pid_dir)
    crt_directory(params.hive_log_dir)
    crt_directory(params.hive_var_lib)

  File(format("{hive_config_dir}/hive-env.sh"),
       owner=params.hive_user,
       group=params.user_group,
       content=Template('hive-env.sh.j2', conf_dir=hive_config_dir)
  )

  crt_file(format("{hive_conf_dir}/hive-default.xml.template"))
  crt_file(format("{hive_conf_dir}/hive-env.sh.template"))
  crt_file(format("{hive_conf_dir}/hive-exec-log4j.properties.template"))
  crt_file(format("{hive_conf_dir}/hive-log4j.properties.template"))

def crt_directory(name):
  import params

  Directory(name,
            create_parents = True,
            owner=params.hive_user,
            group=params.user_group,
            mode=0755)

def crt_file(name):
  import params

  File(name,
       owner=params.hive_user,
       group=params.user_group
  )

def jdbc_connector():
  import params

  if params.hive_jdbc_driver == "com.mysql.jdbc.Driver":
    cmd = format("hive mkdir -p {artifact_dir} ; cp /usr/share/java/{jdbc_jar_name} {target}")

    Execute(cmd,
            not_if=format("test -f {target}"),
            creates=params.target,
            path=["/bin", "/usr/bin/"])

  elif params.hive_jdbc_driver == "oracle.jdbc.driver.OracleDriver":
    cmd = format(
      "mkdir -p {artifact_dir} ; curl -kf --retry 10 {driver_curl_source} -o {driver_curl_target} &&  "
      "cp {driver_curl_target} {target}")

    Execute(cmd,
            not_if=format("test -f {target}"),
            path=["/bin", "/usr/bin/"])


text:
package com.dianping.cat.report.page.matrix;

import com.dianping.cat.report.ReportContext;

public class Context extends ReportContext<Payload> {

}


text:
/**
 * Creates a checkbox.
 * @constructor
 * @class
 * This class represents a checkbox.
 *
 * @param {hash}	params	a hash of parameters
 * @param {DwtComposite}	params.parent	the parent widget
 * @param {DwtCheckbox.TEXT_LEFT|DwtCheckbox.TEXT_RIGHT}       [params.style=DwtCheckbox.TEXT_RIGHT] 	the text style
 * @param {string}       params.name		the input control name (required for IE)
 * @param {string}       params.value     the input control value
 * @param {boolean}       params.checked	the input control checked status (required for IE)
 * @param {string}       params.className	the CSS class
 * @param {constant}       params.posStyle	the positioning style (see {@link Dwt})
 * @param {string}       params.id		an explicit ID to use for the control's HTML element
 * @param {number}       params.index 	the index at which to add this control among parent's children
 *
 *  @extends		DwtControl
 */
DwtCheckbox = function(params) {
	if (arguments.length == 0) { return; }

	params = Dwt.getParams(arguments, DwtCheckbox.PARAMS);
	params.className = params.className || "DwtCheckbox";

	DwtControl.call(this, params);

	this._textPosition = DwtCheckbox.DEFAULT_POSITION;
	this._initName = params.name;
    this._initValue = params.value;
	this._initChecked = params.checked;
	this._createHtml();
};

DwtCheckbox.prototype = new DwtControl;
DwtCheckbox.prototype.constructor = DwtCheckbox;

DwtCheckbox.prototype.isDwtCheckbox = true;
DwtCheckbox.prototype.isInputControl = true;
DwtCheckbox.prototype.toString = function() { return "DwtCheckbox"; };

//
// Constants
//
DwtCheckbox.PARAMS = [
	"parent",
	"style",
	"name",
	"checked",
	"className",
	"posStyle",
	"id",
	"index",
    "value"
];
/**
 * Defines the "left" text style position.
 */
DwtCheckbox.TEXT_LEFT			= "left";
/**
 * Defines the "right" text style position.
 */
DwtCheckbox.TEXT_RIGHT			= "right";
/**
 * Defines the default text style position.
 */
DwtCheckbox.DEFAULT_POSITION	= DwtCheckbox.TEXT_RIGHT;

//
// Data
//
DwtCheckbox.prototype.TEMPLATE = "dwt.Widgets#DwtCheckbox";

//
// Public methods
//
DwtCheckbox.prototype.getTabGroupMember =
function() {
	return this._inputEl;
};

DwtCheckbox.prototype.focus =
function() {
	if (this._inputEl) {
		this._inputEl.focus();
		DwtShell.getShell(window).getKeyboardMgr().grabFocus(this.getTabGroupMember());
	}
};

DwtCheckbox.prototype.blur =
function() {
	if (this._inputEl) {
		this._inputEl.blur();
	}
};

// listeners

/**
 * Adds a selection listener.
 *
 * @param	{AjxListener}	listener		the listener
 */
DwtCheckbox.prototype.addSelectionListener =
function(listener) {
	this.addListener(DwtEvent.SELECTION, listener);
};

/**
 * Removes a selection listener.
 *
 * @param	{AjxListener}	listener		the listener
 */
DwtCheckbox.prototype.removeSelectionListener =
function(listener) {
	this.removeListener(DwtEvent.SELECTION, listener);
};

// properties

/**
 * Sets the enabled state.
 *
 * @param	{boolean}	enabled		if true, the checkbox is enabled
 */
DwtCheckbox.prototype.setEnabled =
function(enabled) {
	if (enabled != this._enabled) {
		DwtControl.prototype.setEnabled.call(this, enabled);
		this._inputEl.disabled = !enabled;
		var className = enabled ? "Text" : "DisabledText";
		if (this._textElLeft) this._textElLeft.className = className;
		if (this._textElRight) this._textElRight.className = className;
	}
};

/**
 * Sets the selected state.
 *
 * @param	{boolean}	selected		if true, the checkbox is selected
 */
DwtCheckbox.prototype.setSelected =
function(selected) {
	if (this._inputEl && this._inputEl.checked != selected) {
		this._inputEl.checked = selected;
	}
};

/**
 * Checks if the checkbox is selected state.
 *
 * @return	{boolean}	true if the checkbox is selected
 */
DwtCheckbox.prototype.isSelected =
function() {
	return this._inputEl && this._inputEl.checked;
};

/**
 * Sets the checkbox text.
 *
 * @param		{string}	text		the text
 */
DwtCheckbox.prototype.setText =
function(text) {
	if (this._textEl && this._text != text) {
		this._text = text;
		this._textEl.innerHTML = text || "";
	}
};

/**
 * Gets the checkbox text.
 *
 * @return	{string}	the text
 */
DwtCheckbox.prototype.getText =
function() {
	return this._text;
};

/**
 * Sets the text position.
 *
 * @param	{DwtCheckbox.TEXT_LEFT|DwtCheckbox.TEXT_RIGHT}		position	the position
 */
DwtCheckbox.prototype.setTextPosition =
function(position) {
	this._textEl = position == DwtCheckbox.TEXT_LEFT ? this._textElLeft : this._textElRight;
	if (this._textPosition != position) {
		this._textPosition = position;
		if (this._textElLeft) this._textElLeft.innerHTML = "";
		if (this._textElRight) this._textElRight.innerHTML = "";
		this.setText(this._text);
	}
};

/**
 * Gets the text position.
 *
 * @return	{DwtCheckbox.TEXT_LEFT|DwtCheckbox.TEXT_RIGHT}		the position
 */
DwtCheckbox.prototype.getTextPosition =
function() {
	return this._textPosition;
};

/**
 * Sets the value.
 *
 * @param	{string}		value		the value
 */
DwtCheckbox.prototype.setValue =
function(value) {
    var object = this._inputEl || this;
	if (object.value !== value) {
        object.value = value;
    }
};

/**
 * Gets the value.
 *
 * @return		{string}		the value
 */
DwtCheckbox.prototype.getValue =
function() {
    var object = this._inputEl || this;
	return object.value != null ? object.value : this.getText();
};

/**
 * Gets the input element.
 *
 * @return		{Element}		the element
 */
DwtCheckbox.prototype.getInputElement =
function() {
	return this._inputEl;
};

//
// DwtControl methods
//

DwtCheckbox.prototype.setToolTipContent = function(content) {
    if (content && !this.__mouseEventsSet) {
        // NOTE: We need mouse events in order to initiate tooltips on hover.
        // TODO: This should be done transparently in DwtControl for all
        // TODO: controls with tooltips.
        this.__mouseEventsSet = true;
        this._setMouseEvents();
    }
    DwtControl.prototype.setToolTipContent.apply(this, arguments);
};

//
// Protected methods
//

/**
 * The input field inherits the id for accessibility purposes.
 *
 * @private
 */
DwtCheckbox.prototype._replaceElementHook =
function(oel, nel, inheritClass, inheritStyle) {
	nel = this.getInputElement();
	DwtControl.prototype._replaceElementHook.call(this, oel, nel, inheritClass, inheritStyle);
	if (oel.id) {
		this.setHtmlElementId(oel.id+"_control");
		nel.id = oel.id;
		if (this._textEl) {
			this._textEl.setAttribute(AjxEnv.isIE ? "htmlFor" : "for", oel.id);
		}
	}
};

//
// Private methods
//

DwtCheckbox.prototype._createHtml =
function(templateId) {
	var data = { id: this._htmlElId };
	this._createHtmlFromTemplate(templateId || this.TEMPLATE, data);
};

DwtCheckbox.prototype._createHtmlFromTemplate =
function(templateId, data) {
	// NOTE: If  you don't set the name and checked status when
	//       creating checkboxes and radio buttons on IE, they will
	//       not take the first programmatic value. So we pass in
	//       the init values from the constructor.
	data.name = this._initName || this._htmlElId;
    data.value = this._initValue;
	data.checked = Boolean(this._initChecked) ? "checked" : "";
	DwtControl.prototype._createHtmlFromTemplate.call(this, templateId, data);
	this._inputEl = document.getElementById(data.id+"_input");
	if (this._inputEl) {
		var keyboardMgr = DwtShell.getShell(window).getKeyboardMgr();
		var handleFocus = AjxCallback.simpleClosure(keyboardMgr.grabFocus, keyboardMgr, this.getTabGroupMember());
		Dwt.setHandler(this._inputEl, DwtEvent.ONFOCUS, handleFocus);
		Dwt.setHandler(this._inputEl, DwtEvent.ONCLICK, DwtCheckbox.__handleClick);
	}
	this._textElLeft = document.getElementById(data.id+"_text_left");
	this._textElRight = document.getElementById(data.id+"_text_right");
	this.setTextPosition(this._textPosition);
};

//
// Private functions
//

DwtCheckbox.__handleClick =
function(evt) {
	var event = DwtUiEvent.getEvent(evt);
	var target = DwtUiEvent.getTarget(event);

	var selEv = DwtShell.selectionEvent;
	DwtUiEvent.copy(selEv, event);
	selEv.item = this;
	selEv.detail = target.checked;

	var checkbox = DwtControl.findControl(target);
	checkbox.setSelected(target.checked);
	checkbox.notifyListeners(DwtEvent.SELECTION, selEv);
};


text:
package org.carrot2.core.test;

import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;

import java.util.*;

import org.carrot2.core.*;
import org.carrot2.core.attribute.AttributeNames;
import org.carrot2.util.attribute.Bindable;
import org.carrot2.util.attribute.metadata.BindableMetadata;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;

import com.google.common.base.Function;

/**
 * Simple baseline tests that apply to a generic data sources.
 */
public abstract class DocumentSourceTestBase<T extends IDocumentSource> extends
    ProcessingComponentTestBase<T>
{
    /**
     * Processing components should be bindable, so their metadata should
     * always be available.
     */
    @Test
    public void testMetadataAvailable()
    {
        Class<? extends IDocumentSource> c = getComponentClass();
        Assume.assumeTrue(c.getAnnotation(Bindable.class) != null);

        BindableMetadata metadata = BindableMetadata.forClassWithParents(c);
        assertNotNull(metadata);
        assertNotNull(metadata.getAttributeMetadata());
    }

    /**
     * Runs a query without specifying any additional attributes. The query is run using
     * a simple {@link Controller}.
     *
     * @return Returns the number of fetched documents. Access
     *         {@link #resultAttributes} map to get hold of the actual documents.
     */
    protected int runQuery()
    {
        return runQuery(getSimpleController(initAttributes));
    }

    /**
     * Runs a query without specifying any additional attributes. The query is run using
     * a {@link Controller} with caching.
     *
     * @return Returns the number of fetched documents. Access
     *         {@link #resultAttributes} map to get hold of the actual documents.
     */
    protected int runQueryInCachingController()
    {
        return runQuery(getCachingController(initAttributes));
    }

    /**
     * Runs a query without specifying any additional attributes.
     *
     * @param controller the {@link Controller} to perform the query
     * @return Returns the number of fetched documents. Access
     *         {@link #resultAttributes} map to get hold of the actual documents.
     */
    @SuppressWarnings("unchecked")
    protected int runQuery(Controller controller)
    {
        final ProcessingResult result = controller.process(processingAttributes,
            getComponentClass());
        resultAttributes = result.getAttributes();

        final List<Document> documents = (List<Document>) resultAttributes
            .get(AttributeNames.DOCUMENTS);
        assertNotNull(result.getDocuments());
        assertThat(result.getDocuments()).isEqualTo(documents);
        return documents.size();
    }

    /**
     * Runs a query and asks for results results. The query is
     * run using a simple {@link Controller}.
     *
     * @return Returns the number of fetched documents. Access
     *         {@link #resultAttributes} map to get hold of the actual documents.
     */
    protected final int runQuery(String query, int results)
    {
        if (query != null)
        {
            processingAttributes.put(AttributeNames.QUERY, query);
        }
        processingAttributes.put(AttributeNames.RESULTS, results);
        return runQuery();
    }

    /**
     * Checks if values of a given field in a collection of {@link Document}s are unique.
     */
    protected final void assertFieldUnique(Collection<Document> result, String fieldName)
    {
        final HashMap<Object, Integer> values = new HashMap<Object, Integer>();

        final StringBuilder builder = new StringBuilder();
        int i = 0;
        for (final Document d : result)
        {
            final Object key = d.getField(fieldName);
            if (values.containsKey(key))
            {
                builder.append("Key: " + key + ", in docs: " + values.get(key) + ", " + i
                    + "\n");
            }
            else
            {
                values.put(key, i);
            }

            i++;
        }

        if (builder.length() > 0)
        {
            Assert.fail("Field values are not unique, offending fields: \n"
                + builder.toString());
        }
    }

    /**
     * Transforms {@link Document}s to their individual fields.
     */
    protected static class DocumentToFieldTransformer implements
        Function<Document, Object>
    {
        /** Field name */
        private final String fieldName;

        /**
         * Builds a transformer with the provided field name.
         */
        public DocumentToFieldTransformer(String fieldName)
        {
            this.fieldName = fieldName;
        }

        public Object apply(Document document)
        {
            return document.getField(fieldName);
        }
    }

    /**
     * Transforms {@link Document}s to their ids.
     */
    protected static final Function<Document, Integer> DOCUMENT_TO_ID = new Function<Document, Integer>()
    {
        public Integer apply(Document document)
        {
            return document.getId();
        }
    };

    /**
     * Transforms {@link Document}s to their titles.
     */
    protected static final DocumentToFieldTransformer DOCUMENT_TO_TITLE = new DocumentToFieldTransformer(
        Document.TITLE);

    /**
     * Transforms {@link Document}s to their summaries.
     */
    protected static final DocumentToFieldTransformer DOCUMENT_TO_SUMMARY = new DocumentToFieldTransformer(
        Document.SUMMARY);

    /**
     * Transforms {@link Document}s to their content URLs.
     */
    protected static final DocumentToFieldTransformer DOCUMENT_TO_CONTENT_URL = new DocumentToFieldTransformer(
        Document.CONTENT_URL);
}