text:
#ifndef __ETL_UNORDEREDMULTIMAPTEMPLATE_H__
#define __ETL_UNORDEREDMULTIMAPTEMPLATE_H__

#include <etl/base/AAllocator.h>
#include <etl/base/UnorderedBase.h>
#include <etl/base/VectorTemplate.h>
#include <etl/etlSupport.h>

#include <algorithm>

namespace ETL_NAMESPACE {

template<class K,
         class E,
         class H = std::hash<K>,
         class KE = std::equal_to<K>>
class UnorderedMultiMap : public Detail::UnorderedBase<std::pair<const K, E>> {

  public:  // types

    using key_type = K;
    using mapped_type = E;
    using value_type = std::pair<const K, E>;

    using hasher = H;
    using key_equal = KE;

    using reference = value_type&;
    using const_reference = const value_type&;
    using pointer = value_type*;
    using const_pointer = const value_type*;

    using Base = Detail::UnorderedBase<value_type>;
    using Node = typename Base::Node;

    using iterator = typename Base::iterator;
    using const_iterator = typename Base::const_iterator;

    using size_type = typename Base::size_type;

  private:

    struct KeyHasher {
        typename Base::HashType operator()(const_reference val) {
            return hasher()(val.first);
        }
    };

  public:  // functions

    /// \name Construction, destruction, assignment
    /// \{
    UnorderedMultiMap(typename Base::BucketImpl& b, typename Base::NodeAllocator& a) :
        Base(b, a) {};

    UnorderedMultiMap& operator=(const UnorderedMultiMap& other) {
        this->clear();  // @todo this could be optimized to reuse existing elements
        this->max_load_factor(other.max_load_factor());
        this->rehash(other.bucket_count());
        ETL_ASSERT(this->empty());
        insert(other.begin(), other.end());
        return *this;
    }

    UnorderedMultiMap& operator=(UnorderedMultiMap&& other) {
        swap(other);
        return *this;
    }

    UnorderedMultiMap& operator=(std::initializer_list<value_type> initList) {
        assign(initList);
        return *this;
    }

    UnorderedMultiMap(const UnorderedMultiMap& other) = delete;
    UnorderedMultiMap(UnorderedMultiMap&& other) = delete;

    ~UnorderedMultiMap() = default;
    /// \}

    /// \name Capacity
    /// \{
    using Base::size;
    using Base::empty;
    using Base::max_size;
    /// \}

    /// \name Iterators
    /// \{
    using Base::begin;
    using Base::cbegin;
    using Base::end;
    using Base::cend;
    /// \}

    /// \name Bucket interface
    /// \{
    size_type bucket(const key_type& key) const {
        return this->bucketIx(hasher()(key));
    }
    /// \}

    /// \name Lookup
    /// \{
    using Base::count;

    iterator find(const key_type& key) {
        return this->findExact(
            hasher()(key),
            [&key](const value_type& item) { return key_equal()(key, item.first); });
    }

    const_iterator find(const key_type& key) const {
        return this->findExact(
            hasher()(key),
            [&key](const value_type& item) { return key_equal()(key, item.first); });
    }

    std::pair<iterator, iterator> equal_range(const K& key) {
        return this->findRange(
            hasher()(key),
            [&key](const value_type& item) { return key_equal()(key, item.first); });
    }

    std::pair<const_iterator, const_iterator> equal_range(const K& key) const {
        return this->findRange(
            hasher()(key),
            [&key](const value_type& item) { return key_equal()(key, item.first); });
    }

    /// \}

    /// \name Modifiers
    /// \{
    using Base::clear;
    using Base::erase;

    size_type erase(const key_type& k) {
        auto found = find(k);
        if (found != end()) {
            erase(found);
            return 1U;
        } else {
            return 0U;
        }
    }

    iterator insert(const value_type& val) {
        return emplace(val);
    }

    iterator insert(const K& k, const E& e) {
        return emplace(k, e);
    }

    template<typename InputIt>
    enable_if_t<!is_integral<InputIt>::value, void> insert(InputIt first, InputIt last) {
        while (first != last) {
            emplace(*first);
            ++first;
        }
    }

    template<typename... Args>
    iterator emplace(Args&&... args) {
        return Base::emplace(KeyHasher(), std::forward<Args>(args)...);
    }

    void swap(UnorderedMultiMap& other) {
        Base::swap(KeyHasher(), other);
    }
    /// \}

    /// \name Observers
    /// \{

    hasher hash_function() const {
        return hasher();
    }

    key_equal key_eq() const {
        return key_equal();
    }
    /// \}

  protected:

    template<typename InputIt>
    void assign(InputIt first, InputIt last) {
        this->clear();
        insert(first, last);
    }

    template<class Cont>
    void assign(const Cont& other) {
        assign(other.begin(), other.end());
    }

  private:

    friend bool operator==(const UnorderedMultiMap& lhs, const UnorderedMultiMap& rhs) {

        if (lhs.size() != rhs.size()) {
            return false;
        }
        if (lhs.empty()) {
            return true;
        }

        bool notEqual = false;
        auto lIt = lhs.begin();
        while (lIt != lhs.end() && (!notEqual)) {
            auto lEr = lhs.equal_range(lIt->first);
            auto rEr = rhs.equal_range(lIt->first);
            if (std::distance(lEr.first, lEr.second) != std::distance(rEr.first, rEr.second)) {
                notEqual = true;
            } else {
                notEqual = !std::is_permutation(lEr.first, lEr.second, rEr.first);
            }
            lIt = lEr.second;
        }

        return !notEqual;
    }

    friend bool operator!=(const UnorderedMultiMap& lhs, const UnorderedMultiMap& rhs) {
        return !(lhs == rhs);
    }

    friend void swap(UnorderedMultiMap& lhs, UnorderedMultiMap& rhs) {
        lhs.swap(rhs);
    }
};

}  // namespace ETL_NAMESPACE

#endif /* __ETL_UNORDEREDMULTIMAPTEMPLATE_H__ */


text:
package org.diirt.graphene;

import org.diirt.util.stats.Statistics;
import java.util.List;
import org.diirt.util.array.ListNumber;
import org.diirt.util.stats.Range;

/**
 *
 * @author carcassi
 */
public interface Point3DWithLabelDataset {

    public ListNumber getXValues();

    public ListNumber getYValues();

    public ListNumber getZValues();

    public List<String> getLabels();

    public Statistics getXStatistics();

    public Statistics getYStatistics();

    public Statistics getZStatistics();

    public Range getXDisplayRange();

    public Range getYDisplayRange();

    public Range getZDisplayRange();

    public int getCount();

}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Hermes::API::Mails do

  describe "#mail" do

    before do
      stub_post("/1.0/mails").with(:body => {
        :template => 'T',
        :to => "frank@email.com"
      }).to_return(:body => fixture("mail.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end

    it "requests the correct resource" do
      Hermes.mail( :template => 'T', :to => "frank@email.com")
      expect(a_post("/1.0/mails").with(:body => {:template => 'T', :to => "frank@email.com"})).to have_been_made
    end

    it "returns a Mail" do
      mail = Hermes.mail( :template => 'T', :to => "frank@email.com")
      expect(mail).to be_a Hermes::Mail
      expect(mail.id).to eq 123
    end

    it "raises error if missing params" do
      stub_post("/1.0/mails").with(body: { template: 'online_ordering_order_received' }).to_return(
        status: 400,
        body: fixture("invalid_to_param.json"),
        headers: {content_type: "application/json; charset=utf-8"})

      expect { Hermes.mail( template: 'online_ordering_order_received') }.to raise_error Hermes::Error::BadRequest

    end

  end

end


text:
using System.Reflection;
using System.Composition.Hosting.Util;
using System.Composition.Hosting.Core;
using System.Linq;
using System.Collections.Generic;
using System.Composition.Hosting.Providers.Metadata;
using Microsoft.Internal;

namespace System.Composition.Hosting.Providers.ExportFactory
{
    internal class ExportFactoryWithMetadataExportDescriptorProvider : ExportDescriptorProvider
    {
        private static readonly MethodInfo s_getLazyDefinitionsMethod =
            typeof(ExportFactoryWithMetadataExportDescriptorProvider).GetTypeInfo().GetDeclaredMethod("GetExportFactoryDescriptors");

        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
        {
            if (!contract.ContractType.GetTypeInfo().IsGenericType ||
                        contract.ContractType.GetGenericTypeDefinition() != typeof(ExportFactory<,>))
                return NoExportDescriptors;

            var ga = contract.ContractType.GenericTypeArguments;
            var gld = s_getLazyDefinitionsMethod.MakeGenericMethod(ga[0], ga[1]);
            var gldm = gld.CreateStaticDelegate<Func<CompositionContract, DependencyAccessor, object>>();
            return (ExportDescriptorPromise[])gldm(contract, definitionAccessor);
        }

        private static ExportDescriptorPromise[] GetExportFactoryDescriptors<TProduct, TMetadata>(CompositionContract exportFactoryContract, DependencyAccessor definitionAccessor)
        {
            var productContract = exportFactoryContract.ChangeType(typeof(TProduct));
            var boundaries = EmptyArray<string>.Value;

            IEnumerable<string> specifiedBoundaries;
            CompositionContract unwrapped;
            if (exportFactoryContract.TryUnwrapMetadataConstraint(Constants.SharingBoundaryImportMetadataConstraintName, out specifiedBoundaries, out unwrapped))
            {
                productContract = unwrapped.ChangeType(typeof(TProduct));
                boundaries = (specifiedBoundaries ?? EmptyArray<string>.Value).ToArray();
            }

            var metadataProvider = MetadataViewProvider.GetMetadataViewProvider<TMetadata>();

            return definitionAccessor.ResolveDependencies("product", productContract, false)
                .Select(d => new ExportDescriptorPromise(
                    exportFactoryContract,
                    typeof(ExportFactory<TProduct, TMetadata>).Name,
                    false,
                    () => new[] { d },
                    _ =>
                    {
                        var dsc = d.Target.GetDescriptor();
                        return ExportDescriptor.Create((c, o) =>
                        {
                            return new ExportFactory<TProduct, TMetadata>(() =>
                            {
                                var lifetimeContext = new LifetimeContext(c, boundaries);
                                return Tuple.Create<TProduct, Action>((TProduct)CompositionOperation.Run(lifetimeContext, dsc.Activator), lifetimeContext.Dispose);
                            },
                            metadataProvider(dsc.Metadata));
                        },
                        dsc.Metadata);
                    }))
                .ToArray();
        }
    }
}


text:
from node_visitor import NodeVisitor
import token_names as tokens
from code import Code

class InstructionGenerator(NodeVisitor):
    def __init__(self):
        self.code = Code()

    def __call__(self, tree):
        self.visit(tree)

    def visit_Program(self, node):
        # print "in visit_Program"
        self.visit(node.block)

    def visit_Block(self, node):
        # print "in visit_Block"
        for declaration in node.declarations:
            self.visit(declaration)
        self.visit(node.compound_statement)

    def visit_Variable(self, node):
        # print "in visit_Variable"
        self.code.instructions.append(('LOOKUP_AND_PUSH_VALUE', node.value))

    def visit_VariableDeclaration(self, node):
        # print "in visit_VariableDeclaration"
        pass

    def visit_FunctionDeclaration(self, node):
        # print "in visit_FunctionDeclaration"
        pass

    def visit_UnaryOperator(self, node):
        # print "in visit_UnaryOperator"
        pass

    def visit_BinaryOperator(self, node):
        # print "in visit_BinaryOperator"
        if node.op.type == tokens.PLUS:
            self.code.instructions.append(('ADD_TWO_VALUES', None))
            self.visit(node.left)
            self.visit(node.right)
        elif node.op.type == tokens.MINUS:
            self.code.instructions.append(('SUBTRACT_TWO_VALUES', None))
            self.visit(node.left)
            self.visit(node.right)
        elif node.op.type == tokens.MULTIPLY:
            self.code.instructions.append(('MULTIPLY_TWO_VALUES', None))
            self.visit(node.left)
            self.visit(node.right)
        elif node.op.type == tokens.DIVIDE:
            self.code.instructions.append(('DIVIDE_TWO_VALUES', None))
            self.visit(node.left)
            self.visit(node.right)

    def visit_Number(self, node):
        # print "in visit_Number"
        index = len(self.code.number_stack)
        self.code.instructions.append(('PUSH_VALUE', index))
        self.code.number_stack.append(node.value)
        return node.value

    def visit_Compound(self, node):
        # print "in visit_Compound"
        for child in node.children:
            self.visit(child)

    def visit_NoOp(self, node):
        # print "in visit_NoOp"
        return self.code

    def visit_Assign(self, node):
        # print "in visit_Assign"
        self.visit(node.left)
        self.visit(node.right)
        index = len(self.code.name_stack)
        name = node.left.value
        self.code.instructions.append(('ASSIGN', index))
        self.code.name_stack.append(name)

    def visit_Print(self, node):
        # print "in visit_Print"
        self.code.instructions.append(('PRINT', None))
        self.visit(node.expr)


text:
var React = require('react');
var ReactPropTypes = React.PropTypes;

var MovieResult = React.createClass({

	propTypes: {
        value: ReactPropTypes.number.isRequired,
        label: ReactPropTypes.string.isRequired
    },

	render: function() {
		return (
			<option value={this.props.value}>{this.props.label}</option>
		);
	}

});

module.exports = MovieResult;


text:
package org.apache.ignite.internal.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.ConnectorConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;

import static org.apache.ignite.IgniteSystemProperties.IGNITE_JETTY_PORT;

/**
 * Tests that client is able to connect to a grid with only default cache enabled.
 */
public class ClientDefaultCacheSelfTest extends GridCommonAbstractTest {
    /** Path to jetty config configured with SSL. */
    private static final String REST_JETTY_CFG = "modules/clients/src/test/resources/jetty/rest-jetty.xml";

    /** IP finder. */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** Host. */
    private static final String HOST = "127.0.0.1";

    /** Cached local node id. */
    private UUID locNodeId;

    /** Http port. */
    private static final int HTTP_PORT = 8081;

    /** Url address to send HTTP request. */
    private static final String TEST_URL = "http://" + HOST + ":" + HTTP_PORT + "/ignite";

    /** Used to sent request charset. */
    private static final String CHARSET = StandardCharsets.UTF_8.name();

    /** Name of node local cache. */
    private static final String LOCAL_CACHE = "local";

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        System.setProperty(IGNITE_JETTY_PORT, String.valueOf(HTTP_PORT));

        startGrid();
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        stopGrid();

        System.clearProperty(IGNITE_JETTY_PORT);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        locNodeId = grid().localNode().id();
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(gridName);

        assert cfg.getConnectorConfiguration() == null;

        ConnectorConfiguration clientCfg = new ConnectorConfiguration();

        clientCfg.setJettyPath(REST_JETTY_CFG);

        cfg.setConnectorConfiguration(clientCfg);

        TcpDiscoverySpi disco = new TcpDiscoverySpi();

        disco.setIpFinder(IP_FINDER);

        cfg.setDiscoverySpi(disco);

        CacheConfiguration cLocal = new CacheConfiguration();

        cLocal.setName(LOCAL_CACHE);

        cLocal.setCacheMode(CacheMode.LOCAL);

        cLocal.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);

        cfg.setCacheConfiguration(defaultCacheConfiguration(), cLocal);

        return cfg;
    }

    /**
     * Builds list of connection strings with few different ports.
     * Used to avoid possible failures in case of port range active.
     *
     * @param startPort Port to start list from.
     * @return List of client connection strings.
     */
    private Collection<String> getServerList(int startPort) {
        Collection<String> srvs = new ArrayList<>();

        for (int i = startPort; i < startPort + 10; i++)
            srvs.add(HOST + ":" + i);

        return srvs;
    }

    /*
     * Send HTTP request to Jetty server of node and process result.
     *
     * @param query Send query parameters.
     * @return Processed response string.
     */
    private String sendHttp(String query) {
        String res = "No result";

        try {
            URLConnection connection = new URL(TEST_URL + "?" + query).openConnection();

            connection.setRequestProperty("Accept-Charset", CHARSET);

            BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            res = r.readLine();

            r.close();
        }
        catch (IOException e) {
            error("Failed to send HTTP request: " + TEST_URL + "?" + query, e);
        }

        // Cut node id from response.
        return res.substring(res.indexOf("\"response\""));
    }

    /**
     * Json format string in cache should not transform to Json object on get request.
     */
    public void testSkipString2JsonTransformation() {
        // Put to cache JSON format string value.
        assertEquals("Incorrect query response", "\"response\":true,\"sessionToken\":\"\",\"successStatus\":0}",
            sendHttp("cmd=put&cacheName=" + LOCAL_CACHE +
                "&key=a&val=%7B%22v%22%3A%22my%20Value%22%2C%22t%22%3A1422559650154%7D"));

        // Escape '\' symbols disappear from response string on transformation to JSON object.
        assertEquals(
            "Incorrect query response",
            "\"response\":\"{\\\"v\\\":\\\"my Value\\\",\\\"t\\\":1422559650154}\"," +
                "\"sessionToken\":\"\",\"successStatus\":0}",
            sendHttp("cmd=get&cacheName=" + LOCAL_CACHE + "&key=a"));
    }
}


text:
package com.zcc.cryptex.lib;

/**
 * Created by Hengyun on 16/4/15.
 */
public class Initializer {
}


text:
package org.drools.planner.config.heuristic.selector;

import org.drools.planner.config.heuristic.selector.entity.EntitySelectorConfig;
import org.drools.planner.config.heuristic.selector.move.MoveSelectorConfig;
import org.drools.planner.config.heuristic.selector.value.ValueSelectorConfig;

/**
 * General superclass for {@link MoveSelectorConfig}, {@link EntitySelectorConfig} and {@link ValueSelectorConfig}.
 */
public abstract class SelectorConfig {

    // ************************************************************************
    // Builder methods
    // ************************************************************************

    protected void inherit(SelectorConfig inheritedConfig) {
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "()";
    }

}


text:
package org.keycloak.authentication.authenticators.console;

import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.ConsoleDisplayMode;

import javax.ws.rs.core.MultivaluedMap;

public final class ConsolePasswordAuthenticator extends ConsoleUsernamePasswordAuthenticator {

    public static ConsolePasswordAuthenticator SINGLETON = new ConsolePasswordAuthenticator();

    @Override
    protected ConsoleDisplayMode challenge(AuthenticationFlowContext context) {
        return ConsoleDisplayMode.challenge(context)
                .header()
                .param("password")
                .label("console-password")
                .mask(true)
                .challenge();
    }

    @Override
    public void action(AuthenticationFlowContext context) {
        MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
        if (!validatePassword(context, context.getUser(), formData, false)) {
            return;
        }
        context.success();
    }

    @Override
    public boolean requiresUser() {
        return true;
    }

}


text:
import unicodecsv as csv
from nltk import wordpunct_tokenize

class CorpusReader(object):
    """
    Normally would extend nltk.corpus.reader.api.CorpusReader but that
    seems like a bit much for now- on other corpora you might do this.

    In this case, the job of this class to yield text, label pairs for
    the annotated corpus - which hopefully won't be too tough to do!
    """

    def __init__(self, path):
        pass

    def rows(self, categories=None):
        """
        Does the work of reading the CSV file for each row.
        """
        pass

    def categories(self):
        """
        Finds the categories in the CSV file.
        """
        pass

    def words(self, categories=None):
        """
        Iterates through all the words in the corpus
        """
        pass

    def vocab(self, categories=None):
        """
        returns the vocabulary, the set of unique words
        """
        pass

    def count(self, categories=None):
        """
        Returns the word count of the corpus
        """
        pass

    def metrics(self, categories=None):
        """
        Returns statistics about the corpus like word count, vocab count,
        lexical diversity for the given categories requested.
        """
        pass

    def pprint(self, categories=None):
        """
        Pretty prints the metrics of the corpus
        """
        pass


text:
layout: post
title: 'Reunión #3'
date: '2011-01-20T12:03:00-04:30'
tags:
- reunión
tumblr_url: http://ruby.org.ve/post/2843190323/reunion-3
---
¿Listos para nuestra primera reunión del año? Ya las hallacas, el pan de jamón y el ponche crema quedaron atrás así que vamos a mover esas neuronas con algo de código **Ruby** para deshacer los excesos navideños ;)

La agenda está completamente abierta, es decir aún no tenemos propuestas de ponencias, así que anímense, y lancen sus propuestas en el [Grupo de Discusión](https://groups.google.com/forum/#!forum/rubyve).

Recuerden que sólo hacen falta inquietud de compartir sus experiencias con **Ruby**, **Rails** o cualquier otro tema relacionado, y las ganas de preparar un poco su tema para los que estaremos ahí reunidos, todos aprendiendo. No hacen falta certificaciones, 15 años de experiencia ni títulos universitarios ;)

**Fecha**: Jueves 27 de Enero de 2011.

**Hora**: 6 a 8 pm.

**Donde**: Softrain - Servicios Educativos Av. Libertador, Calle Alameda, Torre Exa, Piso 2, El Rosal, Chacao Caracas 1060 Venezuela

Por favor regístrense aquí: [http://rubyve.eventbrite.com](http://rubyve.eventbrite.com)

Gracias a los amigos de [Softrain](http://www.softrain.com.ve/) ([@softrain_vzla](https://twitter.com/softrain_vzla)) por facilitarnos de nuevo la sede para esta reunión.


text:
#include <ztest.h>
#include <kernel.h>
#include <pthread.h>
#include <semaphore.h>

#define N_THR_E 3
#define N_THR_T 4
#define BOUNCES 64
#define STACKS (1024 + CONFIG_TEST_EXTRA_STACKSIZE)
#define THREAD_PRIORITY 3
#define ONE_SECOND 1

/* Macros to test invalid states */
#define PTHREAD_CANCEL_INVALID -1
#define SCHED_INVALID -1
#define PRIO_INVALID -1

K_THREAD_STACK_ARRAY_DEFINE(stack_e, N_THR_E, STACKS);
K_THREAD_STACK_ARRAY_DEFINE(stack_t, N_THR_T, STACKS);

void *thread_top_exec(void *p1);
void *thread_top_term(void *p1);

PTHREAD_MUTEX_DEFINE(lock);

PTHREAD_COND_DEFINE(cvar0);

PTHREAD_COND_DEFINE(cvar1);

PTHREAD_BARRIER_DEFINE(barrier, N_THR_E);

sem_t main_sem;

static int bounce_failed;
static int bounce_done[N_THR_E];

static int curr_bounce_thread;

static int barrier_failed;
static int barrier_done[N_THR_E];

/* First phase bounces execution between two threads using a condition
 * variable, continuously testing that no other thread is mucking with
 * the protected state.  This ends with all threads going back to
 * sleep on the condition variable and being woken by main() for the
 * second phase.
 *
 * Second phase simply lines up all the threads on a barrier, verifies
 * that none run until the last one enters, and that all run after the
 * exit.
 *
 * Test success is signaled to main() using a traditional semaphore.
 */

void *thread_top_exec(void *p1)
{
	int i, j, id = (int) p1;
	int policy;
	struct sched_param schedparam;

	pthread_getschedparam(pthread_self(), &policy, &schedparam);
	printk("Thread %d starting with scheduling policy %d & priority %d\n",
		 id, policy, schedparam.priority);
	/* Try a double-lock here to exercise the failing case of
	 * trylock.  We don't support RECURSIVE locks, so this is
	 * guaranteed to fail.
	 */
	pthread_mutex_lock(&lock);

	if (!pthread_mutex_trylock(&lock)) {
		printk("pthread_mutex_trylock inexplicably succeeded\n");
		bounce_failed = 1;
	}

	pthread_mutex_unlock(&lock);

	for (i = 0; i < BOUNCES; i++) {

		pthread_mutex_lock(&lock);

		/* Wait for the current owner to signal us, unless we
		 * are the very first thread, in which case we need to
		 * wait a bit to be sure the other threads get
		 * scheduled and wait on cvar0.
		 */
		if (!(id == 0 && i == 0)) {
			pthread_cond_wait(&cvar0, &lock);
		} else {
			pthread_mutex_unlock(&lock);
			usleep(500 * USEC_PER_MSEC);
			pthread_mutex_lock(&lock);
		}

		/* Claim ownership, then try really hard to give someone
		 * else a shot at hitting this if they are racing.
		 */
		curr_bounce_thread = id;
		for (j = 0; j < 1000; j++) {
			if (curr_bounce_thread != id) {
				printk("Racing bounce threads\n");
				bounce_failed = 1;
				sem_post(&main_sem);
				pthread_mutex_unlock(&lock);
				return NULL;
			}
			sched_yield();
		}

		/* Next one's turn, go back to the top and wait.  */
		pthread_cond_signal(&cvar0);
		pthread_mutex_unlock(&lock);
	}

	/* Signal we are complete to main(), then let it wake us up.  Note
	 * that we are using the same mutex with both cvar0 and cvar1,
	 * which is non-standard but kosher per POSIX (and it works fine
	 * in our implementation
	 */
	pthread_mutex_lock(&lock);
	bounce_done[id] = 1;
	sem_post(&main_sem);
	pthread_cond_wait(&cvar1, &lock);
	pthread_mutex_unlock(&lock);

	/* Now just wait on the barrier.  Make sure no one else finished
	 * before we wait on it, then signal that we're done
	 */
	for (i = 0; i < N_THR_E; i++) {
		if (barrier_done[i]) {
			printk("Barrier exited early\n");
			barrier_failed = 1;
			sem_post(&main_sem);
		}
	}
	pthread_barrier_wait(&barrier);
	barrier_done[id] = 1;
	sem_post(&main_sem);
	pthread_exit(p1);

	return NULL;
}

int bounce_test_done(void)
{
	int i;

	if (bounce_failed) {
		return 1;
	}

	for (i = 0; i < N_THR_E; i++) {
		if (!bounce_done[i]) {
			return 0;
		}
	}

	return 1;
}

int barrier_test_done(void)
{
	int i;

	if (barrier_failed) {
		return 1;
	}

	for (i = 0; i < N_THR_E; i++) {
		if (!barrier_done[i]) {
			return 0;
		}
	}

	return 1;
}

void *thread_top_term(void *p1)
{
	pthread_t self;
	int oldstate, policy, ret;
	int val = (u32_t) p1;
	struct sched_param param, getschedparam;

	param.priority = N_THR_T - (s32_t) p1;

	self = pthread_self();

	/* Change priority of thread */
	zassert_false(pthread_setschedparam(self, SCHED_RR, &param),
		      "Unable to set thread priority!");

	zassert_false(pthread_getschedparam(self, &policy, &getschedparam),
			"Unable to get thread priority!");

	printk("Thread %d starting with a priority of %d\n", (s32_t) p1,
			getschedparam.priority);

	if (val % 2) {
		ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
		zassert_false(ret, "Unable to set cancel state!");
	}

	if (val >= 2) {
		ret = pthread_detach(self);
		if (val == 2) {
			zassert_equal(ret, EINVAL, "re-detached thread!");
		}
	}

	printk("Cancelling thread %d\n", (s32_t) p1);
	pthread_cancel(self);
	printk("Thread %d could not be cancelled\n", (s32_t) p1);
	sleep(ONE_SECOND);
	pthread_exit(p1);
	return NULL;
}

void test_posix_pthread_execution(void)
{
	int i, ret, min_prio, max_prio;
	int dstate, policy;
	pthread_attr_t attr[N_THR_E] = {};
	struct sched_param schedparam, getschedparam;
	pthread_t newthread[N_THR_E];
	int schedpolicy = SCHED_FIFO;
	void *retval, *stackaddr;
	size_t stacksize;

	sem_init(&main_sem, 0, 1);
	schedparam.priority = CONFIG_NUM_COOP_PRIORITIES - 1;
	min_prio = sched_get_priority_min(schedpolicy);
	max_prio = sched_get_priority_max(schedpolicy);

	ret = (min_prio < 0 || max_prio < 0 ||
			schedparam.priority < min_prio ||
			schedparam.priority > max_prio);

	/* TESTPOINT: Check if scheduling priority is valid */
	zassert_false(ret,
			"Scheduling priority outside valid priority range");

	/* TESTPOINTS: Try setting attributes before init */
	ret = pthread_attr_setschedparam(&attr[0], &schedparam);
	zassert_equal(ret, EINVAL, "uninitialized attr set!");

	ret = pthread_attr_setdetachstate(&attr[0], PTHREAD_CREATE_JOINABLE);
	zassert_equal(ret, EINVAL, "uninitialized attr set!");

	ret = pthread_attr_setschedpolicy(&attr[0], schedpolicy);
	zassert_equal(ret, EINVAL, "uninitialized attr set!");

	/* TESTPOINT: Try setting attribute with empty stack */
	ret = pthread_attr_setstack(&attr[0], 0, STACKS);
	zassert_equal(ret, EACCES, "empty stack set!");

	/* TESTPOINTS: Try getting attributes before init */
	ret = pthread_attr_getschedparam(&attr[0], &getschedparam);
	zassert_equal(ret, EINVAL, "uninitialized attr retrieved!");

	ret = pthread_attr_getdetachstate(&attr[0], &dstate);
	zassert_equal(ret, EINVAL, "uninitialized attr retrieved!");

	ret = pthread_attr_getschedpolicy(&attr[0], &policy);
	zassert_equal(ret, EINVAL, "uninitialized attr retrieved!");

	ret = pthread_attr_getstack(&attr[0], &stackaddr, &stacksize);
	zassert_equal(ret, EINVAL, "uninitialized attr retrieved!");

	ret = pthread_attr_getstacksize(&attr[0], &stacksize);
	zassert_equal(ret, EINVAL, "uninitialized attr retrieved!");

	/* TESTPOINT: Try destroying attr before init */
	ret = pthread_attr_destroy(&attr[0]);
	zassert_equal(ret, EINVAL, "uninitialized attr destroyed!");

	/* TESTPOINT: Try creating thread before attr init */
	ret = pthread_create(&newthread[0], &attr[0],
				thread_top_exec, NULL);
	zassert_equal(ret, EINVAL, "thread created before attr init!");

	for (i = 0; i < N_THR_E; i++) {
		ret = pthread_attr_init(&attr[i]);
		if (ret != 0) {
			zassert_false(pthread_attr_destroy(&attr[i]),
				      "Unable to destroy pthread object attrib");
			zassert_false(pthread_attr_init(&attr[i]),
				      "Unable to create pthread object attrib");
		}

		/* TESTPOINTS: Retrieve set stack attributes and compare */
		pthread_attr_setstack(&attr[i], &stack_e[i][0], STACKS);
		pthread_attr_getstack(&attr[i], &stackaddr, &stacksize);
		zassert_equal_ptr(attr[i].stack, stackaddr,
				"stack attribute addresses do not match!");
		zassert_equal(STACKS, stacksize, "stack sizes do not match!");

		pthread_attr_getstacksize(&attr[i], &stacksize);
		zassert_equal(STACKS, stacksize, "stack sizes do not match!");

		pthread_attr_setschedpolicy(&attr[i], schedpolicy);
		pthread_attr_getschedpolicy(&attr[i], &policy);
		zassert_equal(schedpolicy, policy,
				"scheduling policies do not match!");

		pthread_attr_setschedparam(&attr[i], &schedparam);
		pthread_attr_getschedparam(&attr[i], &getschedparam);
		zassert_equal(schedparam.priority, getschedparam.priority,
				"scheduling priorities do not match!");

		ret = pthread_create(&newthread[i], &attr[i], thread_top_exec,
				(void *)i);

		/* TESTPOINT: Check if thread is created successfully */
		zassert_false(ret, "Number of threads exceed max limit");
	}

	while (!bounce_test_done()) {
		sem_wait(&main_sem);
	}

	/* TESTPOINT: Check if bounce test passes */
	zassert_false(bounce_failed, "Bounce test failed");

	printk("Bounce test OK\n");

	/* Wake up the worker threads */
	pthread_mutex_lock(&lock);
	pthread_cond_broadcast(&cvar1);
	pthread_mutex_unlock(&lock);

	while (!barrier_test_done()) {
		sem_wait(&main_sem);
	}

	/* TESTPOINT: Check if barrier test passes */
	zassert_false(barrier_failed, "Barrier test failed");

	for (i = 0; i < N_THR_E; i++) {
		pthread_join(newthread[i], &retval);
	}

	printk("Barrier test OK\n");
}

void test_posix_pthread_termination(void)
{
	s32_t i, ret;
	int oldstate, policy;
	pthread_attr_t attr[N_THR_T];
	struct sched_param schedparam;
	pthread_t newthread[N_THR_T];
	void *retval;

	/* Creating 4 threads with lowest application priority */
	for (i = 0; i < N_THR_T; i++) {
		ret = pthread_attr_init(&attr[i]);
		if (ret != 0) {
			zassert_false(pthread_attr_destroy(&attr[i]),
				      "Unable to destroy pthread object attrib");
			zassert_false(pthread_attr_init(&attr[i]),
				      "Unable to create pthread object attrib");
		}

		if (i == 2) {
			pthread_attr_setdetachstate(&attr[i],
						    PTHREAD_CREATE_DETACHED);
		}

		schedparam.priority = 2;
		pthread_attr_setschedparam(&attr[i], &schedparam);
		pthread_attr_setstack(&attr[i], &stack_t[i][0], STACKS);
		ret = pthread_create(&newthread[i], &attr[i], thread_top_term,
				     (void *)i);

		zassert_false(ret, "Not enough space to create new thread");
	}

	/* TESTPOINT: Try setting invalid cancel state to current thread */
	ret = pthread_setcancelstate(PTHREAD_CANCEL_INVALID, &oldstate);
	zassert_equal(ret, EINVAL, "invalid cancel state set!");

	/* TESTPOINT: Try setting invalid policy */
	ret = pthread_setschedparam(newthread[0], SCHED_INVALID, &schedparam);
	zassert_equal(ret, EINVAL, "invalid policy set!");

	/* TESTPOINT: Try setting invalid priority */
	schedparam.priority = PRIO_INVALID;
	ret = pthread_setschedparam(newthread[0], SCHED_RR, &schedparam);
	zassert_equal(ret, EINVAL, "invalid priority set!");

	for (i = 0; i < N_THR_T; i++) {
		pthread_join(newthread[i], &retval);
	}

	/* TESTPOINT: Test for deadlock */
	ret = pthread_join(pthread_self(), &retval);
	zassert_equal(ret, EDEADLK, "thread joined with self inexplicably!");

	/* TESTPOINT: Try canceling a terminated thread */
	ret = pthread_cancel(newthread[N_THR_T/2]);
	zassert_equal(ret, ESRCH, "cancelled a terminated thread!");

	/* TESTPOINT: Try getting scheduling info from terminated thread */
	ret = pthread_getschedparam(newthread[N_THR_T/2], &policy, &schedparam);
	zassert_equal(ret, ESRCH, "got attr from terminated thread!");
}


text:
draw() {
    if (!isVisible()) return; //se não estiver visível não tem porque desenhar
    ...
}

bool saque(int valor) {
    if (saldo - valor + limite < 0) return false;
    ...
}

T getElement(int index) {
    if (index >= this.length) throw new OutOfBounds();
    ...
}

T join(T a, T b) {
    if (a == null) return b; //não precisa fazer a operação se o outro não existe
    if (b == null) return a;
    ...
}

//https://pt.stackoverflow.com/q/455667/101


text:
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

namespace EventStore.ClientAPI
{
    /// <summary>
    /// Represents the reason subscription drop happened
    /// </summary>
    public enum SubscriptionDropReason
    {
        /// <summary>
        /// Subscription dropped because the client called Close.
        /// </summary>
        UserInitiated,
        /// <summary>
        /// Subscription dropped because the client is not authenticated.
        /// </summary>
        NotAuthenticated,
        /// <summary>
        /// Subscription dropped because access to the stream was denied.
        /// </summary>
        AccessDenied,
        /// <summary>
        /// Subscription dropped because of an error in the subscription phase.
        /// </summary>
        SubscribingError,
        /// <summary>
        /// Subscription dropped because of a server error.
        /// </summary>
        ServerError,
        /// <summary>
        /// Subscription dropped because the connection was closed.
        /// </summary>
        ConnectionClosed,

        /// <summary>
        /// Subscription dropped because of an error during the catch-up phase.
        /// </summary>
        CatchUpError,
        /// <summary>
        /// Subscription dropped because it's queue overflowed.
        /// </summary>
        ProcessingQueueOverflow,
        /// <summary>
        /// Subscription dropped because an exception was thrown by a handler.
        /// </summary>
        EventHandlerException,

        /// <summary>
        /// Subscription was dropped for an unknown reason.
        /// </summary>
        Unknown = 100
    }
}


text:
/**
 *
 */
package org.corpus_tools.atomic.tagset;

import java.io.IOException;

import org.corpus_tools.atomic.tagset.api.TagsetValue;
import org.corpus_tools.atomic.tagset.impl.JavaTagsetValueImpl;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * // TODO Add description
 *
 * @author Stephan Druskat <[mail@sdruskat.net](mailto:mail@sdruskat.net)>
 *
 */
public class TagsetValueDeserializer extends JsonDeserializer<TagsetValue> {

	@Override
	public TagsetValue deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectMapper mapper = (ObjectMapper) p.getCodec();
        ObjectNode root = mapper.readTree(p);
        return mapper.readValue(root.toString(), JavaTagsetValueImpl.class);
	}

}


text:
@interface NSString (Category)

//将NSString转化成标准日期NSDate
- (NSDate *)standDate;

//base64转成UIImage
- (UIImage *)base64ToImage;

- (NSAttributedString *)attributedSubString1:(NSString *)string1 font1:(UIFont *)font1 color1:(UIColor *)color1 subString2:(NSString *)string2 font2:(UIFont *)font2 color2:(UIColor *)color2;

- (NSAttributedString *)attributedSubString1:(NSString *)string1 font1:(UIFont *)font1 color1:(UIColor *)color1 udlin1:(BOOL)unlin1 subString2:(NSString *)string2 font2:(UIFont *)font2 color2:(UIColor *)color2 udlin2:(BOOL)unlin2;

- (NSAttributedString *)attributedSubString:(NSString *)string font:(UIFont *)font color:(UIColor *)color udline:(BOOL)unline;

@end


text:
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <xi:include href="admin.html" />

    <title>Custom Fields Admin</title>

Manage Custom Fields

    <form py:if="cf_display=='detail'" class="mod" id="addcf" method="POST">
      <fieldset>
        <legend>Modify Custom Field:</legend>

          Name (cannot modify): ${cfield.name}

        <input name="name" value="${cfield.name}" type="hidden" />
        <input name="order" value="${cfield.order}" type="hidden" />

          Type:

            <select name="type" id="type">
              <option py:for="value in cfstd_types"
                  value="${value}"
                  selected="${cfield.type==value and 'selected' or None}">
                ${value.capitalize()}</option>
              <option py:for="name, label, provider in cfextra_types"
                      value="$name"
                      selected="${cfield.type == name and 'selected' or None}">$label</option>
            </select>

          Label:

            <input type="text" name="label" value="${cfield.label}" />

          Default value
                  (regular text for Text, Textarea, Radio or Select):

            <input type="text" name="value" value="${cfield.value}" />

          Format (Text or Textarea):

            <select name="format" id="format">
              <option py:for="format in ['plain', 'wiki']" value="${format}"
                  selected="${cfield.format==format and 'selected' or None}">
                ${format.capitalize()}</option>
            </select>

          <fieldset class="iefix">

              Options for Radio or Select
                  (for Select, empty first line makes field optional):

              <textarea id="options" name="options"
                        rows="5" cols="30">${cfield.options}</textarea>

          </fieldset>

          Size of Textarea for entry (Textarea only):

            Columns: <input type="text" name="cols" id="cols" size="5" value="${cfield.cols}" />

            Rows: <input type="text" size="5" name="rows" id="rows" value="${cfield.rows}" />

        <py:for each="name, label, provider in cfextra_types">

$content

        </py:for>

          <input type="submit" name="cancel" value="${_('Cancel')}" />
          <input type="submit" name="save" value="${_('Save')}" />

      </fieldset>
    </form>

    <form py:if="cf_display=='list'" class="addnew" id="addcf" method="POST">
      <fieldset>
        <legend>Add Custom Field:</legend>

          Name:

            <input type="text" name="name" id="name" />

          Type:

            <select name="type" id="type">
              <option py:for="value in cfstd_types"
                  value="${value}">${value.capitalize()}</option>
              <option py:for="name, label, provider in cfextra_types"
                      value="$name">$label</option>
            </select>

          Label:

            <input type="text" name="label" id="label" />

          Default value:

            <input type="text" name="value" id="value" />

          Format:

            <select name="format" id="format">
              <option py:for="format in ['plain', 'wiki']"
                  value="${format}">${format.capitalize()}</option>
            </select>

          <fieldset class="iefix">
            Options:

              <textarea id="options" name="options"
                        rows="4" cols="17"></textarea>

          </fieldset>

          Size of Textarea:

            Cols: <input type="text" name="cols" id="cols" size="2" />

            Rows: <input type="text" size="2" name="rows" id="rows" />

        <py:for each="name, label, provider in cfextra_types">

$content

        </py:for>

          <input type="submit" name="add" value="${_('Add')}" />

      </fieldset>
    </form>

        No Custom Fields defined for this project.

      <form py:if="len(cfields)" method="POST">

              Name
              Type
              Label
              Order

              <input type="checkbox" name="sel"
                value="${cf.name}"/>

              ${cf.name}
              ${cf.type}
              ${cf.label}

                <select name="order_${cf.name}" py:with="count = len(cfields)">
                  <option py:for="num in range(1, count+1)"
                      selected="${num==cf.order and 'selected' or None}">
                      ${num}
                  </option>

                  <py:if test="cf.order not in range(1, count+1)">
                    <option disabled="disabled">—</option>
                    <option title="Currently outside regular range"
                            selected="selected">${cf.order}</option>
                  </py:if>
                </select>

          <input type="submit" name="remove"
                 value="${_('Remove selected items')}" />
          <input type="submit" name="apply" value="${_('Apply changes')}" />

      </form>


text:
Fork of original Skadi with some functions reworked:
Allows you to comfortably watch Twitch channels via streamlink / VLC (or any videoplayer compatible with streamlink).
No browser needed - you only watch plain stream in video player.

## Download
see https://github.com/piddubnyi/skadi-simple/releases

## Required software
* ~~[Java 1.8u60+]~~[Any Java version](https://www.java.com/download/)
* [streamlink](https://github.com/streamlink/streamlink/releases)
* ~~[Chrome]~~(https://www.google.com/chrome/)
* [VLC](https://www.videolan.org/vlc/) (or any videoplayer compatible with streamlink, see  [streamlink documentation](http://docs.streamlink.io/players.html))

Make sure to keep streamlink and Java up to date.

## Features
* ~~version check / update download~~
* import followed channels
* channel filtering
* streams can be opened in all available stream qualities
* ~~chats are opened in chrome/chromium~~ no chat, Just watch your stream.
* channel detail pane (double click on a channel or click the 'i' button) showing the channel panels, preview, stats, sub-emotes and a viewer graph
* light and dark theme
* table and grid view
* logging
* ~~notifications if a channel goes live~~ Suitable for work, nothing bothers you
* minimize to tray (https://javafx-jira.kenai.com/browse/RT-17503 uses old AWT API)
* drag and drop channel names/urls do add
* channel auto updated every 60s / force refresh
* twitch-auth and followed sync between Skadi and Twitch

### TODO
If you have a feature request or found a bug, create a new issue (and include the log file if appropriate).

## Setup
If Skadi fails to open streams or chats with the default configuration values (see log file or the status bar), you might need to change the paths to streamlink in the settings dialog. Often the problem isn't related to Skadi but to streamlink, so you might want to check if streamlink is setup correctly first.
The log and config are in ./.skadi
There is a button to open the log in the settings dialog.

## Usage
launch Skadi via `java -jar skadi.jar` if a double click on the jar does not work.

## Building
Skadi uses maven as build tool.
use `mvn package` to build Skadi, result can be found at `target/Skadi-xyz.jar`