text:
package org.apache.ignite.internal.processors.cache.consistency;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteEvents;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.events.CacheConsistencyViolationEvent;
import org.apache.ignite.events.Event;
import org.apache.ignite.events.EventType;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheObjectImpl;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.processors.cache.GridCacheEntryEx;
import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersionManager;
import org.apache.ignite.internal.processors.dr.GridDrType;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Before;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
import static org.apache.ignite.events.EventType.EVT_CONSISTENCY_VIOLATION;

/**
 *
 */
public abstract class AbstractReadRepairTest extends GridCommonAbstractTest {
    /** Events. */
    private static final ConcurrentLinkedDeque<CacheConsistencyViolationEvent> evtDeq = new ConcurrentLinkedDeque<>();

    /** Key. */
    protected static int iterableKey;

    /** Backups count. */
    protected Integer backupsCount() {
        return 3;
    }

    /** Cache mode. */
    protected CacheMode cacheMode() {
        return PARTITIONED;
    }

    /** Atomicy mode. */
    protected CacheAtomicityMode atomicyMode() {
        return TRANSACTIONAL;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        Ignite ignite = startGrids(7); // Server nodes.

        grid(0).getOrCreateCache(cacheConfiguration());

        startClientGrid(G.allGrids().size() + 1); // Client node 1.
        startClientGrid(G.allGrids().size() + 1); // Client node 2.

        final IgniteEvents evts = ignite.events();

        evts.remoteListen(null,
            (IgnitePredicate<Event>)e -> {
                assert e instanceof CacheConsistencyViolationEvent;

                evtDeq.add((CacheConsistencyViolationEvent)e);

                return true;
            },
            EVT_CONSISTENCY_VIOLATION);

        awaitPartitionMapExchange();
    }

    /**
     *
     */
    @Before
    public void before() {
        evtDeq.clear();
    }

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

        log.info("Checked " + iterableKey + " keys");

        stopAllGrids();
    }

    /**
     *
     */
    protected CacheConfiguration<Integer, Integer> cacheConfiguration() {
        CacheConfiguration<Integer, Integer> cfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);

        cfg.setWriteSynchronizationMode(FULL_SYNC);
        cfg.setCacheMode(cacheMode());
        cfg.setAtomicityMode(atomicyMode());
        cfg.setBackups(backupsCount());

        return cfg;
    }

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

        cfg.setIncludeEventTypes(EventType.EVTS_ALL);

        return cfg;
    }

    /**
     *
     */
    protected void checkEventMissed() {
        assertTrue(evtDeq.isEmpty());
    }

    /**
     *
     */
    protected void checkEvent(ReadRepairData data, boolean checkFixed) {
        Map<Object, Map<ClusterNode, CacheConsistencyViolationEvent.EntryInfo>> entries = new HashMap<>();

        while (!entries.keySet().equals(data.data.keySet())) {
            if (!evtDeq.isEmpty()) {
                CacheConsistencyViolationEvent evt = evtDeq.remove();

                entries.putAll(evt.getEntries()); // Optimistic and read committed transactions produce per key fixes.
            }
        }

        int fixedCnt = 0;

        for (Map.Entry<Integer, InconsistentMapping> mapping : data.data.entrySet()) {
            Integer key = mapping.getKey();
            Integer latest = mapping.getValue().latest;

            Object fixedVal = null;

            Map<ClusterNode, CacheConsistencyViolationEvent.EntryInfo> values = entries.get(key);

            if (values != null)
                for (Map.Entry<ClusterNode, CacheConsistencyViolationEvent.EntryInfo> infoEntry : values.entrySet()) {
                    ClusterNode node = infoEntry.getKey();
                    CacheConsistencyViolationEvent.EntryInfo info = infoEntry.getValue();

                    if (info.isCorrect()) {
                        assertNull(fixedVal);

                        fixedVal = info.getValue();

                        fixedCnt++;
                    }

                    if (info.isPrimary())
                        assertEquals(node, primaryNode(key, DEFAULT_CACHE_NAME).cluster().localNode());
                }

            assertEquals(checkFixed ? latest : null, fixedVal);
        }

        assertEquals(checkFixed ? data.data.size() : 0, fixedCnt);

        assertTrue(evtDeq.isEmpty());
    }

    /**
     *
     */
    protected void prepareAndCheck(
        Ignite initiator,
        Integer cnt,
        boolean raw,
        boolean async,
        Consumer<ReadRepairData> c)
        throws Exception {
        IgniteCache<Integer, Integer> cache = initiator.getOrCreateCache(DEFAULT_CACHE_NAME);

        for (int i = 0; i < ThreadLocalRandom.current().nextInt(1, 10); i++) {
            Map<Integer, InconsistentMapping> results = new HashMap<>();

            for (int j = 0; j < cnt; j++) {
                InconsistentMapping res = setDifferentValuesForSameKey(++iterableKey);

                results.put(iterableKey, res);
            }

            for (Ignite node : G.allGrids()) { // Check that cache filled properly.
                Map<Integer, Integer> all =
                    node.<Integer, Integer>getOrCreateCache(DEFAULT_CACHE_NAME).getAll(results.keySet());

                for (Map.Entry<Integer, Integer> entry : all.entrySet()) {
                    Integer key = entry.getKey();
                    Integer val = entry.getValue();

                    Integer exp = results.get(key).mapping.get(node); // Should read from itself (backup or primary).

                    if (exp == null)
                        exp = results.get(key).primary; // Should read from primary (not a partition owner).

                    assertEquals(exp, val);
                }
            }

            c.accept(new ReadRepairData(cache, results, raw, async));
        }
    }

    /**
     *
     */
    private InconsistentMapping setDifferentValuesForSameKey(
        int key) throws Exception {
        List<Ignite> nodes = new ArrayList<>();
        Map<Ignite, Integer> mapping = new HashMap<>();

        Ignite primary = primaryNode(key, DEFAULT_CACHE_NAME);

        if (ThreadLocalRandom.current().nextBoolean()) { // Reversed order.
            nodes.addAll(backupNodes(key, DEFAULT_CACHE_NAME));
            nodes.add(primary);
        }
        else {
            nodes.add(primary);
            nodes.addAll(backupNodes(key, DEFAULT_CACHE_NAME));
        }

        if (ThreadLocalRandom.current().nextBoolean()) // Random order.
            Collections.shuffle(nodes);

        GridCacheVersionManager mgr =
            ((GridCacheAdapter)(grid(1)).cachex(DEFAULT_CACHE_NAME).cache()).context().shared().versions();

        int val = 0;
        int primVal = -1;

        for (Ignite node : nodes) {
            IgniteInternalCache cache = ((IgniteEx)node).cachex(DEFAULT_CACHE_NAME);

            GridCacheAdapter adapter = ((GridCacheAdapter)cache.cache());

            GridCacheEntryEx entry = adapter.entryEx(key);

            boolean init = entry.initialValue(
                new CacheObjectImpl(++val, null), // Incremental value.
                mgr.next(entry.context().kernalContext().discovery().topologyVersion()), // Incremental version.
                0,
                0,
                false,
                AffinityTopologyVersion.NONE,
                GridDrType.DR_NONE,
                false,
                false);

            assertTrue("iterableKey " + key + " already inited", init);

            mapping.put(node, val);

            if (node.equals(primary))
                primVal = val;
        }

        assertEquals(nodes.size(), new HashSet<>(mapping.values()).size()); // Each node have unique value.

        assertTrue(primVal != -1); // Primary value set.

        return new InconsistentMapping(mapping, primVal, val);
    }

    /**
     *
     */
    protected static final class ReadRepairData {
        /** Initiator's cache. */
        IgniteCache<Integer, Integer> cache;

        /** Generated data across topology per key mapping. */
        Map<Integer, InconsistentMapping> data;

        /** Raw read flag. True means required GetEntry() instead of get(). */
        boolean raw;

        /** Async read flag. */
        boolean async;

        /**
         *
         */
        public ReadRepairData(
            IgniteCache<Integer, Integer> cache,
            Map<Integer, InconsistentMapping> data,
            boolean raw,
            boolean async) {
            this.cache = cache;
            this.data = new HashMap<>(data);
            this.raw = raw;
            this.async = async;
        }
    }

    /**
     *
     */
    protected static final class InconsistentMapping {
        /** Value per node. */
        Map<Ignite, Integer> mapping;

        /** Primary node's value. */
        Integer primary;

        /** Latest value across the topology. */
        Integer latest;

        /**
         *
         */
        public InconsistentMapping(Map<Ignite, Integer> mapping, Integer primary, Integer latest) {
            this.mapping = new HashMap<>(mapping);
            this.primary = primary;
            this.latest = latest;
        }
    }
}


text:
[[img/klumlogo.png]]
* [[Home]]
* Overview
  * [[Terms]]
  * [[Usage]]
  * [[Basics]]
  * [[Static Models]]
* Advanced Features
  * [[Convenience Factories]]
  * [[Templates]]
  * [[Validation]]
  * [[Default Values]]
  * [[Inheritance]]
  * [[Converters]]
  * [[Alternatives Syntax]]
  * [[Advanced Techniques]]
  * [[Jackson Integration]]
* More
  * [[FAQ]]
  * [[Changelog]]
  * [[Migration]]
  * [[Roadmap]]

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.core.convert.support;

import java.nio.ByteBuffer;
import java.util.Set;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.lang.Nullable;

/**
 * Converts a {@link ByteBuffer} directly to and from {@code byte[] ByteBuffer} directly to and from {@code byte[]s} and indirectly
 * to any type that the {@link ConversionService} support via {@code byte[]}.
 *
 * @author Phillip Webb
 * @author Juergen Hoeller
 * @since 4.0
 */
final class ByteBufferConverter implements ConditionalGenericConverter {

	private static final TypeDescriptor BYTE_BUFFER_TYPE = TypeDescriptor.valueOf(ByteBuffer.class);

	private static final TypeDescriptor BYTE_ARRAY_TYPE = TypeDescriptor.valueOf(byte[].class);

	private static final Set<ConvertiblePair> CONVERTIBLE_PAIRS = Set.of(
				new ConvertiblePair(ByteBuffer.class, byte[].class),
				new ConvertiblePair(byte[].class, ByteBuffer.class),
				new ConvertiblePair(ByteBuffer.class, Object.class),
				new ConvertiblePair(Object.class, ByteBuffer.class));

	private final ConversionService conversionService;

	public ByteBufferConverter(ConversionService conversionService) {
		this.conversionService = conversionService;
	}

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		return CONVERTIBLE_PAIRS;
	}

	@Override
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
		boolean byteBufferTarget = targetType.isAssignableTo(BYTE_BUFFER_TYPE);
		if (sourceType.isAssignableTo(BYTE_BUFFER_TYPE)) {
			return (byteBufferTarget || matchesFromByteBuffer(targetType));
		}
		return (byteBufferTarget && matchesToByteBuffer(sourceType));
	}

	private boolean matchesFromByteBuffer(TypeDescriptor targetType) {
		return (targetType.isAssignableTo(BYTE_ARRAY_TYPE) ||
				this.conversionService.canConvert(BYTE_ARRAY_TYPE, targetType));
	}

	private boolean matchesToByteBuffer(TypeDescriptor sourceType) {
		return (sourceType.isAssignableTo(BYTE_ARRAY_TYPE) ||
				this.conversionService.canConvert(sourceType, BYTE_ARRAY_TYPE));
	}

	@Override
	@Nullable
	public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		boolean byteBufferTarget = targetType.isAssignableTo(BYTE_BUFFER_TYPE);
		if (source instanceof ByteBuffer buffer) {
			return (byteBufferTarget ? buffer.duplicate() : convertFromByteBuffer(buffer, targetType));
		}
		if (byteBufferTarget) {
			return convertToByteBuffer(source, sourceType);
		}
		// Should not happen
		throw new IllegalStateException("Unexpected source/target types");
	}

	@Nullable
	private Object convertFromByteBuffer(ByteBuffer source, TypeDescriptor targetType) {
		byte[] bytes = new byte[source.remaining()];
		source.get(bytes);

		if (targetType.isAssignableTo(BYTE_ARRAY_TYPE)) {
			return bytes;
		}
		return this.conversionService.convert(bytes, BYTE_ARRAY_TYPE, targetType);
	}

	private Object convertToByteBuffer(@Nullable Object source, TypeDescriptor sourceType) {
		byte[] bytes = (byte[]) (source instanceof byte[] ? source :
				this.conversionService.convert(source, sourceType, BYTE_ARRAY_TYPE));

		if (bytes == null) {
			return ByteBuffer.wrap(new byte[0]);
		}

		ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
		byteBuffer.put(bytes);

		return byteBuffer.rewind();
	}

}


text:
layout: page
title: Warren Financial Show
date: 2016-05-24
author: Jacqueline Abbott
tags: weekly links, java
status: published
summary: Nullam placerat sem sit amet eros tempor.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 02/19/2016
  endDate: 02/21/2016
  ctyhocn: NYCSPHX
  groupCode: WFS
published: true
---
Donec finibus, eros ut congue feugiat, dui justo elementum est, vitae commodo sem nulla vel mauris. Nunc at nunc sit amet enim mattis rhoncus et in lacus. Phasellus hendrerit vitae turpis vitae congue. In tincidunt finibus nisl id bibendum. Phasellus ornare aliquam convallis. Phasellus iaculis ante in lectus dictum, sed ultricies ligula scelerisque. Etiam mollis sollicitudin turpis sed facilisis. Quisque facilisis dapibus metus eget commodo. Cras euismod, metus a malesuada commodo, magna augue efficitur enim, eu aliquet leo est tristique metus.
Curabitur ultrices justo ut convallis tristique. Pellentesque quis magna enim. Donec venenatis feugiat dui, et mattis sem efficitur a. Nullam fringilla ligula at lacinia cursus. Suspendisse tristique ante a nibh mollis sagittis. Aenean arcu metus, eleifend id efficitur ac, posuere eu augue. Mauris lectus enim, vulputate id pretium ut, mollis ut tortor. Ut sed rhoncus felis, id consequat leo. Phasellus ac luctus arcu. Maecenas sagittis felis et diam egestas, vel rhoncus diam euismod. Maecenas id dui luctus diam lobortis tincidunt. Vestibulum sed lobortis metus. Aliquam in purus ac orci fermentum tempor a sed enim.

1 Proin fringilla arcu ut massa molestie, nec tempor ligula rutrum
1 Aliquam at turpis lacinia, venenatis nisi nec, facilisis metus
1 Nulla efficitur augue et venenatis hendrerit.

Sed accumsan ipsum a ex vestibulum viverra. Sed risus orci, dignissim eget nunc a, pretium euismod neque. Aliquam dapibus feugiat hendrerit. In scelerisque, odio eu finibus semper, eros ex facilisis justo, vitae tempor ante ante non felis. Vivamus accumsan condimentum ligula, sed fringilla est tincidunt at. Aliquam erat volutpat. Pellentesque rutrum vel neque commodo efficitur. Donec in odio eu dolor ullamcorper accumsan vehicula in lectus.


text:
CakePHP Captcha Library
==========================

CakePHP 2.1 :Put the "captcha" folder on path-to-cakephp-2.0/vendors/ on root vendors folder. Use following

    App::import('Vendor', 'captcha/captcha');

Since CakePHP 2.1 the Pages Controller is no longer part of the core but ships in the app folder. So my advice would be create UsersController and put the captcha_image() on that controller and and use the function on view

    $this->Html->url('/users/captcha_image');.

CakePHP 2.0 :Put the "captcha" folder on path-to-cakephp-2.0/app/vendors/ on App's vendors folder. Use following

    App::import('Vendor', 'captcha/captcha');

CakePHP 1.3 :Put the "captcha" folder on path-to-cakephp-1.3/vendors/ on the root vendors folder.

    App::import('Vendor', 'captcha/captcha');

CakePHP 1.2 :This post and code is for CakePHP 1.2 and CakePHP 1.3. For CakePHP 1.3 put the "captcha" folder on path-to-cakephp-1.3/vendors/ on the root vendors folder.

Now we implement it on our site. to do that we have to add a function the controller or we can add it to our pages controller.

    function captcha_image(){
    	App::import('Vendor', 'captcha/captcha');
    	$captcha = new captcha();
    	$captcha->show_captcha();
    }

Then we call it in our view.

    <img id="captcha" src="<?php echo $this->Html->url('/pages/captcha_image');?>" alt="" />

Add the following code to add refresh button

    <a href="javascript:void(0);" onclick="javascript:document.images.captcha.src="
    <?php echo $this->Html->url("/pages/captcha_image");?>?" + Math.round(Math.random(0)*1000)+1" >Reset
To check the captcha in controller we will use this one.

    if($this->data['ContactMsge']['captcha']!=$this->Session->read('captcha'))
    {
    $this->Session->setFlash(__('Please enter correct captcha code and try again.', true));
    }

So as you can see you add this to you site very easily and it is very much customizable.

## Contact

Follow [@jambura.blog](https://www.facebook.com/jambura.blog) on Facebook

### Creators

[Zakir Hyder](https://github.com/zakir-hyder)
[@jambura.blog](https://www.facebook.com/jambura.blog)

## License

CakePHP Captcha Library is available under the MIT license. See the LICENSE file for more info.


text:
package org.apache.camel.component.netty4;

import java.net.InetSocketAddress;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.AddressedEnvelope;
import io.netty.channel.DefaultAddressedEnvelope;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Assert;
import org.junit.Test;

public class DatagramPacketByteArrayCodecTest {

    private static final String VALUE = "~!Camel rocks@%";

    @Test
    public void testDecoder() {
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(VALUE.getBytes());
        ByteBuf input = buf.duplicate();
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop =
                new DefaultAddressedEnvelope<Object, InetSocketAddress>(input, new InetSocketAddress(8888));
        EmbeddedChannel channel = new EmbeddedChannel(ChannelHandlerFactories.newByteArrayDecoder("udp").newChannelHandler());
        Assert.assertTrue(channel.writeInbound(addressedEnvelop));
        Assert.assertTrue(channel.finish());
        AddressedEnvelope<Object, InetSocketAddress> result = (AddressedEnvelope) channel.readInbound();
        Assert.assertEquals(result.recipient().getPort(), addressedEnvelop.recipient().getPort());
        Assert.assertTrue(result.content() instanceof byte[]);
        Assert.assertEquals(VALUE, new String((byte[]) result.content()));
        Assert.assertNull(channel.readInbound());
    }

    @Test
    public void testEncoder() {
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(VALUE.getBytes());
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop =
                new DefaultAddressedEnvelope<Object, InetSocketAddress>(VALUE.getBytes(), new InetSocketAddress(8888));
        EmbeddedChannel channel = new EmbeddedChannel(ChannelHandlerFactories.newByteArrayEncoder("udp").newChannelHandler());
        Assert.assertTrue(channel.writeOutbound(addressedEnvelop));
        Assert.assertTrue(channel.finish());
        AddressedEnvelope output = (AddressedEnvelope) channel.readOutbound();
        Assert.assertTrue(output.content() instanceof ByteBuf);
        ByteBuf resultContent = (ByteBuf) output.content();
        Assert.assertEquals(VALUE, new String(resultContent.array()));
        Assert.assertNull(channel.readOutbound());
    }
}


text:
#pragma once

#include <thrust/detail/config.h>

// the purpose of this header is to #include the equal.h header
// of the sequential, host, and device systems. It should be #included in any
// code which uses adl to dispatch equal

#include <thrust/system/detail/sequential/equal.h>

#define __THRUST_HOST_SYSTEM_EQUAL_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/equal.h>
#include __THRUST_HOST_SYSTEM_EQUAL_HEADER
#undef __THRUST_HOST_SYSTEM_EQUAL_HEADER

#define __THRUST_DEVICE_SYSTEM_EQUAL_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/equal.h>
#include __THRUST_DEVICE_SYSTEM_EQUAL_HEADER
#undef __THRUST_DEVICE_SYSTEM_EQUAL_HEADER


text:
from sys import exit
from sys import argv
import numpy as np

OrthoTable = argv[1]
cut = argv[2]
cut = float(cut)
outfileName = OrthoTable.strip(".txt") + "_rep{}.txt".format(cut)
# print "cut = {}".format(cut)

passing = 0
rejected = 0
totalGenes = 0
with open(OrthoTable, 'r') as infile:
    with open(outfileName, 'w') as out:
        lineNumber = 0
        for line in infile:
            lineNumber += 1
            line = line.strip('\n').split("\t")
            if lineNumber == 1:
                header = line
                total = (len(header) - 1)
                minimum = int(np.round(cut*total))
                # print "minium = {}".format(minimum)
                out.write("\t".join(header))
                continue
            else:
                totalGenes += 1
                missing = line.count("NA")
                count = total - missing
                # print line[0] + "\t" + str(count)
                if count >= minimum:
                    passing += 1
                    out.write("\n" + "\t".join(line))
                #skip lines without sufficient representation
                else:
                    rejected += 1
                    continue

print "\nOf {} total genes...".format(totalGenes)
print "{} had at least {} representative species and were kept".format(passing, minimum)
print "{} were rejected because they did not have enough species".format(rejected)


text:
First, you must enabled the bootstrap-datepicker, if it are not enabled yet, see how at the footer of this doc in the section [Enabling Datepicker and jquery access](./enable_datepicker.md)

For example to add the **date of birth** at the families table:

* just add the field date_of_birth:date and run

i.e.:

```bash

	php artisan makefast:remove families --auto --dirs
	php artisan makefast:scaffold families --fields="first_name:string(64),last_name:string(64), gender:custom, employee_id:master, date_of_birth:date"

```

* now check the results in your browser!!.

surprised?

[home](../readme.md)


text:
package Warmup;

import java.io.InputStreamReader;
import java.util.Scanner;

/*
 * Link: https://www.hackerrank.com/challenges/simple-array-sum
*/
public class _52simpleArraySum {

	    public static void main(String[] args) {
	        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
	        Scanner scanner=new Scanner(new InputStreamReader(System.in));
	        int N=Integer.parseInt(scanner.nextLine());
	        String inputArray[]=(scanner.nextLine().split(" "));
	        int sum=0;
	        for(int i=0;i<inputArray.length;i++)
	        {
	            sum+=Integer.parseInt(inputArray[i]);
	        }
	        System.out.println(sum);
	    }

}


text:
namespace One.One
{
	partial class ResolutionPicker
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.selectBtn = new System.Windows.Forms.Button();
			this.resolutionsLv = new System.Windows.Forms.ListView();
			this.SuspendLayout();
			//
			// selectBtn
			//
			this.selectBtn.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
			this.selectBtn.Location = new System.Drawing.Point(95, 280);
			this.selectBtn.MaximumSize = new System.Drawing.Size(86, 23);
			this.selectBtn.Name = "selectBtn";
			this.selectBtn.Size = new System.Drawing.Size(86, 23);
			this.selectBtn.TabIndex = 1;
			this.selectBtn.Text = "Select";
			this.selectBtn.UseVisualStyleBackColor = true;
			this.selectBtn.Click += new System.EventHandler(this.selectBtn_Click);
			//
			// resolutionsLv
			//
			this.resolutionsLv.FullRowSelect = true;
			this.resolutionsLv.GridLines = true;
			this.resolutionsLv.Location = new System.Drawing.Point(12, 12);
			this.resolutionsLv.Name = "resolutionsLv";
			this.resolutionsLv.Size = new System.Drawing.Size(249, 262);
			this.resolutionsLv.TabIndex = 2;
			this.resolutionsLv.UseCompatibleStateImageBehavior = false;
			this.resolutionsLv.View = System.Windows.Forms.View.Details;
			this.resolutionsLv.SelectedIndexChanged += new System.EventHandler(this.resolutionsLv_SelectedIndexChanged);
			//
			// ResolutionPicker
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(273, 315);
			this.Controls.Add(this.resolutionsLv);
			this.Controls.Add(this.selectBtn);
			this.Name = "ResolutionPicker";
			this.Text = "Resolutions";
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.Button selectBtn;
		private System.Windows.Forms.ListView resolutionsLv;
	}
}


text: Exploring the relationships between [DIY](diy.org) skills


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2759981</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753461078</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Achtmaal</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Achtmaal</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Achtmaal</Appelation>
        <LocationNameType>populated place</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>4.58472</Longitude>
        <Latitude>51.45417</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2759981</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
LDAP (Active Directory) Authentication is disabled by default.

To enable LDAP on server-side open `*CoreModule.cs` in ***.Core** project, uncomment the following line

```csharp
Configuration.Modules.ZeroLdap().Enable(typeof(AppLdapAuthenticationSource));
```

See [server side](Features-Mvc-Core-Tenant-Active-Directory) to enable LDAP. Once we enable, we can see **LDAP settings** section in the settings page:

<img src="images/tenant-settings-ldap-1.png" alt="LDAP Settings" class="img-thumbnail" />

We can check "**Enable LDAP Authentication**" to enable it. If the server works in domain and application runs with a domain user or local system, then generally even **no need** to set Domain name, user and password. You can logout and then login with your **domain user name and password**. If not, you should set these credentials.

## Next

- [Maintenance](Features-Angular-Maintenance)


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>simpatičan dostavljač, novozaposleni :)hrana standardno odličnaprijedlog- napišite koja vrsta pive.. no, ofc, nisam ni očekivala rcmo tuborg za tu cijenu :)</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/catering-andjeo</Source>
</CrawlItem>


text:
"""
    Swaggy Jenkins

    Jenkins API clients generated from Swagger / Open API specification  # noqa: E501

    The version of the OpenAPI document: 1.5.1-pre.0
    Contact: blah@cliffano.com
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import

import unittest

import openapi_client
from openapi_client.api.base_api import BaseApi  # noqa: E501
from openapi_client.rest import ApiException

class TestBaseApi(unittest.TestCase):
    """BaseApi unit test stubs"""

    def setUp(self):
        self.api = openapi_client.api.base_api.BaseApi()  # noqa: E501

    def tearDown(self):
        pass

    def test_get_crumb(self):
        """Test case for get_crumb

        """
        pass

if __name__ == '__main__':
    unittest.main()


text:
import React from 'react';

import './input-mixin.less';

import Label from './../internal/label.js';
import InputWrapper from './../internal/input-wrapper.js';

const INITIAL_FEEDBACK = 'initial';
const SUCCESS_FEEDBACK = 'success';
const WARNING_FEEDBACK = 'warning';
const ERROR_FEEDBACK = 'error';
const LOADING_FEEDBACK = 'loading';

export const InputMixin = {

  //@@viewOn:mixins
  //@@viewOff:mixins

  //@@viewOn:statics
  statics: {
    UU5_Forms_InputMixin: {
      classNames: {
        main: 'uu5-forms-input',
        formItem: 'uu5-forms-input-form-item',
        input: 'uu5-forms-input-',
        readOnly: 'uu5-forms-input-read-only',
        hasGlyphicon: "uu5-forms-input-glyphicon"
      }
    }
  },
  //@@viewOff:statics

  //@@viewOn:propTypes
  propTypes: {
    label: React.PropTypes.any,
    message: React.PropTypes.any,

    feedback: React.PropTypes.oneOf([INITIAL_FEEDBACK, SUCCESS_FEEDBACK, WARNING_FEEDBACK, ERROR_FEEDBACK, LOADING_FEEDBACK]),

    readOnly: React.PropTypes.bool,

    size: React.PropTypes.oneOf(['lg', 'md', 'sm']),

    onChange: React.PropTypes.func,
    onValidate: React.PropTypes.func,
    onChangeFeedback: React.PropTypes.func,

    successGlyphicon: React.PropTypes.string,
    warningGlyphicon: React.PropTypes.string,
    errorGlyphicon: React.PropTypes.string,

    labelColWidth: React.PropTypes.oneOfType([React.PropTypes.shape({
      xs: React.PropTypes.number,
      sm: React.PropTypes.number,
      md: React.PropTypes.number,
      lg: React.PropTypes.number
    }), React.PropTypes.string
    ]),
    inputColWidth: React.PropTypes.oneOfType([React.PropTypes.shape({
      xs: React.PropTypes.number,
      sm: React.PropTypes.number,
      md: React.PropTypes.number,
      lg: React.PropTypes.number
    }), React.PropTypes.string
    ]),

    inputAttrs: React.PropTypes.object
  },
  //@@viewOff:propTypes

  //@@viewOn:getDefaultProps
  getDefaultProps: function () {
    return {
      label: null,
      message: null,
      feedback: INITIAL_FEEDBACK,
      readOnly: false,
      size: 'md',
      onChange: null,
      onValidate: null,
      successGlyphicon: 'uu-glyphicon-ok-circle',
      warningGlyphicon: 'uu-glyphicon-alert-circle',
      errorGlyphicon: 'uu-glyphicon-error-circle',
      labelColWidth: 'xs-12 sm-3',
      inputColWidth: 'xs-12 sm-9',
      inputAttrs: null
    };
  },
  //@@viewOff:getDefaultProps

  //@@viewOn:standardComponentLifeCycle
  getInitialState: function () {
    return {
      message: this.props.message,
      feedback: this.props.feedback,
      value: this.props.value,
      readOnly: this.props.readOnly
    };
  },

  componentDidMount: function () {
    var parentForm = this._getForm();
    parentForm && parentForm.registerFormControl(this.getId(), this);
  },

  componentWillReceiveProps: function (nextProps) {
    if (nextProps.id && nextProps.id !== this.props.id) {
      var parentForm = this._getForm();
      if (parentForm) {
        parentForm.unregisterFormControl(this.props.id);
        parentForm.registerFormControl(nextProps.id, this);
      }
    }
    if (nextProps.controlled) {
      //TODO: jine komponenty jak text zkontrolovat willRecievePros (byude se modifikovat jen value), vsude musi byt nextProps.controled
      this.setFeedback(nextProps.feedback, nextProps.message, nextProps.value);
      this.setState({readOnly: nextProps.readOnly})
    }
  },

  componentWillUnmount: function () {
    var parentForm = this._getForm();
    parentForm && parentForm.unregisterFormControl(this.getId());
  },
  //@@viewOff:standardComponentLifeCycle

  //@@viewOn:interface
  isInput() {
    return true;
  },

  getValue() {
    let value;
    if (typeof this.getValue_ === 'function') {
      value = this.getValue_();
    } else {
      value = this.state.value;
    }
    return value;
  },

  setValue(value, setStateCallback) {
    if (typeof this.setValue_ === 'function') {
      this.setValue_(value, setStateCallback);
    } else {
      this.setState({value: value || ''}, setStateCallback);
    }
    return this;
  },

  getMessage() {
    let message;
    if (typeof this.getMessage_ === 'function') {
      message = this.getMessage_();
    } else {
      message = this.state.message;
    }
    return message;
  },

  setMessage(message, setStateCallback) {
    if (typeof this.setMessage_ === 'function') {
      this.setMessage_(message, setStateCallback);
    } else {
      this.setState({message: message}, setStateCallback);
    }
    return this;
  },

  getFeedback(){
    let feedback;
    if (typeof this.getFeedback_ === 'function') {
      feedback = this.getFeedback_();
    } else {
      feedback = this.state.feedback;
    }
    return feedback;
  },

  setFeedback(feedback, message, value, setStateCallback){
    if (typeof this.setFeedback_ === 'function') {
      this.setFeedback_(feedback, message, value, setStateCallback);
    } else {
      this.setState({
        feedback: feedback,
        message: message,
        value: value || ''
      }, setStateCallback);
    }
    return this;
  },

  setInitial(message, value, setStateCallback){
    if (typeof this.setInitial_ === 'function') {
      this.setInitial_(message, value, setStateCallback);
    } else {
      this._setFeedback(INITIAL_FEEDBACK, message, value, setStateCallback);
    }
    return this;
  },

  isInitial(){
    return this.getFeedback() === INITIAL_FEEDBACK;
  },

  setLoading(message, value, setStateCallback){
    if (typeof this.setLoading_ === 'function') {
      this.setLoading_(message, value, setStateCallback);
    } else {
      this._setFeedback(LOADING_FEEDBACK, message, value, setStateCallback);
    }
    return this;
  },

  isLoading(){
    return this.getFeedback() === LOADING_FEEDBACK;
  },

  setSuccess(message, value, setStateCallback){
    if (typeof this.setSuccess_ === 'function') {
      this.setSuccess_(message, value, setStateCallback);
    } else {
      this._setFeedback(SUCCESS_FEEDBACK, message, value, setStateCallback);
    }
    return this;
  },

  isSuccess(){
    return this.getFeedback() === SUCCESS_FEEDBACK;
  },

  setWarning(message, value, setStateCallback){
    if (typeof this.setWarning_ === 'function') {
      this.setWarning_(message, value, setStateCallback);
    } else {
      this._setFeedback(WARNING_FEEDBACK, message, value, setStateCallback);
    }
    return this;
  },

  isWarning(){
    return this.getFeedback() === WARNING_FEEDBACK;
  },

  setError(message, value, setStateCallback){
    if (typeof this.setError_ === 'function') {
      this.setError_(message, value, setStateCallback);
    } else {
      this._setFeedback(ERROR_FEEDBACK, message, value, setStateCallback);
    }
    return this;
  },

  isError(){
    return this.getFeedback() === ERROR_FEEDBACK;
  },

  reset(setStateCallback){
    if (typeof this.reset_ === 'function') {
      this.reset_(setStateCallback);
    } else {
      this.setState({
        message: this.props.message,
        feedback: this.props.feedback,
        value: this.props.value,
        readOnly: this.props.readOnly
      }, setStateCallback);
    }
    return this;
  },

  //TODO getResetValues

  getChangeFeedback(opt){
    let result;

    if (typeof this.getChangeFeedback_ === 'function') {
      result = this.getChangeFeedback_(opt);
    } else {
      result = {
        feedback: opt.required ? SUCCESS_FEEDBACK : INITIAL_FEEDBACK,
        message: null,
        value: opt.value
      }
    }

    return result;
  },

  setChangeFeedback(opt, setStateCallback){
    let result;

    if (typeof this.setChangeFeedback_ === 'function') {
      result = this.setChangeFeedback_(opt, setStateCallback);
    } else {
      result = this.getChangeFeedback(opt);

      this.setState({
        feedback: result.feedback,
        message: result.message,
        value: result.value
      }, setStateCallback);
    }

    return this;
  },

  isReadOnly(){
    return this.state.readOnly;
  },

  setEditableValue(value, setStateCallback){
    if (typeof this.setEditableValue_ === 'function') {
      this.setEditableValue_(value, setStateCallback);
    } else {
      this.setState({readOnly: !value}, setStateCallback);
    }
    return this;
  },

  readOnly(setStateCallback){
    if (typeof this.readOnly_ === 'function') {
      this.readOnly_(setStateCallback);
    } else {
      this.setEditableValue(false, setStateCallback);
    }
    return this;
  },

  editable(setStateCallback){
    if (typeof this.editable_ === 'function') {
      this.editable_(setStateCallback);
    } else {
      this.setEditableValue(true, setStateCallback);
    }
    return this;
  },

  getLabel(inputId){
    let result = null;
    if (this.props.label != null) {
      result = <Label {...this._getLabelProps(inputId)}/>
    }
    return result;
  },

  getInputWrapper(children, buttons){
    return <InputWrapper {...this._getInputWrapperProps(children, buttons)} />;
  },
  //@@viewOff:interface

  //@@viewOn:overridingMethods
  //@@viewOff:overridingMethods

  //@@viewOn:componentSpecificHelpers
  _getForm: function () {
    var form = null;
    var parent = this.getParent && this.getParent();
    while (parent) {
      if (typeof parent.isInput === 'function' && parent.isInput()) {
        break;
      } else if (typeof parent.isForm === 'function' && parent.isForm()) {
        form = parent;
        break;
      } else {
        parent = parent.getParent && parent.getParent();
      }
    }
    return form;
  },

  _setFeedback: function (feedback, message, value, setStateCallback) {
    if (typeof this.props.onChangeFeedback === 'function') {
      this.props.onChangeFeedback({
        feedback: feedback,
        message: message,
        value: value || '',
        callback: setStateCallback,
        component: this
      });
    } else {
      this.setFeedback(feedback, message, value, setStateCallback);
    }
    return this;
  },

  _buildColWidthClassName: function (colWidth) {
    var newBsColWidth = colWidth;

    if (typeof newBsColWidth === 'string') {
      var colWidthArray = newBsColWidth.split(' ');
      newBsColWidth = {};
      colWidthArray.forEach(function (colWidth) {
        var match = colWidth.match(/^(.*)-(\d+)$/);
        newBsColWidth[match[1]] = parseInt(match[2]);
      });
    }

    var sizeClassNames = [];
    var lowerWidth = 12;

    !newBsColWidth.xs && lowerWidth && (newBsColWidth.xs = lowerWidth);
    (lowerWidth = newBsColWidth.xs) && sizeClassNames.push('col-xs-' + newBsColWidth.xs);
    !newBsColWidth.sm && lowerWidth && (newBsColWidth.sm = lowerWidth);
    (lowerWidth = newBsColWidth.sm) && sizeClassNames.push('col-sm-' + newBsColWidth.sm);
    !newBsColWidth.md && lowerWidth && (newBsColWidth.md = lowerWidth);
    (lowerWidth = newBsColWidth.md) && sizeClassNames.push('col-md-' + newBsColWidth.md);
    !newBsColWidth.lg && lowerWidth && (newBsColWidth.lg = lowerWidth);
    newBsColWidth.lg && sizeClassNames.push('col-lg-' + newBsColWidth.lg);

    return sizeClassNames.join(' ');
  },

  _getInputAttrs() {
    let mainAttrs = this.getMainAttrs();

    mainAttrs.className += ' ' + this.getClassName('main', 'UU5_Forms_InputMixin');
    mainAttrs.className += ' ' + this.getClassName('input', 'UU5_Forms_InputMixin') + this.props.size;
    mainAttrs.className += ' ' + this.getClassName('input', 'UU5_Forms_InputMixin') + this.state.feedback;
    if (this.isReadOnly()) {
      mainAttrs.className += ' ' + this.getClassName('readOnly', 'UU5_Forms_InputMixin');
    }

    if (this.state.feedback != INITIAL_FEEDBACK || this.props.required) {
      mainAttrs.className += ' ' + this.getClassName('hasGlyphicon', 'UU5_Forms_InputMixin');
    }

    return mainAttrs;
  },

  _getLabelProps(inputId){
    let className;
    if (this.props.labelPosition === 'right') {
      className = 'uu5-forms-input-label-right';
    }
    return {
      for: inputId,
      content: this.props.label,
      colWidth: this._buildColWidthClassName(this.props.labelColWidth),
      className: className
    }
  },

  _getInputWrapperProps(children, buttons) {

    let colWidth = this._buildColWidthClassName(this.props.label ? this.props.inputColWidth : 'xs-12');
    let feedback = this.getFeedback();
    let message = this.getMessage();
    // if(this.props.labelPosition  && this.props.labelPosition !== 'left') {
    //   colWidth = this._buildColWidthClassName('xs-12');
    //   //feedback = null;
    //   //message = null;
    // }

    return {
      colWidth: colWidth,
      feedback: feedback,
      message: message,
      required: this.props.required,
      buttons: buttons,
      children: children,
      slider: this.getTagName() === 'UU5.Forms.Slider'
    }
  },
  //@@viewOff:componentSpecificHelpers

  //@@viewOn:render
  //@@viewOff:render
};

InputMixin.INITIAL_FEEDBACK = INITIAL_FEEDBACK;
InputMixin.SUCCESS_FEEDBACK = SUCCESS_FEEDBACK;
InputMixin.WARNING_FEEDBACK = WARNING_FEEDBACK;
InputMixin.ERROR_FEEDBACK = ERROR_FEEDBACK;
InputMixin.LOADING_FEEDBACK = LOADING_FEEDBACK;

export default InputMixin;


text:
/**
 * webida.preference plugin main
 *
 * @since: 15. 8. 18
 * @author: Koong Kyungmi (kyungmi.k@samsung.com)
 * @module webida.preference
 */

/* jshint unused:false */

define([
    'dojo/topic',
    'external/lodash/lodash.min',
    'plugins/project-configurator/project-info-service',
    'webida-lib/plugins/workbench/ui/promiseMap',
    'webida-lib/plugins/workspace/plugin',
    'webida-lib/util/logger/logger-client',
    'webida-lib/util/path',
    './preference-manager'
], function (
    topic,
    _,
    projectInfo,
    promiseMap,
    workspace,
    Logger,
    pathUtil,
    manager
) {
    'use strict';

    var MODULE_PATH_VIEW_CTRL = 'plugins/webida.preference/view-controller';
    var logger = new Logger();
    var module = {};

    var workbenchItems = {
        '&Preferences': ['cmnd', 'plugins/webida.preference/plugin', 'openDialogByWorkspaceScope']
    };

    var workspaceItems = {
        'Preferences': ['cmnd', 'plugins/webida.preference/plugin', 'openDialogByContext']
    };

    var managerInitialized = promiseMap.get('preference/load');

    function _getContextInfo(paths) {
        var info = {
            multi: false,
            nodeType: 'file'
        };
        var pathSplit;
        if (paths) {
            if (paths.length === 1 && pathUtil.isDirPath(paths[0])) {
                info.nodeType = 'directory';
                pathSplit = paths[0].split('/');
                if (pathSplit.length === 3) {
                    info.nodeType = 'workspace';
                } else if (pathSplit.length === 4) {
                    if (projectInfo.getByName(pathSplit[2])) {
                        info.projectName = pathSplit[2];
                        info.nodeType = 'project';
                    }
                }
            } else if (paths.length > 1) {
                info.multi = true;
            }
        }
        return info;
    }

    function _openDialog(scope, info) {
        require([MODULE_PATH_VIEW_CTRL], function (viewController) {
            managerInitialized.then(function () {
                viewController.openDialog(scope, info);
            });
        });
    }

    module.getViableItemsForWorkbench = function () {
        var preferenceTypes = manager.getAllPreferenceTypes(manager.SCOPE.WORKSPACE);
        return preferenceTypes.length > 0 ? workbenchItems : null;
    };

    module.getViableItemsForWorkspace = function () {
        var context = _getContextInfo(workspace.getSelectedPaths());
        var viable = !context.multi && (context.nodeType === 'workspace' || context.nodeType === 'project');
        var preferenceTypes = manager.getAllPreferenceTypes(manager.SCOPE[context.nodeType.toUpperCase()]);
        return (viable && preferenceTypes.length > 0) ? workspaceItems : null;
    };

    module.openDialogByWorkspaceScope = function () {
        _openDialog(manager.SCOPE.WORKSPACE);
    };

    module.openDialogByContext = function () {
        var context = _getContextInfo(workspace.getSelectedPaths());
        var scope = manager.SCOPE.WORKSPACE;
        var info = {};
        if (context.nodeType) {
            if (context.nodeType === 'project') {
                scope = manager.SCOPE.PROJECT;
                info = {projectName: context.projectName};
            }
            _openDialog(scope, info);
        }
    };

    return module;
});


text: automatic for windows and Linux


text:
package com.bsuir.shoken.iam;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
class SpringBCryptPasswordHashEncoder extends BCryptPasswordEncoder implements PasswordHashEncoder {
}


text:
package inloopio.util.pinyin.format

/**
 * This classes define how the Hanyu Pinyin should be outputted.
 *
 */
final case class HanyuPinyinOutputFormat(vCharType: HanyuPinyinVCharType = HanyuPinyinVCharType.WITH_U_AND_COLON,
                                         caseType: HanyuPinyinCaseType = HanyuPinyinCaseType.LOWERCASE,
                                         toneType: HanyuPinyinToneType = HanyuPinyinToneType.WITH_TONE_NUMBER)


text:
@interface PodsDummy_Pods_XCTest_Gherkin_Example_XCTest_Gherkin_Tests : NSObject
@end
@implementation PodsDummy_Pods_XCTest_Gherkin_Example_XCTest_Gherkin_Tests
@end


text:
FROM wordpress:4.6

# Restore apache defaults
ADD ./conf/apache2.conf /etc/apache2/apache2.conf


text: echo "wait for rundeck and hostnode to become ready"


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace ZackRankFinder
{
    public class Sungard
    {
        public string bidasksize { get; set; }
        public string dividend_freq { get; set; }
        public string prev_close_date { get; set; }
        public string timestamp { get; set; }
        public string exchange { get; set; }
        public string shares { get; set; }
        public string volatility { get; set; }
        public string zacks_recommendation { get; set; }
        public string pos_size { get; set; }
        public string open { get; set; }
        public string yrlow { get; set; }
        public string type { get; set; }
        public string yield { get; set; }
        public string market_cap { get; set; }
        public string ask { get; set; }
        public string dividend { get; set; }
        public string dividend_date { get; set; }
        public string earnings { get; set; }
        public string close { get; set; }
        public string day_low { get; set; }
        public string last_trade_datetime { get; set; }
        public string volume { get; set; }
        public string yrhigh { get; set; }
        public string day_high { get; set; }
        public string bid { get; set; }
        public string name { get; set; }
        public string pe_ratio { get; set; }
        public string updated { get; set; }
    }

    public class Bats
    {
        public string ask_size { get; set; }
        public string routed { get; set; }
        public string last_trade_datetime { get; set; }
        public string matched { get; set; }
        public string bid_size { get; set; }
        public string net_pct_change { get; set; }
        public string updated { get; set; }
        public string end_mkt_day_price { get; set; }
        public string ask_price { get; set; }
        public string bid_price { get; set; }
        public string last { get; set; }
        public string pre_after_updated { get; set; }
        public string net_price_change { get; set; }
        public string pre_after_price { get; set; }
        public string net_change { get; set; }
    }

    public class Pre
    {
        public string after_percent_net_change { get; set; }
        public string after_net_change { get; set; }
    }

    public class Source
    {
        public Sungard sungard { get; set; }
        public Bats bats { get; set; }
        public Pre pre { get; set; }
    }

    public class Stock
    {
        public Source source { get; set; }
        public string exchange { get; set; }
        public string dividend_yield { get; set; }
        public string last { get; set; }
        public string ticker { get; set; }
        public string ticker_type { get; set; }
        public string zacks_rank_text { get; set; }
        public string volume { get; set; }
        public string updated { get; set; }
        public string percent_net_change { get; set; }
        public string zacks_rank { get; set; }
        public string name { get; set; }
        public string net_change { get; set; }
        public string market_time { get; set; }
        public string previous_close { get; set; }
        public string SUNGARD_BID { get; set; }
        public string SUNGARD_YRLOW { get; set; }
        public string SUNGARD_MARKET_CAP { get; set; }
        public string FEED_NET_CHANGE { get; set; }
        public string BATS_PRE_AFTER_UPDATED { get; set; }
        public string SUNGARD_EARNINGS { get; set; }
        public string SUNGARD_VOLATILITY { get; set; }
        public string SUNGARD_PE_RATIO { get; set; }
        public string SUNGARD_DAY_LOW { get; set; }
        public string SUNGARD_YRHIGH { get; set; }
        public string SUNGARD_DIVIDEND_FREQ { get; set; }
        public string SUNGARD_PREV_CLOSE_DATE { get; set; }
        public string BATS_ASK_PRICE { get; set; }
        public string SUNGARD_YIELD { get; set; }
        public string SUNGARD_DAY_HIGH { get; set; }
        public string SUNGARD_ZACKS_RECOMMENDATION { get; set; }
        public string SUNGARD_NAME { get; set; }
        public string SUNGARD_TIMESTAMP { get; set; }
        public string SUNGARD_VOLUME { get; set; }
        public string SUNGARD_BIDASKSIZE { get; set; }
        public string BATS_BID_PRICE { get; set; }
        public string BATS_LAST_TRADE_DATETIME { get; set; }
        public string FEED_VOLUME { get; set; }
        public string SUNGARD_SHARES { get; set; }
        public string SUNGARD_DIVIDEND { get; set; }
        public string SUNGARD_DIVIDEND_DATE { get; set; }
        public string BATS_BID_SIZE { get; set; }
        public string SUNGARD_LAST_TRADE_DATETIME { get; set; }
        public string SUNGARD_UPDATED { get; set; }
        public string BATS_ROUTED { get; set; }
        public string BATS_ASK_SIZE { get; set; }
        public string FEED_TICKER { get; set; }
        public string SUNGARD_POS_SIZE { get; set; }
        public string SUNGARD_EXCHANGE { get; set; }
        public string SUNGARD_TYPE { get; set; }
        public string BATS_PRE_AFTER_PRICE { get; set; }
        public string BATS_UPDATED { get; set; }
        public string FEED_LAST { get; set; }
        public string FEED_PERCENT_NET_CHANGE { get; set; }
        public string FEED_SOURCE { get; set; }
        public string FEED_UPDATED { get; set; }
        public string SUNGARD_OPEN { get; set; }
        public string SUNGARD_CLOSE { get; set; }
        public string SUNGARD_ASK { get; set; }
        public string BATS_MATCHED { get; set; }
        public string pre_after_net_change { get; set; }
        public string pre_after_percent_net_change { get; set; }
        public string ticker_market_status { get; set; }
        public string ap_short_name { get; set; }
        public string market_status { get; set; }
        public string previous_close_date { get; set; }
    }
}


text:
import os
import sys
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.escape
from biothings.www.settings import BiothingESWebSettings
from biothings.utils.common import is_str
from tempfile import NamedTemporaryFile
from string import Template

def _is_module(m):
    try:
        _ret = import_module(m)
    except ImportError:
        return False

    return _ret

def _is_file(f):
    return os.path.exists(os.path.abspath(f)) and os.path.isfile(os.path.abspath(f))

class BiothingsAPIApp(object):
    def __init__(self, *args, **kwargs):
        if kwargs.get('object_name', False) or (len(args) >= 1 and not _is_module(args[0]) and not _is_file(args[0])):
            _arg = args[0] if args else ''
            self._configure_by_object_name(object_name=kwargs.get('object_name', _arg))
        elif ((kwargs.get('config_file', False) and _file_exists(kwargs['config_file'])) or
            (len(args) >= 1 and _is_file(args[0]))):
            _arg = args[0] if args else ''
            self._configure_by_file(config_file=os.path.abspath(kwargs.get('config_file', _arg)))
        elif ((kwargs.get('config_module', False) and _is_module(kwargs['config_module'])) or
            (len(args) >= 1 and _is_module(args[0]))):
            _arg = args[0] if args else ''
            self._configure_by_module(config_module=kwargs.get('config_module', _arg))
        else:
            self._configure_by_kwargs(**kwargs)

    def start(self, debug=True, port=8000, address='127.0.0.1', app_settings={}):
        if debug:
            #import tornado.autoreload
            import logging
            logging.getLogger().setLevel(logging.DEBUG)
            address='0.0.0.0'

        with NamedTemporaryFile(mode='w', suffix='.py', dir=os.path.abspath('.')) as _tempfile:
            if not getattr(self, 'settings_mod', False):
                if not getattr(self, 'settings_str', False):
                    raise("Could not configure biothings app")
                _tempfile.file.write(self.settings_str)
                _tempfile.file.flush()
                self.settings_mod = os.path.split(_tempfile.name)[1].split('.')[0]
            self.settings = BiothingESWebSettings(config=self.settings_mod)
            application = tornado.web.Application(self.settings.generate_app_list(), **app_settings)
            http_server = tornado.httpserver.HTTPServer(application)
            http_server.listen(port, address)
            loop = tornado.ioloop.IOLoop.instance()
            if debug:
                #tornado.autoreload.start(loop)
                logging.info('Server is running on "%s:%s"...' % (address, port))
            loop.start()

    def _configure_by_object_name(self, object_name):
        # get the config file template
        config_string = """from biothings.www.settings.default import *\n""" + \
                        """from biothings.www.api.es.handlers import *\n""" + \
                        """ES_INDEX = '${src_package}_current'\n""" + \
                        """ES_DOC_TYPE = '${es_doctype}'\n""" + \
                        """API_VERSION = 'v1'\n""" + \
                        """APP_LIST = [(r'/status', StatusHandler), (r'/metadata/?', MetadataHandler), (r'/metadata/fields/?', MetadataHandler), (r'/{}/${annotation_endpoint}/(.+)/?'.format(API_VERSION), BiothingHandler), (r'/{}/${annotation_endpoint}/?$$'.format(API_VERSION), BiothingHandler), (r'/{}/query/?'.format(API_VERSION), QueryHandler), (r'/{}/metadata/?'.format(API_VERSION), MetadataHandler), (r'/{}/metadata/fields/?'.format(API_VERSION), MetadataHandler),]\n""" + \
                        """GA_RUN_IN_PROD = False"""
        settings_dict = {'src_package': 'my' + object_name.lower(),
                         'es_doctype': object_name.lower(),
                         'annotation_endpoint': object_name.lower()}

        self.settings_str = Template(config_string).substitute(settings_dict)

    def _configure_by_module(self, config_module):
        self.settings_mod = config_module

    def _configure_by_kwargs(self, **kwargs):
        self.settings_str = """from biothings.www.settings.default import *\nfrom biothings.www.api.es.handlers import *\n"""
        for (k,v) in kwargs.items():
            if k == 'APP_LIST':
                self.settings_str += '{k}=['.format(k=k)
                for (reg, handler_str) in v:
                    self.settings_str += "(r'{reg}', {handler}),".format(reg=reg, handler=handler_str)
                self.settings_str += ']\n'
            elif k in ['ES_QUERY_BUILDER', 'ES_QUERY', 'ES_RESULT_TRANSFORMER']:
                self.settings_str += '{k}={v}\n'
            elif is_str(v):
                self.settings_str += '{k}="{v}"\n'.format(k=k, v=v)
            else:
                self.settings_str += '{k}={v}\n'

    def _configure_by_file(self, config_file):
        with open(config_file, 'r') as config_handle:
            self.settings_str = config_handle.read()


text:
'use strict';

const models = require('./index');

/**
 * A Data Lake Analytics catalog U-SQL table type item.
 *
 * @extends models['USqlType']
 */
class USqlTableType extends models['USqlType'] {
  /**
   * Create a USqlTableType.
   * @member {array} [columns] the type field information associated with this
   * table type.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of USqlTableType
   *
   * @returns {object} metadata of USqlTableType
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'USqlTableType',
      type: {
        name: 'Composite',
        className: 'USqlTableType',
        modelProperties: {
          computeAccountName: {
            required: false,
            serializedName: 'computeAccountName',
            type: {
              name: 'String'
            }
          },
          version: {
            required: false,
            serializedName: 'version',
            type: {
              name: 'String'
            }
          },
          databaseName: {
            required: false,
            serializedName: 'databaseName',
            type: {
              name: 'String'
            }
          },
          schemaName: {
            required: false,
            serializedName: 'schemaName',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'typeName',
            type: {
              name: 'String'
            }
          },
          typeFamily: {
            required: false,
            serializedName: 'typeFamily',
            type: {
              name: 'String'
            }
          },
          cSharpName: {
            required: false,
            serializedName: 'cSharpName',
            type: {
              name: 'String'
            }
          },
          fullCSharpName: {
            required: false,
            serializedName: 'fullCSharpName',
            type: {
              name: 'String'
            }
          },
          systemTypeId: {
            required: false,
            serializedName: 'systemTypeId',
            type: {
              name: 'Number'
            }
          },
          userTypeId: {
            required: false,
            serializedName: 'userTypeId',
            type: {
              name: 'Number'
            }
          },
          schemaId: {
            required: false,
            serializedName: 'schemaId',
            type: {
              name: 'Number'
            }
          },
          principalId: {
            required: false,
            serializedName: 'principalId',
            type: {
              name: 'Number'
            }
          },
          isNullable: {
            required: false,
            serializedName: 'isNullable',
            type: {
              name: 'Boolean'
            }
          },
          isUserDefined: {
            required: false,
            serializedName: 'isUserDefined',
            type: {
              name: 'Boolean'
            }
          },
          isAssemblyType: {
            required: false,
            serializedName: 'isAssemblyType',
            type: {
              name: 'Boolean'
            }
          },
          isTableType: {
            required: false,
            serializedName: 'isTableType',
            type: {
              name: 'Boolean'
            }
          },
          isComplexType: {
            required: false,
            serializedName: 'isComplexType',
            type: {
              name: 'Boolean'
            }
          },
          columns: {
            required: false,
            readOnly: true,
            serializedName: 'columns',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'TypeFieldInfoElementType',
                  type: {
                    name: 'Composite',
                    className: 'TypeFieldInfo'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = USqlTableType;