text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | empty-state', function(hooks): void {
  setupRenderingTest(hooks);

  test('it renders', async function(assert): Promise<void> {
    await render(hbs`<EmptyState />`);

    assert.equal(this.element.textContent && this.element.textContent.trim(), 'No data found');

    await render(hbs`
      <EmptyState>
        template block text
      </EmptyState>
    `);

    assert.equal(this.element.textContent && this.element.textContent.trim(), 'template block text');
  });

  test('it renders a heading', async function(assert): Promise<void> {
    const heading = 'Not found!';
    assert.expect(1);

    this.set('heading', heading);

    await render(hbs`<EmptyState @heading={{heading}} />`);

    assert.equal(this.element.textContent && this.element.textContent.trim(), heading, 'shows the heading text');
  });

  test('it renders a subheading', async function(assert): Promise<void> {
    const subHeading = 'We could not find any results.';
    assert.expect(1);

    this.set('subHeading', subHeading);

    await render(hbs`<EmptyState @subHead={{subHeading}} />`);

    const subHead = this.element.querySelector('.empty-state__sub-head');
    assert.equal(subHead && subHead.textContent && subHead.textContent.trim(), subHeading, 'shows the subheading text');
  });
});

redpajama_set_name: RedPajamaGithub


text:
package hu.sztaki.phytree;

import hu.sztaki.fileops.FileNumber;
import hu.sztaki.phytree.io.FastaReader;
import hu.sztaki.phytree.io.FastaWriter;
import hu.sztaki.phytree.tree.SeqsToTreeNodes;
import hu.sztaki.phytree.tree.Tree;
import hu.sztaki.phytree.tree.TreeNode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class Main {

  Configuration config;
  boolean renameTreeSeqs = false;
  boolean treeColors = true;
  String outDirPath;
  String pattern;
  String treeDir;
  String fastaDir;

  private boolean checkRequiredConfigPropertiesExist() {
    if (!config.containsKey("treeFilesDir")) {
      System.out
          .println("Please specify a directory with .nwk tree files " +
              "with the \"treeFilesDir\" property!");
      return false;
    } else {
      this.treeDir = config.getString("treeFilesDir");
    }
    if (!config.containsKey("fastaFilesDir")) {
      System.out
          .println("Please specify a directory with .fasta files " +
              "with the \"fastaFilesDir\" property!");
      return false;
    } else {
      this.fastaDir = config.getString("fastaFilesDir");
    }
    if (!config.containsKey("outputTreeFilesDir")) {
      System.out
          .println("Please specify output directory for results " +
              "with the \"outputTreeFilesDir\" property!");
      return false;
    }
    return true;
  }

  private void readConfig(String configFileName) {
    try {
      config = new PropertiesConfiguration(configFileName);
      if (!checkRequiredConfigPropertiesExist()) {
        System.exit(3);
      }
      if (!config.containsKey("seqPattern")) {
        System.out
            .println("Please specify a pattern to search for in sequences " +
                "with the \"seqPattern\" property!");
        return;
      }
      if (config.containsKey("treeColors")) {
        if (config.getString("treeColors").toLowerCase().equals("no")) {
          treeColors = false;
          System.out.println("Output tree coloring is turned OFF");
        }
      }
      outDirPath = config.getString("outputTreeFilesDir");

    } catch (ConfigurationException e) {
      e.printStackTrace();
    }
  }

  private void outputResultSubTrees(TreeNode result, int number, int counter,
    SubTreeSearch ts) throws UnsupportedEncodingException, IOException {

    File targetFile = new File(outDirPath);
    targetFile.mkdirs();

    String subtree = "(" + result.getNewickSubtree(treeColors) + ");";
    String resultFileName = outDirPath + File.separator + "sub" + number + "tree" + counter;

    OutputStream outputTree = new FileOutputStream(resultFileName + ".nwk");
    outputTree.write(subtree.getBytes("UTF-8"));
    outputTree.flush();
    outputTree.close();
    FastaWriter fastaWriter = new FastaWriter(new FileOutputStream(resultFileName + ".fasta"));

    List<FastaItem> fastaResult = ts.getFastaResult(result);
    fastaWriter.writeOrderedFastaList(fastaResult , config.getString("seqPattern"));
    System.out.println("Written: " + resultFileName + ".nwk and .fasta\n");
  }

  private int[] doSearchSubtrees(Tree tree) {
    int allNodeCnt = 0;
    int patternNodeCnt = 0;
    try {
      SubTreeSearch ts = new SubTreeSearch();
      ts.setConfig(config);
      List<TreeNode> results = ts.findSubtrees(tree);
      if (results.size() > 0) {
        int treeId = tree.getKey();
        System.out.println("Number of result subtrees for input tree :" +
              treeId + " is " + results.size());
        int counter = 0;
        for (TreeNode res : results) {
          outputResultSubTrees(res, treeId, counter, ts);
          counter++;
          patternNodeCnt += res.getLeafNumWithPattern("HD");
          allNodeCnt += res.getLeafNum();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    int[] ret = {allNodeCnt, patternNodeCnt};
    return ret;
  }

  private void searchSubtrees() {
    TreeAndFastaFilesMatcher filesMatcher = new TreeAndFastaFilesMatcher(treeDir, fastaDir);
    List<Tree> treeList = filesMatcher.getTreesWithSequences();
    int allNodes = 0;
    int patternNodes = 0;
    for (Tree tree : treeList) {
      int[] nums = doSearchSubtrees(tree);
      allNodes += nums[0];
      patternNodes += nums[1];
    }
    System.out.println("All nodes found in all subtrees: " + allNodes + " of which " +
        patternNodes + " contain the required pattern");
  }

  public static void main(String[] args) {
    if (args.length == 1) {
      Main m = new Main();
      m.readConfig(args[0]);
      m.searchSubtrees();
    } else {
      System.out.println("Expecting 1 arguments: propertiesFile");
      System.out.println("Found args: " + args.length);
      return;
    }
  }
}


text:
package com.amazonaws.services.lookoutmetrics.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum Frequency {

    P1D("P1D"),
    PT1H("PT1H"),
    PT10M("PT10M"),
    PT5M("PT5M");

    private String value;

    private Frequency(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return Frequency corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static Frequency fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (Frequency enumEntry : Frequency.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package test.prefuse.visual;

import java.util.Iterator;

import junit.framework.TestCase;
import prefuse.Visualization;
import prefuse.visual.AggregateTable;
import prefuse.visual.VisualItem;
import prefuse.visual.VisualTable;
import test.prefuse.data.TableTest;

public class VisualAggregateTableTest extends TestCase {

    private AggregateTable m_agg;
    private VisualTable m_items;

    protected void setUp() throws Exception {
        Visualization v = new Visualization();
        m_items = v.addTable("items", TableTest.getTestCaseTable());

        m_agg = v.addAggregates("aggregates", VisualItem.SCHEMA);
        m_agg.addRow();
        m_agg.addRow();

        Iterator iter = m_items.tuples();
        for ( int i=0, count=m_items.getRowCount(); iter.hasNext(); ++i ) {
            VisualItem item = (VisualItem)iter.next();
            int j = i<count/2 ? 0 : 1;
            m_agg.addToAggregate(j, item);
        }
    }

    protected void tearDown() throws Exception {
        m_items = null;
        m_agg = null;
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.getAggregateSize(int)'
     */
    public void testGetAggregateSize() {
        int cc = m_items.getRowCount();
        int s1 = cc/2, s2 = cc-s1;
        assertEquals(s1, m_agg.getAggregateSize(0));
        assertEquals(s2, m_agg.getAggregateSize(1));
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.addToAggregate(int, Tuple)'
     */
    public void testAddToAggregate() {
        VisualItem t = m_items.getItem(0);
        int size = m_agg.getAggregateSize(1);
        assertFalse(m_agg.aggregateContains(1, t));
        m_agg.addToAggregate(1, t);
        assertTrue(m_agg.aggregateContains(1, t));
        assertEquals(size+1, m_agg.getAggregateSize(1));
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.removeFromAggregate(int, Tuple)'
     */
    public void testRemoveFromAggregate() {
        int s = m_agg.getAggregateSize(0);

        assertTrue(m_agg.aggregateContains(0, m_items.getItem(0)));
        m_agg.removeFromAggregate(0, m_items.getItem(0));
        assertFalse(m_agg.aggregateContains(0, m_items.getItem(0)));
        assertEquals(--s, m_agg.getAggregateSize(0));

        assertTrue(m_agg.aggregateContains(0, m_items.getItem(1)));
        m_agg.removeFromAggregate(0, m_items.getItem(1));
        assertFalse(m_agg.aggregateContains(0, m_items.getItem(1)));
        assertEquals(--s, m_agg.getAggregateSize(0));
    }

    public void testRemoveFromAggregateUnderIteration() {
        int s = m_agg.getAggregateSize(0);
        Iterator iter = m_agg.aggregatedTuples(0);
        while ( iter.hasNext() ) {
            VisualItem t = (VisualItem)iter.next();
            assertTrue(m_agg.aggregateContains(0, t));
            m_agg.removeFromAggregate(0, t);
            assertEquals(--s, m_agg.getAggregateSize(0));
            assertFalse(m_agg.aggregateContains(0, t));
        }
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.removeAllFromAggregate(int)'
     */
    public void testRemoveAllFromAggregate() {
        m_agg.removeAllFromAggregate(0);
        m_agg.removeAllFromAggregate(1);
        assertEquals(0, m_agg.getAggregateSize(0));
        assertEquals(0, m_agg.getAggregateSize(1));
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.aggregateContains(int, Tuple)'
     */
    public void testAggregateContains() {
        VisualItem vi0 = m_items.getItem(0);
        VisualItem vi1 = m_items.getItem(m_items.getRowCount()-1);
        assertTrue(m_agg.aggregateContains(0, vi0));
        assertTrue(m_agg.aggregateContains(1, vi1));
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.aggregatedTuples(int)'
     */
    public void testAggregatedTuples() {
        int s = m_agg.getAggregateSize(0);
        Iterator iter = m_agg.aggregatedTuples(0);
        int count = 0;
        for ( ; iter.hasNext(); ++count ) {
            VisualItem t = (VisualItem)iter.next();
            assertTrue(m_agg.aggregateContains(0, t));
        }
        assertEquals(s, count);
    }

    /*
     * Test method for 'prefuse.data.tuple.AggregateTable.getAggregates(Tuple)'
     */
    public void testGetAggregates() {
        for ( int i=0; i<2; ++i ) {
            Iterator iter = m_agg.aggregatedTuples(0);
            while ( iter.hasNext() ) {
                VisualItem t = (VisualItem)iter.next();
                Iterator aggr = m_agg.getAggregates(t);
                assertEquals(m_agg.getTuple(0), aggr.next());
            }
        }
    }

}


text:
namespace cpptorch
{
    namespace nn
    {
        template<typename T, GPUFlag F>
        class Add : public Layer<T, F>
        {
        public:
            virtual const std::string name() const override { return "nn.Add"; }
            virtual Tensor<T, F> forward(const Tensor<T, F> &input) const override;

        protected:
            bool scalar_;
            Tensor<T, F> bias_, gradBias_, _ones_;
        };
    }
}


text:
@interface ViewController ()
@property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *textFields;

@property (nonatomic, strong) NSMutableArray *contents;
@property (nonatomic, assign) sqlite3  *db;
@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    if ([self fileExist]) {
        [self loadSqliteData];
    }

}

- (void)loadPlistData{

    NSArray *lines = [NSArray arrayWithContentsOfFile:[self filePath]];

    for (NSInteger i = 0; i < lines.count; i ++) {
        UITextField *tf = self.textFields[i];
        tf.text = lines[i];
    }

}

- (void)loadSqliteData{

    sqlite3 *db ;

    if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK) {
        NSLog(@"open db failed");
        return ;
    }

    NSString *querySQL = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(db, [querySQL UTF8String], -1, &stmt, NULL) == SQLITE_OK) {

        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int row = sqlite3_column_int(stmt, 0);
            char* ctext = (char*)sqlite3_column_text(stmt, 1);

            UITextField *tf = self.textFields[row];

            tf.text = [NSString stringWithUTF8String:ctext];

        }
        sqlite3_finalize(stmt);
    }
    sqlite3_close(db);

}

- (void)loadArchiveData{
    NSData *readData = [NSData dataWithContentsOfFile:[self filePath]];

    NSKeyedUnarchiver *unchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readData];

    LZFileContent *fileContent = [unchiver decodeObjectForKey:@"fileContent"];

    for (NSInteger i = 0; i < fileContent.content.count; i ++) {
        UITextField *tf = self.textFields[i];
        tf.text = fileContent.content[i];
    }

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}

- (NSString *)filePath{

    NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    NSString *filelPath = [basePath stringByAppendingPathComponent:kFileName];

    return filelPath;
}

- (void)applicationWillResignActive:(NSNotification *)noti{

    [self saveBySqlite3];
}

- (BOOL)fileExist{

    return [[NSFileManager defaultManager] fileExistsAtPath:[self filePath]];

}

- (void)prePareBeforeSave{

    if ([self fileExist]) {

        [[NSFileManager defaultManager] removeItemAtPath:[self filePath] error:nil];

    }
    self.contents = [NSMutableArray array];
    for (UITextField *tf  in self.textFields) {

        [self.contents addObject:tf.text];

    }

}

- (void)saveDataByPlist{

    [self prePareBeforeSave];

    [self.contents writeToFile:[self filePath] atomically:YES];

}

- (void)saveDataByArchive{

    [self prePareBeforeSave];

    LZFileContent *fileContent = [[LZFileContent alloc] init];
    fileContent.content = self.contents;

    NSMutableData *saveData = [NSMutableData data];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:saveData];

    [archiver encodeObject:fileContent forKey:@"fileContent"];

    [archiver finishEncoding];

    [saveData writeToFile:[self filePath] atomically:YES];

}

- (BOOL)sqlitePrepare{

    if (![self fileExist]) {
        sqlite3 *db ;

        if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK) {
            NSLog(@"create db failed");
            return NO;
        }

        NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS FIELDS(ROW INTEGER PRIMERY KEY, FIELD_DATA TEXT);";

        char *errMSG = NULL;

        if (sqlite3_exec(db, [createTableSQL UTF8String], NULL, NULL, &errMSG) != SQLITE_OK) {
            sqlite3_close(db);
            NSLog(@"create table error %s", errMSG);
            return NO;
        }
        self.db = db;
    }
    return YES;
}

- (void)saveBySqlite3{

    if (![self sqlitePrepare]) {
        return;
    }
    for (int i = 0; i < 4; i ++) {
        UITextField *tf = self.textFields[i];
        char *updateSQL = "INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES(?, ?);";
        char *errMSG = NULL;
        sqlite3_stmt *stmt;
        if (sqlite3_prepare_v2(self.db, updateSQL, -1, &stmt, NULL) == SQLITE_OK) {
            sqlite3_bind_int(stmt, 1, i);
            sqlite3_bind_text(stmt, 2, [tf.text UTF8String], -1, NULL);
        }
        if (sqlite3_step(stmt) != SQLITE_DONE) {
            NSLog(@"update table fail");
            sqlite3_finalize(stmt);
            sqlite3_close(self.db);
            return ;

        }
        sqlite3_finalize(stmt);
    }
    sqlite3_close(self.db);

}
@end


text:
local M = {}

local ta_regex = require 'ta-regex.pegex'

-- Replace textadept's events.FIND handler with one implementing better regex.

function M.install()
    events.connect(events.FIND, M.find, 1)
end

-- Find expression forwards from the current point.
function M.find(regex, forward)
    local pat = ta_regex.compile(regex)

    -- Search a subset of the buffer, and adjust the match to set the
    -- start/end pointers correctly.
    local function search(startpos, endpos)
        local m = pat:match(buffer:text_range(startpos, endpos))
        if m then
            -- Adjust result to take account of startpos
            m._start = m._start + startpos - 1
            m._end = m._end + startpos
        end
        return m
    end

    -- As search(), but search backwards.
    -- This isn't as efficient, as it searches forward and waits for the
    -- last match.
    local function search_rev(startpos, endpos)
        local res = nil
        while true do
            local m = search(startpos, endpos)
            if m then
                -- a later match than we'd previously had
                res = m

                -- Start searching from this point (non-overlapping)
                startpos = m._end
            else
                -- no other matches - return the last we got.
                break
            end
        end
        return res
    end

    local m = nil
    if forward then
        local startpos = buffer.current_pos + 1
        local endpos = buffer.length

        -- If we're at the end of the buffer, then start from
        -- the beginning.
        if startpos >= endpos then startpos = 0 end

        m = search(startpos, endpos) or search(0, endpos)
    else
        local startpos = 0
        local endpos = buffer.current_pos

        m = search_rev(startpos, endpos) or search_rev(0, buffer.length)
    end

    if m then
        local s, e = m._start, m._end
        buffer:set_sel(e, s)
    else
        ui.statusbar_text = "Not found"
    end

    return false
end

return M


text:
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyTitle("SvgNet Visual Test")]
[assembly: AssemblyDescription("Testing the C# framework for creating SVG images")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("RiskCare Ltd, SvgNet and SvgGdi Bridge Project, Rafael Teixeira, Mojmír Němeček, Benjamin Peterson")]
[assembly: AssemblyProduct("SvgNet")]
[assembly: AssemblyCopyright("Copyright 2003, 2010, 2015 RiskCare Ltd, SvgNet and SvgGdi Bridge Project, Rafael Teixeira, Mojmír Němeček, Benjamin Peterson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]

[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]


text:
> List of binary file extensions

The list is just a [JSON file](binary-extensions.json) and can be used wherever.

## Install

```
$ npm install --save binary-extensions
```

## Usage

```js
var binaryExtensions = require('binary-extensions');

console.log(binaryExtensions);
//=> ['3ds', '3g2', ...]
```

## Related

- [`is-binary-path`](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file
- [`text-extensions`](https://github.com/sindresorhus/text-extensions) - List of text file extensions

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)


text:
package org.jtwig.resource.loader;

import com.google.common.base.Optional;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class StringResourceLoaderTest {
    private StringResourceLoader underTest = StringResourceLoader.instance();

    @Test
    public void charset() throws Exception {
        Optional<Charset> result = underTest.getCharset("path");

        assertThat(result.isPresent(), is(false));
    }

    @Test
    public void exists() throws Exception {
        boolean result = underTest.exists("path");

        assertThat(result, is(true));
    }

    @Test
    public void load() throws Exception {
        InputStream result = underTest.load("path");

        assertThat(IOUtils.toString(result), is("path"));
    }

    @Test
    public void toUrl() throws Exception {
        Optional<URL> result = underTest.toUrl("path");

        assertThat(result.isPresent(), is(false));
    }
}


text:
using System;
using Windows.UI.Xaml.Data;

namespace LangTransRT.Common
{
	/// <summary>
	/// true를 false로, false를 true로 변환하는 값 변환기입니다.
	/// </summary>
	public sealed class BooleanNegationConverter : IValueConverter
	{
		public object Convert ( object value, Type targetType, object parameter, string language )
		{
			return !( value is bool && ( bool ) value );
		}

		public object ConvertBack ( object value, Type targetType, object parameter, string language )
		{
			return !( value is bool && ( bool ) value );
		}
	}
}


text:
<!-- This file was autogenerated via cilium cmdref, do not edit manually-->

## cilium bpf policy

Manage policy related BPF maps

### Options

```
  -h, --help   help for policy
```

### Options inherited from parent commands

```
      --config string   config file (default is $HOME/.cilium.yaml)
  -D, --debug           Enable debug messages
  -H, --host string     URI to server-side API
```

### SEE ALSO

* [cilium bpf](../cilium_bpf)	 - Direct access to local BPF maps
* [cilium bpf policy add](../cilium_bpf_policy_add)	 - Add/update policy entry
* [cilium bpf policy delete](../cilium_bpf_policy_delete)	 - Delete a policy entry
* [cilium bpf policy get](../cilium_bpf_policy_get)	 - List contents of a policy BPF map


text:
from .api_key import APIKeyCookie as APIKeyCookie
from .api_key import APIKeyHeader as APIKeyHeader
from .api_key import APIKeyQuery as APIKeyQuery
from .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials
from .http import HTTPBasic as HTTPBasic
from .http import HTTPBasicCredentials as HTTPBasicCredentials
from .http import HTTPBearer as HTTPBearer
from .http import HTTPDigest as HTTPDigest
from .oauth2 import OAuth2 as OAuth2
from .oauth2 import OAuth2AuthorizationCodeBearer as OAuth2AuthorizationCodeBearer
from .oauth2 import OAuth2PasswordBearer as OAuth2PasswordBearer
from .oauth2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestForm
from .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrict
from .oauth2 import SecurityScopes as SecurityScopes
from .open_id_connect_url import OpenIdConnect as OpenIdConnect


text:
{% extends 'federation/providers/base.html' %}

{% load common ui %}

{% block head_title %}Create provider{% endblock %}

{% block subnav_providers_create %}active{% endblock %}

{% block breadcrumbs %}
{% url federation_providers_create as url %}{% breadcrumb 'Create provider' url %}{{ block.super }}
{% endblock %}

{% block title %}

Create Provider

{% endblock title %}

{% block content %}
  <form action="" method="post" class="form-horizontal">
    <fieldset>
      {% csrf_token %}

      {% form_errors form %}

      {% form_field form.name 'Name' %}
      {% form_field form.provider_uri 'Provider URI' %}

        <button class="btn btn-primary" type="submit">Create provider</button>

    </fieldset>
  </form>
{% endblock %}


text:
s{{ define "base" }}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Gophish - Open-Source Phishing Toolkit">
    <meta name="author" content="Jordan Wright (http://github.com/jordan-wright)">
    <link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">

    <title>{{ .Title }} - Phishaway</title>

    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,600,700' rel='stylesheet' type='text/css'>

    <link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
    <link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="../assets/global/css/components.min.css" rel="stylesheet" id="style_components" type="text/css" />
    <link href="../assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" />

    <link href="../assets/pages/css/login.min.css" rel="stylesheet" type="text/css" />

        <form class="form-signin" action="/register" method="POST">

Please register below

            {{template "flashes" .Flashes}}

                <button class="close" data-close="alert"></button>
                 Enter any username and password.

                Username

                    <input type="text" name="username" class="form-control top-input placeholder-no-fix" placeholder="Username" required autofocus/>

                Password

                    <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" />

                Confirm Password

                    <input type="password" name="confirm_password" class="form-control bottom-input" placeholder="Confirm Password" required/>
                    <input type="hidden" name="csrf_token" value="{{.Token}}"/>

                <button type="submit" class="btn green pull-right"> Register </button>

 2017 © Triskele Labs

        </form>

{{ end }}


text:
module Store
    ( store
    , retrieve
    ) where

import           Data.ByteString            (ByteString)
import qualified Data.ByteString.Char8 as C (pack, unpack)
import           Database.Redis
import           System.Environment         (getEnv, lookupEnv)

store :: ByteString -> ByteString -> IO (Either String ())
store key value = do
  conn <- connect =<< getConnectionSettings
  fmap (either replyResult statusResult) <$> runRedis conn $ set key value

retrieve :: ByteString -> IO (Either String ByteString)
retrieve key = do
  conn <- connect =<< getConnectionSettings
  fmap (either replyResult returnResult) <$> runRedis conn $ get key

replyResult :: Reply -> Either String a
replyResult (SingleLine s) = Left (C.unpack s)
replyResult (Error e)      = Left (C.unpack e)
replyResult (Integer i)    = Left (show i)
replyResult (Bulk _)       = Left "Bulk"
replyResult (MultiBulk _)  = Left "MultiBulk..."

returnResult :: Maybe ByteString -> Either String ByteString
returnResult = maybe (Left "no result") Right

statusResult :: Status -> Either String ()
statusResult Ok         = Right ()
statusResult Pong       = Left "pong..."
statusResult (Status s) = Left (C.unpack s)

getConnectionSettings :: IO ConnectInfo
getConnectionSettings = connectionSettings <$> getRedisHost
                                           <*> getRedisPort
                                           <*> tryGetRedisPassword

connectionSettings :: HostName -> PortID -> Maybe ByteString -> ConnectInfo
connectionSettings host port pass = defaultConnectInfo { connectHost = host
                                                       , connectPort = port
                                                       , connectAuth = pass
                                                       }

getRedisHost :: IO HostName
getRedisHost = getEnv "YUMMY_REDIS_HOST"

getRedisPort :: IO PortID
getRedisPort = PortNumber . fromInteger . read <$> getEnv "YUMMY_REDIS_PORT"

tryGetRedisPassword :: IO (Maybe ByteString)
tryGetRedisPassword = fmap C.pack <$> lookupEnv "YUMMY_REDIS_AUTH"


text:
using System;

namespace Light.DataCore
{
    class LightBinaryQueryExpression : QueryExpression
    {
        readonly QueryPredicate _predicate;

        readonly object _left;

        readonly object _right;

        public LightBinaryQueryExpression(DataEntityMapping mapping, QueryPredicate predicate, object left, object right)
            : base(mapping)
        {
            _predicate = predicate;
            _left = left;
            _right = right;
        }

        internal override string CreateSqlString(CommandFactory factory, bool isFullName, CreateSqlState state)
        {
            string sql = null;

            DataFieldInfo leftInfo = _left as DataFieldInfo;
            DataFieldInfo rightInfo = _right as DataFieldInfo;
            if (!Object.Equals(leftInfo, null) && !Object.Equals(rightInfo, null)) {
                string leftSql = leftInfo.CreateSqlString(factory, isFullName, state);
                string rightSql = rightInfo.CreateSqlString(factory, isFullName, state);
                sql = factory.CreateSingleParamSql(leftSql, _predicate, rightSql);
            }
            else if (!Object.Equals(leftInfo, null)) {
                string leftSql = leftInfo.CreateSqlString(factory, isFullName, state);
                object right = LambdaExpressionExtend.ConvertLambdaObject(_right);
                if (Object.Equals(right, null)) {
                    bool predicate;
                    if (_predicate == QueryPredicate.Eq) {
                        predicate = true;
                    }
                    else if (_predicate == QueryPredicate.NotEq) {
                        predicate = false;
                    }
                    else {
                        throw new LightDataException(string.Format(SR.UnsupportPredicate, _predicate, "null"));
                    }
                    sql = factory.CreateNullQuerySql(leftSql, predicate);
                }
                else if (right is bool) {
                    bool predicate;
                    if (_predicate == QueryPredicate.Eq) {
                        predicate = true;
                    }
                    else if (_predicate == QueryPredicate.NotEq) {
                        predicate = false;
                    }
                    else {
                        throw new LightDataException(string.Format(SR.UnsupportPredicate, _predicate, "bool"));
                    }
                    bool ret = (bool)right;
                    sql = factory.CreateBooleanQuerySql(leftSql, ret, predicate, false);
                }
                else {
                    string name = state.AddDataParameter(factory, right);
                    sql = factory.CreateSingleParamSql(leftSql, _predicate, name);
                }
            }
            else if (!Object.Equals(rightInfo, null)) {
                string rightSql = rightInfo.CreateSqlString(factory, isFullName, state);
                object left = LambdaExpressionExtend.ConvertLambdaObject(_left);
                if (Object.Equals(left, null)) {
                    bool predicate;
                    if (_predicate == QueryPredicate.Eq) {
                        predicate = true;
                    }
                    else if (_predicate == QueryPredicate.NotEq) {
                        predicate = false;
                    }
                    else {
                        throw new LightDataException(string.Format(SR.UnsupportPredicate, _predicate, "null"));
                    }
                    sql = factory.CreateNullQuerySql(rightSql, predicate);
                }
                else if (left is bool) {
                    bool predicate;
                    if (_predicate == QueryPredicate.Eq) {
                        predicate = true;
                    }
                    else if (_predicate == QueryPredicate.NotEq) {
                        predicate = false;
                    }
                    else {
                        throw new LightDataException(string.Format(SR.UnsupportPredicate, _predicate, "bool"));
                    }
                    bool ret = (bool)left;
                    sql = factory.CreateBooleanQuerySql(rightSql, ret, predicate, true);
                }
                else {
                    string name = state.AddDataParameter(factory, left);
                    sql = factory.CreateSingleParamSql(name, _predicate, rightSql);
                }
            }
            else {
                throw new LightDataException(SR.DataFieldContentError);
            }
            return sql;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;

namespace ContactApp.Web.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IActionResult Get([FromQuery, Required]SearchOptions searchOptions)
        {
            var searchResults = new[] {
                                new { id = searchOptions.Id, Name = searchOptions.Name },
                            }.ToList();

            var formattedResult = JsonConvert.SerializeObject(searchResults, Formatting.Indented);

            Response.Headers.Add("x-total-count", searchResults.Count.ToString());

            return Ok(formattedResult);
        }

        // GET api/values/5
        [HttpGet("{id:int:min(1)}", Name = "GetById")]
        public IActionResult GetById([Required]int id)
        {
            try
            {
                var obj = new { id = id, name = "name" };
                var jsonObj = JsonConvert.SerializeObject(obj, Formatting.Indented);

                return Ok(jsonObj);
            }
            catch (KeyNotFoundException)
            {
                Response.Headers.Add("x-status-reason", $"No resource was found with the unique identifier '{id}'.");
                return NotFound();
            }
        }

        [HttpGet("{name}")]
        public IActionResult GetByName([Required]string name)
        {
            Response.Headers.Add("x-status-reason", $"The value '{name}' is not recognised as a valid integer to uniquely identify a resource.");
            return BadRequest();
        }

        // POST api/values
        [HttpPost]
        public IActionResult Post([FromBody]string value)
        {
            return Created($"api/Values/{value}", value);
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody]string value)
        {
            return Accepted(value);
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            return NoContent();
        }
    }
}


text:
package com.zaradai.gluon.quickstart;

import com.zaradai.gluon.MicroService;
import com.zaradai.gluon.server.MicroServiceFactory;

import java.util.function.Function;

public class Squared implements Function<Double, Double> {
    // Typically in a production system you wouldn't have the service name within the same package that inplements it as
    // it would add a dependency on the client.
    public static final String SERVICE_NAME = "Squared";
    // create a convenient factory that can create a micro service from a Function
    public static MicroService<Double, Double> create() {
        return MicroServiceFactory.create(Squared.SERVICE_NAME, new Squared());
    }

    @Override
    public Double apply(Double input) {
        return input * input;
    }
}


text:
package com.leavjenn.hews.data.local;

import com.leavjenn.hews.model.Comment;
import com.leavjenn.hews.model.Post;
import com.pushtorefresh.storio.sqlite.operations.delete.DeleteResult;
import com.pushtorefresh.storio.sqlite.operations.put.PutResult;
import com.pushtorefresh.storio.sqlite.operations.put.PutResults;

import java.util.List;

import rx.Observable;

public interface LocalContract {
    Observable<PutResult> putPostToDb(Post post);

    Observable<List<Post>> getPostFromDb(long postId);

    Observable<List<Post>> getAllPostsFromDb();

    Observable<DeleteResult> deletePostFromDb(Post post);

    Observable<PutResults<Comment>> putCommentsToDb(List<Comment> commentList);

    Observable<List<Comment>> getStoryCommentsFromDb(long postId);

    Observable<DeleteResult> deleteStoryCommentsFromDb(long postId);

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Pixelhive</title>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque adipisci nemo, cum aliquid earum doloremque magni facere doloribus minus ipsum, unde quod libero explicabo vitae animi rerum autem impedit illo.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque adipisci nemo, cum aliquid earum doloremque magni facere doloribus minus ipsum, unde quod libero explicabo vitae animi rerum autem impedit illo.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa praesentium adipisci nam voluptatum dolorum officia ea dolores placeat libero quasi sit illum, unde architecto porro inventore, facilis est repudiandae nemo!


text:
.class final synthetic Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;
.super Ljava/lang/Object;

# interfaces
.implements Ljava/lang/Runnable;

# instance fields
.field private final synthetic -$f0:Ljava/lang/Object;

.field private final synthetic -$f1:Ljava/lang/Object;

.field private final synthetic -$f2:Ljava/lang/Object;

# direct methods
.method private final synthetic $m$0()V
    .locals 3

    iget-object v0, p0, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->-$f0:Ljava/lang/Object;

    check-cast v0, Lcom/android/server/autofill/RemoteFillService;

    iget-object v1, p0, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->-$f1:Ljava/lang/Object;

    check-cast v1, Lcom/android/server/autofill/RemoteFillService$PendingRequest;

    iget-object v2, p0, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->-$f2:Ljava/lang/Object;

    check-cast v2, Ljava/lang/CharSequence;

    invoke-virtual {v0, v1, v2}, Lcom/android/server/autofill/RemoteFillService;->lambda$-com_android_server_autofill_RemoteFillService_11423(Lcom/android/server/autofill/RemoteFillService$PendingRequest;Ljava/lang/CharSequence;)V

    return-void
.end method

.method public synthetic constructor <init>(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->-$f0:Ljava/lang/Object;

    iput-object p2, p0, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->-$f1:Ljava/lang/Object;

    iput-object p3, p0, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->-$f2:Ljava/lang/Object;

    return-void
.end method

# virtual methods
.method public final run()V
    .locals 0

    invoke-direct {p0}, Lcom/android/server/autofill/-$Lambda$JYqZriexGNVTrQ5cwTlcgjPSZFY$3;->$m$0()V

    return-void
.end method


text:
package com.tianyu.jty.system.dao;

import org.springframework.stereotype.Repository;

import com.tianyu.jty.common.persistence.HibernateDao;
import com.tianyu.jty.system.entity.Organization;

/**
 * 机构DAO
 * @author kkomge
 * @date 2015年5月09日
 */
@Repository
public class OrganizationDao extends HibernateDao<Organization, Integer>{

}


text:
package org.apache.juddi.v3.tck;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;

import java.rmi.RemoteException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.juddi.jaxb.EntityCreator;
import org.junit.Assert;
import org.uddi.api_v3.BusinessDetail;
import org.uddi.api_v3.BusinessEntity;
import org.uddi.api_v3.CategoryBag;
import org.uddi.api_v3.DeleteBusiness;
import org.uddi.api_v3.Description;
import org.uddi.api_v3.GetBusinessDetail;
import org.uddi.api_v3.KeyedReference;
import org.uddi.api_v3.KeyedReferenceGroup;
import org.uddi.api_v3.SaveBusiness;
import org.uddi.v3_service.UDDIInquiryPortType;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
 * @author Kurt T Stam
 * @author Jeff Faath
 */
public class TckBusiness
{
	final static String JOE_BUSINESS_XML        = "uddi_data/joepublisher/businessEntity.xml";
    final static String JOE_BUSINESS_KEY        = "uddi:uddi.joepublisher.com:businessone";
    final static String JOE_BUSINESS3_XML       = "uddi_data/joepublisher/businessEntity3.xml";
    final static String JOE_BUSINESS3_KEY       = "uddi:uddi.joepublisher.com:businessthree.com";
    final static String JOE_BUSINESS_MOVE_XML   = "uddi_data/joepublisher/moveBusinessService1to3.xml";
    final static String MARY_BUSINESS_XML       = "uddi_data/marypublisher/businessEntity.xml";
    final static String MARY_BUSINESS_KEY       = "uddi:uddi.marypublisher.com:marybusinessone";
    final static String SAM_BUSINESS_XML        = "uddi_data/samsyndicator/businessEntity.xml";
    final static String SAM_BUSINESS_WITHPROJECTION_XML = "uddi_data/samsyndicator/businessEntity_withProjection.xml";
    final static String SAM_BUSINESS_KEY        = "uddi:www.samco.com:samco";
    final static String COMBINE_CATBAGS_BIZ_XML = "uddi_data/joepublisher/combineCatBagsBusinessServices.xml";
    final static String COMBINE_CATBAGS_BIZ_KEY = "uddi:uddi.joepublisher.com:business01";
    public final static String RIFTSAW_BUSINESS_KEY    = "uddi:riftsaw.jboss.org:business_redhat-jboss";
    public final static String RIFTSAW_BUSINESS_XML    = "uddi_data/bpel/riftsaw/businessEntity.xml";

    final static String SIGNATURE_KEYSTORE = "uddi_data/signature/signature.jks";
    final static String SIGNATURE_KEYSTORE_TYPE = "JKS";
    final static String SIGNATURE_KEYSTORE_PASSWORD = "changeit";
    final static String SIGNATURE_KEYSTORE_ALIAS = "mykey";

    private Log logger = LogFactory.getLog(this.getClass());
	private UDDIPublicationPortType publication = null;
    private UDDIInquiryPortType inquiry = null;

	public TckBusiness(UDDIPublicationPortType publication,
				  UDDIInquiryPortType inquiry) {
		super();
		this.publication = publication;
		this.inquiry = inquiry;
	}

	public void saveSamSyndicatorBusiness(String authInfoSam) {
		saveBusiness(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY);
	}

	public void saveSamSyndicatorBusinesses(String authInfoSam, int numberOfCopies) {
		saveBusinesses(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY, numberOfCopies);
	}

	public void saveSamSyndicatorBusinessWithProjection(String authInfoSam) {
		saveBusiness(authInfoSam, SAM_BUSINESS_WITHPROJECTION_XML, SAM_BUSINESS_KEY);
	}

	public void deleteSamSyndicatorBusiness(String authInfoSam) {
		deleteBusiness(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY);
	}

	public void deleteSamSyndicatorBusinesses(String authInfoSam, int numberOfCopies) {
		deleteBusinesses(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY, numberOfCopies);
	}

        public void saveJoePublisherBusinessX509Signature(String authInfoJoe) {
            saveBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY);
            signBusiness(authInfoJoe, JOE_BUSINESS_KEY);
            verifyBusinessSignature(authInfoJoe, JOE_BUSINESS_KEY);
        }

	public void saveJoePublisherBusiness(String authInfoJoe) {
		saveBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, true);
    }

	public void saveCombineCatBagsPublisherBusiness(String authInfoJoe) {
		saveBusiness(authInfoJoe, COMBINE_CATBAGS_BIZ_XML, COMBINE_CATBAGS_BIZ_KEY);
    }

	public void saveJoePublisherBusiness3(String authInfoJoe) {
		saveBusiness(authInfoJoe, JOE_BUSINESS3_XML, JOE_BUSINESS3_KEY);
    }

	public void saveJoePublisherBusiness1to3(String authInfoJoe) {
		saveBusiness(authInfoJoe, JOE_BUSINESS_MOVE_XML, JOE_BUSINESS3_KEY);
    }

	public void saveMaryPublisherBusiness(String authInfoMary) {
		saveBusiness(authInfoMary, MARY_BUSINESS_XML, MARY_BUSINESS_KEY);
    }

	public void updateJoePublisherBusiness(String authInfoJoe) {
		updateBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY);
    }

	public void saveJoePublisherBusinesses(String authInfoJoe, int numberOfCopies) {
    	saveBusinesses(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, numberOfCopies);
    }

	public void deleteJoePublisherBusiness(String authInfoJoe) {
    	deleteBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY);
    }

	public void deleteJoePublisherBusiness3(String authInfoJoe) {
    	deleteBusiness(authInfoJoe, JOE_BUSINESS3_XML, JOE_BUSINESS3_KEY);
    }

	public void deleteMaryPublisherBusiness(String authInfoMary) {
    	deleteBusiness(authInfoMary, MARY_BUSINESS_XML, MARY_BUSINESS_KEY);
    }

	public void deleteJoePublisherBusinesses(String authInfoJoe, int numberOfCopies) {
    	deleteBusinesses(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, numberOfCopies);
    }

	public void checkServicesBusinessOne(int expectedNumberOfServices) {
		checkNumberOfServices(JOE_BUSINESS_KEY,expectedNumberOfServices);
	}

	public void checkServicesBusinessThree(int expectedNumberOfServices) {
		checkNumberOfServices(JOE_BUSINESS3_KEY,expectedNumberOfServices);
	}

	public void saveBusinesses(String authInfo, String businessXML, String businessKey, int numberOfCopies) {
		try {
			BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3");
			String businessName = beIn.getName().get(0).getValue();
			for (int i=0; i<numberOfCopies; i++) {
				SaveBusiness sb = new SaveBusiness();
				sb.setAuthInfo(authInfo);
				beIn.getName().get(0).setValue(businessName + "-" + i);
				beIn.setBusinessKey(businessKey + "-" + i);
				sb.getBusinessEntity().add(beIn);
				publication.saveBusiness(sb);
				logger.debug("Saved business with key " + businessName + "-" + i);
			}

		} catch(Throwable e) {
			logger.error(e.getMessage(),e);
			Assert.fail("No exception should be thrown");
		}
	}

	public void checkNumberOfServices(String businessKey, int expectedServices) {

		try {
			GetBusinessDetail gb = new GetBusinessDetail();
			gb.getBusinessKey().add(businessKey);
			BusinessDetail bd;
			bd = inquiry.getBusinessDetail(gb);
			List<BusinessEntity> beOutList = bd.getBusinessEntity();
			BusinessEntity beOut = beOutList.get(0);
			if (expectedServices > 0) {
				assertEquals(expectedServices, beOut.getBusinessServices().getBusinessService().size());
			} else {
				Assert.assertNull(beOut.getBusinessServices());
			}
		} catch (RemoteException e) {
			logger.error(e.getMessage(),e);
			Assert.fail("No exception should be thrown");
		}
	}

        public void signBusiness(String authInfo, String businessKey) {
            try {
                GetBusinessDetail gb = new GetBusinessDetail();
                gb.getBusinessKey().add(businessKey);
                BusinessDetail bd = inquiry.getBusinessDetail(gb);
                List<BusinessEntity> beOutList = bd.getBusinessEntity();
                BusinessEntity bizEntity = beOutList.get(0);
                bizEntity.getSignature().clear();
                BusinessEntity bizEntitySigned = signJAXBObject(bizEntity);

                SaveBusiness sb = new SaveBusiness();
                sb.setAuthInfo(authInfo);
                sb.getBusinessEntity().add(bizEntitySigned);
                publication.saveBusiness(sb);
            } catch(Throwable e) {
                logger.error(e.getMessage(),e);
                Assert.fail("No exception should be thrown");
            }
        }

        public void verifyBusinessSignature(String authInfo, String businessKey) {
            try {
                GetBusinessDetail gb = new GetBusinessDetail();
                gb.getBusinessKey().add(businessKey);
                BusinessDetail bd = inquiry.getBusinessDetail(gb);
                List<BusinessEntity> beOutList = bd.getBusinessEntity();
                BusinessEntity bizEntity = beOutList.get(0);

                boolean sigOk = verifySignedJAXBObject(bizEntity);
                assertTrue("Signature invalid!", sigOk);
            } catch(Throwable e) {
                logger.error(e.getMessage(),e);
                Assert.fail("No exception should be thrown");
            }
        }

        private <T> T signJAXBObject(T jaxbObj) {
            DOMResult domResult = new DOMResult();
            JAXB.marshal(jaxbObj, domResult);
            Document doc = ((Document)domResult.getNode());
            Element docElement = doc.getDocumentElement();

            try {
                KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE);
                URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE);
                ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray());
                KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray()));
                PrivateKey privateKey = keyEntry.getPrivateKey();
                Certificate origCert = keyEntry.getCertificate();
                PublicKey validatingKey = origCert.getPublicKey();
                TckSigningUtil.signDOM(docElement, privateKey, origCert);

                DOMSource domSource = new DOMSource(doc);
                T result = (T)JAXB.unmarshal(domSource, jaxbObj.getClass());
                return result;
            } catch (Exception e) {
                throw new RuntimeException("Signature failure due to: " + e.getMessage(), e);
            }
        }

        private boolean verifySignedJAXBObject(Object obj) {
            try {
                DOMResult domResult = new DOMResult();
                JAXB.marshal(obj, domResult);
                Document doc = ((Document)domResult.getNode());
                Element docElement = doc.getDocumentElement();

                KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE);
                URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE);
                ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray());
                KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray()));
                PrivateKey privateKey = keyEntry.getPrivateKey();
                Certificate origCert = keyEntry.getCertificate();
                PublicKey validatingKey = origCert.getPublicKey();
                return TckSigningUtil.verifySignature(docElement, validatingKey);
            } catch (Exception e) {
                throw new RuntimeException (e);
            }
        }

        public void saveBusiness(String authInfo, String businessXML, String businessKey) {
            saveBusiness(authInfo, businessXML, businessKey, false);
        }
	public void saveBusiness(String authInfo, String businessXML, String businessKey, boolean serialize) {
		try {
			SaveBusiness sb = new SaveBusiness();
			sb.setAuthInfo(authInfo);

			BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3");
			sb.getBusinessEntity().add(beIn);

			publication.saveBusiness(sb);

			// Now get the entity and check the values
			GetBusinessDetail gb = new GetBusinessDetail();
			gb.getBusinessKey().add(businessKey);
			BusinessDetail bd = inquiry.getBusinessDetail(gb);
			List<BusinessEntity> beOutList = bd.getBusinessEntity();
			BusinessEntity beOut = beOutList.get(0);

            if (serialize) {
                JAXB.marshal(beOut, new File("target/aftersave.xml"));
            }

			assertEquals(beIn.getBusinessKey(), beOut.getBusinessKey());

			TckValidator.checkNames(beIn.getName(), beOut.getName());
			TckValidator.checkDescriptions(beIn.getDescription(), beOut.getDescription());
			TckValidator.checkDiscoveryUrls(beIn.getDiscoveryURLs(), beOut.getDiscoveryURLs());
			TckValidator.checkContacts(beIn.getContacts(), beOut.getContacts());
			TckValidator.checkCategories(beIn.getCategoryBag(), beOut.getCategoryBag());
			TckValidator.checkSignatures(beIn.getSignature(), beOut.getSignature());
		} catch(Throwable e) {
			logger.error(e.getMessage(),e);
			Assert.fail("No exception should be thrown");
		}

	}

	public void updateBusiness(String authInfo, String businessXML, String businessKey) {
		try {

			// Now get the entity and check the values
			GetBusinessDetail gb = new GetBusinessDetail();
			gb.getBusinessKey().add(businessKey);
			BusinessDetail bd = inquiry.getBusinessDetail(gb);
			List<BusinessEntity> beOutList = bd.getBusinessEntity();
			BusinessEntity beOut = beOutList.get(0);
			//We are expecting 2 services
			assertEquals(2,beOut.getBusinessServices().getBusinessService().size());

			//Now updating the business by adding another description
			SaveBusiness sb = new SaveBusiness();
			sb.setAuthInfo(authInfo);
			BusinessEntity beIn = beOut;
			Description desc2= new Description();
			desc2.setLang("nl");
			desc2.setValue("Omschrijving");
			beIn.getDescription().add(desc2);
			sb.getBusinessEntity().add(beIn);
			publication.saveBusiness(sb);

			// Now get the entity and check the values
			BusinessDetail bdnew = inquiry.getBusinessDetail(gb);
			List<BusinessEntity> beOutListNew = bdnew.getBusinessEntity();
			BusinessEntity beOutNew = beOutListNew.get(0);

			assertEquals(beIn.getBusinessKey(), beOutNew.getBusinessKey());
			// After the update we still are supposed to see two services.
			assertNotNull(beOutNew.getBusinessServices());
			assertEquals(2,beOutNew.getBusinessServices().getBusinessService().size());

		} catch(Throwable e) {
			logger.error(e.getMessage(),e);
			Assert.fail("No exception should be thrown");
		}

	}

	public void deleteBusinesses(String authInfo, String businessXML, String businessKey, int numberOfCopies) {
		try {
			for (int i=0; i<numberOfCopies; i++) {
				// Delete the entity and make sure it is removed
				String key = businessKey + "-" + i;
				DeleteBusiness db = new DeleteBusiness();
				db.setAuthInfo(authInfo);
				db.getBusinessKey().add(key);
				publication.deleteBusiness(db);
				logger.debug("Deleted business with key " + key);
			}

		} catch(Exception e) {
			logger.error(e.getMessage(),e);
			Assert.fail("No exception should be thrown");
		}
	}

	public void deleteBusiness(String authInfo, String businessXML, String businessKey) {
		try {
			// Delete the entity and make sure it is removed
			DeleteBusiness db = new DeleteBusiness();
			db.setAuthInfo(authInfo);
			db.getBusinessKey().add(businessKey);
			publication.deleteBusiness(db);

		} catch(Exception e) {
			logger.error(e.getMessage(),e);
			Assert.fail("No exception should be thrown");
		}
	}

}


text:
Standalone Golang webserver which receives webhooks from Gitlab and forwards them to more than one channel in Slack.
Current Slack service integration in Gitlab specifies only one channel.

Currently supports only commit webhooks.

### Usage

After building with ```go build``` run it as follows:

```gitlab2slack -c #channel -c @user -d domain -t token -l 0.0.0.0:8080```

#### Parameters:

 - ```-c```, ```--channel``` - Slack channel(s) (one or more) to send Gitlab messages to
 - ```-d```, ```--domain``` - Slack domain
 - ```-t```, ```--token``` - Slack incoming webhook token
 - ```-l```, ```--listen``` - IP:port pair on which to listen for requests

Incoming Gitlab webook requests should arrive on ```http://your-address:8080/gitlab```. Add a webhook with that URL for a project on your Gitlab.

### Docker

Buil the docker image as follows:

```docker build -t gitlab2slack .```

Then run it with the following options:

```docker run -p 8080:5000 gitlab2slack -c #channel -c @user -d domain -t token```


text:
package collectors

import (
	"os"
	"strconv"
	"strings"

	"github.com/oliveagle/go-collectors/datapoint"
	"github.com/oliveagle/go-collectors/metadata"
	// "github.com/oliveagle/go-collectors/util"
)

func init() {
	collectors = append(collectors, &IntervalCollector{F: c_conntrack_linux, Enable: conntrackEnable})
}

const (
	conntrackCount = "/proc/sys/net/netfilter/nf_conntrack_count"
	conntrackMax   = "/proc/sys/net/netfilter/nf_conntrack_max"
)

func conntrackEnable() bool {
	f, err := os.Open(conntrackCount)
	defer f.Close()
	return err == nil
}

func c_conntrack_linux() (datapoint.MultiDataPoint, error) {
	var md datapoint.MultiDataPoint
	var max, count float64
	if err := readLine(conntrackCount, func(s string) error {
		values := strings.Fields(s)
		if len(values) > 0 {
			var err error
			count, err = strconv.ParseFloat(values[0], 64)
			if err != nil {
				return nil
			}
			Add(&md, "linux.net.conntrack.count", count, nil, metadata.Gauge, metadata.Count, "")
		}
		return nil
	}); err != nil {
		return nil, err
	}
	if err := readLine(conntrackMax, func(s string) error {
		values := strings.Fields(s)
		if len(values) > 0 {
			var err error
			max, err = strconv.ParseFloat(values[0], 64)
			if err != nil {
				return nil
			}
			Add(&md, "linux.net.conntrack.max", max, nil, metadata.Gauge, metadata.Count, "")
		}
		return nil
	}); err != nil {
		return nil, err
	}
	if max != 0 {
		Add(&md, "linux.net.conntrack.percent_used", count/max*100, nil, metadata.Gauge, metadata.Pct, "")
	}
	return md, nil
}


text:
package com.xeiam.xchange.cryptsy;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xeiam.xchange.cryptsy.dto.CryptsyOrder;
import com.xeiam.xchange.cryptsy.dto.CryptsyOrder.CryptsyOrderType;
import com.xeiam.xchange.cryptsy.dto.account.CryptsyAccountInfo;
import com.xeiam.xchange.cryptsy.dto.account.CryptsyAccountInfoReturn;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyBuyOrder;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyGetMarketsReturn;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyMarketData;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyMarketTradesReturn;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyOrderBook;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyOrderBookReturn;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyPublicMarketData;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyPublicOrder;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyPublicOrderbook;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyPublicTrade;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsySellOrder;
import com.xeiam.xchange.cryptsy.dto.trade.CryptsyOpenOrders;
import com.xeiam.xchange.cryptsy.dto.trade.CryptsyOpenOrdersReturn;
import com.xeiam.xchange.cryptsy.dto.trade.CryptsyTradeHistory;
import com.xeiam.xchange.cryptsy.dto.trade.CryptsyTradeHistoryReturn;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.Order.OrderType;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trade;
import com.xeiam.xchange.dto.marketdata.Trades;
import com.xeiam.xchange.dto.marketdata.Trades.TradeSortType;
import com.xeiam.xchange.dto.trade.LimitOrder;
import com.xeiam.xchange.dto.trade.OpenOrders;
import com.xeiam.xchange.dto.trade.UserTrade;
import com.xeiam.xchange.dto.trade.UserTrades;
import com.xeiam.xchange.dto.trade.Wallet;

/**
 * @author ObsessiveOrange
 */
public final class CryptsyAdapters {

  public static final Logger log = LoggerFactory.getLogger(CryptsyAdapters.class);

  /**
   * Adapt CryptsyOrderBookReturn DTO to XChange OrderBook DTO
   *
   * @param cryptsyOrderBookReturn Raw returned data from Cryptsy, CryptsyOrderBookReturn DTO
   * @param currencyPair The market for which this orderbook belongs to (Not given in Cryptsy response)
   * @return Standard XChange OrderBook DTO
   */
  public static OrderBook adaptOrderBook(CryptsyOrderBookReturn cryptsyOrderBookReturn, CurrencyPair currencyPair) {

    CryptsyOrderBook cryptsyOrderBook = cryptsyOrderBookReturn.getReturnValue();

    List<LimitOrder> asks = CryptsyAdapters.adaptSellOrders(cryptsyOrderBook.sellOrders(), currencyPair);
    List<LimitOrder> bids = CryptsyAdapters.adaptBuyOrders(cryptsyOrderBook.buyOrders(), currencyPair);

    return new OrderBook(null, asks, bids);
  }

  /**
   * Private method for adapting a list of CryptsySellOrders to LimitOrders
   *
   * @param sellOrders List of CryptsySellOrders
   * @param currencyPair The market for which this list belongs to (Usually not given in Cryptsy response)
   * @return Standard XChange LimitOrder DTO
   */
  private static List<LimitOrder> adaptSellOrders(List<CryptsySellOrder> sellOrders, CurrencyPair currencyPair) {

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>();

    if (sellOrders != null) {
      for (CryptsySellOrder order : sellOrders) {

        limitOrders.add(new LimitOrder(OrderType.ASK, order.getQuantity(), currencyPair, null, null, order.getSellPrice()));
      }
    }

    return limitOrders;
  }

  /**
   * Private method for adapting a list of CryptsyBuyOrders to LimitOrders
   *
   * @param buyOrders List of CryptsyBuyOrders
   * @param currencyPair The market for which this list belongs to (Usually not given in Cryptsy response)
   * @return Standard XChange LimitOrder DTO
   */
  private static List<LimitOrder> adaptBuyOrders(List<CryptsyBuyOrder> buyOrders, CurrencyPair currencyPair) {

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>();

    if (buyOrders != null) {
      for (CryptsyBuyOrder order : buyOrders) {

        limitOrders.add(new LimitOrder(OrderType.BID, order.getQuantity(), currencyPair, null, null, order.getBuyPrice()));
      }
    }

    return limitOrders;
  }

  public static List<OrderBook> adaptPublicOrderBooks(Map<Integer, CryptsyPublicOrderbook> cryptsyOrderBooks) {

    List<OrderBook> orderBooks = new ArrayList<OrderBook>();
    for (CryptsyPublicOrderbook cryptsyOrderBook : cryptsyOrderBooks.values()) {
      CurrencyPair currencyPair = adaptCurrencyPair(cryptsyOrderBook.getLabel());
      List<LimitOrder> asks = adaptPublicOrders(cryptsyOrderBook.getSellOrders(), OrderType.ASK, currencyPair);
      List<LimitOrder> bids = adaptPublicOrders(cryptsyOrderBook.getBuyOrders(), OrderType.BID, currencyPair);

      orderBooks.add(new OrderBook(null, asks, bids));
    }

    return orderBooks;
  }

  private static List<LimitOrder> adaptPublicOrders(List<CryptsyPublicOrder> orders, OrderType orderType, CurrencyPair currencyPair) {

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>();

    if (orders != null) {
      for (CryptsyPublicOrder order : orders) {

        limitOrders.add(new LimitOrder(orderType, order.getQuantity(), currencyPair, null, null, order.getPrice()));
      }
    }

    return limitOrders;
  }

  /**
   * Adapts CryptsyMarketTradesReturn DTO to XChange standard Trades DTO
   *
   * @param cryptsyTrades Raw returned data from Cryptsy, CryptsyMarketTradesReturn DTO
   * @param currencyPair The market for which this list belongs to (Usually not given in Cryptsy response)
   * @return Standard XChange Trades DTO
   */
  public static Trades adaptTrades(CryptsyMarketTradesReturn cryptsyTrades, CurrencyPair currencyPair) {

    List<Trade> tradesList = new ArrayList<Trade>();
    long lastTradeId = 0;
    for (CryptsyOrder trade : cryptsyTrades.getReturnValue()) {
      long tradeId = trade.getTradeId();
      if (tradeId > lastTradeId) {
        lastTradeId = tradeId;
      }
      tradesList.add(adaptTrade(trade, currencyPair));
    }
    return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
  }

  /**
   * Private method for adapting a CryptsyOrder to Trade
   *
   * @param order CryptsyOrder DTO to be adapted
   * @param currencyPair The market for which this CryptsyOrder belongs to (Usually not given in Cryptsy response)
   * @return Standard XChange Trade DTO
   */
  private static Trade adaptTrade(CryptsyOrder order, CurrencyPair currencyPair) {

    OrderType orderType = order.getType() == CryptsyOrderType.Buy ? OrderType.BID : OrderType.ASK;

    return new Trade(orderType, order.getQuantity(), currencyPair, order.getPrice(), order.getTime(), String.valueOf(order.getTradeId()));
  }

  public static Map<CurrencyPair, Trades> adaptPublicTrades(Map<Integer, CryptsyPublicMarketData> cryptsyMarketData) {

    Map<CurrencyPair, Trades> trades = new HashMap<CurrencyPair, Trades>();
    for (CryptsyPublicMarketData cryptsyMarketDataEntry : cryptsyMarketData.values()) {
      CurrencyPair currencyPair = adaptCurrencyPair(cryptsyMarketDataEntry.getLabel());
      List<Trade> tradesList = new ArrayList<Trade>();
      long lastTradeId = 0;
      List<CryptsyPublicTrade> recentTrades = cryptsyMarketDataEntry.getRecentTrades();
      if (recentTrades != null) {
        for (CryptsyPublicTrade trade : recentTrades) {
          long tradeId = trade.getId();
          if (tradeId > lastTradeId) {
            lastTradeId = tradeId;
          }
          tradesList.add(adaptTrade(trade, currencyPair));
        }
      }
      trades.put(currencyPair, new Trades(tradesList, lastTradeId, TradeSortType.SortByID));
    }

    return trades;
  }

  private static Trade adaptTrade(CryptsyPublicTrade trade, CurrencyPair currencyPair) {

    OrderType type = null;

    if (trade.getType() != null) {
      type = trade.getType().equalsIgnoreCase("Buy") ? OrderType.BID : OrderType.ASK;
    }

    return new Trade(type, trade.getQuantity(), currencyPair, trade.getPrice(), trade.getTime(), String.valueOf(trade.getId()));
  }

  /**
   * Adapts CryptsyGetMarketsReturn DTO to XChange standard Ticker DTO Note: Cryptsy does not natively have a Ticker method, so getMarkets function
   * will have to be called to get summary data
   *
   * @param marketsReturnData Raw returned data from Cryptsy, CryptsyGetMarketsReturn DTO
   * @param currencyPair The market for which this CryptsyGetMarketsReturn belongs to (Usually not given in Cryptsy response)
   * @return Standard XChange Ticker DTO
   */
  public static Ticker adaptTicker(CryptsyGetMarketsReturn marketsReturnData, CurrencyPair currencyPair) {

    List<CryptsyMarketData> marketData = marketsReturnData.getReturnValue();

    String label = currencyPair.toString().replace("_", "/");

    CryptsyMarketData targetMarket = null;
    for (CryptsyMarketData currMarket : marketData) {
      if (currMarket.getLabel().equalsIgnoreCase(label)) {
        targetMarket = currMarket;
        break;
      }
    }

    BigDecimal last = targetMarket.getLast();
    BigDecimal bid = null;
    BigDecimal ask = null;
    BigDecimal high = targetMarket.getHigh();
    BigDecimal low = targetMarket.getLow();
    BigDecimal volume = targetMarket.get24hVolume();

    Date timestamp = targetMarket.getCreatedTime();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
  }

  public static List<Ticker> adaptPublicTickers(Map<Integer, CryptsyPublicMarketData> marketsReturnData) {

    List<Ticker> tickers = new ArrayList<Ticker>();
    for (CryptsyPublicMarketData publicMarketData : marketsReturnData.values()) {
      tickers.add(adaptPublicTicker(publicMarketData));
    }
    return tickers;
  }

  /**
   * Adapts CryptsyPublicMarketData DTO to XChange standard Ticker DTO Note: Cryptsy does not natively have a Ticker method, so getCryptsyMarketData
   * function will have to be called to get summary data
   *
   * @param publicMarketData Raw returned data from Cryptsy, CryptsyGetMarketsReturn DTO
   * @return Standard XChange Ticker DTO
   */
  public static Ticker adaptPublicTicker(CryptsyPublicMarketData publicMarketData) {

    List<CryptsyPublicTrade> recentTrades = publicMarketData.getRecentTrades();
    BigDecimal last = (recentTrades != null && recentTrades.size() > 0) ? recentTrades.get(0).getPrice() : null;
    List<CryptsyPublicOrder> bids = publicMarketData.getBuyOrders();
    BigDecimal bid = (bids != null && bids.size() > 0) ? bids.get(0).getPrice() : null;
    List<CryptsyPublicOrder> asks = publicMarketData.getSellOrders();
    BigDecimal ask = (asks != null && asks.size() > 0) ? asks.get(0).getPrice() : null;
    BigDecimal high = null;
    BigDecimal low = null;
    BigDecimal volume = publicMarketData.getVolume();

    Date timestamp = publicMarketData.getLastTradeTime();
    return new Ticker.Builder().currencyPair(adaptCurrencyPair(publicMarketData)).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp)
            .build();
  }

  /**
   * Adapts CryptsyAccountInfoReturn DTO to XChange standard AccountInfo DTO
   *
   * @param cryptsyAccountInfoReturn Raw returned data from Cryptsy, CryptsyAccountInfoReturn DTO
   * @return Standard XChange AccountInfo DTO
   */
  public static AccountInfo adaptAccountInfo(CryptsyAccountInfoReturn cryptsyAccountInfoReturn) {

    CryptsyAccountInfo cryptsyAccountInfo = cryptsyAccountInfoReturn.getReturnValue();

    List<Wallet> wallets = new ArrayList<Wallet>();
    Map<String, BigDecimal> funds = cryptsyAccountInfo.getAvailableFunds();

    for (String lcCurrency : funds.keySet()) {
      String currency = lcCurrency.toUpperCase();

      wallets.add(new Wallet(currency, funds.get(lcCurrency)));
    }
    return new AccountInfo(null, wallets);
  }

  /**
   * Adapts CryptsyOpenOrdersReturn DTO to XChange standard OpenOrd ers DTO
   *
   * @param openOrdersReturnValue Raw returned data from Cryptsy, CryptsyOpenOrdersReturn DTO
   * @return Standard XChange OpenOrders DTO
   */
  public static OpenOrders adaptOpenOrders(CryptsyOpenOrdersReturn openOrdersReturnValue) {

    List<CryptsyOpenOrders> cryptsyOpenOrders = openOrdersReturnValue.getReturnValue();

    List<LimitOrder> limitOrders = new ArrayList<LimitOrder>();
    if (cryptsyOpenOrders != null) {
      for (CryptsyOpenOrders order : cryptsyOpenOrders) {

        OrderType orderType = order.getTradeType() == CryptsyOrderType.Buy ? OrderType.BID : OrderType.ASK;

        limitOrders.add(new LimitOrder(orderType, order.getQuantityRemaining(), CryptsyCurrencyUtils.convertToCurrencyPair(order.getMarketId()),
                String.valueOf(order.getOrderId()), order.getTimestamp(), order.getPrice()));

      }
    }
    return new OpenOrders(limitOrders);
  }

  /**
   * Adapts CryptsyTradeHistoryReturn DTO to XChange standard Trades DTO
   *
   * @param tradeHistoryReturnData Raw returned data from Cryptsy, CryptsyTradeHistoryReturn DTO
   * @return Standard XChange Trades DTO
   */
  public static UserTrades adaptTradeHistory(CryptsyTradeHistoryReturn tradeHistoryReturnData) {

    List<CryptsyTradeHistory> cryptsyTradeHistory = tradeHistoryReturnData.getReturnValue();

    List<UserTrade> trades = new ArrayList<UserTrade>();
    if (cryptsyTradeHistory != null) {
      for (CryptsyTradeHistory trade : cryptsyTradeHistory) {
        OrderType tradeType = trade.getTradeType() == CryptsyOrderType.Buy ? OrderType.BID : OrderType.ASK;
        CurrencyPair currencyPair = CryptsyCurrencyUtils.convertToCurrencyPair(trade.getMarketId());

        trades.add(new UserTrade(tradeType, trade.getQuantity(), currencyPair, trade.getPrice(), trade.getTimestamp(),
                String.valueOf(trade.getTradeId()), String.valueOf(trade.getOrderId()), trade.getFee(), currencyPair.counterSymbol));
      }
    }
    return new UserTrades(trades, TradeSortType.SortByTimestamp);
  }

  /**
   * Adapts CryptsyPublicMarketData DTO's to List<CurrencyPair> Used mainly by CryptsyBasePollingService to update list of CurrencyPairs and Markets
   *
   * @param cryptsyPublicMarketData returned data from Cryptsy
   * @return Collection<CurrencyPair>
   */
  public static Collection<CurrencyPair> adaptCurrencyPairs(Map<Integer, CryptsyPublicMarketData> cryptsyPublicMarketData) {

    Set<CurrencyPair> pairs = new HashSet<CurrencyPair>();
    for (CryptsyPublicMarketData cryptsyMarket : cryptsyPublicMarketData.values()) {
      pairs.add(adaptCurrencyPair(cryptsyMarket));
    }

    return pairs;
  }

  public static CurrencyPair adaptCurrencyPair(CryptsyPublicMarketData cryptsyPublicMarketData) {

    return new CurrencyPair(cryptsyPublicMarketData.getPrimaryCurrencyCode(), cryptsyPublicMarketData.getSecondaryCurrencyCode());
  }

  public static CurrencyPair adaptCurrencyPair(String cryptsyLabel) {

    return new CurrencyPair(cryptsyLabel);
  }

  /**
   * Adapts CryptsyPublicMarketData DTO's to HashMap[2] of markets, keyed by marketId, and Name Used mainly by CryptsyBasePollingService to update
   * list of CurrencyPairs and Markets
   *
   * @param cryptsyPublicMarketData returned data from Cryptsy
   * @return HashMap[2] of markets, keyed by marketId, and Name
   */
  @SuppressWarnings({ "unchecked", "rawtypes" })
  public static HashMap[] adaptMarketSets(Map<Integer, CryptsyPublicMarketData> cryptsyPublicMarketData) {

    HashMap[] marketSets = new HashMap[2];

    marketSets[0] = new HashMap<Integer, CurrencyPair>();
    marketSets[1] = new HashMap<CurrencyPair, Integer>();

    for (CryptsyPublicMarketData currMarketData : cryptsyPublicMarketData.values()) {
      CurrencyPair currencyPair = adaptCurrencyPair(currMarketData.getLabel());

      ((HashMap<Integer, CurrencyPair>) marketSets[0]).put(currMarketData.getMarketId(), currencyPair);
      ((HashMap<CurrencyPair, Integer>) marketSets[1]).put(currencyPair, currMarketData.getMarketId());
    }

    return marketSets;
  }

  public static Map<Integer, CryptsyPublicMarketData> adaptPublicMarketDataMap(Map<String, CryptsyPublicMarketData> rawData) {

    Map<Integer, CryptsyPublicMarketData> resultData = new HashMap<Integer, CryptsyPublicMarketData>();
    for (CryptsyPublicMarketData cryptsyPublicMarketData : rawData.values()) {
      resultData.put(cryptsyPublicMarketData.getMarketId(), cryptsyPublicMarketData);
    }
    return resultData;
  }

  public static Map<Integer, CryptsyPublicOrderbook> adaptPublicOrderBookMap(Map<String, CryptsyPublicOrderbook> rawData) {

    Map<Integer, CryptsyPublicOrderbook> resultData = new HashMap<Integer, CryptsyPublicOrderbook>();
    for (CryptsyPublicOrderbook cryptsyPublicOrderBook : rawData.values()) {
      resultData.put(cryptsyPublicOrderBook.getMarketId(), cryptsyPublicOrderBook);
    }
    return resultData;
  }
}


text:
Rails.application.routes.draw do
  mount DelayedJobProgress::Engine => "/delayed_job_progress"
end


text:
namespace minigo {

namespace internal {

ModelBatcher::ModelBatcher(std::unique_ptr<Model> model_impl, int buffer_count)
    : model_impl_(std::move(model_impl)), stats_(buffer_count) {}

ModelBatcher::~ModelBatcher() {
  MG_LOG(INFO) << "Ran " << num_batches_ << " batches with an average size of "
               << static_cast<float>(num_inferences_) / num_batches_;
}

void ModelBatcher::StartGame() {
  absl::MutexLock lock(&mutex_);
  num_active_clients_ += 1;
}

void ModelBatcher::EndGame() {
  absl::MutexLock lock(&mutex_);
  num_active_clients_ -= 1;
  MaybeRunBatchesLocked();
}

void ModelBatcher::RunMany(ModelBatcher* other_batcher,
                           const std::vector<const ModelInput*>& inputs,
                           std::vector<ModelOutput*>* outputs,
                           std::string* model_name) {
  WTF_SCOPE("ModelBatcher::RunMany", size_t)(inputs.size());

  absl::Notification notification;

  {
    absl::MutexLock lock(&mutex_);
    queue_.push({other_batcher, &inputs, outputs, model_name, &notification});
    if (other_batcher != nullptr) {
      other_batcher->num_waiting_ += 1;
    }
    MaybeRunBatchesLocked();
  }

  if (other_batcher != nullptr) {
    absl::MutexLock lock(&other_batcher->mutex_);
    other_batcher->MaybeRunBatchesLocked();
  }

  notification.WaitForNotification();
}

BatchingModelStats ModelBatcher::FlushStats() {
  mutex_.Lock();
  auto result = stats_;
  stats_ = BatchingModelStats(stats_.buffer_count);
  mutex_.Unlock();
  return result;
}

size_t ModelBatcher::GetBatchSize() const {
  return std::max<size_t>(1, num_active_clients_ / stats_.buffer_count);
}

void ModelBatcher::MaybeRunBatchesLocked() {
  while (!queue_.empty()) {
    auto queue_size = queue_.size();
    if (queue_size < GetBatchSize()) {
      // The queue doesn't have enough requests to fill a batch: see if we
      // can run a smaller batch instead.
      //
      // We run a small batch if all clients of this model have either
      // submitted inference requests, or are in a two player game and
      // waiting for the other player's inference.
      //
      // Additionally... when starting a bunch of games in parallel, we
      // will initially submit several smaller batches until all the
      // clients have been created. This has a ripple effect across all
      // subsequent reads, making the batching irregular. To counteract
      // this, we additionally enforce the constraint that a small batch
      // can't be run until at least half of the clients have submitted
      // inference requests. This has the effect of forcing those clients
      // to run their batches in lock-step.
      bool can_run_small_batch =
          queue_size >= num_active_clients_ / stats_.buffer_count &&
          queue_size + num_waiting_ >= num_active_clients_;
      if (!can_run_small_batch) {
        break;
      }
    }

    RunBatch();
  }
}

void ModelBatcher::RunBatch() {
  WTF_SCOPE0("ModelBatcher::RunBatch");
  auto run_batch_start_time = absl::Now();

  auto batch_size = GetBatchSize();

  // TODO(tommadams): reserve GetBatchSize() * virtual_losses elements.
  std::vector<const ModelInput*> inputs;
  std::vector<ModelOutput*> outputs;
  std::vector<InferenceRequest> inferences;

  while (!queue_.empty() && inferences.size() < batch_size) {
    auto& inference = queue_.front();
    size_t num_features = inference.inputs->size();

    std::copy_n(inference.inputs->begin(), num_features,
                std::back_inserter(inputs));
    std::copy_n(inference.outputs->begin(), num_features,
                std::back_inserter(outputs));
    inferences.push_back(inference);

    queue_.pop();
  }

  num_batches_ += 1;
  num_inferences_ += inputs.size();
  auto num_inferences_in_batch = inputs.size();

  // Unlock the mutex while running inference. This allows more inferences
  // to be enqueued while inference is running.
  mutex_.Unlock();

  std::string model_name;
  auto run_many_start_time = absl::Now();

  MG_CHECK(inputs.size() == outputs.size());
  model_impl_->RunMany(inputs, &outputs, &model_name);
  auto run_many_time = absl::Now() - run_many_start_time;

  for (auto& inference : inferences) {
    if (inference.model_name != nullptr) {
      *inference.model_name = model_name;
    }
    // For all two player games, tell the batcher of the opponent model that
    // it isn't blocked on this inference any more.
    if (inference.other_batcher != nullptr) {
      inference.other_batcher->num_waiting_ -= 1;
    }
  }

  // All the required work is done, unblock all the waiting clients.
  for (auto& inference : inferences) {
    inference.notification->Notify();
  }

  // Lock the mutex again.
  mutex_.Lock();

  stats_.run_batch_time +=
      (absl::Now() - run_batch_start_time) / stats_.buffer_count;
  stats_.run_many_time += (run_many_time) / stats_.buffer_count;
  stats_.num_inferences += num_inferences_in_batch;
}

}  // namespace internal

BatchingModel::BatchingModel(std::shared_ptr<internal::ModelBatcher> batcher)
    : Model(batcher->name(), batcher->feature_descriptor()),
      batcher_(std::move(batcher)) {}

void BatchingModel::RunMany(const std::vector<const ModelInput*>& inputs,
                            std::vector<ModelOutput*>* outputs,
                            std::string* model) {
  batcher_->RunMany(other_batcher_.get(), inputs, outputs, model);
}

void BatchingModel::StartGame() { batcher_->StartGame(); }

void BatchingModel::EndGame() { batcher_->EndGame(); }

void BatchingModel::SetOther(BatchingModel* other) {
  if (other == nullptr) {
    MG_CHECK(other_batcher_ != nullptr);
    other_batcher_ = nullptr;
  } else {
    MG_CHECK(other_batcher_ == nullptr);
    other_batcher_ = other->batcher_;
  }
}

BatchingModelFactory::BatchingModelFactory(std::string device, int buffer_count)
    : device_(std::move(device)), buffer_count_(buffer_count) {}

std::unique_ptr<BatchingModel> BatchingModelFactory::NewModel(
    const std::string& path) {
  absl::MutexLock lock(&mutex_);

  // Find or create a service for the requested model.
  auto it = batchers_.find(path);
  if (it == batchers_.end()) {
    std::vector<std::unique_ptr<Model>> models;
    auto def = LoadModelDefinition(path);
    auto* factory = GetModelFactory(def, device_);
    for (int i = 0; i < buffer_count_; ++i) {
      models.push_back(factory->NewModel(def));
    }
    auto batcher = std::make_shared<internal::ModelBatcher>(
        absl::make_unique<BufferedModel>(std::move(models)), buffer_count_);
    it = batchers_.emplace(path, std::move(batcher)).first;
  }

  auto model = absl::make_unique<BatchingModel>(it->second);

  // Take this opportunity to prune any services that have no clients.
  it = batchers_.begin();
  while (it != batchers_.end()) {
    // If the factory is the only one left with a reference to the batcher,
    // delete it.
    if (it->second.use_count() == 1) {
      batchers_.erase(it++);
    } else {
      ++it;
    }
  }

  return model;
}

void BatchingModelFactory::StartGame(Model* black, Model* white) {
  // TODO(tommadams): figure out if we can refactor the code somehow to take
  // BatchingModel pointers and avoid these dynamic_casts.
  auto* b = dynamic_cast<BatchingModel*>(black);
  auto* w = dynamic_cast<BatchingModel*>(white);
  MG_CHECK(b != nullptr && w != nullptr);

  if (b != w) {
    // This is a two player game, inform each client who the other one is.
    b->SetOther(w);
    w->SetOther(b);
  }

  b->StartGame();
  if (b != w) {
    w->StartGame();
  }
}

void BatchingModelFactory::EndGame(Model* black, Model* white) {
  // TODO(tommadams): figure out if we can refactor the code somehow to take
  // BatchingModel pointers and avoid these dynamic_casts.
  auto* b = dynamic_cast<BatchingModel*>(black);
  auto* w = dynamic_cast<BatchingModel*>(white);
  MG_CHECK(b != nullptr && w != nullptr);

  if (b != w) {
    b->SetOther(nullptr);
    w->SetOther(nullptr);
  }

  b->EndGame();
  if (b != w) {
    w->EndGame();
  }
}

std::vector<std::pair<std::string, BatchingModelStats>>
BatchingModelFactory::FlushStats() {
  absl::MutexLock lock(&mutex_);
  std::vector<std::pair<std::string, BatchingModelStats>> result;
  for (const auto& kv : batchers_) {
    result.emplace_back(kv.first, kv.second->FlushStats());
  }
  return result;
}

}  // namespace minigo


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using SIL.Windows.Forms.ClearShare;
using SIL.Windows.Forms.ClearShare.WinFormsUI;
using SIL.Windows.Forms.Widgets.BetterGrid;

namespace SIL.Windows.Forms.TestApp
{
	public partial class ContributorsForm : Form
	{
		private TableLayoutPanel _tableLayout;
		private ContributorsListControl _contributorsControl;
		private ContributorsListControlViewModel _model;
		private BetterGrid _contributorNames;

		private class AutoCompleter : IAutoCompleteValueProvider
		{
			public BetterGrid Source {get; set;}

			public IEnumerable<string> GetValuesForKey(string key)
			{
				if (key == "person")
				{
					foreach (DataGridViewRow row in Source.Rows)
					{
						yield return row.Cells[0].Value as string;
					}
				}
			}
		}

		public ContributorsForm()
		{
			var autoCompleter = new AutoCompleter();
			_model = new ContributorsListControlViewModel(autoCompleter, () => { });
			var dataGridView = new DataGridView();

			_contributorsControl = new ContributorsListControl(_model);
			_contributorsControl.Dock = DockStyle.Fill;
			_contributorsControl.Location = new System.Drawing.Point(0, 0);
			_contributorsControl.Name = "_contributorsControl";

			_contributorsControl.ValidatingContributor += HandleValidatingContributor;

			// set the column header text
			string[] headerText =
			{
				"Name",
				"Role",
				"Date",
				"Comments"
			};

			for (var i = 0; i < headerText.Length; i++)
				_contributorsControl.SetColumnHeaderText(i, headerText[i]);

			InitializeComponent();
			autoCompleter.Source = _contributorNames;

			var contribs = new ContributionCollection(new [] { new Contribution("Fred", new Role("a", "Author", "guy who writes stuff")) });
			_model.SetContributionList(contribs);
		}

		private void InitializeComponent()
		{
			SuspendLayout();
			AutoScaleDimensions = new SizeF(6F, 13F);
			AutoScaleMode = AutoScaleMode.Font;
			ClientSize = new Size(700, 350);

			_tableLayout = new TableLayoutPanel
			{
				Name = "_tableLayout",
				Dock = DockStyle.Top,
				AutoSize = true,
				BackColor = Color.Transparent,
				ColumnCount = 2,
				RowCount = 2
			};
			_tableLayout.SuspendLayout();
			_tableLayout.ColumnStyles.Add(new ColumnStyle());
			_tableLayout.Location = new Point(0, 0);

			var btnUpdateContributorNames = new Label();
			btnUpdateContributorNames.Text = "Hover over this text to Update Contributors";
			btnUpdateContributorNames.MouseEnter += UpdateNames;
			btnUpdateContributorNames.AutoSize = true;
			btnUpdateContributorNames.Anchor = AnchorStyles.Right;

			_contributorNames = new BetterGrid();
			((ISupportInitialize)_contributorNames).BeginInit();
			_contributorNames.AllowUserToAddRows = false;
			_contributorNames.AllowUserToDeleteRows = false;
			_contributorNames.AllowUserToResizeRows = false;
			_contributorNames.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
			_contributorNames.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			_contributorNames.Dock = System.Windows.Forms.DockStyle.Fill;
			_contributorNames.DrawTextBoxEditControlBorder = false;
			_contributorNames.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;
			_contributorNames.Location = new System.Drawing.Point(1, 1);
			_contributorNames.Name = "_contributorNames";
			_contributorNames.RowHeadersVisible = false;
			var colName = new DataGridViewColumn(new DataGridViewTextBoxCell());
			colName.HeaderText = "Name";
			_contributorNames.Columns.Add(colName);
			_contributorNames.RowCount = 3;
			_contributorNames.Rows[0].Cells[0].Value = "Andrew";
			_contributorNames.Rows[1].Cells[0].Value = "Fred";
			_contributorNames.Rows[2].Cells[0].Value = "Tom";

			_tableLayout.Controls.Add(_contributorsControl, 0, 0);
			_tableLayout.SetColumnSpan(_contributorsControl, 2);
			_tableLayout.Controls.Add(_contributorNames, 0, 1);
			_tableLayout.Controls.Add(btnUpdateContributorNames, 1, 1);

			_tableLayout.ColumnStyles[0].SizeType = SizeType.Percent;
			_tableLayout.ColumnStyles.Add(new ColumnStyle { SizeType = SizeType.AutoSize });

			_tableLayout.RowStyles.Add(new RowStyle { SizeType = SizeType.Percent, Height = 50 });
			_tableLayout.RowStyles.Add(new RowStyle { SizeType = SizeType.Percent, Height = 50 });

			_tableLayout.Dock = DockStyle.Fill;

			Controls.Add(_tableLayout);

			Name = "ContributorsForm";
			Text = "Contributors";

			((ISupportInitialize)_contributorNames).EndInit();
			_tableLayout.ResumeLayout(true);
			ResumeLayout(true);
		}

		/// ------------------------------------------------------------------------------------
		private KeyValuePair<string, string> HandleValidatingContributor(ContributorsListControl sender,
			Contribution contribution, CancelEventArgs e)
		{
			var kvp = CheckIfContributorIsValid(contribution);
			e.Cancel = !string.IsNullOrEmpty(kvp.Key);
			return kvp;
		}

		/// ------------------------------------------------------------------------------------
		private static KeyValuePair<string, string> CheckIfContributorIsValid(Contribution contribution)
		{
			if (contribution != null)
			{
				if (string.IsNullOrEmpty(contribution.ContributorName))
					return new KeyValuePair<string, string>("name", "Enter a name.");

				if (contribution.Role == null)
					return new KeyValuePair<string, string>("role", "Choose a role.");
			}

			return new KeyValuePair<string, string>();
		}

		/// ------------------------------------------------------------------------------------
		private void UpdateNames(object sender, EventArgs e)
		{
			// The following illustrates how to avoid an InvalidOperationException when the
			// grid is not in a state where it passes validation.
			if (!_contributorsControl.Validate())
				return;

			var contribs = _model.Contributions;
			for (var i = 0; i < _contributorNames.RowCount && i < contribs.Count; i++)
			{
				contribs[i].ContributorName = (string)_contributorNames.Rows[i].Cells[0].Value;
			}

			_model.SetContributionList(contribs);
		}
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>mobi.cangol.mobile.service.status 类分层结构 (appcore 1.1.74 API)</title>
<meta name="date" content="2020-05-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

程序包mobi.cangol.mobile.service.status的分层结构

程序包分层结构:

所有程序包

接口分层结构

mobi.cangol.mobile.service.AppService

mobi.cangol.mobile.service.status.StatusService

mobi.cangol.mobile.service.status.StatusListener

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类


text:
module Telegraphist
  class Bot
    include ActiveModel::Model

    attr_accessor :id, :first_name, :username, :client

    def self.create(authentication_token)
      client = Client.new(authentication_token)
      new(client.get(:getMe)['result'].merge(client: client))
    end

    def update_loop(&block)
      last_update = nil
      loop do
        updates(last_update).try(:each) do |update|
          block.call(update)
          last_update = [last_update, update.update_id + 1].compact.max
        end
        sleep 1
      end
    end

    def updates(offset=nil)
      (client.get(:getUpdates, query: {offset: offset})['result'] || []).map do |update|
        Model::Update.new(update)
      end
    end

    def send_message(chat_id, text)
      client.post(:sendMessage, query: {chat_id: chat_id, text: text})
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

  <changeSet id="1" author="owl">
    <createTable tableName="User">
      <column name="Id" type="bigint" autoIncrement="true">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="FirstName" type="varchar(255)">
        <constraints nullable="false"/>
      </column>
      <column name="LastName" type="varchar(255)">
        <constraints nullable="false"/>
      </column>
      <column name="Password" type="varchar(255)">
        <constraints nullable="false"/>
      </column>
      <column name="Username" type="varchar(255)">
        <constraints nullable="false" unique="true"/>
      </column>
    </createTable>
  </changeSet>

  <changeSet id="2" author="owl">
    <sqlFile path="db/sql/add_user.sql"/>
  </changeSet>

  <changeSet id="3" author="owl">
    <createTable tableName="Authority">
      <column name="Id" type="bigint" autoIncrement="true">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="Name" type="varchar(255)">
        <constraints nullable="false"/>
      </column>
    </createTable>
  </changeSet>

  <changeSet id="4" author="owl">
    <sqlFile path="db/sql/add_authority.sql"/>
  </changeSet>

  <changeSet id="5" author="owl">
    <createTable tableName="UserAuthority">
      <column name="Id" type="bigint" autoIncrement="true">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="UserId" type="bigint"/>
      <column name="AuthorityId" type="bigint"/>
    </createTable>
  </changeSet>

  <changeSet id="6" author="owl">
    <sqlFile path="db/sql/add_user_authority.sql"/>
  </changeSet>

</databaseChangeLog>


text:
package com.asi.hopeitapp.Messages;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.asi.hopeitapp.Main.BaseFragment;
import com.asi.hopeitapp.Model.Message;
import com.asi.hopeitapp.Model.Patient;
import com.asi.hopeitapp.R;
import com.bumptech.glide.Glide;

import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MessagesFragment extends BaseFragment {

    @BindView(R.id.messagesRecyclerView)
    RecyclerView recyclerView;

    private int lastMessageSize = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.messages_fragment, container, false);
        ButterKnife.bind(this, view);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        return view;
    }

    @Override
    protected void loadContent() {
        super.loadContent();
        loadRecyclerView();
    }

    private void loadRecyclerView(){
        List<Message> messages;

        try {
            messages = Patient.listAll(Message.class);
        }
        catch (Exception e){
            recyclerView.setVisibility(View.GONE);
            return;
        }

        if(messages.isEmpty()){
            recyclerView.setVisibility(View.GONE);
            return;
        }

        Collections.reverse(messages);

        MessagesAdapter adapter = new MessagesAdapter(messages, Glide.with(this), getContext());
        recyclerView.setAdapter(adapter);

        checkIfGotNew(messages);
    }

    private boolean checkIfGotNew(List<Message> messages){

        SharedPreferences settings = getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
        lastMessageSize = settings.getInt("MessageCount", 0);

        if (lastMessageSize != messages.size()){

            Toast.makeText(getContext(), "Dostałeś nowe wiadomości od fundacjii",
                    Toast.LENGTH_SHORT).show();

            SharedPreferences.Editor editor = settings.edit();
            editor.putInt("MessageCount", messages.size());
            editor.apply();
        }

        return false;
    }
}


text:
- EOI based on the input length

### String scanning
- add support for YYFILL
  - streams
  - change EOI

## Parser
- test locations support
- change it to push parser (stream support)

## IO
- rename read hook to fill
- create a new hook read that will copy data to the buffer
- suppress valgrind errors without using calloc for new buffer
- test various allocation using valgrind

## Encoder

### Double encoding
- use custom dtoa function for double serialization
  - allows selection of custom precision and mode

### String encoding
- flag for escaping slashes
- utf8 validation
- unicode escaping
- marked buffering

## CLI
- generate help message
  - extend `jso_cli_param` with description
- add support for grouping of short arguments
- allow setting of output stream (stdout and stderr)
- allow stream input (stdin - using jso in pipe)
  - it requires parser stream support

## Build
- parser debug
  - use option --enable-parser-debug
  - set YYDEBUG macro to 1 if enabled, otherwise 0
- autogen.sh
  - check for autoconf, automake, libtool (libtoolize)
- optional generating of files (re2c and bison)
  - included generated files that will be used if not checked
- re2c
  - autoconf version check
  - try to replace Makefile AM rule with AC
- bison
  - autoconf version check
  - remove Makefile AM rule (use AC)
  - jso_parser.tab.h - prerequisite (build error when it's not created)

## Documentation
- document source using doxygent comments
- MarkDown documentation (Github)
  - document jso executable
  - document exported API
  - add some examples