text:
package com.xuhao.didi.socket.server.impl.clientpojo;

import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.socket.common.interfaces.common_interfacies.server.IClient;
import com.xuhao.didi.socket.common.interfaces.common_interfacies.server.IClientPool;
import com.xuhao.didi.socket.server.exceptions.CacheException;

public class ClientPoolImpl extends AbsClientPool<String, IClient> implements IClientPool<IClient, String> {

    public ClientPoolImpl(int capacity) {
        super(capacity);
    }

    @Override
    public void cache(IClient client) {
        super.set(client.getUniqueTag(), client);
    }

    @Override
    public IClient findByUniqueTag(String tag) {
        return get(tag);
    }

    public void unCache(IClient iClient) {
        remove(iClient.getUniqueTag());
    }

    public void unCache(String key) {
        remove(key);
    }

    @Override
    public int size() {
        return super.size();
    }

    @Override
    public void sendToAll(final ISendable sendable) {
        echoRun(new Echo<String, IClient>() {
            @Override
            public void onEcho(String key, IClient value) {
                value.send(sendable);
            }
        });
    }

    public void serverDown(){
        echoRun(new Echo<String, IClient>(){
            @Override
            public void onEcho(String key, IClient value) {
                value.disconnect();
            }
        });
        removeAll();
    }

    @Override
    void onCacheFull(String key, IClient lastOne) {
        lastOne.disconnect(new CacheException("cache is full,you need remove"));
        unCache(lastOne);
    }

    @Override
    void onCacheDuplicate(String key, IClient oldOne) {
        oldOne.disconnect(new CacheException("there are cached in this server.it need removed before new cache"));
        unCache(oldOne);
    }

    @Override
    public void onCacheEmpty() {
        //do nothing
    }
}


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../../polymer/polymer.html">
<link rel="import" href="../../iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../../iron-media-query/iron-media-query.html">
<link rel="import" href="../../iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="../app-scroll-behaviors/app-document-scroll-behavior.html">
<link rel="import" href="../app-drawer/app-drawer.html">
<link rel="import" href="../app-scrim/app-scrim.html">

<!--
app-drawer-layout lays out an app-drawer and the content. When the viewport width is smaller
than `responsiveWidth`, this element changes to narrow layout. In narrow layout, the
drawer will be stacked on top of the main content. The drawer will slide in/out to
hide/reveal the main content.

By default the drawer is on the left side of the screen:

```html
<app-drawer-layout>
  <div drawer>
    <!\-\- drawer content \-\->
  </div>
  <div main>
    <!\-\- main content \-\->
  </div>
</app-drawer-layout>
```

A drawer on the right side of the screen:

```html
<app-drawer-layout drawer-position="right">
  <div drawer>
    <!\-\- drawer content \-\->
  </div>
  <div main>
    <!\-\- main content \-\->
  </div>
</app-drawer-layout>
```

With an app-header-layout:

```html
<app-drawer-layout>
  <div drawer>
    <!\-\- drawer content \-\->
  </div>
  <app-header-layout main>
    <app-header>
      <app-toolbar>
        <div title>App name</div>
      </app-toolbar>
    </app-header>

    <!\-\- main content \-\->

  </app-header-layout>
</app-drawer-layout>
```

@demo app-drawer-layout/demo.html
-->

<dom-module id="app-drawer-layout">

  <style>

    :host {
      display: block;
    }

    :host([fullbleed]) {
      @apply(--layout-fit);
    }

    #drawerContainer {
      position: fixed;
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;

      @apply(--app-drawer-layout-drawer);
    }

    :host([narrow]) > #drawerContainer {
      @apply(--app-drawer-layout-narrow-drawer);
    }

    #main {
      position: relative;
      height: 100%;
    }

    :host([narrow]) app-drawer {
      box-shadow: 1px 0 2px 1px rgba(0,0,0,0.18);
    }

    :host([narrow]) app-drawer[position=right] {
      box-shadow: -1px 0 2px 1px rgba(0,0,0,0.18);
    }

    :host([fullbleed]) > #main > ::content > * {
      @apply(--layout-fit);
    }

    :host(:not([narrow])) ::content [drawer-toggle] {
      display: none;
    }

  </style>

  <template>

    <div id="main" style$="[[_computeMainStyle(narrow, drawerWidth)]]">
      <content select=":not([drawer])"></content>
      <app-scrim id="scrim" visible$="[[_isScrimVisible(narrow, opened)]]" on-tap="toggleDrawer"></app-scrim>
    </div>

    <app-drawer id="drawerContainer" position="[[drawerPosition]]"
        opened="[[_drawerOpened(narrow, opened)]]" style$="[[_computeDrawerStyle(drawerWidth)]]"
        on-iron-activate="_drawerActivate">
      <content id="drawer" select="[drawer]"></content>
    </app-drawer>

    <iron-media-query query="[[_computeMediaQuery(forceNarrow, responsiveWidth)]]"
        on-query-matches-changed="_onQueryMatchesChanged"></iron-media-query>

  </template>

  <script>

    Polymer({

      is: 'app-drawer-layout',

      behaviors: [
        Polymer.IronResizableBehavior,
        Polymer.AppDocumentScrollBehavior
      ],

      properties: {

        /**
         * Returns true if the panel is in narrow layout. This is useful if you
         * need to show/hide elements based on the layout.
         */
        narrow: {
          type: Boolean,
          readOnly: true,
          notify: true,
          reflectToAttribute: true,
          value: false
        },

        /**
         * If true, ignore `responsiveWidth` setting and force the narrow layout.
         */
        forceNarrow: {
          type: Boolean,
          value: false,
          observer: '_responsiveChange'
        },

        /**
         * If the viewport's width is smaller than this value, the panel will change to narrow layout.
         * In the mode the drawer will be closed.
         */
        responsiveWidth: {
          type: String,
          value: '640px'
        },

        /**
         * The width of the drawer panel.
         */
        drawerWidth: {
          type: String,
          value: '256px'
        },

        /**
         * Specifies whether or not the drawer is opened.
         */
        opened: {
          type: Boolean,
          notify: true,
          reflectToAttribute: true,
          value: false
        },

        /**
         * If true, the current element will take the whole canvas of the nearast positioned element.
         */
        fullbleed: {
          type: Boolean,
          reflectToAttribute: true,
          value: false
        },

        /**
         * Indicates position of the drawer on the screen. Options are left, right, top, bottom.
         */
        drawerPosition: {
          type: String,
          value: 'left'
        },

        disableDrawerActivate: {
          type: Boolean,
          value: false
        }
      },

      listeners: {
        tap: '_tapHandler'
      },

      attached: function() {
        this.fire('iron-resize');
        this.shouldEnableScroll(true, this.$.drawerContainer);
      },

      /**
       * Toggles the drawer panel open and closed.
       *
       * @method toggleDrawer
       */
      toggleDrawer: function() {
        this.opened = !this.opened;
      },

      /**
       * Gets the drawer element.
       *
       * @property drawer
       */
      get drawer() {
        return Polymer.dom(this.$.drawer).getDistributedNodes()[0];
      },

      _tapHandler: function(e) {
        var target = Polymer.dom(e).localTarget;
        if (target && target.hasAttribute('drawer-toggle')) {
          this.toggleDrawer();
        }
      },

      _drawerOpened: function(narrow, opened) {
        return !narrow || opened;
      },

      _drawerActivate: function() {
        if (!this.disableDrawerActivate && this.narrow) {
          this.async(function() {
            this.opened = false;
          });
        }
      },

      _responsiveChange: function(narrow) {
        this._setNarrow(narrow);
        this.async(this.notifyResize);
      },

      _onQueryMatchesChanged: function(event) {
        this._responsiveChange(event.detail.value);
      },

      _computeMediaQuery: function(forceNarrow, responsiveWidth) {
        return forceNarrow ? '' : '(max-width: ' + responsiveWidth + ')';
      },

      _isScrimVisible: function(narrow, opened) {
        var shouldHaveScrim = narrow && opened;
        this.shouldEnableDocScroll(!shouldHaveScrim);
        return shouldHaveScrim;
      },

      _computeDrawerStyle: function(drawerWidth) {
        return 'width: ' + drawerWidth;
      },

      _computeMainStyle: function(narrow, drawerWidth) {
        return 'margin-left: ' + (narrow ? '' : drawerWidth);
      }

    });

  </script>

</dom-module>

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class ConfigTest < MiniTest::Unit::TestCase
  include TTYCoke::Log

  def setup
    @config = TTYCoke::Config.new(File.dirname(__FILE__) + '/../data/config.yaml')
  end

  def test_find_program
    assert @config.find_program('lsmod')
    refute @config.find_program('do not exist')
  end

  def test_yaml_file_syntax_error
    buggie_test_file = File.dirname(__FILE__) + '/../data/syntax_error_config.yaml'
    exception = assert_raises(TTYCoke::Errors::YamlSyntaxError) {
      TTYCoke::Config.new(buggie_test_file)
    }
  end

end


text:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

require('redux');
require('./turn-order-0846b669.js');
require('immer');
require('./reducer-172d838d.js');
require('./initialize-05ccbf0c.js');
require('./base-4e44970d.js');
var socketio = require('./socketio-7f71fa7c.js');
require('./master-07165369.js');
require('socket.io-client');

exports.Local = socketio.Local;
exports.SocketIO = socketio.SocketIO;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<html>
<head>
    <title>starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
</head>
<body>
500..
</body>
<script type="text/javascript">
    alert(500);
</script>
</html>


text:
var _ = require('underscore');
var userModel = require('oae-principals/lib/model.user.js');
var groupModel = require('oae-principals/lib/model.group.js');

// Expose the user and group model.
_.extend(module.exports, userModel, groupModel);


text:
package com.reactnativenavigation.utils;

import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

public class UiUtils {
    private static final int STATUS_BAR_HEIGHT_M = 24;
    private static final int STATUS_BAR_HEIGHT_L = 25;
    private static final int DEFAULT_TOOLBAR_HEIGHT = 56;

    private static int statusBarHeight = -1;
    private static int topBarHeight = -1;

    public static void runOnPreDrawOnce(final View view, final Runnable task) {
        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                view.getViewTreeObserver().removeOnPreDrawListener(this);
                task.run();
                return true;
            }
        });
    }

    public static void runOnMeasured(View view, Runnable task) {
        if (view.getHeight() > 0 && view.getWidth() > 0) {
            task.run();
        } else {
            view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (view.getHeight() > 0 && view.getWidth() > 0) {
                        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        task.run();
                    }
                }
            });
        }
    }

	public static void runOnMainThread(Runnable runnable) {
		new Handler(Looper.getMainLooper()).post(runnable);
	}

	public static float getWindowHeight(Context context) {
        return getDisplayMetrics(context).heightPixels;
	}

    public static float getWindowWidth(Context context) {
        return getDisplayMetrics(context).widthPixels;
    }

    @NonNull
    private static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getMetrics(metrics);
        }
        return metrics;
    }

    public static int getStatusBarHeight(Context context) {
        if (statusBarHeight > 0) {
            return statusBarHeight;
        }
        final Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        statusBarHeight = resourceId > 0 ?
                resources.getDimensionPixelSize(resourceId) :
                dpToPx(context, Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? STATUS_BAR_HEIGHT_M : STATUS_BAR_HEIGHT_L);
        return statusBarHeight;
    }

    public static int getTopBarHeightDp(Context context) {
        return (int) UiUtils.pxToDp(context, getTopBarHeight(context));
    }

    public static int getTopBarHeight(Context context) {
        if (topBarHeight > 0) {
            return topBarHeight;
        }
        final Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier("action_bar_size", "dimen", "android");
        topBarHeight = resourceId > 0 ?
                resources.getDimensionPixelSize(resourceId) :
                dpToPx(context, DEFAULT_TOOLBAR_HEIGHT);
        return topBarHeight;
    }

    public static float dpToPx(Context context, float dp) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    }

    public static int dpToPx(Context context, int dp) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
    }

    public static float pxToDp(Context context, float px) {
        return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    }

    public static float dpToSp(Context context, float dp) {
        return dpToPx(context, dp) / context.getResources().getDisplayMetrics().density;
    }
}


text:
__author__ = 'Aaron J. Masino'

'''
Created on Feb 3, 2014

@author: masinoa
'''

import nltk.data
from nltk.tokenize import regexp_tokenize
from nltk.corpus import stopwords
import re
from functools import reduce

#load a sentence tokenizer, faster for many tokenizations
sent_tokenizer = nltk.data.load('file:./learn/english.pickle')

def sentences(text):
    '''Uses /tokenizers/punkt/english tokenizer to create list of sentences from text'''
    return sent_tokenizer.tokenize(text)

def words(text, splitContractions=False, contractChars = ["'"]):
    '''uses a regexpTokenizer to tokenize text to words. If splitContractions is true,
    the regex pattern is [\w]+ so that contractions are split, e.g. "I can't" -> ['I','can','t'],
    otherwise the regex pattern is [\w']+ so that contractions are not split, i.e. "I can't" -> ['I', "can't"]
    Additional contract characters, e.g. a hyphen, can be added by over riding the contractChars arg'''
    if splitContractions:
        pat = "[\w]+"
    else:
        pat = "[\w{0}]+".format(reduce(lambda x,y: x+y, contractChars, ""))
    return regexp_tokenize(text, pat, discard_empty=True)

def replace_patterns(text, patterns, replaceWith="", flags = None):
    '''replaces each occurrence of each pattern with the replaceWith value'''
    rt = text
    for pat in patterns:
        if not flags:
            rt =  re.sub(pat, replaceWith, rt)
        else:
            rt = re.sub(pat, replaceWith, rt, flags = flags)
    return rt

def replace_whole_words(text, words=[], replaceWith="", flags = re.IGNORECASE):
    rt = text
    for w in words:
        rt = replace_patterns(rt, [r'(?<=\s){0}(?=[\s,!\.;])'.format(w), r'^{0}(?=[\s,!\.;])'.format(w)], replaceWith, flags=flags)
    return rt

def replace_digits(text, replaceWith='number'):
    '''attempts to remove numbers from text using given regex patterns and replace them with the replacementWord'''
    return replace_patterns(text, [r'[-+]?\d+\.\d*',r'[-+]?\d*\.\d+',r'[-+]?\d+'], replaceWith)

def standard_numerals():
    return ["one","two","three","four", "five","six","seven","eight","nine", "eleven","twelve"]

def replace_numerals(text, replaceWith='number', numerals=None, flags = re.IGNORECASE):
    if not numerals:
        return replace_whole_words(text, standard_numerals(), replaceWith, flags)
    else:
        return replace_whole_words(text, numerals, replaceWith, flags)

def standard_units():
    return [r"year", r"years",
            r"month", r"months",
            r"day", r"days",
            r"hour", r"hours",
            r"minute", r"minutes",
            r"second", r"seconds",
            r"cm", r"mm"]

def replace_units(text, replaceWith='unit', units = None, flags = re.IGNORECASE):
    if not units:
        return replace_whole_words(text, standard_units(), replaceWith, flags)
    else:
        return replace_whole_words(text, units, replaceWith, flags)

def porter_stem(wordList):
    porter = nltk.PorterStemmer()
    return [porter.stem(w) for w in wordList]

def filter_stop_words(wordlist):
    sw = stopwords.words('english')
    return filter(lambda w: w not in sw, wordlist)

def text_preprocessor(text):
    ct = replace_digits(text)
    ct = replace_numerals(ct)
    ct = replace_units(ct)
    _words = [word.lower() for word in words(ct)]
    _words = filter(lambda x: x not in stopwords.words('english') and len(x)>2, _words)
    _words = porter_stem(_words)
    return reduce(lambda x,y: '{0} {1}'.format(x,y), _words, "")


text:
package org.aja

import org.scalatest.FunSuite

/**
 * Created by mageswaran on 20/10/15.
 */
class FirstTestSuit extends FunSuite {

  test("very basic") {
    assert (1 == 1)
  }

  test ("another very basic test") {
    assert ("Hello" == "Hello")
  }

}


text:
package org.kuali.rice.core.api.criteria;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * An abstract implementation of a {@link CompositePredicate}.  This class defines all of the JAXB
 * annotations such that sub-classes should not have to.
 *
 * <p>If a class subclasses this class then it *MUST* be sure to add itself to the JAXB
 * annotations for {@link #predicates}
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = AbstractCompositePredicate.Constants.TYPE_NAME)
abstract class AbstractCompositePredicate extends AbstractPredicate implements CompositePredicate {

    private static final long serialVersionUID = 6164560054223588779L;
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    /**
     * Defines the JAXB annotations for the List of predicates.  All supported predicates *MUST* be
     * included in this List in order for them to be supported in the XML schema.
     *
     * If a new type of predicate is created it *MUST* be added to this list.
     */
    @XmlElements(value = {
            @XmlElement(name = AndPredicate.Constants.ROOT_ELEMENT_NAME, type = AndPredicate.class, required = false),
            @XmlElement(name = EqualPredicate.Constants.ROOT_ELEMENT_NAME, type = EqualPredicate.class, required = false),
            @XmlElement(name = EqualIgnoreCasePredicate.Constants.ROOT_ELEMENT_NAME, type = EqualIgnoreCasePredicate.class, required = false),
            @XmlElement(name = ExistsSubQueryPredicate.Constants.ROOT_ELEMENT_NAME, type = ExistsSubQueryPredicate.class, required = false),
            @XmlElement(name = GreaterThanPredicate.Constants.ROOT_ELEMENT_NAME, type = GreaterThanPredicate.class, required = false),
            @XmlElement(name = GreaterThanOrEqualPredicate.Constants.ROOT_ELEMENT_NAME, type = GreaterThanOrEqualPredicate.class, required = false),
            @XmlElement(name = InPredicate.Constants.ROOT_ELEMENT_NAME, type = InPredicate.class, required = false),
            @XmlElement(name = InIgnoreCasePredicate.Constants.ROOT_ELEMENT_NAME, type = InIgnoreCasePredicate.class, required = false),
            @XmlElement(name = LessThanPredicate.Constants.ROOT_ELEMENT_NAME, type = LessThanPredicate.class, required = false),
            @XmlElement(name = LessThanOrEqualPredicate.Constants.ROOT_ELEMENT_NAME, type = LessThanOrEqualPredicate.class, required = false),
            @XmlElement(name = LikePredicate.Constants.ROOT_ELEMENT_NAME, type = LikePredicate.class, required = false),
            @XmlElement(name = LikeIgnoreCasePredicate.Constants.ROOT_ELEMENT_NAME, type = LikeIgnoreCasePredicate.class, required = false),
            @XmlElement(name = NotEqualPredicate.Constants.ROOT_ELEMENT_NAME, type = NotEqualPredicate.class, required = false),
            @XmlElement(name = NotEqualIgnoreCasePredicate.Constants.ROOT_ELEMENT_NAME, type = NotEqualIgnoreCasePredicate.class, required = false),
            @XmlElement(name = NotInPredicate.Constants.ROOT_ELEMENT_NAME, type = NotInPredicate.class, required = false),
            @XmlElement(name = NotInIgnoreCasePredicate.Constants.ROOT_ELEMENT_NAME, type = NotInIgnoreCasePredicate.class, required = false),
            @XmlElement(name = NotLikePredicate.Constants.ROOT_ELEMENT_NAME, type = NotLikePredicate.class, required = false),
            @XmlElement(name = NotNullPredicate.Constants.ROOT_ELEMENT_NAME, type = NotNullPredicate.class, required = false),
            @XmlElement(name = NullPredicate.Constants.ROOT_ELEMENT_NAME, type = NullPredicate.class, required = false),
            @XmlElement(name = OrPredicate.Constants.ROOT_ELEMENT_NAME, type = OrPredicate.class, required = false)
    })
    private final Set<Predicate> predicates;

	/**
	 * This default constructor exists only to be invoked by sub-classes
	 * in their default constructors which is used by JAXB.
	 */
    AbstractCompositePredicate() {
        this.predicates = null;
    }

    /**
     * When invoked by a subclass, this constructor will set the predicates
     * to the given set. If the set is null then it will be translated
     * internally to an empty set.
     *
     * @param predicates the list of predicates to set
     */
    AbstractCompositePredicate(final Set<Predicate> predicates) {
        if (predicates == null) {
            this.predicates = Collections.emptySet();
        } else {
            final Set<Predicate> temp = new HashSet<Predicate>();
            for (Predicate predicate: predicates) {
                if (predicate != null) {
                    temp.add(predicate);
                }
            }
            this.predicates = Collections.unmodifiableSet(temp);
        }
    }

    @Override
    public Set<Predicate> getPredicates() {
        return Collections.unmodifiableSet(predicates);
    }

    /**
     * Defines some internal constants used on this class.
     */
    static class Constants {
        final static String TYPE_NAME = "CompositePredicateType";
    }

    @Override
    public final String toString() {
        StringBuilder b = new StringBuilder(CriteriaSupportUtils.findDynName(this.getClass().getSimpleName()));
        b.append("(");
        if (!predicates.isEmpty()) {
            for (Predicate p : predicates) {
                b.append(LINE_SEPARATOR);
                //b.append("\t");
                b.append(p);
                b.append(", ");
            }
            b.deleteCharAt(b.lastIndexOf(", "));
            b.append(LINE_SEPARATOR);
        }
        b.append(')');
        return  b.toString();
    }
}


text:
package com.lindar.getaddress.io.client;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lindar.getaddress.io.client.util.GetAddressAPI;
import com.lindar.getaddress.io.client.vo.AddressVO;
import com.lindar.getaddress.io.client.vo.PostcodeVO;
import com.lindar.wellrested.WellRestedRequest;
import com.lindar.wellrested.vo.Result;
import com.lindar.wellrested.vo.ResultBuilder;
import com.lindar.wellrested.vo.WellRestedResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
public class GetAddressClient {

    public static final String START = "?";
    public static final String AND = "&";
    public static final String API_KEY_QUERY = "api-key=%s";

    private final GetAddressAPI API;
    private final String apiKey;

    /**
     * Creates a getAddress.io client with the default API root path:
     * https://api.getAddress.io/v2/uk/ . Please provide your valid API key. If
     * you don't have one you can register for a free account on:
     * https://getaddress.io/
     *
     * @param apiKey your valid getAddress.io API key.
     */
    public GetAddressClient(String apiKey) {
        this.API = new GetAddressAPI();
        this.apiKey = apiKey;
    }

    /**
     * Creates a getAddress.io client with a custom getAddress.io API root path
     * - useful for when you host your own instance of getAddress.io or the
     * default API changes and the library hasn't been updated yet. Please
     * provide your valid API key. If you don't have one you can register for a
     * free account on: https://getaddress.io/
     *
     * @param getAddressAPIRootpath the custom getAddress.io API root path
     * @param apiKey your valid getAddress.io API key.
     * @throws IllegalArgumentException when the argument provided is blank -
     * please use the empty constructor if you want to use the default API path
     */
    public GetAddressClient(String getAddressAPIRootpath, String apiKey) {
        if (StringUtils.isBlank(getAddressAPIRootpath)) {
            throw new IllegalArgumentException("You provided a blank getAddress API root path. If you want to use the default getAddress.io API root path then use the default constructor");
        }
        this.API = new GetAddressAPI(getAddressAPIRootpath);
        this.apiKey = apiKey;
    }

    /**
     * Lookup a postcode. Returns all available data if found. Returns 404 if
     * postcode does not exist. Returns 401 if not authorized and make sure you don't go over your daily limit!
     *
     * @param postcode
     * @return
     */
    public Result<PostcodeVO> lookupPostcode(String postcode) {
        return processGetRequestAndReturnResponse(String.format(API.LOOKUP_POSTCODE + START + API_KEY_QUERY, postcode, this.apiKey));
    }

    /**
     * Lookup a postcode and house number. Returns all available data if found.
     * Returns 404 if postcode does not exist.
     *
     * @param postcode
     * @param houseNumber
     * @return
     */
    public Result<PostcodeVO> lookupPostcodeAndHouseNumber(String postcode, int houseNumber) {
        return processGetRequestAndReturnResponse(String.format(API.LOOKUP_POSTCODE_AND_HOUSE_NUMBER + START + API_KEY_QUERY, postcode, houseNumber, apiKey));
    }

    /**
     * Returns a list of postcodes - please NOTE: Bulk Requests are not allowed for the free plan or the second account plan.
     * You need a 2000 requests or 10000 requests plan in order to make bulk requests otherwise you get a 401 Unauthorized response
     * @param postcodes
     * @return
     */
    public Result<List<PostcodeVO>> bulkLookupPostcodes(List<String> postcodes) {
        String url = String.format(API.BATCH_LOOKUP_POSTCODE
                + START + API_KEY_QUERY, StringUtils.join(postcodes, ","), apiKey);

        WellRestedResponse serverResponse = WellRestedRequest.builder().url(url).build().get().submit();

        ResultBuilder<List<PostcodeVO>> response = ResultBuilder.empty();
        if (serverResponse.isValid()) {
            Gson gson = new Gson();
            List<PostcodeVO> postcodeVOs = gson.fromJson(serverResponse.getServerResponse(), new TypeToken<List<PostcodeVO>>() {
            }.getType());
            response.data(postcodeVOs).success(true);
        } else {
            response.success(false);
        }
        return response.build();
    }

    private Result<PostcodeVO> processGetRequestAndReturnResponse(String url) {
        WellRestedResponse serverResponse = WellRestedRequest.builder().url(url).build().get().submit();

        return getResponseFromServerResponse(serverResponse);
    }

    private Result<PostcodeVO> getResponseFromServerResponse(WellRestedResponse serverResponse) {
        ResultBuilder<PostcodeVO> response = ResultBuilder.empty();
        if (serverResponse.isValid()) {
            Gson gson = new Gson();
            PostcodeVO postcodeVO = gson.fromJson(serverResponse.getServerResponse(), new TypeToken<PostcodeVO>() {}.getType());
            for (String address : postcodeVO.getAddresses()) {
                String[] addressComponents = address.split(",");
                if (addressComponents.length != 7) {
                    log.warn("Address provided appear to be invalid. Please check with getAddress.io and try again");
                    continue;
                }
                AddressVO addressVO = new AddressVO();
                addressVO.setLine1(addressComponents[0]);
                addressVO.setLine2(addressComponents[1]);
                addressVO.setLine3(addressComponents[2]);
                addressVO.setLine4(addressComponents[3]);
                addressVO.setLocality(addressComponents[4]);
                addressVO.setCity(addressComponents[5]);
                addressVO.setCounty(addressComponents[6]);
                postcodeVO.getCompiledAddresses().add(addressVO);
            }
            response.data(postcodeVO).success(true).visible(false);
        } else {
            response.msg("Invalid or nonexistent postcode").success(false).visible(true);
        }
        return response.build();
    }
}


text:
Disclaimer: This spec is still in development and can change without special notice!!!

## Basic notes
Most of syntax in Ivy language is based on directives. Directive consists of it's name followed by attributes.
In general case attribute can be any other `Ivy node`. But every directive has it's own syntax that describes
type of Ivy nodes in list of attributes, their count and order.
Ivy lang has set of basic directives that follow general directive syntax, but treated as special by Ivy compiler
and interpreter. They are: *if* conditional directive, *for* loop, *var* and *set* directives used to create
and assign variables in current execution scope.
One of them is *def* directive that is used to declare new directives in Ivy language itself. It has it's
own special syntax that is recognized by Ivy compiler. So compiler will compile new code object for it
and cache in module constants, so it could be invoked where needed after point of declaration.

## Def syntax description
In current stage of development of Ivy lang *def* directive syntax consists (at top level) of the following parts:
	def <directive name> (#
		<attribute definition directives>
	#);

For this stage of development followed definition directives are subject to implement (their name still can change):
1. def.kv - definition of block of key-value attributes. Basic syntax consists of directive name and list of attribute definitions:
	def.kv <attr definition>...
	Each attribute definition can follow one of the following forms.
	<attr name>
	<attr name> : <default value>
	<attr name> as <attr type>
	<attr name> : <default value> as <attr type>
	So attribut name is essential, but other attribute properties as default value or type are optional
	Let's paint some stupid example with list of definitions using forms descibed above:
	(# def.kv
		attrName1
		attrName2: "default str"
		attrName3 as int
		attrName4: "default str 2" as str
	#)

2. def.pos - definition of block of positional attributes. Syntax is exactly the same as for key-value attributes,
	but `def.pos` word is used.

3. def.kwd - definition of keyword. Exactly this name should be present in specified position
	Syntax is:
	def.kwd <keyword name>
	Only single keyword supported, because I think more has no sense for now
	Example:
	{# def.kwd in #}

4. def.names - definition of list of symbols that will be used to declare some identifiers inside directive.
	Spec is not developed and not implement yet

5. def.body - definition of block or expression that will not be calculated and shall be passed directly to dir body as AST
	Example: {# def.body #}


text:
/**
 * FILE Neighbour.cpp
 * AUTHOR Blackcatn13
 * DATE Jun 29, 2015
 * VERSION 1
 * This file contains the implementation of the Neighbour class.
 */

#include "Node/Neighbour/Neighbour.h"
#include <string>
#include <cstdint>
#include <vector>
#include <chrono>
#include "Utils/Logger.h"

Neighbour::Neighbour(const std::string &nodeId, const std::string &nodeAddress,
                     const uint16_t &nodePort,
                     std::vector<std::string> endpoints)
    : m_nodeId(nodeId),
      m_nodeAddress(nodeAddress),
      m_nodePort(nodePort),
      m_endpoints(endpoints),
      m_lastActivity(std::chrono::steady_clock::now()) {
  LOG(69) << "Creating new neighbour from parameters [nodeId: " << nodeId

  << "][nodeAddress: "
          << nodeAddress << "][nodePort: " << nodePort << "]";
}

Neighbour::~Neighbour() {
}

int Neighbour::getElapsedActivityTime() {
  LOG(69) << "Getting last activity time";
  std::chrono::nanoseconds now = std::chrono::steady_clock::now()
      - m_lastActivity;
  return now.count() * std::chrono::nanoseconds::period::num
      / std::chrono::nanoseconds::period::den;
}

void Neighbour::update(std::shared_ptr<Neighbour> neighbour) {
  LOG(69) << "Updating neighbour last activity time to now";
  m_nodeAddress = neighbour->getNodeAddress();
  m_nodePort = neighbour->getNodePort();
  m_endpoints = neighbour->getEndpoints();
  m_lastActivity = std::chrono::steady_clock::now();
}

bool Neighbour::operator ==(const Neighbour &neighbour) const {
  bool equals = m_nodeId == neighbour.m_nodeId;
  equals &= m_nodeAddress == neighbour.m_nodeAddress;
  equals &= m_nodePort == neighbour.m_nodePort;
  equals &= m_endpoints == neighbour.m_endpoints;
  return equals;
}

std::string Neighbour::getId() {
  return m_nodeId;
}

std::string Neighbour::getNodeAddress() {
  return m_nodeAddress;
}

uint16_t Neighbour::getNodePort() {
  return m_nodePort;
}

std::vector<std::string> Neighbour::getEndpoints() {
  return m_endpoints;
}


text:
import os

# Display sane URLs in the docs:
STATIC_URL = "/static/"

# Required by Django
SECRET_KEY = "foo"
SITE_ID = 1

INSTALLED_APPS = [
    "parser",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sites",
]

MIDDLEWARE = [
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
]

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": (),
        "OPTIONS": {
            "loaders": (
                "django.template.loaders.filesystem.Loader",
                "django.template.loaders.app_directories.Loader",
            )
        },
    }
]


text:
/**
 * Main package containing the Manta implementation of a COSBench
 * adapter.
 *
 * @author Elijah Zupancic
 */
package com.joyent.manta.cosbench;


text:
title: "Developing Rust"
slug: "contributions-rust"
excerpt: "Hacking on the Pants engine in Rust."
hidden: false
createdAt: "2020-05-16T23:11:31.121Z"
updatedAt: "2022-02-08T20:56:52.599Z"
---
We welcome contributions to Rust! We use Rust to implement the Pants engine in a performant, safe, and ergonomic way.

> 📘 Still learning Rust? Ask to get added to reviews
>
> We'd be happy to ping you on Rust changes we make for you to see how Rust is used in the wild. Please message us on the #engine channel in [Slack](doc:community) to let us know your interest.

> 🚧 Recommendation: share your plan first
>
> Because changes to Rust deeply impact how Pants runs, it is especially helpful to share any plans to work on Rust before making changes. Please message us on [Slack](doc:community) in the #engine channel or open a [GitHub issue](https://github.com/pantsbuild/pants/issues).

Code organization
-----------------

The code for the top-level Pants Rust crate lives in `src/rust/engine`. The top-level `Cargo.toml` file at `src/rust/engine/Cargo.toml` defines a cargo workspace containing a number of other subcrates, which live in subdirectories of `src/rust/engine`. Defining multiple subcrates in this way allows changes affecting one subcrate to avoid affecting other subcrates and triggering more recompilation than is necessary.

Several of the particularly important subcrates are:

- `graph`: the core of Pants's rule graph implementation.
- `ui`: the dynamic UI.
- `sharded_lmdb`: custom wrappers around the `crates.io` `lmdb` crate, which provides bindings to [lmdb](https://en.wikipedia.org/wiki/Lightning_Memory-Mapped_Database).
- `fs`: manipulating the filesystem.
- `process_execution`: running local and remote processes.

Rust \<-> Python interaction
----------------------------

Pants is best conceptualized as a Python program that makes frequent foreign function interface (FFI) calls into Rust code.

The top-level `engine` Rust crate gets compiled into a library named `native_engine.so`, which Python code knows how to interact with. We use the Rust [PyO3](https://pyo3.rs/) crate to manage foreign function interaction.

The C FFI functions that Rust code exposes as a public interface live in `src/rust/engine/src/externs/interface.rs`. On the Python side, `src/python/pants/engine/internals/native_engine.pyi` provides type hints for the functions and classes provided by Rust.

Rust can also invoke Python functions and object constructors thanks to [PyO3](https://pyo3.rs) crate.

We are planning to port additional functionality from Python to Rust, generally for performance reasons.

Common commands
---------------

Rather than using a global installation of Cargo, use the `./cargo` script.

### Compile

To check that the Rust code is valid, use `./cargo check`. To check that it integrates correctly with Pants' Python code, use `MODE=debug ./pants ...` as usual (which will `compile` first, and is slower than `check`).

> 🚧 Set `MODE=debug` when iterating on Rust
>
> As described in [Setting up Pants](doc:contributor-setup), we default to compiling Rust in release mode, rather than debug mode.
>
> When working on Rust, you typically should set the environment variable `MODE=debug` for substantially faster compiles.

### Run tests

To run tests for all crates, run:

```bash
./cargo test
```

To run for a specific crate, such as the `fs` create, run:

```bash
./cargo test -p fs
```

To run for a specific test, use Cargo's filtering mechanism, e.g.:

```bash
./cargo test -p fs read_file_missing
```

> 📘 Tip: enabling logging in tests
>
> When debugging, it can be helpful to capture logs with [`env_logger`](https://docs.rs/env_logger/0.6.1/env_logger/).
>
> To enable logging:
>
> 1. Add `env_logger = "..."` to `dev-dependencies` in the crate's `Cargo.toml`, replacing the `...` with the relevant version. Search for the version used in other crates.
> 2. At the start of your test, add `let _logger = env_logger::try_init();`.
> 3. Add log statements wherever you'd like using `log::info!()` et al.
> 4. Run your test with `RUST_LOG=trace ./cargo test -p $crate test_name -- --nocapture`, using one of `error`, `warn`, `info`, `debug`, or `trace`.

### Autoformat

```bash
./cargo fmt
```

To run in lint mode, add `--check`.

### Run Clippy

```bash
./cargo clippy
```

The `fs_util` tool
------------------

`fs_util` is a utility that enables you to interact with `Snapshot`s from the command line. You can use it to help debug issues with snapshotted files.

To build it, run this from the root of the repository:

```bash
$ ./cargo build -p fs_util
```

That will produce `src/rust/engine/target/debug/fs_util`.

To inspect a particular snapshot, you'll need to tell `fs_util` where the storage is and the digest and length of the snapshot to inspect. You can use the `--local-store-path` flag for that.

For example, this command pretty prints the recursive file list of a directory through the directory subcommand.

```bash
$ src/rust/engine/target/debug/fs_util --local-store-path=${HOME}/.cache/pants/lmdb_store directory cat-proto --output-format=recursive-file-list <digesh> <len>
```

Pass the `--help` flag to see other ways of using `fs_util`, along with its subcommands. Each subcommand can be passed the `--help` flag.


text:
namespace node {
class Environment;
class MultiIsolatePlatform;
}  // namespace node

namespace electron {

class MicrotasksRunner;
// Manage the V8 isolate and context automatically.
class JavascriptEnvironment {
 public:
  explicit JavascriptEnvironment(uv_loop_t* event_loop);
  ~JavascriptEnvironment();

  // disable copy
  JavascriptEnvironment(const JavascriptEnvironment&) = delete;
  JavascriptEnvironment& operator=(const JavascriptEnvironment&) = delete;

  void CreateMicrotasksRunner();
  void DestroyMicrotasksRunner();

  node::MultiIsolatePlatform* platform() const { return platform_.get(); }
  v8::Isolate* isolate() const { return isolate_; }
  v8::Local<v8::Context> context() const {
    return v8::Local<v8::Context>::New(isolate_, context_);
  }

  static v8::Isolate* GetIsolate();

 private:
  v8::Isolate* Initialize(uv_loop_t* event_loop);
  std::unique_ptr<node::MultiIsolatePlatform> platform_;

  v8::Isolate* isolate_;
  gin::IsolateHolder isolate_holder_;
  v8::Locker locker_;
  v8::Global<v8::Context> context_;

  std::unique_ptr<MicrotasksRunner> microtasks_runner_;
};

// Manage the Node Environment automatically.
class NodeEnvironment {
 public:
  explicit NodeEnvironment(node::Environment* env);
  ~NodeEnvironment();

  // disable copy
  NodeEnvironment(const NodeEnvironment&) = delete;
  NodeEnvironment& operator=(const NodeEnvironment&) = delete;

  node::Environment* env() { return env_; }

 private:
  node::Environment* env_;
};

}  // namespace electron

#endif  // ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_


text:
package test;

/**
 * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info)
 */
public class EngineException extends RuntimeException {
    public EngineException(final String message, final Throwable cause) {
        super(message, cause);
    }
}


text:
#ifndef SFNTLY_CPP_SRC_SFNTLY_TABLE_CORE_HORIZONTAL_HEADER_TABLE_H_
#define SFNTLY_CPP_SRC_SFNTLY_TABLE_CORE_HORIZONTAL_HEADER_TABLE_H_

#include "sfntly/table/table.h"
#include "sfntly/table/table_based_table_builder.h"

namespace sfntly {

// A Horizontal Header table - 'hhea'.
class HorizontalHeaderTable : public Table,
                              public RefCounted<HorizontalHeaderTable> {
 public:
  // Builder for a Horizontal Header table - 'hhea'.
  class Builder : public TableBasedTableBuilder, public RefCounted<Builder> {
   public:
    // Constructor scope altered to public because C++ does not allow base
    // class to instantiate derived class with protected constructors.
    Builder(Header* header, WritableFontData* data);
    Builder(Header* header, ReadableFontData* data);
    virtual ~Builder();
    virtual CALLER_ATTACH FontDataTable* SubBuildTable(ReadableFontData* data);

    static CALLER_ATTACH Builder* CreateBuilder(Header* header,
                                                WritableFontData* data);

    int32_t TableVersion();
    void SetTableVersion(int32_t version);
    int32_t Ascender();
    void SetAscender(int32_t ascender);
    int32_t Descender();
    void SetDescender(int32_t descender);
    int32_t LineGap();
    void SetLineGap(int32_t line_gap);
    int32_t AdvanceWidthMax();
    void SetAdvanceWidthMax(int32_t value);
    int32_t MinLeftSideBearing();
    void SetMinLeftSideBearing(int32_t value);
    int32_t MinRightSideBearing();
    void SetMinRightSideBearing(int32_t value);
    int32_t XMaxExtent();
    void SetXMaxExtent(int32_t value);
    int32_t CaretSlopeRise();
    void SetCaretSlopeRise(int32_t value);
    int32_t CaretSlopeRun();
    void SetCaretSlopeRun(int32_t value);
    int32_t CaretOffset();
    void SetCaretOffset(int32_t value);
    int32_t MetricDataFormat();
    void SetMetricDataFormat(int32_t value);
    int32_t NumberOfHMetrics();
    void SetNumberOfHMetrics(int32_t value);
  };

  virtual ~HorizontalHeaderTable();
  int32_t TableVersion();
  int32_t Ascender();
  int32_t Descender();
  int32_t LineGap();
  int32_t AdvanceWidthMax();
  int32_t MinLeftSideBearing();
  int32_t MinRightSideBearing();
  int32_t XMaxExtent();
  int32_t CaretSlopeRise();
  int32_t CaretSlopeRun();
  int32_t CaretOffset();
  int32_t MetricDataFormat();
  int32_t NumberOfHMetrics();

 private:
  struct Offset {
    enum {
      kVersion = 0,
      kAscender = 4,
      kDescender = 6,
      kLineGap = 8,
      kAdvanceWidthMax = 10,
      kMinLeftSideBearing = 12,
      kMinRightSideBearing = 14,
      kXMaxExtent = 16,
      kCaretSlopeRise = 18,
      kCaretSlopeRun = 20,
      kCaretOffset = 22,
      kMetricDataFormat = 32,
      kNumberOfHMetrics = 34,
    };
  };

  HorizontalHeaderTable(Header* header, ReadableFontData* data);
};
typedef Ptr<HorizontalHeaderTable> HorizontalHeaderTablePtr;
typedef Ptr<HorizontalHeaderTable::Builder> HorizontalHeaderTableBuilderPtr;

}  // namespace sfntly

#endif  // SFNTLY_CPP_SRC_SFNTLY_TABLE_CORE_HORIZONTAL_HEADER_TABLE_H_


text:
var dogescript = require('../../');

var input  = document.getElementsByClassName('dogescript')[0];
var output = document.getElementsByClassName('javascript')[0];

input.addEventListener('keyup', function () {
    output.value = dogescript(input.value, true);
});

output.value = dogescript(input.value, true);

rundoge = function(src)
{
  window.eval(dogescript(src));
}


text:
package huajiteam.zhuhaibus;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Timer;
import java.util.TimerTask;

import huajiteam.zhuhaibus.zhdata.data.BusLineInfo;
import huajiteam.zhuhaibus.zhdata.GetBusInfo;
import huajiteam.zhuhaibus.zhdata.data.OnlineBusInfo;
import huajiteam.zhuhaibus.zhdata.data.StationInfo;
import huajiteam.zhuhaibus.zhdata.exceptions.HttpCodeInvalidException;

public class OnlineBusActivity extends AppCompatActivity {

    BusLineInfo busLineInfo;
    GetConfig config;
    StationInfo[] stationInfos = null;
    OnlineBusInfo[] onlineBusInfos = null;
    Timer timer;
    MAdapter mAdapter = null;
    ListView listView;
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;

    private ProgressDialog progressDialog;

    boolean firstRun = true;
    boolean timerRunning = false;

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (config.getWaitTime() <= 0) {
                        new Thread(new UpdateOnlineBuses(config, busLineInfo)).start();
                        timerRunning = false;
                    } else {
                        if (stationInfos == null) {
                            return;
                        }
                        if (timerRunning) {
                            timer.cancel();
                        }
                        timer = new Timer();
                        timer.schedule(new UpdateOnlineBuses(config, busLineInfo), 0, config.getWaitTime() * 1000);
                        timerRunning = true;
                    }
                    break;
                case 1:
                    if (!firstRun) {
                        return;
                    }
                    firstRun = false;
                    if (stationInfos == null) {
                        new Thread(new GetStation(config, busLineInfo)).start();
                        setFirstRun();
                        return;
                    }
                    onlineBusInfos = (OnlineBusInfo[]) msg.obj;
                    mAdapter = new MAdapter(OnlineBusActivity.this);
                    if (listView != null) {
                        listView.setAdapter(mAdapter);
                    }
                    progressDialog.dismiss();
                    break;
                case 2:
                    if (config.getAutoFlushNotice()) {
                        makeSnackbar("少女祈祷中...");
                    }
                    onlineBusInfos = (OnlineBusInfo[]) msg.obj;
                    mAdapter.notifyDataSetChanged();
                    break;
                case -1:
                    makeAlert("出现了一个错误", "未知错误: " + msg.obj);
                    if (firstRun) {
                        progressDialog.dismiss();
                    }
                    break;
                case -1001:
                    makeSnackbar(getString(R.string.error_api_invalid));
                    if (firstRun) {
                        progressDialog.dismiss();
                    }
                    break;
                case -1003:
                    makeSnackbar(getString(R.string.network_error));
                    if (firstRun) {
                        progressDialog.dismiss();
                    }
                    break;
                case -2:
                    makeAlert("出现了一个错误", "未知错误: " + msg.obj);
                    timer.cancel();
                    timerRunning = false;
                    break;
                case -2001:
                    makeSnackbar(getString(R.string.error_api_invalid));
                    timer.cancel();
                    timerRunning = false;
                    break;
                case -2003:
                    makeSnackbar(getString(R.string.network_error));
                    timer.cancel();
                    timerRunning = false;
                    break;
                default:
                    makeSnackbar("噫");
                    if (firstRun) {
                        progressDialog.dismiss();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_bus);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getDelegate().getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        Bundle bundle = getIntent().getExtras();
        this.busLineInfo = (BusLineInfo) bundle.get("busLineInfo");
        this.config = new GetConfig(this);

        listView = (ListView) findViewById(R.id.onlineBusListView);
        this.progressDialog = ProgressDialog.show(this, getString(R.string.waiting), getString(R.string.loading));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(OnlineBusActivity.this, StationOptionsSelectActivity.class);
                intent.putExtra("stationName", stationInfos[position].getName());
                intent.putExtra("busLineInfo", busLineInfo);
                startActivity(intent);
            }
        });

        new Thread(new GetStation(config, busLineInfo)).start();

        FloatingActionButton reflushButton = (FloatingActionButton) findViewById(R.id.flushButton);
        reflushButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!config.getAutoFlushNotice()) {
                    makeSnackbar(getString(R.string.loading));
                    progressDialog = ProgressDialog.show(OnlineBusActivity.this, getString(R.string.waiting), getString(R.string.loading));
                    setFirstRun();
                }
                if (stationInfos == null) {
                    new Thread(new GetStation(config, busLineInfo)).start();
                    timer = new Timer();
                } else {
                    if (config.getWaitTime() == 0) {
                        new Thread(new UpdateOnlineBuses(config, busLineInfo)).start();
                        timerRunning = false;
                    } else {
                        timer.cancel();
                        timer = new Timer();
                        timer.schedule(new UpdateOnlineBuses(config, busLineInfo), 200, config.getWaitTime() * 1000);
                        timerRunning = true;
                    }
                }
            }
        });

        if (config.getAlwaysDisplay()) {
            powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ZHBUS");
        }
    }

    protected void onResume() {
        if (config.getWaitTime() != 0) {
            if (!timerRunning) {
                timer = new Timer();
                timer.schedule(new UpdateOnlineBuses(config, busLineInfo), 200, config.getWaitTime() * 1000);
                timerRunning = true;
            }
        }
        if (wakeLock != null) {
            wakeLock.acquire();
        }
        super.onResume();
    }

    protected void onPause() {
        if (timerRunning) {
            if (!firstRun) {
                timer.cancel();
                timerRunning = false;
            }
        }
        if (wakeLock != null) {
            wakeLock.release();
        }
        super.onPause();
    }

    protected void onStop() {
        if (timerRunning) {
            timer.cancel();
        }
        super.onStop();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void makeSnackbar(String content) {
        Snackbar.make(findViewById(R.id.toolbar), content, Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }

    private void makeAlert(String title, String content) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton(getString(R.string.okay),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
    }

    private void setFirstRun() {
        this.firstRun = true;
        if (this.timer != null) {
            try {
                this.timer.cancel();
            } catch (Exception e) {
                // Pass
            }
            this.timer = null;
        }
        this.timerRunning = false;
    }

    public final class ViewHolder {
        ImageView statusImg;
        TextView stationName;
        TextView onlineBuses;
    }

    class GetStation implements Runnable {

        GetConfig config;
        BusLineInfo busLineInfo;

        GetStation(GetConfig config, BusLineInfo busLineInfo) {
            this.config = config;
            this.busLineInfo = busLineInfo;
        }

        @Override
        public void run() {
            try {
                if (stationInfos != null) {
                    return;
                }
                if (config.getEnableStaticIP()) {
                    stationInfos = new GetBusInfo().getStationInfo(
                            this.config.getBusApiUrl() ,
                            this.busLineInfo.getID(),
                            config.getStataicIP()
                    );
                } else {
                    stationInfos = new GetBusInfo().getStationInfo(
                            this.config.getBusApiUrl(),
                            this.busLineInfo.getID()
                    );
                }
            } catch (HttpCodeInvalidException |
                    StringIndexOutOfBoundsException |
                    JsonSyntaxException |
                    IllegalArgumentException e) {
                mHandler.obtainMessage(-1001).sendToTarget();
                return;
            } catch (UnknownHostException | SocketTimeoutException | ConnectException e) {
                mHandler.obtainMessage(-1003).sendToTarget();
                return;
            } catch (IOException e) {
                if (e.toString().contains("okhttp3.Address@")) {
                    mHandler.obtainMessage(-1003).sendToTarget();
                } else {
                    mHandler.obtainMessage(-1, e.toString()).sendToTarget();
                }
                return;
            } catch (Exception e) {
                mHandler.obtainMessage(-1, e.toString()).sendToTarget();
                return;
            }
            if (stationInfos == null) {
                mHandler.obtainMessage(-1003).sendToTarget();
                return;
            } else {
                mHandler.obtainMessage(0).sendToTarget();
            }
        }
    }

    class UpdateOnlineBuses extends TimerTask {

        BusLineInfo busLineInfo;
        GetConfig config;

        UpdateOnlineBuses(GetConfig config, BusLineInfo busLineInfo) {
            this.config = config;
            this.busLineInfo = busLineInfo;
        }

        @Override
        public void run() {
            OnlineBusInfo[] onlineBusInfos;
            try {
                if (config.getEnableStaticIP()) {
                    onlineBusInfos = new GetBusInfo().getOnlineBusInfo(
                            this.config.getBusApiUrl() ,
                            this.busLineInfo.getName() ,
                            this.busLineInfo.getFromStation(),
                            config.getStataicIP()
                    );
                } else {
                    onlineBusInfos = new GetBusInfo().getOnlineBusInfo(
                            this.config.getBusApiUrl() ,
                            this.busLineInfo.getName() ,
                            this.busLineInfo.getFromStation()
                    );
                }
            } catch (HttpCodeInvalidException |
                    StringIndexOutOfBoundsException |
                    JsonSyntaxException |
                    IllegalArgumentException e) {
                mHandler.obtainMessage(-2001).sendToTarget();
                return;
            } catch (UnknownHostException | SocketTimeoutException | ConnectException e) {
                mHandler.obtainMessage(-2003).sendToTarget();
                return;
            } catch (IOException e) {
                if (e.toString().contains("okhttp3.Address@")) {
                    mHandler.obtainMessage(-2003).sendToTarget();
                } else {
                    mHandler.obtainMessage(-2, e.toString()).sendToTarget();
                }
                return;
            }
            if (onlineBusInfos == null) {
                onlineBusInfos = new OnlineBusInfo[0];
            }
            if (firstRun) {
                mHandler.obtainMessage(1, onlineBusInfos).sendToTarget();
            } else {
                mHandler.obtainMessage(2, onlineBusInfos).sendToTarget();
            }
        }
    }

    public class MAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        MAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return stationInfos.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;

            final StationInfo stationInfo = stationInfos[position];
            if (convertView == null) {
                viewHolder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.display_online_bus, null);
                viewHolder.statusImg = (ImageView) convertView.findViewById(R.id.onlineBusImg);
                viewHolder.stationName = (TextView) convertView.findViewById(R.id.stationName);
                viewHolder.onlineBuses = (TextView) convertView.findViewById(R.id.onlineBuses);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            GetDisplayImg getDisplayImg = new GetDisplayImg();

            String onlineBus = "";
            int olBusCount = 0;

            if (onlineBusInfos.length > 0) {
                for (OnlineBusInfo data : onlineBusInfos) {
                    if (data.getCurrentStation().equals(stationInfo.getName())) {
                        onlineBus = onlineBus + data.getBusNumber() + "; ";
                        olBusCount++;
                    }
                }
            } else {
                if (config.getTitleIsBus()) {
                    viewHolder.stationName.setText("");
                } else  {
                    viewHolder.onlineBuses.setText("");
                }
                if (!getDisplayImg.getIsNone()) {
                    viewHolder.statusImg.setImageDrawable(getDisplayImg.getNoBusDrawable());
                }
            }

            if (config.getTitleIsBus()) {
                if (olBusCount != 0) {
                    viewHolder.stationName.setText(onlineBus.substring(0, onlineBus.length() - 2));
                } else {
                    viewHolder.stationName.setText("");
                }
                viewHolder.onlineBuses.setText(stationInfo.getName() + ",共有 " + olBusCount + " 辆车");
            } else  {
                viewHolder.stationName.setText(stationInfo.getName());
                if (olBusCount != 0) {
                    viewHolder.onlineBuses.setText(onlineBus.substring(0, onlineBus.length() - 2) + ",共有 " + olBusCount + " 辆车");
                } else {
                    viewHolder.onlineBuses.setText("该站无车");
                }
            }
            if (!getDisplayImg.getIsNone()) {
                if (!onlineBus.equals("")) {
                    viewHolder.statusImg.setImageDrawable(getDisplayImg.getHaveBusDrawable());
                } else {
                    viewHolder.statusImg.setImageDrawable(getDisplayImg.getNoBusDrawable());
                }
            } else {
                viewHolder.statusImg.getLayoutParams().width = 0;
            }
            return convertView;
        }
    }

    class GetDisplayImg {
        private Drawable haveBusDrawable = null;
        private Drawable noBusDrawable = null;
        private Boolean isNone = false;

        GetDisplayImg() {
            switch (config.getHintLogo()) {
                case "apple_moon_emoji":
                    this.noBusDrawable = getImg(R.drawable.hint_icon_apple_black_moon_emoji);
                    this.haveBusDrawable = getImg(R.drawable.hint_icon_apple_yellow_moon_emoji);
                    return;
                case "google_moon_emoji":
                    this.noBusDrawable = getImg(R.drawable.hint_icon_google_black_moon_emoji);
                    this.haveBusDrawable = getImg(R.drawable.hint_icon_google_yellow_moon_emoji);
                    return;
                case "md_circle":
                    this.noBusDrawable = getImg(R.drawable.hint_icon_md_circle_2);
                    this.haveBusDrawable = getImg(R.drawable.hint_icon_md_circle_1);
                    return;
                case "md_bus":
                    this.noBusDrawable = null;
                    this.haveBusDrawable = getImg(R.drawable.hint_icon_md_bus);
                    return;
                case "classic_bus":
                    this.noBusDrawable = null;
                    this.haveBusDrawable = getImg(R.drawable.hint_icon_classic_bus);
                    return;
                case "none":
                    this.noBusDrawable = null;
                    this.haveBusDrawable = null;
                    this.isNone = true;
                    return;
                default:
                    this.noBusDrawable = getImg(R.drawable.hint_icon_apple_black_moon_emoji);
                    this.haveBusDrawable = getImg(R.drawable.hint_icon_apple_yellow_moon_emoji);
            }
            this.isNone = haveBusDrawable == null && noBusDrawable == null;
        }

        private Drawable getImg(int imgId) {
            return getResources().getDrawable(imgId);
        }

        Boolean getIsNone() {
            return this.isNone;
        }

        Drawable getHaveBusDrawable() {
            return this.haveBusDrawable;
        }

        Drawable getNoBusDrawable() {
            return this.noBusDrawable;
        }
    }
}


text:
const scriptUrl = '_test_resources/api_test/webnavigation/framework.js';
let loadScript = chrome.test.loadScript(scriptUrl);

loadScript.then(async function() {
  debug = true;
  let getURL = chrome.extension.getURL;
  let tab = await promise(chrome.tabs.create, {"url": "about:blank"});
  let config = await promise(chrome.test.getConfig);
  let port = config.testServer.port;
  let URL_MAIN = getURL('main.html');
  let PATH_FRAME =
    '/extensions/api_test/webnavigation/crossProcessIframe/frame.html';
  let URL_FRAME1 = 'http://a.com:' + port + PATH_FRAME;
  let URL_FRAME2 = 'http://b.com:' + port + PATH_FRAME;
  let URL_FRAME3 = 'http://c.com:' + port + PATH_FRAME;
  chrome.test.runTests([
    // Navigates from an extension page to a HTTP page which causes a
    // process switch. The extension page embeds a same-process iframe which
    // embeds another frame that navigates three times (cross-process):
    // c. Loaded by the parent frame.
    // d. Navigated by the parent frame.
    // e. Navigated by the child frame.
    // Tests whether the frameId stays constant across navigations.
    function crossProcessIframe() {
      expect([
        { label: 'main-onBeforeNavigate',
          event: 'onBeforeNavigate',
          details: { documentLifecycle: "active",
                     frameId: 0,
                     frameType: "outermost_frame",
                     parentFrameId: -1,
                     processId: -1,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_MAIN }},
        { label: 'main-onCommitted',
          event: 'onCommitted',
          details: { documentId: 1,
                     documentLifecycle: "active",
                     frameId: 0,
                     frameType: "outermost_frame",
                     parentFrameId: -1,
                     processId: 0,
                     tabId: 0,
                     timeStamp: 0,
                     transitionQualifiers: [],
                     transitionType: 'link',
                     url: URL_MAIN }},
        { label: 'main-onDOMContentLoaded',
          event: 'onDOMContentLoaded',
          details: { documentId: 1,
                     documentLifecycle: "active",
                     frameId: 0,
                     frameType: "outermost_frame",
                     parentFrameId: -1,
                     processId: 0,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_MAIN }},
        { label: 'main-onCompleted',
          event: 'onCompleted',
          details: { documentId: 1,
                     documentLifecycle: "active",
                     frameId: 0,
                     frameType: "outermost_frame",
                     parentFrameId: -1,
                     processId: 0,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_MAIN }},
        { label: 'a.com-onBeforeNavigate',
          event: 'onBeforeNavigate',
          details: { documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: -1,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME1 }},
        { label: 'a.com-onCommitted',
          event: 'onCommitted',
          details: { documentId: 2,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 1,
                     tabId: 0,
                     timeStamp: 0,
                     transitionQualifiers: [],
                     transitionType: 'auto_subframe',
                     url: URL_FRAME1 }},
        { label: 'a.com-onDOMContentLoaded',
          event: 'onDOMContentLoaded',
          details: { documentId: 2,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 1,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME1 }},
        { label: 'a.com-onCompleted',
          event: 'onCompleted',
          details: { documentId: 2,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 1,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME1 }},
        { label: 'b.com-onBeforeNavigate',
          event: 'onBeforeNavigate',
          details: { documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: -1,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME2 }},
        { label: 'b.com-onCommitted',
          event: 'onCommitted',
          details: { documentId: 3,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 2,
                     tabId: 0,
                     timeStamp: 0,
                     transitionQualifiers: [],
                     transitionType: 'manual_subframe',
                     url: URL_FRAME2 }},
        { label: 'b.com-onDOMContentLoaded',
          event: 'onDOMContentLoaded',
          details: { documentId: 3,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 2,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME2 }},
        { label: 'b.com-onCompleted',
          event: 'onCompleted',
          details: { documentId: 3,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 2,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME2 }},
        { label: 'c.com-onBeforeNavigate',
          event: 'onBeforeNavigate',
          details: { documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: -1,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME3 }},
        { label: 'c.com-onCommitted',
          event: 'onCommitted',
          details: { documentId: 4,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 3,
                     tabId: 0,
                     timeStamp: 0,
                     transitionQualifiers: [],
                     transitionType: 'manual_subframe',
                     url: URL_FRAME3 }},
        { label: 'c.com-onDOMContentLoaded',
          event: 'onDOMContentLoaded',
          details: { documentId: 4,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 3,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME3 }},
        { label: 'c.com-onCompleted',
          event: 'onCompleted',
          details: { documentId: 4,
                     documentLifecycle: "active",
                     frameId: 1,
                     frameType: "sub_frame",
                     parentDocumentId: 1,
                     parentFrameId: 0,
                     processId: 3,
                     tabId: 0,
                     timeStamp: 0,
                     url: URL_FRAME3 }}],
        [
          navigationOrder('main-'),
          navigationOrder('a.com-'),
          navigationOrder('b.com-'),
          navigationOrder('c.com-'),
          ['a.com-onCommitted', 'b.com-onBeforeNavigate'],
          ['b.com-onCommitted', 'c.com-onBeforeNavigate'],
        ]);

      chrome.tabs.update(tab.id, {url: URL_MAIN + '?' + port});
    },

  ]);
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright (C) 2006-2007 the original author or authors.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

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

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

<!-- $Id$ -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.codehaus.gmaven.it.gmaven-testsuite.mojo</groupId>
        <artifactId>mojo-1</artifactId>
        <version>@project.version@</version>
    </parent>

    <artifactId>module</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>${pom.groupId}</groupId>
                <artifactId>plugin</artifactId>
                <version>@project.version@</version>

                <executions>
                    <execution>
                        <id>1</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>mymojo</goal>
                        </goals>
                    </execution>

                    <execution>
                        <id>2</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>mygroovymojo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. N. Y. St. Mus. 85 (1923)

#### Original name
Glomerularia lonicerae Dearn. & House, 1923

### Remarks
null


text:
typedef void (^BEPRefreshCompletionHandler)(BOOL didReceiveNewImage, NSError* error);

@interface BEPBackgroundDownloadHandler : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate, UITableViewDataSource>

+ (instancetype) sharedInstance;

- (void) refreshWithCompletionHandler:(BEPRefreshCompletionHandler)completionHandler;

@end


text:
import logging
from typing import Dict, List

import aiohttp.web
import aiohttp.web_request

from app.clients.github_client import GithubClient
from app.clients.mongo_client import MongoClient
from app.enums.event_types import EventType
from app.mongo.clear_query import ClearQuery
from app.mongo.deregistration_query import DeregistrationQuery
from app.mongo.registration_query import RegistrationQuery
from app.request_schemes.clear_request_data import ClearRequestData
from app.request_schemes.comment_request_data import CommentRequestData
from app.request_schemes.deployment_request_data import DeploymentRequestData
from app.request_schemes.deployment_status_request_data import DeploymentStatusRequestData
from app.request_schemes.deregister_request_data import DeregisterRequestData
from app.request_schemes.register_request_data import RegisterRequestData
from app.request_schemes.status_request_data import StatusRequestData

class PipelineController:
    def __init__(self,
                 github_client: GithubClient,
                 mongo_client: MongoClient) -> None:
        self.__gh_client: GithubClient = github_client
        self.__mongo_client: MongoClient = mongo_client

    def get_github(self) -> GithubClient:
        return self.__gh_client

    async def handle_register(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data: Dict = await request.json()
        logging.warning(f"Register REQ received: {data}")
        if not RegisterRequestData.is_valid_register_request_data(data):
            return aiohttp.web.Response(reason='Invalid register request params!', status=400)
        await self.__mongo_client.add_or_update_registration(RegistrationQuery.from_registration_request_data(data))
        return aiohttp.web.Response(text='Register ACK')

    async def handle_missing(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        event_type = request.match_info.get('eventType')
        logging.warning(f"Missing REQ received for: {event_type}")
        if event_type not in EventType.get_allowed_registration_event_types():
            return aiohttp.web.Response(status=400, text='Invalid eventType requested')
        return aiohttp.web.Response(text=','.join(await self.__mongo_client.get_missed_info(event_type)))

    async def handle_deregister(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data: Dict = await request.json()
        logging.warning(f"Deregister REQ received: {data}")
        if not DeregisterRequestData.is_valid_deregister_request_data(data):
            return aiohttp.web.Response(reason='Invalid deregister request params!', status=400)
        await self.__mongo_client.deregister(DeregistrationQuery.from_deregistration_request_data(data))
        return aiohttp.web.Response(text=f'Deregistration of {data[DeregisterRequestData.job_name]} '
                                         f'for {data[DeregisterRequestData.event_type]} succeeded')

    async def handle_clear(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data: Dict = await request.json()
        logging.warning(f"Clear REQ received: {data}")
        if not ClearRequestData.is_valid_clear_request_data(data):
            return aiohttp.web.Response(reason='Invalid clear request params!', status=400)
        clear_query = ClearQuery.from_clear_request_data(data)
        await self.__mongo_client.clear(clear_query)
        return aiohttp.web.Response(text=f'Clear of {clear_query.job_name} missed counter succeeded')

    async def handle_status(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data = await request.json()
        if not StatusRequestData.is_valid_status_data(data):
            return aiohttp.web.Response(reason='Invalid status request params!', status=400)
        logging.warning(f"Status REQ received: {data}")
        await self.get_github().create_github_build_status(
            repo=data['repository'],
            sha=data['sha'],
            state=data['state'],
            description=data['description'],
            url=data['url'],
            context=data['context']
        )
        return aiohttp.web.Response(text='Status ACK')

    async def handle_comment(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data = await request.json()
        if not CommentRequestData.is_valid_comment_data(data):
            return aiohttp.web.Response(reason='Invalid comment request params!', status=400)
        logging.warning(f"Comment REQ received: {data}")
        await self.get_github().create_comment(
            repo=data['repository'],
            sha=data['sha'],
            body=data['jobName'] + "\nComments: " + data['body'],
        )
        return aiohttp.web.Response(text='Comment ACK')

    async def handle_deployment(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data: Dict = await request.json()
        logging.warning(f'Deployment request received: {data}')
        if not DeploymentRequestData.is_valid_deployment_request_data(data):
            return aiohttp.web.Response(reason='Invalid deployment request payload!', status=400)
        await self.get_github().create_deployment(repo=data[DeploymentRequestData.repo],
                                                  ref=data[DeploymentRequestData.ref],
                                                  environment=data[DeploymentRequestData.environment],
                                                  description=data[DeploymentRequestData.description])
        return aiohttp.web.Response(text='Deployment ACK')

    async def handle_deployment_status(self, request: aiohttp.web_request.Request) -> aiohttp.web.Response:
        data: Dict = await request.json()
        logging.warning(f'Deployment status request received: {data}')
        if not DeploymentStatusRequestData.is_valid_deployment_status_request_data(data):
            return aiohttp.web.Response(reason='Invalid deployment status request payload!', status=400)
        deployments: List = await self.get_github().get_deployments(repo=data[DeploymentRequestData.repo],
                                                                    ref=data[DeploymentRequestData.ref],
                                                                    environment=data[DeploymentRequestData.environment])

        deployment_matcher = {
            'environment': data[DeploymentRequestData.environment],
            'ref': data[DeploymentRequestData.ref],
            'description': data[DeploymentRequestData.description]
        }
        for deployment in deployments:
            match = {k: deployment[k] for k in deployment_matcher.keys()}
            if match == deployment_matcher:
                await self.get_github().create_deployment_status(repo=data[DeploymentRequestData.repo],
                                                                 deployment_id=deployment['id'],
                                                                 state=data[DeploymentStatusRequestData.state],
                                                                 target_url=data[DeploymentStatusRequestData.target_url],
                                                                 description=data[DeploymentStatusRequestData.description])
                return aiohttp.web.Response(text='Deployment status ACK')
        logging.error(f'Deployment matching {deployment_matcher} not found')
        return aiohttp.web.Response(reason=f'Deployment matching {deployment_matcher} not found', status=404)


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Saml2.Properties;

namespace dk.nita.saml20.config
{
    /// <summary>
    /// Container for a list of strings (from config) that represent wellformed absolute audience uris
    /// </summary>
    public class AudienceUris
    {
        private List<string> _audiences;

        /// <summary>
        /// Gets or sets the audiences.
        /// </summary>
        /// <value>The audiences.</value>
        [XmlElement("Audience")]
        public List<string> Audiences
        {
            get { return _audiences; }
            set
            {
                ValidateUris(value);
                _audiences = value;
            }
        }

        /// <summary>
        /// Validates the wellformedness of a list of uri strings.
        /// </summary>
        /// <param name="value">The value.</param>
        private void ValidateUris(IEnumerable<string> value)
        {
            if (value == null)
                return;

            foreach (string uri in value)
            {
                if (Uri.IsWellFormedUriString(uri, UriKind.Absolute))
                    continue;

                throw new FormatException(Resources.InvalidWellformedAbsoluteUriStringFormat(uri));
            }
        }
    }
}


text:
Article 1173
----
La condition de ne pas faire une chose impossible ne rend pas nulle l'obligation
contractée sous cette condition.


text:
set -e

if [ "$#" -ne 1 ]; then
  echo "Usage: $0 <dask version>"
  exit 1
fi

dask=$1

if [ "${dask}" = "master" ]; then
  pip install https://github.com/dask/dask/archive/master.tar.gz#egg=dask[dataframe]
elif [ "${dask}" = "latest" ]; then
  conda install -q dask
else
  conda install -q dask=${dask}
fi
conda clean --all


text:
/*
UI functions dedicated to the Twitter modal panel
*/

var twitter_api_user = 'https://twitter.com/users/';
var twitter_api_timeline = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=';
var twitter_api_json = '.json';

var spinner = (new Spinner(spin_opts)).spin();
var template = null;
var url = null;
var twitter_data = {};

$('a[id^="Twitter-link"]').click(function (e)
{
    var url = prepare_link(e, this);
    adjustSelection("Twitter-link");
    remove_modal();
    showTwitter(url, this);
});

function showTwitter(e, t) {
    url = t.href;
    var twitter_profile = $("#twitter-profile");
    if (twitter_profile.length > 0) {
        twitter_profile.modal('show');
    }
    else {
        $("#Twitter-link").append(spinner.el);

        $.get('/theme/templates/twitter-view.html', function(data) {
            // Request succeeded, data contains HTML template, we can load data
            template = Handlebars.compile(data);
            var user_url = twitter_api_user+twitter_username+twitter_api_json;

            try {
                $.ajax({
                    url: user_url,
                    dataType: "jsonp",
                    jsonpCallback: "readTwitterData",
                    error: function(s, statusCode, errorThrown) {
                        window.location.href = url;
                        spinner.stop();
                    }
                });
            }
            catch (err) {
                window.location.href = url;
                spinner.stop();
            }
        })
        .error(function() {
            window.location.href = url;
            spinner.stop();
        });
    }
}

function readTwitterData(user) {
    try {
        user.statuses_count = numberWithCommas(user.statuses_count);
        user.friends_count = numberWithCommas(user.friends_count);
        user.followers_count = numberWithCommas(user.followers_count);
        user.description = twitterLinkify(user.description);
        twitter_data['user'] = user

        var tweets_url = twitter_api_timeline+twitter_username;
        $.ajax({
            url: tweets_url,
            dataType: "jsonp",
            jsonpCallback: "readTweets",
            error: function(s, statusCode, errorThrown) {
                window.location.href = url;
                spinner.stop();
            }
        });
    }
    catch (err) {
        window.location.href = url;
        spinner.stop();
    }
}

function readTweets(tweets) {
    try {
        for(var index = 0 ; index < tweets.length ; index++) {
            var tweet = tweets[index];
            tweet.formated_date = moment(tweet.created_at).fromNow();
            tweet.text = twitterLinkify(tweet.text);
        }
        twitter_data['tweets'] = tweets

        var html = template(twitter_data);
        $('body').append(html);
        $("#twitter-profile").modal();
        spinner.stop();
    }
    catch (err) {
        window.location.href = url;
        spinner.stop();
    }
}

function twitterLinkify(e) {
    return e = e.replace(/(https?:\/\/\S+)/gi, function (e) {
        return '' + e + ""
    }), e = e.replace(/(^|) @(\w+)/gi, function (e) {
        return '' + e + ""
    }), e = e.replace(/(^|) #(\w+)/gi, function (e) {
        return '' + e + ""
    }), e
}


text:
package com.rotka.watcher;

import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

public class MotionWatcher
{
  private String directoryToWatch;
  IMotionEvent me;

  public MotionWatcher(String directoryToWatch, IMotionEvent event) {
    this.directoryToWatch = directoryToWatch;
    this.me = event;
  }

  public void startWatching()
  {

    // get the directory we want to watch, using the Paths singleton class
    Path toWatch = Paths.get(directoryToWatch);
    if(toWatch == null)
    {
      throw new UnsupportedOperationException("Directory not found");
    }

    // make a new watch service that we can register interest in
    // directories and files with.
    WatchService motionWatcher;
    try
    {
      motionWatcher = toWatch.getFileSystem().newWatchService();
      // start the file watcher thread below
      MotionWatch fileWatcher = new MotionWatch(motionWatcher,this.me);
      Thread th = new Thread(fileWatcher, "FileWatcher");
      th.start();

      // register a file
      toWatch.register(motionWatcher, ENTRY_CREATE);
      th.join();

    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  /**
   * This Runnable is used to constantly attempt to take from the watch
   * queue, and will receive all events that are registered with the
   * fileWatcher it is associated. In this sample for simplicity we
   * just output the kind of event and name of the file affected to
   * standard out.
   */
  private class MotionWatch implements Runnable {

    /** the watchService that is passed in from above */
    private WatchService motionFolderWatcher;
    IMotionEvent me;

    public MotionWatch(WatchService motionFolderWatcher, IMotionEvent me) {
      this.motionFolderWatcher= motionFolderWatcher;
      this.me = me;
    }

    /**
     * In order to implement a file watcher, we loop forever
     * ensuring requesting to take the next item from the file
     * watchers queue.
     */
    @Override
    public void run() {
      try {
        // get the first event before looping
        WatchKey key = motionFolderWatcher.take();
        while(key != null)
        {
          // we have a polled event, now we traverse it and
          // receive all the states from it
          for (WatchEvent event : key.pollEvents())
          {
            WatchEvent.Kind<?> kind = event.kind();

            if (kind == OVERFLOW) {
              continue;
            }

            Path filename = (Path) event.context();
            //callback launcher
            System.out.printf("Received %s event for file: %s\n",
                event.kind(), event.context() );
            if(filename.toString().contains("jpg"))
            {
              String imgPath = directoryToWatch + "/" + filename.toString();
              this.me.motionDetected(imgPath);
            }
          }
          key.reset();
          key = motionFolderWatcher.take();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Stopping thread");
    }
  }
}


text:
namespace SilverNeedle.Actions.CharacterGeneration.ClassFeatures
{
    using SilverNeedle.Characters;
    using SilverNeedle.Characters.Magic;
    using SilverNeedle.Characters.SpecialAbilities;
    using SilverNeedle.Serialization;

    public class AddBloodlineBonusSpell : ICharacterDesignStep, IFeatureCommand
    {
        private int spellLevel;
        public AddBloodlineBonusSpell(IObjectStore configuration)
        {
            spellLevel = configuration.GetInteger("spell-level");
        }
        public void ExecuteStep(CharacterSheet character)
        {
            Execute(character.Components);
        }

        public void Execute(Utility.ComponentContainer components)
        {
            var bloodline = components.Get<Bloodline>();
            var casting = components.Get<SpontaneousCasting>();
            var classLevel = components.Get<ClassLevel>();
            var bonusSpell = bloodline.GetBonusSpell(classLevel.Level);
            casting.LearnSpell(spellLevel, bonusSpell);
        }
    }
}


text:
import { IBMiQueryGeneratorTypeScript } from './query-generator-typescript.js';

export class IBMiQueryGenerator extends IBMiQueryGeneratorTypeScript {}


text:
from plasTeX.Tokenizer import Token
from plasTeX import Command, Environment

class alltt(Environment):

    def invoke(self, tex):
        self.ownerDocument.context.push(self)
        esc = self.ownerDocument.context.categories[Token.CC_ESCAPE]
        begin = self.ownerDocument.context.categories[Token.CC_BGROUP]
        end = self.ownerDocument.context.categories[Token.CC_EGROUP]
        self.ownerDocument.context.setVerbatimCatcodes()
        for i in esc:
            self.ownerDocument.context.catcode(i, Token.CC_ESCAPE)
        for i in begin:
            self.ownerDocument.context.catcode(i, Token.CC_BGROUP)
        for i in end:
            self.ownerDocument.context.catcode(i, Token.CC_EGROUP)
        Environment.invoke(self, tex)
        self.ownerDocument.context.pop(self)