text:
"""Observes message interactions through the Exchange"""

__author__ = 'Prashant Kediyal, Michael Meisinger'

import string

from pyon.util.containers import get_ion_ts
from pyon.event.event import EventSubscriber
from pyon.ion.conversation_log import ConvSubscriber

MAX_MSGLOG = 3000
SLICE = 100

class InteractionObserver(object):
    """
    Observes ongoing interactions in the Exchange. Logs them to disk and makes them available
    in the local container (for development purposes) and on request.
    """

    def start(self):
        self.msg_log = []

        self.event_sub = None
        self.conv_sub = None

        #Conv subscription
        self.conv_sub = ConvSubscriber(callback=self._msg_received)
        self.conv_sub.start()

        # Event subscription
        self.event_sub = EventSubscriber(pattern=EventSubscriber.ALL_EVENTS,
                                         callback=self._event_received,
                                         queue_name="event_persister")
        self.event_sub.start()

        self.started = True

    def stop(self):
        # Stop event subscriber
        self.event_sub.stop()
        # Stop conv subscriber
        self.conv_sub.stop()
        self.started = False

    def _msg_received(self, msg, *args, **kwargs):
        self.log_message(args[0])

    def _event_received(self, event, *args, **kwargs):
        if 'origin' in event:
            args[0]['origin'] = event.origin
        if 'origin_type' in event:
            args[0]['origin_type'] = event.origin_type
        if 'sub_type' in event:
            args[0]['sub_type'] = event.sub_type
        self.log_message(args[0], True)

    def log_message(self, mhdrs, evmsg=False):
        """
        @param evmsg    This message is an event, render it as such!
        """
        mhdrs['_content_type'] = mhdrs.get('format', None)

        # TUPLE: timestamp (MS), type, boolean if its an event
        msg_rec = (get_ion_ts(), mhdrs, evmsg)
        self.msg_log.append(msg_rec)

        # Truncate if too long in increments of slice
        if len(self.msg_log) > MAX_MSGLOG + SLICE:
            self.msg_log = self.msg_log[SLICE:]

    def _get_data(self, msglog, response_msgs):
        """
        Provides msc data in python format, to be converted either to msc text or to json
        for use with msc web monitor.
        Returns a list of hashes in the form:
        { to, from, content, type, ts, error (boolean), to_raw, from_raw, topline }
        """
        msgdata = []

        for msgtup in msglog:

            datatemp = {"to": None, "from": None, "content": None, "type": None,
                        "ts": None, "error": False}
            msg = msgtup[1]

            convid = msg.get('conv-id', None)

            if (convid in response_msgs):
                response = response_msgs.pop(convid)
                sname = response.get('sender')
                rname = response.get('receiver')

            else:
                if (msg.get('sender-type', 'unknown') == 'service'):
                    sname = msg.get('sender-service', msg.get('sender-name',
                                    msg.get('sender', 'unknown')))
                else:
                    sname = msg.get('sender-name', msg.get('sender', 'unknown'))
                rname = msg.get('receiver', 'unknown')

                if (convid is not None):
                    response_msgs[convid] = {'sender': rname, 'receiver': sname}

            # from_raw is displayed as the header on the webpage
            datatemp["from_raw"] = sname
            sname = self._sanitize(sname)
            datatemp["from"] = sname
            datatemp["ts"] = msg.get("ts", "Unknown")
            datatemp["to_raw"] = rname
            rname = self._sanitize(rname)
            datatemp["to"] = rname

            if msgtup[2]:
                # this is an EVENT, show it as a box!
                datatemp["type"] = "events"

                #todo: not sure if we can hard code the splitting mechanism like done below !!
                datatemp["from"] = "events,"+ (msg.get('routing_key').split('._._.')[0]).split('.')[1]
                datatemp["from_raw"] = "events,"+(msg.get('routing_key').split('._._.')[0]).split('.')[1]
                datatemp["to"] = "events,"+ (msg.get('routing_key').split('._._.')[0]).split('.')[1]
                datatemp["to_raw"] = "events,"+ (msg.get('routing_key').split('._._.')[0]).split('.')[1]

                evlabel = "%s \nOrigin: %s" % (msg.get('routing_key'), msg.get('origin'))
                datatemp["content"] = evlabel
                datatemp["topline"] = msg.get('sub_type', '') + " " + msg.get('origin_type', '')
                if (datatemp['topline'] == " "):
                    datatemp['topline'] = msg.get('origin')

            else:

                mlabel = "%s\n(%s->%s)\n<%s>" % (msg.get('op', None), sname.rsplit(",", 1)[-1],
                         rname.rsplit(",", 1)[-1], msg.get('_content_type', '?content-type?'))
                datatemp["content"] = mlabel
                datatemp["topline"] = mlabel.split("\n")[0]

                if msg.get('protocol', None) == 'rpc':

                    datatemp["type"] = "rpcres"

                    performative = msg.get('performative', None)
                    if performative == 'request':
                        datatemp["type"] = "rpcreq"
                    elif performative == 'timeout':
                        pass  # timeout, unfortunately you don't see this @TODO

                    if performative == 'failure' or performative == 'error':
                        datatemp["error"] = True

                else:
                    # non rpc -> perhaps a data message?
                    datatemp["type"] = "data"

            msgdata.append(datatemp)

        return msgdata, response_msgs

    @classmethod
    def _sanitize(cls, input):
        return string.replace(string.replace(input, ".", "_"), "-", "_")


text:
import _String from '../classes/String'
import Indexed from '../protocols/Indexed'
import anyIsString from '../util/anyIsString'
import anyToString from '../util/anyToString'
import defineAny from '../util/defineAny'
import definitionToType from '../util/definitionToType'
import definitionsToFn from '../util/definitionsToFn'
import stringDeleteIndex from '../util/stringDeleteIndex'
import stringGetIndex from '../util/stringGetIndex'
import stringHasIndex from '../util/stringHasIndex'
import stringLength from '../util/stringLength'
import stringSetIndex from '../util/stringSetIndex'

import Any from './Any'
import Boolean from './Boolean'
import Character from './Character'
import Index from './IndexType'
import Integer from './Integer'
import Self from './Self'

const String = defineAny(
  'lang.String',
  {
    description: 'A text value',
    since: 'v0.1.0'
  },

  definitionToType({
    class: _String,
    is: anyIsString,
    protocols: [
      Indexed,
      {
        'lang.deleteIndex': definitionsToFn([
          [Self, Index, () => Self],
          stringDeleteIndex,

          [Index, Self, () => Self],
          (index, self) => stringDeleteIndex(self, index)
        ]),
        'lang.getIndex': definitionsToFn([
          [Self, Index, () => Character],
          stringGetIndex,

          [Index, Self, () => Character],
          (index, self) => stringGetIndex(self, index)
        ]),
        'lang.hasIndex': definitionsToFn([
          [Self, Index, () => Boolean],
          stringHasIndex,

          [Index, Self, () => Boolean],
          (index, self) => stringHasIndex(self, index)
        ]),
        'lang.setIndex': definitionsToFn([
          [Self, Index, Any, () => Self],
          stringSetIndex,

          [Index, Any, Self, () => Self],
          (index, any, self) => stringSetIndex(self, index, any)
        ]),
        'lang.size': definitionsToFn([[Self, () => Integer], stringLength])
      }
    ],
    to: anyToString
  })
)

export default String

redpajama_set_name: RedPajamaGithub


text:
Auth with incoming WebHook

## Documentation
[WebHooks](https://training.bitrix24.com/rest_help/rest_sum/webhooks.php)

## use web-hooks
1. Create WebHook
2. install bitrix24-php-sdk
3. Configure ApiClient for webhook auth

```php
<?php

declare(strict_types=1);
require_once 'vendor/autoload.php';

use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Symfony\Component\HttpClient\HttpClient;

$log = new Logger('name');
$log->pushHandler(new StreamHandler('b24-api-client-debug.log', Logger::DEBUG));

$client = HttpClient::create();

$credentials = new \Bitrix24\SDK\Core\Credentials\Credentials(
    new \Bitrix24\SDK\Core\Credentials\WebhookUrl('https://test.bitrix24.ru/rest/7/9kc3tt3kr7qxjt0c/'),
    null,
    null
);

$apiClient = new \Bitrix24\SDK\Core\ApiClient($credentials, $client, $log);

$result = $apiClient->getResponse('app.info');
$result = json_decode($result->getContent(), true);
var_dump($result);
```


text:
using System;
using System.Data.Common;
using System.Diagnostics;

namespace Foundation
{
    internal static class RelationalDiagnosticsExtensions
    {
        private const string NamePrefix = "Foundation.";

        public const string BeforeExecuteCommand = NamePrefix + nameof(BeforeExecuteCommand);
        public const string AfterExecuteCommand = NamePrefix + nameof(AfterExecuteCommand);
        public const string CommandExecutionError = NamePrefix + nameof(CommandExecutionError);

        public static void WriteCommandBefore(this DiagnosticSource diagnosticSource, DbCommand command, string executeMethod, Guid instanceId, long startTimestamp, bool async)
        {
            if (diagnosticSource.IsEnabled(BeforeExecuteCommand))
            {
                diagnosticSource.Write(BeforeExecuteCommand, new RelationalDiagnosticSourceBeforeMessage
                                                             {
                                                                 Command = command,
                                                                 ExecuteMethod = executeMethod,
                                                                 InstanceId = instanceId,
                                                                 Timestamp = startTimestamp,
                                                                 IsAsync = async
                                                             });
            }
        }

        public static void WriteCommandAfter(this DiagnosticSource diagnosticSource, DbCommand command, string executeMethod, Guid instanceId, long startTimestamp, long currentTimestamp, bool async = false)
        {
            if (diagnosticSource.IsEnabled(AfterExecuteCommand))
            {
                diagnosticSource.Write(AfterExecuteCommand, new RelationalDiagnosticSourceAfterMessage
                                                            {
                                                                Command = command,
                                                                ExecuteMethod = executeMethod,
                                                                InstanceId = instanceId,
                                                                Timestamp = currentTimestamp,
                                                                Duration = currentTimestamp - startTimestamp,
                                                                IsAsync = async
                                                            });
            }
        }

        public static void WriteCommandError(this DiagnosticSource diagnosticSource, DbCommand command, string executeMethod, Guid instanceId, long startTimestamp, long currentTimestamp, Exception exception, bool async)
        {
            if (diagnosticSource.IsEnabled(CommandExecutionError))
            {
                diagnosticSource.Write(CommandExecutionError, new RelationalDiagnosticSourceAfterMessage
                                                              {
                                                                  Command = command,
                                                                  ExecuteMethod = executeMethod,
                                                                  InstanceId = instanceId,
                                                                  Timestamp = currentTimestamp,
                                                                  Duration = currentTimestamp - startTimestamp,
                                                                  Exception = exception,
                                                                  IsAsync = async
                                                              });
            }
        }

        internal class RelationalDiagnosticSourceAfterMessage
        {
            public DbCommand Command { get; set; }
            public string ExecuteMethod { get; set; }
            public bool IsAsync { get; set; }
            public Guid InstanceId { get; set; }
            public long Timestamp { get; set; }
            public long Duration { get; set; }
            public Exception Exception { get; set; }
        }

        internal class RelationalDiagnosticSourceBeforeMessage
        {
            public DbCommand Command { get; set; }
            public string ExecuteMethod { get; set; }
            public bool IsAsync { get; set; }
            public Guid InstanceId { get; set; }
            public long Timestamp { get; set; }
        }
    }

}


text:
Combine Query
=================

WordPress plugin - Combine Query

[![Build Status](https://travis-ci.org/birgire/wp-combine-queries.svg?branch=master)](https://travis-ci.org/birgire/wp-combine-queries)
[![GitHub license](https://img.shields.io/github/license/birgire/wp-combine-queries.svg)](https://github.com/birgire/wp-combine-queries/blob/master/LICENCE)
[![Packagist](https://img.shields.io/packagist/v/birgir/combined-query.svg)](https://packagist.org/packages/birgir/combined-query)

### Description

This experimental plugin allows you to combine multiple `WP_Query` queries into a single one, using the `combined_query` attribute.

This started as an answer on Stackoverflow, see [here](http://stackoverflow.com/questions/23555109/wordpress-combine-queries/) and [here](http://wordpress.stackexchange.com/questions/159228/combining-two-wordpress-queries-with-pagination-is-not-working/).

The idea behind this plugin is to combine the SQL queries for each `WP_Query()` query with `UNION` or `UNION ALL`.

I first noticed this technique in a [great answer on WordPress Development](http://wordpress.stackexchange.com/a/912/26350) by Mike Schinkel.

I use the trick mentioned [here](http://stackoverflow.com/a/7587423/2078474) to preserve the order of `UNION` sub queries.

This implementation supports combining `N` sub-queries.

### Notice about the new 1.0.0 version

This version is a total rewrite of the plugin.

The `WP_Combine_Query` class has been removed in favour of simply using the `combined_query` attribute of the `WP_Query` class.

Now the plugin only supports PHP versions 5.4+.

### Settings

The supported settings for the `combined_query` attribute:

	'combined_query' => [
		'args'           => [ $args1, $args2, ... ], // Array (default [])
		'union'          => 'UNION',                 // String Possible values are UNION or UNION ALL (default UNION)
		'posts_per_page' => 10,                      // Integer 1,2,...
		'offset'         => 0,                       // Integer 0,1,...
		'orderby'        => 'meta_value_num',        // String (post_name, ..., name, ..., none, meta_value, meta_value_num )
		'order'          => 'DESC',                  // String (ASC,DESC)
	]

If you want to remove duplicated posts use `UNION`, else use `UNION ALL`.

### Custom filters

There are two custom filters currently available:

    // Modify combined ordering:
    add_filter( 'cq_orderby', function( $orderby ) {
        return $orderby;
    });

    // Modify sub fields:
    add_filter( 'cq_sub_fields', function( $fields ) {
        return $fields;
    });

To keep the order by arguments arg1, arg2, ... use:

    'combined_query' => [
        ...
        'orderby' => 'none',
        ...
    ]

or

    add_filter( 'cq_orderby', '__return_empty_string' );
    $query = new WP_Query( $args );
    remove_filter( 'cq_orderby', '__return_empty_string' );

### Installation

Upload the plugin to the plugin folder and activate it.

To install dependencies with Composer (not required):

    composer install

or

    php composer.phar install

within our folder. See [here](https://getcomposer.org/doc/00-intro.md) for more information on how to install Composer.

Then play with the examples below, in your theme or in a plugin.

Have fun ;-)

### Example 1:

Here we want to display the first published page in an alphabetical order and then the three oldest published posts:

	//-----------------
	// Sub query #1:
	//-----------------
	$args1 = [
		'post_type'      => 'page',
		'posts_per_page' => 1,
		'orderby'        => 'title',
		'order'          => 'asc',
	];

	//-----------------
	// Sub query #2:
	//-----------------
	$args2 = [
		'post_type'      => 'post',
		'posts_per_page' => 3,
		'orderby'        => 'date',
		'order'          => 'asc',
	];

	//---------------------------
	// Combined queries #1 + #2:
	//---------------------------
	$args = [
		'combined_query' => [
			'args'           => [ $args1, $args2 ],
			'union'          => 'UNION',
			'posts_per_page' => 4,
			'orderby'        => 'none',
		]
	];

	//---------
	// Output:
	//---------
	$q = new WP_Query( $args );
	if( $q->have_posts() ):
		?>
<?php
		while( $q->have_posts() ): $q->the_post();
			?>
<a href="<?php the_permalink();?>"><?php the_title();?>
<?php
		endwhile;
		?>
<?php
		wp_reset_postdata();
	else:
		_e( 'Sorry no posts found!' );
	endif;

### Example 2:

Here we want to display all foo posts with a date query, sorted by comment count and after that all bar posts sorted by comment count.
Then we sort all by decreasing comment count.

	//-----------------
	// Sub query #1:
	//-----------------
	$args1 = [
		'post_type'           => 'foo',
		'orderby'             => 'comment_count',
		'order'               => 'desc',
		'posts_per_page'      => 100, // adjust to your needs
		'date_query'          => [
			[
				'after' => date('Y-m-d'),
			],
			'inclusive'  => true,
		]
	];

	//-----------------
	// Sub query #2:
	//-----------------
	$args2 = [
		'post_type'           => 'bar',
		'orderby'             => 'comment_count',
		'order'               => 'desc',
		'posts_per_page'      => 100, // adjust to your needs
	];

	//---------------------------
	// Combined queries #1 + #2:
	//---------------------------
	$args = [
		'combined_query' => [
			'args'                => [ $args1, $args2 ],
			'posts_per_page'      => 5,
			'paged'               => 2,
			'orderby'             => 'comment_count',
			'order'               => 'desc',
		]
	];

	//---------
	// Output:
	//---------
	// See example 1

### Example 3:

Let's combine two meta queries and order by a common meta value:

    //-----------------
    // Sub query #1:
    //-----------------
    $args1 = [
       'post_type'      => 'cars',
       'posts_per_page' => 10,
       'orderby'        => 'title',
       'order'          => 'asc',
       'meta_query'     => [
            [
                'key'      => 'doors',
                'value'    => 0,
                'compare'  => '>=',
                'type'     => 'UNSIGNED'
            ],
        ],
    ];

    //-----------------
    // Sub query #2:
    //-----------------
    $args2 = [
       'post_type'      => 'post',
       'posts_per_page' => 10,
       'orderby'        => 'date',
       'order'          => 'desc',
       'tax_query' => [
            [
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => 'cars',
            ],
        ],
        'meta_query'     => [
            [
                'key'      => 'doors',
                'value'    => 0,
                'compare'  => '>=',
                'type'     => 'UNSIGNED'
            ],
        ],
    ];

    //------------------------------
    // Order by a common meta value
    //------------------------------

    // Modify sub fields:
    add_filter( 'cq_sub_fields', $callback = function( $fields ) {
        return $fields . ', meta_value';
    });

    //---------------------------
    // Combined queries #1 + #2:
    //---------------------------
    $args = [
        'combined_query' => [
		'args'           => [ $args1, $args2 ],
		'posts_per_page' => 5,
		'orderby'        => 'meta_value_num',
		'order'          => 'DESC',
        ]
    ];

    //---------
    // Output:
    //---------
    // See example 1

	remove_filter( 'cq_sub_fields', $callback );

### Example 4:

We could also combine more than two sub queries, here's an example of four sub-queries:

     $args = [
        'combined_query' => [
		'args' => [ $args1, $args2, $args3, $args4 ],
		...
        ]
      ];

    //---------
    // Output:
    //---------
    // See example 1

### Example 5:

The above examples are all for secondary queries. So let's add a query to the main home query:

    add_action( 'pre_get_posts', function( \WP_Query $q ) {

	if( $q->is_home() && $q->is_main_query() ) {

		//-----------------
		// Sub query #1:
		//-----------------
		$args1 = [
		   'post_type'	    => 'page',
		   'posts_per_page' => 1,
		   'orderby'        => 'title',
		   'order'          => 'asc',
		];

		//-----------------
		// Original query #2:
		//-----------------
		$args2 = $q->query;

		//---------------------------
		// Combined queries #1 + #2:
		//---------------------------
		$args = [
			'combined_query' => [
				'args'           => [ $args1, $args2 ],
				'union'          => 'UNION',
				'posts_per_page' => 4,
				'orderby'        => 'none',
			]
		];

		//-----------------------
		// Modify the Main query:
		//-----------------------
		$q->set( 'combined_query', $args['combined_query'] );
        }
    } );

### Changelog

(2022-03-03)
 - Fixed: Wrong plugin URI in header (Props: therealgilles)

1.2.2 (2021-02-20)
 - Fixed: Fixes #14 regarding subsequent queries. (Props: @Suranex)

1.2.1 (2020-09-14)
 - Fixed: Readme.

1.2.0 (2020-09-14)
 - Added: Support for ordering by 'none'.
 - Added: Test cases.
 - Added: Support for adding parameters (posts_per_page, offset, orderby, order) inside combined_query args.
 - Fixed: Hooks handling for pre_get_posts example.
 - Adjusted: Examples.

1.1.1 (2020-09-04)
 - Added:    Example how to keep the order by arguments arg1, arg2, ...
 - Adjusted: UNION ALL test

1.1.0 (2020-09-04)
 - Added:   Ticket #19 - Add test cases for argument order workaround. (Props: therealgilles)
 - Cleanup: phpcs

1.0.5 (2016-05-08)
 - Fixed:    Ticket #8 - Fallback for those who don't use Composer.
 - Improved: Removed an explicit call to $GLOBALS['wpdb'] through the use keyword.
 - Improved: Simplified the namespace to only CombinedQuery.

1.0.4 (2016-04-21)
 - Fixed:    Adjusted the paged bug that sneaked in with verion 1.0.2 yesterday.
 - Improved: Simplified the example that uses get_query_var() that can now handle default as an input parameter.

1.0.3 (2016-04-21)
 - Fixed:    Ticket #7 - Not able to set the "UNION ALL" union option
 - Improved: Inline docs

1.0.2 (2016-04-20)
 - Fixed: Ticket #6 - Escape % in the Generator class. (Props: @DArcMattr)
 - Improved: Inline docs

1.0.1 (2015-11-09)
 - Fixed: Remove vendor dependency and let the user install it via 'composer install' (Props: @pdufour)
 - Fixed: Ignore sticky posts in the EmptyQuery class

1.0.0 (2015-05-10)
 - ** Total Plugin Rewrite **
 - Closed: Ticket #3
 - Added: New classes Main, EmptyQuery and Generator.
 - Added: Support for 'combined_query' attribute of the WP_Query class.
 - Added: Support only for PHP 5.4+
 - Added: Autoload via Composer.
 - Added: New filter 'cq_sub_fields' instead of 'cq_sub_fields'
 - Added: New filter 'cq_orderby' instead of 'cq_orderby'

0.1.3 (2015-05-09)
 - Added: Support for ignory_sticky_posts.
 - Fixed: Minor

0.1.2 (2015-05-08)
 - Added: Support for the GitHub Updater.
 - Added: New filter 'wcq_sub_fields'
 - Added: New filter 'wcq_orderby'
 - Added: New example for meta value ordering
 - Fixed: Ordering didn't work correctly.

0.1.1
 - Changed: Coding style and autoloading (Props: @egill)

0.1  Various plugin improvements, for example:
 - Added: orderby in the combined query.
 - Added: posts_per_page in the sub queries.
 - Added: offset in the sub queries.
 - Added: paged in the sub queries.
 - Removed: sublimit in the combined query, use posts_per_page instead in sub queries.
 - Fixed: Issue #1 related to max_num_pages (Props: @hellofantastic).

0.0.4
 - Added: support for offset in the combined query

0.0.3
 - Added: GPL2+ License part
 - Removed: Dropped namespace + anonymous function for wider PHP support.

0.0.2
 - Added: Input parameter 'union' with possible values UNION and UNION ALL.
 - Fixed: Empty paged resulted in a sql error. (Props: Robert Hue)


text:
namespace TraktApiSharp.Objects.Post.Comments.Json.Factories
{
    using Objects.Json;
    using System;
    using Writer;

    internal class SeasonCommentPostJsonIOFactory : IJsonIOFactory<ITraktSeasonCommentPost>
    {
        public IObjectJsonReader<ITraktSeasonCommentPost> CreateObjectReader()
            => throw new NotSupportedException($"A object json reader for {nameof(ITraktSeasonCommentPost)} is not supported.");

        public IArrayJsonReader<ITraktSeasonCommentPost> CreateArrayReader()
            => throw new NotSupportedException($"A array json reader for {nameof(ITraktSeasonCommentPost)} is not supported.");

        public IObjectJsonWriter<ITraktSeasonCommentPost> CreateObjectWriter() => new SeasonCommentPostObjectJsonWriter();
    }
}


text:
//#define LOG_NDEBUG 0
#define LOG_TAG "MediaRecorderJNI"
#include <utils/Log.h>

#include <gui/Surface.h>
#include <camera/ICameraService.h>
#include <camera/Camera.h>
#include <media/mediarecorder.h>
#include <stdio.h>
#include <assert.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <utils/threads.h>

#include "jni.h"
#include "JNIHelp.h"
#include "android_runtime/AndroidRuntime.h"

#include <system/audio.h>
#include <android_runtime/android_view_Surface.h>

// ----------------------------------------------------------------------------

using namespace android;

// ----------------------------------------------------------------------------

// helper function to extract a native Camera object from a Camera Java object
extern sp<Camera> get_native_camera(JNIEnv *env, jobject thiz, struct JNICameraContext** context);

struct fields_t {
    jfieldID    context;
    jfieldID    surface;

    jmethodID   post_event;
};
static fields_t fields;

static Mutex sLock;

// ----------------------------------------------------------------------------
// ref-counted object for callbacks
class JNIMediaRecorderListener: public MediaRecorderListener
{
public:
    JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz);
    ~JNIMediaRecorderListener();
    void notify(int msg, int ext1, int ext2);
private:
    JNIMediaRecorderListener();
    jclass      mClass;     // Reference to MediaRecorder class
    jobject     mObject;    // Weak ref to MediaRecorder Java object to call on
};

JNIMediaRecorderListener::JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz)
{

    // Hold onto the MediaRecorder class for use in calling the static method
    // that posts events to the application thread.
    jclass clazz = env->GetObjectClass(thiz);
    if (clazz == NULL) {
        ALOGE("Can't find android/media/MediaRecorder");
        jniThrowException(env, "java/lang/Exception", NULL);
        return;
    }
    mClass = (jclass)env->NewGlobalRef(clazz);

    // We use a weak reference so the MediaRecorder object can be garbage collected.
    // The reference is only used as a proxy for callbacks.
    mObject  = env->NewGlobalRef(weak_thiz);
}

JNIMediaRecorderListener::~JNIMediaRecorderListener()
{
    // remove global references
    JNIEnv *env = AndroidRuntime::getJNIEnv();
    env->DeleteGlobalRef(mObject);
    env->DeleteGlobalRef(mClass);
}

void JNIMediaRecorderListener::notify(int msg, int ext1, int ext2)
{
    ALOGV("JNIMediaRecorderListener::notify");

    JNIEnv *env = AndroidRuntime::getJNIEnv();
    env->CallStaticVoidMethod(mClass, fields.post_event, mObject, msg, ext1, ext2, 0);
}

// ----------------------------------------------------------------------------

static sp<Surface> get_surface(JNIEnv* env, jobject clazz)
{
    ALOGV("get_surface");
    return android_view_Surface_getSurface(env, clazz);
}

// Returns true if it throws an exception.
static bool process_media_recorder_call(JNIEnv *env, status_t opStatus, const char* exception, const char* message)
{
    ALOGV("process_media_recorder_call");
    if (opStatus == (status_t)INVALID_OPERATION) {
        jniThrowException(env, "java/lang/IllegalStateException", NULL);
        return true;
    } else if (opStatus != (status_t)OK) {
        jniThrowException(env, exception, message);
        return true;
    }
    return false;
}

static sp<MediaRecorder> getMediaRecorder(JNIEnv* env, jobject thiz)
{
    Mutex::Autolock l(sLock);
    MediaRecorder* const p = (MediaRecorder*)env->GetIntField(thiz, fields.context);
    return sp<MediaRecorder>(p);
}

static sp<MediaRecorder> setMediaRecorder(JNIEnv* env, jobject thiz, const sp<MediaRecorder>& recorder)
{
    Mutex::Autolock l(sLock);
    sp<MediaRecorder> old = (MediaRecorder*)env->GetIntField(thiz, fields.context);
    if (recorder.get()) {
        recorder->incStrong(thiz);
    }
    if (old != 0) {
        old->decStrong(thiz);
    }
    env->SetIntField(thiz, fields.context, (int)recorder.get());
    return old;
}

static void android_media_MediaRecorder_setCamera(JNIEnv* env, jobject thiz, jobject camera)
{
    // we should not pass a null camera to get_native_camera() call.
    if (camera == NULL) {
        jniThrowNullPointerException(env, "camera object is a NULL pointer");
        return;
    }
    sp<Camera> c = get_native_camera(env, camera, NULL);
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setCamera(c->remote(), c->getRecordingProxy()),
            "java/lang/RuntimeException", "setCamera failed.");
}

static void
android_media_MediaRecorder_setVideoSource(JNIEnv *env, jobject thiz, jint vs)
{
    ALOGV("setVideoSource(%d)", vs);
    if (vs < VIDEO_SOURCE_DEFAULT || vs >= VIDEO_SOURCE_LIST_END) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video source");
        return;
    }
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setVideoSource(vs), "java/lang/RuntimeException", "setVideoSource failed.");
}

static void
android_media_MediaRecorder_setAudioSource(JNIEnv *env, jobject thiz, jint as)
{
    ALOGV("setAudioSource(%d)", as);
    if (as < AUDIO_SOURCE_DEFAULT || as >= AUDIO_SOURCE_CNT) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio source");
        return;
    }

    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setAudioSource(as), "java/lang/RuntimeException", "setAudioSource failed.");
}

static void
android_media_MediaRecorder_setOutputFormat(JNIEnv *env, jobject thiz, jint of)
{
    ALOGV("setOutputFormat(%d)", of);
    if (of < OUTPUT_FORMAT_DEFAULT || of >= OUTPUT_FORMAT_LIST_END) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid output format");
        return;
    }
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setOutputFormat(of), "java/lang/RuntimeException", "setOutputFormat failed.");
}

static void
android_media_MediaRecorder_setVideoEncoder(JNIEnv *env, jobject thiz, jint ve)
{
    ALOGV("setVideoEncoder(%d)", ve);
    if (ve < VIDEO_ENCODER_DEFAULT || ve >= VIDEO_ENCODER_LIST_END) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video encoder");
        return;
    }
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setVideoEncoder(ve), "java/lang/RuntimeException", "setVideoEncoder failed.");
}

static void
android_media_MediaRecorder_setAudioEncoder(JNIEnv *env, jobject thiz, jint ae)
{
    ALOGV("setAudioEncoder(%d)", ae);
    if (ae < AUDIO_ENCODER_DEFAULT || ae >= AUDIO_ENCODER_LIST_END) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio encoder");
        return;
    }
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setAudioEncoder(ae), "java/lang/RuntimeException", "setAudioEncoder failed.");
}

static void
android_media_MediaRecorder_setParameter(JNIEnv *env, jobject thiz, jstring params)
{
    ALOGV("setParameter()");
    if (params == NULL)
    {
        ALOGE("Invalid or empty params string.  This parameter will be ignored.");
        return;
    }

    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);

    const char* params8 = env->GetStringUTFChars(params, NULL);
    if (params8 == NULL)
    {
        ALOGE("Failed to covert jstring to String8.  This parameter will be ignored.");
        return;
    }

    process_media_recorder_call(env, mr->setParameters(String8(params8)), "java/lang/RuntimeException", "setParameter failed.");
    env->ReleaseStringUTFChars(params,params8);
}

static void
android_media_MediaRecorder_setOutputFileFD(JNIEnv *env, jobject thiz, jobject fileDescriptor, jlong offset, jlong length)
{
    ALOGV("setOutputFile");
    if (fileDescriptor == NULL) {
        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
        return;
    }
    int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    status_t opStatus = mr->setOutputFile(fd, offset, length);
    process_media_recorder_call(env, opStatus, "java/io/IOException", "setOutputFile failed.");
}

static void
android_media_MediaRecorder_setVideoSize(JNIEnv *env, jobject thiz, jint width, jint height)
{
    ALOGV("setVideoSize(%d, %d)", width, height);
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);

    if (width <= 0 || height <= 0) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "invalid video size");
        return;
    }
    process_media_recorder_call(env, mr->setVideoSize(width, height), "java/lang/RuntimeException", "setVideoSize failed.");
}

static void
android_media_MediaRecorder_setVideoFrameRate(JNIEnv *env, jobject thiz, jint rate)
{
    ALOGV("setVideoFrameRate(%d)", rate);
    if (rate <= 0) {
        jniThrowException(env, "java/lang/IllegalArgumentException", "invalid frame rate");
        return;
    }
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->setVideoFrameRate(rate), "java/lang/RuntimeException", "setVideoFrameRate failed.");
}

static void
android_media_MediaRecorder_setMaxDuration(JNIEnv *env, jobject thiz, jint max_duration_ms)
{
    ALOGV("setMaxDuration(%d)", max_duration_ms);
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);

    char params[64];
    sprintf(params, "max-duration=%d", max_duration_ms);

    process_media_recorder_call(env, mr->setParameters(String8(params)), "java/lang/RuntimeException", "setMaxDuration failed.");
}

static void
android_media_MediaRecorder_setMaxFileSize(
        JNIEnv *env, jobject thiz, jlong max_filesize_bytes)
{
    ALOGV("setMaxFileSize(%lld)", max_filesize_bytes);
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);

    char params[64];
    sprintf(params, "max-filesize=%lld", max_filesize_bytes);

    process_media_recorder_call(env, mr->setParameters(String8(params)), "java/lang/RuntimeException", "setMaxFileSize failed.");
}

static void
android_media_MediaRecorder_prepare(JNIEnv *env, jobject thiz)
{
    ALOGV("prepare");
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);

    jobject surface = env->GetObjectField(thiz, fields.surface);
    if (surface != NULL) {
        const sp<Surface> native_surface = get_surface(env, surface);

        // The application may misbehave and
        // the preview surface becomes unavailable
        if (native_surface.get() == 0) {
            ALOGE("Application lost the surface");
            jniThrowException(env, "java/io/IOException", "invalid preview surface");
            return;
        }

        ALOGI("prepare: surface=%p", native_surface.get());
        if (process_media_recorder_call(env, mr->setPreviewSurface(native_surface->getIGraphicBufferProducer()), "java/lang/RuntimeException", "setPreviewSurface failed.")) {
            return;
        }
    }
    process_media_recorder_call(env, mr->prepare(), "java/io/IOException", "prepare failed.");
}

static int
android_media_MediaRecorder_native_getMaxAmplitude(JNIEnv *env, jobject thiz)
{
    ALOGV("getMaxAmplitude");
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    int result = 0;
    process_media_recorder_call(env, mr->getMaxAmplitude(&result), "java/lang/RuntimeException", "getMaxAmplitude failed.");
    return result;
}

static void
android_media_MediaRecorder_start(JNIEnv *env, jobject thiz)
{
    ALOGV("start");
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->start(), "java/lang/RuntimeException", "start failed.");
}

static void
android_media_MediaRecorder_stop(JNIEnv *env, jobject thiz)
{
    ALOGV("stop");
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->stop(), "java/lang/RuntimeException", "stop failed.");
}

static void
android_media_MediaRecorder_native_reset(JNIEnv *env, jobject thiz)
{
    ALOGV("native_reset");
    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    process_media_recorder_call(env, mr->reset(), "java/lang/RuntimeException", "native_reset failed.");
}

static void
android_media_MediaRecorder_release(JNIEnv *env, jobject thiz)
{
    ALOGV("release");
    sp<MediaRecorder> mr = setMediaRecorder(env, thiz, 0);
    if (mr != NULL) {
        mr->setListener(NULL);
        mr->release();
    }
}

// This function gets some field IDs, which in turn causes class initialization.
// It is called from a static block in MediaRecorder, which won't run until the
// first time an instance of this class is used.
static void
android_media_MediaRecorder_native_init(JNIEnv *env)
{
    jclass clazz;

    clazz = env->FindClass("android/media/MediaRecorder");
    if (clazz == NULL) {
        return;
    }

    fields.context = env->GetFieldID(clazz, "mNativeContext", "I");
    if (fields.context == NULL) {
        return;
    }

    fields.surface = env->GetFieldID(clazz, "mSurface", "Landroid/view/Surface;");
    if (fields.surface == NULL) {
        return;
    }

    jclass surface = env->FindClass("android/view/Surface");
    if (surface == NULL) {
        return;
    }

    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
    if (fields.post_event == NULL) {
        return;
    }
}

static void
android_media_MediaRecorder_native_setup(JNIEnv *env, jobject thiz, jobject weak_this,
                                         jstring packageName)
{
    ALOGV("setup");

    sp<MediaRecorder> mr = new MediaRecorder();
    if (mr == NULL) {
        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
        return;
    }
    if (mr->initCheck() != NO_ERROR) {
        jniThrowException(env, "java/lang/RuntimeException", "Unable to initialize media recorder");
        return;
    }

    // create new listener and give it to MediaRecorder
    sp<JNIMediaRecorderListener> listener = new JNIMediaRecorderListener(env, thiz, weak_this);
    mr->setListener(listener);

   // Convert client name jstring to String16
    const char16_t *rawClientName = env->GetStringChars(packageName, NULL);
    jsize rawClientNameLen = env->GetStringLength(packageName);
    String16 clientName(rawClientName, rawClientNameLen);
    env->ReleaseStringChars(packageName, rawClientName);

    // pass client package name for permissions tracking
    mr->setClientName(clientName);

    setMediaRecorder(env, thiz, mr);
}

static void
android_media_MediaRecorder_native_finalize(JNIEnv *env, jobject thiz)
{
    ALOGV("finalize");
    android_media_MediaRecorder_release(env, thiz);
}

// ----------------------------------------------------------------------------

static JNINativeMethod gMethods[] = {
    {"setCamera",            "(Landroid/hardware/Camera;)V",    (void *)android_media_MediaRecorder_setCamera},
    {"setVideoSource",       "(I)V",                            (void *)android_media_MediaRecorder_setVideoSource},
    {"setAudioSource",       "(I)V",                            (void *)android_media_MediaRecorder_setAudioSource},
    {"setOutputFormat",      "(I)V",                            (void *)android_media_MediaRecorder_setOutputFormat},
    {"setVideoEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setVideoEncoder},
    {"setAudioEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setAudioEncoder},
    {"setParameter",         "(Ljava/lang/String;)V",           (void *)android_media_MediaRecorder_setParameter},
    {"_setOutputFile",       "(Ljava/io/FileDescriptor;JJ)V",   (void *)android_media_MediaRecorder_setOutputFileFD},
    {"setVideoSize",         "(II)V",                           (void *)android_media_MediaRecorder_setVideoSize},
    {"setVideoFrameRate",    "(I)V",                            (void *)android_media_MediaRecorder_setVideoFrameRate},
    {"setMaxDuration",       "(I)V",                            (void *)android_media_MediaRecorder_setMaxDuration},
    {"setMaxFileSize",       "(J)V",                            (void *)android_media_MediaRecorder_setMaxFileSize},
    {"_prepare",             "()V",                             (void *)android_media_MediaRecorder_prepare},
    {"getMaxAmplitude",      "()I",                             (void *)android_media_MediaRecorder_native_getMaxAmplitude},
    {"start",                "()V",                             (void *)android_media_MediaRecorder_start},
    {"stop",                 "()V",                             (void *)android_media_MediaRecorder_stop},
    {"native_reset",         "()V",                             (void *)android_media_MediaRecorder_native_reset},
    {"release",              "()V",                             (void *)android_media_MediaRecorder_release},
    {"native_init",          "()V",                             (void *)android_media_MediaRecorder_native_init},
    {"native_setup",         "(Ljava/lang/Object;Ljava/lang/String;)V", (void *)android_media_MediaRecorder_native_setup},
    {"native_finalize",      "()V",                             (void *)android_media_MediaRecorder_native_finalize},
};

static const char* const kClassPathName = "android/media/MediaRecorder";

// This function only registers the native methods, and is called from
// JNI_OnLoad in android_media_MediaPlayer.cpp
int register_android_media_MediaRecorder(JNIEnv *env)
{
    return AndroidRuntime::registerNativeMethods(env,
                "android/media/MediaRecorder", gMethods, NELEM(gMethods));
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/item_root_layout"
    style="@style/ListItem"
    tools:ignore="RtlHardcoded">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image_user"
            style="@style/UserIconStyle"
            tools:background="@color/color_new_blue"/>

        <TextView
            android:id="@+id/text_user_avatar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:paddingBottom="2dp"
            android:textColor="@color/text_color_white"
            android:textSize="17sp"
            android:textStyle="normal"
            tools:text="E" />
    </RelativeLayout>

    <TextView
        android:id="@+id/text_user_login"
        style="@style/UserTitleStyle"
        tools:text="abrakadabra"/>

    <CheckBox
        android:id="@+id/checkbox_user"
        style="@style/UserCheckboxStyle" />
</LinearLayout>


text:
package org.apache.druid.java.util.common.parsers;

import java.util.List;

/**
 * This type of ParseException is meant to be used within ingestion to hold parse exception information for
 * rows that were partially parseable but had one or more unparseable columns, such as when passing a non-numeric
 * value to a numeric column. There may be several such exceptions in a given row, so this exception can hold
 * multiple column exception messages.
 */
public class UnparseableColumnsParseException extends ParseException
{
  private final List<String> columnExceptionMessages;

  public UnparseableColumnsParseException(
      String event,
      List<String> details,
      boolean fromPartiallyValidRow,
      String formatText,
      Object... arguments
  )
  {
    super(event, fromPartiallyValidRow, formatText, arguments);
    this.columnExceptionMessages = details;
  }

  public List<String> getColumnExceptionMessages()
  {
    return columnExceptionMessages;
  }
}


text:
'use strict';

var Key = protractor.Key;

exports.execute = function(){
    browser.actions().sendKeys(Key.chord('e')).perform();
};

exports.cancelExecution = function(){
    browser.actions().sendKeys(Key.chord(Key.SHIFT, 'e')).perform();
};

exports.delete = function(){
    browser.actions().sendKeys(Key.chord(Key.SHIFT, 'd')).perform();
};

exports.updateDeployment = function(){
    browser.actions().sendKeys(Key.chord('u')).perform();
};


text:
package com.coremedia.iso.boxes.apple;

import com.googlecode.mp4parser.AbstractFullBox;

import java.nio.ByteBuffer;

/**
 * Most stupid box of the world. Encapsulates actual data within
 */
public final class AppleDataBox extends AbstractFullBox {
    public static final String TYPE = "data";

    private byte[] fourBytes = new byte[4];
    private byte[] data;

    private static AppleDataBox getEmpty() {
        AppleDataBox appleDataBox = new AppleDataBox();
        appleDataBox.setVersion(0);
        appleDataBox.setFourBytes(new byte[4]);
        return appleDataBox;
    }

    public static AppleDataBox getStringAppleDataBox() {
        AppleDataBox appleDataBox = getEmpty();
        appleDataBox.setFlags(1);
        appleDataBox.setData(new byte[]{0});
        return appleDataBox;
    }

    public static AppleDataBox getUint8AppleDataBox() {
        AppleDataBox appleDataBox = new AppleDataBox();
        appleDataBox.setFlags(21);
        appleDataBox.setData(new byte[]{0});
        return appleDataBox;
    }

    public static AppleDataBox getUint16AppleDataBox() {
        AppleDataBox appleDataBox = new AppleDataBox();
        appleDataBox.setFlags(21);
        appleDataBox.setData(new byte[]{0, 0});
        return appleDataBox;
    }

    public static AppleDataBox getUint32AppleDataBox() {
        AppleDataBox appleDataBox = new AppleDataBox();
        appleDataBox.setFlags(21);
        appleDataBox.setData(new byte[]{0, 0, 0, 0});
        return appleDataBox;
    }

    public AppleDataBox() {
        super(TYPE);
    }

    protected long getContentSize() {
        return data.length + 8;
    }

    public void setData(byte[] data) {
        this.data = new byte[data.length];
        System.arraycopy(data, 0, this.data, 0, data.length);
    }

    public void setFourBytes(byte[] fourBytes) {
        System.arraycopy(fourBytes, 0, this.fourBytes, 0, 4);
    }

    @Override
    public void _parseDetails(ByteBuffer content) {
        parseVersionAndFlags(content);
        fourBytes = new byte[4];
        content.get(fourBytes);
        data = new byte[content.remaining()];
        content.get(data);
    }

    @Override
    protected void getContent(ByteBuffer byteBuffer) {
        writeVersionAndFlags(byteBuffer);
        byteBuffer.put(fourBytes, 0, 4);
        byteBuffer.put(data);
    }

    public byte[] getFourBytes() {
        return fourBytes;
    }

    public byte[] getData() {
        return data;
    }
}


text:
/* Add .clearfix to container block element to clear both floats. */
.clearfix:after{content:".";display:block;height:0;clear: both;visibility: hidden;}
.clearfix{display:inline-table;}
/* backslash hack hides from IE mac \*/
* html .clearfix{height:1%;}
.clearfix{display:block;}
/* end backslash hack */


text:
from visual import *
from viewer.visual.viewer2d import *

import math as m

class KidneyViewer(Viewer2D):
    """
    """

    def __init__(self, lsystem):
        """
        """

        self.viewer_type = "kidney viewer"

        self.lsystem = lsystem
        self.alpha = float(self.lsystem.alpha)
        self.debug = False

        self.init()

    def init(self):
        """
        """

        # Symbol behaviour initialisation
        self.draw_forward = ['F']
        self.move_forward = ['M']
        self.rotation = ['+', '-']
        self.push_pop = ['[', ']']
        self.do_nothing = ['X']

        # Init heap / stack to remember position
        self.saved_pos = []
        self.saved_vector = []

        # Visual initialisation
        self.scene = display(title = "L-System name : " + self.lsystem.name + " ( " + self.viewer_type + " )",
                             x = 0, y = 0, width = 1024, height = 768,
                             center = (0,0,0), background = (0,0,0),
                             autocenter = True)
        rate(50)
        self.line = curve( pos = (0,0) )
        self.color = color.green
        #self.draw_axis()

        # Branch initial parameters
        self.radius = 0.1
        self.length = 2
        self.angle = self.lsystem.angle

        self.saved_radius = [self.radius]
        self.saved_length = [self.length]
        self.saved_angleRatio = [1]
        self.parents = {}

        # Calculate ratios
        self.computeRadius()
        self.computeLength()
        self.computeAngle()
        self.d1 = True

    def draw(self, state):
        """
        """

        # Remove previous curve
        self.line.visible = False

        # Init curve
        self.vector = vector(1, 0)
        self.pos = vector(0,0)
        self.line = curve( pos = (0,0),
                           color = self.color,
                           radius = self.radius)

        # Debug stuff
        self.sphere = None

        # Draw curve
        for s in state:

            symbol = self.lsystem.get_symbol(s)
            self.execute_symbol(symbol)

            ## Debug info
            if self.debug:
                if self.sphere:
                    self.sphere.visible = False
                self.sphere = sphere(pos = self.pos, color = color.red, radius = 0.25)

    def execute_symbol(self, symbol):
        """
        """

        if symbol in self.draw_forward:
            """
            Draw forward
            """

            self.old = self.pos
            self.pos = self.pos + self.vector * self.saved_length[-1]

            self.line = curve( pos = [self.old, self.pos],
                               color = self.color,
                               radius = self.saved_radius[-1] )

        if symbol in self.move_forward:
            """
            Move forward
            """

            self.pos = self.pos + self.vector * self.saved_length[-1]
            self.line = curve( pos = self.pos,
                               color = self.color,
                               radius = self.radius)

        elif symbol in self.rotation:
            """
            Rotation
            """

            angle = float(symbol + str(self.angle))

            x, y = self.rotate(self.vector, radians(angle) * self.saved_angleRatio[-1])
            self.vector = vector(x, y)

        elif symbol in self.push_pop:
            """
            Save current position or restore it
            """

            if symbol == '[':
                self.saved_pos.append(self.pos)
                self.saved_vector.append(self.vector)

                if self.d1:
                    self.saved_length.append(self.saved_length[-1] * self.lengthRatio1)
                    self.saved_radius.append(self.saved_radius[-1] * self.radiusRatio1)
                    self.saved_angleRatio.append(self.angleRatio1)
                else:
                    self.saved_length.append(self.saved_length[-1] * self.lengthRatio2)
                    self.saved_radius.append(self.saved_radius[-1] * self.radiusRatio2)
                    self.saved_angleRatio.append(self.angleRatio2)

            elif symbol == ']':

                self.pos = self.saved_pos.pop()
                self.vector = self.saved_vector.pop()
                self.saved_radius.pop()
                self.saved_length.pop()
                self.saved_angleRatio.pop()

                self.d1 = not self.d1

                self.line = curve( pos = self.pos,
                                   color = color.green,
                                   radius = self.radius)

        elif symbol in self.do_nothing:
            """
            Do nothing
            """

            pass

    def computeRadius(self):
        """
        """

        self.radiusRatio1 = 1.0 / m.pow( (1.0 + m.pow(self.alpha, 3.0)), 1.0/3)
        self.radiusRatio2 = self.alpha / m.pow( (1.0 + m.pow(self.alpha, 3.0)), 1.0/3)

    def computeLength(self):
        """
        """

        self.lengthRatio1 = self.radiusRatio1
        self.lengthRatio2 = self.radiusRatio2

    def computeAngle(self):
        """
        """

        a = self.alpha

        self.angleRatio1 = m.acos(( (1 + a**3.0)**(4/3.0) + 1 - a**4.0 ) / ( 2.0 * ( 1 + a ** 3.0) ** (2/3.0)))
        self.angleRatio2 = m.acos(( (1 + a**3.0)**(4/3.0) + a**4.0 - 1 ) / ( 2.0 * a**2 * ( 1 + a ** 3.0) ** (2/3.0)))

    def rotate(self, vec, radian):
        """
        """

        x = vec.x * cos(radian) - vec.y * sin(radian)
        y = vec.x * sin(radian) + vec.y * cos(radian)

        return x, y


text:
So I can keep track of what I'm working on

[![Stories in Ready](https://badge.waffle.io/Widdershin/projects.png?label=ready&title=Ready)](http://waffle.io/Widdershin/projects)


text:
package it.synthema;

/**
 * Representation of a transcripted word.
 * Is composed by a triplet:<br>
 * - word spoken;
 * - starting time of the speech
 * - ending time of the speech
 * @author ercole
 *
 */
public class TranscriptedWord {

	public String word;
	public long start_time;
	public long end_time;

	@Override
	public String toString() {
		return this.word+"\t"+ start_time + "\t"+ end_time+"\n";
	}

	public TranscriptedWord(String word, long start_time, long end_time) {
		super();
		this.word = word;
		this.start_time = start_time;
		this.end_time = end_time;
	}

}


text:
var $sFormAjaxRequest = null;
var $bButtonSubmitActive = true;
var $ActivityFeedCompleted = {};
var $sCurrentSectionDefaultPhrase = null;
var $sCssHeight = '40px';
var $sCustomPhrase = null;
var $sCurrentForm = null;
var $sStatusUpdateValue = null;
var $iReloadIteration = 0;
var $oLastFormSubmit = null;
var bCheckUrlCheck = false;
var bCheckUrlForceAdd = false;

$Core.isInView = function(elem)
{
    if (!$Core.exists(elem)){
		return false;
	}

	var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

	return ((docViewTop < elemTop) && (docViewBottom > elemBottom));
}

$Core.resetActivityFeedForm = function()
{
	$('.activity_feed_form_attach li a').removeClass('active');
	$('.activity_feed_form_attach li a:first').addClass('active');
	$('.global_attachment_holder_section').hide();
	$('#global_attachment_status').show();
	$('.global_attachment_holder_section textarea').val($('#global_attachment_status_value').html()).css({height: $sCssHeight});

	$('.activity_feed_form_button_status_info').hide();
	$('.activity_feed_form_button_status_info textarea').val('');

	$Core.resetActivityFeedErrorMessage();

	$sFormAjaxRequest = $('.activity_feed_form_attach li a.active').find('.activity_feed_link_form_ajax').html();

	$Core.activityFeedProcess(false);

	$('.js_share_connection').val('0');
	$('.feed_share_on_item a').removeClass('active');

	$.each($ActivityFeedCompleted, function()
	{
		this(this);
	});
}

$Core.resetActivityFeedErrorMessage = function()
{
	$('#activity_feed_upload_error').hide();
	$('#activity_feed_upload_error_message').html('');
}

$Core.resetActivityFeedError = function(sMsg)
{
	$('.activity_feed_form_share_process').hide();
	$('.activity_feed_form_button .button').removeClass('button_not_active');
	$bButtonSubmitActive = true;
	$('#activity_feed_upload_error').show();
	$('#activity_feed_upload_error_message').html(sMsg);
}

$Core.activityFeedProcess = function($bShow)
{
	if ($bShow)
	{
		$bButtonSubmitActive = false;
		$('.activity_feed_form_share_process').show();
		$('.activity_feed_form_button .button').addClass('button_not_active');
	}
	else
	{
		$bButtonSubmitActive = true;
		$('.activity_feed_form_share_process').hide();
		$('.activity_feed_form_button .button').removeClass('button_not_active');
		$('.egift_wrapper').hide();
	}
}

$Core.addNewPollOption = function()
{
	$('.js_poll_feed_answer').append('
<input type="text" name="val[answer][][answer]" value="" size="30" class="js_feed_poll_answer v_middle" />
');

	return false;
}

/*

$(function()
{

	$('body').click(function()
	{
		$('.js_comment_feed_textarea').each(function()
		{
			if ($(this).hasClass('is_focus'))
			{
				$(this).removeClass('is_focus');
			}
			else
			{
				if (empty($(this).val()))
				{
					$(this).removeClass('js_comment_feed_textarea_focus');
					$(this).val($('.js_comment_feed_value').html());
					if (!$(this).parents('.comment_mini:first').hasClass('feed_item_view'))
					{
						$(this).parents('.comment_mini:first').find('.comment_mini_textarea_holder').removeClass('comment_mini_content');
						$(this).parents('.comment_mini:first').find('.comment_mini_image').hide();
					}
				}

				$(this).parents('.comment_mini').find('.feed_comment_buttons_wrap').hide();
			}
		});
	});
});

*/

$Core.forceLoadOnFeed = function()
{
	if ($iReloadIteration >= 2){
		return;
	}

	$iReloadIteration++;
	$('#feed_view_more_loader').show();
	$('.global_view_more').hide();

	setTimeout("$.ajaxCall('feed.viewMore', $('#js_feed_pass_info').html().replace(/&/g, '&') + '&iteration=" + $iReloadIteration + "', 'GET');", 1000);
}

$Core.handlePasteInFeed = function(oObj)
{
	if ((substr($(oObj).val(), 0, 7) == 'http://' || substr($(oObj).val(), 0, 8) == 'https://' || (substr($(oObj).val(), 0, 4) == 'www.')))
	{
		bCheckUrlCheck = true;

		$('.activity_feed_form_share_process').show();
		$(oObj).parent().append('

');
		$Core.ajax('link.preview',{
			type: 'POST',
			params:{
				'no_page_update': '1',
				value: $(oObj).val()
			},
			success: function($sOutput){
				$('.activity_feed_form_share_process').hide();
				if (substr($sOutput, 0, 1) == '{'){

				}
				else{
					$('#js_global_attach_value').val($(oObj).val());
					bCheckUrlForceAdd = true;
					// bCheckUrlCheck = false;
					$('#js_preview_link_attachment_custom_form_sub').html($sOutput);
				}
			}
		});
	}
}

$Behavior.activityFeedProcess = function()
	{
		if (!$Core.exists('#js_feed_content')){
			$iReloadIteration = 0;
			return;
		}

		if ($Core.exists('.global_view_more')){
			if ($Core.isInView('.global_view_more')){
				$Core.forceLoadOnFeed();
			}

			$(window).scroll(function(){
				if ($Core.isInView('.global_view_more')){
					$Core.forceLoadOnFeed();
				}
			});
		}

		$sFormAjaxRequest = $('.activity_feed_form_attach li a.active').find('.activity_feed_link_form_ajax').html();
		if (typeof Plugin_sFormAjaxRequest == 'function')
		{
			Plugin_sFormAjaxRequest();
		}

		if ($Core.exists('.profile_timeline_header')){
			$(window).scroll(function(){
				if (isScrolledIntoView('.profile_timeline_header')){
					$('.timeline_main_menu').removeClass('timeline_main_menu_fixed');
					$('#timeline_dates').removeClass('timeline_dates_fixed');
				}
				else{
					if (!$('.timeline_main_menu').hasClass('timeline_main_menu_fixed')){
						$('.timeline_main_menu').addClass('timeline_main_menu_fixed');

						if ($('.content').height() > 600){
							$('#timeline_dates').addClass('timeline_dates_fixed');
						}
					}
				}
			});
		}

		$('#global_attachment_status textarea').keyup(function(){
			$Core.handlePasteInFeed($(this));}).bind('paste', function()
			{
				var that = this;
				setTimeout(function(){
					$Core.handlePasteInFeed(that);
				}, 0);

			});

		$('#global_attachment_status textarea').keydown(function(){
			$Core.resizeTextarea($(this));
		});

		$('.activity_feed_form_button_status_info textarea').keydown(function(){$Core.resizeTextarea($(this));});

		$('#global_attachment_status textarea').focus(function()
		{
			if ($(this).val() == $('#global_attachment_status_value').html())
			{
				$(this).val('');
				$(this).css({height: '50px'});
				$('.activity_feed_form_button').show();
				$(this).addClass('focus');
				$('.activity_feed_form_button_status_info textarea').addClass('focus');
			}
		});

		$('.activity_feed_form_button_status_info textarea').focus(function()
		{
			var $sDefaultValue = $(this).val();
			var $bIsDefault = true;

			$('.activity_feed_extra_info').each(function()
			{
				if ($(this).html() == $sDefaultValue)
				{
					$bIsDefault = false;

					return false;
				}
			});

			if (($('#global_attachment_status textarea').val() == $('#global_attachment_status_value').html() && empty($sDefaultValue)) || !$bIsDefault)
			{
				$(this).val('');
				$(this).css({height: '50px'});

				$(this).addClass('focus');
				$('#global_attachment_status textarea').addClass('focus');
			}
		});

		$('#js_activity_feed_form').submit(function()
		{
			if ($sCurrentForm == 'global_attachment_status'){
				var oStatusUpdateTextareaFilled = $('#global_attachment_status textarea');

				if ($sStatusUpdateValue == oStatusUpdateTextareaFilled.val()){
					oStatusUpdateTextareaFilled.val('');
				}
			}
			else{
				var oCustomTextareaFilled = $('.activity_feed_form_button_status_info textarea');

				if ($sCustomPhrase == oCustomTextareaFilled.val()){
					oCustomTextareaFilled.val('');
				}
			}

			if ($bButtonSubmitActive === false)
			{
				return false;
			}

			$Core.activityFeedProcess(true);

			if ($sFormAjaxRequest === null)
			{
				return true;
			}

			$('.js_no_feed_to_show').remove();

			if (bCheckUrlForceAdd){
				$('.activity_feed_form_button_status_info textarea').val($('#global_attachment_status textarea').val());
				$sFormAjaxRequest = 'link.addViaStatusUpdate';
			}

			$(this).ajaxCall($sFormAjaxRequest);

			if (bCheckUrlForceAdd){
				$('#js_preview_link_attachment_custom_form_sub').remove();
			}

			return false;
		});

		$('.activity_feed_form_attach li a').click(function()
		{
			$sCurrentForm = $(this).attr('rel');

			if ($sCurrentForm == 'view_more_link'){
				$('.view_more_drop').toggle();
				return false;
			}
			else{
				$('.view_more_drop').hide();
			}

			$('#js_preview_link_attachment_custom_form_sub').remove();
			$('#activity_feed_upload_error').hide();

			$('.global_attachment_holder_section').hide();
			$('.activity_feed_form_attach li a').removeClass('active');
			$(this).addClass('active');

			if ($(this).find('.activity_feed_link_form').length > 0)
			{
				$('#js_activity_feed_form').attr('action', $(this).find('.activity_feed_link_form').html()).attr('target', 'js_activity_feed_iframe_loader');
				$sFormAjaxRequest = null;
				if (empty($('.activity_feed_form_iframe').html()))
				{
					$('.activity_feed_form_iframe').html('');
				}
			}
			else
			{
				$sFormAjaxRequest = $(this).find('.activity_feed_link_form_ajax').html();
			}

			$('#' + $(this).attr('rel')).show();
			$('.activity_feed_form_holder_attach').show();
			$('.activity_feed_form_button').show();

			var $oStatusUpdateTextarea = $('#global_attachment_status textarea');
			var $sStatusUpdateTextarea = $oStatusUpdateTextarea.val();
			$sStatusUpdateValue = $('#global_attachment_status_value').html();

			var $oCustomTextarea = $('.activity_feed_form_button_status_info textarea');
			var $sCustomTextarea = $oCustomTextarea.val();

			$sCustomPhrase = $(this).find('.activity_feed_extra_info').html();

			var $bHasDefaultValue = false;
			$('.activity_feed_extra_info').each(function()
			{
				if ($(this).html() == $sCustomTextarea)
				{
					$bHasDefaultValue = true;

					return false;
				}
			});

			if ($(this).attr('rel') != 'global_attachment_status')
			{
				$('.activity_feed_form_button_status_info').show();

				if ((empty($sCustomTextarea) && ($sStatusUpdateTextarea == $sStatusUpdateValue
					|| empty($sStatusUpdateTextarea)))
					|| ($sStatusUpdateTextarea == $sStatusUpdateValue && $bHasDefaultValue)
					|| (!$bButtonSubmitActive && $bHasDefaultValue)
				)
				{
					$oCustomTextarea.val($sCustomPhrase).css({height: $sCssHeight});
				}
				else if ($sStatusUpdateTextarea != $sStatusUpdateValue && $bButtonSubmitActive && !empty($sStatusUpdateTextarea))
				{
					$oCustomTextarea.val($sStatusUpdateTextarea);
				}

				$('.activity_feed_form_button .button').addClass('button_not_active');
				$bButtonSubmitActive = false;
			}
			else
			{
				$('.activity_feed_form_button_status_info').hide();
				$('.activity_feed_form_button .button').removeClass('button_not_active');

				if (!$bHasDefaultValue && !empty($sCustomTextarea))
				{
					$oStatusUpdateTextarea.val($sCustomTextarea);
				}
				else if ($bHasDefaultValue && empty($sStatusUpdateTextarea))
				{
					$oStatusUpdateTextarea.val($sStatusUpdateValue).css({height: $sCssHeight});
				}

				$bButtonSubmitActive = true;
			}

			if ($(this).hasClass('no_text_input'))
			{
				$('.activity_feed_form_button_status_info').hide();
			}

			if (((navigator.userAgent.match(/iPhone/i)) ||  (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) )
			{
				if ($('#Filedata').length < 1) /* it means we already added it and triggered mobileInit() */
				{
					$('.activity_feed_form_button .button').hide().after('<input type="button" name="Filedata" id="Filedata" value="Choose photo">');
					mobileInit();
				}

			}
			return false;
		});
	}

$Behavior.activityFeedLoader = function()
{
	/**
	 * Click on adding a new comment link.
	 */
	$('.js_feed_entry_add_comment').click(function()
	{
		$('.js_comment_feed_textarea').each(function()
		{
			if ($(this).val() == $('.js_comment_feed_value').html())
			{
				$(this).removeClass('js_comment_feed_textarea_focus');
				$(this).val($('.js_comment_feed_value').html());
			}

			$(this).parents('.comment_mini').find('.feed_comment_buttons_wrap').hide();
		});

		$(this).parents('.js_parent_feed_entry:first').find('.comment_mini_content_holder').show();
		$(this).parents('.js_parent_feed_entry:first').find('.feed_comment_buttons_wrap').show();

		if ($(this).parents('.js_parent_feed_entry:first').find('.js_comment_feed_textarea').val() == $('.js_comment_feed_value').html())
		{
			$(this).parents('.js_parent_feed_entry:first').find('.js_comment_feed_textarea').val('');
		}
		$(this).parents('.js_parent_feed_entry:first').find('.js_comment_feed_textarea').focus().addClass('js_comment_feed_textarea_focus');
		$(this).parents('.js_parent_feed_entry:first').find('.comment_mini_textarea_holder').addClass('comment_mini_content');
		$(this).parents('.js_parent_feed_entry:first').find('.js_feed_comment_form').find('.comment_mini_image').show();

		var iTotalComments = 0;
		$(this).parents('.js_parent_feed_entry:first').find('.js_mini_feed_comment').each(function()
		{
			iTotalComments++;
		});

		if (iTotalComments > 2)
		{
			$.scrollTo($(this).parents('.js_parent_feed_entry:first').find('.js_comment_feed_textarea_browse:first'), 340);
		}

		return false;
	});

	/**
	 * Comment textarea on focus.
	 */
	$('.js_comment_feed_textarea').click(function()
	{
		$Core.commentFeedTextareaClick(this);
	});

	$('#js_captcha_load_for_check_submit').submit(function(){

		if (function_exists('' + Editor.sEditor + '_wysiwyg_feed_comment_form'))
		{
			eval('' + Editor.sEditor + '_wysiwyg_feed_comment_form(this);');
		}

		$oLastFormSubmit.parent().parent().find('.js_feed_comment_process_form:first').show();
		$(this).ajaxCall('comment.add', $oLastFormSubmit.getForm());

		return false;
	});

	$('.js_comment_feed_form').submit(function()
	{
		if ($Core.exists('#js_captcha_load_for_check')){
			$('#js_captcha_load_for_check').css({
				top: getPageScroll()[1] + (getPageHeight() / 5),
				left: '50%',
				'margin-left': '-' + (($('#js_captcha_load_for_check').width() / 2) + 12) + 'px',
				display: 'block'
			});

			$oLastFormSubmit = $(this);

			return false;
		}

		if (function_exists('' + Editor.sEditor + '_wysiwyg_feed_comment_form'))
		{
			eval('' + Editor.sEditor + '_wysiwyg_feed_comment_form(this);');
		}

		$(this).parent().parent().find('.js_feed_comment_process_form:first').show();
		$(this).ajaxCall('comment.add');

		return false;
	});

	$('.js_comment_feed_new_reply').click(function(){

		var oParent = $(this).parents('.js_mini_feed_comment:first').find('.js_comment_form_holder:first');
		if (Editor.sEditor == 'tiny_mce' || Editor.sEditor == 'tinymce'){
			$('.js_comment_feed_form').find('.js_feed_comment_parent_id:first').val($(this).attr('rel'));
			tinyMCE.activeEditor.focus();
			if (typeof($.scrollTo) == 'function'){
				$.scrollTo('.js_comment_feed_form', 800);
			}
			return false;
		}

		oParent.html($('.js_feed_comment_form').html());
		oParent.find('.js_feed_comment_parent_id:first').val($(this).attr('rel'));

		oParent.find('.js_comment_feed_textarea:first').focus();
		$Core.commentFeedTextareaClick(oParent.find('.js_comment_feed_textarea:first'));

		$Core.loadInit();
		/*$Behavior.activityFeedLoader();*/

		return false;
	});

	$('.comment_mini').hover(function(){

		$('.feed_comment_delete_link').hide();
		$(this).find('.feed_comment_delete_link:first').show();

	}, function(){

		$('.feed_comment_delete_link').hide();

	});

}

$Core.commentFeedTextareaClick = function($oObj)
{
	$($oObj).keydown(function()
	{
		if ($(this).hasClass('no_resize_textarea')){
			return;
		}
		$Core.resizeTextarea($(this));
	});

	if ($($oObj).val() == $('.js_comment_feed_value').html())
	{
		$($oObj).val('');
	}

	$($oObj).addClass('js_comment_feed_textarea_focus').addClass('is_focus');
	$($oObj).parents('.comment_mini').find('.feed_comment_buttons_wrap:first').show();

	$($oObj).parent().parent().find('.comment_mini_textarea_holder:first').addClass('comment_mini_content');
	$($oObj).parent().parent().find('.comment_mini_image:first').show();
	/*p($($oObj).parent().parent().html());*/
}

$Behavior.activityFeedAttachLink = function()
{
	$('#js_global_attach_link').click(function()
	{
		$Core.activityFeedProcess(true);

		$Core.ajax('link.preview',
		{
			params:
			{
				'no_page_update': '1',
				value: $('#js_global_attach_value').val()
			},
			type: 'POST',
			success: function($sOutput)
			{
				$('#js_global_attachment_link_cancel').show();

				if (substr($sOutput, 0, 1) == '{'){
					var $oOutput = $.parseJSON($sOutput);
					$Core.resetActivityFeedError($oOutput['error']);
					$bButtonSubmitActive = false;
					$('.activity_feed_form_button .button').addClass('button_not_active');
				}
				else{
					$Core.activityFeedProcess(false);

					$('#js_preview_link_attachment').html($sOutput);
					$('#global_attachment_link_holder').hide();
				}
			}
		});
	});
}

$ActivityFeedCompleted.link = function()
{
	$bButtonSubmitActive = true;

	$('#global_attachment_link_holder').show();
	$('.activity_feed_form_button .button').removeClass('button_not_active');
	$('#js_preview_link_attachment').html('');
	$('#js_global_attach_value').val('http://');
}

$ActivityFeedCompleted.photo = function()
{
	$bButtonSubmitActive = true;

	$('#global_attachment_photo_file_input').val('');
}

function attachFunctionTagger(sSelector)
{
	$(sSelector).data('selector', sSelector).keyup(function(eventObject, sSelector){
				var sInput = $($(this).data('selector')).val();

				var iInputLength = sInput.length;
				var iAtSymbol = sInput.lastIndexOf('@');

				if (sInput == '@' || empty(sInput) || iAtSymbol < 0 || iAtSymbol == (iInputLength-1))
				{
					$($(this).data('selector')).siblings('.chooseFriend').hide(function(){$(this).remove();});
					return;
				}
				var sNameToFind = sInput.substring(iAtSymbol+1, iInputLength);

				/* loop through friends */
				var aFoundFriends = [], sOut = '';
				for (var i in $Cache.friends)
				{
					if ($Cache.friends[i]['full_name'].toLowerCase().indexOf(sNameToFind.toLowerCase()) >= 0)
					{

						var sNewInput = sInput.substr(0, iAtSymbol).replace(/\'/g,'\\\'').replace(/\"/g,'"');
						aFoundFriends.push({user_id: $Cache.friends[i]['user_id'], full_name: $Cache.friends[i]['full_name'], user_image: $Cache.friends[i]['user_image']});

						sOut += '

' +(($Cache.friends[i]['full_name'].length > 25) ?($Cache.friends[i]['full_name'].substr(0,25) + '...') : $Cache.friends[i]['full_name']) + '
';
						/* just delete the fancy choose your friend and recreate it */
					}
				}

				$($(this).data('selector')).siblings('.chooseFriend').remove();
				$($(this).data('selector')).after('
'+sOut+'
');

			}).focus(function(){
				if (typeof $Cache == 'undefined' || typeof $Cache.friends == 'undefined')
				{

					$.ajaxCall('friend.buildCache','','GET');
				}
			});

}

$Behavior.tagger = function()
{
	var aSelectors = ['#js_activity_feed_form > .activity_feed_form_holder > #global_attachment_status > textarea','.js_comment_feed_textarea', '.js_comment_feed_textarea_focus'];
	/*js_comment_feed_textarea js_comment_feed_textarea_focus is_focus
	 try to replace a class selector for the ids of all of the inputs that it matches*/
	for (var i in aSelectors)
	{

		if ( $(aSelectors[i]).length >= 1)
		{
			var bChanged = false;
			$.each($(aSelectors[i]), function(key, value)
			{

				if ($(value).attr('id') != undefined)
				{
					aSelectors.push('#' + $(value).attr('id'));
					bChanged = true;
				}
			});
			if (bChanged)
			{
				aSelectors.splice(i,1);
			}
		}
	}

	for (var i in aSelectors)
	{
		var sSelector = aSelectors[i];

		/* Dont tag users in feeds in pages, events or profiles other than mine*/
		if (sSelector == '#pageFeedTextarea' || sSelector == '#eventFeedTextarea'  || sSelector == '#profileFeedTextarea')
		{

			continue;
		}

		if ($(sSelector).length > 1)
		{

			$.each($(sSelector), function(key, value)
			{

				if ($(value).attr('id') != undefined)
				{
					attachFunctionTagger('#'+$(value).attr('id'));
				}
			});
			continue;
		}
		attachFunctionTagger(sSelector);
	}
};


text:
@implementation NSString (TestNonEmpty)

- (BOOL)notEmpty {
    return [self length] > 0;
}

@end


text:
class MembersRole < ApplicationRecord
  validates :member_id, presence: true
  validates :role_id, presence: true
  # attr_accessible :created_at, :member, :role

  belongs_to :member, touch: true
  belongs_to :role
end

# == Schema Information
#
# Table name: members_roles
#
#  id         :bigint           not null, primary key
#  member_id  :integer
#  role_id    :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#


text:
package querqy.solr.rewriter.commonrules;

import querqy.rewrite.commonrules.select.SelectionStrategyFactory;
import querqy.rewrite.commonrules.select.SelectionStrategy;
import querqy.rewrite.commonrules.select.ExpressionCriteriaSelectionStrategyFactory;
import querqy.solr.FactoryAdapter;

import java.util.Map;

public class ExpressionSelectionStrategyFactory implements FactoryAdapter<SelectionStrategyFactory> {

    @Override
    public SelectionStrategyFactory createFactory(final String strategyId, final Map<String, Object> args) {
        // TODO: pass strategyId
        return new ExpressionCriteriaSelectionStrategyFactory();
    }

    @Override
    public Class<?> getCreatedClass() {
        return SelectionStrategy.class;
    }
}


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.

.. _howto/operator:ImapAttachmentToS3Operator:

Imap Attachment To S3 Operator
==============================

.. contents::
  :depth: 1
  :local:

Overview
--------

The ``ImapAttachmentToS3Operator`` can transfer an email attachment via IMAP
protocol from a mail server to S3 Bucket.

An example dag ``example_imap_attachment_to_s3.py`` is provided which showcase the
:class:`~airflow.providers.amazon.aws.operators.imap_attachment_to_s3.ImapAttachmentToS3Operator`
in action.

example_imap_attachment_to_s3.py
--------------------------------

Purpose
"""""""
This is an example dag for using ``ImapAttachmentToS3Operator`` to transfer an email attachment via IMAP
protocol from a mail server to S3 Bucket.

Environment variables
"""""""""""""""""""""

These examples rely on the following variables, which can be passed via OS environment variables.

.. exampleinclude:: ../../../../../airflow/providers/amazon/aws/example_dags/example_imap_attachment_to_s3.py
    :language: python
    :start-after: [START howto_operator_imap_attachment_to_s3_env_variables]
    :end-before: [END howto_operator_imap_attachment_to_s3_env_variables]

Transfer Mail Attachments via IMAP to S3
""""""""""""""""""""""""""""""""""""""""

.. exampleinclude:: ../../../../../airflow/providers/amazon/aws/example_dags/example_imap_attachment_to_s3.py
    :language: python
    :start-after: [START howto_operator_imap_attachment_to_s3_task_1]
    :end-before: [END howto_operator_imap_attachment_to_s3_task_1]

Reference
---------

For further information, look at:

* `IMAP Library Documentation <https://docs.python.org/3.6/library/imaplib.html>`__
* `AWS boto3 Library Documentation for S3 <https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html>`__


text:
<?php

namespace ServerGrove\KbBundle\Controller\Admin;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\SecurityContext;

/**
 * Class AdminDefaultController
 *
 * @Route("/admin")
 *
 * @author Ismael Ambrosi<ismael@servergrove.com>
 */
class DefaultController extends Controller
{

    /**
     * @Route("/login", name="sgkb_admin_login")
     * @Template
     */
    final public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        }

        return array(
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error
        );
    }

    /**
     * @Route("/login-check", name="sgkb_admin_login_check")
     * @Method("post")
     * @Template
     */
    final public function loginCheckAction()
    {
        return array();
    }

    /**
     * @Route("/logout", name="sgkb_admin_logout")
     */
    final public function logoutAction()
    {
        return array();
    }

    /**
     * @Route("/", name="sgkb_admin")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    final public function redirectAction()
    {
        return $this->redirect($this->generateUrl('sgkb_admin_categories_index'));
    }

    /**
     * @Template
     */
    public function adminAccessAction()
    {
        if (!$this->get('security.context')->isGranted('ROLE_EDITOR')) {
            return new \Symfony\Component\HttpFoundation\Response('');
        }

        return array();
    }

    /**
     * @Template
     *
     * @return array
     */
    public function topbarAction()
    {
        /** @var $token \Symfony\Component\Security\Core\Authentication\Token\TokenInterface */
        $roles = $this->get('security.context')->getToken()->getRoles();

        return array('authenticated' => !empty($roles));
    }
}


text:
package com.namelessmc.java_api.exception;

import com.namelessmc.java_api.modules.NamelessModule;

public class MissingModuleException extends NamelessException {

	private static final long serialVersionUID = 1L;

	public MissingModuleException(final NamelessModule module) {
		super(getExceptionMessage(module));
	}

	private static String getExceptionMessage(final NamelessModule module) {
		StringBuilder builder = new StringBuilder("Required module not installed: ");
		builder.append(module.name());
		builder.append(".");

		if (module.isIncluded()) {
			builder.append(" This module is an official module, included with NamelessMC. Please enable it.");
		} else {
			builder.append(" This module is a third-party module.");
			if (module.downloadLink() != null) {
				builder.append(" It can be downloaded here: ");
				builder.append(module.downloadLink());
			} else {
				builder.append(" It can be downloaded externally.");
			}
		}

		return builder.toString();
	}

}


text:
<?php

	/* Simple order form script
		Uses $_POST variables: email, name, date, suggestions
	**/
	$email = htmlspecialchars($_POST['email']);
	$phone = htmlspecialchars($_POST['phone']);
	$name = htmlspecialchars($_POST['name']);
	$company = htmlspecialchars($_POST['company']);

	/* You can edit the templates below to customize reservation emails. Remember to change $mail_address to your email address. */
	$mail_subject = "Someone has made a request through Motivationaal";
	$mail_content = "Inquiry Details!\r\n
			\r\nName: ".$name."
			\r\nEmail: ".$email."
			\r\nPhone: ".$phone."
			\r\nCompany: ".$company."
			";
	$mail_address = "gibbs.justin@gmail.com";   /*  Your email **/

	$mail_content = wordwrap($mail_content, 70, "\r\n");
	$headers = 'From: Motivationaal' . "\r\n" .
    'Reply-To: $email' . "\r\n" .'X-Mailer: PHP/'.phpversion();
	mail($mail_address, $mail_subject, $mail_content, $headers);
	$redirect_page = getcwd()."thank-you.html";
	header('Location:thank-you.html');
?>


text:
title: Primary
date: 2017-03-02 21:22:00 Z
tags:
- shopify
- e-commerce
- design
- homewares
- bedding
image: "/uploads/249-primarygoods@2x.jpg"
store-link: https://primarygoods.com
credit: Need/Want
credit-link: http://needwant.com
---


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Clouds</title>
    <link rel="stylesheet" href="../css/style.css">
    <script type="text/javascript" src="../../dist/paper-full.js"></script>
    <script type="text/paperscript" canvas="canvas">
        // Any newly created item will inherit the following styles:
        project.currentStyle = {
            strokeColor: 'black',
            strokeWidth: 5,
            strokeJoin: 'round',
            strokeCap: 'round'
        };

        // The user has to drag the mouse at least 30pt before the mouse drag
        // event is fired:
        tool.minDistance = 30;

        var path;
        function onMouseDown(event) {
            path = new Path();
            path.add(event.point);
        }

        function onMouseDrag(event) {
            path.arcTo(event.point, true);
        }
    </script>
</head>
<body>
    <canvas id="canvas" resize></canvas>
</body>
</html>


text:
body {
  font-family: 'Lora', 'Times New Roman', serif;
  font-size: 20px;
  color: #404040;
}
p {
  line-height: 1.5;
  margin: 30px 0;
}
p a {
  text-decoration: underline;
}
p a.btn {
  text-decoration: none;
}
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 800;
}
a {
  color: #404040;
}
a:hover,
a:focus {
  color: #0085a1;
}
a img:hover,
a img:focus {
  cursor: zoom-in;
}
blockquote {
  color: #808080;
  font-style: italic;
}
hr.small {
  max-width: 100px;
  margin: 15px auto;
  border-width: 4px;
  border-color: white;
}
.alert {
  border-radius: 0;
}
.fa-inifity:before {
  content: "\x221E";
}
.navbar-custom {
  background: white;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 3;
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.navbar-custom .navbar-brand {
  font-weight: 800;
}
.navbar-custom .nav li a {
  text-transform: uppercase;
  font-size: 12px;
  font-weight: 800;
  letter-spacing: 1px;
}
@media only screen and (min-width: 768px) {
  .navbar-custom {
    background: transparent;
    border-bottom: 1px solid transparent;
  }
  .navbar-custom .navbar-brand {
    color: white;
    padding: 20px;
  }
  .navbar-custom .navbar-brand:hover,
  .navbar-custom .navbar-brand:focus {
    color: rgba(255, 255, 255, 0.8);
  }
  .navbar-custom .nav li a {
    color: white;
    padding: 20px;
  }
  .navbar-custom .nav li a:hover,
  .navbar-custom .nav li a:focus {
    color: rgba(255, 255, 255, 0.8);
  }
}
@media only screen and (min-width: 1170px) {
  .navbar-custom {
    -webkit-transition: background-color 0.3s;
    -moz-transition: background-color 0.3s;
    transition: background-color 0.3s;
    /* Force Hardware Acceleration in WebKit */
    -webkit-transform: translate3d(0, 0, 0);
    -moz-transform: translate3d(0, 0, 0);
    -ms-transform: translate3d(0, 0, 0);
    -o-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
  }
  .navbar-custom.is-fixed {
    /* when the user scrolls down, we hide the header right above the viewport */
    position: fixed;
    top: -61px;
    background-color: rgba(255, 255, 255, 0.9);
    border-bottom: 1px solid #f2f2f2;
    -webkit-transition: -webkit-transform 0.3s;
    -moz-transition: -moz-transform 0.3s;
    transition: transform 0.3s;
  }
  .navbar-custom.is-fixed .navbar-brand {
    color: #404040;
  }
  .navbar-custom.is-fixed .navbar-brand:hover,
  .navbar-custom.is-fixed .navbar-brand:focus {
    color: #0085a1;
  }
  .navbar-custom.is-fixed .nav li a {
    color: #404040;
  }
  .navbar-custom.is-fixed .nav li a:hover,
  .navbar-custom.is-fixed .nav li a:focus {
    color: #0085a1;
  }
  .navbar-custom.is-visible {
    /* if the user changes the scrolling direction, we show the header */
    -webkit-transform: translate3d(0, 100%, 0);
    -moz-transform: translate3d(0, 100%, 0);
    -ms-transform: translate3d(0, 100%, 0);
    -o-transform: translate3d(0, 100%, 0);
    transform: translate3d(0, 100%, 0);
  }
}
.intro-header {
  background: no-repeat center center;
  background-color: #808080;
  background-attachment: scroll;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  margin-bottom: 50px;
}
.intro-header.no-margin {
  margin: 0;
}
.intro-header .site-heading,
.intro-header .post-heading,
.intro-header .page-heading {
  padding: 100px 0 50px;
  color: white;
}
@media only screen and (min-width: 768px) {
  .intro-header .site-heading,
  .intro-header .post-heading,
  .intro-header .page-heading {
    padding: 150px 0;
  }
}
.intro-header .site-heading,
.intro-header .page-heading {
  text-align: center;
}
.intro-header .site-heading h1,
.intro-header .page-heading h1 {
  margin-top: 0;
  font-size: 50px;
}
.intro-header .site-heading .subheading,
.intro-header .page-heading .subheading {
  font-size: 24px;
  line-height: 1.1;
  display: block;
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 300;
  margin: 10px 0 0;
}
.intro-header .site-heading .subheading a,
.intro-header .page-heading .subheading a {
  color: white;
}
@media only screen and (min-width: 768px) {
  .intro-header .site-heading h1,
  .intro-header .page-heading h1 {
    font-size: 80px;
  }
}
.intro-header .post-heading h1 {
  font-size: 35px;
}
.intro-header .post-heading .subheading,
.intro-header .post-heading .meta {
  line-height: 1.1;
  display: block;
}
.intro-header .post-heading .subheading {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 24px;
  margin: 10px 0 30px;
  font-weight: 600;
}
.intro-header .post-heading .subheading a {
  color: white;
}
.intro-header .post-heading .meta {
  font-family: 'Lora', 'Times New Roman', serif;
  font-style: italic;
  font-weight: 300;
  font-size: 20px;
}
.intro-header .post-heading .meta a {
  color: white;
}
@media only screen and (min-width: 768px) {
  .intro-header .post-heading h1 {
    font-size: 55px;
  }
  .intro-header .post-heading .subheading {
    font-size: 30px;
  }
}
.post-update {
  color: white;
  background-color: #0083a1;
  border-bottom: solid 1px #00667d;
  border-top: solid 1px #00667d;
  padding: 20px;
}
.post-update a,
.post-update a:hover {
  color: white;
  text-decoration: underline;
}
.talk {
  margin-bottom: 30px;
}
.talk p {
  margin: 10px 0;
}
#about .intro-header {
  margin-bottom: 0;
}
#about .alt-row {
  background-color: #f8f8f8;
  border-top: solid 1px #e7e7e7;
  border-bottom: solid 1px #f4f4f4;
}
#about .container.row {
  margin-right: auto;
  margin-left: auto;
  padding-top: 20px;
  padding-bottom: 20px;
}
#about .container.row .heading {
  margin-top: 20px;
}
#about .projects h3 {
  margin-top: 15px;
}
#about .projects .description {
  margin: 15px 0;
}
.control-buttons {
  margin-top: 20px;
}
@media (min-width: 768px) {
  #about .projects .description {
    min-height: 100px;
  }
}
.post-preview > a {
  color: #404040;
}
.post-preview > a:hover,
.post-preview > a:focus {
  text-decoration: none;
  color: #0085a1;
}
.post-preview > a > .post-title {
  font-size: 30px;
  margin-top: 30px;
  margin-bottom: 10px;
}
.post-preview > a > .post-subtitle {
  margin: 0;
  font-weight: 300;
  margin-bottom: 10px;
}
.post-preview > .post-meta {
  color: #808080;
  font-size: 18px;
  font-style: italic;
  margin-top: 0;
}
.post-preview > .post-meta > a {
  text-decoration: none;
  color: #404040;
}
.post-preview > .post-meta > a:hover,
.post-preview > .post-meta > a:focus {
  color: #0085a1;
  text-decoration: underline;
}
@media only screen and (min-width: 768px) {
  .post-preview > a > .post-title {
    font-size: 36px;
  }
}
.section-heading {
  font-size: 36px;
  margin-top: 60px;
  font-weight: 700;
}
.caption {
  text-align: center;
  font-size: 14px;
  padding: 10px;
  font-style: italic;
  margin: 0;
  display: block;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
}
footer {
  padding: 50px 0 65px;
}
footer .list-inline {
  margin: 0;
  padding: 0;
}
footer .copyright {
  font-size: 14px;
  text-align: center;
  margin-bottom: 0;
}
.floating-label-form-group {
  font-size: 14px;
  position: relative;
  margin-bottom: 0;
  padding-bottom: 0.5em;
  border-bottom: 1px solid #eeeeee;
}
.floating-label-form-group input,
.floating-label-form-group textarea {
  z-index: 1;
  position: relative;
  padding-right: 0;
  padding-left: 0;
  border: none;
  border-radius: 0;
  font-size: 1.5em;
  background: none;
  box-shadow: none !important;
  resize: none;
}
.floating-label-form-group label {
  display: block;
  z-index: 0;
  position: relative;
  top: 2em;
  margin: 0;
  font-size: 0.85em;
  line-height: 1.764705882em;
  vertical-align: middle;
  vertical-align: baseline;
  opacity: 0;
  -webkit-transition: top 0.3s ease,opacity 0.3s ease;
  -moz-transition: top 0.3s ease,opacity 0.3s ease;
  -ms-transition: top 0.3s ease,opacity 0.3s ease;
  transition: top 0.3s ease,opacity 0.3s ease;
}
.floating-label-form-group::not(:first-child) {
  padding-left: 14px;
  border-left: 1px solid #eeeeee;
}
.floating-label-form-group-with-value label {
  top: 0;
  opacity: 1;
}
.floating-label-form-group-with-focus label {
  color: #0085a1;
}
form .row:first-child .floating-label-form-group {
  border-top: 1px solid #eeeeee;
}
.btn {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 800;
  letter-spacing: 1px;
  border-radius: 0;
  padding: 15px 25px;
}
.btn-lg {
  font-size: 16px;
  padding: 25px 35px;
}
.btn-xs {
  font-size: 12px;
  padding: 8px 10px;
  font-weight: 600;
}
.btn-default:hover,
.btn-default:focus {
  background-color: #0085a1;
  border: 1px solid #0085a1;
  color: white;
}
.pager {
  margin: 20px 0 0;
}
.pager li > a,
.pager li > span {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 800;
  letter-spacing: 1px;
  padding: 10px 5px;
  background-color: white;
  border-radius: 0;
}
@media only screen and (min-width: 768px) {
  .pager li > a,
  .pager li > span {
    font-size: 14px;
    padding: 15px 25px;
  }
}
.pager li > a:hover,
.pager li > a:focus {
  color: white;
  background-color: #0085a1;
  border: 1px solid #0085a1;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
  color: #808080;
  background-color: #404040;
  cursor: not-allowed;
}
::-moz-selection {
  color: white;
  text-shadow: none;
  background: #0085a1;
}
::selection {
  color: white;
  text-shadow: none;
  background: #0085a1;
}
img::selection {
  color: white;
  background: transparent;
}
img::-moz-selection {
  color: white;
  background: transparent;
}
body {
  webkit-tap-highlight-color: #0085a1;
}
@font-face {
  font-family: 'MatthewOsborn';
  src: url('/fonts/matthew-osborn-regular.eot?v=1.0.0');
  src: url('/fonts/matthew-osborn-regular.eot?#iefix&v=1.0.0') format('embedded-opentype'), url('/fonts/matthew-osborn-regular.woff2?v=1.0.0') format('woff2'), url('/fonts/matthew-osborn-regular.woff?v=1.0.0') format('woff');
  font-weight: normal;
  font-style: normal;
}
.fa-500px:before {
  font-family: MatthewOsborn;
  content: "\f084";
}
.fa-kettlebell:before {
  font-family: MatthewOsborn;
  content: "\f085";
}
.fa-ux:before {
  font-family: MatthewOsborn;
  content: "\f086";
}
.gist .table > tbody > tr > td {
  border-top: none;
  padding-top: 0;
  padding-bottom: 0;
}
dd {
  margin-bottom: 20px;
}
dt a {
  text-decoration: underline;
}