text:
#include <stdio.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <time.h>
#include <string.h>

#include "ext2_fs.h"
#include "ext2fsP.h"

static int test_root(int a, int b)
{
	if (a == 0)
		return 1;
	while (1) {
		if (a == 1)
			return 1;
		if (a % b)
			return 0;
		a = a / b;
	}
}

int ext2fs_bg_has_super(ext2_filsys fs, int group_block)
{
	if (!(fs->super->s_feature_ro_compat &
	      EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER))
		return 1;

	if (test_root(group_block, 3) || (test_root(group_block, 5)) ||
	    test_root(group_block, 7))
		return 1;

	return 0;
}

/*
 * This function returns the location of the superblock, block group
 * descriptors for a given block group.  It currently returns the
 * number of free blocks assuming that inode table and allocation
 * bitmaps will be in the group.  This is not necessarily the case
 * when the flex_bg feature is enabled, so callers should take care!
 * It was only really intended for use by mke2fs, and even there it's
 * not that useful.  In the future, when we redo this function for
 * 64-bit block numbers, we should probably return the number of
 * blocks used by the super block and group descriptors instead.
 *
 * See also the comment for ext2fs_reserve_super_and_bgd()
 */
int ext2fs_super_and_bgd_loc(ext2_filsys fs,
			     dgrp_t group,
			     blk_t *ret_super_blk,
			     blk_t *ret_old_desc_blk,
			     blk_t *ret_new_desc_blk,
			     int *ret_meta_bg)
{
	blk_t	group_block, super_blk = 0, old_desc_blk = 0, new_desc_blk = 0;
	unsigned int meta_bg, meta_bg_size;
	blk_t	numblocks, old_desc_blocks;
	int	has_super;

	group_block = ext2fs_group_first_block(fs, group);

	if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
		old_desc_blocks = fs->super->s_first_meta_bg;
	else
		old_desc_blocks =
			fs->desc_blocks + fs->super->s_reserved_gdt_blocks;

	if (group == fs->group_desc_count-1) {
		numblocks = (fs->super->s_blocks_count -
			     fs->super->s_first_data_block) %
			fs->super->s_blocks_per_group;
		if (!numblocks)
			numblocks = fs->super->s_blocks_per_group;
	} else
		numblocks = fs->super->s_blocks_per_group;

	has_super = ext2fs_bg_has_super(fs, group);

	if (has_super) {
		super_blk = group_block;
		numblocks--;
	}
	meta_bg_size = EXT2_DESC_PER_BLOCK(fs->super);
	meta_bg = group / meta_bg_size;

	if (!(fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) ||
	    (meta_bg < fs->super->s_first_meta_bg)) {
		if (has_super) {
			old_desc_blk = group_block + 1;
			numblocks -= old_desc_blocks;
		}
	} else {
		if (((group % meta_bg_size) == 0) ||
		    ((group % meta_bg_size) == 1) ||
		    ((group % meta_bg_size) == (meta_bg_size-1))) {
			if (has_super)
				has_super = 1;
			new_desc_blk = group_block + has_super;
			numblocks--;
		}
	}

	numblocks -= 2 + fs->inode_blocks_per_group;

	if (ret_super_blk)
		*ret_super_blk = super_blk;
	if (ret_old_desc_blk)
		*ret_old_desc_blk = old_desc_blk;
	if (ret_new_desc_blk)
		*ret_new_desc_blk = new_desc_blk;
	if (ret_meta_bg)
		*ret_meta_bg = meta_bg;
	return (numblocks);
}

/*
 * This function forces out the primary superblock.  We need to only
 * write out those fields which we have changed, since if the
 * filesystem is mounted, it may have changed some of the other
 * fields.
 *
 * It takes as input a superblock which has already been byte swapped
 * (if necessary).
 *
 */
static errcode_t write_primary_superblock(ext2_filsys fs,
					  struct ext2_super_block *super)
{
	__u16		*old_super, *new_super;
	int		check_idx, write_idx, size;
	errcode_t	retval;

	if (!fs->io->manager->write_byte || !fs->orig_super) {
	fallback:
		io_channel_set_blksize(fs->io, SUPERBLOCK_OFFSET);
		retval = io_channel_write_blk(fs->io, 1, -SUPERBLOCK_SIZE,
					      super);
		io_channel_set_blksize(fs->io, fs->blocksize);
		return retval;
	}

	old_super = (__u16 *) fs->orig_super;
	new_super = (__u16 *) super;

	for (check_idx = 0; check_idx < SUPERBLOCK_SIZE/2; check_idx++) {
		if (old_super[check_idx] == new_super[check_idx])
			continue;
		write_idx = check_idx;
		for (check_idx++; check_idx < SUPERBLOCK_SIZE/2; check_idx++)
			if (old_super[check_idx] == new_super[check_idx])
				break;
		size = 2 * (check_idx - write_idx);
#if 0
		printf("Writing %d bytes starting at %d\n",
		       size, write_idx*2);
#endif
		retval = io_channel_write_byte(fs->io,
			       SUPERBLOCK_OFFSET + (2 * write_idx), size,
					       new_super + write_idx);
		if (retval == EXT2_ET_UNIMPLEMENTED)
			goto fallback;
		if (retval)
			return retval;
	}
	memcpy(fs->orig_super, super, SUPERBLOCK_SIZE);
	return 0;
}

/*
 * Updates the revision to EXT2_DYNAMIC_REV
 */
void ext2fs_update_dynamic_rev(ext2_filsys fs)
{
	struct ext2_super_block *sb = fs->super;

	if (sb->s_rev_level > EXT2_GOOD_OLD_REV)
		return;

	sb->s_rev_level = EXT2_DYNAMIC_REV;
	sb->s_first_ino = EXT2_GOOD_OLD_FIRST_INO;
	sb->s_inode_size = EXT2_GOOD_OLD_INODE_SIZE;
	/* s_uuid is handled by e2fsck already */
	/* other fields should be left alone */
}

static errcode_t write_backup_super(ext2_filsys fs, dgrp_t group,
				    blk_t group_block,
				    struct ext2_super_block *super_shadow)
{
	dgrp_t	sgrp = group;

	if (sgrp > ((1 << 16) - 1))
		sgrp = (1 << 16) - 1;
#ifdef WORDS_BIGENDIAN
	super_shadow->s_block_group_nr = ext2fs_swab16(sgrp);
#else
	fs->super->s_block_group_nr = sgrp;
#endif

	return io_channel_write_blk(fs->io, group_block, -SUPERBLOCK_SIZE,
				    super_shadow);
}

errcode_t ext2fs_flush(ext2_filsys fs)
{
	dgrp_t		i;
	errcode_t	retval;
	unsigned long	fs_state;
	__u32		feature_incompat;
	struct ext2_super_block *super_shadow = 0;
	struct ext2_group_desc *group_shadow = 0;
#ifdef WORDS_BIGENDIAN
	struct ext2_group_desc *s, *t;
	dgrp_t		j;
#endif
	char	*group_ptr;
	int	old_desc_blocks;

	EXT2_CHECK_MAGIC(fs, EXT2_ET_MAGIC_EXT2FS_FILSYS);

	fs_state = fs->super->s_state;
	feature_incompat = fs->super->s_feature_incompat;

	fs->super->s_wtime = fs->now ? fs->now : time(NULL);
	fs->super->s_block_group_nr = 0;
#ifdef WORDS_BIGENDIAN
	retval = EXT2_ET_NO_MEMORY;
	retval = ext2fs_get_mem(SUPERBLOCK_SIZE, &super_shadow);
	if (retval)
		goto errout;
	retval = ext2fs_get_array(fs->desc_blocks, fs->blocksize,
				  &group_shadow);
	if (retval)
		goto errout;
	memset(group_shadow, 0, (size_t) fs->blocksize *
	       fs->desc_blocks);

	/* swap the group descriptors */
	for (j=0, s=fs->group_desc, t=group_shadow;
	     j < fs->group_desc_count; j++, t++, s++) {
		*t = *s;
		ext2fs_swap_group_desc(t);
	}
#else
	super_shadow = fs->super;
	group_shadow = fs->group_desc;
#endif

	/*
	 * Set the state of the FS to be non-valid.  (The state has
	 * already been backed up earlier, and will be restored after
	 * we write out the backup superblocks.)
	 */
	fs->super->s_state &= ~EXT2_VALID_FS;
	fs->super->s_feature_incompat &= ~EXT3_FEATURE_INCOMPAT_RECOVER;
#ifdef WORDS_BIGENDIAN
	*super_shadow = *fs->super;
	ext2fs_swap_super(super_shadow);
#endif

	/*
	 * If this is an external journal device, don't write out the
	 * block group descriptors or any of the backup superblocks
	 */
	if (fs->super->s_feature_incompat &
	    EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)
		goto write_primary_superblock_only;

	/*
	 * Write out the master group descriptors, and the backup
	 * superblocks and group descriptors.
	 */
	group_ptr = (char *) group_shadow;
	if (fs->super->s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG)
		old_desc_blocks = fs->super->s_first_meta_bg;
	else
		old_desc_blocks = fs->desc_blocks;

	for (i = 0; i < fs->group_desc_count; i++) {
		blk_t	super_blk, old_desc_blk, new_desc_blk;
		int	meta_bg;

		ext2fs_super_and_bgd_loc(fs, i, &super_blk, &old_desc_blk,
					 &new_desc_blk, &meta_bg);

		if (!(fs->flags & EXT2_FLAG_MASTER_SB_ONLY) &&i && super_blk) {
			retval = write_backup_super(fs, i, super_blk,
						    super_shadow);
			if (retval)
				goto errout;
		}
		if (fs->flags & EXT2_FLAG_SUPER_ONLY)
			continue;
		if ((old_desc_blk) &&
		    (!(fs->flags & EXT2_FLAG_MASTER_SB_ONLY) || (i == 0))) {
			retval = io_channel_write_blk(fs->io,
			      old_desc_blk, old_desc_blocks, group_ptr);
			if (retval)
				goto errout;
		}
		if (new_desc_blk) {
			retval = io_channel_write_blk(fs->io, new_desc_blk,
				1, group_ptr + (meta_bg*fs->blocksize));
			if (retval)
				goto errout;
		}
	}

	/*
	 * If the write_bitmaps() function is present, call it to
	 * flush the bitmaps.  This is done this way so that a simple
	 * program that doesn't mess with the bitmaps doesn't need to
	 * drag in the bitmaps.c code.
	 */
	if (fs->write_bitmaps) {
		retval = fs->write_bitmaps(fs);
		if (retval)
			goto errout;
	}

write_primary_superblock_only:
	/*
	 * Write out master superblock.  This has to be done
	 * separately, since it is located at a fixed location
	 * (SUPERBLOCK_OFFSET).  We flush all other pending changes
	 * out to disk first, just to avoid a race condition with an
	 * insy-tinsy window....
	 */

	fs->super->s_block_group_nr = 0;
	fs->super->s_state = fs_state;
	fs->super->s_feature_incompat = feature_incompat;
#ifdef WORDS_BIGENDIAN
	*super_shadow = *fs->super;
	ext2fs_swap_super(super_shadow);
#endif

	retval = io_channel_flush(fs->io);
	retval = write_primary_superblock(fs, super_shadow);
	if (retval)
		goto errout;

	fs->flags &= ~EXT2_FLAG_DIRTY;

	retval = io_channel_flush(fs->io);
errout:
	fs->super->s_state = fs_state;
#ifdef WORDS_BIGENDIAN
	if (super_shadow)
		ext2fs_free_mem(&super_shadow);
	if (group_shadow)
		ext2fs_free_mem(&group_shadow);
#endif
	return retval;
}

errcode_t ext2fs_close(ext2_filsys fs)
{
	errcode_t	retval;
	int		meta_blks;
	io_stats stats = 0;

	EXT2_CHECK_MAGIC(fs, EXT2_ET_MAGIC_EXT2FS_FILSYS);

	if (fs->write_bitmaps) {
		retval = fs->write_bitmaps(fs);
		if (retval)
			return retval;
	}
	if (fs->super->s_kbytes_written &&
	    fs->io->manager->get_stats)
		fs->io->manager->get_stats(fs->io, &stats);
	if (stats && stats->bytes_written && (fs->flags & EXT2_FLAG_RW)) {
		fs->super->s_kbytes_written += stats->bytes_written >> 10;
		meta_blks = fs->desc_blocks + 1;
		if (!(fs->flags & EXT2_FLAG_SUPER_ONLY))
			fs->super->s_kbytes_written += meta_blks /
				(fs->blocksize / 1024);
		if ((fs->flags & EXT2_FLAG_DIRTY) == 0)
			fs->flags |= EXT2_FLAG_SUPER_ONLY | EXT2_FLAG_DIRTY;
	}
	if (fs->flags & EXT2_FLAG_DIRTY) {
		retval = ext2fs_flush(fs);
		if (retval)
			return retval;
	}
	ext2fs_free(fs);
	return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Blip;

namespace Blip.TestServer
{
    ///
    /// Little test for the Blip websocket server.
    ///
    class Program
    {
        /// Server reference.
        public static BlipWebSocket blip;

        /// Application entrypoint
        public static void Main(string[] args)
        {
            // Create a new Blip websocket server.
            blip = new BlipWebSocket("ws://0.0.0.0:9224");

            // Register a few RPC functions.
            blip.Register("Test.Hello", (Func<String>)Hello);
            blip.Register("Test.Increment", (Func<long, long>)Increment);

            // Register an RPC function on an instance.
            var svc = new Service();
            blip.Register("Test.Service.Names", (Func<List<String>>)svc.ComputeNames);
            blip.Register("Test.ThrowError", (Action)svc.Error);

            // Wait.
            Console.ReadKey();
        }

        /// Publish server settings and return some arbitary text.
        public static String Hello()
        {
            blip.Publish("Test.Settings", 1, 2, new List<String>() { "Hello", "Subscribers", "Here", "Are", "Settings" });
            return "Hello World";
        }

        /// Add one number to another and return the result.
        public static long Increment(long a)
        {
            return a + 1;
        }
    }

    ///
    /// Demonstrates Blip running on an instance.
    ///
    public class Service
    {
        ///
        /// Get some names.
        ///
        /// <returns></returns>
        public List<String> ComputeNames()
        {
            return new List<string>(){"Bob", "Sally", "Lizzy"};
        }

        ///
        /// Throw an error.
        ///
        public void Error()
        {
            throw new Exception("Intentional Test Error");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).

package com.twitter.intellij.pants.integration;

import com.intellij.execution.process.OSProcessHandler;
import com.intellij.util.ArrayUtil;
import com.twitter.intellij.pants.execution.PantsExecuteTaskResult;
import com.twitter.intellij.pants.testFramework.OSSPantsIntegrationTest;

public class OSSPantsTestExamplesIntegrationTest extends OSSPantsIntegrationTest {
  @Override
  protected String[] getRequiredPluginIds() {
    return ArrayUtil.append(super.getRequiredPluginIds(), "JUnit");
  }

  public void testJUnitTests() throws Throwable {
    doImport("intellij-integration/tests/java/org/pantsbuild/testprojects");

    assertFirstSourcePartyModules("intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects");

    PantsExecuteTaskResult result = pantsCompileModule("intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects");
    assertPantsCompileExecutesAndSucceeds(result);
    assertTrue(result.output.isPresent());
    assertTrue(result.output.get().contains("compile intellij-integration/tests/java/org/pantsbuild/testprojects:testprojects"));
    assertSuccessfulTest(
      "intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects", "org.pantsbuild.testprojects.JUnitIntegrationTest");
    final OSProcessHandler processHandler = runJUnitTest(
      "intellij-integration_tests_java_org_pantsbuild_testprojects_testprojects",
      "org.pantsbuild.testprojects.JUnitIntegrationTest",
      "-DPANTS_FAIL_TEST=true"
    );
    assertTrue("Tests should fail!", processHandler.getProcess().exitValue() != 0);
  }

  public void testScopedJUnitTests() throws Throwable {
    /**
     * Import 3 targets:
     * testprojects/tests/java/org/pantsbuild/testproject/dummies:passing_target
     * testprojects/tests/java/org/pantsbuild/testproject/dummies:failing_target
     * testprojects/tests/java/org/pantsbuild/testproject/matcher:matcher
     */
    doImport("testprojects/tests/java/org/pantsbuild/testproject/matcher");
    doImport("testprojects/tests/java/org/pantsbuild/testproject/dummies");

    String passingTarget = "testprojects/tests/java/org/pantsbuild/testproject/dummies:passing_target";
    String failingTarget = "testprojects/tests/java/org/pantsbuild/testproject/dummies:failing_target";
    String matcherTarget = "testprojects/tests/java/org/pantsbuild/testproject/matcher:matcher";

    PantsExecuteTaskResult result = pantsCompileModule("testprojects_tests_java_org_pantsbuild_testproject_matcher_matcher");
    assertPantsCompileExecutesAndSucceeds(result);
    assertTrue(result.output.isPresent());
    String output = result.output.get();
    // Make sure only matcher target is compiled
    assertContainsSubstring(output, matcherTarget);
    assertNotContainsSubstring(output, passingTarget);
    assertNotContainsSubstring(output, failingTarget);

    assertSuccessfulTest(
      "testprojects_tests_java_org_pantsbuild_testproject_matcher_matcher",
      "org.pantsbuild.testproject.matcher.MatcherTest"
    );

    // Make sure only the 2 dummies targets are compiled.
    PantsExecuteTaskResult resultB = pantsCompileModule("testprojects_tests_java_org_pantsbuild_testproject_dummies_common_sources");
    String outputB = resultB.output.get();
    assertContainsSubstring(outputB, passingTarget);
    assertContainsSubstring(outputB, failingTarget);
    assertNotContainsSubstring(outputB, matcherTarget);

    // makeProject() will result all 3 targets to be compiled.
    PantsExecuteTaskResult resultC = pantsCompileProject();
    assertPantsCompileExecutesAndSucceeds(resultC);
    String outputC = resultC.output.get();
    assertContainsSubstring(outputC, passingTarget);
    assertContainsSubstring(outputC, failingTarget);
    assertContainsSubstring(outputC, matcherTarget);
  }
}


text:
var App = require('app');

require('views/main/dashboard/widget');
require('views/main/dashboard/widgets/text_widget');
require('views/main/dashboard/widgets/hawqsegment_live');

var view;

function testCounterOrNa(propertyName, dependentKey) {
  describe('#' + propertyName, function () {

    beforeEach(function () {
      view.reopen({
        model: Em.Object.create()
      });
      view.get('model').set(dependentKey, []);
    });

    it('n/a (1)', function () {
      view.get('model').set(dependentKey, null);
      expect(view.get(propertyName)).to.be.equal(Em.I18n.t('services.service.summary.notAvailable'));
    });

    it('n/a (2)', function () {
      view.get('model').set(dependentKey, undefined);
      expect(view.get(propertyName)).to.be.equal(Em.I18n.t('services.service.summary.notAvailable'));
    });

    it('value exist', function () {
      view.get('model').set(dependentKey, 123);
      expect(view.get(propertyName)).to.be.equal(123);
    });

  });
}

describe('App.HawqSegmentUpView', function() {

  beforeEach(function () {
    view = App.HawqSegmentUpView.create();
  });

  testCounterOrNa('hawqSegmentsStarted', 'hawqSegmentsStarted');
  testCounterOrNa('hawqSegmentsInstalled', 'hawqSegmentsInstalled');
  testCounterOrNa('hawqSegmentsStarted', 'hawqSegmentsStarted');

});


text:
import os
import time
import itertools

from invoke import run

import textwrap
from colored import fg, attr

try:
    from docker import Client
except ImportError:
    from docker import APIClient as Client
import netaddr

DEFAULT_TEST_PREFIX = ''
DEFAULT_TEST_BASE_DIR = '/tmp/gobgp'
TEST_PREFIX = DEFAULT_TEST_PREFIX
TEST_BASE_DIR = DEFAULT_TEST_BASE_DIR

BGP_FSM_IDLE = 'idle'
BGP_FSM_ACTIVE = 'active'
BGP_FSM_ESTABLISHED = 'established'

BGP_ATTR_TYPE_ORIGIN = 1
BGP_ATTR_TYPE_AS_PATH = 2
BGP_ATTR_TYPE_NEXT_HOP = 3
BGP_ATTR_TYPE_MULTI_EXIT_DISC = 4
BGP_ATTR_TYPE_LOCAL_PREF = 5
BGP_ATTR_TYPE_COMMUNITIES = 8
BGP_ATTR_TYPE_ORIGINATOR_ID = 9
BGP_ATTR_TYPE_CLUSTER_LIST = 10
BGP_ATTR_TYPE_MP_REACH_NLRI = 14
BGP_ATTR_TYPE_EXTENDED_COMMUNITIES = 16

GRACEFUL_RESTART_TIME = 30
LONG_LIVED_GRACEFUL_RESTART_TIME = 30

FLOWSPEC_NAME_TO_TYPE = {
    "destination": 1,
    "source": 2,
    "protocol": 3,
    "port": 4,
    "destination-port": 5,
    "source-port": 6,
    "icmp-type": 7,
    "icmp-code": 8,
    "tcp-flags": 9,
    "packet-length": 10,
    "dscp": 11,
    "fragment": 12,
    "label": 13,
    "ether-type": 14,
    "source-mac": 15,
    "destination-mac": 16,
    "llc-dsap": 17,
    "llc-ssap": 18,
    "llc-control": 19,
    "snap": 20,
    "vid": 21,
    "cos": 22,
    "inner-vid": 23,
    "inner-cos": 24,
}

# with this label, we can do filtering in `docker ps` and `docker network prune`
TEST_CONTAINER_LABEL = 'gobgp-test'
TEST_NETWORK_LABEL = TEST_CONTAINER_LABEL

def local(s, capture=False):
    print('[localhost] local:', s)
    _env = {'NOSE_NOLOGCAPTURE': '1' if capture else '0'}
    return run(s, hide=True, env=_env).stdout.strip()

def yellow(s):
    return fg('yellow') + str(s) + attr('reset')

def indent(s):
    return textwrap.indent(str(s), ' '*4, lambda line: True)

def community_str(i):
    """
    Converts integer in to colon separated two bytes decimal strings like
    BGP Community or Large Community representation.

    For example, this function converts 13107300 = ((200 << 16) | 100)
    into "200:100".
    """
    values = []
    while i > 0:
        values.append(str(i & 0xffff))
        i >>= 16
    return ':'.join(reversed(values))

def wait_for_completion(f, timeout=120):
    interval = 1
    count = 0
    while True:
        if f():
            return

        time.sleep(interval)
        count += interval
        if count >= timeout:
            raise Exception('timeout')

def try_several_times(f, t=3, s=1):
    e = Exception
    for _ in range(t):
        try:
            r = f()
        except RuntimeError as e:
            time.sleep(s)
        else:
            return r
    raise e

def assert_several_times(f, t=30, s=1):
    e = AssertionError
    for _ in range(t):
        try:
            f()
        except AssertionError as e:
            time.sleep(s)
        else:
            return
    raise e

def get_bridges():
    return try_several_times(lambda: local("docker network ls | awk 'NR > 1{print $2}'", capture=True)).split('\n')

def get_containers():
    return try_several_times(lambda: local("docker ps -a | awk 'NR > 1 {print $NF}'", capture=True)).split('\n')

class CmdBuffer(list):
    def __init__(self, delim='\n'):
        super(CmdBuffer, self).__init__()
        self.delim = delim

    def __lshift__(self, value):
        self.append(value)

    def __str__(self):
        return self.delim.join(self)

class Bridge(object):
    def __init__(self, name, subnet='', with_ip=True, self_ip=False):
        self.name = name
        if TEST_PREFIX != '':
            self.name = '{0}_{1}'.format(TEST_PREFIX, name)
        self.with_ip = with_ip
        if with_ip:
            self.subnet = netaddr.IPNetwork(subnet)

            def _f():
                for host in self.subnet:
                    yield host
            self._ip_generator = _f()
            # throw away first network address
            self.next_ip_address()

        def f():
            if self.name in get_bridges():
                self.delete()
            v6 = ''
            if self.subnet.version == 6:
                v6 = '--ipv6'
            self.id = local('docker network create --driver bridge {0} --subnet {1} --label {2} {3}'.format(v6, subnet, TEST_NETWORK_LABEL, self.name), capture=True)
        try_several_times(f)

        self.self_ip = self_ip
        if self_ip:
            self.ip_addr = self.next_ip_address()
            try_several_times(lambda: local("ip addr add {0} dev {1}".format(self.ip_addr, self.name)))
        self.ctns = []

        # Note: Here removes routes from the container host to prevent traffic
        # from going through the container host's routing table.
        if with_ip:
            local('ip route del {0}; echo $?'.format(subnet),
                  capture=True)
            # When IPv6, 2 routes will be installed to the container host's
            # routing table.
            if self.subnet.version == 6:
                local('ip -6 route del {0}; echo $?'.format(subnet),
                      capture=True)

    def next_ip_address(self):
        return "{0}/{1}".format(next(self._ip_generator),
                                self.subnet.prefixlen)

    def addif(self, ctn, ip_addr=''):
        _name = ctn.next_if_name()
        self.ctns.append(ctn)
        ip = ''
        if not ip_addr == '':
            ip = '--ip {0}'.format(ip_addr)
            if self.subnet.version == 6:
                ip = '--ip6 {0}'.format(ip_addr)
        local("docker network connect {0} {1} {2}".format(ip, self.name, ctn.docker_name()))
        i = [x for x in list(Client(timeout=60, version='auto').inspect_network(self.id)['Containers'].values()) if x['Name'] == ctn.docker_name()][0]
        if self.subnet.version == 4:
            eth = 'eth{0}'.format(len(ctn.ip_addrs))
            addr = i['IPv4Address']
            ctn.ip_addrs.append((eth, addr, self.name))
        else:
            eth = 'eth{0}'.format(len(ctn.ip6_addrs))
            addr = i['IPv6Address']
            ctn.ip6_addrs.append((eth, addr, self.name))

    def delete(self):
        try_several_times(lambda: local("docker network rm {0}".format(self.name)))

class Container(object):
    def __init__(self, name, image):
        self.name = name
        self.image = image
        self.shared_volumes = []
        self.ip_addrs = []
        self.ip6_addrs = []
        self.is_running = False
        self.eths = []
        self.tcpdump_running = False

        if self.docker_name() in get_containers():
            self.remove()

    def docker_name(self):
        if TEST_PREFIX == DEFAULT_TEST_PREFIX:
            return '{0}'.format(self.name)
        return '{0}_{1}'.format(TEST_PREFIX, self.name)

    def next_if_name(self):
        name = 'eth{0}'.format(len(self.eths) + 1)
        self.eths.append(name)
        return name

    def run(self):
        c = CmdBuffer(' ')
        c << "docker run --privileged=true"
        for sv in self.shared_volumes:
            c << "-v {0}:{1}".format(sv[0], sv[1])
        c << "--name {0} -l {1} -id {2}".format(self.docker_name(), TEST_CONTAINER_LABEL, self.image)
        self.id = try_several_times(lambda: local(str(c), capture=True))
        self.is_running = True
        self.local("ip li set up dev lo")
        for line in self.local("ip a show dev eth0", capture=True).split('\n'):
            if line.strip().startswith("inet "):
                elems = [e.strip() for e in line.strip().split(' ')]
                self.ip_addrs.append(('eth0', elems[1], 'docker0'))
            elif line.strip().startswith("inet6 "):
                elems = [e.strip() for e in line.strip().split(' ')]
                self.ip6_addrs.append(('eth0', elems[1], 'docker0'))
        return 0

    def stop(self):
        ret = try_several_times(lambda: local("docker stop -t 0 " + self.docker_name(), capture=True))
        self.is_running = False
        return ret

    def remove(self):
        ret = try_several_times(lambda: local("docker rm -f " + self.docker_name(), capture=True))
        self.is_running = False
        return ret

    def local(self, cmd, capture=False, stream=False, detach=False, tty=True):
        if stream:
            dckr = Client(timeout=120, version='auto')
            i = dckr.exec_create(container=self.docker_name(), cmd=cmd)
            return dckr.exec_start(i['Id'], tty=tty, stream=stream, detach=detach)
        else:
            flag = '-d' if detach else ''
            return local('docker exec {0} {1} {2}'.format(flag, self.docker_name(), cmd), capture)

    def get_pid(self):
        if self.is_running:
            cmd = "docker inspect -f '{{.State.Pid}}' " + self.docker_name()
            return int(local(cmd, capture=True))
        return -1

    def start_tcpdump(self, interface=None, filename=None, expr='tcp port 179'):
        if self.tcpdump_running:
            raise Exception('tcpdump already running')
        self.tcpdump_running = True
        if not interface:
            interface = "eth0"
        if not filename:
            filename = '{0}.dump'.format(interface)
        self.local("tcpdump -U -i {0} -w {1}/{2} {3}".format(interface, self.shared_volumes[0][1], filename, expr), detach=True)
        return '{0}/{1}'.format(self.shared_volumes[0][0], filename)

    def stop_tcpdump(self):
        self.local("pkill tcpdump")
        self.tcpdump_running = False

class BGPContainer(Container):

    WAIT_FOR_BOOT = 1
    RETRY_INTERVAL = 5

    def __init__(self, name, asn, router_id, ctn_image_name):
        self.config_dir = '/'.join((TEST_BASE_DIR, TEST_PREFIX, name))
        local('if [ -e {0} ]; then rm -rf {0}; fi'.format(self.config_dir))
        local('mkdir -p {0}'.format(self.config_dir))
        local('chmod 777 {0}'.format(self.config_dir))
        self.asn = asn
        self.router_id = router_id
        self.peers = {}
        self.routes = {}
        self.policies = {}
        super(BGPContainer, self).__init__(name, ctn_image_name)

    def __repr__(self):
        return str({'name': self.name, 'asn': self.asn, 'router_id': self.router_id})

    def run(self):
        self.create_config()
        super(BGPContainer, self).run()
        return self.WAIT_FOR_BOOT

    def peer_name(self, peer):
        if peer not in self.peers:
            raise Exception('not found peer {0}'.format(peer.router_id))
        name = self.peers[peer]['interface']
        if name == '':
            name = self.peers[peer]['neigh_addr'].split('/')[0]
        return name

    def update_peer(self, peer, **kwargs):
        if peer not in self.peers:
            raise Exception('peer not exists')
        self.add_peer(peer, **kwargs)

    def add_peer(self, peer, passwd=None, vpn=False, is_rs_client=False,
                 policies=None, passive=False,
                 is_rr_client=False, cluster_id=None,
                 flowspec=False, bridge='', reload_config=True, as2=False,
                 graceful_restart=None, local_as=None, prefix_limit=None,
                 v6=False, llgr=None, vrf='', interface='', allow_as_in=0,
                 remove_private_as=None, replace_peer_as=False, addpath=False,
                 treat_as_withdraw=False, remote_as=None, mup=False):
        neigh_addr = ''
        local_addr = ''
        it = itertools.product(self.ip_addrs, peer.ip_addrs)
        if v6:
            it = itertools.product(self.ip6_addrs, peer.ip6_addrs)

        if interface == '':
            for me, you in it:
                if bridge != '' and bridge != me[2]:
                    continue
                if me[2] == you[2]:
                    neigh_addr = you[1]
                    local_addr = me[1]
                    if v6:
                        addr, mask = local_addr.split('/')
                        local_addr = "{0}%{1}/{2}".format(addr, me[0], mask)
                    break

            if neigh_addr == '':
                raise Exception('peer {0} seems not ip reachable'.format(peer))

        if not policies:
            policies = {}

        self.peers[peer] = {'neigh_addr': neigh_addr,
                            'interface': interface,
                            'passwd': passwd,
                            'vpn': vpn,
                            'flowspec': flowspec,
                            'is_rs_client': is_rs_client,
                            'is_rr_client': is_rr_client,
                            'cluster_id': cluster_id,
                            'policies': policies,
                            'passive': passive,
                            'local_addr': local_addr,
                            'as2': as2,
                            'graceful_restart': graceful_restart,
                            'local_as': local_as,
                            'prefix_limit': prefix_limit,
                            'llgr': llgr,
                            'vrf': vrf,
                            'allow_as_in': allow_as_in,
                            'remove_private_as': remove_private_as,
                            'replace_peer_as': replace_peer_as,
                            'addpath': addpath,
                            'treat_as_withdraw': treat_as_withdraw,
                            'remote_as': remote_as or peer.asn,
                            'mup': mup}
        if self.is_running and reload_config:
            self.create_config()
            self.reload_config()

    def del_peer(self, peer, reload_config=True):
        del self.peers[peer]
        if self.is_running and reload_config:
            self.create_config()
            self.reload_config()

    def disable_peer(self, peer):
        raise Exception('implement disable_peer() method')

    def enable_peer(self, peer):
        raise Exception('implement enable_peer() method')

    def log(self):
        return local('cat {0}/*.log'.format(self.config_dir), capture=True)

    def _extract_routes(self, families):
        routes = {}
        for prefix, paths in list(self.routes.items()):
            if paths and paths[0]['rf'] in families:
                routes[prefix] = paths
        return routes

    def add_route(self, route, rf='ipv4', attribute=None, aspath=None,
                  community=None, med=None, extendedcommunity=None,
                  nexthop=None, matchs=None, thens=None,
                  local_pref=None, identifier=None, reload_config=True):
        if route not in self.routes:
            self.routes[route] = []
        prefix = route
        if 'flowspec' in rf:
            prefix = ' '.join(['match'] + matchs)
        self.routes[route].append({
            'prefix': prefix,
            'rf': rf,
            'attr': attribute,
            'next-hop': nexthop,
            'as-path': aspath,
            'community': community,
            'med': med,
            'local-pref': local_pref,
            'extended-community': extendedcommunity,
            'identifier': identifier,
            'matchs': matchs,
            'thens': thens,
        })
        if self.is_running and reload_config:
            self.create_config()
            self.reload_config()

    def del_route(self, route, identifier=None, reload_config=True):
        if route not in self.routes:
            return
        self.routes[route] = [p for p in self.routes[route] if p['identifier'] != identifier]
        if self.is_running and reload_config:
            self.create_config()
            self.reload_config()

    def add_policy(self, policy, peer, typ, default='accept', reload_config=True):
        self.set_default_policy(peer, typ, default)
        self.define_policy(policy)
        self.assign_policy(peer, policy, typ)
        if self.is_running and reload_config:
            self.create_config()
            self.reload_config()

    def set_default_policy(self, peer, typ, default):
        if typ in ['in', 'out', 'import', 'export'] and default in ['reject', 'accept']:
            if 'default-policy' not in self.peers[peer]:
                self.peers[peer]['default-policy'] = {}
            self.peers[peer]['default-policy'][typ] = default
        else:
            raise Exception('wrong type or default')

    def define_policy(self, policy):
        self.policies[policy['name']] = policy

    def assign_policy(self, peer, policy, typ):
        if peer not in self.peers:
            raise Exception('peer {0} not found'.format(peer.name))
        name = policy['name']
        if name not in self.policies:
            raise Exception('policy {0} not found'.format(name))
        self.peers[peer]['policies'][typ] = policy

    def get_local_rib(self, peer, rf):
        raise Exception('implement get_local_rib() method')

    def get_global_rib(self, rf):
        raise Exception('implement get_global_rib() method')

    def get_neighbor_state(self, peer_id):
        raise Exception('implement get_neighbor() method')

    def get_reachability(self, prefix, timeout=20):
        version = netaddr.IPNetwork(prefix).version
        addr = prefix.split('/')[0]
        if version == 4:
            ping_cmd = 'ping'
        elif version == 6:
            ping_cmd = 'ping6'
        else:
            raise Exception('unsupported route family: {0}'.format(version))
        cmd = '/bin/bash -c "/bin/{0} -c 1 -w 1 {1} | xargs echo"'.format(ping_cmd, addr)
        interval = 1
        count = 0
        while True:
            res = self.local(cmd, capture=True)
            print(yellow(res))
            if ('1 packets received' in res or '1 received' in res) and '0% packet loss' in res:
                break
            time.sleep(interval)
            count += interval
            if count >= timeout:
                raise Exception('timeout')
        return True

    def wait_for(self, expected_state, peer, timeout=120):
        interval = 1
        count = 0
        while True:
            state = self.get_neighbor_state(peer)
            print(yellow("{0}'s peer {1} state: {2}".format(self.router_id,
                                                            peer.router_id,
                                                            state)))
            if state == expected_state:
                return

            time.sleep(interval)
            count += interval
            if count >= timeout:
                raise Exception('timeout')

    def add_static_route(self, network, next_hop):
        cmd = '/sbin/ip route add {0} via {1}'.format(network, next_hop)
        self.local(cmd, capture=True)

    def set_ipv6_forward(self):
        cmd = 'sysctl -w net.ipv6.conf.all.forwarding=1'
        self.local(cmd, capture=True)

    def create_config(self):
        raise Exception('implement create_config() method')

    def reload_config(self):
        raise Exception('implement reload_config() method')

class OSPFContainer(Container):
    WAIT_FOR_BOOT = 1

    def __init__(self, name, ctn_image_name):
        self.config_dir = '/'.join((TEST_BASE_DIR, TEST_PREFIX, name))
        local('if [ -e {0} ]; then rm -rf {0}; fi'.format(self.config_dir))
        local('mkdir -p {0}'.format(self.config_dir))
        local('chmod 777 {0}'.format(self.config_dir))

        # Example:
        # networks = {
        #     '192.168.1.0/24': '0.0.0.0',  # <network>: <area>
        # }
        self.networks = {}
        super(OSPFContainer, self).__init__(name, ctn_image_name)

    def __repr__(self):
        return str({'name': self.name, 'networks': self.networks})

    def run(self):
        self.create_config()
        super(OSPFContainer, self).run()
        return self.WAIT_FOR_BOOT

    def create_config(self):
        raise NotImplementedError


text:
package com.sfsu.entities.response;

/**
 * Wrapper for Activities and Observation count
 * <p/>
 * Created by Pavitra on 5/13/2016.
 */
public class CombinedCount {
    /**
     * Holds counts for total Activities and Observations
     */
    public int activitiesCount;
    public int observationsCount;
}


text:
namespace Gu.Reactive
{
    using System.Reflection;

    /// <summary>
    /// A wrapper around a delegate created from a <see cref="PropertyInfo.GetMethod"/>.
    /// </summary>
    /// <typeparam name="TSource">The source type.</typeparam>
    /// <typeparam name="TValue">The property type.</typeparam>
    public interface IGetter<in TSource, TValue>
    {
        /// <summary>
        /// Get the value of the property for <paramref name="source"/>.
        /// </summary>
        /// <param name="source">The source value.</param>
        /// <returns>The property value.</returns>
        TValue GetValue(TSource source);

        /// <summary>
        /// Get the value of the property for <paramref name="source"/>.
        /// </summary>
        /// <param name="source">The source value.</param>
        /// <returns>A <see cref="Maybe{TValue}"/>.</returns>
        Maybe<TValue> GetMaybe(TSource source);
    }
}


text:
namespace LIGHTING
{
	enum GRAPHICSDLL_API LIGHT_TYPE
	{
		LT_POINT,
		LT_DIRECTIONAL,
		LT_AREA,
		LT_SPOT,

		NUM_LT
	};

	//struct LightBufferData
	//{
	//	UINT NUM_POINTLIGHTS;
	//	UINT NUM_AREALIGHTS;
	//	UINT NUM_DIRECTIONALLIGHTS;
	//	UINT NUM_SPOTLIGHTS;
	//	float AMBIENT_COLOR[3]  = { 1.0f,1.0f,1.0f };
	//	float AMBIENT_INTENSITY = 0.2f;
	//
	//};

	struct GRAPHICSDLL_API LightColor
	{
		float r = 1.0f;
		float g = 1.0f;
		float b = 1.0f;

	};
	struct GRAPHICSDLL_API LightFalloff
	{
		float constant = 1.0f, linear  =1.0f, quadratic = 1.0f;
	};

	struct GRAPHICSDLL_API Light // Any changes to these structs need to be made in the shader
	{
		BOOL isActive = TRUE; //16 bit aligned

		BOOL padding[3];	  //16 bit aligned
		LightColor color;
		float intensity = 1.0f;
		DirectX::XMVECTOR position;

		 void* operator new(size_t i) { return _aligned_malloc(i, 16); };
		 void* operator new[](size_t i) { return _aligned_malloc(i, 16); };
		 void operator delete[](void* p) { _aligned_free(p); };
		 void operator delete(void* p) { _aligned_free(p); };
	};

	struct GRAPHICSDLL_API Point : Light
	{
		float radius = 10.0f;
		LightFalloff falloff;
	};

	struct GRAPHICSDLL_API Area : Light
	{
		DirectX::XMVECTOR direction;
		DirectX::XMVECTOR up;
		DirectX::XMVECTOR right;

		LightFalloff falloff;

		float width;
		float height;
		void* operator new(size_t i) { return _aligned_malloc(i, 16); };
		void operator delete(void* p) { _aligned_free(p); };
	};

	struct GRAPHICSDLL_API Directional : Light
	{
		DirectX::XMVECTOR direction;
		void* operator new(size_t i) { return _aligned_malloc(i, 16); };
		void operator delete(void* p) { _aligned_free(p); };
	};

	struct GRAPHICSDLL_API Spot : Light
	{
		DirectX::XMVECTOR direction;
		LightFalloff falloff;
		//cone stuff here
		float range, cone, pad;
		void* operator new(size_t i) { return _aligned_malloc(i, 16); };
		void operator delete(void* p) { _aligned_free(p); };
	};

}

#endif


text:
layout: post
slug: mini-zgphp-conference-extra-week-on-call-for-paper-deadline
title: Mini ZgPHP conference, extra week on call for paper deadline
tags:
    -konferencija
---

We got requests to prolong our call for paper deadline, so we added an extra
week. Call for papers will be opened till August 25th, 2013 and please contact
us by e-mail on zgphpmeetup [at] gmail [dot] com with title, short abstract and
your biography.

**UPDATE:** [Our conference site is up, click here.](http://2013.zgphp.org/)


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="trip" class="transitdata.io.domain.Trip" scope="prototype"/>

    <bean id="tripItemReader"
          class="org.springframework.batch.item.file.FlatFileItemReader">
        <property name="resource" value="${resourceBase}/trips.txt"/>

        <property name="linesToSkip" value="1"/>
        <property name="skippedLinesCallback" ref="headerHandler"/>

        <property name="lineMapper">
            <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                <!-- split it -->
                <property name="lineTokenizer" ref="lineTokenizer"/>

                <!-- map to an object -->
                <property name="fieldSetMapper">
                    <bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
                        <property name="prototypeBeanName" value="trip"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <bean id="tripItemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
        <property name="dataSource" ref="dataSource"/>
        <property name="sql">
            <value>
                <![CDATA[
                    INSERT INTO trip(
                     transit_system,route_id,service_id,trip_id,trip_headsign,trip_short_name,direction_id,block_id,shape_id,wheelchair_accessible,bikes_allowed
                    )
                    VALUES(
                     'METRO_TRANSIT',:route_id,:service_id,:trip_id,:trip_headsign,:trip_short_name,:direction_id,:block_id,:shape_id,:wheelchair_accessible,:bikes_allowed
                    );
                ]]>
            </value>
        </property>
        <property name="itemSqlParameterSourceProvider">
            <bean class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
        </property>
    </bean>

</beans>


text:
<?php
namespace Elementor;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Control_Order extends Control_Base_Multiple {

	public function get_type() {
		return 'order';
	}

	public function get_default_value() {
		return [
			'order_by' => '',
			'reverse_order' => '',
		];
	}

	public function content_template() {
		?>

			{{{ data.label }}}

					<select data-setting="order_by">
						<# _.each( data.options, function( option_title, option_value ) { #>
							<option value="{{ option_value }}">{{{ option_title }}}</option>
							<# } ); #>
					</select>
					<input id="elementor-control-order-input-{{ data._cid }}" type="checkbox" data-setting="reverse_order">

		<# if ( data.description ) { #>

{{{ data.description }}}

		<# } #>
		<?php
	}
}


text:
[https://github.com/rtorr/angular-bootstrap](https://github.com/rtorr/angular-bootstrap)

Install grunt

    npm install -g grunt-cli

    or to use the project copy

    ./node_modules/grunt-cli/bin/grunt

Install bower (version 1.2.x or higher)

    npm install -g bower

    or to use the project copy

    ./node_modules/bower/bin/bower install

Get Dependencies

    npm install && bower install

### Run dev server:

    grunt server

### Build

Build files currently end up in the `out` directory

    grunt

### Test

Unit

    grunt test

End to End

    grunt test-e2e

## Documentation

TODO


text:
package api

import (
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"testing"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/validation"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/fielderrors"
)

func TestCompatibility_v1_Pod(t *testing.T) {
	// Test "spec.host" -> "spec.nodeName"
	expectedHost := "my-host"
	// Test "spec.serviceAccount" -> "spec.serviceAccountName"
	expectedServiceAccount := "my-service-account"
	// Test "tcp" protocol gets converted to "TCP" and validated
	originalProtocol := "tcp"
	expectedProtocol := "TCP"

	input := []byte(fmt.Sprintf(`
{
	"kind":"Pod",
	"apiVersion":"v1",
	"metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"},
	"spec": {
		"host":"%s",
		"serviceAccount":"%s",
		"containers":[{
			"name":"my-container-name",
			"image":"my-container-image",
			"ports":[{"containerPort":1,"protocol":"%s"}]
		}]
	}
}
`, expectedHost, expectedServiceAccount, originalProtocol))

	t.Log("Testing 1.0.0 v1 migration added in PR #3592")
	testCompatibility(
		t, "v1", input,
		func(obj runtime.Object) fielderrors.ValidationErrorList {
			return validation.ValidatePod(obj.(*api.Pod))
		},
		map[string]string{
			"spec.host":     expectedHost,
			"spec.nodeName": expectedHost,

			"spec.serviceAccount":     expectedServiceAccount,
			"spec.serviceAccountName": expectedServiceAccount,

			"spec.containers[0].ports[0].protocol": expectedProtocol,
		},
	)
}

func TestCompatibility_v1_Service(t *testing.T) {
	// Test "spec.portalIP" -> "spec.clusterIP"
	expectedIP := "1.2.3.4"
	// Test "tcp" protocol gets converted to "TCP" and validated
	originalProtocol := "tcp"
	expectedProtocol := "TCP"

	input := []byte(fmt.Sprintf(`
{
	"kind":"Service",
	"apiVersion":"v1",
	"metadata":{"name":"my-service-name", "namespace":"my-service-namespace"},
	"spec": {
		"portalIP":"%s",
		"ports":[{"port":1,"protocol":"%s"}]
	}
}
`, expectedIP, originalProtocol))

	t.Log("Testing 1.0.0 v1 migration added in PR #3592")
	testCompatibility(
		t, "v1", input,
		func(obj runtime.Object) fielderrors.ValidationErrorList {
			return validation.ValidateService(obj.(*api.Service))
		},
		map[string]string{
			"spec.portalIP":          expectedIP,
			"spec.clusterIP":         expectedIP,
			"spec.ports[0].protocol": expectedProtocol,
		},
	)
}

func TestCompatibility_v1_Endpoints(t *testing.T) {
	// Test "tcp" protocol gets converted to "TCP" and validated
	originalProtocol := "tcp"
	expectedProtocol := "TCP"

	input := []byte(fmt.Sprintf(`
{
	"kind":"Endpoints",
	"apiVersion":"v1",
	"metadata":{"name":"my-endpoints-name", "namespace":"my-endpoints-namespace"},
	"subsets": [{
		"addresses":[{"ip":"1.2.3.4"}],
		"ports": [{"port":1,"targetPort":1,"protocol":"%s"}]
	}]
}
`, originalProtocol))

	t.Log("Testing 1.0.0 v1 migration added in PR #3592")
	testCompatibility(
		t, "v1", input,
		func(obj runtime.Object) fielderrors.ValidationErrorList {
			return validation.ValidateEndpoints(obj.(*api.Endpoints))
		},
		map[string]string{
			"subsets[0].ports[0].protocol": expectedProtocol,
		},
	)
}

func testCompatibility(
	t *testing.T,
	version string,
	input []byte,
	validator func(obj runtime.Object) fielderrors.ValidationErrorList,
	serialized map[string]string,
) {

	// Decode
	codec := runtime.CodecFor(api.Scheme, version)
	obj, err := codec.Decode(input)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	// Validate
	errs := validator(obj)
	if len(errs) != 0 {
		t.Fatalf("Unexpected errors: %v", errs)
	}

	// Encode
	output, err := codec.Encode(obj)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	// Validate old and new fields are encoded
	generic := map[string]interface{}{}
	if err := json.Unmarshal(output, &generic); err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	for k, expectedValue := range serialized {
		keys := strings.Split(k, ".")
		if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok {
			t.Errorf("Unexpected error for %s: %v", k, err)
		} else if !reflect.DeepEqual(expectedValue, actualValue) {
			t.Errorf("Expected %v, got %v", expectedValue, actualValue)
		}
	}
}

func getJSONValue(data map[string]interface{}, keys ...string) (interface{}, bool, error) {
	// No keys, current value is it
	if len(keys) == 0 {
		return data, true, nil
	}

	// Get the key (and optional index)
	key := keys[0]
	index := -1
	if matches := regexp.MustCompile(`^(.*)\[(\d+)\]$`).FindStringSubmatch(key); len(matches) > 0 {
		key = matches[1]
		index, _ = strconv.Atoi(matches[2])
	}

	// Look up the value
	value, ok := data[key]
	if !ok {
		return nil, false, fmt.Errorf("No key %s found", key)
	}

	// Get the indexed value if an index is specified
	if index >= 0 {
		valueSlice, ok := value.([]interface{})
		if !ok {
			return nil, false, fmt.Errorf("Key %s did not hold a slice", key)
		}
		if index >= len(valueSlice) {
			return nil, false, fmt.Errorf("Index %d out of bounds for slice at key: %v", index, key)
		}
		value = valueSlice[index]
	}

	if len(keys) == 1 {
		return value, true, nil
	}

	childData, ok := value.(map[string]interface{})
	if !ok {
		return nil, false, fmt.Errorf("Key %s did not hold a map", keys[0])
	}
	return getJSONValue(childData, keys[1:]...)
}


text: .. automodule:: skrf.constants


text:
/* Author: Beck Chen, Mark Moll */

#include "KoulesDirectedControlSampler.h"
#include "KoulesStateSpace.h"
#include <ompl/base/spaces/RealVectorStateSpace.h>

namespace ob = ompl::base;
namespace oc = ompl::control;

unsigned int KoulesDirectedControlSampler::sampleTo(oc::Control *control, const ob::State *source, ob::State *dest)
{
    const double* dstPos = dest->as<KoulesStateSpace::StateType>()->values;
    double stepSize = si_->getPropagationStepSize();
    unsigned int steps = propagateMax_ ? si_->getMaxControlDuration() :
        cs_.sampleStepCount(si_->getMinControlDuration(), si_->getMaxControlDuration());

    cs_.steer(control, source, dstPos[0], dstPos[1]);
    // perform the first step of propagation
    statePropagator_->propagate(source, control, stepSize, dest);
    // if we reached the goal, we're done
    if (goal_->isSatisfied(dest))
        return 1;
    // if we found a valid state after one step, we can go on
    if (si_->isValid(dest))
    {
        ob::State *temp1 = dest, *temp2 = si_->allocState(), *toDelete = temp2;
        unsigned int r = steps;
        for (unsigned int i = 1 ; i < steps ; ++i)
        {
            statePropagator_->propagate(temp1, control, stepSize, temp2);
            if (goal_->isSatisfied(dest))
            {
                si_->copyState(dest, temp2);
                si_->freeState(toDelete);
                return i + 1;
            }
            if (si_->isValid(temp2))
                std::swap(temp1, temp2);
            else
            {
                // the last valid state is temp1;
                r = i;
                break;
            }
        }
        // if we finished the for-loop without finding an invalid state, the last valid state is temp1
        // make sure dest contains that information
        if (dest != temp1)
            si_->copyState(dest, temp1);
        si_->freeState(toDelete);
        return r;
    }
    // if the first propagation step produced an invalid step, return 0 steps
    // the last valid state is the starting one (assumed to be valid)
    else
    {
        if (dest != source)
            si_->copyState(dest, source);
        return 0;
    }
}


text:
import { createStructuredSelector } from 'reselect';

const getIsModalOpen = ({ modalPngDownload }) => modalPngDownload.modalIdOpen;

export default createStructuredSelector({
  modalIdOpen: getIsModalOpen
});


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process = require("child_process");
const fs = require("fs-extra");
const path = require("path");
const exec_1 = require("./exec");
const korepath = require("./korepath");
const log = require("./log");
const Platform_1 = require("./Platform");
const ProjectFile_1 = require("./ProjectFile");
const AssetConverter_1 = require("./AssetConverter");
const HaxeCompiler_1 = require("./HaxeCompiler");
const ShaderCompiler_1 = require("./ShaderCompiler");
const AndroidExporter_1 = require("./Exporters/AndroidExporter");
const DebugHtml5Exporter_1 = require("./Exporters/DebugHtml5Exporter");
const EmptyExporter_1 = require("./Exporters/EmptyExporter");
const FlashExporter_1 = require("./Exporters/FlashExporter");
const Html5Exporter_1 = require("./Exporters/Html5Exporter");
const Html5WorkerExporter_1 = require("./Exporters/Html5WorkerExporter");
const JavaExporter_1 = require("./Exporters/JavaExporter");
const KoreExporter_1 = require("./Exporters/KoreExporter");
const KoreHLExporter_1 = require("./Exporters/KoreHLExporter");
const KromExporter_1 = require("./Exporters/KromExporter");
const NodeExporter_1 = require("./Exporters/NodeExporter");
const PlayStationMobileExporter_1 = require("./Exporters/PlayStationMobileExporter");
const WpfExporter_1 = require("./Exporters/WpfExporter");
const UnityExporter_1 = require("./Exporters/UnityExporter");
const HaxeProject_1 = require("./HaxeProject");
let lastAssetConverter;
let lastShaderCompiler;
let lastHaxeCompiler;
function fixName(name) {
    name = name.replace(/[-\ \.\/\\]/g, '_');
    if (name[0] === '0' || name[0] === '1' || name[0] === '2' || name[0] === '3' || name[0] === '4'
        || name[0] === '5' || name[0] === '6' || name[0] === '7' || name[0] === '8' || name[0] === '9') {
        name = '_' + name;
    }
    return name;
}
function safeName(name) {
    return name.replace(/[\\\/]/g, '_');
}
function createKorefile(name, exporter, options, targetOptions, libraries, cdefines, korehl) {
    let out = '';
    out += 'let fs = require(\'fs\');\n';
    out += 'let path = require(\'path\');\n';
    out += 'let project = new Project(\'' + name + '\');\n';
    for (let cdefine of cdefines) {
        out += 'project.addDefine(\'' + cdefine + '\');\n';
    }
    if (options.haxe3) {
        out += 'project.addDefine(\'HXCPP_API_LEVEL=331\');\n';
    }
    else {
        out += 'project.addDefine(\'HXCPP_API_LEVEL=332\');\n';
    }
    if (targetOptions) {
        let koreTargetOptions = {};
        for (let option in targetOptions) {
            if (option.endsWith('_native'))
                continue;
            koreTargetOptions[option] = targetOptions[option];
        }
        for (let option in targetOptions) {
            if (option.endsWith('_native')) {
                koreTargetOptions[option.substr(0, option.length - '_native'.length)] = targetOptions[option];
            }
        }
        out += 'project.targetOptions = ' + JSON.stringify(koreTargetOptions) + ';\n';
    }
    out += 'project.setDebugDir(\'' + path.relative(options.from, path.join(options.to, exporter.sysdir())).replace(/\\/g, '/') + '\');\n';
    let buildpath = path.relative(options.from, path.join(options.to, exporter.sysdir() + '-build')).replace(/\\/g, '/');
    if (buildpath.startsWith('..'))
        buildpath = path.resolve(path.join(options.from.toString(), buildpath));
    out += 'await project.addProject(\'' + buildpath.replace(/\\/g, '/') + '\');\n';
    if (korehl)
        out += 'await project.addProject(\'' + path.join(options.kha, 'Backends', 'KoreHL').replace(/\\/g, '/') + '\');\n';
    else
        out += 'await project.addProject(\'' + path.normalize(options.kha).replace(/\\/g, '/') + '\');\n';
    for (let lib of libraries) {
        let libPath = lib.libroot;
        out += 'if (fs.existsSync(path.join(\'' + libPath.replace(/\\/g, '/') + '\', \'korefile.js\'))) {\n';
        out += '\tawait project.addProject(\'' + libPath.replace(/\\/g, '/') + '\');\n';
        out += '}\n';
    }
    out += 'resolve(project);\n';
    return out;
}
async function exportProjectFiles(name, resourceDir, options, exporter, kore, korehl, libraries, targetOptions, defines, cdefines) {
    if (options.haxe !== '') {
        let haxeOptions = exporter.haxeOptions(name, targetOptions, defines);
        haxeOptions.defines.push('kha');
        haxeOptions.defines.push('kha_version=1810');
        haxeOptions.safeName = safeName(haxeOptions.name);
        if (options.debug && haxeOptions.parameters.indexOf('-debug') < 0) {
            haxeOptions.parameters.push('-debug');
        }
        HaxeProject_1.writeHaxeProject(options.to, !options.noproject, haxeOptions);
        if (!options.nohaxe) {
            let compiler = new HaxeCompiler_1.HaxeCompiler(options.to, haxeOptions.to, haxeOptions.realto, resourceDir, options.haxe, 'project-' + exporter.sysdir() + '.hxml', haxeOptions.sources, exporter.sysdir());
            lastHaxeCompiler = compiler;
            try {
                await compiler.run(options.watch);
            }
            catch (error) {
                return Promise.reject(error);
            }
        }
        for (let callback of ProjectFile_1.Callbacks.postHaxeCompilation) {
            callback();
        }
        await exporter.export(name, targetOptions, haxeOptions);
    }
    let buildDir = path.join(options.to, exporter.sysdir() + '-build');
    if (options.haxe !== '' && kore && !options.noproject) {
        // If target is a Kore project, generate additional project folders here.
        // generate the korefile.js
        fs.copySync(path.join(__dirname, '..', 'Data', 'build-korefile.js'), path.join(buildDir, 'korefile.js'), { overwrite: true });
        fs.writeFileSync(path.join(options.from, 'korefile.js'), createKorefile(name, exporter, options, targetOptions, libraries, cdefines, false));
        // Similar to khamake.js -> main.js -> run(...)
        // We now do koremake.js -> main.js -> run(...)
        // This will create additional project folders for the target,
        // e.g. 'build/android-native-build'
        try {
            let name = await require(path.join(korepath.get(), 'out', 'main.js')).run({
                from: options.from,
                to: buildDir,
                target: koreplatform(options.target),
                graphics: options.graphics,
                audio: options.audio,
                vrApi: options.vr,
                raytrace: options.raytrace,
                visualstudio: options.visualstudio,
                compile: options.compile,
                run: options.run,
                debug: options.debug,
                noshaders: true
            }, {
                info: log.info,
                error: log.error
            });
            for (let callback of ProjectFile_1.Callbacks.postCppCompilation) {
                callback();
            }
            log.info('Done.');
            return name;
        }
        catch (error) {
            log.error(error);
            return '';
        }
    }
    else if (options.haxe !== '' && korehl && !options.noproject) {
        fs.copySync(path.join(__dirname, '..', 'Data', 'hl', 'kore_sources.c'), path.join(buildDir, 'kore_sources.c'), { overwrite: true });
        fs.copySync(path.join(__dirname, '..', 'Data', 'hl', 'korefile.js'), path.join(buildDir, 'korefile.js'), { overwrite: true });
        fs.writeFileSync(path.join(options.from, 'korefile.js'), createKorefile(name, exporter, options, targetOptions, libraries, cdefines, korehl));
        try {
            let name = await require(path.join(korepath.get(), 'out', 'main.js')).run({
                from: options.from,
                to: buildDir,
                target: koreplatform(options.target),
                graphics: options.graphics,
                vrApi: options.vr,
                raytrace: options.raytrace,
                visualstudio: options.visualstudio,
                compile: options.compile,
                run: options.run,
                debug: options.debug,
                noshaders: true
            }, {
                info: log.info,
                error: log.error
            });
            log.info('Done.');
            return name;
        }
        catch (error) {
            log.error(error);
            return '';
        }
    }
    else {
        // If target is not a Kore project, e.g. HTML5, finish building here.
        log.info('Done.');
        return name;
    }
}
function checkKorePlatform(platform) {
    return platform === 'windows'
        || platform === 'windowsapp'
        || platform === 'ios'
        || platform === 'osx'
        || platform === 'android'
        || platform === 'linux'
        || platform === 'html5'
        || platform === 'tizen'
        || platform === 'pi'
        || platform === 'tvos'
        || platform === 'ps4'
        || platform === 'xboxone'
        || platform === 'switch';
}
function koreplatform(platform) {
    // 'android-native' becomes 'android'
    if (platform.endsWith('-native'))
        return platform.substr(0, platform.length - '-native'.length);
    else if (platform.endsWith('-hl'))
        return platform.substr(0, platform.length - '-hl'.length);
    else
        return platform;
}
async function exportKhaProject(options) {
    log.info('Creating Kha project.');
    let project = null;
    let foundProjectFile = false;
    // get the khafile.js and load the config code,
    // then create the project config object, which contains stuff
    // like project name, assets paths, sources path, library path...
    if (fs.existsSync(path.join(options.from, options.projectfile))) {
        try {
            project = await ProjectFile_1.loadProject(options.from, options.projectfile, options.target);
        }
        catch (x) {
            log.error(x);
            throw 'Loading the projectfile failed.';
        }
        foundProjectFile = true;
    }
    if (!foundProjectFile) {
        throw 'No khafile found.';
    }
    let temp = path.join(options.to, 'temp');
    fs.ensureDirSync(temp);
    let exporter = null;
    let kore = false;
    let korehl = false;
    let target = options.target.toLowerCase();
    let baseTarget = target;
    let customTarget = null;
    if (project.customTargets.get(options.target)) {
        customTarget = project.customTargets.get(options.target);
        baseTarget = customTarget.baseTarget;
    }
    switch (baseTarget) {
        case Platform_1.Platform.Krom:
            exporter = new KromExporter_1.KromExporter(options);
            break;
        case Platform_1.Platform.Flash:
            exporter = new FlashExporter_1.FlashExporter(options);
            break;
        case Platform_1.Platform.HTML5:
            exporter = new Html5Exporter_1.Html5Exporter(options);
            break;
        case Platform_1.Platform.HTML5Worker:
            exporter = new Html5WorkerExporter_1.Html5WorkerExporter(options);
            break;
        case Platform_1.Platform.DebugHTML5:
            exporter = new DebugHtml5Exporter_1.DebugHtml5Exporter(options);
            break;
        case Platform_1.Platform.WPF:
            exporter = new WpfExporter_1.WpfExporter(options);
            break;
        case Platform_1.Platform.Java:
            exporter = new JavaExporter_1.JavaExporter(options);
            break;
        case Platform_1.Platform.PlayStationMobile:
            exporter = new PlayStationMobileExporter_1.PlayStationMobileExporter(options);
            break;
        case Platform_1.Platform.Android:
            // 'android-native' bypasses this option
            exporter = new AndroidExporter_1.AndroidExporter(options);
            break;
        case Platform_1.Platform.Node:
            exporter = new NodeExporter_1.NodeExporter(options);
            break;
        case Platform_1.Platform.Unity:
            exporter = new UnityExporter_1.UnityExporter(options);
            break;
        case Platform_1.Platform.Empty:
            exporter = new EmptyExporter_1.EmptyExporter(options);
            break;
        default:
            if (target.endsWith('-hl')) {
                korehl = true;
                options.target = koreplatform(target);
                if (!checkKorePlatform(options.target)) {
                    log.error('Unknown platform: ' + options.target);
                    return Promise.reject('');
                }
                exporter = new KoreHLExporter_1.KoreHLExporter(options);
            }
            else {
                kore = true;
                // If target is 'android-native' then options.target becomes 'android'
                options.target = koreplatform(target);
                if (!checkKorePlatform(options.target)) {
                    log.error('Unknown platform: ' + options.target);
                    return Promise.reject('');
                }
                exporter = new KoreExporter_1.KoreExporter(options);
            }
            break;
    }
    exporter.setSystemDirectory(target);
    let buildDir = path.join(options.to, exporter.sysdir() + '-build');
    // Create the target build folder
    // e.g. 'build/android-native'
    fs.ensureDirSync(path.join(options.to, exporter.sysdir()));
    let defaultWindowOptions = {
        width: 800,
        height: 600
    };
    let windowOptions = project.windowOptions ? project.windowOptions : defaultWindowOptions;
    exporter.setName(project.name);
    exporter.setWidthAndHeight('width' in windowOptions ? windowOptions.width : defaultWindowOptions.width, 'height' in windowOptions ? windowOptions.height : defaultWindowOptions.height);
    for (let source of project.sources) {
        exporter.addSourceDirectory(source);
    }
    for (let library of project.libraries) {
        exporter.addLibrary(library);
    }
    exporter.parameters = exporter.parameters.concat(project.parameters);
    project.scriptdir = options.kha;
    if (baseTarget !== Platform_1.Platform.Java && baseTarget !== Platform_1.Platform.WPF) {
        project.addShaders('Sources/Shaders/**', {});
    }
    for (let callback of ProjectFile_1.Callbacks.preAssetConversion) {
        callback();
    }
    let assetConverter = new AssetConverter_1.AssetConverter(exporter, options, project.assetMatchers);
    lastAssetConverter = assetConverter;
    let assets = await assetConverter.run(options.watch, temp);
    let shaderDir = path.join(options.to, exporter.sysdir() + '-resources');
    if (target === Platform_1.Platform.Unity) {
        shaderDir = path.join(options.to, exporter.sysdir(), 'Assets', 'Shaders');
    }
    for (let callback of ProjectFile_1.Callbacks.preShaderCompilation) {
        callback();
    }
    fs.ensureDirSync(shaderDir);
    let oldResources = null;
    let recompileAllShaders = false;
    try {
        oldResources = JSON.parse(fs.readFileSync(path.join(options.to, exporter.sysdir() + '-resources', 'files.json'), 'utf8'));
        for (let file of oldResources.files) {
            if (file.type === 'shader') {
                if (!file.files || file.files.length === 0) {
                    recompileAllShaders = true;
                    break;
                }
            }
        }
    }
    catch (error) {
    }
    let exportedShaders = [];
    if (!options.noshaders) {
        if (fs.existsSync(path.join(options.from, 'Backends'))) {
            let libdirs = fs.readdirSync(path.join(options.from, 'Backends'));
            for (let ld in libdirs) {
                let libdir = path.join(options.from, 'Backends', libdirs[ld]);
                if (fs.statSync(libdir).isDirectory()) {
                    let exe = path.join(libdir, 'krafix', 'krafix-' + options.target + '.exe');
                    if (fs.existsSync(exe)) {
                        options.krafix = exe;
                    }
                }
            }
        }
        let shaderCompiler = new ShaderCompiler_1.ShaderCompiler(exporter, options.target, options.krafix, shaderDir, temp, buildDir, options, project.shaderMatchers);
        lastShaderCompiler = shaderCompiler;
        try {
            exportedShaders = await shaderCompiler.run(options.watch, recompileAllShaders);
        }
        catch (err) {
            return Promise.reject(err);
        }
    }
    if (target === Platform_1.Platform.Unity) {
        fs.ensureDirSync(path.join(options.to, exporter.sysdir() + '-resources'));
        for (let shader of exportedShaders) {
            fs.writeFileSync(path.join(options.to, exporter.sysdir() + '-resources', shader.name + '.hlsl'), shader.name);
        }
        let proto = fs.readFileSync(path.join(options.from, options.kha, 'Tools', 'khamake', 'Data', 'unity', 'Shaders', 'proto.shader'), 'utf8');
        for (let i1 = 0; i1 < exportedShaders.length; ++i1) {
            if (exportedShaders[i1].name.endsWith('.vert')) {
                for (let i2 = 0; i2 < exportedShaders.length; ++i2) {
                    if (exportedShaders[i2].name.endsWith('.frag')) {
                        let shadername = exportedShaders[i1].name + '.' + exportedShaders[i2].name;
                        let proto2 = proto.replace(/{name}/g, shadername);
                        proto2 = proto2.replace(/{vert}/g, exportedShaders[i1].name);
                        proto2 = proto2.replace(/{frag}/g, exportedShaders[i2].name);
                        fs.writeFileSync(path.join(shaderDir, shadername + '.shader'), proto2, 'utf8');
                    }
                }
            }
        }
        let blobDir = path.join(options.to, exporter.sysdir(), 'Assets', 'Resources', 'Blobs');
        fs.ensureDirSync(blobDir);
        for (let i = 0; i < exportedShaders.length; ++i) {
            fs.writeFileSync(path.join(blobDir, exportedShaders[i].files[0] + '.bytes'), exportedShaders[i].name, 'utf8');
        }
    }
    function findShader(name) {
        let fallback = {};
        fallback.files = [];
        fallback.inputs = [];
        fallback.outputs = [];
        fallback.uniforms = [];
        fallback.types = [];
        try {
            for (let file of oldResources.files) {
                if (file.type === 'shader' && file.name === fixName(name)) {
                    return file;
                }
            }
        }
        catch (error) {
            return fallback;
        }
        return fallback;
    }
    let files = [];
    for (let asset of assets) {
        let file = {
            name: fixName(asset.name),
            files: asset.files,
            type: asset.type
        };
        if (file.type === 'image') {
            file.original_width = asset.original_width;
            file.original_height = asset.original_height;
            if (asset.readable)
                file.readable = asset.readable;
        }
        files.push(file);
    }
    for (let shader of exportedShaders) {
        let oldShader = findShader(shader.name);
        files.push({
            name: fixName(shader.name),
            files: shader.files === null ? oldShader.files : shader.files,
            type: 'shader',
            inputs: shader.inputs === null ? oldShader.inputs : shader.inputs,
            outputs: shader.outputs === null ? oldShader.outputs : shader.outputs,
            uniforms: shader.uniforms === null ? oldShader.uniforms : shader.uniforms,
            types: shader.types === null ? oldShader.types : shader.types
        });
    }
    function secondPass() {
        // First pass is for main project files. Second pass is for shaders.
        // Will try to look for the folder, e.g. 'build/Shaders'.
        // if it exists, export files similar to other a
        let hxslDir = path.join('build', 'Shaders');
        /** if (fs.existsSync(hxslDir) && fs.readdirSync(hxslDir).length > 0) {
            addShaders(exporter, platform, project, from, to.resolve(exporter.sysdir() + '-resources'), temp, from.resolve(Paths.get(hxslDir)), krafix);
            if (foundProjectFile) {
                fs.outputFileSync(to.resolve(Paths.get(exporter.sysdir() + '-resources', 'files.json')).toString(), JSON.stringify({ files: files }, null, '\t'), { encoding: 'utf8' });
                log.info('Assets done.');
                exportProjectFiles(name, from, to, options, exporter, platform, khaDirectory, haxeDirectory, kore, project.libraries, project.targetOptions, callback);
            }
            else {
                exportProjectFiles(name, from, to, options, exporter, platform, khaDirectory, haxeDirectory, kore, project.libraries, project.targetOptions, callback);
            }
        }*/
    }
    if (foundProjectFile) {
        fs.outputFileSync(path.join(options.to, exporter.sysdir() + '-resources', 'files.json'), JSON.stringify({ files: files }, null, '\t'));
    }
    for (let callback of ProjectFile_1.Callbacks.preHaxeCompilation) {
        callback();
    }
    if (options.onlydata) {
        log.info('Exporting only data.');
        // We need to copy assets into project folder for Android native
        if (exporter.sysdir() === 'android-native') {
            // Location of preprocessed assets
            let dataDir = path.join(options.to, exporter.sysdir());
            // Use the same 'safename' as koremake
            let safename = project.name.replace(/ /g, '-');
            let assetsDir = path.resolve(buildDir, safename, 'app', 'src', 'main', 'assets');
            // Create path if it does not exist (although it should)
            fs.ensureDirSync(assetsDir);
            log.info(assetsDir);
            fs.copySync(path.resolve(dataDir), assetsDir);
        }
        return project.name;
    }
    else {
        return await exportProjectFiles(project.name, path.join(options.to, exporter.sysdir() + '-resources'), options, exporter, kore, korehl, project.libraries, project.targetOptions, project.defines, project.cdefines);
    }
}
function isKhaProject(directory, projectfile) {
    return fs.existsSync(path.join(directory, 'Kha')) || fs.existsSync(path.join(directory, projectfile));
}
async function exportProject(options) {
    if (isKhaProject(options.from, options.projectfile)) {
        return await exportKhaProject(options);
    }
    else {
        log.error('Neither Kha directory nor project file (' + options.projectfile + ') found.');
        return 'Unknown';
    }
}
function runProject(options) {
    return new Promise((resolve, reject) => {
        log.info('Running...');
        let run = child_process.spawn(path.join(process.cwd(), options.to, 'linux-build', name), [], { cwd: path.join(process.cwd(), options.to, 'linux') });
        run.stdout.on('data', function (data) {
            log.info(data.toString());
        });
        run.stderr.on('data', function (data) {
            log.error(data.toString());
        });
        run.on('close', function (code) {
            resolve();
        });
    });
}
exports.api = 2;
async function run(options, loglog) {
    if (options.silent) {
        log.silent();
    }
    else {
        log.set(loglog);
    }
    if (!options.kha) {
        let p = path.join(__dirname, '..', '..', '..');
        if (fs.existsSync(p) && fs.statSync(p).isDirectory()) {
            options.kha = p;
        }
    }
    else {
        options.kha = path.resolve(options.kha);
    }
    log.info('Using Kha from ' + options.kha);
    if (options.parallelAssetConversion === undefined) {
        options.parallelAssetConversion = 0;
    }
    if (options.haxe3 === undefined) {
        options.haxe3 = false;
    }
    if (!options.haxe) {
        let haxepath = options.haxe3
            ? path.join(options.kha, 'Tools', 'haxe', 'v3.x')
            : path.join(options.kha, 'Tools', 'haxe');
        if (fs.existsSync(haxepath) && fs.statSync(haxepath).isDirectory())
            options.haxe = haxepath;
    }
    if (!options.krafix) {
        let krafixpath = path.join(options.kha, 'Kore', 'Tools', 'krafix', 'krafix' + exec_1.sys());
        if (fs.existsSync(krafixpath))
            options.krafix = krafixpath;
    }
    if (!options.ogg) {
        let oggpath = path.join(options.kha, 'Tools', 'oggenc', 'oggenc' + exec_1.sys());
        if (fs.existsSync(oggpath))
            options.ogg = oggpath + ' {in} -o {out} --quiet';
    }
    if (!options.mp3) {
        let lamepath = path.join(options.kha, 'Tools', 'lame', 'lame' + exec_1.sys());
        if (fs.existsSync(lamepath))
            options.mp3 = lamepath + ' {in} {out}';
    }
    // if (!options.kravur) {
    //     let kravurpath = path.join(options.kha, 'Tools', 'kravur', 'kravur' + sys());
    //     if (fs.existsSync(kravurpath)) options.kravur = kravurpath + ' {in} {size} {out}';
    // }
    if (!options.aac && options.ffmpeg) {
        options.aac = options.ffmpeg + ' -nostdin -i {in} {out}';
    }
    if (!options.h264 && options.ffmpeg) {
        options.h264 = options.ffmpeg + ' -nostdin -i {in} {out}';
    }
    if (!options.webm && options.ffmpeg) {
        options.webm = options.ffmpeg + ' -nostdin -i {in} {out}';
    }
    if (!options.wmv && options.ffmpeg) {
        options.wmv = options.ffmpeg + ' -nostdin -i {in} {out}';
    }
    if (!options.theora && options.ffmpeg) {
        options.theora = options.ffmpeg + ' -nostdin -i {in} {out}';
    }
    let name = '';
    try {
        name = await exportProject(options);
    }
    catch (err) {
        process.exit(1);
    }
    if (options.target === Platform_1.Platform.Linux && options.run) {
        await runProject(options);
    }
    if (options.compile && options.target === Platform_1.Platform.Android) {
        let gradlew = (process.platform === 'win32') ? 'gradlew.bat' : 'bash';
        let args = (process.platform === 'win32') ? [] : ['gradlew'];
        args.push('assemble');
        let make = child_process.spawn(gradlew, args, { cwd: path.join(options.to, 'android', name) });
        make.stdout.on('data', function (data) {
            log.info(data.toString());
        });
        make.stderr.on('data', function (data) {
            log.error(data.toString());
        });
        make.on('close', function (code) {
            if (code === 0) {
            }
            else {
                log.error('Compilation failed.');
                process.exit(code);
            }
        });
    }
    return name;
}
exports.run = run;
function close() {
    if (lastAssetConverter)
        lastAssetConverter.close();
    if (lastShaderCompiler)
        lastShaderCompiler.close();
    if (lastHaxeCompiler)
        lastHaxeCompiler.close();
}
exports.close = close;
//# sourceMappingURL=main.js.map


text:
#region License

// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#endregion

using System;
using Hotcakes.Commerce;

namespace Hotcakes.Modules.Core.Api.Rest
{
    [Serializable]
    public class RestHandlerFactory
    {
        public static IRestHandler Instantiate(string version, string modelname, HotcakesApplication app)
        {
            switch (modelname.Trim().ToLowerInvariant())
            {
                case "categories":
                    return new CategoriesHandler(app);
                case "pricegroups":
                    return new PriceGroupsHandler(app);
                case "customeraccounts":
                    return new CustomerAccountHandler(app);
                case "affiliates":
                    return new AffiliatesHandler(app);
                case "taxschedules":
                    return new TaxSchedulesHandler(app);
                case "taxes":
                    return new TaxesHandler(app);
                case "vendors":
                    return new VendorsHandler(app);
                case "manufacturers":
                    return new ManufacturersHandler(app);
                case "producttypes":
                    return new ProductTypesHandler(app);
                case "productproperties":
                    return new ProductPropertiesHandler(app);
                case "productoptions":
                    return new ProductOptionsHandler(app);
                case "products":
                    return new ProductsHandler(app);
                case "productmainimage":
                    return new ProductsMainImageHandler(app);
                case "categoriesimagesicon":
                    return new CategoriesImagesIconHandler(app);
                case "categoriesimagesbanner":
                    return new CategoriesImagesBannerHandler(app);
                case "productfiles":
                    return new ProductFilesHandler(app);
                case "productfilesdata":
                    return new ProductFilesDataHandler(app);
                case "productfilesxproducts":
                    return new ProductFilesXProductsHandler(app);
                case "productrelationships":
                    return new ProductRelationshipsHandler(app);
                case "productinventory":
                    return new ProductInventoryHandler(app);
                case "productimages":
                    return new ProductImagesHandler(app);
                case "productimagesupload":
                    return new ProductImagesUploadHandler(app);
                case "productvariantssku":
                case "productvariant":
                    return new ProductVariantsHandler(app);
                case "productvolumediscounts":
                    return new ProductVolumeDiscountsHandler(app);
                case "productreviews":
                    return new ProductReviewsHandler(app);
                case "categoryproductassociations":
                    return new CategoryProductAssociationsHandler(app);
                case "searchmanager":
                    return new SearchManagerHandler(app);
                case "orders":
                    return new OrdersHandler(app);
                case "ordertransactions":
                    return new OrderTransactionsHandler(app);
                case "utilities":
                    return new UtilitiesHandler(app);
                case "wishlistitems":
                    return new WishListItemsHandler(app);
                case "catalogroles":
                    return new CatalogRolesHandler(app);
                case "giftcards":
                    return new GiftCardsHandler(app);
            }

            return null;
        }
    }
}


text:
module.exports = function render (content, user) {
  if (content instanceof Array) {
    return content.map(model => renderObject(model, user))
  }

  return renderObject(content, user)
}

function renderObject (model, user) {
  const result = {}
  const isAdmin = user && (user.role === 'admin' || model.id === user.id)
  const isTeam = user && (user.role === 'team' || isAdmin)

  result.id = model.id
  result.name = model.name
  result.img = model.img || 'https://sinfo.ams3.cdn.digitaloceanspaces.com/static/26-sinfo/hacky/hacky.png'
  result.role = model.role
  result.points = model.points !== undefined && typeof model.points === 'number'
    ? model.points : undefined
  result.registered = model.registered
  result.signatures = model.signatures && model.signatures.map(signature => ({
    edition: signature && signature.edition,
    day: signature && signature.day,
    redeemed: signature && signature.redeemed,
    signatures: signature && signature.signatures
  }))

  if (isAdmin || isTeam) {
    result.mail = model.mail
    result.facebook = model.facebook && {
      id: model.facebook && model.facebook.id
    }
    result.linkedin = model.linkedin && {
      id: model.linkedin && model.linkedin.id
    }
    result.google = model.google && {
      id: model.google && model.google.id
    }
    result.fenix = model.fenix && {
      id: model.fenix && model.fenix.id
    }
    result.job = model.job && {
      startup: model.job && model.job.startup,
      internship: model.job && model.job.internship,
      start: model.job && model.job.start
    }
    result.updated = model.updated
    result.company = model.company && model.company.map(participation => ({
      edition: participation && participation.edition,
      company: participation && participation.company
    }))
  }

  return result
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>coordinate descent on k317h</title>
    <link>https://keithzeng.github.io/tags/coordinate-descent/</link>
    <description>Recent content in coordinate descent on k317h</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 18 Feb 2019 10:37:54 -0800</lastBuildDate>

	<atom:link href="https://keithzeng.github.io/tags/coordinate-descent/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>CSE250 Proj2</title>
      <link>https://keithzeng.github.io/hws/cse250-proj2/</link>
      <pubDate>Mon, 18 Feb 2019 10:37:54 -0800</pubDate>

      <guid>https://keithzeng.github.io/hws/cse250-proj2/</guid>
      <description>Coordinate Descent (a) In this project I compared different methods using different approaches. Besides the random coordinate descent (RCD), I implemented two ways to choose the coordinate: cyclic coordinate descent method(CCD) and greatest coordinate descent method (GCD). CCD updates the coordinate in cycle and GCD update the coordinate with greatest derivative.1
(b) For every iteration, the coordinate, i, being picked will be updated with below methods.
Method 1 (Minimize Loss Function)</description>
    </item>

  </channel>
</rss>


text:
/**
 * @class Oskari.mapframework.bundle.admin-users.Tile
 * Renders the "admin users" tile.
 */
Oskari.clazz.define('Oskari.mapframework.bundle.admin-users.Tile',

    /**
     * @method create called automatically on construction
     * @static
     * @param {Oskari.mapframework.bundle.layerselector2.LayerSelectorBundleInstance} instance
     *     reference to component that created the tile
     */
    function (instance) {
        //"use strict";
        this.instance = instance;
        this.container = null;
        this.template = null;
    }, {
        /**
         * @method getName
         * @return {String} the name for the component
         */
        getName: function () {
            //"use strict";
            return 'Oskari.mapframework.bundle.admin-users.Tile';
        },
        /**
         * @method setEl
         * @param {Object} el
         *     reference to the container in browser
         * @param {Number} width
         *     container size(?) - not used
         * @param {Number} height
         *     container size(?) - not used
         *
         * Interface method implementation
         */
        setEl: function (el, width, height) {
            //"use strict";
            this.container = jQuery(el);
        },
        /**
         * @method startPlugin
         * Interface method implementation, calls #refresh()
         */
        startPlugin: function () {
            //"use strict";
            this.refresh();
        },
        /**
         * @method stopPlugin
         * Interface method implementation, clears the container
         */
        stopPlugin: function () {
            //"use strict";
            this.container.empty();
        },
        /**
         * @method getTitle
         * @return {String} localized text for the title of the tile
         */
        getTitle: function () {
            //"use strict";
            return this.instance.getLocalization('title');
        },
        /**
         * @method getDescription
         * @return {String} localized text for the description of the tile
         */
        getDescription: function () {
            //"use strict";
            return this.instance.getLocalization('desc');
        },
        /**
         * @method getOptions
         * Interface method implementation, does nothing atm
         */
        getOptions: function () {
            //"use strict";
        },
        /**
         * @method setState
         * @param {Object} state
         *     state that this component should use
         * Interface method implementation, does nothing atm
         */
        setState: function (state) {
            //"use strict";
        },
        /**
         * @method refresh
         * Creates the UI for a fresh start
         */
        refresh: function () {
            //"use strict";
        }
    }, {
        /**
         * @property {String[]} protocol
         * @static
         */
        'protocol': ['Oskari.userinterface.Tile']
    });


text:
package uk.submergedcode.SubmergedCore.commands.exception;

import org.bukkit.command.CommandException;

public class CommandUsageException extends CommandException {

}


text:
@class TangibleSyncMediator;

// Delegate for the Sync mediator.
@protocol TangibleSyncMediatorDelegate

// Notifies the delegate that `mediator` has finished sign in with success.
- (void)tangibleSyncMediatorDidSuccessfulyFinishSignin:
    (TangibleSyncMediator*)mediator;

// Notifies the delegate that the user has been removed.
- (void)tangibleSyncMediatorUserRemoved:(TangibleSyncMediator*)mediator;

// Sets the UI as interactable or not.
- (void)tangibleSyncMediator:(TangibleSyncMediator*)mediator
                   UIEnabled:(BOOL)UIEnabled;

@end

#endif  // IOS_CHROME_BROWSER_UI_AUTHENTICATION_TANGIBLE_SYNC_TANGIBLE_SYNC_MEDIATOR_DELEGATE_H_


text:
from cass_functions import cassandra_query, get_keyspaces, get_rpc_address

def destroy_schema(host):

    keyspaces = get_keyspaces(host)

    for k in keyspaces:
        print('Dropping keyspace: %s' % k)
        cassandra_query(host, 'DROP KEYSPACE %s;' % k)

if __name__ == '__main__':
    destroy_schema(get_rpc_address())


text:
package protocol // import "github.com/nathanaelle/gearman/v2/protocol"

import "errors"

type (
	// MarshalerGearman describe methods needed to marshal a interface to a []byte
	MarshalerGearman interface {
		MarshalGearman() ([]byte, error)
		Len() int
	}

	// UnmarshalerGearman describe methods needed to unmarshal a []byte to an interface
	UnmarshalerGearman interface {
		UnmarshalGearman([]byte) error
		Cast(Opaque) error
	}

	// Opaque describe an opaque data attribute to a gearman Function
	Opaque interface {
		MarshalerGearman
		UnmarshalerGearman
		Bytes() []byte
	}

	opaque []byte

	opaque0size struct{}
)

var emptyOpaque Opaque = &opaque0size{}

// Opacify create an Opaque data from a []byte
func Opacify(b []byte) Opaque {
	if len(b) == 0 {
		return emptyOpaque
	}

	o := opaque(b)

	return &o
}

func (o *opaque) UnmarshalGearman(d []byte) error {
	*o = d
	return nil
}

func (o *opaque) Cast(opq Opaque) error {
	return ErrCastOpaqueAsOpaque
}

func (o opaque) MarshalGearman() ([]byte, error) {
	return o.Bytes(), nil
}

func (o opaque) Bytes() []byte {
	return []byte(o)
}

func (o opaque) Len() int {
	return len(o.Bytes())
}

func (o *opaque0size) UnmarshalGearman(d []byte) error {
	if len(d) > 0 {
		return errors.New("empty_opaque can't unmarshal data")
	}
	return nil
}

func (o *opaque0size) Cast(opq Opaque) error {
	return ErrCastOpaqueAsOpaque
}

func (o opaque0size) MarshalGearman() ([]byte, error) {
	return []byte{}, nil
}

func (o opaque0size) Bytes() []byte {
	return []byte{}
}

func (o opaque0size) Len() int {
	return 0
}