text:
#include <proxygen/lib/http/HTTPConstants.h>

namespace proxygen {

#define CONNECTION_CLOSE_REASON_STRING(e, r) r,
const char* connectionCloseStrings[] = {
  CONNECTION_CLOSE_REASON_GEN(CONNECTION_CLOSE_REASON_STRING)
};
#undef CONNECTION_CLOSE_REASON_STRING

const char* getConnectionCloseReasonStringByIndex(unsigned int index) {
  if (index >= (unsigned int)ConnectionCloseReason::kMAX_REASON) {
    index = (unsigned int)ConnectionCloseReason::kMAX_REASON - 1;
  }

  return connectionCloseStrings[index];
}

const char* getConnectionCloseReasonString(ConnectionCloseReason r) {
  return connectionCloseStrings[(unsigned int)r];
}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Df\Payment\Comment;
use Magento\Config\Model\Config\CommentInterface as IComment;
# 2017-09-05
/** @final Unable to use the PHP «final» keyword here because of the M2 code generation. */
class Description extends \Df\Config\Comment {
	/**
	 * 2017-09-05
	 * @final Unable to use the PHP «final» keyword here because of the M2 code generation.
	 * «How to implement a dynamically generated comment for a backend configuration field?»
	 * https://mage2.pro/t/4076
	 * @override
	 * @see IComment::getCommentText()
	 * @used-by \Magento\Config\Model\Config\Structure\Element\Field::getComment():
	 *		public function getComment($currentValue = '') {
	 *			$comment = '';
	 *			if (isset($this->_data['comment']) && $this->_data['comment']) {
	 *				if (is_array($this->_data['comment'])) {
	 *					if (isset($this->_data['comment']['model'])) {
	 *						$model = $this->_commentFactory->create($this->_data['comment']['model']);
	 *						$comment = $model->getCommentText($currentValue);
	 *					}
	 *				}
	 *				else {
	 *					$comment = parent::getComment();
	 *				}
	 *			}
	 *			return $comment;
	 *		}
	 * https://github.com/magento/magento2/blob/2.2.0-RC1.8/app/code/Magento/Config/Model/Config/Structure/Element/Field.php#L106-L126
	 * @param string $v
	 */
	function getCommentText($v):string {
		$rules = $this->sibling('description_rules'); /** @var array(string => mixed)|null $rules */
		# 2019-09-27 $lengthS is empty for Dfe_ACH.
		$lengthS = ''; /** @var string $lengthS */
		# 2019-09-28 Variables are disabled for Dfe_ACH.
		$allowVariables = df_bool(dfa($rules, 'allowVariables', true)); /** @var bool $allowVariables */
		if ($maxLength = dfa($rules, 'maxLength')) { /** @var array(string => mixed)|null $maxLength */
			$title = $maxLength['title']; /** @var string $title */
			$url = $maxLength['url']; /** @var string $url */
			$v = dfa($maxLength, 'value'); /** @var int|null $v */
			$variablesS = !$allowVariables ? '' : ' (after the variables substitution)';
			$lengthS = $v
				? "
The full description length$variablesS should be not greater than $v characters (the description is automatically chopped to $v characters if it is longer).
"
				: "
The length is not limited.
"
			;
		}
		return df_cc_n(
			"
It is shown {$this->locations(dfa($rules, 'locations', []))}.
"
			,!$allowVariables ? '' : "
You can use some variables in the description.
"
			,$lengthS
		);
	}

	/**
	 * 2017-09-11
	 * @used-by self::locations()
	 * @param string $text
	 * @param array(string => string|bool) $o
	 */
	private function a($text, array $o):string {return df_tag_if($text, dfa($o, 'url'), 'a', [
		'target' => '_blank', 'title' => dfa($o, 'title'), 'href' => dfa($o, 'url')
	]);}

	/**
	 * 2017-09-11
	 * @used-by self::getCommentText()
	 * @param array(string => mixed) $l
	 */
	private function locations(array $l):string {
		$customer = dfa($l, 'customer', []); /** @var array(string => mixed)|null $customer */
		$merchant = dfa($l, 'merchant', []); /** @var array(string => mixed)|null $merchant */
		$payment = dfa($l, 'payment', []); /** @var array(string => mixed)|null $payment */
		$mTitle = dfpm_title(df_config_group($this->groupPath())->getData()['dfExtension']); /** @var string $mTitle */
		$m = !df_bool(dfa($merchant, 'shown')) ? '' :
			"to you {$this->a("in the $mTitle merchant interface", $merchant)} alongside the payment"
		; /** @var string $m */
		/** @var string $c */
		$c = !df_bool(dfa($customer, 'shown')) ? '' : $this->a("in the $mTitle customer account", $customer);
		/** @var string $p */
		$p = !df_bool(dfa($payment, 'shown')) ? '' :$this->a("on the $mTitle payment page", $payment);
		/** @var string $c */
		$cc = !($c || $p) ? '' : 'to customers' . ($c && $p ? ": $c and $p" : ' ' . ($c ?: $p));
		return df_ccc(' and ', $m, $cc);
	}
}


text:
layout: "docs_api"
version: "nightly"
versionHref: "/docs/nightly"
path: "api/directive/ionSideMenuContent/"

title: "ion-side-menu-content"
header_sub_title: "Directive in module ionic"
doc: "ionSideMenuContent"
docType: "directive"
---

    Improve this doc

  ion-side-menu-content

A container for the main visible content, sibling to one or more
ionSideMenu directives.

Usage

```html
<ion-side-menu-content
  drag-content="true">
</ion-side-menu-content>
```
For a complete side menu example, see the
ionSideMenus documentation.

API

      Attr
      Type
      Details

        drag-content

(optional)

  boolean

Whether the content can be dragged. Default true.


text:
v1.0.0 Initial stable release
v2.0.0 ES5 retargeting for easier browser compatibility.
       Removed isRoot.
v2.0.1 Updated dependencies to latest versions, incl. typescript to 2.1.5
       Arrays in model are now declared as ReadOnly.
v2.1.1 Fixed JsonSchema bug.
       Made values in TypedField nullable
       Added optional comment fields.
       Turned on strict null-checks for typescript.
       Removed test files from distribution npm


text:
<?php

class Google_Service_BigtableAdmin_CreateBackupMetadata extends Google_Model
{
  public $endTime;
  public $name;
  public $sourceTable;
  public $startTime;

  public function setEndTime($endTime)
  {
    $this->endTime = $endTime;
  }
  public function getEndTime()
  {
    return $this->endTime;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  public function setSourceTable($sourceTable)
  {
    $this->sourceTable = $sourceTable;
  }
  public function getSourceTable()
  {
    return $this->sourceTable;
  }
  public function setStartTime($startTime)
  {
    $this->startTime = $startTime;
  }
  public function getStartTime()
  {
    return $this->startTime;
  }
}


text:
import * as express from 'express';
import * as redis from 'redis';

const nameData = require('../data/name.list.json');

export function nameList(app: express.Application) {

  /**
   * Get name list.
   * @static
   */
  app.get('/api/name-list/static',
    (req: express.Request, res: express.Response,
     next: express.NextFunction) => {

      res.json(nameData);
    });

  /**
   * Get name list.
   * @database
   */
  app.get('/api/name-list',
    (req: express.Request, res: express.Response,
     next: express.NextFunction) => {

      const RedisClient = redis.createClient();

      let nameList: string[] = [];

      RedisClient.smembers('name-list',
        (err: any, replies: any) => {
          console.log(`
          Reply length: ${replies.length}.
          Reply: ${replies}.`);
          nameList = replies;
          res.json(nameList);
      });

      RedisClient.quit();
    });

  /**
   * Add new name.
   * @database
   */
  app.post('/api/name-list',
    (req: express.Request, res: express.Response,
     next: express.NextFunction) => {

      const RedisClient = redis.createClient(),
            request = req.body;
            // request = JSON.parse(req.body);

      RedisClient.sadd('name-list', request.name,
        (err: any, replies: any) => {
          console.log(`
          Reply: ${replies}.`);

          res.json({success: true});
        });

      RedisClient.quit();
    });

  /**
   * Delete name.
   * @database
   */
  app.delete('/api/name-list',
    (req: express.Request, res: express.Response,
     next: express.NextFunction) => {

      const RedisClient = redis.createClient(),
            request = req.body;
            // request = JSON.parse(req.body);

      RedisClient.srem('name-list', request.name,
        (err: any, replies: any) => {
          console.log(`
          Reply length: ${replies.length}.
          Reply: ${replies}.`);

          res.json({success: true});
        });

      RedisClient.quit();
    });

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FLib;

namespace SketchTypingBrowser
{
    public partial class Form1 : Form
    {
        const string host = "127.0.0.1";
        const int port = 8094;
        const string gesturePath = "../../../Resource/gestureBrows.txt";
        System.Diagnostics.Process server = null;
        SketchTypingClient client;
        Timer timer = new Timer();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (client == null) return;

            string text = client.ReadString();

            try
            {
                if (text != "" && !text.StartsWith("StartInput") && !text.StartsWith("TabPressed"))
                {
                    label1.Text = text;
                    SendKeys.SendWait(text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex + ":" + ex.StackTrace);
            }
            client.SendReceivedSignal();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            DisposeSketchTyping();
        }

        void CreateSketchTyping()
        {
            try
            {
                server = System.Diagnostics.Process.Start(System.IO.Path.GetFullPath(SketchTypingServer.serverPath), host + " " + port + " " + gesturePath);
                client = new SketchTypingClient(host, port);
                timer.Interval = 66;
                timer.Tick += new EventHandler(timer_Tick);
                timer.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex + ":" + ex.StackTrace);
            }
        }

        void DisposeSketchTyping()
        {
            timer.Stop();
            try
            {
                if (client != null)
                {
                    client.Dispose();
                    client = null;
                }
                if (server != null)
                {
                    server.Kill();
                    server = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex + ":" + ex.StackTrace);
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                CreateSketchTyping();
            }
            else
            {
                DisposeSketchTyping();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/background_light">

    <include

        android:id="@+id/common_actionbar"
        layout="@layout/include_action_bar" />

    <com.touchmenotapps.widget.radialmenu.progress.widget.RadialProgressWidget
        android:layout_below="@id/common_actionbar"
        android:id="@+id/radial_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp" />

</RelativeLayout>


text:
package com.arcgis.android.samples.localdata.localrasterdata;

import com.esri.core.renderer.RasterRenderer;

// Event listener of the OK button of a dialog.
public interface OnDialogDismissListener {
  public void onPositiveClicked(RasterRenderer renderer);
}


text:
package test.preserveorder;

import org.testng.annotations.Test;

public class C {

  @Test
  public void c1() {}

  @Test
  public void c2() {}

  @Test
  public void c3() {}
}


text:
[![Build Status](https://travis-ci.org/enb/enb-require-or-eval.svg)](https://travis-ci.org/enb/enb-require-or-eval)
[![Build status](https://ci.appveyor.com/api/projects/status/e70sj2xly3krnde4?svg=true)](https://ci.appveyor.com/project/SwinX/enb-require-or-eval)

Module, which assists in supporting transitional (from 'eval' to 'require') BEM formats.

Usage:

```js
var requireOrEval = require('enb-require-or-eval');

function someEvalingFunc() {
	return requireOrEval('path/to/bemjson.js').then(function (result) {
		//process result here
	}
}
```


text:
Pseudo GTID is the method of injecting unique entries into the binary logs, such that they can be used to
match/sync replicas without direct connection, or replicas whose master is corrupted/dead.

Pseudo-GTID is attractive to users not using GTID. Pseudo-GTID has most of GTID's benefits, but without making the commitment GTID requires. With Pseudo-GTID you can keep your existing topologies, whichever version of MySQL you're running.

### Advantages of Pseudo-GTID

- Enable master failovers.
- Enable intermediate master failovers.
- Arbitrary refactoring, relocating replicas from one place to another (even those replicas that don't have binary logging).
- Vendor neutral; works on both Oracle and MariaDB, even both combined.
- No configuration changes. Your replication setup remains as it is.
- No commitment. You can choose to move away from Pseudo-GTID at any time; just stop writing P-GTID entries.
- Pseudo-GTID implies crash-safe replication for replicas running with:
  - `log-slave-updates`
  - `sync_binlog=1`
- As opposed to GTID on MySQL `5.6`, servers don't _have to_ run with `log-slave-updates`, though `log-slave-updates` is recommended.

### Automated Pseudo-GTID injection

`orchestrator` can inject Pseudo-GTID entries for you. See [Automated Pseudo-GTID](configuration-discovery-pseudo-gtid.md#automated-pseudo-gtid-injection)

### Manual Pseudo-GTID injection

Automated Pseudo-GTID is a later addition which supersedes the need for manual Pseudo-GTID injection, and is recommended. However, you may still choose to inject your own Pseudo-GTID.

See [Manual Pseudo-GTID injection](pseudo-gtid-manual-injection.md)

### Limitations
- Active-Active master-master replication not supported
  - Active-passive master-master replication, where Pseudo-GTID is injected on the active master only, _is supported_.
- Replicas that don't run `log-slave-updates` are synced via relay logs. MySQL's default aggressive purging of relay logs implies that if a crash happens on a master, and a replica's relay logs have just been rotated (i.e. immediately also purged), then there's no Pseudo-GTID info in the relay logs to use for healing the topology
  - Frequent injections of P-GTID mitigate this problem. We inject P-GTID every `5sec`.
- When a replica reads Statement Based Replication relay logs and relays Row Based Replication binary logs (i.e. master has `binlog_format=STATEMENT` and replica has `binlog_format=ROW`), then `orchestrator` matches Pseudo-GTID via relay logs. See the above bullet for limitations on relay logs.
- You cannot match two servers where one is fully RBR (receives and writes Row Based Replication logs) and the other is fully SBR. Such scenario can happen when migrating from SBR based topology to RBR topology.
- An edge case scenario is known when replicating from `5.6` to `5.7`: `5.7` adds `ANONYMOUS` statements to the binary logs, which `orchestrator` knows how to skip. However if `5.6`->`5.7` replication breaks (e.g. dead master) and an `ANONYMOUS` statement is the last statement in the binary log, `orchestrator` is unable at this time to align the servers.

### Deploying Pseudo-GTID

Please follow [deployment, Pseudo-GTID](deployment.md#pseudo-gtid).

#### Using Pseudo GTID

Via web:

![Orchestrator pseudo GTID demo](images/orchestrator-pseudo-gtid-relocate-demo.gif)

Via command line:

```
orchestrator-client -c relocate -i some.server.to.relocate -d under.some.other.server
```

The `relocate` command will auto-identify that Pseudo-GTID is enabled.


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('openstack_tenant', '0022_floatingip_internal_ip'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='instance',
            name='external_ip',
        ),
    ]


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Defines a Tts interface.
 * All TTS engines in ChromeVox conform to the this interface.
 */
import {QueueMode, TtsSpeechProperties} from './tts_types.js';

/**
 * An interface for clients who want to get notified when an utterance
 * starts or ends from any source.
 * @interface
 */
export class TtsCapturingEventListener {
  /** Called when any utterance starts. */
  onTtsStart() {}

  /** Called when any utterance ends. */
  onTtsEnd() {}

  /** Called when any utterance gets interrupted. */
  onTtsInterrupted() {}
}

/** @interface */
export class TtsInterface {
  /**
   * Speaks the given string using the specified queueMode and properties.
   * @param {string} textString The string of text to be spoken.
   * @param {QueueMode} queueMode The queue mode to use for speaking.
   * @param {TtsSpeechProperties=} properties Speech properties to use for this
   *     utterance.
   * @return {TtsInterface} A tts object useful for chaining speak calls.
   */
  speak(textString, queueMode, properties) {}

  /**
   * Returns true if the TTS is currently speaking.
   * @return {boolean} True if the TTS is speaking.
   */
  isSpeaking() {}

  /**
   * Stops speech.
   */
  stop() {}

  /**
   * Adds a listener to get called whenever any utterance starts or ends.
   * @param {TtsCapturingEventListener} listener Listener to get called.
   */
  addCapturingEventListener(listener) {}

  /**
   * Removes a listener to get called whenever any utterance starts or ends.
   * @param {TtsCapturingEventListener} listener Listener to get called.
   */
  removeCapturingEventListener(listener) {}

  /**
   * Increases a TTS speech property.
   * @param {string} propertyName The name of the property to change.
   * @param {boolean} increase If true, increases the property value by one
   *     step size, otherwise decreases.
   */
  increaseOrDecreaseProperty(propertyName, increase) {}

  /**
   * Converts an engine property value to a percentage from 0.00 to 1.00.
   * @param {string} property The property to convert.
   * @return {?number} The percentage of the property.
   */
  propertyToPercentage(property) {}

  /**
   * Returns the default properties of the first tts that has default
   * properties.
   * @param {string} property Name of property.
   * @return {?number} The default value.
   */
  getDefaultProperty(property) {}

  /**
   * Toggles on or off speech.
   * @return {boolean} Whether speech is now on or off.
   */
  toggleSpeechOnOrOff() {}

  /**
   * Sets the rate, pitch, and volume TTS Settings to their defaults.
   */
  resetTextToSpeechSettings() {}
}


text:
class UserAssetsSettings : public DAVA::SettingsNode
{
public:
    DAVA::Color selectionRectColor = DAVA::Color(0.8f, 0.8f, 0.8f, 0.9f);
    DAVA::Color highlightColor = DAVA::Color(0.26f, 0.75f, 1.0f, 0.9f);
    DAVA::Color hudRectColor = DAVA::Color(0.8f, 0.8f, 0.8f, 0.9f);
    DAVA::String cornerRectPath2 = DAVA::String("~res:/QuickEd/UI/HUDControls/CornerRect.png");
    DAVA::String borderRectPath2 = DAVA::String("~res:/QuickEd/UI/HUDControls/BorderRect.png");
    DAVA::String pivotPointPath2 = DAVA::String("~res:/QuickEd/UI/HUDControls/Pivot.png");
    DAVA::String rotatePath2 = DAVA::String("~res:/QuickEd/UI/HUDControls/Rotate.png");
    DAVA::String magnetLinePath2 = DAVA::String("~res:/QuickEd/UI/HUDControls/MagnetLine/dotline.png");
    DAVA::String magnetRectPath2 = DAVA::String("~res:/QuickEd/UI/HUDControls/MagnetLine/MagnetLine.png");
    DAVA::Color guidesColor = DAVA::Color(1.0f, 0.0f, 0.0f, 1.0f);
    DAVA::Color previewGuideColor = DAVA::Color(1.0f, 0.0f, 0.0f, 0.5f);

    DAVA_VIRTUAL_REFLECTION(UserAssetsSettings, DAVA::SettingsNode);
};


text:
<?php

namespace Intervention\Gif\Encoder;

use Intervention\Gif\ApplicationExtension;

class ApplicationExtensionEncoder extends AbstractEncoder
{
    /**
     * Create new decoder instance
     *
     * @param ApplicationExtension $source
     */
    public function __construct(ApplicationExtension $source)
    {
        $this->source = $source;
    }

    /**
     * Encode current source
     *
     * @return string
     */
    public function encode(): string
    {
        return implode('', [
            ApplicationExtension::MARKER,
            ApplicationExtension::LABEL,
            pack('C', $this->source->getBlockSize()),
            $this->source->getApplication(),
            implode('', array_map(function ($block) {
                return $block->encode();
            }, $this->source->getBlocks())),
            ApplicationExtension::TERMINATOR,
        ]);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('lotes', '0061_op_sync'),
    ]

    operations = [
        migrations.AddField(
            model_name='op',
            name='sync_id',
            field=models.IntegerField(default=-1),
        ),
    ]


text:
"""Admin settings"""
from django.conf import settings
from django.contrib import admin

from social.utils import setting_name
from social.apps.django_app.default.models import UserSocialAuth, Nonce, \
                                                  Association

class UserSocialAuthOption(admin.ModelAdmin):
    """Social Auth user options"""
    list_display = ('id', 'user', 'provider', 'uid')
    list_filter = ('provider',)
    raw_id_fields = ('user',)
    list_select_related = True

    def get_search_fields(self, request=None):
        search_fields = getattr(
            settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None
        )
        if search_fields is None:
            _User = UserSocialAuth.user_model()
            username = getattr(_User, 'USERNAME_FIELD', None) or \
                       hasattr(_User, 'username') and 'username' or \
                       None
            fieldnames = ('first_name', 'last_name', 'email', username)
            all_names = _User._meta.get_all_field_names()
            search_fields = [name for name in fieldnames
                                if name and name in all_names]
        return ['user_' + name for name in search_fields]

class NonceOption(admin.ModelAdmin):
    """Nonce options"""
    list_display = ('id', 'server_url', 'timestamp', 'salt')
    search_fields = ('server_url',)

class AssociationOption(admin.ModelAdmin):
    """Association options"""
    list_display = ('id', 'server_url', 'assoc_type')
    list_filter = ('assoc_type',)
    search_fields = ('server_url',)

admin.site.register(UserSocialAuth, UserSocialAuthOption)
admin.site.register(Nonce, NonceOption)
admin.site.register(Association, AssociationOption)


text:
alias cb='curl -o bootstrap.sh https://raw.githubusercontent.com/realulim/Bornemisza/master/salt/bootstrap.sh'
alias cbapp='curl -o bootstrap-bornemisza.sh https://raw.githubusercontent.com/realulim/Bornemisza/master/salt/app/bootstrap-bornemisza.sh'
alias cbdb='curl -o bootstrap-bornemisza.sh https://raw.githubusercontent.com/realulim/Bornemisza/master/salt/db/bootstrap-bornemisza.sh'
alias e='nano -w'
alias ebr='nano -w /etc/profile.d/bash.sh'
alias h='history'
alias haproxy-configcheck='haproxy -c -V -f /etc/haproxy/haproxy.cfg'
alias ipdown='ip link set dummy1 down'
alias ipup='ip link set dummy1 up'
alias l='ls -lah'
alias lt='l -rt'
alias p-='systemctl stop payara'
alias p+='systemctl start payara'
alias rm='rm -i'
alias sbr='source /etc/profile.d/bash.sh'
alias sch='salt-call -l info state.highstate'
alias showhaproxyerrors='echo "show errors" | nc -U /var/lib/haproxy/stats'
alias x='exit'

PS1="\u@\H:\w => ";


text:
'use strict';

/**
 *  This file contains the variables used in other gulp files
 *  which defines tasks
 *  By design, we only put there very generic config values
 *  which are used in several places to keep good readability
 *  of the tasks
 */

var gutil = require('gulp-util');

/**
 * The name of your angular module for templateCache
 */

exports.moduleName = 'movieApp';

/**
 *  The main paths of your project handle these with care
 */
exports.paths = {
    client: 'src/client',
    app: 'src/client/app',
    server: 'src/server',
    src: 'src',
    dist: 'dist',
    tmp: '.tmp',
    e2e: 'e2e',
    openBrowserWindow: false
};

/**
 *  Wiredep is the lib which inject bower dependencies in your project
 *  Mainly used to inject script tags in the index.html but also used
 *  to inject css preprocessor deps and js files in karma
 */
exports.wiredep = {
    directory: 'src/client/bower_components',
    exclude: ['bower_components/isotope/js/layout-modes',
        'bower_components/angular-isotope',
        'bower_components/isotope/js/layout-mode.js',
        'bower_components/outlayer',
        'bower_components/masonry',
        'bower_components/fizzy-ui-utils',
        'bower_components/isotope/js/item.js',
        'bower_components/ev-emitter/',
        'bower_components/eventie',
        'bower_components/desandro-matches-selector',
        'bower_components/get-size',
        'bower_components/get-style-property',
        'bower_components/doc-ready'
    ]
};

/**
 *  Common implementation for an error handler of a Gulp plugin
 */
exports.errorHandler = function (title) {
    return function (err) {
        gutil.log(gutil.colors.red('[' + title + ']'), err.toString());
        this.emit('end');
    };
};


text:
#ifndef __MISAGENT_H
#define __MISAGENT_H

#include "libimobiledevice/misagent.h"
#include "property_list_service.h"

struct misagent_client_private {
	property_list_service_client_t parent;
	int last_error;
};

#endif


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

namespace SharedHardware.Models
{
    public class AccountConfirmationCode
    {
        public Guid Id { get; set; }
        public string Code { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public DateTime ExpirationDate { get; set; }
    }
}


text:
#pragma once
#include <aws/scheduler/Scheduler_EXPORTS.h>
#include <aws/scheduler/SchedulerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace Scheduler
{
namespace Model
{

  /**
   */
  class AWS_SCHEDULER_API ListScheduleGroupsRequest : public SchedulerRequest
  {
  public:
    ListScheduleGroupsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListScheduleGroups"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     *
If specified, limits the number of results returned by this operation. The
     * operation also returns a NextToken which you can use in a
     * subsequent operation to retrieve the next set of results.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
If specified, limits the number of results returned by this operation. The
     * operation also returns a NextToken which you can use in a
     * subsequent operation to retrieve the next set of results.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
If specified, limits the number of results returned by this operation. The
     * operation also returns a NextToken which you can use in a
     * subsequent operation to retrieve the next set of results.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
If specified, limits the number of results returned by this operation. The
     * operation also returns a NextToken which you can use in a
     * subsequent operation to retrieve the next set of results.

     */
    inline ListScheduleGroupsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline const Aws::String& GetNamePrefix() const{ return m_namePrefix; }

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline bool NamePrefixHasBeenSet() const { return m_namePrefixHasBeenSet; }

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline void SetNamePrefix(const Aws::String& value) { m_namePrefixHasBeenSet = true; m_namePrefix = value; }

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline void SetNamePrefix(Aws::String&& value) { m_namePrefixHasBeenSet = true; m_namePrefix = std::move(value); }

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline void SetNamePrefix(const char* value) { m_namePrefixHasBeenSet = true; m_namePrefix.assign(value); }

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline ListScheduleGroupsRequest& WithNamePrefix(const Aws::String& value) { SetNamePrefix(value); return *this;}

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline ListScheduleGroupsRequest& WithNamePrefix(Aws::String&& value) { SetNamePrefix(std::move(value)); return *this;}

    /**
     *
The name prefix that you can use to return a filtered list of your schedule
     * groups.

     */
    inline ListScheduleGroupsRequest& WithNamePrefix(const char* value) { SetNamePrefix(value); return *this;}

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline ListScheduleGroupsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline ListScheduleGroupsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token returned by a previous call to retrieve the next set of
     * results.

     */
    inline ListScheduleGroupsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;

    Aws::String m_namePrefix;
    bool m_namePrefixHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace Scheduler
} // namespace Aws


text:
package es.cesga.hadoop.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;

/**
 * A Ip.
 */
@Entity
@Table(name = "IP")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Ip implements Serializable {

 	private static final long serialVersionUID = 1L;

	@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @Pattern(regexp = "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}.\\d{1,3}$")
    @Column(name = "address")
    private String address;

    @NotNull
    @Column(name = "mask")
    private Integer mask;

    @NotNull
    @Column(name = "enabled")
    private Boolean enabled;

    @JsonIgnore
    @Column(name = "username")
    private String username;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAddress() {
    	if(this.mask != null){
	    	if(this.mask == 0){
	    		return "0.0.0.0";
	    	}else if(this.mask == 32){
	    		return address;
	    	}else if(this.mask > 0 && this.mask < 32){
	        	 String ipAddr=this.address;
	        	 int cidrMask = this.mask;
	        	 long bits = 0;
	        	 bits = 0xffffffff ^ (1 << 32 - cidrMask) - 1;
	        	 String maskString = String.format("%d.%d.%d.%d", (bits & 0x0000000000ff000000L) >> 24, (bits & 0x0000000000ff0000) >> 16, (bits & 0x0000000000ff00) >> 8, bits & 0xff);
	        	 String networkAddr="";
	        	 String[] ipAddrParts=ipAddr.split("\\.");
	        	 String[] maskParts=maskString.split("\\.");
	        	 for(int i=0;i<4;i++){
		        	 int x=Integer.parseInt(ipAddrParts[i]);
		        	 int y=Integer.parseInt(maskParts[i]);
		        	 int z=x&y;
		        	 networkAddr+=z+".";
	        	 }
	        	//Remove last dot
	        	networkAddr = networkAddr.substring(0, networkAddr.length() - 1);
	        	return networkAddr;
	    	}else{
	    		return "0.0.0.0";
	    	}
        }else{
        	return address;
        }
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getMask() {
        return mask;
    }

    public void setMask(Integer mask) {
        this.mask = mask;
    }

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

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

        Ip ip = (Ip) o;

        if ( ! Objects.equals(id, ip.id)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }

    @Override
    public String toString() {
        return "Ip{" +
                "id=" + id +
                ", address='" + address + "'" +
                ", mask='" + mask + "'" +
                ", enabled='" + enabled + "'" +
                ", username='" + username + "'" +
                '}';
    }
}


text:
layout: page
title: Fire Media Executive Retreat
date: 2016-05-24
author: Jerry Cross
tags: weekly links, java
status: published
summary: Pellentesque gravida malesuada eros, ac porta ante.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 05/19/2019
  endDate: 05/22/2019
  ctyhocn: CRPPTHX
  groupCode: FMER
published: true
---
Fusce augue arcu, sagittis vitae lacinia vel, ullamcorper dapibus risus. Ut sodales placerat magna, et elementum tellus rhoncus eleifend. Maecenas id accumsan tellus, ac molestie ligula. Praesent finibus quam ut felis imperdiet dignissim. Mauris ut arcu dolor. Nulla a suscipit odio. Nulla pulvinar, diam a feugiat convallis, velit eros accumsan tellus, eget ultricies justo turpis vitae nunc.

1 Phasellus scelerisque massa sit amet eleifend faucibus
1 Nulla luctus turpis sed accumsan aliquam.

Integer faucibus venenatis finibus. Nam euismod lacus ut nisi lobortis, et venenatis nunc sollicitudin. Morbi consequat cursus leo, id faucibus diam aliquam vel. In placerat malesuada mi, id interdum ex laoreet ut. Integer ornare convallis erat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean ut tristique magna. Curabitur blandit tortor lorem, sagittis maximus dui sollicitudin eu. Nullam nisl elit, faucibus eu odio in, euismod ornare mi. Proin lorem dui, cursus ut turpis ac, consectetur ultrices diam.


text:
from contextlib import contextmanager
from datetime import datetime
import gzip
from hashlib import sha512
from itertools import zip_longest
import json
import os
import shutil
import struct
import sys
import tempfile
import zlib

from zoneinfo import ZoneInfo

from ichnaea.conf import settings
from ichnaea.exceptions import GZIPDecodeError

HERE = os.path.dirname(__file__)
APP_ROOT = os.path.dirname(HERE)
UTC = ZoneInfo("UTC")

@contextmanager
def gzip_open(filename, mode, compresslevel=6):
    """Open a gzip file.

    :param mode: Either `r` or `w` for read or write access.
    """
    with open(filename, mode + "b") as fd:
        with gzip.open(
            fd, mode=mode + "t", compresslevel=compresslevel, encoding="utf-8"
        ) as gzip_file:
            yield gzip_file

def encode_gzip(data, compresslevel=6):
    """Encode the passed in data with gzip."""
    return gzip.compress(data, compresslevel=compresslevel)

def decode_gzip(data):
    """Return the gzip-decompressed bytes.

    :raises: :exc:`~ichnaea.exceptions.GZIPDecodeError`
    """
    try:
        return gzip.decompress(data)
    except (IOError, OSError, EOFError, struct.error, zlib.error) as exc:
        raise GZIPDecodeError(repr(exc))

@contextmanager
def selfdestruct_tempdir():
    base_path = tempfile.mkdtemp()
    try:
        yield base_path
    finally:
        shutil.rmtree(base_path)

def utcnow():
    """Return the current time in UTC with a UTC timezone set."""
    return datetime.utcnow().replace(microsecond=0, tzinfo=UTC)

def version_info():
    """Return version.json information."""
    version_file = os.path.join(APP_ROOT, "version.json")
    info = {}
    if os.path.exists(version_file):
        with open(version_file, "r") as fp:
            try:
                info = json.load(fp)
            except json.JsonDecodeException:
                pass
    return info

def contribute_info():
    """Return contribute.json information."""
    contribute_file = os.path.join(APP_ROOT, "contribute.json")
    if os.path.exists(contribute_file):
        with open(contribute_file, "r") as fp:
            try:
                return json.load(fp)
            except json.JsonDecodeException:
                pass
    return {}

def print_table(table, delimiter=" | ", stream_write=sys.stdout.write):
    """Takes a list of lists and prints a table to stdout.

    :arg list-of-lists table: the table to print out
    :arg str delimiter: the delimiter between fields in a row
    :arg writer stream_write: the ``write`` of a file-like object

    """
    # Find the max size value for each column
    col_maxes = [0] * len(table[0])
    for row in table:
        col_maxes = [
            max(len(str(field)), col_max)
            for field, col_max in zip_longest(row, col_maxes, fillvalue=0)
        ]

    for row in table:
        stream_write(
            delimiter.join(
                [
                    str(field).ljust(col_max)
                    for field, col_max in zip_longest(row, col_maxes, fillvalue="")
                ]
            )
            + "\n"
        )

def generate_signature(reason, *parts):
    """
    Generate a salted signature for a set of strings.

    :arg reason A short "why" string used to salt the hash
    :arg parts A list of strings to add to the signature
    """
    siggen = sha512()
    for part in parts:
        if part:
            siggen.update(part.encode())
    siggen.update(reason.encode())
    siggen.update(settings("secret_key").encode())
    return siggen.hexdigest()


text:
package org.kavaproject.kavatouch.foundation;

import org.kavaproject.kavatouch.util.NotImplementedException;

import java.util.List;

public class DefaultOperationQueue implements OperationQueue {
    private final OperationQueueFactory mOperationQueueFactory;

    protected DefaultOperationQueue(OperationQueueFactory operationQueueFactory) {
        mOperationQueueFactory = operationQueueFactory;
    }

    @Override
    public void addOperation(Operation operation) {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void addOperations(List<Operation> operations, boolean wait) {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void addOperation(Runnable block) {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public List operations() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public int operationCount() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void cancelAllOperations() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void waitUntilAllOperationsAreFinished() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public int maxConcurrentOperationCount() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void setMaxConcurrentOperationCount(int count) {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public boolean isSuspended() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void setSuspended(boolean suspend) {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public void setName(String newName) {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public String name() {
        throw new NotImplementedException(); //TODO
    }

    @Override
    public OperationQueueFactory getFactory() {
        return mOperationQueueFactory;
    }
}


text:
<?php declare(strict_types = 1);

namespace Smalldb\StateMachine\ClassGenerator;

class GeneratedClassAutoloader
{
	private string $namespace;
	private string $directory;
	private int $namespaceLen;
	private bool $prependAutoloader;

	public function __construct(string $namespace, string $directory, bool $prependAutoloader = false)
	{
		$this->namespace = $namespace[-1] === '\\' ? $namespace : $namespace . "\\";
		$this->namespaceLen = strlen($this->namespace);
		$this->directory = $directory[-1] === DIRECTORY_SEPARATOR ? $directory : $directory . DIRECTORY_SEPARATOR;
		$this->prependAutoloader = $prependAutoloader;
	}

	public function registerLoader()
	{
		spl_autoload_register(function($class) {
			if (strncmp($class, $this->namespace, $this->namespaceLen) === 0) {
				require $this->directory . substr($class, $this->namespaceLen) . '.php';
			}
		}, true, $this->prependAutoloader);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">VolumeRender</string>
</resources>


text:
using System;
using System.Data;
using System.Data.Common;
using System.Linq;
using BenchmarkDotNet.Attributes;
using LinqToDB.Benchmarks.Mappings;
using LinqToDB.Benchmarks.TestProvider;
using LinqToDB.Data;
using LinqToDB.DataProvider.PostgreSQL;

namespace LinqToDB.Benchmarks.Queries
{
	public class UpdateBenchmark
	{
		private const int      _iterations = 2;
		private DataConnection _db     = null!;
		private DbConnection   _cn     = null!;
		private Func<DataConnection, Workflow, int> _compiledLinqSet    = null!;
		private Func<DataConnection, Workflow, int> _compiledLinqObject = null!;

		private readonly Workflow _record = new ()
		{
			Id            = 1,
			RowVersion    = 2,
			Status        = StatusEnum.One,
			Result        = $"Result:{3}",
			Error         = $"Error:{4}",
			Steps         = $"Steps:{5}",
			StartTime     = DateTimeOffset.Now,
			UpdateTime    = DateTimeOffset.Now,
			ProcessedTime = DateTimeOffset.Now,
			CompleteTime  = DateTimeOffset.Now
		};

		[GlobalSetup]
		public void Setup()
		{
			_cn = new MockDbConnection(new QueryResult() { Return = 1 }, ConnectionState.Open);
			_db = new DataConnection(PostgreSQLTools.GetDataProvider(PostgreSQLVersion.v95), _cn);

			_compiledLinqSet = CompiledQuery.Compile<DataConnection, Workflow, int>(
				(db, record) => db.GetTable<Workflow>()
					.Where(x => x.Id == record.Id && x.RowVersion == record.RowVersion)
					.Set(x => x.Status, record.Status)
					.Set(x => x.Result, record.Result)
					.Set(x => x.Error, record.Error)
					.Set(x => x.Steps, record.Steps)
					.Set(x => x.UpdateTime, record.UpdateTime)
					.Set(x => x.RowVersion, x => x.RowVersion + 1)
					.Set(x => x.StartTime, record.StartTime)
					.Set(x => x.ProcessedTime, record.ProcessedTime)
					.Set(x => x.CompleteTime, record.CompleteTime)
					.Update());
			_compiledLinqObject = CompiledQuery.Compile<DataConnection, Workflow, int>(
				(db, record) => db.GetTable<Workflow>()
					.Where(x => x.Id == _record.Id && x.RowVersion == _record.RowVersion)
					.Update(x => new()
					{
						Status        = record.Status,
						Result        = record.Result,
						Error         = record.Error,
						Steps         = record.Steps,
						UpdateTime    = record.UpdateTime,
						RowVersion    = x.RowVersion + 1,
						StartTime     = record.StartTime,
						ProcessedTime = record.ProcessedTime,
						CompleteTime  = record.CompleteTime
					}));
		}

		[Benchmark]
		public int LinqSet()
		{
			int cnt = 0;

			for (var i = 0; i < _iterations; i++)
			{
				cnt = _db.GetTable<Workflow>()
					.Where(x => x.Id == _record.Id && x.RowVersion == _record.RowVersion)
					.Set(x => x.Status       , _record.Status)
					.Set(x => x.Result       , _record.Result)
					.Set(x => x.Error        , _record.Error)
					.Set(x => x.Steps        , _record.Steps)
					.Set(x => x.UpdateTime   , _record.UpdateTime)
					.Set(x => x.RowVersion   , x => x.RowVersion + 1)
					.Set(x => x.StartTime    , _record.StartTime)
					.Set(x => x.ProcessedTime, _record.ProcessedTime)
					.Set(x => x.CompleteTime , _record.CompleteTime)
					.Update();
			}

			return cnt;
		}

		[Benchmark]
		public int LinqObject()
		{
			int cnt = 0;

			for (var i = 0; i < _iterations; i++)
			{
				cnt = _db.GetTable<Workflow>()
					.Where(x => x.Id == _record.Id && x.RowVersion == _record.RowVersion)
					.Update(x => new()
					{
						Status        = _record.Status,
						Result        = _record.Result,
						Error         = _record.Error,
						Steps         = _record.Steps,
						UpdateTime    = _record.UpdateTime,
						RowVersion    = x.RowVersion + 1,
						StartTime     = _record.StartTime,
						ProcessedTime = _record.ProcessedTime,
						CompleteTime  = _record.CompleteTime
					});
			}

			return cnt;
		}

		// a bit different query: update by id only
		[Benchmark]
		public int Object()
		{
			int cnt = 0;

			for (var i = 0; i < _iterations; i++)
			{
				cnt = _db
					.Update(new Workflow()
					{
						Status        = _record.Status,
						Result        = _record.Result,
						Error         = _record.Error,
						Steps         = _record.Steps,
						UpdateTime    = _record.UpdateTime,
						RowVersion    = _record.RowVersion + 1,
						StartTime     = _record.StartTime,
						ProcessedTime = _record.ProcessedTime,
						CompleteTime  = _record.CompleteTime
					});
			}

			return cnt;
		}

		[Benchmark]
		public int CompiledLinqSet()
		{
			int cnt = 0;

			for (var i = 0; i < _iterations; i++)
			{
				cnt = _compiledLinqSet(_db, _record);
			}

			return cnt;
		}

		[Benchmark]
		public int CompiledLinqObject()
		{
			int cnt = 0;

			for (var i = 0; i < _iterations; i++)
			{
				cnt = _compiledLinqObject(_db, _record);
			}

			return cnt;
		}

		[Benchmark(Baseline = true)]
		public int RawAdoNet()
		{
			int cnt = 0;

			using (var cmd = _cn.CreateCommand())
			{
				cmd.CommandText = $"UPDATE workflow w SET w.status = :status, w.result = :result, w.error = :error, w.steps = :steps, w.update_time = :update_time, w.row_version = :row_version + 1, w. start_time = :start_time, w.processed_time = :processed_time, w.complete_time = :complete_time WHERE w.id = :id AND w.row_version = :rowversion";

				cmd.Parameters.Add(new MockDbParameter(":status"        , _record.Status));
				cmd.Parameters.Add(new MockDbParameter(":result"        , _record.Result));
				cmd.Parameters.Add(new MockDbParameter(":error"         , _record.Error));
				cmd.Parameters.Add(new MockDbParameter(":steps"         , _record.Steps));
				cmd.Parameters.Add(new MockDbParameter(":update_time"   , _record.UpdateTime));
				cmd.Parameters.Add(new MockDbParameter(":row_version"   , _record.RowVersion));
				cmd.Parameters.Add(new MockDbParameter(":start_time"    , _record.StartTime));
				cmd.Parameters.Add(new MockDbParameter(":processed_time", _record.ProcessedTime));
				cmd.Parameters.Add(new MockDbParameter(":complete_time" , _record.CompleteTime));
				cmd.Parameters.Add(new MockDbParameter(":id"            , _record.Id));
				cnt = cmd.ExecuteNonQuery();
			}

			return cnt;
		}
	}
}


text:
<?php

namespace SpBar\Bundle\BlogBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

use Doctrine\Common\Collections\ArrayCollection;
use SpBar\Bundle\BlogBundle\Model\PostMetaManager;

class MetaTransformer implements DataTransformerInterface
{
    private $pm;

    public function __construct(PostMetaManager $pm)
    {
        $this->pm = $pm;
    }

    /**
    * Transforms an object (meta) to a array (source).
    */
    public function transform($metas)
    {
        if(count($metas)==0)
        {
            return;
        }

        $temp = array();
        foreach ($metas as $meta) {
            $temp[] = $meta->getSource();
        }
        return implode(',', $temp);
    }

    /**
     * Transforms a string (source) to an object (meta).
     */
    public function reverseTransform($source)
    {
        if (!$source) {
            return null;
        }
        $meta = new ArrayCollection();

        foreach (explode(',', $source) as $src) {

            $mt = $this->pm->getPostMetaBySource($src);

            if (null === $mt) {
                $mt = $this->pm->createPostMeta();
                $mt->setSource($src);
                $this->pm->updatePostMeta($mt, false);
            }

            $meta[] = $mt;
        }
        return $meta;
    }
}


text:
package main

import (
	"path/filepath"
	"reflect"
	"testing"

	"istio.io/istio/tests/util/checker"
	"istio.io/istio/tests/util/checker/testlinter/rules"
)

func getAbsPath(path string) string {
	if !filepath.IsAbs(path) {
		path, _ = filepath.Abs(path)
	}
	return path
}

func clearLintRulesList() {
	delete(LintRulesList, UnitTest)
	delete(LintRulesList, IntegTest)
	delete(LintRulesList, E2eTest)
}

func TestUnitTestSkipByIssueRule(t *testing.T) {
	clearLintRulesList()
	LintRulesList[UnitTest] = []checker.Rule{rules.NewSkipByIssue()}

	rpts, _ := getReport([]string{"testdata/"})
	expectedRpts := []string{getAbsPath("testdata/unit_test.go") +
		":9:2:Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue. (skip_issue)"}

	if !reflect.DeepEqual(rpts, expectedRpts) {
		t.Errorf("lint reports don't match\nReceived: %v\nExpected: %v", rpts, expectedRpts)
	}
}

func TestUnitTestNoShortRule(t *testing.T) {
	clearLintRulesList()
	LintRulesList[UnitTest] = []checker.Rule{rules.NewNoShort()}

	rpts, _ := getReport([]string{"testdata/"})
	expectedRpts := []string{getAbsPath("testdata/unit_test.go") + ":32:5:testing.Short() is disallowed. (no_short)"}

	if !reflect.DeepEqual(rpts, expectedRpts) {
		t.Errorf("lint reports don't match\nReceived: %v\nExpected: %v", rpts, expectedRpts)
	}
}

func TestUnitTestNoSleepRule(t *testing.T) {
	clearLintRulesList()
	LintRulesList[UnitTest] = []checker.Rule{rules.NewNoSleep()}

	rpts, _ := getReport([]string{"testdata/"})
	expectedRpts := []string{getAbsPath("testdata/unit_test.go") + ":49:2:time.Sleep() is disallowed. (no_sleep)"}

	if !reflect.DeepEqual(rpts, expectedRpts) {
		t.Errorf("lint reports don't match\nReceived: %v\nExpected: %v", rpts, expectedRpts)
	}
}

func TestUnitTestNoGoroutineRule(t *testing.T) {
	clearLintRulesList()
	LintRulesList[UnitTest] = []checker.Rule{rules.NewNoGoroutine()}

	rpts, _ := getReport([]string{"testdata/"})
	expectedRpts := []string{getAbsPath("testdata/unit_test.go") + ":57:2:goroutine is disallowed. (no_goroutine)"}

	if !reflect.DeepEqual(rpts, expectedRpts) {
		t.Errorf("lint reports don't match\nReceived: %v\nExpected: %v", rpts, expectedRpts)
	}
}

func TestUnitTestWhitelist(t *testing.T) {
	clearLintRulesList()
	LintRulesList[UnitTest] = []checker.Rule{rules.NewSkipByIssue(),
		rules.NewNoShort(),
		rules.NewNoSleep(),
		rules.NewNoGoroutine()}
	Whitelist = make(map[string][]string)
	Whitelist["testdata/unit_test.go"] = []string{"skip_by_issue_rule", "no_short_rule",
		"no_sleep_rule", "no_goroutine_rule"}

	rpts, _ := getReport([]string{"testdata/*"})
	expectedRpts := []string{}

	if (len(rpts) > 0 || len(expectedRpts) > 0) && !reflect.DeepEqual(rpts, expectedRpts) {
		t.Errorf("lint reports don't match\nReceived: %v\nExpected: %v", rpts, expectedRpts)
	}
}


text:
export comp1 from './comp1';
export customDefaultComponent from './customDefaultComponent';
export comp2 from './comp2';


text:
layout:     post
title:      I wanna meet the agent who sold Willem on doing this film.
date:       2014-06-11 15:31:19
summary:
categories: jekyll pixyll
---

Tweet


text:
package cn.wizzer.modules.controllers.platform.opo;

import cn.wizzer.common.base.Result;
import cn.wizzer.common.filter.PrivateFilter;
import cn.wizzer.common.page.DataTableColumn;
import cn.wizzer.common.page.DataTableOrder;
import cn.wizzer.modules.models.opo.Opo_order;
import cn.wizzer.modules.models.opo.Opo_use;
import cn.wizzer.modules.models.sys.Sys_user;
import cn.wizzer.modules.services.opo.OpoOrderService;
import cn.wizzer.modules.services.opo.OpoUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.dao.*;
import org.nutz.dao.Chain;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 业务管理
 * Created by liaojian on 2016/11/13.
 */

@IocBean
@At("/platform/opo/busiMng")
@Filters({@By(type = PrivateFilter.class)})
public class OpoBusiMng {
    @Inject
    private OpoOrderService opoOrderService;
    @Inject
    private OpoUserService opoUserService;

    @At("")
    @Ok("beetl:/platform/opo/opo_busi/busiMng.html")
    @RequiresAuthentication
    public void index(HttpServletRequest req) {
        Sys_user user = (Sys_user) SecurityUtils.getSubject().getPrincipal();
        String orderInfo = "";
        if(user!=null){
            Opo_order opoOrder = opoOrderService.fetch(Cnd.where("userID","=",user.getId()).and("state","<>",Opo_order.STATE_CLOSE));
            if(opoOrder == null){
                orderInfo = "no_order";
                req.setAttribute("opoOrder","no_order");
                req.setAttribute("opoUser","no_opoUser");
            }else{
                if(Opo_order.STATE_WAIT.equals(opoOrder.getState())){
                    orderInfo = "wait_match";
                }else if(Opo_order.STATE_SUCCESS.equals(opoOrder.getState())){
                    orderInfo = "match_success";
                }else if(Opo_order.STATE_REMITTANCE.equals(opoOrder.getState())){
                    orderInfo = "remittanced";
                }
                req.setAttribute("opoOrder",opoOrder);
                if(null != opoOrder.getMatchUserID() || "".equals(opoOrder.getMatchUserID())){
                    Opo_use opoUser = opoUserService.fetch(Cnd.where("uuid","=",opoOrder.getMatchUserID()));
                    opoUser.setUser(null);
                    opoUser.setSafe_password("");
                    opoUser.setSafe_question("");
                    opoUser.setSafe_solution("");
                    opoUser.setInviter("");
                    opoUser.setInviter_phone("");
                    opoUser.setScore(0);
                    opoUser.setDynamic_wallet(0);
                    req.setAttribute("opoUser", opoUser);
                }else{
                    req.setAttribute("opoUser","no_opoUser");
                }
            }
        }
        req.setAttribute("orderInfo",orderInfo);
    }

    @At
    @Ok("json:full")
    @RequiresAuthentication
    public Object orderList(@Param("length") int length,
                       @Param("start") int start,
                       @Param("draw") int draw,
                       @Param("::order") List<DataTableOrder> order,
                       @Param("::columns") List<DataTableColumn> columns) {
        Cnd cnd = Cnd.NEW();
        Sys_user sysUser = (Sys_user)SecurityUtils.getSubject().getPrincipal();
        if(sysUser!=null){
            return opoOrderService.data(length, start, draw, order, columns, cnd.where("userID","=",sysUser.getId()).and("state","=",Opo_order.STATE_CLOSE), null);
        }else {
            return null;
        }
    }

    @At
    @Ok("->:/platform/opo/busiMng")
    @RequiresAuthentication
    public Object addDo(@Param("..") Opo_order opoOrder, HttpServletRequest req) {
        try {
            Sys_user sysUser = (Sys_user)SecurityUtils.getSubject().getPrincipal();
            Opo_order orderInfo = opoOrderService.fetch(Cnd.where("userID","=",sysUser.getId()).and("state","=",Opo_order.STATE_SUCCESS));
            if("购买理财".equals(orderInfo.getOrd_flag())){
                opoOrderService.update(Chain.make("remittance_evidence",opoOrder.getRemittance_evidence()).add("remittance_time",opoOrder.getRemittance_time()).add("state",Opo_order.STATE_REMITTANCE),Cnd.where("userID","=",sysUser.getId()).and("matchUserID","=",opoOrder.getMatchUserID()).and("state","=",opoOrder.STATE_SUCCESS));
                opoOrderService.update(Chain.make("remittance_evidence",opoOrder.getRemittance_evidence()).add("remittance_time",opoOrder.getRemittance_time()),Cnd.where("userID","=",opoOrder.getMatchUserID()).and("matchUserID","=",sysUser.getId()).and("state","=",opoOrder.STATE_SUCCESS));
            }else if("投资理财".equals(orderInfo.getOrd_flag())){
                Opo_use opo_use = opoUserService.fetch(Cnd.where("uuid","=",sysUser.getId()));
                //交易完成设置积分,当前用户Opo_user相关信息(投资总次数)
                opoUserService.update(Chain.make("score",5000).add("invest_count",opo_use.getInvest_count() + 1),Cnd.where("uuid","=",sysUser.getId()));
                opoUserService.update(Chain.make("score",5000),Cnd.where("uuid","=",orderInfo.getMatchUserID()));
                //设置静态钱包金额、静态钱包总金额纪录
                if(opo_use.getIsDividendReduce() == 1){ //分红降低
                    if((opo_use.getInvest_count() - opo_use.getInvest_count()%3)/3 == opo_use.getDividendReduceCycle()){
                        opoUserService.update(Chain.make("static_wallet",opo_use.getStatic_wallet() + 225).add("static_wallet_recrod",opo_use.getStatic_wallet_recrod() + 300),Cnd.where("uuid","=",sysUser.getId()));
                        opoOrderService.update(Chain.make("dividend",225),Cnd.where("userID","=",sysUser.getId()).and("matchUserID","=",opoOrder.getMatchUserID()).and("state","=",opoOrder.STATE_SUCCESS));
                    }
                }else{
                    opoUserService.update(Chain.make("static_wallet",opo_use.getStatic_wallet() + 600).add("static_wallet_recrod",opo_use.getStatic_wallet_recrod() + 600),Cnd.where("uuid","=",sysUser.getId()));
                    opoOrderService.update(Chain.make("dividend",600),Cnd.where("userID","=",sysUser.getId()).and("matchUserID","=",opoOrder.getMatchUserID()).and("state","=",opoOrder.STATE_SUCCESS));
                }

                opoOrderService.update(Chain.make("match_evidence",opoOrder.getMatch_evidence()).add("Receive_time",opoOrder.getReceive_time()).add("state",Opo_order.STATE_CLOSE),Cnd.where("userID","=",sysUser.getId()).and("matchUserID","=",opoOrder.getMatchUserID()).and("state","=",opoOrder.STATE_SUCCESS));
                opoOrderService.update(Chain.make("match_evidence",opoOrder.getMatch_evidence()).add("Receive_time",opoOrder.getReceive_time()).add("state",Opo_order.STATE_CLOSE),Cnd.where("userID","=",opoOrder.getMatchUserID()).and("matchUserID","=",sysUser.getId()).and("state","=",opoOrder.STATE_REMITTANCE));
            }
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }
}


text:
/*
This question is from https://leetcode.com/problems/utf-8-validation/
Difficulty: medium

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For 1-byte character, the first bit is a 0, followed by its unicode code.
For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.
This is how the UTF-8 encoding would work:

   Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Given an array of integers representing the data, return whether it is a valid utf-8 encoding.

Note:
The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

Example 1:

data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.

Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
Example 2:

data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.

Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
*/
// T:O(N), S:O(1), 1 ms
class Solution {
    public boolean validUtf8(int[] data) {
        int numberOfBytes = 0;
        int mask1 = 1 << 7;
        int mask2 = 1 << 6;

        for(int i = 0; i < data.length; i++){
            if(numberOfBytes == 0){
                int mask = 1 << 7;
                while((data[i] & mask) != 0){
                    mask = mask >> 1;
                    numberOfBytes++;
                }

                if(numberOfBytes == 0) continue;

                if(numberOfBytes > 4 || numberOfBytes == 1)
                    return false;

            }else{
                // if(!((data[i] & mask1) != 0 && (data[i] & mask2) == 0)) return false;
                if((data[i] & mask1) != mask1 || (data[i] & mask2) != 0) return false;
            }
            numberOfBytes--;
        }

        return (numberOfBytes == 0);
    }
}


text:
import mouseEventListeners from './mouseEventListeners.js';
import wheelEventListener from './wheelEventListener.js';
import touchEventListeners from './touchEventListeners.js';

export { mouseEventListeners, wheelEventListener, touchEventListeners };


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from future import standard_library

standard_library.install_aliases()

__title__ = 'Tasks'
__version__ = '0.0.1'
__copyright__ = '(C) Copyright (2012-2016) Hewlett Packard Enterprise ' \
                ' Development LP'
__license__ = 'MIT'
__status__ = 'Development'

from hpOneView.resources.resource import ResourceClient

class Tasks(object):
    URI = '/rest/tasks'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get(self, id_or_uri):
        """
        Retrieve a task by its uri
        Args:
            id_or_uri: task id (or uri)

        Returns: dict

        """

        task = self._client.get(id_or_uri)
        return task

    def get_all(self, start=0, count=-1, fields='', filter='', query='', sort='', view=''):
        """
        Gets all the tasks based upon filters provided. Note: filters are optional.
        Args:

            start:
                 The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                 first available item.
            count:
                The number of resources to return. A count of -1 requests all the items. The actual number of items in
                the response may differ from the requested count if the sum of start and count exceed the total number
                of items.
            fields:
                 Specifies which fields should be returned in the result set.
            filter:
                 A general filter/query string to narrow the list of items returned. The default is no filter - all
                 resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default is no query - all
                 resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based on create time, with the
                oldest entry first.
            view:
                 Return a specific subset of the attributes of the resource or collection, by specifying the name of a
                 predefined view. The default view is expand - show all attributes of the resource and all elements of
                 collections of resources.

        Returns:
            list: A list of tasks.
        """
        return self._client.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view,
                                    fields=fields)


text:
package org.jsefa.test.rbf;

import static org.jsefa.test.common.JSefaTestUtil.FormatType.CSV;
import static org.jsefa.test.common.JSefaTestUtil.FormatType.FLR;
import junit.framework.TestCase;

import org.jsefa.csv.annotation.CsvDataType;
import org.jsefa.csv.annotation.CsvField;
import org.jsefa.flr.annotation.FlrDataType;
import org.jsefa.flr.annotation.FlrField;
import org.jsefa.test.common.AbstractTestDTO;
import org.jsefa.test.common.JSefaTestUtil;
import org.jsefa.test.common.JSefaTestUtil.FormatType;

/**
 * Tests for testing deserialization of records with missing fields.
 *
 * @author Norman Lahme-Huetig
 *
 */
public class MissingFieldsTest extends TestCase {

    /**
     * Tests it for CSV.
     */
    public void testCSV() {
        check(CSV, "a", TestDTO.class);
    }

    /**
     * Tests it for FLR.
     */
    public void testFLR() {
        check(FLR, "a         ", TestDTO.class);
    }

    @SuppressWarnings("unchecked")
    private void check(FormatType formatType, String inputString, Class<?> objectType) {
        JSefaTestUtil.deserialize(formatType, inputString, objectType);
    }

    @CsvDataType()
    @FlrDataType()
    static final class TestDTO extends AbstractTestDTO {
        @CsvField(pos = 0)
        @FlrField(pos = 0, length = 10)
        String stringFieldA;

        @CsvField(pos = 1)
        @FlrField(pos = 1, length = 10)
        String stringFieldB;
    }
}


text:
package org.syphr.mythtv.commons.socket;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.syphr.mythtv.commons.exception.ResponseTimeoutException;

/**
 * This class manages a low-level network connection. It provides the necessary
 * read/write capabilities as well as the ability to take over the
 * communications channel entirely to perform bulk raw data transfer, such as
 * transferring a file while another manager controls the flow.
 *
 * @author Gregory P. Moyer
 */
public class DefaultSocketManager implements SocketManager
{
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSocketManager.class);

    private final Packet packet;

    private final BlockingQueue<String> queue;
    private final AtomicInteger skippedResponses;
    private final ExecutorService receiverExecutor;

    private SocketChannel socket;
    private Selector readSelector;
    private Selector writeSelector;

    private Future<?> receiver;

    private Interceptor interceptor;

    private ByteChannel redirect;

    private volatile long defaultMessageTimeout = 10000;

    /**
     * Construct a new socket manager that is not connected to a server.
     *
     * @param packet
     *            a packet implementation that will handle formatting outgoing
     *            messages and parsing incoming messages
     */
    public DefaultSocketManager(Packet packet)
    {
        this.packet = packet;

        queue = new LinkedBlockingQueue<String>();
        skippedResponses = new AtomicInteger(0);
        receiverExecutor = Executors.newSingleThreadExecutor(new ThreadFactory()
        {
            @Override
            public Thread newThread(Runnable r)
            {
                SecurityManager s = System.getSecurityManager();
                ThreadGroup group = (s != null)
                        ? s.getThreadGroup()
                        : Thread.currentThread().getThreadGroup();

                Thread t = new Thread(group, r, DefaultSocketManager.class.getSimpleName()
                        + " Receiver Thread", 0);
                if (!t.isDaemon())
                {
                    t.setDaemon(true);
                }
                if (t.getPriority() != Thread.NORM_PRIORITY)
                {
                    t.setPriority(Thread.NORM_PRIORITY);
                }

                return t;
            }
        });
    }

    @Override
    public void setInterceptor(Interceptor interceptor)
    {
        this.interceptor = interceptor;
    }

    @Override
    public void setDefaultMessageTimeout(long time, TimeUnit unit)
    {
        this.defaultMessageTimeout = unit.toMillis(time);
    }

    @Override
    public long getDefaultMessageTimeout(TimeUnit unit)
    {
        return unit.convert(defaultMessageTimeout, TimeUnit.MILLISECONDS);
    }

    @Override
    public void connect(String host, int port, final long timeout) throws IOException
    {
        connect(new InetSocketAddress(host, port), timeout);
    }

    @Override
    public void connect(InetSocketAddress addr, final long timeout) throws IOException
    {
        if (isConnected())
        {
            disconnect();
        }

        LOGGER.info("Connecting to {}:{}", addr.getHostName(), addr.getPort());

        socket = SocketChannel.open();
        socket.configureBlocking(true);

        final Thread connectionThread = Thread.currentThread();
        Thread timeoutThread = new Thread("Connection Timeout Listener")
        {
            @Override
            public void run()
            {
                try
                {
                    if (timeout < 1)
                    {
                        return;
                    }

                    LOGGER.trace("Starting connection timeout for {} milliseconds", timeout);
                    Thread.sleep(timeout);

                    LOGGER.error("Connection timed out after {} milliseconds", timeout);
                    connectionThread.interrupt();
                }
                catch (InterruptedException e)
                {
                    /*
                     * Let this thread die when it's interrupted.
                     */
                    LOGGER.trace("Connection completed, stopping timeout thread");
                }
            }
        };

        timeoutThread.start();
        try
        {
            socket.connect(addr);
        }
        finally
        {
            timeoutThread.interrupt();
        }

        LOGGER.info("Connected");

        socket.configureBlocking(false);
        openSelectors();
        startReceiver();
    }

    /**
     * Open the read and write selectors. This needs to be done before data can
     * be send through this socket manager using its own API (not the
     * {@link #redirectChannel() redirected channel}). These selectors should be
     * {@link #closeSelectors() closed} before redirecting the channel to
     * prevent corruption.
     *
     * @throws IOException
     *             if an error occurs while opening either selector
     */
    private void openSelectors() throws IOException
    {
        readSelector = Selector.open();
        socket.register(readSelector, SelectionKey.OP_READ);

        writeSelector = Selector.open();
        socket.register(writeSelector, SelectionKey.OP_WRITE);
    }

    /**
     * Close the read and write selectors. This will prevent any further
     * communication to the connected server through this manager until the
     * selectors are {@link #openSelectors() opened} again. This should happen
     * before {@link #redirectChannel() redirecting the channel}. If any errors
     * occur here they will be logged, but not thrown.
     */
    private void closeSelectors()
    {
        if (readSelector != null)
        {
            try
            {
                readSelector.close();
            }
            catch (IOException e)
            {
                LOGGER.debug("Error while closing read selector", e);
            }
        }

        if (writeSelector != null)
        {
            try
            {
                writeSelector.close();
            }
            catch (IOException e)
            {
                LOGGER.debug("Error while closing write selector", e);
            }
        }
    }

    /**
     * Start the receiver thread. This thread will wait for data to arrive from
     * the connected server and deal with it (as either a response or an
     * unsolicited message). The receiver must be started before communication
     * can proceed, but it should be {@link #stopReceiver() stopped} before
     * redirecting the channel to prevent corruption.
     */
    private void startReceiver()
    {
        if (receiver != null)
        {
            return;
        }

        receiver = receiverExecutor.submit(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    try
                    {
                        if (readSelector.select() != 1 || Thread.interrupted())
                        {
                            break;
                        }

                        readSelector.selectedKeys().clear();

                        for (String value : packet.read(socket))
                        {
                            LOGGER.trace("Received message: {}", value);

                            if (interceptor != null && interceptor.intercept(value))
                            {
                                continue;
                            }

                            /*
                             * If the client stops waiting for a response, it
                             * will increment this value. To keep things in
                             * sync, those skipped responses need to be thrown
                             * away when they arrive.
                             */
                            if (skippedResponses.get() > 0)
                            {
                                LOGGER.trace("Discarding skipped message: {}", value);

                                skippedResponses.decrementAndGet();
                                continue;
                            }

                            queue.add(value);
                        }
                    }
                    catch (InterruptedIOException e)
                    {
                        LOGGER.info("Receiver interrupted");
                        break;
                    }
                    catch (ClosedByInterruptException e)
                    {
                        LOGGER.info("Receiver closed by interrupt");
                        break;
                    }
                    catch (IOException e)
                    {
                        LOGGER.error("Connection error", e);

                        disconnect();
                        break;
                    }
                }
            }
        });
    }

    /**
     * Stop the receiver thread from pulling incoming data off the channel. Once
     * this occurs, communication from the server will be ignored. This must
     * occur before {@link #redirectChannel() redirecting the channel}.
     */
    private void stopReceiver()
    {
        if (receiver == null)
        {
            return;
        }

        receiver.cancel(true);
        receiver = null;
    }

    @Override
    public boolean isConnected()
    {
        return socket != null && socket.isConnected();
    }

    @Override
    public InetSocketAddress getConnectedAddress()
    {
        return isConnected() ? (InetSocketAddress)socket.socket().getRemoteSocketAddress() : null;
    }

    @Override
    public SocketManager newConnection() throws IOException
    {
        SocketManager newManager = createSocketManager(packet);

        if (isConnected())
        {
            newManager.connect(getConnectedAddress(), 0);
        }

        return newManager;
    }

    /**
     * Build a new {@link DefaultSocketManager} in a default state.
     *
     * @param packet
     *            the packet implementation to use
     * @return the new manager
     */
    protected SocketManager createSocketManager(Packet packet)
    {
        return new DefaultSocketManager(packet);
    }

    @Override
    public void disconnect()
    {
        /*
         * Make sure the receiver thread is cancelled and forgotten in case this
         * disconnect call is made after the socket has already been closed for
         * some other reason (like an error).
         */
        stopReceiver();

        if (!isConnected())
        {
            return;
        }

        LOGGER.info("Disconnecting");

        closeSelectors();

        try
        {
            socket.close();
        }
        catch (IOException e)
        {
            LOGGER.debug("Error while closing socket", e);
        }

        LOGGER.info("Disconnected");
    }

    @Override
    public void send(String message) throws IOException
    {
        confirmConnected();

        LOGGER.trace("Sending message: {}", message);

        if (writeSelector.select() != 1 || Thread.interrupted())
        {
            throw new InterruptedIOException();
        }

        writeSelector.selectedKeys().clear();

        packet.write(socket, message);

        LOGGER.trace("Message sent");
    }

    @Override
    public String sendAndWait(String message) throws ResponseTimeoutException, IOException
    {
        return sendAndWait(message, defaultMessageTimeout, TimeUnit.MILLISECONDS);
    }

    @Override
    public String sendAndWait(String message, long timeout, TimeUnit unit) throws ResponseTimeoutException,
                                                                          IOException
    {
        synchronized (Lock.SEND_AND_WAIT)
        {
            send(message);

            try
            {
                LOGGER.trace("Waiting for reply");

                if (timeout < 1)
                {
                    return queue.take();
                }

                String response = queue.poll(timeout, unit);
                if (response == null)
                {
                    /*
                     * Indicate to the receiver thread that this response is
                     * being skipped so that it can be thrown away when it
                     * arrives.
                     */
                    skippedResponses.incrementAndGet();

                    throw new ResponseTimeoutException(TimeUnit.MILLISECONDS.convert(timeout, unit)
                            + " ms");
                }

                return response;
            }
            catch (InterruptedException e)
            {
                LOGGER.info("Interrupted while waiting for response", e);
                return "";
            }
        }
    }

    @Override
    public ByteChannel redirectChannel()
    {
        synchronized (Lock.REDIRECT_CHANNEL)
        {
            stopReceiver();
            closeSelectors();

            if (redirect == null)
            {
                redirect = new RedirectedChannel();
            }

            return redirect;
        }
    }

    private void confirmConnected() throws IOException
    {
        if (!isConnected())
        {
            throw new IOException("not connected");
        }
    }

    private enum Lock
    {
        SEND_AND_WAIT, REDIRECT_CHANNEL
    }

    private class RedirectedChannel implements ByteChannel
    {
        private volatile boolean closed;

        @Override
        public void close() throws IOException
        {
            synchronized (Lock.REDIRECT_CHANNEL)
            {
                if (closed)
                {
                    return;
                }

                closed = true;
                redirect = null;

                openSelectors();
                startReceiver();
            }
        }

        @Override
        public int read(ByteBuffer dst) throws IOException
        {
            confirmOpen();
            return socket.read(dst);
        }

        @Override
        public int write(ByteBuffer src) throws IOException
        {
            confirmOpen();
            return socket.write(src);
        }

        @Override
        public boolean isOpen()
        {
            return !closed;
        }

        private void confirmOpen() throws IOException
        {
            if (!isOpen())
            {
                throw new IOException("redirected channel is no longer accessible");
            }
        }
    }
}


text:
# ----------------------------------------------------------------------------
#
#   enso.providers
#
# ----------------------------------------------------------------------------

"""
    This module provides a simple Abstract Factory-like mechanism to
    that allows for platform-specific functionalities that conform to
    common interfaces to be implemented by different libraries.

    A provider is just a Python module or package with a single
    function in it, provideInterface(), which takes a single string
    argument that corresponds to the name of an interface.  If the
    provider has an implementation of the interface, it returns it; if
    not, it returns None.

    Providers are specified as their fully-qualified module or package
    names in the enso.config.PROVIDERS list.  For instance, if the
    provider "mypackage.myprovider" should be loaded when Enso is
    started, then the string "mypackage.myprovider" should be added to
    enso.config.PROVIDERS.

    Whenever an interface implementation is requested through this
    module's getInterface() function, each provider is consulted in
    the order listed in enso.config.PROVIDERS until an implementation
    is found.  In this way, it's possible for providers to be
    "layered" (in a variation of the Chain of Responsibility pattern)
    so that Enso attempts to load the most functional and
    feature-loaded implementation first, and if that fails, Enso's
    functionality is able to "gracefully degrade" until a working
    implementation of an interface is found.

    For instance, take the hypothetical example of an interface called
    "dictionary", which has a single function, lookupWord(), that
    looks up a particular word in a dictionary and presents the
    definition to the end-user.  Under Mac OS X, the ideal
    functionality would be to use the built-in dictionary that comes
    with the operating system.  Under Windows, the ideal functionality
    would be to see if the user has some kind of offline dictionary
    program installed, and if so, to use that.  If all of these fail,
    then the final alternative would be to open the user's web browser
    and look up the word online.  Each one of these mechanisms can be
    implemented by a different provider, and as long as the "most
    generic" ones are at the end of the provider chain, Enso's
    functionality will degrade gracefully.
"""

# ----------------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------------

import logging

import enso.config

# ----------------------------------------------------------------------------
# Private module variables
# ----------------------------------------------------------------------------

# Dictionary mapping interface names to their implementations.
_interfaces = {}

# List of all provider objects.
_providers = []

# ----------------------------------------------------------------------------
# Private functions
# ----------------------------------------------------------------------------

def _initDefaultProviders():
    """
    Resolves all provider names in enso.config.PROVIDERS to actual
    Python objects.
    """

    for moduleName in enso.config.PROVIDERS:
        try:
            # Import the module; most of this code was taken from the
            # Python Library Reference documentation for __import__().
            module = __import__( moduleName, {}, {}, [] )
            components = moduleName.split( "." )
            for component in components[1:]:
                module = getattr( module, component )

            _providers.append( module )
            logging.info( "Added provider %s." % moduleName )
        except ProviderUnavailableError:
            logging.info( "Skipping provider %s." % moduleName )

# ----------------------------------------------------------------------------
# Public functions
# ----------------------------------------------------------------------------

def getInterface( name ):
    """
    Finds and returns an implementation that provides an interface
    with the given name.  If no interface exists that provides the
    given interface, this function raises a ProviderNotFoundError.
    """

    if not _providers:
        _initDefaultProviders()
    if name not in _interfaces:
        for provider in _providers:
            interface = provider.provideInterface( name )
            if interface:
                logging.info( "Obtained interface '%s' from provider '%s'."
                              % (name, provider.__name__) )
                _interfaces[name] = interface
                break
    if name in _interfaces:
        return _interfaces[name]
    else:
        raise ProviderNotFoundError( name )

# ----------------------------------------------------------------------------
# Exceptions
# ----------------------------------------------------------------------------

class ProviderUnavailableError( Exception ):
    """
    Exception raised when a provider is unavailable for use, even
    though its implementation exists; this may be because, for
    instance, the host system is unsupported by the provider, or the
    provider communcates with third-party software that isn't
    installed.
    """

    pass

class ProviderNotFoundError( Exception ):
    """
    Exception raised when an implementation for a particular interface
    is not found.
    """

    pass


text:
package php.id.ganapatih;

import helper.peopleData;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SplashScreen extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        peopleData p = new peopleData(getApplicationContext());

        if(p.isLogin()){
        	startActivity(new Intent(SplashScreen.this, Home.class));
        	finish();
        }else{
        	setContentView(R.layout.activity_splash_screen);

			Thread timer = new Thread() {
				public void run() {
					try {
						sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						startActivity(new Intent(SplashScreen.this,
								Welcome.class));
						finish();
					}
				}
			};
			timer.start();
        }
    }
}


text:
require 'spec_helper'

describe Devise::SessionsController do
  render_views

  describe "POST /users/sign_in" do
    before do
      @request.env["devise.mapping"] = Devise.mappings[:user]
    end

    let(:app)  { Fabricate(:app) }
    let(:user) { Fabricate(:user) }

    it 'redirects to app index page if there are no apps for the user' do
      post :create, params: { user: { 'email' => user.email, 'password' => user.password } }
      expect(response).to redirect_to(root_path)
    end

    it 'redirects to app page if there is app for the user' do
      Fabricate(:user_watcher, app: app, user: user)
      post :create, params: { user: { 'email' => user.email, 'password' => user.password } }
      expect(response).to redirect_to(app_path(app))
    end
  end
end


text:
from __future__ import division

__all__ = ['write_forcefield']

import re
import json
import parmed as pmd
import numpy as np
from parmed.periodic_table import AtomicNum
from .hoomdxml import RB_to_OPLS
from collections import OrderedDict
from oset import oset as OrderedSet

def write_forcefield(structure, filename, ref_distance=1.0, ref_energy=1.0):
    """Output force field information in JSON format.

    Parameters
    ----------
    structure : parmed.GromacsTopologyFile
        Parmed structure object
    filename : str
        Path of the output file.
    ref_distance : float, default=1.0
        Reference distance for conversion to reduced units
    ref_energy : float, default=1.0
        Reference energy for conversion to reduced units
    """

    params = pmd.ParameterSet.from_structure(structure)
    ff_data = OrderedDict()

    styles = OrderedDict()

    with open(filename, 'w') as f:

        # Pair
        charges = np.any([atom.charge for atom in structure.atoms])
        if charges:
            styles['pair'] = 'lj/coul'
        else:
            styles['pair'] = 'lj'

        pair_data = dict()
        for key in params.atom_types.items():
            temp_dict = OrderedDict()
            temp_dict['element'] = {enum:ename for ename,enum in AtomicNum.items()}[key[1].atomic_number]
            temp_dict['epsilon'] = round(key[1].epsilon,3) / ref_energy
            temp_dict['sigma'] = round(key[1].sigma,3) / ref_distance
            pair_data[key[0]] = temp_dict
        pair_data = OrderedDict(sorted(pair_data.items(),
                                       key=lambda p: int(p[0].split('_')[1])))

        # Bonds
        bonds = [bond for bond in structure.bonds]
        if bonds:
            styles['bond'] = 'harmonic'
            unique_bond_types = dict(enumerate(OrderedSet([(round(bond.type.k,3),
                                                            round(bond.type.req,3)) for bond in structure.bonds])))
            bond_data = OrderedDict()
            for idx,key in unique_bond_types.items():
                temp_dict = OrderedDict()
                temp_dict['k'] = round(key[0]*2,3) * ((ref_distance**2)/ref_energy)
                temp_dict['r0'] = round(key[1],3) / ref_distance
                bond_data[str(idx)] = temp_dict

        # Angles
        angles = [angle for angle in structure.angles]
        if angles:
            styles['angle'] = 'harmonic'
            unique_angle_types = dict(enumerate(OrderedSet([(round(angle.type.k,3),
                                                    round(angle.type.theteq,3)) for angle in structure.angles])))
            angle_data = OrderedDict()
            for idx,key in unique_angle_types.items():
                temp_dict = OrderedDict()
                temp_dict['k'] = round(key[0]*2,3) / ref_energy
                temp_dict['t0'] = round(key[1],3) * (np.pi/180)
                angle_data[str(idx)] = temp_dict

        # Dihedrals
        dihedrals = [dihedral for dihedral in structure.rb_torsions]
        if dihedrals:
            styles['dihedral'] = 'opls'

            unique_dihedral_types = dict(enumerate(OrderedSet([(round(dihedral.type.c0,3),
                                                    round(dihedral.type.c1,3),
                                                    round(dihedral.type.c2,3),
                                                    round(dihedral.type.c3,3),
                                                    round(dihedral.type.c4,3),
                                                    round(dihedral.type.c5,3),
                                                    round(dihedral.type.scee,1),
                                                    round(dihedral.type.scnb,1)) for dihedral in structure.rb_torsions])))
            dihedrals_opls = [RB_to_OPLS(y[0],y[1],y[2],y[3],y[4],y[5]) for x,y in unique_dihedral_types.items()]
            dihedral_data = OrderedDict()
            for idx,key in enumerate(dihedrals_opls):
                temp_dict = OrderedDict()
                temp_dict['k1'] = round(key[0],3) / ref_energy
                temp_dict['k2'] = round(key[1],3) / ref_energy
                temp_dict['k3'] = round(key[2],3) / ref_energy
                temp_dict['k4'] = round(key[3],3) / ref_energy
                dihedral_data[str(idx)] = temp_dict

        ff_data['styles'] = styles
        ff_data['pair_coeffs'] = pair_data
        if bonds:
            ff_data['bond_coeffs'] = bond_data
        if angles:
            ff_data['angle_coeffs'] = angle_data
        if dihedrals:
            ff_data['dihedral_coeffs'] = dihedral_data

        json.dump(ff_data,f,indent=4)


text:
class PageController < ApplicationController

  def index
  end

end