text:
package ru.aserdyuchenko.UserSort;

import java.util.*;

/**
 * Created by Anton on 30.04.17.
 */
public class SortUser {
    /**
     * Sort by age.
     * @param list
     * @return sortSet
     */
    public Set<User> sort(List<User> list) {
        Set<User> sortSet = new TreeSet<>();
        sortSet.addAll(list);
        return sortSet;
    }

    /**
     * Sort by hashCode.
     * @param users - list, what need to sort.
     * @return users - sort by hashCode
     */
    public List<User> sortHash(List<User> users) {
        Collections.sort(users,
                new Comparator<User>() {
                    @Override
                    public int compare(User o1, User o2) {
                        return o1.hashCode() - o2.hashCode();
                    }
                }
        );
        return users;
    }

    /**
     * Sort by name`s length.
     * @param users
     * @return users - sort by name`s length.
     */
    public List<User> sortLength(List<User> users) {
        Collections.sort(users,
                new Comparator<User>() {
                    @Override
                    public int compare(User o1, User o2) {
                        return o1.getName().length() - o2.getName().length();
                    }
                }
        );
        return users;
    }
}


text:
<html>
<head>
</head>
<body>
<script defer="defer">
	alert("with defer, run later.");
	document.write("with defer, run later.");
</script>
<script>
	alert("without defer, run immediately.");
	document.write("without defer, run immediately.");
</script>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
//MIT, 2019-present, WinterDev
using System;
using System.Security.Cryptography;
using System.Text;

namespace LayoutFarm.TextEditing
{
    public enum PlainTextLineEnd : byte
    {
        None,
        /// <summary>
        /// \r\n
        /// </summary>
        CRLF,
        /// <summary>
        /// \n
        /// </summary>
        LF,
    }

    /// <summary>
    /// immutable plain text line
    /// </summary>
    public class PlainTextLine
    {
        readonly char[] _text;//***

        public PlainTextLine(string text)
        {
            _text = text.ToCharArray();
        }
        public PlainTextLine(char[] buffer)
        {
            _text = buffer;
        }
        public PlainTextLineEnd EndWith { get; set; }

        public string GetText() => new string(_text);

        public void CopyText(StringBuilder stbuilder)
        {
            stbuilder.Append(_text);
        }
        public void CopyText(char[] destBuffer, int srcIndex, int srcLen, int dstIndex)
        {
            Array.Copy(_text, srcIndex, destBuffer, dstIndex, srcLen);
        }
        public int CharCount => _text.Length;
#if DEBUG
        public override string ToString()
        {
            return GetText();
        }
#endif
        public PlainTextLine Clone()
        {
            return new PlainTextLine(_text);
        }
    }

}


text:
namespace http {
namespace server {

/// The top-level class of the HTTP server.
class server
  : private boost::noncopyable
{
public:
  /// Construct the server to listen on the specified TCP address and port, and
  /// serve up files from the given directory.
  explicit server(const std::string& address, const std::string& port,
      const std::string& doc_root);

  /// Run the server's io_service loop.
  void run();

private:
  /// Initiate an asynchronous accept operation.
  void start_accept();

  /// Handle completion of an asynchronous accept operation.
  void handle_accept(const boost::system::error_code& e);

  /// Handle a request to stop the server.
  void handle_stop();

  /// The io_service used to perform asynchronous operations.
  boost::asio::io_service io_service_;

  /// The signal_set is used to register for process termination notifications.
  boost::asio::signal_set signals_;

  /// Acceptor used to listen for incoming connections.
  boost::asio::ip::tcp::acceptor acceptor_;

  /// The connection manager which owns all live connections.
  connection_manager connection_manager_;

  /// The next connection to be accepted.
  connection_ptr new_connection_;

  /// The handler for all incoming requests.
  request_handler request_handler_;
};

} // namespace server
} // namespace http

#endif // HTTP_SERVER_HPP


text:
import time
import numpy as np
import tensorflow as tf
import os

class NERTagger(object):
    """The NER Tagger Model."""

    def __init__(self, is_training, config):
        self.batch_size = batch_size = config.batch_size
        self.seq_length = seq_length = config.seq_length
        self.is_training = is_training
        size = config.hidden_size
        vocab_size = config.vocab_size

        # Define input and target tensors
        self._input_data = tf.placeholder(tf.int32, [batch_size, seq_length])
        self._targets = tf.placeholder(tf.int32, [batch_size, seq_length])

        with tf.device("/cpu:0"):
            embedding = tf.get_variable("embedding", [vocab_size, size], dtype=tf.float32)
            inputs = tf.nn.embedding_lookup(embedding, self._input_data)

        self._cost, self._logits, self._accuracy = _bilstm_model(inputs, self._targets, config)

        # Gradients and SGD update operation for training the model.
        self._lr = tf.Variable(0.0, trainable=False)
        tvars = tf.trainable_variables()
        grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars), config.max_grad_norm)
        optimizer = tf.train.GradientDescentOptimizer(self._lr)
        self._train_op = optimizer.apply_gradients(
            zip(grads, tvars),
            global_step=tf.contrib.framework.get_or_create_global_step())

        self._new_lr = tf.placeholder(tf.float32, shape=[], name="new_learning_rate")
        self._lr_update = tf.assign(self._lr, self._new_lr)
        self.saver = tf.train.Saver(tf.global_variables())

    def assign_lr(self, session, lr_value):
        session.run(self._lr_update, feed_dict={self._new_lr: lr_value})

    @property
    def input_data(self):
        return self._input_data

    @property
    def targets(self):
        return self._targets

    @property
    def cost(self):
        return self._cost

    @property
    def logits(self):
        return self._logits

    @property
    def lr(self):
        return self._lr

    @property
    def train_op(self):
        return self._train_op

    @property
    def accuracy(self):
        return self._accuracy

def _bilstm_model(inputs, targets, config):
    '''
    @Use BasicLSTMCell, MultiRNNCell method to build LSTM model,
    @return logits, cost and others
    '''
    batch_size = config.batch_size
    seq_length = config.seq_length
    num_layers = config.num_layers
    size = config.hidden_size
    tag_size = config.tag_size

    lstm_fw_cell = tf.nn.rnn_cell.BasicLSTMCell(size, forget_bias=0.0, state_is_tuple=True)
    lstm_bw_cell = tf.nn.rnn_cell.BasicLSTMCell(size, forget_bias=0.0, state_is_tuple=True)

    cell_fw = tf.nn.rnn_cell.MultiRNNCell([lstm_fw_cell] * num_layers, state_is_tuple=True)
    cell_bw = tf.nn.rnn_cell.MultiRNNCell([lstm_bw_cell] * num_layers, state_is_tuple=True)

    initial_state_fw = cell_fw.zero_state(batch_size, tf.float32)
    initial_state_bw = cell_bw.zero_state(batch_size, tf.float32)

    # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)
    inputs_list = [tf.squeeze(s, axis=1) for s in tf.split(value=inputs, num_or_size_splits=seq_length, axis=1)]

    with tf.variable_scope("ner_bilstm"):
        outputs, state_fw, state_bw = tf.nn.static_bidirectional_rnn(
            cell_fw, cell_bw, inputs_list, initial_state_fw=initial_state_fw,
            initial_state_bw=initial_state_bw)

    # outputs is a length T list of output vectors, which is [batch_size, 2 * hidden_size]
    # [time][batch][cell_fw.output_size + cell_bw.output_size]

    output = tf.reshape(tf.concat(outputs, 1), [-1, size * 2])
    # output has size: [T, size * 2]

    softmax_w = tf.get_variable("softmax_w", [size * 2, tag_size], dtype=tf.float32)
    softmax_b = tf.get_variable("softmax_b", [tag_size], dtype=tf.float32)
    logits = tf.matmul(output, softmax_w) + softmax_b

    correct_prediction = tf.equal(tf.cast(tf.argmax(logits, 1), tf.int32), tf.reshape(targets, [-1]))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.reshape(targets, [-1]), logits=logits)
    cost = tf.reduce_sum(loss) / batch_size  # loss [time_step]
    return cost, logits, accuracy

def run(session, model, dataset, eval_op, ner_train_dir, epoch):
    """Runs the model on the given data."""
    start_time = time.time()
    costs = 0.0
    iters = 0
    step = 0
    while dataset.has_next():
        step = step + 1
        (x, y) = dataset.next_batch(model.batch_size)
        fetches = [model.cost, model.logits, eval_op]  # eval_op define the m.train_op or m.eval_op
        feed_dict = {}
        feed_dict[model.input_data] = x
        feed_dict[model.targets] = y
        cost, logits, _ = session.run(fetches, feed_dict)
        costs += cost
        iters += model.seq_length

    # Save Model to CheckPoint when is_training is True
    if model.is_training:
        checkpoint_path = os.path.join(ner_train_dir, "bilstm/model.ckpt")
        model.saver.save(session, checkpoint_path)
        print("Model Saved... at time step " + str(step))

    return np.exp(costs / iters)


text:
package org.elasticsearch.cluster.routing.allocation.decider;

import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.settings.Settings;

/**
 * Only allow rebalancing when all shards are active within the shard replication group.
 */
public class RebalanceOnlyWhenActiveAllocationDecider extends AllocationDecider {

    public static final String NAME = "rebalance_only_when_active";

    public RebalanceOnlyWhenActiveAllocationDecider(Settings settings) {
        super(settings);
    }

    @Override
    public Decision canRebalance(ShardRouting shardRouting, RoutingAllocation allocation) {
        if (!allocation.routingNodes().allReplicasActive(shardRouting.shardId(), allocation.metaData())) {
            return allocation.decision(Decision.NO, NAME, "rebalancing can not occur if not all replicas are active in the cluster");
        }
        return allocation.decision(Decision.YES, NAME, "all replicas are active in the cluster, rebalancing can occur");
    }
}


text:
/*
  Alternate execution starting point for generating the hashtable of actions
  from a file (read from standard input).
*/

#include <stdio.h>
#include <stdlib.h>

int main(/* arguments are ignored */) {
    /* read from file */
    char *buffer=malloc(100); /* assume nothing malicious */
    int cnt=0;
    puts("/* auto-generated array - do not modify */");
    puts("#include \"actionlist.h\"");
    puts("#include \"control.h\"");
    puts("struct action_struct action_table[]={");
    while(!feof(stdin)) {
        /* for each line */
        /* print the corresponding array entry */
        scanf("%s\n",buffer);
        printf("    {\"%s\",%s_action},\n",buffer,buffer);
        cnt++;
    }
    puts("};");
    printf("\nint action_count=%d;\n",cnt);
    return 0;
}


text:
<!-- **************************************************************************
#
# Copyright (c) 2010-2011 Sonatype, Inc.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#
#   ved.
#
#
#************************************************************************** -->

<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <target>System.out</target>
        <encoder>
            <pattern>%date %level [%thread%X{DC}] %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.hudsonci.inject" level="TRACE"/>

    <root level="TRACE">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>


text:
package serene.internal;

import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import serene.bind.ElementTask;
import serene.bind.ElementTaskContext;

import serene.validation.schema.simplified.SAttribute;

import serene.validation.schema.parsed.ParsedComponentBuilder;

import serene.util.NameInfo;
import serene.util.AttributeInfo;

class ForeignElementTask  extends RNGParseElementTask{
	ForeignElementTask(){
		super();
	}

	public void execute(){
		builder.endLevel();
		builder.buildForeignComponent(/*context.getDeclaredXmlns(),*/ context.getElementInputRecordIndex());
	}

	public boolean needsStartElementInputData(){
	    return true;
	}
}


text:
package io.github.hapjava.server.impl.crypto;

import java.io.IOException;
import org.bouncycastle.crypto.engines.ChaChaEngine;
import org.bouncycastle.crypto.generators.Poly1305KeyGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;

public class ChachaEncoder {

  private final ChaChaEngine encryptCipher;

  public ChachaEncoder(byte[] key, byte[] nonce) throws IOException {

    this.encryptCipher = new ChaChaEngine(20);

    this.encryptCipher.init(true, new ParametersWithIV(new KeyParameter(key), nonce));
  }

  public byte[] encodeCiphertext(byte[] plaintext) throws IOException {
    return encodeCiphertext(plaintext, null);
  }

  public byte[] encodeCiphertext(byte[] plaintext, byte[] additionalData) throws IOException {
    KeyParameter macKey = initRecordMAC(encryptCipher);

    byte[] ciphertext = new byte[plaintext.length];
    encryptCipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0);

    byte[] calculatedMAC = PolyKeyCreator.create(macKey, additionalData, ciphertext);

    byte[] ret = new byte[ciphertext.length + 16];
    System.arraycopy(ciphertext, 0, ret, 0, ciphertext.length);
    System.arraycopy(calculatedMAC, 0, ret, ciphertext.length, 16);
    return ret;
  }

  private KeyParameter initRecordMAC(ChaChaEngine cipher) {
    byte[] firstBlock = new byte[64];
    cipher.processBytes(firstBlock, 0, firstBlock.length, firstBlock, 0);

    // NOTE: The BC implementation puts 'r' after 'k'
    System.arraycopy(firstBlock, 0, firstBlock, 32, 16);
    KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);
    Poly1305KeyGenerator.clamp(macKey.getKey());
    return macKey;
  }
}


text:
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from __future__ import print_function

import logging
import posixpath
import subprocess
from multiprocessing.pool import ThreadPool

from pystachio import Environment, Required, String
from twitter.common import log

from apache.aurora.client.api import AuroraClientAPI
from apache.aurora.client.base import AURORA_V2_USER_AGENT_NAME, combine_messages
from apache.aurora.common.cluster import Cluster
from apache.aurora.config.schema.base import MesosContext
from apache.thermos.config.schema import ThermosContext

from gen.apache.aurora.api.constants import LIVE_STATES
from gen.apache.aurora.api.ttypes import JobKey, ResponseCode, TaskQuery

class CommandRunnerTrait(Cluster.Trait):
  slave_root          = Required(String)  # noqa
  slave_run_directory = Required(String)  # noqa

class DistributedCommandRunner(object):

  @classmethod
  def make_executor_path(cls, cluster, executor_name):
    parameters = cls.sandbox_args(cluster)
    parameters.update(executor_name=executor_name)
    return posixpath.join(
        '%(slave_root)s',
        'slaves/*/frameworks/*/executors/%(executor_name)s/runs',
        '%(slave_run_directory)s'
    ) % parameters

  @classmethod
  def thermos_sandbox(cls, cluster, executor_sandbox=False):
    sandbox = cls.make_executor_path(cluster, 'thermos-{{thermos.task_id}}')
    return sandbox if executor_sandbox else posixpath.join(sandbox, 'sandbox')

  @classmethod
  def sandbox_args(cls, cluster):
    cluster = cluster.with_trait(CommandRunnerTrait)
    return {'slave_root': cluster.slave_root, 'slave_run_directory': cluster.slave_run_directory}

  @classmethod
  def substitute(cls, command, task, cluster, **kw):
    prefix_command = 'cd %s;' % cls.thermos_sandbox(cluster, **kw)
    thermos_namespace = ThermosContext(
        task_id=task.assignedTask.taskId,
        ports=task.assignedTask.assignedPorts)
    mesos_namespace = MesosContext(instance=task.assignedTask.instanceId)
    command = String(prefix_command + command) % Environment(
        thermos=thermos_namespace,
        mesos=mesos_namespace)
    return command.get()

  @classmethod
  def query_from(cls, role, env, job):
    return TaskQuery(statuses=LIVE_STATES, jobKeys=[JobKey(role=role, environment=env, name=job)])

  def __init__(self, cluster, role, env, jobs, ssh_user=None, ssh_options=None, log_fn=log.log):
    self._cluster = cluster
    self._api = AuroraClientAPI(
        cluster=cluster,
        user_agent=AURORA_V2_USER_AGENT_NAME)
    self._role = role
    self._env = env
    self._jobs = jobs
    self._ssh_user = ssh_user if ssh_user else self._role
    self._ssh_options = ssh_options if ssh_options else []
    self._log = log_fn

  def execute(self, args):
    hostname, role, command = args
    ssh_command = ['ssh', '-n', '-q']
    ssh_command += self._ssh_options
    ssh_command += ['%s@%s' % (role, hostname), command]
    self._log(logging.DEBUG, "Running command: %s" % ssh_command)
    po = subprocess.Popen(ssh_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = po.communicate()
    return '\n'.join('%s:  %s' % (hostname, line) for line in output[0].splitlines())

  def resolve(self):
    for job in self._jobs:
      resp = self._api.query(self.query_from(self._role, self._env, job))
      if resp.responseCode != ResponseCode.OK:
        self._log(logging.ERROR, 'Failed to query job: %s' % job)
        continue
      for task in resp.result.scheduleStatusResult.tasks:
        yield task

  def process_arguments(self, command, **kw):
    for task in self.resolve():
      host = task.assignedTask.slaveHost
      yield (host, self._ssh_user, self.substitute(command, task, self._cluster, **kw))

  def run(self, command, parallelism=1, **kw):
    threadpool = ThreadPool(processes=parallelism)
    for result in threadpool.imap_unordered(self.execute, self.process_arguments(command, **kw)):
      print(result)

class InstanceDistributedCommandRunner(DistributedCommandRunner):
  """A distributed command runner that only runs on specified instances of a job."""

  @classmethod
  def query_from(cls, role, env, job, instances=None):
    return TaskQuery(
        statuses=LIVE_STATES,
        jobKeys=[JobKey(role=role, environment=env, name=job)],
        instanceIds=instances)

  def __init__(self,
               cluster,
               role,
               env,
               job,
               ssh_user=None,
               ssh_options=None,
               instances=None,
               log_fn=logging.log):
    super(InstanceDistributedCommandRunner, self).__init__(
        cluster,
        role,
        env,
        [job],
        ssh_user,
        ssh_options,
        log_fn)
    self._job = job
    self._ssh_user = ssh_user if ssh_user else self._role
    self.instances = instances

  def resolve(self):
    resp = self._api.query(self.query_from(self._role, self._env, self._job, self.instances))
    if resp.responseCode == ResponseCode.OK:
      for task in resp.result.scheduleStatusResult.tasks:
        yield task
    else:
      self._log(
          logging.ERROR,
          'Error: could not retrieve task information for run command: %s' % combine_messages(resp))
      raise ValueError('Could not retrieve task information: %s' % combine_messages(resp))


text:
package org.apache.hadoop.yarn.webapp.util;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

import org.junit.jupiter.api.Test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.http.HttpServer2;
import org.apache.hadoop.http.TestHttpServer.EchoServlet;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.ssl.KeyStoreTestUtil;
import org.apache.hadoop.yarn.conf.YarnConfiguration;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class TestWebServiceClient {

  private static final String BASEDIR = System.getProperty("test.build.dir",
      "target/test-dir") + "/" + TestWebServiceClient.class.getSimpleName();
  static final String SSL_SERVER_KEYSTORE_PROP_PREFIX = "ssl.server.keystore";
  static final String SSL_SERVER_TRUSTSTORE_PROP_PREFIX =
      "ssl.server.truststore";
  static final String SERVLET_NAME_ECHO = "echo";
  static final String SERVLET_PATH_ECHO = "/" + SERVLET_NAME_ECHO;

  @Test
  void testGetWebServiceClient() throws Exception {
    Configuration conf = new Configuration();
    conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, "HTTPS_ONLY");
    WebServiceClient.initialize(conf);
    WebServiceClient client = WebServiceClient.getWebServiceClient();
    assertNotNull(client.getSSLFactory());
    WebServiceClient.destroy();
  }

  @Test
  void testCreateClient() throws Exception {
    Configuration conf = new Configuration();
    conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, "HTTPS_ONLY");
    File base = new File(BASEDIR);
    FileUtil.fullyDelete(base);
    base.mkdirs();
    String keystoresDir = new File(BASEDIR).getAbsolutePath();
    String sslConfDir = KeyStoreTestUtil
        .getClasspathDir(TestWebServiceClient.class);

    KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfDir, conf, false,
        true);

    Configuration sslConf = KeyStoreTestUtil.getSslConfig();
    sslConf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, "HTTPS_ONLY");

    HttpServer2 server = new HttpServer2.Builder().setName("test")
        .addEndpoint(new URI("https://localhost")).setConf(sslConf)
        .keyPassword(
            sslConf.get(SSL_SERVER_KEYSTORE_PROP_PREFIX + ".keypassword"))
        .keyStore(sslConf.get(SSL_SERVER_KEYSTORE_PROP_PREFIX + ".location"),
            sslConf.get(SSL_SERVER_KEYSTORE_PROP_PREFIX + ".password"),
            sslConf.get(SSL_SERVER_KEYSTORE_PROP_PREFIX + ".type", "jks"))
        .trustStore(
            sslConf.get(SSL_SERVER_TRUSTSTORE_PROP_PREFIX + ".location"),
            sslConf.get(SSL_SERVER_TRUSTSTORE_PROP_PREFIX + ".password"),
            sslConf.get(SSL_SERVER_TRUSTSTORE_PROP_PREFIX + ".type", "jks"))
        .excludeCiphers(sslConf.get("ssl.server.exclude.cipher.list")).build();
    server.addServlet(SERVLET_NAME_ECHO, SERVLET_PATH_ECHO, EchoServlet.class);
    server.start();

    final URL baseUrl = new URL(
        "https://" + NetUtils.getHostPortString(server.getConnectorAddress(0)));
    URL u = new URL(baseUrl, SERVLET_PATH_ECHO + "?a=b&c=d");
    WebServiceClient.initialize(sslConf);
    WebServiceClient client = WebServiceClient.getWebServiceClient();
    HttpURLConnection conn = client.getHttpURLConnectionFactory()
        .getHttpURLConnection(u);
    assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    WebServiceClient.destroy();
    server.stop();
    FileUtil.fullyDelete(new File(BASEDIR));
    KeyStoreTestUtil.cleanupSSLConfig(keystoresDir, sslConfDir);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="library_name">PresentationLib.XF.Android</string>
</resources>


text:
package org.apache.cassandra.tools;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.CounterColumn;
import org.apache.cassandra.db.DeletedColumn;
import org.apache.cassandra.db.ExpiringColumn;
import org.apache.cassandra.db.IColumn;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.db.columniterator.IColumnIterator;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.SSTableReader;

import org.apache.cassandra.utils.ByteBufferUtil;

import static org.apache.cassandra.utils.ByteBufferUtil.hexToBytes;

import static org.apache.cassandra.io.sstable.SSTableUtils.tempSSTableFile;
import static org.junit.Assert.assertEquals;

import org.apache.cassandra.Util;

import org.json.simple.parser.ParseException;
import org.junit.Test;

public class SSTableImportTest extends SchemaLoader
{
    @Test
    public void testImportSimpleCf() throws IOException, URISyntaxException
    {
        // Import JSON to temp SSTable file
        String jsonUrl = resourcePath("SimpleCF.json");
        File tempSS = tempSSTableFile("Keyspace1", "Standard1");
        SSTableImport.importJson(jsonUrl, "Keyspace1", "Standard1", tempSS.getPath());

        // Verify results
        SSTableReader reader = SSTableReader.open(Descriptor.fromFilename(tempSS.getPath()));
        QueryFilter qf = QueryFilter.getIdentityFilter(Util.dk("rowA"), new QueryPath("Standard1"));
        IColumnIterator iter = qf.getSSTableColumnIterator(reader);
        ColumnFamily cf = iter.getColumnFamily();
        while (iter.hasNext()) cf.addColumn(iter.next());
        assert cf.getColumn(ByteBufferUtil.bytes("colAA")).value().equals(hexToBytes("76616c4141"));
        assert !(cf.getColumn(ByteBufferUtil.bytes("colAA")) instanceof DeletedColumn);
        IColumn expCol = cf.getColumn(ByteBufferUtil.bytes("colAC"));
        assert expCol.value().equals(hexToBytes("76616c4143"));
        assert expCol instanceof ExpiringColumn;
        assert ((ExpiringColumn)expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
    }

    private String resourcePath(String name) throws URISyntaxException
    {
        // Naive resource.getPath fails on Windows in many cases, for example if there are spaces in the path
        // which get encoded as %20 which Windows doesn't like. The trick is to create a URI first, which satisfies all platforms.
        return new URI(getClass().getClassLoader().getResource(name).toString()).getPath();
    }

    @Test
    public void testImportSimpleCfOldFormat() throws IOException, URISyntaxException
    {
        // Import JSON to temp SSTable file
        String jsonUrl = resourcePath("SimpleCF.oldformat.json");
        File tempSS = tempSSTableFile("Keyspace1", "Standard1");
        SSTableImport.importJson(jsonUrl, "Keyspace1", "Standard1", tempSS.getPath());

        // Verify results
        SSTableReader reader = SSTableReader.open(Descriptor.fromFilename(tempSS.getPath()));
        QueryFilter qf = QueryFilter.getIdentityFilter(Util.dk("rowA"), new QueryPath("Standard1"));
        IColumnIterator iter = qf.getSSTableColumnIterator(reader);
        ColumnFamily cf = iter.getColumnFamily();
        while (iter.hasNext()) cf.addColumn(iter.next());
        assert cf.getColumn(ByteBufferUtil.bytes("colAA")).value().equals(hexToBytes("76616c4141"));
        assert !(cf.getColumn(ByteBufferUtil.bytes("colAA")) instanceof DeletedColumn);
        IColumn expCol = cf.getColumn(ByteBufferUtil.bytes("colAC"));
        assert expCol.value().equals(hexToBytes("76616c4143"));
        assert expCol instanceof ExpiringColumn;
        assert ((ExpiringColumn)expCol).getTimeToLive() == 42 && expCol.getLocalDeletionTime() == 2000000000;
    }

    @Test
    public void testImportSuperCf() throws IOException, ParseException, URISyntaxException
    {
        String jsonUrl = resourcePath("SuperCF.json");
        File tempSS = tempSSTableFile("Keyspace1", "Super4");
        SSTableImport.importJson(jsonUrl, "Keyspace1", "Super4", tempSS.getPath());

        // Verify results
        SSTableReader reader = SSTableReader.open(Descriptor.fromFilename(tempSS.getPath()));
        QueryFilter qf = QueryFilter.getNamesFilter(Util.dk("rowA"), new QueryPath("Super4", null, null), ByteBufferUtil.bytes("superA"));
        ColumnFamily cf = qf.getSSTableColumnIterator(reader).getColumnFamily();
        IColumn superCol = cf.getColumn(ByteBufferUtil.bytes("superA"));
        assert superCol != null;
        assert superCol.getSubColumns().size() > 0;
        IColumn subColumn = superCol.getSubColumn(ByteBufferUtil.bytes("636f6c4141"));
        assert subColumn.value().equals(hexToBytes("76616c75654141"));
    }

    @Test
    public void testImportUnsortedMode() throws IOException, URISyntaxException
    {
        String jsonUrl = resourcePath("UnsortedSuperCF.json");
        File tempSS = tempSSTableFile("Keyspace1", "Super4");

        ColumnFamily columnFamily = ColumnFamily.create("Keyspace1", "Super4");
        IPartitioner<?> partitioner = DatabaseDescriptor.getPartitioner();

        SSTableImport.setKeyCountToImport(3);
        int result = SSTableImport.importSorted(jsonUrl, columnFamily, tempSS.getPath(), partitioner);
        assert result == -1;
    }

    @Test
    public void testImportCounterCf() throws IOException, URISyntaxException
    {
        // Import JSON to temp SSTable file
        String jsonUrl = resourcePath("CounterCF.json");
        File tempSS = tempSSTableFile("Keyspace1", "Counter1");
        SSTableImport.importJson(jsonUrl, "Keyspace1", "Counter1", tempSS.getPath());

        // Verify results
        SSTableReader reader = SSTableReader.open(Descriptor.fromFilename(tempSS.getPath()));
        QueryFilter qf = QueryFilter.getIdentityFilter(Util.dk("rowA"), new QueryPath("Counter1"));
        IColumnIterator iter = qf.getSSTableColumnIterator(reader);
        ColumnFamily cf = iter.getColumnFamily();
        while (iter.hasNext()) cf.addColumn(iter.next());
        IColumn c = cf.getColumn(ByteBufferUtil.bytes("colAA"));
        assert c instanceof CounterColumn: c;
        assert ((CounterColumn) c).total() == 42;
    }
}


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

<title>epsylon.exception</title>
<meta name="date" content="2014-09-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

epsylon.exception

Exceptions

EvaluationException

IllegalTokenException

ParseException

TypecheckException

UnknownTokenException


text:
@extends('layouts.admin')

@section('content')

            arrow_back

Add Post

        {{ $message }}
        <form action="{{ url('/admin-post') }}" method="post" class="col s12">
            {!! csrf_field() !!}

              <input name="title" id="title" type="text" class="validate">
              Title

              <textarea name="abstract" id="abstract" class="materialize-textarea"></textarea>
              Abstract

              <textarea name="content" id="content" class="materialize-textarea"></textarea>
              Content

          <button type="submit" class="waves-effect waves-light btn">Add</button>
        </form>

@endsection


text:
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using Microsoft.EntityFrameworkCore.Storage;

namespace MR.AspNetCore.Jobs.Server
{
	public class SqlTransactionFetchedJob : IFetchedJob
	{
		private readonly Timer _timer;
		private readonly object _lock = new object();

		private IDbConnection _connection;
		private readonly IDbContextTransaction _transaction;

		public SqlTransactionFetchedJob(
			int jobId,
			IDbConnection connection,
			IDbContextTransaction transaction)
		{
			JobId = jobId;
			_connection = connection;
			_transaction = transaction;
			if (TransactionCanTerminate)
			{
				_timer = new Timer(ExecuteKeepAliveQuery, null, KeepAliveInterval, KeepAliveInterval);
			}
		}

		public virtual bool TransactionCanTerminate => true;

		public virtual TimeSpan KeepAliveInterval => TimeSpan.FromMinutes(1);

		public int JobId { get; }

		public Task RemoveFromQueueAsync()
		{
			lock (_lock)
			{
				_transaction.Commit();
			}
			return Task.CompletedTask;
		}

		public Task RequeueAsync()
		{
			lock (_lock)
			{
				_transaction.Rollback();
			}
			return Task.CompletedTask;
		}

		public void Dispose()
		{
			lock (_lock)
			{
				_timer?.Dispose();
				_transaction.Dispose();
				_connection = null;
			}
		}

		private void ExecuteKeepAliveQuery(object obj)
		{
			lock (_lock)
			{
				try
				{
					_connection?.Execute("SELECT 1;", transaction: _transaction.GetDbTransaction());
				}
				catch
				{
				}
			}
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace Booker.Pages
{
    public partial class LastRead : PhoneApplicationPage
    {
        public LastRead()
        {
            InitializeComponent();
        }
    }
}


text:
<html>
<head>
    <base href="/">
    <title>MirIn</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function (err) {
            console.error(err);
        });
    </script>
</head>
<!-- 3. Display the application -->
<body>
<mirin>Loading...</mirin>
</body>
</html>


text:
import { is, join, pipe, replace } from 'ramda';
import sortAndSerialize from './sortAndSerialize';
import { NodeWithId } from './tree';

export function collapseChildren(node: NodeWithId) {
  if (node.children) {
    node._children = node.children;
    node._children.forEach(collapseChildren);
    node.children = null;
  }
}

export function expandChildren(node: NodeWithId) {
  if (node._children) {
    node.children = node._children;
    node.children.forEach(expandChildren);
    node._children = null;
  }
}

export function toggleChildren(node: NodeWithId) {
  if (node.children) {
    node._children = node.children;
    node.children = null;
  } else if (node._children) {
    node.children = node._children;
    node._children = null;
  }
  return node;
}

export function visit(
  parent: NodeWithId,
  visitFn: (parent: NodeWithId) => void,
  childrenFn: (parent: NodeWithId) => NodeWithId[] | null | undefined
) {
  if (!parent) {
    return;
  }

  visitFn(parent);

  const children = childrenFn(parent);
  if (children) {
    const count = children.length;

    for (let i = 0; i < count; i++) {
      visit(children[i], visitFn, childrenFn);
    }
  }
}

export function getNodeGroupByDepthCount(rootNode: NodeWithId) {
  const nodeGroupByDepthCount = [1];

  const traverseFrom = function traverseFrom(node: NodeWithId, depth = 0) {
    if (!node.children || node.children.length === 0) {
      return 0;
    }

    if (nodeGroupByDepthCount.length <= depth + 1) {
      nodeGroupByDepthCount.push(0);
    }

    nodeGroupByDepthCount[depth + 1] += node.children.length;

    node.children.forEach((childNode) => {
      traverseFrom(childNode, depth + 1);
    });
  };

  traverseFrom(rootNode);
  return nodeGroupByDepthCount;
}

export function getTooltipString(
  node: unknown,
  i: number | undefined,
  { indentationSize = 4 }
) {
  if (!is(Object, node)) return '';

  const spacer = join('  ');
  const cr2br = replace(/\n/g, '<br/>');
  const spaces2nbsp = replace(/\s{2}/g, spacer(new Array(indentationSize)));
  const json2html = pipe(sortAndSerialize, cr2br, spaces2nbsp);

  const children = (node as any).children || (node as any)._children;

  if (typeof (node as any).value !== 'undefined')
    return json2html((node as any).value);
  if (typeof (node as any).object !== 'undefined')
    return json2html((node as any).object);
  if (children && children.length)
    return `childrenCount: ${(children as unknown[]).length}`;
  return 'empty';
}


text:
package org.apache.fineract.portfolio.savings.domain;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface SavingsAccountRepository extends JpaRepository<SavingsAccount, Long>, JpaSpecificationExecutor<SavingsAccount> {

    @Query("from SavingsAccount s_acc where s_acc.client.id = :clientId")
    List<SavingsAccount> findSavingAccountByClientId(@Param("clientId") Long clientId);

    @Query("from SavingsAccount s_acc where s_acc.status = :status")
    List<SavingsAccount> findSavingAccountByStatus(@Param("status") Integer status);

    @Query("from SavingsAccount sa where sa.client.id = :clientId and sa.group.id = :groupId")
    List<SavingsAccount> findByClientIdAndGroupId(@Param("clientId") Long clientId, @Param("groupId") Long groupId);

    @Query("select case when (count (saving) > 0) then true else false end from SavingsAccount saving where saving.client.id = :clientId and saving.status in (100,200,300,303,304)")
    boolean doNonClosedSavingAccountsExistForClient(@Param("clientId") Long clientId);

    @Query("from SavingsAccount sa where sa.client.id is null and sa.group.id = :groupId")
    List<SavingsAccount> findByGroupId(@Param("groupId") Long groupId);

    @Query("from SavingsAccount sa where sa.id = :accountId and sa.depositType = :depositAccountTypeId")
    SavingsAccount findByIdAndDepositAccountType(@Param("accountId") Long accountId,
            @Param("depositAccountTypeId") Integer depositAccountTypeId);

    @Query("from SavingsAccount sa where sa.accountNumber = :accountNumber and sa.status in (100, 200, 300, 303, 304) ")
    SavingsAccount findNonClosedAccountByAccountNumber(@Param("accountNumber") String accountNumber);
}


text:
package org.apache.commons.imaging.formats.tiff.taginfos;

import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImageWriteException;
import org.apache.commons.imaging.formats.tiff.TiffField;
import org.apache.commons.imaging.formats.tiff.constants.TiffDirectoryType;
import org.apache.commons.imaging.formats.tiff.fieldtypes.FieldType;

public class TagInfo {
    public static final int LENGTH_UNKNOWN = -1;
    public final String name;
    public final int tag;
    public final List<FieldType> dataTypes;
    public final int length;
    public final TiffDirectoryType directoryType;
    private final boolean isOffset;

    public TagInfo(final String name, final int tag, final FieldType dataType, final int length,
            final TiffDirectoryType exifDirectory) {
        this(name, tag, Arrays.asList(dataType), length, exifDirectory);
    }

    public TagInfo(final String name, final int tag, final FieldType dataType, final int length,
            final TiffDirectoryType exifDirectory, final boolean isOffset) {
        this(name, tag, Arrays.asList(dataType), length, exifDirectory,
                isOffset);
    }

    public TagInfo(final String name, final int tag, final FieldType dataType, final int length) {
        this(name, tag, Arrays.asList(dataType), length,
                TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);
    }

    public TagInfo(final String name, final int tag, final FieldType dataType) {
        this(name, tag, dataType, LENGTH_UNKNOWN,
                TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);
    }

    public TagInfo(final String name, final int tag, final List<FieldType> dataTypes, final int length,
            final TiffDirectoryType exifDirectory) {
        this(name, tag, dataTypes, length, exifDirectory, false);
    }

    public TagInfo(final String name, final int tag, final List<FieldType> dataTypes, final int length,
            final TiffDirectoryType exifDirectory, final boolean isOffset) {
        this.name = name;
        this.tag = tag;
        this.dataTypes = Collections.unmodifiableList(new ArrayList<>(
                dataTypes));
        this.length = length;
        this.directoryType = exifDirectory;
        this.isOffset = isOffset;
    }

    /**
     *
     * @param entry the TIFF field whose value to return
     * @return the value of the TIFF field
     * @throws ImageReadException thrown by subclasses
     */
    public Object getValue(final TiffField entry) throws ImageReadException {
        return entry.getFieldType().getValue(entry);
    }

    public byte[] encodeValue(final FieldType fieldType, final Object value, final ByteOrder byteOrder)
            throws ImageWriteException {
        return fieldType.writeData(value, byteOrder);
    }

    public String getDescription() {
        return tag + " (0x" + Integer.toHexString(tag) + ": " + name + "): ";
    }

    @Override
    public String toString() {
        return "[TagInfo. tag: " + tag + " (0x" + Integer.toHexString(tag)
                + ", name: " + name + "]";
    }

    public boolean isOffset() {
        return isOffset;
    }

    public boolean isText() {
        return false;
    }
}


text:
Installation instructions
~~~~~~~~~~~~~~~~~~~~~~~~~

Install with `pip`
==================
.. code:: bash

    pip install eazy

    # Forked dependencies that don't come with pip
    pip install git+https://github.com/gbrammer/dust_attenuation.git
    pip install git+https://github.com/gbrammer/dust_extinction.git

Install from the repository
===========================
.. code:: bash

    cd /usr/local/share/python # or some other location

    ### Fetch the eazy-py repo
    git clone https://github.com/gbrammer/eazy-py.git

    ### Build the python code
    cd eazy-py
    pip install . -r requirements.txt

Binder Demo
~~~~~~~~~~~
.. image:: https://mybinder.org/badge_logo.svg
 :target: https://mybinder.org/v2/gh/gbrammer/eazy-py/HEAD?filepath=docs%2Fexamples%2FHDFN-demo.ipynb


text:
For evaluation, please go to [`examples/classification`](https://github.com/chainer/chainercv/tree/master/examples/classification).

## Convert TensorFlow model
Convert TensorFlow's `*.ckpt` to `*.npz`.

```
$ python tfckpt2npz.py mobilenetv2 <source>.ckpt <target>.npz
```

The pretrained `.ckpt` for mobilenet can be downloaded from here.
https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet


text:
package org.opentosca.toscana.core.parse.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

import org.opentosca.toscana.model.EntityId;

import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;

public class SequenceEntity extends Entity {

    private final SequenceNode sequenceNode;

    public SequenceEntity(SequenceNode node, EntityId id, ServiceGraph graph) {
        super(id, graph);
        this.sequenceNode = node;
    }

    public List<String> getValues() {
        List<String> values = new ArrayList<>();
        for (Node node : sequenceNode.getValue()) {
            String value = ((ScalarNode) node).getValue();
            values.add(value);
        }
        return values;
    }

    @Override
    public List<Entity> getChildren() {
        List<Entity> children = new ArrayList<>();
        Collection<Entity> entities = super.getChildren();
        List<Entity> orderedEntities = new LinkedList<>(entities);
        // TODO sort per connection name, not entity name.
        orderedEntities.sort((b1, b2) -> b1.getName().compareTo(b2.getName()));
        for (Entity entity : orderedEntities) {
            children.add(entity);
        }
        return children;
    }

    /**
     Returns the associated child for given name and source entity.

     @return null if no child associated with given name was found
     */
    @Override
    public Optional<Entity> getChild(String key) {
        for (Connection connection : graph.outgoingEdgesOf(this)) {
            Entity child = connection.getTarget();
            if (key.equals(child.getName())) {
                return Optional.of(child);
            }
        }
        return Optional.empty();
    }

    @Override
    public String toString() {
        return (String.format("SequenceEntity (id=%s", getId()));
    }
}


text:
#include <iostream>
#define _WAVELETTL_GALERKINUTILS_VERBOSITY 1

#define JMAX 8
#define PMAX 0
#define _DIM 1

#define PRIMALORDER 3
#define DUALORDER   3
#include <fstream>
#include <map>
#include <time.h>

#include <algebra/symmetric_matrix.h>
#include <algebra/sparse_matrix.h>

#include <interval/i_index.h>
#include <interval/i_indexplot.h>
#include <interval/i_q_index.h>
#include <interval/i_q_indexplot.h>
#include <interval/ds_basis.h>
#include <interval/p_basis.h>

#include <interval/pq_frame.h>

#undef BASIS
#define FRAME
#undef RFRAME
#undef CDF

#include <Rd/cdf_basis.h>
#include <Rd/quarklet_frame.h>
#ifdef BASIS
#include <interval/p_expansion.h>
#endif

using namespace std;
using namespace WaveletTL;

int main()
{

  cout << "Testing wavelet-Galerkin solution of a Sturm b.v.p. ..." << endl;

  const int d  = PRIMALORDER;
  const int dT = DUALORDER; // be sure to use a continuous dual here, otherwise the RHS test will fail

  const int jmax = JMAX;
  const int pmax = PMAX;

#ifdef BASIS
  typedef PBasis<d,dT> Basis;
  Basis basis(1,1);
  typedef Basis::Index Index;
  const char* basis_type = "Primbs basis";
  basis.set_jmax(jmax);
#endif

#ifdef CDF
  typedef CDFBasis<d,dT> Basis;
  Basis basis;
  typedef Basis::Index Index;
#endif

#ifdef RFRAME
  typedef QuarkletFrame<d,dT> Basis;
  Basis basis;
  typedef Basis::Index Index;
#endif

#ifdef FRAME
  typedef PQFrame<d,dT> Basis;
  bool dirichlet_left=0;
  bool dirchlet_right=0;
  Basis basis(dirichlet_left, dirchlet_right, true);

  typedef Basis::Index Index;
  basis.set_jpmax(jmax,pmax);
  bool primal = true;

#endif

#ifdef RFRAME
  const int p = 2;
  const int j = 0;
  const int e = 1;
  const int k = 0;
  Index lambda(p,j,e,k);
  char plotnameInd[128];
  const char* filenameInd = "Image_outputs/indexplot.m";
  if(e==1)
    sprintf(plotnameInd, "%s%d%s%d%s%d%s", "rquarklet_m_", d, "_mT_" , dT, "_p_" , p, ".png");
  else
    sprintf(plotnameInd, "%s%d%s%d%s", "rquark_m_", d, "_p_" , p, ".png");

  std::ofstream ind_stream1(filenameInd);
  const int leftx = -2;
  const int rightx= 3;
  Grid<1> grid(leftx, rightx, 1024);
  Array1D<double> values;
  basis.evaluate(0, lambda, grid.points(), values);
  SampledMapping<1>(grid,values).matlab_output(ind_stream1);
  ind_stream1 << "figure;\nplot(x,y,'-');\nset(gca,'fontsize',20)\nxlim([" <<leftx << " " << rightx << "])"
          ";\nylim([-inf inf]);\nprint -dpng " << plotnameInd  << endl;
  ind_stream1.close();
#endif

#ifdef CDF
  const int j = 0;
  const int e = 1;
  const int k = 0;
  Index lambda(j,e,k);
  char plotnameInd[128];
  const char* filenameInd = "Image_outputs/indexplot.m";
  if(e==1)
    sprintf(plotnameInd, "%s%d%s%d%s", "cdf_motherwavelet_m_", d, "_mT_" , dT, ".png");
  else
    sprintf(plotnameInd, "%s%d%s", "cdf_generator_m_", d, ".png");

  std::ofstream ind_stream1(filenameInd);
  const int leftx = -4;
  const int rightx= 5;
  Grid<1> grid(leftx, rightx, 1024);
  Array1D<double> values;
  basis.evaluate(0, lambda, grid.points(), values);
  SampledMapping<1>(grid,values).matlab_output(ind_stream1);
  ind_stream1 << "figure;\nplot(x,y,'-');\nset(gca,'fontsize',20)\nxlim([" <<leftx << " " << rightx << "]);;\nprint -dpng " << plotnameInd  << endl;
  ind_stream1.close();
#endif

#ifdef FRAME
  const int p = 2;
  const int j = basis.j0();
  const int e = 0;
  const int k = 5;

  InfiniteVector<double,Index> indplot;
  cout << basis.Nablamin() << ", " << basis.Nablamax(j,p) << endl;

    Index lambda(p,j,e,k,&basis);
    char filenameInd[128], plotnameInd[128];
    int number=lambda.number();
    sprintf(filenameInd, "%s%d%s%d%s%d%s%d%s%d%s", "Image_outputs/indexplot_bc_", dirichlet_left, "_case_" , primal , "_m_", d, "_mT_" , dT, "_number_" , number , ".m");
    sprintf(plotnameInd, "%s%d%s%d%s%d%s%d%s%d%s", "quarklet_bc_", dirichlet_left, "_case_" , primal , "_m_", d, "_mT_" , dT, "_number_" , number , ".png");
    std::ofstream ind_stream1 (filenameInd);

    /* plot solution*/
   indplot.clear();
    indplot.set_coefficient(lambda, 1);
    SampledMapping<1> indsamp(evaluate(basis, indplot, primal, 8));
    indsamp.matlab_output(ind_stream1);
    ind_stream1 << "figure;\nplot(x,y,'-');\nset(gca,'fontsize',20)\nprint -dpng " << plotnameInd << endl;
    ind_stream1.close();

    cout << "Index " << lambda << " plotted" << endl;

#endif

  return 0;
}


text:
using System;
using System.Runtime.InteropServices;

namespace SharpVk.Multivendor
{
    /// <summary>
    ///
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public partial struct PipelineRasterizationLineStateCreateInfo
    {
        /// <summary>
        ///
        /// </summary>
        public SharpVk.Multivendor.LineRasterizationMode LineRasterizationMode
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        public bool StippledLineEnable
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        public uint? LineStippleFactor
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        public ushort? LineStipplePattern
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="pointer">
        /// </param>
        internal unsafe void MarshalTo(SharpVk.Interop.Multivendor.PipelineRasterizationLineStateCreateInfo* pointer)
        {
            pointer->SType = StructureType.PipelineRasterizationLineStateCreateInfo;
            pointer->Next = null;
            pointer->LineRasterizationMode = this.LineRasterizationMode;
            pointer->StippledLineEnable = this.StippledLineEnable;
            if (this.LineStippleFactor != null)
            {
                pointer->LineStippleFactor = this.LineStippleFactor.Value;
            }
            else
            {
                pointer->LineStippleFactor = default(uint);
            }
            if (this.LineStipplePattern != null)
            {
                pointer->LineStipplePattern = this.LineStipplePattern.Value;
            }
            else
            {
                pointer->LineStipplePattern = default(ushort);
            }
        }
    }
}


text:
ember-gulp-example is a scaffold to start developing Ember.js applications without extensive setup upfront, but with everything you need to enjoy a tidy directory structure.

It features:

 - Ember.js
 - Gulp.js
 - Handlebars precompilation
 - Dependencies via bower
 - Easy local server via PHP
 - Support for `hashchange` and `history` routing out of the box.

## Dependencies

 - [Node.js](http://nodejs.org)
 - [Bower](http://bower.io)
 - PHP (only if you want to use `gulp server`, alternatively you can use WEBrick, SimpleHTTPServer or whatever suits your needs - just adapt `gulpfile.js`)

## Installation

```
git clone https://github.com/felixkiss/ember-gulp-example.git
cd ember-gulp-example/
rm -rf .git/
bower install
npm install
```

## Usage

```
gulp
```

will

 - compile jQuery, Handlebars and Ember (Bower dependencies) into `public/assets/javascripts/dependencies.js`
 - compile all `.js` in `app/` into `public/assets/javascripts/app.js`
 - compile all `.handlebars` in `app/templates` into `public/assets/javascripts/templates.js`
 - watch the `app/` for changes and recompile automatically

```
gulp server
```

will additionally start the webserver built into PHP with `public/` as the document root.

## License

MIT


text:
#
#

# Set environment variables here.

# The java implementation to use.  Java 1.6 required.
# export JAVA_HOME=/usr/java/jdk1.6.0/

# Extra Java CLASSPATH elements.  Optional.
# export HBASE_CLASSPATH=

# The maximum amount of heap to use, in MB. Default is 1000.
# export HBASE_HEAPSIZE=1000

# Extra Java runtime options.
# Below are what we set by default.  May only work with SUN JVM.
# For more on why as well as other possible settings,
# see http://wiki.apache.org/hadoop/PerformanceTuning

export HBASE_OPTS="$HBASE_OPTS -XX:+UseConcMarkSweepGC "
#export HBASE_OPTS="$HBASE_OPTS -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=70 "

# Uncomment below to enable java garbage collection logging in the .out file.
#export HBASE_OPTS="$HBASE_OPTS -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps $HBASE_GC_OPTS "

# Uncomment below (along with above GC logging) to put GC information in its own logfile (will set HBASE_GC_OPTS)
# export HBASE_USE_GC_LOGFILE=true

# Uncomment below if you intend to use the EXPERIMENTAL off heap cache.
# export HBASE_OPTS="$HBASE_OPTS -XX:MaxDirectMemorySize="
# Set hbase.offheapcache.percentage in hbase-site.xml to a nonzero value.

# Uncomment and adjust to enable JMX exporting
# See jmxremote.password and jmxremote.access in $JRE_HOME/lib/management to configure remote password access.
# More details at: http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
#
# export HBASE_JMX_BASE="-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
# export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10101"
# export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10102"
# export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10103"
# export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10104"

# File naming hosts on which HRegionServers will run.  $HBASE_HOME/conf/regionservers by default.
# export HBASE_REGIONSERVERS=${HBASE_HOME}/conf/regionservers

# File naming hosts on which backup HMaster will run.  $HBASE_HOME/conf/backup-masters by default.
# export HBASE_BACKUP_MASTERS=${HBASE_HOME}/conf/backup-masters

# Extra ssh options.  Empty by default.
# export HBASE_SSH_OPTS="-o ConnectTimeout=1 -o SendEnv=HBASE_CONF_DIR"

# Where log files are stored.  $HBASE_HOME/logs by default.
# export HBASE_LOG_DIR=${HBASE_HOME}/logs

# Enable remote JDWP debugging of major HBase processes. Meant for Core Developers
# export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8070"
# export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8071"
# export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8072"
# export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8073"

# A string representing this instance of hbase. $USER by default.
# export HBASE_IDENT_STRING=$USER

# The scheduling priority for daemon processes.  See 'man nice'.
# export HBASE_NICENESS=10

# The directory where pid files are stored. /tmp by default.
# export HBASE_PID_DIR=/var/hadoop/pids

# Seconds to sleep between slave commands.  Unset by default.  This
# can be useful in large clusters, where, e.g., slave rsyncs can
# otherwise arrive faster than the master can service them.
# export HBASE_SLAVE_SLEEP=0.1

# Tell HBase whether it should manage it's own instance of Zookeeper or not.
export HBASE_MANAGES_ZK=true


text:
module System.Ext2.FeatureFlags where

import Data.Bits ((.&.))
import Data.Maybe (fromJust)
import Data.Tuple (swap)

data OptionalFeatureFlag = DirPrealloc
                         | AFSInodes
                         | Journaled
                         | ExtendedAttributes
                         | Resizable
                         | DirHashIndex
                         deriving (Eq, Show)

-- | Optional feature flags
optionalFeatureFlagTable :: [(OptionalFeatureFlag, Int)]
optionalFeatureFlagTable = [ (DirPrealloc, 0x0001)
                           , (AFSInodes, 0x0002)
                           , (Journaled, 0x0004)
                           , (ExtendedAttributes, 0x0008)
                           , (Resizable, 0x0010)
                           , (DirHashIndex, 0x0020)
                           ]

instance Enum OptionalFeatureFlag where
  fromEnum = fromJust . flip lookup optionalFeatureFlagTable
  toEnum = fromJust . flip lookup (map swap optionalFeatureFlagTable)

hasOptionalFlag :: Int -> OptionalFeatureFlag -> Bool
hasOptionalFlag given o = given .&. (fromIntegral . fromEnum $ o) /= 0

listOptionalFlags :: Int -> [OptionalFeatureFlag]
listOptionalFlags given =
  filter (hasOptionalFlag given) (map fst optionalFeatureFlagTable)

-- | Read-only feature flags
data ROFeatureFlag = SparseSuperblocks
                   | LargeFileSize
                   | BTreeDirs
                   deriving (Eq, Show)

roCompatFlagTable :: [(ROFeatureFlag, Int)]
roCompatFlagTable = [ (SparseSuperblocks, 0x0001)
                    , (LargeFileSize, 0x0002)
                    , (BTreeDirs, 0x0004)
                    ]

instance Enum ROFeatureFlag where
  fromEnum = fromJust . flip lookup roCompatFlagTable
  toEnum = fromJust . flip lookup (map swap roCompatFlagTable)

hasRoFlag :: Int -> ROFeatureFlag -> Bool
hasRoFlag given o = given .&. (fromIntegral . fromEnum $ o) /= 0

listRoFlags :: Int -> [ROFeatureFlag]
listRoFlags given = filter (hasRoFlag given) (map fst roCompatFlagTable)

-- | Required feature flags
data RequiredFeatureFlag = Compression
                         | FileType
                         | ReplayJournal
                         | JournalDevice
                         | MetaBg -- TODO: What is this?
                         deriving (Eq, Show)

reqFlagTable :: [(RequiredFeatureFlag, Int)]
reqFlagTable = [ (Compression, 0x0001)
               , (FileType, 0x0002)
               , (ReplayJournal, 0x0004)
               , (JournalDevice, 0x0008)
               , (MetaBg, 0x0010)
               ]

instance Enum RequiredFeatureFlag where
  fromEnum = fromJust . flip lookup reqFlagTable
  toEnum = fromJust . flip lookup (map swap reqFlagTable)

hasReqFlag :: Int -> RequiredFeatureFlag -> Bool
hasReqFlag given o = given .&. (fromIntegral . fromEnum $ o) /= 0

listReqFlags :: Int -> [RequiredFeatureFlag]
listReqFlags given = filter (hasReqFlag given) (map fst reqFlagTable)


text:
@page {
  position: relative; }

@page :left {
  margin: 2cm 2.2cm 2cm 3.5cm; }

@page :right {
  margin: 2cm 3.5cm 2cm 2.2cm; }

@page :first {
  margin-top: 4cm; }

/* line 17, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
body {
  text-align: justify;
  counter-reset: chapter; }

/* line 22, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h1, h2, h3, h4, h5 {
  text-align: left; }

/* line 27, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h1 {
  font: bold 29pt/29pt 'Roboto Condensed', sans-serif;
  color: #000;
  padding: 0 35% 1cm 0;
  margin: 0 0 1cm 0;
  text-align: left;
  letter-spacing: -1px; }

/* line 36, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h1:first-child {
  counter-reset: page 1; }

@page {
  @top {
    content: "Página " counter(page); }
 }

/* line 45, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h2 {
  font: 600 22pt/24.5pt 'Roboto Condensed', sans-serif;
  color: #000;
  margin: 0;
  padding: 2cm 0 0.5cm 0;
  page-break-before: always; }

/* line 52, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h2 span::after {
  content: "Part " counter(chapter);
  counter-increment: chapter; }

/* line 57, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h2:first-child {
  padding-top: 0; }

/* line 61, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h1 + h2, h2 + h2 {
  font: italic 15pt/18.5pt 'Crimson Text', serif;
  color: #333;
  margin: 0 0 0 0;
  padding: 0 0 0.8cm 0;
  text-align: left;
  letter-spacing: -1px;
  list-style: none;
  page-break-before: avoid; }

/* line 72, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h3 {
  font: 800 18pt/19.5pt 'Roboto Condensed', sans-serif;
  color: #000;
  margin: 0;
  padding: 0.8cm 0 0.5cm 0; }

/* line 78, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h4 {
  font: bold 16pt/18pt 'Roboto Condensed', sans-serif;
  margin: 1cm 0 0.3cm 0; }

/* line 83, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
.page-break {
  page-break-after: always; }

/* line 85, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
ul.author {
  font: italic 15pt/18.5pt 'Crimson Text', serif;
  color: #000;
  margin: 0 0 0 0;
  padding: 0 0 0.8cm 0;
  text-align: left;
  letter-spacing: -1px;
  border-bottom: 1px solid #999;
  list-style: none; }

/* line 95, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
ul.author li {
  color: #333;
  padding: 0 0 0.1cm 0; }

/* line 100, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
ul.author li span {
  color: #999;
  font-size: 13pt; }

/* line 105, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
p {
  font: 12pt/14pt 'Crimson Text', serif;
  text-indent: 1cm;
  margin: 0;
  padding: 0;
  orphans: 3;
  widows: 3;
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  hyphens: auto; }

/* line 117, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
h1 + p, h2 + p, h3 + p, h4 + p, h5 + p {
  text-indent: 0; }

/* line 121, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
blockquote {
  font: italic 12pt/15pt 'Crimson Text', serif;
  padding: 0.8cm 0 0.9cm 1.5cm;
  margin: 0;
  text-align: justify;
  orphans: 2;
  widows: 2; }

/* line 130, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
blockquote + p {
  text-indent: 0; }

/* line 134, C:/Dropbox/Eduardo/Trabalhos e Projetos/Pessoais/Bookfy.it/single_column/single_column.scss */
img {
  width: inherit;
  margin: 0.5cm auto 1cm;
  display: block; }

/*# sourceMappingURL=single_column.css.map */


text:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <stroke
        android:width="3dp"
        android:color="@color/red_500"/>

    <solid android:color="@color/red_500"/>

</shape>


text:
package com.dremio.service.autocomplete.statements.grammar;

import static com.dremio.exec.planner.sql.parser.impl.ParserImplConstants.ALTER;
import static com.dremio.exec.planner.sql.parser.impl.ParserImplConstants.CREATE;

import java.util.Arrays;

import com.dremio.exec.planner.sql.parser.impl.ParserImplConstants;
import com.dremio.service.autocomplete.tokens.DremioToken;
import com.dremio.service.autocomplete.tokens.TokenBuffer;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

/**
 * ALTER (TABLE | VDS | PDS | DATASET) tableName
 * CREATE REFLECTION_CREATE_STATEMENT
 */
public final class AlterStatement extends Statement {
  private final Type type;
  private final TableReference tableReference;

  private AlterStatement(
    ImmutableList<DremioToken> tokens,
    Type type,
    TableReference tableReference,
    Statement child) {
    super(tokens, asListIgnoringNulls(tableReference, child));
    this.type = type;
    this.tableReference = tableReference;
  }

  public Type getType() {
    return type;
  }

  public TableReference getTableReference() {
    return tableReference;
  }

  public static AlterStatement parse(TokenBuffer tokenBuffer) {
    Preconditions.checkNotNull(tokenBuffer);

    return builder(tokenBuffer.toList())
      .type(parseType(tokenBuffer))
      .catalogPath(parseTableReference(tokenBuffer))
      .child(tokenBuffer)
      .build();
  }

  private static Type parseType(TokenBuffer tokenBuffer) {
    if (tokenBuffer.isEmpty()) {
      return null;
    }

    tokenBuffer.readAndCheckKind(ALTER);
    if (tokenBuffer.isEmpty()) {
      return null;
    }

    return Type.fromKind(tokenBuffer.readKind());
  }

  private static TableReference parseTableReference(TokenBuffer tokenBuffer) {
    if (tokenBuffer.isEmpty()) {
      return null;
    }

    ImmutableList<DremioToken> tableReferenceTokens = tokenBuffer.readUntilKind(CREATE);
    return TableReference.parse(new TokenBuffer(tableReferenceTokens));
  }

  private static Statement parseChildStatement(TokenBuffer tokenBuffer, TableReference tableReference) {
    if (tokenBuffer.isEmpty()) {
      return null;
    }

    switch (tokenBuffer.peekKind()) {
    case CREATE:
      return ReflectionCreateStatement.parse(tokenBuffer, tableReference);
    default:
      throw new UnsupportedOperationException("UNKNOWN KIND: " + tokenBuffer.peekKind());
    }
  }

  public enum Type {
    UNKNOWN(-1),
    TABLE(ParserImplConstants.TABLE),
    VDS(ParserImplConstants.VDS),
    PDS(ParserImplConstants.PDS),
    DATASET(ParserImplConstants.DATASET);

    private final int kind;

    Type(int kind) {
      this.kind = kind;
    }

    public int getKind() {
      return kind;
    }

    public static AlterStatement.Type fromKind(int kind) {
      if (!isValidType(kind)) {
        return AlterStatement.Type.UNKNOWN;
      }

      return VALID_TYPES.get(kind);
    }

    private static final ImmutableMap<Integer, AlterStatement.Type> VALID_TYPES =
      Arrays.stream(AlterStatement.Type.values())
        .filter(s -> s.kind > 0)
        .collect(ImmutableMap.toImmutableMap(s -> s.kind, s -> s));

    private static boolean isValidType(int kind) {
      return VALID_TYPES.containsKey(kind);
    }
  }

  private static TypeStep builder(ImmutableList<DremioToken> tokens) {
    return new Builder(tokens);
  }

  private interface TypeStep {
    TableReferenceStep type(Type type);
  }

  private interface TableReferenceStep {
    ChildStep catalogPath(TableReference tableReference);
  }

  private interface ChildStep {
    Build child(TokenBuffer tokenBuffer);
  }

  private interface Build {
    AlterStatement build();
  }

  private static final class Builder implements TypeStep, TableReferenceStep, ChildStep, Build{
    private final ImmutableList<DremioToken> tokens;

    private Type type;
    private TableReference tableReference;
    private Statement child;

    public Builder(ImmutableList<DremioToken> tokens) {
      this.tokens = tokens;
    }

    @Override
    public Builder type(Type type) {
      this.type = type;
      return this;
    }

    @Override
    public Builder catalogPath(TableReference tableReference) {
      this.tableReference = tableReference;
      return this;
    }

    @Override
    public Builder child(TokenBuffer tokenBuffer) {
      this.child = parseChildStatement(tokenBuffer, tableReference);
      return this;
    }

    @Override
    public AlterStatement build() {
      return new AlterStatement(tokens, type, tableReference, child);
    }
  }
}


text:
Great RESTful APIs look like they were designed by a single team. This promotes API adoption, reduces friction, and enables clients to use them properly. To build APIs that meet this standard, and to answer many common questions encountered along the way of RESTful API development, the Haufe-Lexware CTO team has created this comprehensive set of guidelines. We have shared it with you to inspire additional discussion and refinement within and among your teams, and contribute our learnings and suggestions to the tech community at large.

### Usage
---
The API style guide MUST be used when you create an API, refactor or extend an API, no exeptions. Existing APIs might be subject to adapt if there is business value in it.

It is the responsibility of the person implementing the API to apply the API Styleguide to a specific API and project!

>	Please follow the guidelines, but don't follow blindly!
>	You can break the rules by talking to us and providing justification.

The style guide is work in progress. We'd love your feedback – whether you agree, disagree, or have some additional practices and tips to add.

We encourage you to improve the style guide with modifications and extensions via the usual Fork/Pull Request dance. If your modification gets merged, it becomes part of the Styleguide. On the other hand if you don't bother, don't complain.

### API Design Review Process
---
We are still at the beginning of our journey to an API driven company.

There will be pros and cons how to handle and apply the style guide to real projects. There are many things to learn and to share with another. Feel free to reach out and ask and share on the `#apistrat` channel on our Haufe RocketChat.

The [API Design Review Process](api-design-review-process/api-design-review-process.md) is **mandatory** for each new or refactored API at Haufe-Lexware.

### Content
---

#### Most important chapters
Please read the bold chapters beow. These chapters describe the intent, mindset and process how we want to design an API.

Each section contains links to the chapters with more details.

#### Table of Content
The chapters are:

- **[Introduction](introduction/introduction.md)**
- **[General Guidlines](general-guidelines/general-guidelines.md)**
- **[API Design Principles](api-design-principles/api-design-principles.md)**
- **[API Design Process](api-design-process/api-design-process.md)**
- **[API Design Review Process](api-design-review-process/api-design-review-process.md)**
- **[REST Principles](rest-principles/rest-principles.md)**
- [URI Components and Versioning](uri-components/uri-components.md)
- [HTTP Verbs](http-verbs/http-verbs.md)
- [Hypermedia and REST](hypermedia-and-rest/hypermedia-and-rest.md)
- [Resources](resources/resources.md)
- [Relationships and Sub-Resources](relationships-and-sub-resources/relationships-and-sub-resources.md)
- [Collection Resources](collection-resources/collection-resources.md)
	- [Resource naming](collection-resources/collection-resources.md#resource-naming)
	- [Get List of resources](collection-resources/collection-resources.md#get-list-of-resources)
	- [Read Single Resource](collection-resources/collection-resources.md#read-single-resources)
	- [Update Single Ressource](collection-resources/collection-resources.md#update-single-ressource)
	- [Update Partial Single Resource](collection-resources/collection-resources.md#update-partial-single-resource)
	- [Delete Single Resource](collection-resources/collection-resources.md#delete-single-resource)
	- [Create New Resource](collection-resources/collection-resources.md#create-new-resource)
	- [Create New Resource - Consumer Supplied Identifier](collection-resources/collection-resources.md#create-new-resource---consumer-supplied-identifier)
- [Filtering, sorting, field selection and paging](filtering-sorting-field-selection-and-paging/filtering-sorting-field-selection-and-paging.md)
- [Hypermedia Response Format](response-format/response-format.md)
- [Type Formatting](type-formatting/type-formatting.md)
- [Message Schema and Postels Law](message-schema/message-schema.md)
- [Security and Authentication](security-and-authentication/security-and-authentication.md)
- [Search](search/search.md)
- [Documentation](documentation/documentation.md)
- [Error handling](error-handling/error-handling.md)
- [HTTP Status Codes](http-status-codes/http-status-codes.md)
- [Caching](caching/caching.md)
- [Correlation-Id](correlation-id/correlation-id.md)
- [API Management](api-management/api-management.md)
- [FAQ](faq/faq.md)
- [Further Reading](further-reading/further-reading.md)

### Credits
---

For the creation of the style guide I took a lot of input from other authors and even copied whole passages.

I want to gratefully thank these authors and hope that I marked the relevant passages. My resources are listed under [Further Reading](further-reading.md). Special thanks goes to

[S.Stedman and G. Laforge from Paypal](https://github.com/paypal/api-standards/blob/master/api-style-guide.md)
[Brian Mulloy](https://pages.apigee.com/rs/apigee/images/api-design-ebook-2012-03.pdf)
[Geert Jansen](http://restful-api-design.readthedocs.org/en/latest/intro.html)
[Vinay Sahni](http://www.vinaysahni.com/)
[Michel Triana](http://micheltriana.com/2013/09/30/http-verbs-in-a-rest-web-api/)
[Stefan Jauker](http://blog.mwaysolutions.com/author/stefan-jauker/)

Another great inspiration were [Zalando's Restful API Guidelines](http://zalando.github.io/restful-api-guidelines/).


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Proc. Acad. nat. Sci. Philad. , 1895 47: 441 (1895)

#### Original name
Stilbomyces berenice Ellis & Everh.

### Remarks
null


text:
from __future__ import absolute_import

from django.conf import settings
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

from sentry import constants
from sentry.app import digests
from sentry.digests import get_option_key as get_digest_option_key
from sentry.plugins import plugins, NotificationPlugin
from sentry.web.forms.projects import (
    DigestSettingsForm,
    NotificationSettingsForm,
)
from sentry.web.frontend.base import ProjectView

OK_SETTINGS_SAVED = _('Your settings were saved successfully.')

class ProjectNotificationsView(ProjectView):
    required_scope = 'project:write'

    def _iter_plugins(self):
        for plugin in plugins.all(version=1):
            if not isinstance(plugin, NotificationPlugin):
                continue
            yield plugin

    def _handle_enable_plugin(self, request, project):
        plugin = plugins.get(request.POST['plugin'])
        plugin.enable(project)
        messages.add_message(
            request, messages.SUCCESS,
            constants.OK_PLUGIN_ENABLED.format(name=plugin.get_title()),
        )

    def _handle_disable_plugin(self, request, project):
        plugin = plugins.get(request.POST['plugin'])
        plugin.disable(project)
        messages.add_message(
            request, messages.SUCCESS,
            constants.OK_PLUGIN_DISABLED.format(name=plugin.get_title()),
        )

    def handle(self, request, organization, team, project):
        op = request.POST.get('op')
        if op == 'enable':
            self._handle_enable_plugin(request, project)
            return HttpResponseRedirect(request.path)
        elif op == 'disable':
            self._handle_disable_plugin(request, project)
            return HttpResponseRedirect(request.path)

        if op == 'save-settings':
            if digests.enabled(project):
                digests_form = DigestSettingsForm(
                    data=request.POST,
                    prefix='digests',
                    initial={
                        'minimum_delay': project.get_option(
                            get_digest_option_key('mail', 'minimum_delay'),
                            digests.minimum_delay / 60,
                        ),
                        'maximum_delay': project.get_option(
                            get_digest_option_key('mail', 'maximum_delay'),
                            digests.maximum_delay / 60,
                        ),
                    },
                )
            else:
                digests_form = None

            general_form = NotificationSettingsForm(
                data=request.POST,
                prefix='general',
                initial={
                    'subject_prefix': project.get_option(
                        'mail:subject_prefix', settings.EMAIL_SUBJECT_PREFIX),
                },
            )
            if general_form.is_valid() and (digests_form.is_valid() if digests_form is not None else True):
                project.update_option('mail:subject_prefix', general_form.cleaned_data['subject_prefix'])
                if digests_form is not None:
                    project.update_option(
                        get_digest_option_key('mail', 'minimum_delay'),
                        digests_form.cleaned_data['minimum_delay'] * 60,
                    )
                    project.update_option(
                        get_digest_option_key('mail', 'maximum_delay'),
                        digests_form.cleaned_data['maximum_delay'] * 60,
                    )
                messages.add_message(
                    request, messages.SUCCESS,
                    OK_SETTINGS_SAVED)
                return HttpResponseRedirect(request.path)
        else:
            if digests.enabled(project):
                digests_form = DigestSettingsForm(
                    prefix='digests',
                    initial={
                        'minimum_delay': project.get_option(
                            get_digest_option_key('mail', 'minimum_delay'),
                            digests.minimum_delay,
                        ) / 60,
                        'maximum_delay': project.get_option(
                            get_digest_option_key('mail', 'maximum_delay'),
                            digests.maximum_delay,
                        ) / 60,
                    },
                )
            else:
                digests_form = None

            general_form = NotificationSettingsForm(
                prefix='general',
                initial={
                    'subject_prefix': project.get_option(
                        'mail:subject_prefix', settings.EMAIL_SUBJECT_PREFIX),
                },
            )

        enabled_plugins = []
        other_plugins = []
        for plugin in self._iter_plugins():
            if plugin.is_enabled(project):
                content = plugin.get_notification_doc_html()

                form = plugin.project_conf_form
                if form is not None:
                    view = plugin.configure(request, project=project)
                    if isinstance(view, HttpResponse):
                        return view
                    enabled_plugins.append((plugin, mark_safe(content + view)))
                elif content:
                    enabled_plugins.append((plugin, mark_safe(content)))
            elif plugin.can_configure_for_project(project):
                other_plugins.append(plugin)

        context = {
            'page': 'notifications',
            'enabled_plugins': enabled_plugins,
            'other_plugins': other_plugins,
            'general_form': general_form,
            'digests_form': digests_form,
        }

        return self.respond('sentry/project-notifications.html', context)


text:
package org.manticore;

import java.net.URI;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
    public final static String METHOD_NAME = "GET";

    public HttpGetWithEntity() {
        super();
    }

    public HttpGetWithEntity(URI url) {
        super();
        setURI(url);
    }

    public HttpGetWithEntity(String url) {
        super();
        setURI(URI.create(url));
    }

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }
}


text:
<BroadcastMonitor>
  <updated>2015-08-07T15:09:07</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-07T15:08:37</startTime>
    <itemId>1000080586:0</itemId>
    <titleId>216139059</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** OPENER 1 ZMOR</titleName>
    <artistName>RUDY</artistName>
    <albumName></albumName>
    <CategoryCode>833</CategoryCode>
    <CategoryName>BEDJES</CategoryName>
    <itemDuration>214</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-07T15:12:12</startTime>
    <itemId>1000080586:1243201</itemId>
    <titleId>216001869</titleId>
    <itemCode>B267</itemCode>
    <itemReference></itemReference>
    <titleName>Come To Me </titleName>
    <artistName>Koop</artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>167</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
from fabric.state import env
# Include all your stage environments here
from stage import stage
from prod import prod
from local import local

from fabrik.transfer.git import copy

# Put settings used by all env stages
env.repro_url = "git@github.com:Frojd/Yourrepro.git"


text:
export const kategorieFilterChange = (kategorie) => ({
  type: 'VITEZOVE_KATEGORIE_FILTER_CHANGE',
  kategorieFilter: kategorie, // typ
});

export const kategorieSubFilterChange = (kategorie) => ({
  type: 'VITEZOVE_KATEGORIE_SUB_FILTER_CHANGE',
  kategorieSubFilter: kategorie, // id
});


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxAccntConfig extends BxBaseModGeneralConfig
{
    protected $_oDb;
    protected $_aHtmlIds;

    /**
     * Constructor
     */
    public function __construct($aModule)
    {
        parent::__construct($aModule);

        $this->CNF = array (
        	// page URIs
        	'URL_MANAGE_ADMINISTRATION' => 'page.php?i=accounts-administration',

	        // objects
	        'OBJECT_FORM_ACCOUNT' => 'bx_accounts_account',
            'OBJECT_FORM_ACCOUNT_DISPLAY_SETTINGS_EMAIL' => 'bx_accounts_account_settings_email',
	        'OBJECT_MENU_MANAGE_TOOLS' => 'bx_accounts_menu_manage_tools', //manage menu in content administration tools
        	'OBJECT_GRID_ADMINISTRATION' => 'bx_accounts_administration',
        	'OBJECT_GRID_MODERATION' => 'bx_accounts_moderation',

        	// some language keys
            'T' => array (
        		'grid_action_err_delete' => '_bx_accnt_grid_action_err_delete',
        		'grid_action_err_perform' => '_bx_accnt_grid_action_err_perform',
            	'filter_item_active' => '_bx_accnt_grid_filter_item_title_adm_active',
                'filter_item_operators' => '_bx_accnt_grid_filter_item_title_adm_operators',
            	'filter_item_pending' => '_bx_accnt_grid_filter_item_title_adm_pending',
            	'filter_item_suspended' => '_bx_accnt_grid_filter_item_title_adm_suspended',
            	'filter_item_select_one_filter1' => '_bx_accnt_grid_filter_item_title_adm_select_one_filter1',
                'filter_item_select_one_filter2' => '_bx_accnt_grid_filter_item_title_adm_select_one_filter2',
        	)
        );

        $this->_aObjects = array(
        	'alert' => $this->_sName,
        );

        $this->_aJsClasses = array(
        	'main' => 'BxAccntMain',
        	'manage_tools' => 'BxAccntManageTools'
        );

        $this->_aJsObjects = array(
        	'main' => 'oBxAccntMain',
        	'manage_tools' => 'oBxAccntManageTools'
        );

        $this->_aGridObjects = array(
        	'moderation' => $this->CNF['OBJECT_GRID_MODERATION'],
        	'administration' => $this->CNF['OBJECT_GRID_ADMINISTRATION'],

        );

        $sHtmlPrefix = str_replace('_', '-', $this->_sName);
        $this->_aHtmlIds = array(
        	'profile' => $sHtmlPrefix . '-profile-',
        	'profile_more_popup' => $sHtmlPrefix . '-profile-more-popup-',

        	'password_text' => $sHtmlPrefix . '-txt-password',
            'password_button' => $sHtmlPrefix . '-btn-copy',
        	'password_popup' => $sHtmlPrefix . '-password-popup',
        );
    }

    public function init(&$oDb)
    {
        $this->_oDb = &$oDb;
    }

	public function getHtmlIds($sKey = '')
    {
        if(empty($sKey))
            return $this->_aHtmlIds;

        return isset($this->_aHtmlIds[$sKey]) ? $this->_aHtmlIds[$sKey] : '';
    }
}

/** @} */


text:
using GroupDocs.Comparison.Common.Exceptions;
using GroupDocs.Comparison.MVC.Products.Common.Entity.Web;
using GroupDocs.Comparison.MVC.Products.Common.Resources;
using GroupDocs.Comparison.MVC.Products.Common.Util.LowercaseContractResolver;
using GroupDocs.Comparison.MVC.Products.Comparison.Config;
using GroupDocs.Comparison.MVC.Products.Comparison.Model.Request;
using GroupDocs.Comparison.MVC.Products.Comparison.Model.Response;
using GroupDocs.Comparison.MVC.Products.Comparison.Service;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace GroupDocs.Comparison.MVC.Products.Comparison.Controllers
{
    /// <summary>
    /// SignatureApiController
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ComparisonApiController : ApiController
    {
        private readonly IComparisonService comparisonService;
        private static readonly Common.Config.GlobalConfiguration globalConfiguration = new Common.Config.GlobalConfiguration();

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="globalConfiguration">GlobalConfiguration</param>
        public ComparisonApiController()
        {
            comparisonService = new ComparisonServiceImpl(globalConfiguration);
        }

        /// <summary>
        /// Load Comparison configuration
        /// </summary>
        /// <returns>Comparison configuration</returns>
        [HttpGet]
        [Route("loadConfig")]
        public ComparisonConfiguration LoadConfig()
        {
            return globalConfiguration.Comparison;
        }

        /// <summary>
        /// Get all files and directories from storage
        /// </summary>
        /// <param name="postedData">Post data</param>
        /// <returns>List of files and directories</returns>
        [HttpPost]
        [Route("loadFileTree")]
        public HttpResponseMessage loadFileTree(PostedDataEntity fileTreeRequest)
        {
            return Request.CreateResponse(HttpStatusCode.OK, comparisonService.LoadFiles(fileTreeRequest));
        }

        /// <summary>
        /// Download results
        /// </summary>
        /// <param name=""></param>
        [HttpGet]
        [Route("downloadDocument")]
        public HttpResponseMessage DownloadDocument(string guid)
        {
            string filePath = guid;
            if (!string.IsNullOrEmpty(filePath))
            {
                if (File.Exists(filePath))
                {
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    var fileStream = new FileStream(filePath, FileMode.Open);
                    response.Content = new StreamContent(fileStream);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = System.IO.Path.GetFileName(filePath);
                    return response;
                }
            }
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }

        /// <summary>
        /// Upload document
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost]
        [Route("uploadDocument")]
        public HttpResponseMessage UploadDocument()
        {
            try
            {
                string url = HttpContext.Current.Request.Form["url"];
                // get documents storage path
                string documentStoragePath = globalConfiguration.Comparison.GetFilesDirectory();
                bool rewrite = bool.Parse(HttpContext.Current.Request.Form["rewrite"]);
                string fileSavePath = "";
                if (string.IsNullOrEmpty(url))
                {
                    if (HttpContext.Current.Request.Files.AllKeys != null)
                    {
                        // Get the uploaded document from the Files collection
                        var httpPostedFile = HttpContext.Current.Request.Files["file"];
                        if (httpPostedFile != null)
                        {
                            if (rewrite)
                            {
                                // Get the complete file path
                                fileSavePath = System.IO.Path.Combine(documentStoragePath, httpPostedFile.FileName);
                            }
                            else
                            {
                                fileSavePath = Resources.GetFreeFileName(documentStoragePath, httpPostedFile.FileName);
                            }

                            // Save the uploaded file to "UploadedFiles" folder
                            httpPostedFile.SaveAs(fileSavePath);
                        }
                    }
                }
                else
                {
                    using (WebClient client = new WebClient())
                    {
                        // get file name from the URL
                        Uri uri = new Uri(url);
                        string fileName = System.IO.Path.GetFileName(uri.LocalPath);
                        if (rewrite)
                        {
                            // Get the complete file path
                            fileSavePath = System.IO.Path.Combine(documentStoragePath, fileName);
                        }
                        else
                        {
                            fileSavePath = Resources.GetFreeFileName(documentStoragePath, fileName);
                        }
                        // Download the Web resource and save it into the current filesystem folder.
                        client.DownloadFile(url, fileSavePath);
                    }
                }
                UploadedDocumentEntity uploadedDocument = new UploadedDocumentEntity();
                uploadedDocument.guid = fileSavePath;
                return Request.CreateResponse(HttpStatusCode.OK, uploadedDocument);
            }
            catch (System.Exception ex)
            {
                // set exception message
                return Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex));
            }
        }

        /// <summary>
        /// Compare files from local storage
        /// </summary>
        /// <param name="compareRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("compare")]
        public HttpResponseMessage Compare(CompareRequest compareRequest)
        {
            try
            {
                // check formats
                if (comparisonService.CheckFiles(compareRequest))
                {
                    // compare
                    CompareResultResponse result = comparisonService.Compare(compareRequest);
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.ContractResolver = new LowercaseContractResolver();
                    string json = JsonConvert.SerializeObject(result, Formatting.Indented, settings);
                    var compareResult = JsonConvert.DeserializeObject(json);
                    return Request.CreateResponse(HttpStatusCode.OK, compareResult);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.OK, new Resources().GenerateException(new Exception("Document types are different")));
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex));
            }
        }

        /// <summary>
        /// Get result page
        /// </summary>
        /// <param name="loadResultPageRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("loadDocumentDescription")]
        public HttpResponseMessage LoadDocumentDescription(PostedDataEntity loadResultPageRequest)
        {
            try
            {
                LoadDocumentEntity document = ComparisonServiceImpl.LoadDocumentPages(loadResultPageRequest.guid,
                                                                                loadResultPageRequest.password,
                                                                                globalConfiguration.Comparison.GetPreloadResultPageCount() == 0);
                return Request.CreateResponse(HttpStatusCode.OK, document);
            }
            catch (PasswordProtectedFileException ex)
            {
                // set exception message
                return Request.CreateResponse(HttpStatusCode.Forbidden, new Resources().GenerateException(ex, loadResultPageRequest.password));
            }
            catch (Exception ex)
            {
                // set exception message
                return Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex, loadResultPageRequest.password));
            }
        }

        /// <summary>
        /// Get document page
        /// </summary>
        /// <param name="postedData">Post data</param>
        /// <returns>Document page object</returns>
        [HttpPost]
        [Route("loadDocumentPage")]
        public HttpResponseMessage LoadDocumentPage(PostedDataEntity postedData)
        {
            return Request.CreateResponse(HttpStatusCode.OK, comparisonService.LoadDocumentPage(postedData));
        }
    }
}


text:
using Swashbuckle.Swagger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Description;

namespace LCL.WebAPI.Utility
{
    public class DocumentFilter : IDocumentFilter
    {
        /// <summary>
        /// This method is for applying the filter
        /// </summary>
        /// <param name="swaggerDoc">Swagger Document</param>
        /// <param name="schemaRegistry">Schema Registry</param>
        /// <param name="apiExplorer">API Explorer</param>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            var methods = swaggerDoc.paths.Select(i => i.Value);
            List<string> tags = new List<string>();
            foreach (var method in methods)
            {
                if (method.delete != null)
                {
                    tags.AddRange(method.delete.tags);
                }

                if (method.get != null)
                {
                    tags.AddRange(method.get.tags);
                }

                if (method.put != null)
                {
                    tags.AddRange(method.put.tags);
                }

                if (method.post != null)
                {
                    tags.AddRange(method.post.tags);
                }

                if (method.patch != null)
                {
                    tags.AddRange(method.patch.tags);
                }
            }

            swaggerDoc.tags = new List<Tag>();
            foreach (var tag in tags)
            {
                swaggerDoc.tags.Add(new Tag() { name = tag, description = "This is a group of methods for " + tag });
            }
        }
    }
}