text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Globalization;

namespace Newtonsoft.Json.Linq
{
  /// <summary>
  /// Contains the LINQ to JSON extension methods.
  /// </summary>
  public static class LinqExtensions
  {
    /// <summary>
    /// Returns a collection of tokens that contains the ancestors of every token in the source collection.
    /// </summary>
    /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JToken"/>.</typeparam>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the ancestors of every node in the source collection.</returns>
    public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken
    {
      ValidationUtils.ArgumentNotNull(source, "source");

      return source.SelectMany(j => j.Ancestors()).AsJEnumerable();
    }

    //TODO
    //public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject
    //{
    //  ValidationUtils.ArgumentNotNull(source, "source");

    //  return source.SelectMany(j => j.AncestorsAndSelf());
    //}

    /// <summary>
    /// Returns a collection of tokens that contains the descendants of every token in the source collection.
    /// </summary>
    /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JContainer"/>.</typeparam>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the descendants of every node in the source collection.</returns>
    public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer
    {
      ValidationUtils.ArgumentNotNull(source, "source");

      return source.SelectMany(j => j.Descendants()).AsJEnumerable();
    }

    //TODO
    //public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer
    //{
    //  ValidationUtils.ArgumentNotNull(source, "source");

    //  return source.SelectMany(j => j.DescendantsAndSelf());
    //}

    /// <summary>
    /// Returns a collection of child properties of every object in the source collection.
    /// </summary>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JObject"/> that contains the source collection.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> that contains the properties of every object in the source collection.</returns>
    public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source)
    {
      ValidationUtils.ArgumentNotNull(source, "source");

      return source.SelectMany(d => d.Properties()).AsJEnumerable();
    }

    /// <summary>
    /// Returns a collection of child values of every object in the source collection with the given key.
    /// </summary>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <param name="key">The token key.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection with the given key.</returns>
    public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key)
    {
      return Values<JToken, JToken>(source, key).AsJEnumerable();
    }

    /// <summary>
    /// Returns a collection of child values of every object in the source collection.
    /// </summary>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns>
    public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source)
    {
      return source.Values(null);
    }

    /// <summary>
    /// Returns a collection of converted child values of every object in the source collection with the given key.
    /// </summary>
    /// <typeparam name="U">The type to convert the values to.</typeparam>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <param name="key">The token key.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection with the given key.</returns>
    public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source, object key)
    {
      return Values<JToken, U>(source, key);
    }

    /// <summary>
    /// Returns a collection of converted child values of every object in the source collection.
    /// </summary>
    /// <typeparam name="U">The type to convert the values to.</typeparam>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns>
    public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source)
    {
      return Values<JToken, U>(source, null);
    }

    /// <summary>
    /// Converts the value.
    /// </summary>
    /// <typeparam name="U">The type to convert the value to.</typeparam>
    /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param>
    /// <returns>A converted value.</returns>
    public static U Value<U>(this IEnumerable<JToken> value)
    {
      return value.Value<JToken, U>();
    }

    /// <summary>
    /// Converts the value.
    /// </summary>
    /// <typeparam name="T">The source collection type.</typeparam>
    /// <typeparam name="U">The type to convert the value to.</typeparam>
    /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param>
    /// <returns>A converted value.</returns>
    public static U Value<T, U>(this IEnumerable<T> value) where T : JToken
    {
      ValidationUtils.ArgumentNotNull(value, "source");

      JToken token = value as JToken;
      if (token == null)
        throw new ArgumentException("Source value must be a JToken.");

      return token.Convert<JToken, U>();
    }

    internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object key) where T : JToken
    {
      ValidationUtils.ArgumentNotNull(source, "source");

      foreach (JToken token in source)
      {
        if (key == null)
        {
          if (token is JValue)
          {
            yield return Convert<JValue, U>((JValue)token);
          }
          else
          {
            foreach (JToken t in token.Children())
            {
              yield return t.Convert<JToken, U>(); ;
            }
          }
        }
        else
        {
          JToken value = token[key];
          if (value != null)
            yield return value.Convert<JToken, U>();
        }
      }

      yield break;
    }

    //TODO
    //public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : JObject;

    //public static IEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken
    //{
    //  ValidationUtils.ArgumentNotNull(source, "source");

    //  return source.SelectMany(c => c.Children());
    //}

    /// <summary>
    /// Returns a collection of child tokens of every array in the source collection.
    /// </summary>
    /// <typeparam name="T">The source collection type.</typeparam>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns>
    public static IJEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken
    {
      return Children<T, JToken>(source).AsJEnumerable();
    }

    /// <summary>
    /// Returns a collection of converted child tokens of every array in the source collection.
    /// </summary>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <typeparam name="U">The type to convert the values to.</typeparam>
    /// <typeparam name="T">The source collection type.</typeparam>
    /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns>
    public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T : JToken
    {
      ValidationUtils.ArgumentNotNull(source, "source");

      return source.SelectMany(c => c.Children()).Convert<JToken, U>();
    }

    internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken
    {
      ValidationUtils.ArgumentNotNull(source, "source");

      foreach (JToken token in source)
      {
        yield return Convert<JToken, U>(token);
      }
    }

    internal static U Convert<T, U>(this T token) where T : JToken
    {
      if (token == null)
        return default(U);

      if (token is U
        // don't want to cast JValue to its interfaces, want to get the internal value
        && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable))
      {
        // HACK
        return (U)(object)token;
      }
      else
      {
        JValue value = token as JValue;
        if (value == null)
          throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T)));

        if (value.Value is U)
          return (U)value.Value;

        Type targetType = typeof(U);

        if (ReflectionUtils.IsNullableType(targetType))
        {
          if (value.Value == null)
            return default(U);

          targetType = Nullable.GetUnderlyingType(targetType);
        }

        return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture);
      }
    }

    //TODO
    //public static void Remove<T>(this IEnumerable<T> source) where T : JContainer;

    /// <summary>
    /// Returns the input typed as <see cref="IJEnumerable{T}"/>.
    /// </summary>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns>
    public static IJEnumerable<JToken> AsJEnumerable(this IEnumerable<JToken> source)
    {
      return source.AsJEnumerable<JToken>();
    }

    /// <summary>
    /// Returns the input typed as <see cref="IJEnumerable{T}"/>.
    /// </summary>
    /// <typeparam name="T">The source collection type.</typeparam>
    /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
    /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns>
    public static IJEnumerable<T> AsJEnumerable<T>(this IEnumerable<T> source) where T : JToken
    {
      if (source == null)
        return null;
      else if (source is IJEnumerable<T>)
        return (IJEnumerable<T>)source;
      else
        return new JEnumerable<T>(source);
    }
  }
}
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/itemLogout" android:title="Log out"/>
</menu>

redpajama_set_name: RedPajamaGithub


text:
#ifndef BADVPN_SAVL_H
#define BADVPN_SAVL_H

#include <stddef.h>
#include <stdint.h>

#include <structure/CAvl.h>
#include <misc/merge.h>
#include <misc/debug.h>

#endif


text:
package core.webui.server.handlers.renderedobjects;

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

import core.keyChain.SharedVariablesActivation;
import core.webui.server.handlers.internals.taskactivation.ActionTaskActivationAddSharedVariables;

public class RenderedSharedVariablesActivation {

	private List<RenderedSharedVariableActivation> variables;

	public static RenderedSharedVariablesActivation fromActivation(List<SharedVariablesActivation> variables) {
		RenderedSharedVariablesActivation output = new RenderedSharedVariablesActivation();
		output.variables = new ArrayList<>();
		for (SharedVariablesActivation variable : variables) {
			String namespace = variable.getVariable().isAll() ?  ActionTaskActivationAddSharedVariables.ALL : variable.getVariable().getNamespace();
			String name = variable.getVariable().isAllForNamespace() ?  ActionTaskActivationAddSharedVariables.ALL : variable.getVariable().getName();

			output.variables.add(RenderedSharedVariableActivation.of(namespace, name));
		}
		return output;
	}

	public List<RenderedSharedVariableActivation> getVariables() {
		return variables;
	}
	public void setVariables(List<RenderedSharedVariableActivation> variables) {
		this.variables = variables;
	}
}


text:
layout: post
title: "New Year blog: Single graphite server with grafana"
date: 2018-01-02 18:30:00 -0400
author: Victor E. Bazterra
categories: system-design telemetry graphite grafana
---

Several of my past and current projects require collecting a lot of data that can naturally be saved as time series. Looking for options of how to save time series, I found out about Graphite, one of the most straightforward and scalable open-source time-series database[^1].

From my point of view graphite has the following features that make it very popular:

* Relatively simple design and implementation.
* Because of its underlying simplicity, it can scale well horizontally.
* Terrific API for rendering time series.
* Modular services that allow deploying it in multiple configurations.

IMHO, Graphite downside is due to following issues:

* Hard to install for the first time.
* No direct ways for managing and indexing time series metadata.
* No best deployment configuration, so it takes R&D to find the right one.

There are also some features like server-side time series rendering that is up to discussion on how beneficial or scalable indeed there are. I will not discuss Graphite design choices because you can learn most of them from a fantastic online resource done by Chris Davis one of Graphite core developers[^2].

People tend to complain a lot about graphite old looking dashboard interface. However, this is easy to fix by using a dedicated front-end application that can handle graphite as its back end. In my opinion, the prettiest of them all is Grafana that can also be used with other time-series databases[^3]

In this post, I plan to show you one of the many configurations to set up one Graphite server together with Grafana, see figure below:

{% include image file="single-graphite-server.svg" %}

I am assuming all these services will be installed on the same host, so it is more a standalone installation that cannot by itself scale horizontally. It is likely that I will discuss in a future post, a configuration that can be scaled up horizontal and that is also somewhat highly available(ish).

Here it is summary of graphite services:

* **Carbon-cache**: Message-queue like service to collect metric points sent via UDP or TCP and save them to disk using Whisper.
* **Whisper**: A library for implementing a file-based time-series database format for graphite.
* **Graphite-web**: Front end distributed with Graphite for showing and rendering time series saved in Whisper. It also implements a simple but efficient dashboard to publish a selected number of metrics. User accounts are implemented by [django](https://www.djangoproject.com/) using [mysql](https://www.mysql.com/) as its database.
* **Grafana**: For beautiful dashboards.
* **NGIX**: Proxy to direct traffic to graphite or grafana based on base URL.
* **Collectl**(optional): For self-monitoring of graphite server, used to detect when the server is stressed and capacity planning.
* **Logter**(optional): For self-monitoring of graphite HTTP requests to quantify the quality of service.

Instead, explain how to do the installation, I can use an [ansible playbook](https://github.com/graphite-server/ansible) that I prepared as programming assignment for this post[^4]. In particular, this playbook will install my modified version of graphite with some improvements for federated rendering and some extra functions for processing time series[^5].

Finally, I like to state that ansible and similar tools are bringing a small revolution by automating system deployments and integrating into the same process configuration management. Also, it provides an efficient and functional way of documenting system designs. This a * significant added value* people do not discuss often!

#### Rerefences ####

[^1]: Graphite project [source code](https://github.com/graphite-project/), and [documentation](http://graphite-api.readthedocs.io/en/latest/)

[^2]: Chris Davis, [Graphite in The Architecture of Open Source Applications](http://www.aosabook.org/en/graphite.html).

[^3]: [Grafana: The open platform for beautiful analytics and monitoring.](https://grafana.com/):

[^4]: [Automation for everyone with ansible](https://www.ansible.com/)

[^5]: [Graphite-server](https://github.com/graphite-server) is from a relatively old fork of the [graphite-project](https://github.com/graphite-project). I recommend to follow principal graphite-project, but for that, you will need to change ansible playbook from this blog. Take it as an exercise!


text:
用C实现的安卓解码与编码库。

目前支持的算法:

- BASE64
- MD5

[使用指南](https://github.com/tyzlmjj/Codec/wiki/%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)

##引入库

for Gradle:
```
compile 'me.majiajie:codec:1.1.0'
```

and for Maven:
```
<dependency>
  <groupId>me.majiajie</groupId>
  <artifactId>codec</artifactId>
  <version>1.1.0</version>
  <type>pom</type>
</dependency>
```

##联系我

**Email:** tyzl931019@gmail.com

**QQ**: 809402737

木有微博、推特!

##错误反馈

这个库有BUG?请点这里 [Github Issues](https://github.com/tyzlmjj/Codec/issues)

代码里没BUG的程序员都太年轻,又或者……

##许可证

Codec is released under the [Apache 2.0 license](https://github.com/tyzlmjj/Codec/blob/master/LICENSE).
```
Copyright 2016 Ma JiaJie

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.
```


text:
package core.models

/**
 * Config specific parameters.
 */
case class Config(someProp: String)


text:
 * create an html document for the visualizer to be displayed on
 * create code to read an audio file
 * pull out waveform from audio
 * create bars from various frequencies
 * color bars


text:
import unittest
import os

from source.informationManagers.search.scriptedFileSearch import ScriptedFileSearch

class ScriptProvider_test(unittest.TestCase):

    mediaRoot = "/media/root/"

    class ProcessProvider(object):
        scriptCalledWith = None

        def call(self, cmd, shell=False):
            self.scriptCalledWith = cmd

    def test_Scan_exists(self):
        x = ScriptedFileSearch(self.ProcessProvider())
        self.assertNotEqual(None, x)

    def test_Scan_does_not_run_by_default(self):
        s = ScriptedFileSearch(self.ProcessProvider())
        self.assertEqual(None, next(s.getList(), None))
        self.assertEqual(False, s.scanHasRun())

    def test_scanner_can_scan(self):
        s = ScriptedFileSearch(self.ProcessProvider())
        s.scan("MyScript.sh", self.mediaRoot)
        self.assertEqual(True, s.scanHasRun())

    def test_scanner_calls_my_subprocess_provider_with_my_script(self):
        provider = self.ProcessProvider()
        s = ScriptedFileSearch(provider)
        s.scan("MyScript.sh", "/scan/root")
        self.assertEqual("MyScript.sh /scan/root > " + self.tempFileName,
                         provider.scriptCalledWith)

    def test_scanner_script_can_find_videos(self):
        s = ScriptedFileSearch(self.ProcessProvider())
        s.scan("MyScript.sh", self.mediaRoot)
        self.assertEqual(["Cheeta Queen", "./some_dir/Cheeta Queen.mp4"], s.getFile("1"))
        self.assertEqual("1", next(s.getList()))

    def test_class_removes_temp_file_after_running(self):
        s = ScriptedFileSearch(self.ProcessProvider())
        s.scan("MyScript.sh", self.mediaRoot)
        self.assertEqual(False, os.path.isfile(self.tempFileName))

    def setUp(self):
        self.tempFileName = "temp.list.csv"
        self.createTempFile()

    def createTempFile(self):
        f = open(self.tempFileName, "w")
        f.write("1,Cheeta Queen,./some_dir/Cheeta Queen.mp4")
        f.close()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Approve.RuleCenter;
using System.Configuration;
using System.Text;

public partial class JSDW_ApplyJGYS_ProjectFile_ChooseQYSG : System.Web.UI.Page
{
    private RCenter rc = new RCenter();
    private static readonly string PrePerSon = ConfigurationManager.AppSettings["PerSon"];
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Show();
        }
    }
    private void Show()
    {
        StringBuilder _builder = new StringBuilder();
        string JSDWBM = CurrentEntUser.UserId;
        _builder.Append(@"select a.QYBM,a.JGDM,a.RegAdrProvinceName+''+a.RegAdrCityName+''+RegAdrCountryName SD,C.ZSBH,D.ZSBH AXZBH,a.QYMC,b.ZZMC,a.FRDB,a.LXR,a.LXDH,a.QYXXDZ
                            from QY_JBXX a
                            left join QY_QYZZXX b on a.QYBM=b.QYBM AND B.SFZX=1 and ISNULL(B.SFZD,0)=0
                            left join QY_QYZSXX c on a.QYBM = c.QYBM and c.ZSLXBM!=150
                            left join QY_QYZSXX D on a.QYBM = D.QYBM AND D.ZSLXBM=150 AND D.SFYX=1
                            where C.SFYX=1");
        //string QYLX = GetQYLX();
        //if (!string.IsNullOrEmpty(QYLX))
        _builder.Append(" AND a.QYLXBM in (101,180)");
        if (!string.IsNullOrEmpty(txtQYName.Text))
            _builder.AppendFormat(" AND a.QYMC like '%{0}%'", txtQYName.Text);
        this.Pager1.className = "JST_XZSPBaseInfo";
        this.Pager1.sql = _builder.ToString();
        this.Pager1.pagecount = 20;
        this.Pager1.controltopage = "DG_List";
        this.Pager1.controltype = "DataGrid";
        this.Pager1.dataBind();
    }
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        Show();
    }
    protected void DG_List_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemIndex > -1)
        {
            e.Item.Cells[0].Text = (e.Item.ItemIndex + 1).ToString();
        }
    }
    private string TypeId
    {
        get
        {
            return Request.QueryString["typeId"];
        }
    }
}


text:
package io.github.mzmine.modules.dataprocessing.align_hierarchical;

import io.github.mzmine.datamodel.features.FeatureListRow;
import java.util.List;

import io.github.mzmine.datamodel.MZmineProject;

public class RowVsRowDistanceProvider {

  MZmineProject project;
  // boolean useOldestRDFancestor;
  // Hashtable<RawDataFile, List<double[]>> rtAdjustementMapping;
  List<FeatureListRow> full_rows_list;
  double mzWeight;
  double rtWeight;
  boolean useApex;
  // boolean useKnownCompoundsAsRef;
  // boolean useDetectedMzOnly;
  // RTTolerance rtToleranceAfter;

  double maximumScore;

  public RowVsRowDistanceProvider(MZmineProject project,
      // boolean useOldestRDFancestor,
      // Hashtable<RawDataFile, List<double[]>> rtAdjustementMapping,
      List<FeatureListRow> full_rows_list, double mzWeight, double rtWeight,
      // boolean useApex, boolean useKnownCompoundsAsRef,
      // boolean useDetectedMzOnly, RTTolerance rtToleranceAfter,
      double maximumScore) {

    this.project = project;
    // this.useOldestRDFancestor = useOldestRDFancestor;
    // this.rtAdjustementMapping = rtAdjustementMapping;
    this.full_rows_list = full_rows_list;
    this.mzWeight = mzWeight;
    this.rtWeight = rtWeight;
    // this.useApex = useApex;
    // this.useKnownCompoundsAsRef = useKnownCompoundsAsRef;
    // this.useDetectedMzOnly = useDetectedMzOnly;
    // this.rtToleranceAfter = rtToleranceAfter;

    this.maximumScore = maximumScore;

  }

  public RowVsRowScoreGC getScore(int row_id, int aligned_row_id, double mzMaxDiff,
      double rtMaxDiff) {

    FeatureListRow peakListRow = full_rows_list.get(row_id);
    FeatureListRow alignedRow = full_rows_list.get(aligned_row_id);

    RowVsRowScoreGC score = new RowVsRowScoreGC(project, // useOldestRDFancestor,
        // rtAdjustementMapping,
        peakListRow, alignedRow, mzMaxDiff, mzWeight, rtMaxDiff, rtWeight, 0.0d// ,
    // useApex, useKnownCompoundsAsRef,
    // useDetectedMzOnly,
    // rtToleranceAfter
    );

    return score;
  }

  // public double getMaximumScore() {
  // return this.maximumScore;
  // }

  public double getSimpleDistance(int i, int j, double mzMaxDiff, double rtMaxDiff,
      double minScore) {

    // Itself
    if (i == j) {
      return 0d;
    }

    return this.maximumScore - this.getScore(i, j, mzMaxDiff, rtMaxDiff).getScore();
  }

  public double getRankedDistance(int i, int j, double mzMaxDiff, double rtMaxDiff,
      double minScore) {

    // Itself
    if (i == j)
      return 0d;

    // if (row_id > aligned_row_id) {
    // int tmp = row_id;
    // row_id = aligned_row_id;
    // aligned_row_id = tmp;
    // }
    // if (row_id < aligned_row_id) {
    // int tmp = row_id;
    // row_id = aligned_row_id;
    // aligned_row_id = tmp;
    // }

    FeatureListRow row = full_rows_list.get(i);
    FeatureListRow k_row = full_rows_list.get(j);

    // System.out.println("(2) Rows: (" + i + "," + j + ")" + row + " | " +
    // k_row);

    // // Same list
    // if ((row_id < 45 && aligned_row_id < 45)
    // || (row_id >= 45 && aligned_row_id >= 45 && row_id < 102 &&
    // aligned_row_id < 102)
    // || (row_id >= 102 && aligned_row_id >= 102)) {
    if (row.getRawDataFiles().get(0) == k_row.getRawDataFiles().get(0)) {
      return 1000.0d;
    }
    // Not candidate
    else {
      // System.out.println("(2) CaseRT: " +
      // Math.abs(row.getBestPeak().getRT() - k_row.getBestPeak().getRT())
      // + " >= " + rtMaxDiff/2.0 + "? " +
      // (Math.abs(row.getBestPeak().getRT() -
      // k_row.getBestPeak().getRT()) >= rtMaxDiff/2.0));
      // System.out.println("(2) CaseMZ: " +
      // Math.abs(row.getBestPeak().getMZ() - k_row.getBestPeak().getMZ())
      // + " >= " + mzMaxDiff/2.0 + "? " +
      // (Math.abs(row.getBestPeak().getMZ() -
      // k_row.getBestPeak().getMZ()) >= mzMaxDiff/2.0));
      if ((Math.abs(row.getBestFeature().getRT() - k_row.getBestFeature().getRT()) >= rtMaxDiff / 2.0
          || Math.abs(row.getBestFeature().getMZ() - k_row.getBestFeature().getMZ()) >= mzMaxDiff
              / 2.0)) {
        return 100.0d;
      }
    }

    double score = this.getScore(i, j, mzMaxDiff, rtMaxDiff).getScore();
    // Score too low
    if (score <= Math.max(HierarAlignerGCTask.MIN_SCORE_ABSOLUTE, minScore)) {
      // System.out.println("Found score " + score + " < " +
      // Math.max(JDXCompoundsIdentificationSingleTask.MIN_SCORE_ABSOLUTE,
      // minScore) + "!");
      // System.out.println("(2) Final dist: " + 10.0f);
      return 10.0d;
    }

    // Score OK
    return this.maximumScore - score;
  }

}


text:
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HelpScoutMetrics.NLogViewer
{
    /// <summary>
    /// Interaction logic for NLogViewerView.xaml
    /// </summary>
    public partial class NLogViewerView : Window
    {
        public NLogViewerView()
        {
            InitializeComponent();
        }

        private static Logger logger = LogManager.GetLogger("NLogViewerView");

        protected override void OnClosed(EventArgs e)
        {
            logger.Log(LogLevel.Info, "Closed Log Window");
            base.OnClosed(e);
        }
    }
}


text:
package org.wso2.carbon.mdm.services.android.bean;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;

/**
 * This class represents the blacklist applications information.
 */
@ApiModel(value = "BlacklistApplications",
        description = "This class represents the blacklist applications information.")
public class BlacklistApplications extends AndroidOperation implements Serializable {

    @ApiModelProperty(name = "appIdentifiers", value = "A list of application package names to be blacklisted.",
            required = true)
	@Size(min = 2, max = 45)
	private List<String> appIdentifiers;

	public List<String> getAppIdentifier() {
		return appIdentifiers;
	}

	public void setAppIdentifier(List<String> appIdentifiers) {
		this.appIdentifiers = appIdentifiers;
	}

}


text:
package ar.integration.api.user;

import static com.jayway.restassured.RestAssured.given;

import ar.entity.User;

import com.jayway.restassured.http.ContentType;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;

public class UserEndpointTests extends AbstractUserIntegrationTests {

  ////////////////////
  // Initialization //
  ////////////////////

  private String userUrl;

  @Override
  @Before
  public void before() {
    super.before();
    userUrl = rootUrl + "/users/1";
  }

  /////////////////////////
  // User Endpoint Tests //
  /////////////////////////

  @Test
  public void user_DELETE() {
    lastResponse = given().delete(userUrl);
    assertNoContentResponse();
  }

  @Test
  public void user_GET() {
    lastResponse = given().get(userUrl);
    assertOkResponse();
    assertUserInResponse("Charles", "Xavier", "Professor X");
  }

  @Test
  public void user_GET_notAcceptable() {
    lastResponse = given().accept(ContentType.XML).get(userUrl);
    assertNotAcceptableResponse();
  }

  @Test
  public void user_HEAD() {
    lastResponse = given().head(userUrl);
    assertNoContentResponse();
  }

  @Test
  public void user_PATCH() {
    lastResponse = given().body(user).contentType(ContentType.JSON).patch(userUrl);
    assertOkResponse();
    assertUserInResponse(user);
  }

  @Test
  public void user_PATCH_nonTrimmedValues() {
    user.setUsername(whitespace + user.getUsername() + whitespace);
    user.setFirstName(whitespace + user.getFirstName() + whitespace);
    user.setLastName(whitespace + user.getLastName() + whitespace);

    lastResponse = given().body(user).contentType(ContentType.JSON).patch(userUrl);
    assertOkResponse();

    user.setUsername(user.getUsername().trim());
    user.setFirstName(user.getFirstName().trim());
    user.setLastName(user.getLastName().trim());
    assertUserInResponse(user);
  }

  @Test
  public void user_PATCH_nullUsername() {
    user.setUsername(null);

    lastResponse = given().body(user).contentType(ContentType.JSON).patch(userUrl);
    assertErrorResponse(HttpStatus.SC_BAD_REQUEST, User.class, usernamePresentMessage, "null", usernameFieldName);
  }

  @Test
  public void user_PATCH_blankUsername() {
    user.setUsername(blank);

    lastResponse = given().body(user).contentType(ContentType.JSON).patch(userUrl);
    assertErrorResponse(HttpStatus.SC_BAD_REQUEST, User.class, usernamePresentMessage, blank, usernameFieldName);
  }

  @Test
  public void user_PATCH_whitespaceOnlyUsername() {
    user.setUsername(whitespace);

    lastResponse = given().body(user).contentType(ContentType.JSON).patch(userUrl);
    assertErrorResponse(HttpStatus.SC_BAD_REQUEST, User.class, usernamePresentMessage, whitespace, usernameFieldName);
  }

  @Test
  public void user_PATCH_nonUniqueUsername() {
    user.setUsername(nonUniqueUsername);

    lastResponse = given().body(user).contentType(ContentType.JSON).patch(userUrl);
    assertErrorResponse(HttpStatus.SC_CONFLICT, User.class, usernameUniqueMessage, nonUniqueUsername,
        usernameFieldName);
  }

  @Test
  public void user_PATCH_notAcceptable() {
    lastResponse = given().body(user).accept(ContentType.XML).patch(userUrl);
    assertNotAcceptableResponse();
  }

  @Test
  public void user_PATCH_unsupportedMediaType() {
    lastResponse = given().body(user).contentType(ContentType.XML).patch(userUrl);
    assertUnsupportedMediaTypeResponse();
  }

  @Test
  public void user_PUT() {
    lastResponse = given().body(user).put(userUrl);
    assertOkResponse();
  }

  @Test
  public void user_PUT_idAlreadyExists() {
    lastResponse = given().body(user).put(userUrl);
    assertErrorResponse(HttpStatus.SC_CONFLICT, User.class, idUniqueMessage, "1", idFieldName);
  }

  @Test
  public void user_PUT_notAcceptable() {
    lastResponse = given().body(user).accept(ContentType.XML).put(userUrl);
    assertNotAcceptableResponse();
  }

  @Test
  public void user_PUT_unsupportedMediaType() {
    lastResponse = given().body(user).contentType(ContentType.XML).put(userUrl);
    assertUnsupportedMediaTypeResponse();
  }

}


text:
package cz.fely.weightedaverage;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see <header href="http://d.android.com/tools/testing">Testing documentation</header>
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
/* Vendor imports */
import React from 'react'
import PropTypes from 'prop-types'
import { graphql, Link } from 'gatsby'
import Image from 'gatsby-image'
/* App imports */
import Layout from '../../components/layout'
import SEO from '../../components/seo'
import Config from '../../../config'
import Utils from '../../utils'
import style from './tag.module.less'

const Tag = ({ data }) => {
  const rawTags = data.allMarkdownRemark.edges
    .map(edge => edge.node.frontmatter.tags)
    .reduce((prev, curr) => prev.concat(curr))
  const tags = rawTags
    .filter((tag, index) => index === rawTags.indexOf(tag))
    .sort() // Remove duplicates and sort values
  const tagPage = Config.pages.tag

  return (
    <Layout title="Tags">
      <SEO
        title="Tags"
        description="All present tags in the site"
        path={tagPage}
      />

        {tags.map(tag => (
          <Link
            to={Utils.resolvePageUrl(tagPage, tag)}
            className={style.card}
            key={tag}
          >

              <Image
                fluid={
                  data.allFile.edges.find(edge => edge.node.name === tag).node
                    .childImageSharp.fluid
                }
              />

{Config.tags[tag].name || Utils.capitalize(tag)}

{Config.tags[tag].description}

              {`${
                rawTags.filter(sTag => sTag === tag).length
              } Posts`}

          </Link>
        ))}

    </Layout>
  )
}

Tag.propTypes = {
  data: PropTypes.shape({
    allMarkdownRemark: PropTypes.shape({
      edges: PropTypes.arrayOf(
        PropTypes.shape({
          node: PropTypes.shape({
            frontmatter: PropTypes.shape({
              tags: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
            }).isRequired,
          }).isRequired,
        }).isRequired
      ).isRequired,
    }).isRequired,
    allFile: PropTypes.shape({
      edges: PropTypes.arrayOf(
        PropTypes.shape({
          node: PropTypes.shape({
            name: PropTypes.string.isRequired,
            childImageSharp: PropTypes.shape({
              fluid: PropTypes.object.isRequired,
            }).isRequired,
          }).isRequired,
        }).isRequired
      ).isRequired,
    }).isRequired,
  }).isRequired,
}

export const query = graphql`
  {
    allMarkdownRemark(filter: { fileAbsolutePath: { regex: "/index.md$/" } }) {
      edges {
        node {
          frontmatter {
            tags
          }
        }
      }
    }
    allFile(filter: { relativeDirectory: { eq: "tags" } }) {
      edges {
        node {
          name
          childImageSharp {
            fluid(maxWidth: 400) {
              ...GatsbyImageSharpFluid_tracedSVG
            }
          }
        }
      }
    }
  }
`

export default Tag


text:
package com.jasondelport.nobelprize.nobelprizelaureates;

/**
 * Created by jasondelport on 12/05/16.
 */

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<NobelPrizeViewHolder> {
    private List<NobelPrize> mPrizes;
    private Context mContext;

    public RecyclerViewAdapter(Context context, List<NobelPrize> prizes) {
        this.mContext = context;
        this.mPrizes = prizes;
    }

    public void addNobelPrize(NobelPrize prize) {
        this.mPrizes.add(prize);
        notifyItemInserted(mPrizes.size()-1);
    }

    public List<NobelPrize> getNobelPrizes() {
        return mPrizes;
    }

    @Override
    public NobelPrizeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview, null);
        return new NobelPrizeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(NobelPrizeViewHolder viewHolder, final int position) {
        NobelPrize prize = mPrizes.get(position);
        viewHolder.firstname.setText(prize.getLaureates().get(0).getFirstname());
        viewHolder.surname.setText(prize.getLaureates().get(0).getSurname());
        viewHolder.year.setText(Integer.toString(prize.getYear()));
        viewHolder.category.setText(prize.getCategory());
    }

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

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lk.megafundtpark.web.tickets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lk.megafundtpark.remote.utils.AdminDetails;
import lk.megafundtpark.remote.utils.CustomerDetails;
import lk.megafundtpark.remote.utils.EbandDetails;
import lk.megafundtpark.remote.utils.TicketDetails;

/**
 *
 * @author Janakshi
 */
@WebServlet(name = "IssueTicketServlet", urlPatterns = {"/IssueTicketServlet"})
public class IssueTicketServlet extends TicketInteractionServlet{

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
          Date today = new Date( );
          final int aPrice = 500;
          final int cPrice = 250;
          CustomerDetails customer;
          EbandDetails band;
          TicketDetails ticket;
          AdminDetails admin =(AdminDetails) session.getAttribute("user");
          ArrayList<EbandDetails> ebands = new ArrayList<EbandDetails>(); //Current customer's ebands
          ArrayList<EbandDetails> ebandList; // Whole session's ebands
          if(session.getAttribute("ebandList")== null){
             ebandList  = new ArrayList<EbandDetails>();
          }
          else{
             ebandList = (ArrayList<EbandDetails>) session.getAttribute("ebandList");
          }

        if(request.getParameter("adult") != null && request.getParameter("child")!= null && request.getParameter("name") != null && request.getParameter("email") !=null){
               int adult = Integer.parseInt(request.getParameter("adult"));
               int child = Integer.parseInt(request.getParameter("child"));
               String name = request.getParameter("name");
               String email = request.getParameter("email");

               if(remoteCustomer.getCustomer(email, name)== null){
               //Creating a customer
                   customer= new CustomerDetails(name,email);
                   remoteCustomer.createCustomer(customer);
               }

               customer = remoteCustomer.getCustomer(email, name);

              //Creating tickets
               for(int i=0;i<adult;i++){
                   ticket= new TicketDetails("adult", today, 500 ,admin.getUserid(), customer.getCustomerid());
                   remoteTicket.createTicket(ticket);
               }
               for(int i=0;i<child;i++){
                   ticket= new TicketDetails("child", today, 250,admin.getUserid(), customer.getCustomerid());
                   remoteTicket.createTicket(ticket);
               }

               List<TicketDetails> tlist=remoteTicket.getTickets(customer.getCustomerid(), today);

               //Creating e-bands
               for(TicketDetails t1 : tlist){
                   band= new EbandDetails(100,t1.getTicketid());
                   remoteBand.createEband(band);

               }

               for(TicketDetails t2 : tlist){
                   band= remoteBand.getEband(t2.getTicketid());
                   ebands.add(band);
                   ebandList.add(band);
               }
               session.setAttribute("issueStatus", "1");
               session.setAttribute("ebands", ebands);
               session.setAttribute("ebandList", ebandList);

               RequestDispatcher rd = request.getRequestDispatcher("tickets.jsp");
               rd.forward(request, response);
        }
        else{
             session.setAttribute("issueStatus", "3");

            RequestDispatcher rd = request.getRequestDispatcher("tickets.jsp");
            rd.forward(request, response);
        }
    }

}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Angular2 Boilerplate</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Angular2 Boilerplate">
    <!-- base url -->
    <!--<base href="/">-->
  </head>
  <body>
    <app>
      Loading...
    </app>

    <!-- Common files to be cached -->
    <script src="/client/common.js"></script>
    <!-- Angular2 files -->
    <script src="/client/angular2.js"></script>
    <!-- App script -->
    <script src="/client/app.js"></script>
  </body>
</html>


text: require "jekyll-categories"


text:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
  <base href="/">
  <link rel="shortcut icon" href="/favicon.ico" />
  <title>ANGULAR-MODULAR-PLATFORM</title>
  <link rel="stylesheet" href="static/css/vendor.css">
  <link rel="stylesheet" href="app/common.css">
  <link rel="stylesheet" href="app/app.css">
</head>

<body class="skin-blue sidebar-mini fixed">
  <angular-app>
    Loading...
  </angular-app>
  <script src="static/js/vendor.js"></script>
  <script src="app/common.js"></script>
  <script src="app/app.js"></script>
  <script>
    (function (i, s, o, g, r, a, m) {
      i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments)
      }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
    ga('create', 'UA-96130716-1', 'none');
    ga('send', 'pageview');
  </script>
</body>

</html>


text:
var expect = chai.expect;

describe("kanaoke", function() {
    describe("hiraganaToKanakana()", function() {
        it("should convert the string to kanakana", function() {
            var hiragana = '', katakana = '';
            for(var i = kanaoke.HIRAGANA_RANGE_START; i <= kanaoke.HIRAGANA_RANGE_END; i++) {
                hiragana += String.fromCharCode(i);
            }

            for(var i = kanaoke.KATAKANA_RANGE_START; i <= kanaoke.KATAKANA_RANGE_END; i++) {
                katakana += String.fromCharCode(i);
            }
            expect(kanaoke.hiraganaToKatakana(hiragana)).to.equal(katakana);
        });
    });

    describe("katakanaToHiragana()", function() {
        it("should convert the string to hiragana", function() {
            var hiragana = '', katakana = '';

            for(var i = kanaoke.KATAKANA_RANGE_START; i <= kanaoke.KATAKANA_RANGE_END; i++) {
                katakana += String.fromCharCode(i);
            }

            for(var i = kanaoke.HIRAGANA_RANGE_START; i <= kanaoke.HIRAGANA_RANGE_END; i++) {
                hiragana += String.fromCharCode(i);
            }
            expect(kanaoke.katakanaToHiragana(katakana)).to.equal(hiragana);
        });

        it("should convert extra katakana", function() {
            expect(kanaoke.katakanaToHiragana("ヷヸヹヺ")).to.equal("ゔぁゔぃゔぇゔぉ");
        });
    });

    describe("fullWidthToHalfWidth()", function() {
        it("should convert fullwidth characters to halfwidth characters", function() {
            var fullWidth = '', halfWidth = '';

            for (var i = kanaoke.FULLWIDTH_START; i <= kanaoke.FULLWIDTH_END; i++) {
                fullWidth += String.fromCharCode(i);
            }

            for(var i = kanaoke.HALFWIDTH_START; i <= kanaoke.HALFWIDTH_END; i++) {
                halfWidth += String.fromCharCode(i);
            }
            expect(kanaoke.fullWidthToHalfWidth(fullWidth)).to.equal(halfWidth);
        });
    });

    describe("halfWidthToFullWidth()", function() {
        it("should convert halfwidth characters to fullwidth characters", function() {
            var fullWidth = '', halfWidth = '';

            for(var i = kanaoke.HALFWIDTH_START; i <= kanaoke.HALFWIDTH_END; i++) {
                halfWidth += String.fromCharCode(i);
            }

            for (var i = kanaoke.FULLWIDTH_START; i <= kanaoke.FULLWIDTH_END; i++) {
                fullWidth += String.fromCharCode(i);
            }
            expect(kanaoke.halfWidthToFullWidth(halfWidth)).to.equal(fullWidth);
        });
    });

    describe("toggleObsolete()", function() {
        it("should toggle between standard and obsolete hiragana (ゐ and ゑ)", function() {
            expect(kanaoke.romajiDictionary['wi']).to.equal('うぃ');
            expect(kanaoke.romajiDictionary['we']).to.equal('うぇ');
            kanaoke.toggleObsolete();
            expect(kanaoke.romajiDictionary['wi']).to.equal('ゐ');
            expect(kanaoke.romajiDictionary['we']).to.equal('ゑ');
            kanaoke.toggleObsolete();
            expect(kanaoke.romajiDictionary['wi']).to.equal('うぃ');
            expect(kanaoke.romajiDictionary['we']).to.equal('うぇ');
        });
    });

    describe("toggleIMEMode()", function() {
        it("should toggle between IME and non IME", function() {
            expect(kanaoke.romajiDictionary['nn']).to.equal("ん");
            kanaoke.toggleIMEMode();
            expect(kanaoke.romajiDictionary['nn']).to.be.undefined;
            kanaoke.toggleIMEMode();
            expect(kanaoke.romajiDictionary['nn']).to.equal("ん");
        });
    });

    describe("isVowel()", function() {
        it("should recognize vowels as vowels", function() {
            expect(kanaoke.isVowel('a')).to.equal(true);
            expect(kanaoke.isVowel('i')).to.equal(true);
            expect(kanaoke.isVowel('u')).to.equal(true);
            expect(kanaoke.isVowel('e')).to.equal(true);
            expect(kanaoke.isVowel('o')).to.equal(true);
        });
    })

    describe("doubleConsonantHiragana()", function() {
        it("should return true only when a consonant is to be doubled", function() {
            expect(kanaoke.doubleConsonantHiragana("a", "a")).to.equal(false);
            expect(kanaoke.doubleConsonantHiragana("", "ka")).to.equal(false);
            expect(kanaoke.doubleConsonantHiragana("k", "ka")).to.equal(true);
            expect(kanaoke.doubleConsonantHiragana("K", "ka")).to.equal(true);
            expect(kanaoke.doubleConsonantHiragana("n", "n")).to.equal(false);
        });
    });

    describe("appendHiragana()", function() {
        it("should append an hiragana to the string", function() {
            expect(kanaoke.appendHiragana("", "a")).to.equal("あ");
            expect(kanaoke.appendHiragana("a", "a")).to.equal("aあ");
            expect(kanaoke.appendHiragana("", "ka")).to.equal("か");
            expect(kanaoke.appendHiragana("k", "ka")).to.equal("っか");
        });
    });

    describe("doubleConsonant()", function() {
        it("should not double vowels", function() {
            expect(kanaoke.doubleConsonant('a', true)).to.equal('a');
            expect(kanaoke.doubleConsonant('i', true)).to.equal('i');
            expect(kanaoke.doubleConsonant('u', true)).to.equal('u');
            expect(kanaoke.doubleConsonant('e', true)).to.equal('e');
            expect(kanaoke.doubleConsonant('o', true)).to.equal('o');
        });
    });

    describe("romajiToHiragana()", function() {
        it("should convert uppercase characters", function() {
            expect(kanaoke.romajiToHiragana("AIUEO KAKIKUKEKO RYARYURYO")).to.equal("あいうえお かきくけこ りゃりゅりょ");
            expect(kanaoke.romajiToHiragana("XAQKO")).to.equal("ぁQこ");
        });

        it("should convert double consonants", function() {
            expect(kanaoke.romajiToHiragana("kkkassatttahammmmma")).to.equal("kっかっさtったはmmmっま");
            expect(kanaoke.romajiToHiragana("yyyarawag gazzaddddabapa")).to.equal("yっやらわg がっざddっだばぱ");
            expect(kanaoke.romajiToHiragana("cchchacchajja")).to.equal("cchちゃっちゃっじゃ");
        });

        it("should change its behavior depending on the value of IMEMode", function() {
            expect(kanaoke.romajiToHiragana("nn")).to.equal("ん");
            expect(kanaoke.romajiToHiragana("n")).to.equal("n");
            expect(kanaoke.romajiToHiragana("nananan")).to.equal("なななn");
            expect(kanaoke.romajiToHiragana("nannannan")).to.equal("なんあんあn");
            expect(kanaoke.romajiToHiragana("rn")).to.equal("rn");
            kanaoke.toggleIMEMode();
            expect(kanaoke.romajiToHiragana("nn")).to.equal("んん");
            expect(kanaoke.romajiToHiragana("n")).to.equal("ん");
            expect(kanaoke.romajiToHiragana("nananan")).to.equal("なななん");
            expect(kanaoke.romajiToHiragana("nannannan")).to.equal("なんなんなん");
            expect(kanaoke.romajiToHiragana("rn")).to.equal("rん");
        });
    });

    describe("romajiToKatakana()", function() {
        it("should convert romaji to katakana", function() {
            expect(kanaoke.romajiToKatakana("AIUEO kakkikuno ryamyu")).to.equal("アイウエオ カッキクノ リャミュ");
        });

        it("should not convert hiragana to katakana", function() {
            expect(kanaoke.romajiToKatakana("Aaiukaかじゅko")).to.equal("アアイウカかじゅコ");
        });
    });

    describe("hiraganaToRomaji()", function() {
        it("should convert 五十音 to romaji", function() {
            expect(kanaoke.hiraganaToRomaji("いろはにほへとちりぬるを")).to.equal("irohanihohetochirinuruwo");
            expect(kanaoke.hiraganaToRomaji("わかよたれそつねならむ")).to.equal("wakayotaresotsunenaramu");
            expect(kanaoke.hiraganaToRomaji("うゐのおくやまけふこえて")).to.equal("uwinookuyamakefukoete");
            expect(kanaoke.hiraganaToRomaji("あさきゆめみしゑひもせすん")).to.equal("asakiyumemishiwehimosesun");
        });

        it("should handle the case when the character is not an hiragana", function() {
            expect(kanaoke.hiraganaToRomaji("ひqょじ。おぎ0ゅ")).to.equal("hiqyoji。ogi0yu");
        });

        it("should convert double consonants", function() {
            expect(kanaoke.hiraganaToRomaji("っか")).to.equal("kka");
            expect(kanaoke.hiraganaToRomaji("っさ")).to.equal("ssa");
            expect(kanaoke.hiraganaToRomaji("った")).to.equal("tta");
            expect(kanaoke.hiraganaToRomaji("っは")).to.equal("hha");
            expect(kanaoke.hiraganaToRomaji("っま")).to.equal("mma");
            expect(kanaoke.hiraganaToRomaji("っや")).to.equal("yya");
            expect(kanaoke.hiraganaToRomaji("っら")).to.equal("rra");
            expect(kanaoke.hiraganaToRomaji("っわ")).to.equal("wwa");
            expect(kanaoke.hiraganaToRomaji("っが")).to.equal("gga");
            expect(kanaoke.hiraganaToRomaji("っざ")).to.equal("zza");
            expect(kanaoke.hiraganaToRomaji("っだ")).to.equal("dda");
            expect(kanaoke.hiraganaToRomaji("っば")).to.equal("bba");
            expect(kanaoke.hiraganaToRomaji("っぱ")).to.equal("ppa");
            expect(kanaoke.hiraganaToRomaji("っちゃ")).to.equal("tcha");
            expect(kanaoke.hiraganaToRomaji("っじゃ")).to.equal("jja");
        });

        it("should convert double consonants (2)", function() {
            expect(kanaoke.hiraganaToRomaji("っりょう")).to.equal("rryou");
            expect(kanaoke.hiraganaToRomaji("っっきゅっ")).to.equal("kkyu");
        });

        it("should write っ as an empty string when not followed by a consonant", function() {
            expect(kanaoke.hiraganaToRomaji("っっっ")).to.equal("");
            expect(kanaoke.hiraganaToRomaji("さむっ!")).to.equal("samu!");
            expect(kanaoke.hiraganaToRomaji("っあっ")).to.equal("a");
        });

        it("should write ん as n' before vowels and y", function() {
            expect(kanaoke.hiraganaToRomaji("んあ")).to.equal("n'a");
            expect(kanaoke.hiraganaToRomaji("んい")).to.equal("n'i");
            expect(kanaoke.hiraganaToRomaji("んう")).to.equal("n'u");
            expect(kanaoke.hiraganaToRomaji("んえ")).to.equal("n'e");
            expect(kanaoke.hiraganaToRomaji("んお")).to.equal("n'o");
            expect(kanaoke.hiraganaToRomaji("こんや が やまだ")).to.equal("kon'ya ga yamada");
            expect(kanaoke.hiraganaToRomaji("んゆ")).to.equal("n'yu");
            expect(kanaoke.hiraganaToRomaji("んよ")).to.equal("n'yo");
        });
    });

    describe("convertPunctuation()", function() {
        it("should convert characters in punctuationDictionary", function() {
            for(var punctuation in kanaoke.punctuationDictionary) {
                if(kanaoke.punctuationDictionary.hasOwnProperty(punctuation)) {
                    expect(kanaoke.convertPunctuation(punctuation)).to.equal(kanaoke.punctuationDictionary[punctuation]);
                }
            }
        });

        it("should convert ' and \" to 「」 and 『』 respectively", function() {
            expect(kanaoke.convertPunctuation("\"\'\'\"\'\"\'")).to.equal("『「」』「『」");
        });
    });

    describe("convertJPPunctuation()", function() {
        it("should convert characters in jpPunctuationDictionary", function() {
            for(var punctuation in kanaoke.jpPunctuationDictionary) {
                if(kanaoke.jpPunctuationDictionary.hasOwnProperty(punctuation)) {
                    expect(kanaoke.convertJPPunctuation(punctuation)).to.equal(kanaoke.jpPunctuationDictionary[punctuation]);
                }
            }
        });
    });
});


text:
module HaskChat where
import Network.Socket
import System.IO
import Control.Concurrent
import Control.Concurrent.Chan
import Control.Monad
import Control.Monad.Fix (fix)
import Control.Exception

type Msg = (Int,String)

main = do
        chan <- newChan
        sock <- socket AF_INET Stream 0
        setSocketOption sock ReuseAddr 1
        bindSocket sock (SockAddrInet 4242 iNADDR_ANY)
        -- que numbers
        listen sock 5
        forkIO $ fix $ \loop -> do
                (_, msg) <- readChan chan
                loop
        mainLoop sock chan 0

mainLoop sock chan nr = do
        conn <- accept sock
        forkIO (runConn conn chan nr)
        mainLoop sock chan $! nr+1

runConn (sock, _) chan nr = do
        let broadcast msg = writeChan chan (nr,msg)
        hdl <- socketToHandle sock ReadWriteMode
        hSetBuffering hdl NoBuffering
        hPutStrLn hdl "Hi How Are YOU ?"
        name <- liftM init (hGetLine hdl)
        broadcast ("--> " ++ name ++ " entered,")
        chan' <- dupChan chan
        reader <- forkIO $ fix $ \loop ->  do
                        (nr', line) <- readChan chan'
                        when (nr /= nr') $ hPutStrLn hdl line
                        loop
        handle (\(SomeException _ ) -> return ()) $ fix $ \loop -> do
            line <- liftM init (hGetLine hdl)
            case line of
             "quit" -> hPutStrLn hdl "Bye!"
             _ -> do
                    broadcast (name ++ ": " ++ line)
                    loop
        killThread reader
        broadcast ("<-- " ++ name ++ " left.")
        hClose hdl


text:
package com.nms.ncms.web.controller;

import com.nms.ncms.entity.SlideContent;
import com.nms.ncms.service.entity.SlideContentService;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

/**
 * Provide slide content for each request.
 *
 * @author Cuong
 * @since 26-11-2014
 */
@Named
@ViewScoped
public class SlideController implements Serializable {

    private static final long serialVersionUID = 6300545196768366986L;

    @EJB
    protected SlideContentService service;
    protected List<SlideContent> slideContents;

    public SlideController() {
    }

    public List<SlideContent> getSlideContents() {
        if (slideContents == null) {
            slideContents = service.findAll();
        }
        return slideContents;
    }
}


text:
package xyz.white.editor.actors;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.DragListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.Selection;
import com.badlogic.gdx.utils.Array;
import xyz.white.editor.EditorManager;
import xyz.white.editor.events.editor.AttrEvent;
import xyz.white.editor.utils.DrawableUtil;
import xyz.white.editor.windows.MainWindow;

/**
 * 选择框
 * Created by 10037 on 2017/4/22 0022.
 */
public class SelectGroup extends Group {
    private Selection<Actor> selection;
    private Drawable cubDra;
    private Rectangle cubRect,childRect;

    public SelectGroup(){
        cubRect = new Rectangle();
        childRect = new Rectangle();
        setCullingArea(cubRect);
        cubDra = DrawableUtil.getRectLineDrawable("icon/select.9.png");
        selection = new Selection<Actor>();
        addListener(dragListener);
    }

    private DragListener dragListener = new DragListener(){
        @Override
        public void drag(InputEvent event, float x, float y, int pointer) {
            if (pointer == -1) return;
            Actor actor = event.getListenerActor();
            actor.moveBy(x - getTouchDownX(), y - getTouchDownY());
            if (getAllActor().contains(SelectGroup.this.getParent(),false)){
                return;
            }
            for (Actor child : getAllActor()){
                if (child instanceof MainWindow){
                    break;
                }else {
                    child.moveBy(x-getTouchDownX(),y-getTouchDownY());
                }
            }
            Actor lastActor = selection.getLastSelected();
            if (lastActor!=null){
                EditorManager.getInstance().getEventBus().post(new AttrEvent(lastActor));
                if (getParent() instanceof MainWindow){
                    MainWindow mainWindow = (MainWindow) getParent();
                    if (mainWindow.getEditorLister()!=null) mainWindow.getEditorLister().change();
                }
            }
        }
    };

    public void setDragBounds(float x, float y, float width, float height) {
        setBounds(x, y, width, height);
        Vector2 vector2 = new Vector2(x,y);
        getParent().localToStageCoordinates(vector2);
        getCullingArea().set(vector2.x,vector2.y,width,height);
        MainWindow mainWindow = (MainWindow) this.getParent();
        isInsideCub(mainWindow);
        setZIndex(100);
    }

    //判断是否在cub中
    private void isInsideCub(Group group){
        for (Actor child:group.getChildren()){
            if (EditorManager.getInstance().getActorType(child).equals(Group.class)){
                isInsideCub((Group) child);
            }
            if (child instanceof SelectGroup) continue;
            Vector2 childVect2 = child.getParent().localToStageCoordinates(new Vector2(child.getX(),child.getY()));
            childRect.set(childVect2.x,childVect2.y,child.getWidth(),child.getHeight());
            if (getCullingArea().overlaps(childRect)){
                if (!selection.contains(child)){
                    child.debug();
                    selection.add(child);
                }
            }else if (selection.contains(child)){
                selection.remove(child);
                child.setDebug(false);
            }
        }
    }

    public void clearAllActor(){
        for (Actor actor:getAllActor()){
            if (actor instanceof MainWindow) continue;
            actor.setDebug(false);
        }
        selection.clear();
        setVisible(false);
        initLayout();
    }

    public void addSelectActor(Actor actor){
        selection.add(actor);
        setZIndex(100);
        initLayout();
    }

    public void addAllSelectActor(Array<Actor> actors){
        selection.addAll(actors);
        initLayout();
    }

    public Actor getLastSelectActor(){
        return selection.getLastSelected();
    }

    public Array<Actor> getAllActor(){
        return selection.toArray();
    }

//    重新设置大小
    public void initLayout(){
        if (selection.size()<=0){
            setVisible(false);
        }else {
            setVisible(true);
            Array<Actor> actors = getAllActor();
            Actor parentWindow = SelectGroup.this.getParent();
            float x1=0,x2 = 0,y1=0,y2=0;
            for (int i = 0; i <actors.size; i++) {

                Actor actor = actors.get(i);

                if (actor instanceof MainWindow){
                    x1 = 0;
                    x2 = actor.getWidth();
                    y1 = 0;
                    y2 = actor.getHeight();
                    break;
                }
                Vector2 posV = new Vector2(0,0);
                Vector2 posV2 = new Vector2(actor.getWidth(),actor.getHeight());
                posV =  actor.localToStageCoordinates(posV);
                posV2 = actor.localToStageCoordinates(posV2);

                posV = parentWindow.stageToLocalCoordinates(posV);
                posV2 = parentWindow.stageToLocalCoordinates(posV2);
                float minX = Math.min(posV.x,posV2.x);
                float maxX = Math.max(posV.x,posV2.x);
                float minY = Math.min(posV.y,posV2.y);
                float maxY = Math.max(posV.y,posV2.y);
                if (i == 0){
                    x1 = minX;
                    x2 = maxX;
                    y1 = minY;
                    y2 = maxY;
                }else {

                    if (minX<x1) x1 = minX;
                    if (maxX>x2) x2 = maxX;
                    if (minY<y1) y1 = minY;
                    if (maxY>y2) y2 = maxY;
                }

            }
            SelectGroup.this.setBounds(x1,y1,x2 - x1,y2 - y1);

        }

    }

    @Override
    public void act(float delta) {

        super.act(delta);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        cubDra.draw(batch,getX(),getY(),getWidth(),getHeight());
        super.draw(batch, parentAlpha);
    }

    public int getSelectedActorSize(){
        return selection.size();
    }

    public Selection<Actor> getSelection() {
        return selection;
    }
}


text:
{% extends "genlib_templates/bluegray_site_base.xhtml" %}
{% block html-extras %} xmlns:schema="http://schema.org/"{% endblock %}
{% block page-title %}EmoryFindingAids {% block page-subtitle %}{% endblock %}{% endblock %}

{% block style %}
    {{ block.super }}
    {% comment %}Place Local changes, modifications and overrisdes in your local.css file.{% endcomment %}
    <link rel="stylesheet" type="text/css" media="all" href="{{ STATIC_URL }}style/local.css" />
    <link rel="stylesheet" type="text/css" media="all" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" />
{% endblock %}

{% block site-logo %}

  <map name="logomap">
    <area shape="rect" coords="0,0,165,70" href="http://www.emory.edu/" alt="Emory University"/>
    <area shape="rect" coords="168,0,316,70" href="{% url 'site-index' %}" alt="EmoryFindingAids" />
  </map>

{% endblock %}
{% comment %}
{% block site-name %}

{% endblock %}
{% endcomment %}

{% block navbar %}   {# override the whole block #}
    Home
    Advanced Search
    Request Materials
    Contributors
    Search Tips
    FindingAid FAQ
    Feedback
{% endblock %}
{% block admin-url %}{% url 'fa-admin:index' %}{% endblock %}

{% block body-extras %}typeof="schema:WebPage" about="http://{{ request.get_host }}{{ request.path }}"{% endblock %}
{# NOTE: not using build_absolute_uri because we do NOT want to include query string #}

{% block sidebar-left %}

  {# give admin users an easy way back to main admin page once they are logged in #}
  {% if user.is_authenticated %}
    {% url 'fa-admin:index' as admin_url %}
    {% if request.path != admin_url %}

Manage Finding Aids

    {% endif %}
  {% endif %}

  {% if kwsearch_form %}

      Search EmoryFindingAids
      <form action="{% url 'fa:search' %}" method="get">
        {{kwsearch_form.keywords}}
        {{kwsearch_form.dao}} {{kwsearch_form.dao.help_text}}

        <input class="form-submit" type="submit" value="Search" />
      </form>

  {% endif %}
{% endblock %}

{% block message %}
  {# if user is logged in, show an indicator and logout link #}
  {% if user.is_authenticated %}

    Welcome, {%firstof user.first_name user.username %}.
    Logout

  {% endif %}
  {# NOTE: cheating a bit by putting login info & logout here,  #}
  {# but content-header is extended by too many templates #}

  {% if user.is_authenticated and messages %} {# clearfix between login info and messages #}

  {% endif %}

  {% if messages %}

        {% for message in messages %}

{{ message|safe }}

        {% endfor %}

  {% endif %}
{% endblock %}

{% block content-outer-bottom %}
  {% if SW_VERSION %}

v{{ SW_VERSION }}

  {% endif %}
  {% if querytime and debug %}{# display eXist query times in debug mode only #}

quer{{ querytime|pluralize:"y,ies" }} took
      {{ querytime|join:", " }} ms

  {% endif %}
{% endblock %}

{% block scripts %}
  {{ block.super }}

{% if not debug %} {# Google Analytics tracking code #}

{% endif %}

  {% if ENABLE_BETA_WARNING %}
    {% include 'snippets/beta_warning.html' %}
  {% endif %}
{% endblock scripts %}

{% block contact-us-link %}{% url 'content:feedback' %}{% endblock %}


text:
namespace views {

// static
const char Separator::kViewClassName[] = "views/Separator";

const int kSeparatorWidth = 1;
// The separator height in pixels.
const int kSeparatorHeight = 1;

// Default color of the separator.
const SkColor kDefaultColor = SkColorSetARGB(255, 233, 233, 233);

Separator::Separator() {
  set_focusable(false);
}

Separator::~Separator() {
}

////////////////////////////////////////////////////////////////////////////////
// Separator, View overrides:

gfx::Size Separator::GetPreferredSize() {
  return gfx::Size(kSeparatorWidth, kSeparatorHeight);
}

void Separator::GetAccessibleState(ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_SEPARATOR;
}

void Separator::Paint(gfx::Canvas* canvas) {
  canvas->FillRect(bounds(), kDefaultColor);
}

std::string Separator::GetClassName() const {
  return kViewClassName;
}

}  // namespace views


text:
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//

package openadk.library;

/**
 * Provisioner is a common interface implemented by the Agent, Zone, and Topic
 * classes. It provides common APIs for setting Subscribers, Publisher, and QueryResults
 * handlers
 * @author Andrew
 *
 */
public interface Provisioner {

	/**
	 *  Register a Publisher message handler to process SIF_Request
	 * 	messages for all object types.

	 *
	 *  @param publisher An object that implements the Publisher
	 *      interface to respond to SIF_Request queries received by the agent.
	 *      This object will be called whenever a SIF_Request is received and
	 *      no other object in the message dispatching chain has
	 *      processed the message.
	 */
	public void setPublisher( Publisher publisher ) throws ADKException;

	/**
	 *  Register a Publisher message handler with this zone to process SIF_Requests
	 * 	for the specified object type. This method may be called repeatedly for
	 * 	each SIF Data Object type the agent will publish on this zone.

	 *
	 *  @param publisher An object that implements the Publisher
	 *      interface to respond to SIF_Request queries received by the agent,
	 *      where the SIF object type referenced by the request matches the
	 *      specified objectType. This Publisher will be called whenever a
	 *      SIF_Request is received on this zone and no other object in the
	 *      message dispatching chain has processed the message.
	 *
	 *  @param objectType An ElementDef constant from the SIFDTD class that
	 *  identifies a SIF Data Object type. E.g. SIFDTD.STUDENTPERSONAL
	 *
	 */
	public void setPublisher( Publisher publisher, ElementDef objectType )
		throws ADKException;

	/**
	 *  Register a Publisher message handler with this zone to process SIF_Requests
	 * 	for the specified object type. This method may be called repeatedly for
	 * 	each SIF Data Object type the agent will publish on this zone.

	 *
	 *  @param publisher An object that implements the Publisher
	 *      interface to respond to SIF_Request queries received by the agent,
	 *      where the SIF object type referenced by the request matches the
	 *      specified objectType. This Publisher will be called whenever a
	 *      SIF_Request is received on this zone and no other object in the
	 *      message dispatching chain has processed the message.
	 *
	 *  @param objectType An ElementDef constant from the SIFDTD class that
	 *  identifies a SIF Data Object type. E.g. SIFDTD.STUDENTPERSONAL
	 *
	 * 	@param options Specify options about which SIF Contexts to join and whether
	 * SIF_Provide messagees will be sent when the agent is running in SIF 1.5r1 or lower
	 */
	public void setPublisher( Publisher publisher, ElementDef objectType, PublishingOptions options )
		throws ADKException;

	/**
	 *  Register a ReportPublisher message handler to respond to
	 * 	SIF_Requests for SIF_ReportObject objects. ReportPublisher is implemented
	 * 	by Vertical Reporting applications that publish report data via the
	 * 	SIF_ReportObject object introduced in SIF 1.5.

	 *
	 *  @param publisher An object that implements the Publisher
	 *      interface to respond to SIF_Request queries received by the agent.
	 *      This object will be called whenever a SIF_Request is received and
	 *      no other object in the message dispatching chain has
	 *      processed the message.
	 *
	 */
	public void setReportPublisher( ReportPublisher publisher )
		throws ADKException;

	/**
	 *  Register a ReportPublisher message handler to respond to
	 * 	SIF_Requests for SIF_ReportObject objects. ReportPublisher is implemented
	 * 	by Vertical Reporting applications that publish report data via the
	 * 	SIF_ReportObject object introduced in SIF 1.5.

	 *
	 *  @param publisher An object that implements the Publisher
	 *      interface to respond to SIF_Request queries received by the agent.
	 *      This object will be called whenever a SIF_Request is received and
	 *      no other object in the message dispatching chain has
	 *      processed the message.
	 *
	 * 	@param options Specify which contexts to join as a provider and whether
	 * to send a SIF_Provide message when the agent is running in SIF 1.5r1 or lower
	 */
	public void setReportPublisher( ReportPublisher publisher, ReportPublishingOptions options )
		throws ADKException;

	/**
	 *  Register a Subscriber message handler with this zone to process SIF_Event
	 * 	messages for the specified object type. This method may be called
	 * 	repeatedly for each SIF Data Object type the agent subscribes to on
	 * 	this zone.

	 *
	 *  @param subscriber An object that implements the Subscriber
	 *      interface to respond to SIF_Event notifications received by the agent,
	 *      where the SIF object type referenced by the request matches the
	 *      specified objectType. This Subscriber will be called whenever a
	 *      SIF_Event is received on this zone and no other object in the
	 *      message dispatching chain has processed the message.
	 *
	 *  @param objectType A constant from the SIFDTD class that identifies a
	 *      SIF Data Object type.
	 *
	 */
	public void setSubscriber( Subscriber subscriber, ElementDef objectType )
		throws ADKException;

	/**
	 *  Register a Subscriber message handler with this zone to process SIF_Event
	 * 	messages for the specified object type. This method may be called
	 * 	repeatedly for each SIF Data Object type the agent subscribes to on
	 * 	this zone.

	 *
	 *  @param subscriber An object that implements the Subscriber
	 *      interface to respond to SIF_Event notifications received by the agent,
	 *      where the SIF object type referenced by the request matches the
	 *      specified objectType. This Subscriber will be called whenever a
	 *      SIF_Event is received on this zone and no other object in the
	 *      message dispatching chain has processed the message.
	 *
	 *  @param objectType A constant from the SIFDTD class that identifies a
	 *      SIF Data Object type.
	 *
	 * 	@param options Specify which contexts to join and whether SIF_Subscribe
	 * messages will be sent when the agent is running in SIF 1.5r1 or lower
	 */
	public void setSubscriber( Subscriber subscriber, ElementDef objectType, SubscriptionOptions options )
		throws ADKException;

	/**
	 *  Register a QueryResults message handler with this zone to process
	 * 	SIF_Response messages for all object types.

	 *
	 *  @param queryResults An object that implements the QueryResults
	 *      interface to respond to SIF_Response query results received by the
	 *      agent. This object will be called whenever a SIF_Response is received
	 *      and no other object in the message dispatching chain has processed the message.
	 */
	public void setQueryResults( QueryResults queryResults )
		throws ADKException;

	/**
	 *  Register a QueryResults object with this zone for the specified SIF object type.

	 *
	 *  @param queryResults An object that implements the QueryResults
	 *      interface to respond to SIF_Response query results received by the agent,
	 *      where the SIF object type referenced by the request matches the
	 *      specified objectType. This QueryResults object will be called whenever
	 *      a SIF_Response is received on this zone and no other object in the
	 *      message dispatching chain has processed the message.
	 *
	 *  @param objectType A constant from the SIFDTD class that identifies a
	 *      SIF Data Object type.
	 *
	 */
	public void setQueryResults( QueryResults queryResults, ElementDef objectType )
		throws ADKException;

	/**
	 *  Register a QueryResults object with this zone for the specified SIF object type.

	 *
	 *  @param queryResults An object that implements the QueryResults
	 *      interface to respond to SIF_Response query results received by the agent,
	 *      where the SIF object type referenced by the request matches the
	 *      specified objectType. This QueryResults object will be called whenever
	 *      a SIF_Response is received on this zone and no other object in the
	 *      message dispatching chain has processed the message.
	 *
	 *  @param objectType A constant from the SIFDTD class that identifies a
	 *      SIF Data Object type.
	 *
	 *  @param options Specify which contexts to join
	 */
	public void setQueryResults( QueryResults queryResults, ElementDef objectType, QueryResultsOptions options )
		throws ADKException;

}


text:
cask 'posterazor' do
  version '1.5'
  sha256 'dbecf2dc00fe2bf106df2e9fd9bc66014015989771db6c369a86d755f516df49'

  # downloads.sourceforge.net/posterazor/ was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/posterazor/Binary%20Releases/#{version}/PosteRazor-#{version}-OSX.dmg"
  appcast 'https://sourceforge.net/projects/posterazor/rss'
  name 'PosteRazor'
  homepage 'https://posterazor.sourceforge.io/'

  app 'PosteRazor.app'
end


text:
magic = get_ipython().magic

import matplotlib.pyplot as plt
import numpy as np
from OPEN.periodograms import gls
from matplotlib.backends.backend_pdf import PdfPages

magic('read /home/joao/yorbit/data/rv_files/HD41248_harps_mean.rdb --skip=2 -v -d')

with PdfPages('consecutive_periodograms.pdf') as pdf:

	for i in reversed(range(155, len(default.time)+1)):
		per = gls(default)
		print 'gls %d points from beginning' % i
		per._plot(verts=[18, 25])
		plt.title('gls %d points from beginning' % i)
		plt.ylim([0, 30])
		plt.xlim([0.1, 1e4])
		pdf.savefig()
		plt.close()
		default.time = np.delete(default.time, -1)
		default.vrad = np.delete(default.vrad, -1)
		default.error = np.delete(default.error, -1)


text:
package com.thoughtworks.go.server.service.support;

import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class MemoryPoolInformationProvider extends AbstractMemoryInformationProvider implements ServerInfoProvider {
    @Override
    public double priority() {
        return 11.0;
    }

    @Override
    public Map<String, Object> asJson() {
        LinkedHashMap<String, Object> json = new LinkedHashMap<>();
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
            Map<String, Object> params = formatInJson(memoryPoolMXBean.getUsage());
            params.put("Type", memoryPoolMXBean.getType());
            json.put(memoryPoolMXBean.getName(), params);
        }
        return json;
    }

    @Override
    public String name() {
        return "Memory Pool Information";
    }
}


text:
<?php declare(strict_types=1);
namespace Phan\Language\Element;

use Phan\Language\Context;
use Phan\Language\FQSEN;
use Phan\Language\FQSEN\FullyQualifiedPropertyName;
use Phan\Language\UnionType;

class Property extends ClassElement
{
    use ElementFutureUnionType;

    /**
     * @param \phan\Context $context
     * The context in which the structural element lives
     *
     * @param string $name,
     * The name of the typed structural element
     *
     * @param UnionType $type,
     * A '|' delimited set of types satisfyped by this
     * typed structural element.
     *
     * @param int $flags,
     * The flags property contains node specific flags. It is
     * always defined, but for most nodes it is always zero.
     * ast\kind_uses_flags() can be used to determine whether
     * a certain kind has a meaningful flags value.
     */
    public function __construct(
        Context $context,
        string $name,
        UnionType $type,
        int $flags,
        FullyQualifiedPropertyName $fqsen
    ) {
        parent::__construct(
            $context,
            $name,
            $type,
            $flags,
            $fqsen
        );
    }

    public function __toString() : string
    {
        $string = '';

        if ($this->isPublic()) {
            $string .= 'public ';
        } elseif ($this->isProtected()) {
            $string .= 'protected ';
        } elseif ($this->isPrivate()) {
            $string .= 'private ';
        }

        // Since the UnionType can be a future, and that
        // can throw an exception, we catch it and ignore it
        try {
            $union_type = $this->getUnionType();
        } catch (\Exception $exception) {
            $union_type = new UnionType();
        }

        $string .= "$union_type {$this->getName()}";

        return $string;
    }

    /**
     * Override the default getter to fill in a future
     * union type if available.
     */
    public function getUnionType() : UnionType
    {
        if (null !== ($union_type = $this->getFutureUnionType())) {
            $this->getUnionType()->addUnionType($union_type);
        }

        return parent::getUnionType();
    }

    /**
     * @return FullyQualifiedPropertyName
     * The fully-qualified structural element name of this
     * structural element
     */
    public function getFQSEN() : FullyQualifiedPropertyName
    {
        assert(!empty($this->fqsen), "FQSEN must be defined");
        return $this->fqsen;
    }
}


text:
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

Current Server Time

                <form class="groups-form" action="/assets-catalog" method="PATCH">
                    <legend>Update groups</legend>
                    <fieldset>
                        <input type="radio" name="asset-id" value="1"/>Asset 1
                        <input type="radio" name="asset-id" value="2"/>Asset 2
                        <input type="radio" name="asset-id" value="3"/>Asset 3
                    </fieldset>
                    <fieldset>
                        <input type="checkbox" name="group" class="group-value" value="a"/>Group A
                        <input type="checkbox" name="group" class="group-value" value="b"/>Group B
                        <input type="checkbox" name="group" class="group-value" value="c"/>Group C
                    </fieldset>
                    <button type="submit" class="btn btn-primary">Apply Groups To Asset</button>
                </form>
                <form class="names-form" action="/assets-catalog" method="PATCH">
                    <legend>Update Names</legend>
                    <fieldset>
                        <input type="radio" name="asset-id" value="1"/>Asset 1
                        <input type="radio" name="asset-id" value="2"/>Asset 2
                        <input type="radio" name="asset-id" value="3"/>Asset 3
                    </fieldset>

                    New Name
                    <input type="text" name="name" class="name-value"/>
                    <button type="submit" class="btn btn-primary">Rename Asset</button>
                </form>

Asset A

Name

Groups

Asset B

Name

Groups

Asset C

Name

Groups


text:
[![](https://img.shields.io/badge/minSDK-15-brightgreen.svg)](https://developer.android.com/training/basics/supporting-devices/platforms.html)
[![](https://jitpack.io/v/Andy671/Dachshund-Tab-Layout.svg)](https://jitpack.io/#Andy671/Dachshund-Tab-Layout)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

# ![Logo](https://raw.githubusercontent.com/Andy671/Dachshund-Tab-Layout/master/dachshund_logo.png)

## Introduction
Boosted Android Tab Layout with custom animated indicators including "Dachshund" animation inspired by [this](https://material.uplabs.com/posts/tab-interaction).

## Sample
![](http://i.giphy.com/1VVYHwT4OFf6U.gif)

## Available Animated Indicators
| Indicator         	|  Example | Custom behavior |
|--------------------- 	|--------------------------------| ----- |
| DachshundIndicator 	| ![](http://i.giphy.com/115nZIzHqsDpcI.gif) | |
| PointMoveIndicator	|![](http://i.giphy.com/yK9y4NcPH7wNa.gif)  | setInterpolator(TimeInterpolator interpolator) |
| LineMoveIndicator 	| ![](http://i.giphy.com/rzvsTmlUOod0I.gif) | setEdgeRadius(int edgeRadius)|
| PointFadeIndicator	| ![](http://i.giphy.com/nQZYOyfYH7gJy.gif)  | |
| LineFadeIndicator 	| ![](http://i.giphy.com/PHUmWmrM0O7YI.gif) | setEdgeRadius(int edgeRadius)|

###

## Installation

### Step 1
Add the JitPack repository to your build file
```gradle
	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}
```

### Step 2
Add the dependency
```gradle
	dependencies {
		compile 'com.github.Andy671:Dachshund-Tab-Layout:v0.3.3'
	}
```

# Usage
DachshundTabLayout is a subclass of TabLayout, so usage is pretty similar. The most of the original methods should work without any problems. See sample and source code for more info.

Add DachshundTabLayout to xml (after the Toolbar in the AppBarLayout), if you have TabLayout simply replace it:
```xml
 <android.support.design.widget.AppBarLayout
 ...
	<android.support.v7.widget.Toolbar
	.../>
	<com.kekstudio.dachshundtablayout.DachshundTabLayout
		android:id="@+id/tab_layout"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"/>
```

Setup it with a ViewPager:
```java
	DachshundTabLayout tabLayout = (DachshundTabLayout) findViewById(R.id.tab_layout);
	tabLayout.setupWithViewPager(yourViewPager);
```

If you want to change animated indicator (see **Available Animated Indicators**):
```java
	//AvailableAnimatedIndicator - change it with available animated indicator

	AvailableAnimatedIndicator indicator = new AvailableAnimatedIndicator(tabLayout);
	tabLayout.setAnimatedIndicator(indicator);
```

## Center align
In **v0.3.2** I've added **ddCenterAlign** parameter. You can use it when you want to center the tabs in **scrollable** tabMode.
Working behavior from [Stackoverflow](https://stackoverflow.com/questions/33191794/android-tablayout-with-active-tab-always-at-center-just-like-in-play-newsstand) question.
```xml
<com.kekstudio.dachshundtablayout.DachshundTabLayout
		...
		custom:tabMode="scrollable"
		custom:ddCenterAlign="true"/>
```

## Creating custom AnimatedIndicator
If you want to create your own custom AnimatedIndicator - you can implement AnimatedIndicatorInterface and if you want to use animators - AnimatorUpdateListener (See JavaDoc of AnimatedIndicatorInterface for more info):
```java
public class CustomIndicator implements AnimatedIndicatorInterface, ValueAnimator.AnimatorUpdateListener {

    private DachshundTabLayout dachshundTabLayout;

    public CustomIndicator(DachshundTabLayout dachshundTabLayout){
        this.dachshundTabLayout = dachshundTabLayout;

    	//here set-up your Animators, Paints etc.
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
    	// when animator updates - invalidate your canvas, and draw what you want.
    }

    @Override
    public void setSelectedTabIndicatorColor(@ColorInt int color) {
        // customization of color
    }

    @Override
    public void setSelectedTabIndicatorHeight(int height) {
        // customization of height
    }

    @Override
    public void setIntValues(int startXLeft, int endXLeft,
                             int startXCenter, int endXCenter,
                             int startXRight, int endXRight){
        // X-positions of the target and current tabs
    }

    @Override
    public void setCurrentPlayTime(long currentPlayTime) {
        // current play time of the animation
    }

    @Override
    public void draw(Canvas canvas) {
        //Make your draw calls here
    }

    @Override
    public long getDuration() {
        return DEFAULT_DURATION;
    }
}
```

## XML Attributes
| Attribute        	| Type                | Default     |
| ----------------------|:-------------------:| :-----------|
| ddIndicatorHeight   	| dimension           | 6dp 	    |
| ddIndicatorColor    	| color               | Color.WHITE |
| ddAnimatedIndicator 	| enum [dachshund, pointMove, lineMove, pointFade, lineFade] | dachshund |

## Contribution
- Feel free to fork the repo, make pull requests or fix existing bug
- Feel free to open issues if you find some bug or unexpected behaviour


text:
namespace OsEngine.Market.Servers.Binance.Spot.BinanceSpotEntity
{
    public class HistoryTrade
    {
        public string id;
        public string price;
        public string qty;
        public string quoteQty;
        public string time;
        public string isBuyerMaker;
        public string isBuyerMatch;
    }
}


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

import torch
import torch.nn as nn
import extlib_cuda as extlib
from abc import ABC, abstractmethod

class DummyJob(object):
    def sync(self):
        pass

class EmbeddingReadOnly(object):
    def __init__(self, embed, gpu_id=-1):
        super(EmbeddingReadOnly, self).__init__()
        self.embed = embed.data
        self.gpu_id = gpu_id
        self.embed_dim = embed.shape[1]
        if gpu_id == -1:
            self.device = 'cpu'
        else:
            self.device = 'cuda:{}'.format(gpu_id)
        if self.embed.is_cuda:
            assert self.embed.device == torch.device(self.device)
        self.dummy_job = DummyJob()
        self.embed.job_handle = self.dummy_job
        self.read_thread_pool = extlib.ThreadPool(1)
        assert gpu_id != -1
        self.stream = torch.cuda.Stream(gpu_id)
        self.default_stream = torch.cuda.default_stream(gpu_id)
        self.read_buf = {}
        self.read_src_cache = {}
        self.last_write_jobs = {}

    def get_or_create_buf(self, name, buf_size, buf_dict, gpu_buf=True):
        if name in buf_dict and buf_dict[name][0].shape[0] >= buf_size:
            return buf_dict[name]
        buf = torch.zeros(buf_size, self.embed_dim, dtype=self.embed.dtype).pin_memory()
        if gpu_buf:
            out = torch.zeros(buf_size, self.embed_dim, dtype=self.embed.dtype).cuda(self.device)
        else:
            out = None
        buf_dict[name] = (buf, out)
        return (buf, out)

    def read(self, indices, name=None):
        if indices is None:
            t = self.embed.to(self.device)
            t.job_handle = self.dummy_job
            return t
        if not self.embed.is_cuda:
            if name is not None and indices.numel() != self.embed.shape[0]:  # TODO: make it more explicit
                return self.async_read(indices, name)
            for key in self.last_write_jobs:
                self.last_write_jobs[key].sync()
        indices = indices.view(-1)
        submat = self.embed[indices].to(self.device)
        submat.job_handle = self.dummy_job
        return submat

    def async_read(self, indices, name):
        assert not indices.is_cuda
        indices = indices.view(-1)
        buf, out = self.get_or_create_buf(name, indices.shape[0], self.read_buf)
        self.read_src_cache[name] = indices
        with torch.cuda.stream(self.stream):
            job_handle = extlib.async_read(self.read_thread_pool,
                                           indices,
                                           self.embed,
                                           buf,
                                           out)
            submat = out[:indices.shape[0]]
            submat.job_handle = job_handle
        return submat

class EmbeddingRW(EmbeddingReadOnly):
    def __init__(self, embed, gpu_id=-1):
        super(EmbeddingRW, self).__init__(embed, gpu_id)
        self.write_thread_pool = self.read_thread_pool
        self.write_buf = {}
        self.write_src_cache = {}

    def write(self, indices, values, name=None, additive=False):
        if self.embed.is_cuda:
            indices = indices.to(self.embed.device)
        elif name is not None:
            return self.async_write(indices, values, name, additive)
        if additive:
            self.embed.index_add_(0, indices, values.to(self.embed.device))
        else:
            self.embed.index_copy_(0, indices, values.to(self.embed.device))
        return self.dummy_job

    def async_write(self, indices, values, name, additive=False):
        src_event = extlib.CudaEvent(self.gpu_id)
        src_event.record()
        indices = indices.view(-1)
        assert indices.is_cuda == False and values.is_cuda
        assert values.shape[0] == indices.shape[0] and values.shape[1] == self.embed_dim
        if name in self.last_write_jobs:
            self.last_write_jobs[name].sync()
        buf, _ = self.get_or_create_buf(name, indices.shape[0], self.write_buf, gpu_buf=False)
        if buf.shape[0] > indices.shape[0]:
            buf = buf[:indices.shape[0]]
        with torch.cuda.stream(self.stream):
            job_handle = extlib.async_write(self.write_thread_pool,
                                            indices,
                                            self.embed,
                                            buf,
                                            values,
                                            src_event,
                                            additive)
        self.write_src_cache[name] = (src_event, indices, values)
        self.last_write_jobs[name] = job_handle
        return job_handle

    def add(self, indices, values, name="default"):
        return self.write(indices, values, name, additive=True)


text:
'use strict';
const assert = require('assert');

let http = require('http');
let https = require('https');
const os = require('os');
const fs = require('fs');
const express = require('../support/express');
const request = require('../support/client');

const app = express();

const key = fs.readFileSync(`${__dirname}/fixtures/key.pem`);
const cert = fs.readFileSync(`${__dirname}/fixtures/cert.pem`);
const cacert = fs.readFileSync(`${__dirname}/fixtures/ca.cert.pem`);
const httpSockPath = [os.tmpdir(), 'superagent-http.sock'].join('/');
const httpsSockPath = [os.tmpdir(), 'superagent-https.sock'].join('/');
let httpServer;
let httpsServer;

if (process.env.HTTP2_TEST) {
  http = https = require('http2');
}

app.get('/', (request_, res) => {
  res.send('root ok!');
});

app.get('/request/path', (request_, res) => {
  res.send('request path ok!');
});

describe('[unix-sockets] http', () => {
  if (process.platform === 'win32') {
    return;
  }

  before((done) => {
    if (fs.existsSync(httpSockPath) === true) {
      // try unlink if sock file exists
      fs.unlinkSync(httpSockPath);
    }

    httpServer = http.createServer(app);
    httpServer.listen(httpSockPath, done);
  });

  const base = `http+unix://${httpSockPath.replace(/\//g, '%2F')}`;

  describe('request', () => {
    it('path: / (root)', (done) => {
      request.get(`${base}/`).end((error, res) => {
        assert(res.ok);
        assert.strictEqual('root ok!', res.text);
        done();
      });
    });

    it('path: /request/path', (done) => {
      request.get(`${base}/request/path`).end((error, res) => {
        assert(res.ok);
        assert.strictEqual('request path ok!', res.text);
        done();
      });
    });
  });

  after(() => {
    if (typeof httpServer.close === 'function') {
      httpServer.close();
    } else httpServer.destroy();
  });
});

describe('[unix-sockets] https', () => {
  if (process.platform === 'win32') {
    return;
  }

  before((done) => {
    if (fs.existsSync(httpsSockPath) === true) {
      // try unlink if sock file exists
      fs.unlinkSync(httpsSockPath);
    }

    httpsServer = process.env.HTTP2_TEST
      ? https.createSecureServer({ key, cert }, app)
      : https.createServer({ key, cert }, app);

    httpsServer.listen(httpsSockPath, done);
  });

  const base = `https+unix://${httpsSockPath.replace(/\//g, '%2F')}`;

  describe('request', () => {
    it('path: / (root)', (done) => {
      request
        .get(`${base}/`)
        .ca(cacert)
        .end((error, res) => {
          assert.ifError(error);
          assert(res.ok);
          assert.strictEqual('root ok!', res.text);
          done();
        });
    });

    it('path: /request/path', (done) => {
      request
        .get(`${base}/request/path`)
        .ca(cacert)
        .end((error, res) => {
          assert.ifError(error);
          assert(res.ok);
          assert.strictEqual('request path ok!', res.text);
          done();
        });
    });
  });

  after((done) => {
    httpsServer.close(done);
  });
});


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

    function seat(dom,options){
        var options=options||{};
        var defaults={
            sections:[{
                columns :13,
                rows:6,
                seatRows:[],
                sectionId:"01",
                sectionName:"默认场区",
            }],
            reachBottom:function(){
                //console.log('f')
            }
        };
        this.settings = $.extend( {}, defaults, options );

        if(typeof dom=='string'){
            this.element=document.querySelector(dom);
        }else{
            this.element=dom;
        }
        this.$element=$(this.element);
        this.init();
        //console.log($el,el);
    }

    seat.prototype.init=function(){

        //var width=this.element.clientWidth;
        //var height=this.element.clientHeight;

        var width=this.settings.sections[0].columns*30+600;
        var height=this.settings.sections[0].rows*30+600;

        var canvas=document.createElement('canvas');

        canvas.setAttribute("width", width);
        canvas.setAttribute("height", height);
        canvas.style.background='#dddddd';
        this.element.appendChild(canvas);

        hb.drag(canvas,{})

        var ctx=canvas.getContext('2d');
        ctx.fillStyle='#FF8800';
        ctx.fillRect(0,0,80,100);
        var img = new Image();
        img.onload = function() {
            ctx.drawImage(img, 0, 0,100,100);
        }
        img.src = "seat.png?v="+new Date().getTime();

    };

    hb.seat=function(dom,options){
        return new seat(dom,options);
    };
}());