text:
<!DOCTYPE html>
<meta charset="utf-8">

<title>Time travel map - Bartholomap</title>
    <meta id='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.12.1/mapbox-gl.css' rel='stylesheet' />
	<link href='https://fonts.googleapis.com/css?family=Dancing+Script|Overlock' rel='stylesheet' type='text/css'>
	<link href='./style/style.css' rel='stylesheet' type='text/css'/>

Chapters

Bartholomap project

John George Bartholomew's map

Air travel map

Enhance with actual destinations

As the crow flies

Manual labour

Other pages

HOWTO

Slippy map

Bartholomap project

The map below, the 'Bartholomap' shows how long it takes from London to any place in the world. This page tells the story how I came to make the Bartholomap. For the technical details and code I refer you to the HOWTO and GitHub repository. If you have any questions feel free to contact me.

The isochronic map created by me showing various travel times from London in 2015 - CC-BY Steven M. Ottens

John George Bartholomew's map
menu

A while ago I read an article in Intelligent Life about a hundred year old map that showed how long it took to travel from London to anywhere on the globe. The map, made before airtravel was common, shows the influence of shipping routes and intercontinental railways. Within a month you could travel to all but the most remote and landlocked places.

An isochronic map created by John George Bartholomew showing various travel times from London in 1914 Photo: RGS/Intelligent Life

Side by side

close

Air travel map
menu

Since that map was created the world has changed, and I was wondering how such a map would look like if it was created today. Since airtravel is the popular choice for long distance travel I decided to start with that. The OpenFlights project provides a list of airport-locations and flight-routes. Taking London as a starting point and using 600km/h as travelspeed it was fairly easy to calculate the time it takes to get to each of the ~3000 airports in the list. TBD: link naar github. Since contemporary travel is so much faster I changed the scale from days to hours:

within 5 hours5 to 10 hours10 to 20 hours20 to 30 hours30 to 40 hoursover 40 hours

Map of all airports as ±3000 dots classified by travel time (left) and as isochronal lines (right)

Enhance with actual destinations
menu

However as any traveler knows, being at the airport doesn't mean that you have arrived. To further the resolution of the isochronic map I used the 7000 places from Natural Earth Data to calculate the travel time to actual places. For each place I looked up the nearest airport and within a radius of a 1000km the nearest nonstop, one-stop and two-stop airports. For all four airports I calculated the total traveltime from London via that airport to the destination. This was done by using the excellent Open Source Routing Machine.

Map of all airports and routable places as ±10350 dots classified by travel time (left) and as isochronal lines (right)

As the crow flies
menu

For about 190 places which did not get a result from the previous exercise, I decided to divide them into landlocked and coastal cities. (This could be done way more advanced, but I just looked on the map and made a judgement call). For both types of places I calculated the straight line distance (using great arc distance) and decided upon 5km/h as landspeed and 25km/h for water. This may sound slow, but this is 'as the crow flies' in terrain without roads. Boats obviously are less hindered by the lack of roads.

Map of all airports and places as ±10500 dots classified by travel time (left) and as isochronic lines (right)

Manual labour
menu

This is as far as the automated process can go. John George Bartholomew created his map by hand, and to reimagine his map I'll have to do some handwork myself. The isochronal lines generated by turf.js are lines and not nicely closed polygons with holes. With some QGIS magic I created the necessary polygons which I then could load into Inkscape to create the map but also load into MapBox Studio to create the slippy map below.

Thanks to the kind folks of the Spatial Community for their inspiration and help, the Open Flight and Natural Earth communities for their data and my wife for the original suggestion to create this map.

Top

HOWTO

High Res Map

Slippy Map

SVG map

Code

Contact

Twitter

~ SMO ~ 2015 ~ DC ~


text:
#ifndef BOOST_PREDEF_PLAT_CLOUDABI_H
#define BOOST_PREDEF_PLAT_CLOUDABI_H

#include <boost/predef/version_number.h>
#include <boost/predef/make.h>

/*`
[heading `BOOST_PLAT_CLOUDABI`]

[@https://github.com/NuxiNL/cloudabi CloudABI] platform.

[table
    [[__predef_symbol__] [__predef_version__]]

    [[`__CloudABI__`] [__predef_detection__]]
    ]
 */

#define BOOST_PLAT_CLOUDABI BOOST_VERSION_NUMBER_NOT_AVAILABLE

#if defined(__CloudABI__)
#   undef BOOST_PLAT_CLOUDABI
#   define BOOST_PLAT_CLOUDABI BOOST_VERSION_NUMBER_AVAILABLE
#endif

#if BOOST_PLAT_CLOUDABI
#   define BOOST_PLAT_CLOUDABI_AVAILABLE
#   include <boost/predef/detail/platform_detected.h>
#endif

#define BOOST_PLAT_CLOUDABI_NAME "CloudABI"

#endif

#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_PLAT_CLOUDABI,BOOST_PLAT_CLOUDABI_NAME)

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Edit account form
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/myaccount/form-edit-account.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
 * will need to copy the new files to your theme to maintain compatibility. We try to do this.
 * as little as possible, but it does happen. When this occurs the version of the template file will.
 * be bumped and the readme will list any important changes.
 *
 * @see 	    http://docs.woothemes.com/document/template-structure/
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     2.5.1
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
?>

<?php wc_print_notices(); ?>

<form class="edit-account" action="" method="post">

	<?php do_action( 'woocommerce_edit_account_form_start' ); ?>

		<?php _e( 'First name', 'woocommerce' ); ?> *
		<input type="text" class="input-text" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />

		<?php _e( 'Last name', 'woocommerce' ); ?> *
		<input type="text" class="input-text" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />

		<?php _e( 'Email address', 'woocommerce' ); ?> *
		<input type="email" class="input-text" name="account_email" id="account_email" value="<?php echo esc_attr( $user->user_email ); ?>" />

	<fieldset>
		<legend><?php _e( 'Password Change', 'woocommerce' ); ?></legend>

			<?php _e( 'Current Password (leave blank to leave unchanged)', 'woocommerce' ); ?>
			<input type="password" class="input-text" name="password_current" id="password_current" />

			<?php _e( 'New Password (leave blank to leave unchanged)', 'woocommerce' ); ?>
			<input type="password" class="input-text" name="password_1" id="password_1" />

			<?php _e( 'Confirm New Password', 'woocommerce' ); ?>
			<input type="password" class="input-text" name="password_2" id="password_2" />

	</fieldset>

	<?php do_action( 'woocommerce_edit_account_form' ); ?>

		<?php wp_nonce_field( 'save_account_details' ); ?>
		<input type="submit" class="button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>" />
		<input type="hidden" name="action" value="save_account_details" />

	<?php do_action( 'woocommerce_edit_account_form_end' ); ?>

</form>


text:
package rfx.core.util.useragent;

/**
 * Collection of parsed data for a given user agent string consisting of UserAgent, OS, Device
 *
 * @author Steve Jiang (@sjiang) <gh at iamsteve com>
 */
public class Client {
  public final UserAgent userAgent;
  public final OS os;
  public final Device device;

  public Client(UserAgent userAgent, OS os, Device device) {
    this.userAgent = userAgent;
    this.os = os;
    this.device = device;
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) return true;
    if (!(other instanceof Client)) return false;

    Client o = (Client) other;
    return ((this.userAgent != null && this.userAgent.equals(o.userAgent)) || this.userAgent == o.userAgent) &&
           ((this.os != null && this.os.equals(o.os)) || this.os == o.os) &&
           ((this.device != null && this.device.equals(o.device)) || this.device == o.device);
  }

  @Override
  public int hashCode() {
    int h = userAgent == null ? 0 : userAgent.hashCode();
    h += os == null ? 0 : os.hashCode();
    h += device == null ? 0 : device.hashCode();
    return h;
  }

  @Override
  public String toString() {
    return String.format("{user_agent: %s, os: %s, device: %s}",
                         userAgent, os, device);
  }
}


text:
LEVEL = ..
DIRS  =

all:: check-local

# Include other test rules
include Makefile.tests

#===------------------------------------------------------------------------===#
# DejaGNU testing support
#===------------------------------------------------------------------------===#

ifneq ($(GREP_OPTIONS),)
$(warning GREP_OPTIONS environment variable may interfere with test results)
endif

ifdef VERBOSE
LIT_ARGS := -v
else
LIT_ARGS := -s -v
endif

# -jN causes crash on Cygwin's python.
ifneq (,$(filter $(HOST_OS),Cygwin))
  LIT_ARGS += -j1
endif

ifdef TESTSUITE
LIT_TESTSUITE := $(TESTSUITE)
CLEANED_TESTSUITE := $(patsubst %/,%,$(TESTSUITE))
CLEANED_TESTSUITE := $(patsubst test/%,%,$(CLEANED_TESTSUITE))
else
LIT_TESTSUITE := .
endif

ifdef VG
VALGRIND := valgrind --tool=memcheck --quiet --trace-children=yes --error-exitcode=3 --leak-check=full $(VALGRIND_EXTRA_ARGS)
endif

# Check what to run for -all.
LIT_ALL_TESTSUITES := $(LIT_TESTSUITE)

extra-site-cfgs::
.PHONY: extra-site-cfgs

ifneq ($(strip $(filter check-local-all,$(MAKECMDGOALS))),)
ifndef TESTSUITE
ifeq ($(shell test -f $(PROJ_OBJ_DIR)/../tools/clang/Makefile && echo OK), OK)
LIT_ALL_TESTSUITES += $(PROJ_OBJ_DIR)/../tools/clang/test

# Force creation of Clang's lit.site.cfg.
clang-site-cfg: FORCE
	$(MAKE) -C $(PROJ_OBJ_DIR)/../tools/clang/test lit.site.cfg Unit/lit.site.cfg
extra-site-cfgs:: clang-site-cfg
endif

ifeq ($(shell test -f $(PROJ_OBJ_DIR)/../tools/clang/tools/extra/Makefile && echo OK), OK)
LIT_ALL_TESTSUITES += $(PROJ_OBJ_DIR)/../tools/clang/tools/extra/test

# Force creation of Clang Tools' lit.site.cfg.
clang-tools-site-cfg: FORCE
	$(MAKE) -C $(PROJ_OBJ_DIR)/../tools/clang/tools/extra/test lit.site.cfg
extra-site-cfgs:: clang-tools-site-cfg
endif
endif
endif

# ulimits like these are redundantly enforced by the buildbots, so
# just removing them here won't work.
# Both AuroraUX & Solaris do not have the -m flag for ulimit
ifeq ($(HOST_OS),SunOS)
ULIMIT=ulimit -t 600 ; ulimit -d 512000 ; ulimit -v 512000 ;
else # !SunOS
ifeq ($(HOST_OS),AuroraUX)
ULIMIT=ulimit -t 600 ; ulimit -d 512000 ; ulimit -v 512000 ;
else # !AuroraUX
# Fedora 13 x86-64 python fails with -v 76800
ULIMIT=ulimit -t 600 ; ulimit -d 512000 ; ulimit -m 512000 ; ulimit -v 1024000 ;
endif # AuroraUX
endif # SunOS

check-local:: lit.site.cfg Unit/lit.site.cfg
	( $(ULIMIT) \
	  $(LLVM_SRC_ROOT)/utils/lit/lit.py $(LIT_ARGS) $(LIT_TESTSUITE) )

# This is a legacy alias dating from when both DejaGNU and lit were in use.
check-local-lit:: check-local

check-local-all:: lit.site.cfg Unit/lit.site.cfg extra-site-cfgs
	( $(ULIMIT) \
	  $(LLVM_SRC_ROOT)/utils/lit/lit.py $(LIT_ARGS) $(LIT_ALL_TESTSUITES) )

clean::
	$(RM) -rf `find $(LLVM_OBJ_ROOT)/test -name Output -type d -print`

# dsymutil is used on the Darwin to manipulate DWARF debugging information.
ifeq ($(TARGET_OS),Darwin)
DSYMUTIL=dsymutil
else
DSYMUTIL=true
endif

ifneq ($(OCAMLOPT),)
CC_FOR_OCAMLOPT := $(shell $(OCAMLOPT) -config | grep native_c_compiler | sed -e 's/native_c_compiler: //')
CXX_FOR_OCAMLOPT := $(subst gcc,g++,$(CC_FOR_OCAMLOPT))
endif

FORCE:

ifeq ($(DISABLE_ASSERTIONS),1)
ENABLE_ASSERTIONS=0
else
ENABLE_ASSERTIONS=1
endif

lit.site.cfg: FORCE
	@echo "Making LLVM 'lit.site.cfg' file..."
	@$(ECHOPATH) s=@TARGET_TRIPLE@=$(TARGET_TRIPLE)=g > lit.tmp
	@$(ECHOPATH) s=@LLVM_SOURCE_DIR@=$(LLVM_SRC_ROOT)=g >> lit.tmp
	@$(ECHOPATH) s=@LLVM_BINARY_DIR@=$(LLVM_OBJ_ROOT)=g >> lit.tmp
	@$(ECHOPATH) s=@LLVM_TOOLS_DIR@=$(ToolDir)=g >> lit.tmp
	@$(ECHOPATH) s=@SHLIBDIR@=$(SharedLibDir)=g >> lit.tmp
	@$(ECHOPATH) s=@SHLIBEXT@=$(SHLIBEXT)=g >> lit.tmp
	@$(ECHOPATH) s=@PYTHON_EXECUTABLE@=python=g >> lit.tmp
	@$(ECHOPATH) s=@OCAMLOPT@=$(OCAMLOPT) -cc $(subst *,'\\\"',*$(subst =,"\\=",$(CXX_FOR_OCAMLOPT))*) -I $(LibDir)/ocaml=g >> lit.tmp
	@$(ECHOPATH) s=@ENABLE_SHARED@=$(ENABLE_SHARED)=g >> lit.tmp
	@$(ECHOPATH) s=@ENABLE_ASSERTIONS@=$(ENABLE_ASSERTIONS)=g >> lit.tmp
	@$(ECHOPATH) s=@TARGETS_TO_BUILD@=$(TARGETS_TO_BUILD)=g >> lit.tmp
	@$(ECHOPATH) s=@LLVM_BINDINGS@=$(BINDINGS_TO_BUILD)=g >> lit.tmp
	@$(ECHOPATH) s=@HOST_OS@=$(HOST_OS)=g >> lit.tmp
	@$(ECHOPATH) s=@HOST_ARCH@=$(HOST_ARCH)=g >> lit.tmp
	@sed -f lit.tmp $(PROJ_SRC_DIR)/lit.site.cfg.in > $@
	@-rm -f lit.tmp

Unit/lit.site.cfg: $(PROJ_OBJ_DIR)/Unit/.dir FORCE
	@echo "Making LLVM unittest 'lit.site.cfg' file..."
	@$(ECHOPATH) s=@LLVM_SOURCE_DIR@=$(LLVM_SRC_ROOT)=g > unit.tmp
	@$(ECHOPATH) s=@LLVM_BINARY_DIR@=$(LLVM_OBJ_ROOT)=g >> unit.tmp
	@$(ECHOPATH) s=@LLVM_TOOLS_DIR@=$(ToolDir)=g >> unit.tmp
	@$(ECHOPATH) s=@LLVM_BUILD_MODE@=$(BuildMode)=g >> unit.tmp
	@$(ECHOPATH) s=@ENABLE_SHARED@=$(ENABLE_SHARED)=g >> unit.tmp
	@$(ECHOPATH) s=@SHLIBDIR@=$(SharedLibDir)=g >> unit.tmp
	@$(ECHOPATH) s=@SHLIBPATH_VAR@=$(SHLIBPATH_VAR)=g >> unit.tmp
	@$(ECHOPATH) s=@HOST_OS@=$(HOST_OS)=g >> unit.tmp
	@$(ECHOPATH) s=@HOST_ARCH@=$(HOST_ARCH)=g >> lit.tmp
	@sed -f unit.tmp $(PROJ_SRC_DIR)/Unit/lit.site.cfg.in > $@
	@-rm -f unit.tmp


text:
- Add `DataClassName.extending` to control the superclass of generated row
  classes.
- Add `setup` parameter to the constructors of `WebDatabase` too.

## 1.4.0

- Most methods to compose statements are now available as an extension on
  tables. As an alternative to `update(todos).replace(newEntry)`, you can
  now write `todos.replaceOne(newEntry)`.
- Deprecate the `from(table)` API introduced in 1.3.0. Having the methods on
  the table instances turned out to be even easier!
- In drift files, you can now use `LIST(SELECT ...)` as a result column to
  get all results of the inner select as a `List` in the result set.

## 1.3.0

- Add the `from(table)` method to generated databases. It can be used to write
  common queries more concisely.
- Make `groupConcat` nullable in the Dart API.
- Throw an exception in a `NativeDatabase` when multiple statements are run in
  a single call. In previous versions, parts of the SQL string would otherwise
  be ignored.
- Close the underlying database when a drift isolate is shut down.

## 1.2.0

- Properly support stream update queries on views.
- Reading blobs from the database is more lenient now.
- Provide a stack trace when `getSingle()` or `watchSingle()` is used on a
  query emitting more than one row.

## 1.1.1

- Rollback transactions when a commit fails.
- Revert a change from 1.1.0 to stop serializing messages over isolates.
  Instead, please set the `serialize` parameter to `false` on the `DriftIsolate` methods.

## 1.1.0

- Add the `references` method to `BuildColumn` to reference a column declared
  in another Dart table.
- Add the `generateInsertable` option to `@UseRowClass`. When enabled, the generator
  will emit an extension to use the row class as an `Insertable`.
  Thanks to [@westito](https://github.com/westito).
- Allow the generator to emit correct SQL code when using arrays with the
  `new_sql_code_generation` option in specific scenarios.
- Add support for [strict tables](https://sqlite.org/stricttables.html) in `.drift` files.
- Add the `generatedAs` method to declare generated columns for Dart tables.
- Add `OrderingTerm.random` to fetch rows in a random order.
- Improved support for pausing query stream subscriptions. Instead of buffering events,
  query streams will suspend fetching data if all listeners are paused.
- Drift isolates no longer serialize messages into a primitive format. This will reduce
  the overhead of using isolates with Drift.

## 1.0.1

- Add `DoUpdate.withExcluded` to refer to the excluded row in an upsert clause.
- Add optional `where` clause to `DoUpdate` constructors

This is the initial release of the `drift` package (formally known as `moor`).
For an overview of old `moor` releases, see its [changelog](https://pub.dev/packages/moor/changelog).


text:
static bool startup_check(const SubProcess &p)
{
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(1s);
    if (p.IsRunning())
    {
        // process hasn't exited, good.
        return true;
    }
    LOGA("Electrum: startup check failed, server exited within 1 second");
    return false;
}

static void log_args(const std::string &path, const std::vector<std::string> &args)
{
    if (!Logging::LogAcceptCategory(ELECTRUM))
    {
        return;
    }

    std::stringstream ss;
    ss << path;
    for (auto &a : args)
    {
        ss << " " << a;
    }
    LOGA("Electrum: spawning %s", ss.str());
}

namespace electrum
{
ElectrumServer::ElectrumServer() : started(false), stop_requested(false) {}
ElectrumServer::~ElectrumServer()
{
    if (started)
        Stop();

    if (process_thread.joinable())
    {
        process_thread.join();
    }
}

//! called when electrs produces a line in stdout/stderr
static void callb_logger(const std::string &line) { LOGA("Electrum: %s", line); }
bool ElectrumServer::Start(int rpcport, const std::string &network)
{
    if (!GetBoolArg("-electrum", false))
    {
        LOGA("Electrum: Disabled. Not starting server.");
        return true;
    }
    return Start(electrs_path(), electrs_args(rpcport, network));
}
bool ElectrumServer::Start(const std::string &path, const std::vector<std::string> &args)
{
    stop_requested = false;
    DbgAssert(!started, return false);
    log_args(path, args);
    std::unique_lock<std::mutex> lock(process_cs);
    process.reset(new SubProcess(path, args, callb_logger, callb_logger));

    process_thread = std::thread([this]() {
        LOGA("Electrum: Starting server");
        try
        {
            this->process->Run();
        }
        catch (const subprocess_error &e)
        {
            LOGA("Electrum: Server not running: %s, exit status %d, termination signal %d", e.what(), e.exit_status,
                e.termination_signal);
        }
        catch (...)
        {
            LOGA("Electrum: Unknown error running server");
        }
        this->started = false;

        if (!stop_requested && GetBoolArg("-electrum.shutdownonerror", false))
        {
            // The electrum server exit was not initiated by us, so it
            // must have stopped due to some error.

            LOGA("Electrum: Bitcoin Unlimited is configured to exit when "
                 "electrum exits on error. Initiating shutdown.");
            StartShutdown();
        }
    });
    started = startup_check(*process);
    return started;
}

static void stop_server(SubProcess &p)
{
    if (!p.IsRunning())
    {
        return;
    }
    LOGA("Electrum: Stopping server");

    try
    {
        p.Interrupt();
    }
    catch (const subprocess_error &e)
    {
        LOGA("Electrum: %s", e.what());
        p.Terminate();
        return;
    }

    using namespace std::chrono_literals;
    using namespace std::chrono;

    auto timeout = 60s;
    auto start = system_clock::now();
    while (p.IsRunning())
    {
        if ((system_clock::now() - start) < timeout)
        {
            std::this_thread::sleep_for(1s);
            continue;
        }
        LOGA("Electrum: Timed out waiting for clean shutdown (%s seconds)", timeout.count());
        p.Terminate();
        return;
    }
}

void ElectrumServer::Stop()
{
    stop_requested = true;
    if (!started)
    {
        return;
    }
    try
    {
        std::unique_lock<std::mutex> lock(process_cs);
        stop_server(*process);
    }
    catch (const std::exception &e)
    {
        LOGA("Electrum: Error stopping server %s", e.what());
    }
    process_thread.join();
    started = false;
}

bool ElectrumServer::IsRunning() const
{
    std::unique_lock<std::mutex> lock(process_cs);
    if (!bool(process))
    {
        return false;
    }
    return process->IsRunning();
}

void ElectrumServer::NotifyNewBlock()
{
    std::unique_lock<std::mutex> lock(process_cs);
    if (!bool(process))
    {
        return;
    }
#if BOOST_OS_LINUX
    process->SendSignal(SIGUSR1);
#endif
}

ElectrumServer &ElectrumServer::Instance()
{
    static ElectrumServer instance;
    return instance;
}

} // ns electrum


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

namespace _4WormsWorldParty
{
    class WormsWorldParty
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine();
            var dataNameTeamScore = new Dictionary<string, SortedDictionary<string, int>>();

            while (input != "quit")
            {
                var tokens = input.Split("->".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var wormName = tokens[0];
                var teamName = tokens[1];
                var wormScore = int.Parse(tokens[2]);

                foreach (var uniqeName in dataNameTeamScore)
                {
                    if (uniqeName.Value.ContainsKey(wormName))
                    {
                        //input = Console.ReadLine();
                        continue;
                    }
                }

                if (!dataNameTeamScore.ContainsKey(teamName))
                {
                    dataNameTeamScore[teamName] = new SortedDictionary<string, int>();
                }
                if (!dataNameTeamScore[teamName].ContainsKey(wormName))
                {
                    dataNameTeamScore[teamName][wormName] = wormScore;
                }
                dataNameTeamScore[teamName][wormName] = wormScore;

                input = Console.ReadLine();
            }
            var ordered = dataNameTeamScore.OrderByDescending(key => key.Value.Values.Sum()).ThenByDescending(key => key.Value.Values.Sum() / key.Value.Values.Count).ToDictionary(x => x.Key, y => y.Value);
            int count = 1;
            foreach (var nameAndTeam in ordered)
            {

                var KVPteam = nameAndTeam.Key;
                var KVPname = nameAndTeam.Value;
                var sumScore = KVPname.Values.Sum();

                Console.WriteLine($"{count}. Team: {KVPteam} - {sumScore}");
                count++;
                foreach (var nameAndScore in KVPname.OrderByDescending(key => key.Value))
                {
                    var Name = nameAndScore.Key;
                    var Score = nameAndScore.Value;

                    Console.WriteLine("###{0} : {1}", Name, Score);
                }
            }
        }
    }
}


text:
package com.fullstackstarter.java.example.repository;

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends MongoRepository<User, String> {
    User findBy_id(String id);
    User findByUsername(String username);
    User findByUsernameAndPassword(String username, String password);

}


text:
package org.jenkinsci.plugins.fixedfifoqueue;

import hudson.Extension;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.queue.QueueListener;
import jenkins.model.Jenkins;

import java.util.List;

@Extension
public class FixedFifoQueueListener extends QueueListener {
    @Override
    public void onEnterWaiting(Queue.WaitingItem wi) {
        super.onEnterWaiting(wi);

        Queue.Task t = wi.task.getOwnerTask();
        if (t instanceof Job) {
            Job j = (Job) t;
            FixedFifoQueueJobProperty p = (FixedFifoQueueJobProperty) j.getProperty(FixedFifoQueueJobProperty.class);
            if (p != null && p.getLimit() > 0) {
                Queue q = Jenkins.getInstance().getQueue();
                List<Queue.Item> items;
                while ((items = q.getItems(t)).size() > p.getLimit()) {
                    q.cancel(items.get(0));
                }
            }
        }
    }
}


text:
/*
This header file allows C and C++ files to access the FPGA software (such as script C files or the main code in interface/).
init_fpga() must be called before any FPGA API is called (ie to get depth or set target yaw) because this creates a process
to communicate with the FPGA. This also creates signal handlers that try to exit gracefully on signals (most notably Ctrl+C).

Note: the function definitions are declared as 'inline' to link properly because this is a header file.

Victor Zhang - Sept 2013
*/

#ifndef __MDA_SCRIPTS_H__
#define __MDA_SCRIPTS_H__

#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "fpga_ui.h"

#ifdef __cplusplus
extern "C" {
#endif

void init_fpga();

#ifdef __cplusplus
}
#endif

inline void int_handler(int signal)
{
  // ignore SIGCHLD
  if (signal == SIGCHLD) {
    return;
  }

  // Second Ctrl+C will be raised to a kill
  static bool killed = false;
  if (killed) {
    raise(SIGKILL);
  }

  killed = true;

  // If the power is already off, just kill child and exit
  if (!get_power()) {
    kill_child();
    exit(0);
  }

  // Calling the int_handler will kill the child process (nios2-terminal)
  // Respawn it, then exit_safe
  spawn_term(NULL);

  exit_safe();
}

inline void init_fpga()
{
  static bool initialized = false;
  if (initialized) {
    return;
  }

  // Fork a nios2-terminal for communication
  spawn_term(NULL);

  // Call int_handler on SIGINT (Ctrl+C)
  signal(SIGINT, int_handler);
  // Call int_handler on SIGCHLD as well
  signal(SIGCHLD, int_handler);

  initialized = true;
}

#endif


text:
#include "ScanCommand.hpp"
#include "Shell.hpp"

using namespace oneiroi;

ScanCommand::ScanCommand( std::string name )
	: ShellCommand( name )
{

}

ScanCommand::~ScanCommand( void )
{

}

ShellCommand::ReturnType ScanCommand::execute( Shell *shell, std::istream & )
{
    shell->getSerialStream() << getName() << SerialStream::End;

    std::string response = shell->getSerialStream().readLine();
    std::cout << "SUCCESS: " << response << std::endl;

	return ShellCommand::ReturnType::SUCCESS;
}


text:
$.fn.displayComfortStep = function(options)
{
    // Will be used later for animation params
    var defauts={};
    var params=$.extend(defauts, options);

    $ajaxLoader = $("#ajaxContainerLoading");
    $ajaxLoader.show();

    $("#preUpdaterContainer").empty();
    $("#updaterLayout").show();
    $("#updaterContainer").show();

    // We need to know the destination build to resume any step
    $destinationBuild = $('#destinationBuildForAjax').val();
    $access_token =  $('#access_tokenForAjax').val();
    $url = "";

    $("#step0Updt").removeClass("on").addClass("off");

    switch(params.step) {
        case "newKey":
            $url = $("#newkeyurl").attr('data-url');
            $("#welcome").hide();
            $("#newKey").show();
            break;

        case "checkFiles":
            $url = $("#filesystemurl").attr('data-url');
            break;

        case "checkLocalErrors":
            $url = $("#checklocalerrorsurl").attr('data-url');
            break;

        case "welcome":
            $url = $("#welcomeurl").attr('data-url');
            break;

    }

    // Those datas are defined in _ajaxVariables view
    datas = 'destinationBuild=' + $destinationBuild + '&access_token=' + $access_token + '&'+csrf_token_name+'='+csrf_token;
    console.log($url);
    $.ajax({
        type: "POST",
        data: datas,
        url: $url,
        success: function(html) {
            // We hide the loader, and we append the submit new key content
            $ajaxLoader.hide();
            $("#updaterContainer").empty().append(html);

            // Menus

        },
        error :  function(html, statut){
            $("#preUpdaterContainer").empty();
            $("#updaterLayout").show();
            $("#updaterContainer").show();

            $("#updaterContainer").empty().append("you have an error, or a notice, inside your local installation of limesurvey. See :
");
            $("#updaterContainer").append(html.responseText);
        }
    });

};


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

namespace com.lover.astd.common.logicexe.equip
{
	public class MhExe : ExeBase
	{
		public MhExe()
		{
			this._name = "mh";
			this._readable = "魔化管理";
		}

        public override void init_data()
        {
            if (this._user.Level < 101)
            {
                return;
            }
            this._factory.getEquipManager().getEquipmentsCanMh(this._proto, this._logger, this._user, "");
            this.refreshUi();
        }

		public override long execute()
		{
			if (this._user.Level < 101)
			{
				return base.next_day();
			}
            Dictionary<string, string> config = base.getConfig();
            if (config.ContainsKey("enabled") && config["enabled"].ToLower().Equals("true"))
            {
                int fail_count_max = 3;
                if (config.ContainsKey("fail_count"))
                {
                    int.TryParse(config["fail_count"], out fail_count_max);
                }
                int stoneAvailable = base.getStoneAvailable();
                if (config.ContainsKey("mh_ids"))
                {
                    string mh_type = "少量";
                    if (config.ContainsKey("mh_type"))
                    {
                        mh_type = config["mh_type"];
                    }
                    string mh_idstr = config["mh_ids"];
                    this._factory.getEquipManager().handleEquipmentsCanMh(this._proto, this._logger, this._user, mh_idstr, fail_count_max, mh_type, stoneAvailable);
                    this.refreshUi();
                }
            }
            return base.next_halfhour();
		}
	}
}


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

<title>SuperCombinedManagerObjectToManageTheMostRecentHabitForUser</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.cmput301f17t07.ingroove.Model

Class SuperCombinedManagerObjectToManageTheMostRecentHabitForUser

java.lang.Object

com.cmput301f17t07.ingroove.Model.SuperCombinedManagerObjectToManageTheMostRecentHabitForUser

public class SuperCombinedManagerObjectToManageTheMostRecentHabitForUser
extends java.lang.Object

[Data Class]

 class used for holding a user, Habit, and HabitEvent for passing results from
      the findMostRecentEvent method in the DataManager

See Also:

Created by Christopher Walter on 2017-12-02.

Field Summary

Fields

Modifier and Type
Field and Description

Habit
habit

HabitEvent
habitEvent

User
user

Constructor Summary

Constructors

Constructor and Description

SuperCombinedManagerObjectToManageTheMostRecentHabitForUser(User user,
                                                           Habit habit,
                                                           HabitEvent habitEvent)

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

user

public final User user

habit

public final Habit habit

habitEvent

public final HabitEvent habitEvent

Constructor Detail

SuperCombinedManagerObjectToManageTheMostRecentHabitForUser

public SuperCombinedManagerObjectToManageTheMostRecentHabitForUser(User user,
                                                                   Habit habit,
                                                                   HabitEvent habitEvent)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "http_log.h"      // ap_log_rerror
#include "ap_config.h"
#include "apr_strings.h"
#include "apr_base64.h" // apr_base64_encode
#include "memcache.h"

#define MODTAG "CountMemCookie: "
#define MEM_MIN_COUNT  (1)
#define MEM_TABLE_SIZE_NO_LIMIT  (0)

/* apache module name */
module AP_MODULE_DECLARE_DATA count_memcookie_module;

typedef struct {
    int enabled;
    char *cookie_name;
    int mem_expiry;
    char* mem_addr;
    int mem_table_size;
    int set_header;
} count_memcookie_config;

void set_default(count_memcookie_config *conf)
{
    if(!conf){
        return;
    }
    conf->enabled = 0;
    conf->cookie_name = NULL;
    conf->mem_expiry = 0;
    conf->mem_addr = NULL;
    conf->mem_table_size = MEM_TABLE_SIZE_NO_LIMIT;
    conf->set_header = 0;
}

static void* count_memcookie_create_dir_config(apr_pool_t *p, char *d)
{
    count_memcookie_config* conf = apr_pcalloc(p, sizeof(count_memcookie_config));
    set_default(conf);
    return conf;
}

static void* count_memcookie_merge_dir_config(apr_pool_t *p,
                                void *parent_conf, void *new_conf)
{
    count_memcookie_config *pc = (count_memcookie_config *)parent_conf;
    count_memcookie_config *nc = (count_memcookie_config *)new_conf;

    count_memcookie_config *conf
            = (count_memcookie_config *) apr_pcalloc(p, sizeof(count_memcookie_config));
    conf->enabled = (nc->enabled?nc->enabled:pc->enabled);
    conf->cookie_name  = (nc->cookie_name?nc->cookie_name:pc->cookie_name);
    conf->mem_expiry   = (nc->mem_expiry?nc->mem_expiry:pc->mem_expiry);
    conf->mem_addr   = (nc->mem_addr?nc->mem_addr:pc->mem_addr);
    conf->mem_table_size   = (nc->mem_table_size?nc->mem_table_size:pc->mem_table_size);
    conf->set_header   = (nc->set_header?nc->set_header:pc->set_header);

    return conf;
}

static char* find_cookie(request_rec *r, const char* cookie_name)
{

    const char* cookies;
    char *cookie = NULL;

    /* todo: protect against xxxCookieNamexxx, regex? */
    /* todo: make case insensitive? */
    /* Get the cookie (code from mod_log_config). */
    if ((cookies = apr_table_get(r->headers_in, "Cookie"))) {
        char *start_cookie, *end_cookie;
        if ((start_cookie = ap_strstr_c(cookies, cookie_name))) {
            start_cookie += strlen(cookie_name) + 1;
            cookie = apr_pstrdup(r->pool, start_cookie);
            /* kill everything in cookie after ';' */
            end_cookie = strchr(cookie, ';');
            if (end_cookie) {
                *end_cookie = '\0';
            }
        }
    }
    if (!cookie) {
        return NULL;
    }
    return apr_pstrdup(r->pool,cookie);
}

static int set_memcookie_counter(request_rec *r, const char* key,
                    const char* mem_addr, int mem_expiry, int mem_table_size )
{
    int count = MEM_MIN_COUNT;
    char* count_str = NULL;
    size_t cur_table_size = 0;
    char* cur_table_size_str = NULL;
    int ret;
    struct memcache *mem =NULL;
    struct memcache_req *req = NULL;
    struct memcache_res *res1= NULL;
    struct memcache_res *res2= NULL;

    mem = mc_new();
    if (!mem) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, MODTAG "memcache init failure");
        return count;
    }

    /*
    * split mem_addr string into each server addr
    */
    int i=0;
    char *next, *last;
    char* mem_addr_tmp = (char*)apr_pstrdup(r->pool, mem_addr);
    next =  (char*)apr_strtok( mem_addr_tmp, ",", &last);
    while (next) {
        apr_collapse_spaces (next, next);
        ret = mc_server_add4( mem, next);
        if (ret!=0 ) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                MODTAG "mc_server_add4 failiure: svr %s err=%d",next,ret);
            mc_free(mem);
            return count;
        }
        i++;
        next = (char*)apr_strtok(NULL, ",", &last);
    }
    if ( i < 1) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, MODTAG "wrong mem_addr failure");
        mc_free(mem);
        return count;
    }

    req = mc_req_new();
    /*
    * set request keys and get results
    */
    if (mem_table_size != MEM_TABLE_SIZE_NO_LIMIT ) {
        res1 = mc_req_add( req, "tsize", strlen("tsize"));
    }
    res2 = mc_req_add( req, (char*)key, strlen(key));
    mc_get( mem, req );

    /*
    * get the user's PV count from memcached
    */
    if( !res2->val ) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, MODTAG "no value in memcached with key:%s", key);

        if (mem_table_size != MEM_TABLE_SIZE_NO_LIMIT ) {

            if( res1->val ) {
                cur_table_size = atoi( (char*)res1->val );
            }
            if (cur_table_size >=  mem_table_size) {
                ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                            MODTAG "counter table size reached max!! "
                            "please check out the value of CountMemCookieMemcachedTableSize ");
                mc_req_free( req );
                mc_free(mem);
                return count;
            }
            /*
            * save the incremented table size to memcached
            */
            cur_table_size++;
            cur_table_size_str=apr_psprintf(r->pool, "%d", cur_table_size);
            ret = mc_set(
                    mem,
                    "tsize", strlen("tsize"),
                    cur_table_size_str, strlen(cur_table_size_str),
                    0,
                    0);

            if( ret != 0 ){
                ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                                MODTAG "memcache set failure key:tsize");
                // even though cur_table_size was not saved to memcached, table size limit
                // is not so important enough to stop the rest of operations. So let it go!
            }
        }

        /*
        * save the initial count to memcached
        */
        count_str=apr_psprintf(r->pool, "%d", count);
        ret = mc_set(
                mem,
                (char*)key, strlen(key),
                count_str, strlen(count_str),
                mem_expiry,
                0);

        if( ret != 0 ){
            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                            MODTAG "memcache set failure key:%s", key);
        }
        mc_req_free( req );
        mc_free(mem);
        return count;
    }
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, MODTAG "USER COUNTER=%s", (char*)res2->val );
    count = atoi( (char*)res2->val );
    mc_req_free( req );

    /*
    * save the incremented count to memcached
    */
    count++;
    count_str=apr_psprintf(r->pool, "%d", count);
    ret = mc_set(
             mem,
             (char*)key, strlen(key),
             count_str, strlen(count_str),
             mem_expiry,
             0);

    if( ret != 0 ){
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                         MODTAG "memcache set failure key:%s", key);
    }

    mc_free(mem);
    return count;
}

static int count_memcookie_access_checker(request_rec *r)
{
    count_memcookie_config *conf = ap_get_module_config(r->per_dir_config, &count_memcookie_module);

    char* cookie;
    char* b64cookiebuf;
    int b64len;
    int curcount;
    char* curcount_str;

    if (!conf || !conf->enabled) {
        return DECLINED;
    }
    /*
    *  validation check on given info
    */
    if (!conf->cookie_name ) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                MODTAG "CountMemCookieName not specified!");
        return DECLINED;
    }
    if (!conf->mem_addr ) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                MODTAG "CountMemCookieMemcachedAddrPort not specified!");
        return DECLINED;
    }
    if (conf->mem_expiry < 1 ) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                MODTAG "CountMemCookieMemcachedObjectExpiry is invalid or  not specified!");
        return DECLINED;
    }
    if (conf->mem_table_size < 0 ) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
                MODTAG "CountMemCookieMemcachedTableSize is invalid!");
        return DECLINED;
    }

    cookie = find_cookie(r, conf->cookie_name);

    if (!cookie || strlen(cookie) < 1 ) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, MODTAG "Cookie not found!");
        return DECLINED;
    }
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, MODTAG "FOUND COOKIE %s", cookie);

    /*
    * encode cookie in base64 format
    */
    b64len = apr_base64_encode_len( strlen(cookie) );
    b64cookiebuf = (char *) apr_palloc( r->pool, b64len + 1 );
    if(!b64cookiebuf){
       ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, MODTAG "memory alloc failed!");
       return DECLINED;
    }
    apr_base64_encode(b64cookiebuf,cookie,strlen(cookie));
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, MODTAG "BASE64 COOKIE %s",  (char*)b64cookiebuf);

    curcount = set_memcookie_counter(r,b64cookiebuf,
            conf->mem_addr, conf->mem_expiry, conf->mem_table_size );

    curcount_str = apr_psprintf(r->pool, "%d", curcount );

    /* set cur count in subprocess_env table for script language */
    apr_table_setn(r->subprocess_env, "count_memcookie", curcount_str);
    /* set cur count in http header */
    if (conf->set_header) {
        apr_table_set(r->headers_in, "count_memcookie", curcount_str);
    }
    return OK;
}

static void count_memcookie_register_hooks(apr_pool_t *p)
{
    ap_hook_access_checker(count_memcookie_access_checker, NULL, NULL, APR_HOOK_MIDDLE);
}

static const command_rec count_memcookie_cmds[] =
{
    AP_INIT_FLAG("CountMemCookieEnabled", ap_set_flag_slot,
        (void *)APR_OFFSETOF(count_memcookie_config, enabled),
        OR_FILEINFO, "set \"On\" to enable count_memcookie, \"Off\" to disable"),
    AP_INIT_TAKE1("CountMemCookieName",ap_set_string_slot,
        (void *)APR_OFFSETOF(count_memcookie_config, cookie_name),
        OR_FILEINFO, "Name of cookie to lookup"),
    AP_INIT_TAKE1("CountMemCookieMemcachedAddrPort", ap_set_string_slot,
        (void *)APR_OFFSETOF(count_memcookie_config, mem_addr),
        OR_FILEINFO, "Liste of the memcached address( ip or host adresse(s) and port ':' separated). The addresses are ',' comma separated"),
    AP_INIT_TAKE1("CountMemCookieMemcachedObjectExpiry", ap_set_int_slot,
        (void *)APR_OFFSETOF(count_memcookie_config, mem_expiry),
        OR_FILEINFO, "expiry time of session object in memcached in seconds"),
    AP_INIT_TAKE1("CountMemCookieMemcachedTableSize",ap_set_int_slot,
        (void *)APR_OFFSETOF(count_memcookie_config, mem_table_size),
        OR_FILEINFO, "Max number of element in session table of memcached. 0 by default, no limit"),
    AP_INIT_FLAG("CountMemCookieSetHTTPHeader",ap_set_flag_slot,
        (void *)APR_OFFSETOF(count_memcookie_config, set_header),
        OR_FILEINFO, "Set to \"On\" to set count information to http header. \"Off\" by default"),
    {NULL}
};

/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA count_memcookie_module = {
    STANDARD20_MODULE_STUFF,
    count_memcookie_create_dir_config,        /* create per-dir    config structures */
    //count_memcookie_merge_dir_config,       /* merge  per-dir    config structures */
    NULL,                                     /* merge  per-dir    config structures */
    NULL,                                     /* create per-server config structures */
    NULL,                                     /* merge  per-server config structures */
    count_memcookie_cmds,                     /* table of config file commands       */
    count_memcookie_register_hooks            /* register hooks                      */
};

/*
 * vim:ts=4 et
 */


text:
<?php

namespace Frontend\Controller;

use Engine\Exception;
use Forms\NewVacancyForm;
use Models\Inputs;
use Models\Vacancy;
use Models\Weights;
use Phalcon\Mvc\Controller;
use Models\Candidate;
use Forms\NewCandidateForm;
use Phalcon\Mvc\View;
use Phalcon\Paginator\Adapter\Model as Paginator;

class VacanciesController extends Controller
{
    public function indexAction()
    {

    }

    public function newAction()
    {

        $form = new NewVacancyForm(null, array('edit' => true));

        if ($this->request->isPost()) {

            $data = $this->request->getPost();
            $data['created'] = date('Y-m-d H:i:s');
            $data['changed'] = date('Y-m-d H:i:s');

            $newVacancy = new Vacancy();
            $this->view->isCreating = false;

            if (!$form->isValid($data, $newVacancy)) {
                foreach ($form->getMessages() as $message) {
                    echo (
                        "

                      Увага! " . $message->getMessage() . "

" .
                        "
");
                }

                $this->view->status = false;

            } else {
                $success = $newVacancy->save($data);

                if ($success) {
                    $this->flash->success("Кандидат створений!");

                } else {
                    foreach ($newVacancy->getMessages() as $message)
                    echo ($message->getMessage());
                }

                $this->view->status = true;

                return true;
            }

        } else {

            $this->view->form = $form;
            $this->view->isCreating = true;

        }

    }

    public function listAction()
    {
        $vacancies = Vacancy::find();
        $numberPage = (!empty($this->request->get('page'))) ? $this->request->get('page') : 1;

        $this->view->vacancies = $vacancies;

        if ($vacancies) {
            $paginator = new Paginator(array(
                'data' => $vacancies,
                'limit'=> 25,
                'page' => $numberPage
            ));
            $this->view->page = $paginator->getPaginate();
        }
    }

    public function viewAction($id)
    {
        echo $id;
        if (!empty($id)) {
            $vacancy = Vacancy::findFirst($id);
            $this->view->vacancy = $vacancy;

            $inputs = Inputs::find();
            $this->view->inputs = $inputs;

        } else {
            echo 5;
            $this->dispatcher->forward(array('module' => 'frontend', 'controller' => 'vacancies', 'view' => 'list'));
        }

    }

    /**
     * Sets weights to a vacancy
     *
     * @param $id
     */
    public function setWeightsAction($id)
    {
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);

        if (isset($id)) {
            foreach (Weights::find('vacancyId=' . $id) as $weight) {
                $weight->delete();
            }

            // get ajax data
            $data = $this->request->getPost('data');

            foreach ($data as $newWeightData) {
                $newWeight = new Weights();
                $newWeight->save(array(
                    'type' => 1,
                    'vacancyId' => $id,
                    'inputId'   => $newWeightData['columnValue'],
                    'value'     => $newWeightData['inputValue'],
                    'operation' => $newWeightData['operationValue']
                ));
            }
        }

        echo json_encode($_POST);
    }

    /**
     * Returns json on vacancy's weights
     *
     * @param $id
     */
    public function getWeightsByIdAction($id)
    {
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);

        if (isset($id)) {
            $weights = Weights::find('vacancyId=' . $id)->toArray();
            $data = array();
            foreach ($weights as $weight) {
                $weight['column'] = $weight['inputId'];
                $data[] = $weight;
            }

            echo json_encode($data);
        }
    }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2750682</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753463110</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Molenkreek</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Molenkreek</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Molenkreek</Appelation>
        <LocationNameType>stream</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>4.34316</Longitude>
        <Latitude>51.617020000000004</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2750682</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import <Foundation/Foundation.h>
#import "JSONModel.h"
#import "MOZUCommerceCategory.h"

@protocol MOZUCommerceCategory
@end

/**
	The category associated with assigned products. Products, product bundles, and options can be classified to multiple categories.
*/
@interface MOZUCommerceCategory : JSONModel<MOZUCommerceCategory>

/**
Unique identifier of the source product property. For a product field it will be the name of the field. For a product attribute it will be the Attribute FQN.
*/
@property(nonatomic) NSNumber * id;

/**
If applicable, the parent category in the category tree. This can be associated to a product as the parent category.
*/
@property(nonatomic) MOZUCommerceCategory *parent;

@end


text:
<?php
/////// Update your database login details here /////
$dbhost_name = "localhost"; // Your host name
$database = "khcy3nti_g5-Airlines";       // Your database name
$username = "khcy3nti_vic";            // Your login userid
$password = "V7ba2oPhQrkM";            // Your password
//////// End of database details of your server //////

$con = mysqli_connect("localhost","khcy3nti_vic","V7ba2oPhQrkM","khcy3nti_g5-Airlines");

if (mysqli_connect_errno($con))
{
    echo "Connection failed" . mysqli_connect_error();
}

else
{
    //echo "Connection successful";
}

//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$dbhost_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>


text:
// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#pragma once

#include <cstddef>

namespace aliceVision {
namespace image {
  /**
   ** Filter an extended row [halfKernelSize][row][halfKernelSize]
   ** @param buffer data to filter
   ** @param kernel kernel array
   ** @param rsize buffer length
   ** @param ksize kernel length
  **/
  template<class T1, class T2> inline
  void conv_buffer_( T1* buffer, const T2* kernel, int rsize, int ksize )
  {
    for( std::size_t i = 0; i < rsize; ++i )
    {
      T2 sum( 0 );
      for ( std::size_t j = 0; j < ksize; ++j )
      {
        sum += buffer[i + j] * kernel[j];
      }
      buffer[i] = sum;
    }
  }
} // namespace image
} // namespace aliceVision


text:
import os
from os import listdir
from os.path import *
import sys
from sys import stdin, stdout, stderr, exit
from pprint import pprint
from glob import glob

import logging
from logging import debug, info, warning, error
logging.basicConfig(format='{}: %(levelname)s: %(message)s'.format(__file__))

if sys.stdout.isatty():
    def _yap_color(s, code):
        ' Make `s` a colored text. Can be nested. '
        return '{}{}{}'.format(
            code,
            s.replace('\033[0m', code),
            '\033[0m',
        )

    def blue(s):
        return _yap_color(s, '\033[94m')

    def gray(s):
        return _yap_color(s, '\033[97m')

    def green(s):
        return _yap_color(s, '\033[92m')

    def orange(s):
        return _yap_color(s, '\033[93m')

    def red(s):
        return _yap_color(s, '\033[91m')

else:
    blue = gray = green = orange = red = _yap_color = lambda s, c='': s

import json
from itertools import zip_longest

def split_lines_fields(s):
    return list(map(str.split, s.splitlines()))

def split_fields_lines(s):
    return list(zip_longest(*split_lines_fields(s)))

def concat(strings):
    return ''.join(strings)

def joinlines(lines):
    return '\n'.join(lines)

def joinfields(fields):
    return ' '.join(fields)

def joinpaths(*args):
    return os.sep.join(args)

def read(filename):
    with open(filename) as fd:
        return filename.read()

def write(filename, content):
    with open(filename, 'w') as fd:
        fd.write(content)

def grep(regex, lines):
    if isinstance(lines, str):
        lines = lines.splitlines()
    regexc = re.compile(regex)
    return filter(regexc.search, lines)

def listget(array, i, alt=None):
    return array[i] if 0 <= i < len(array) else alt

class MissingParameter(object):
    def __init__(self, what):
        self.what = what

    def access(self, *args):
        raise KeyError(self.what)

    __str__ = __repr__ = __getitem__ = __getattr__ = __getslice__ = __call__ = access
    __int__ = __add__ = __sub__ = __gt__ = __lt__ = __ge__ = __le__ = access

    def __bool__(self):
        return False

def missingget(obj, variable):
    v = obj.get(variable)
    return v if v is not None else MissingParameter(variable)

def missingindex(array, i):
    return array[i] if 0 <= i < len(array) else MissingParameter(
        "Argument {}".format(i))

from subprocess import Popen, PIPE, STDOUT, CalledProcessError
import re

re_escape_sh = re.compile(r'([\\ ])')

def escape_sh(s):
    return re_escape_sh.sub(r'\\\1', s)

def yap_call(cmd, flags='', infile=None, convert=None, outfile=None):
    if 'h' in flags:  # Shell mode
        cmd = ' '.join(map(escape_sh, cmd))
    if infile is None or hasattr(infile, 'fileno'):
        infd = infile
        indata = None
    else:
        infd = PIPE
        indata = infile
    outfd = outfile or PIPE

    proc = Popen(
        cmd,
        stdin=infd,
        stdout=outfd if ('o' in flags or 'O' in flags) else None,
        stderr=(
            outfd if 'e' in flags else
            STDOUT if 'O' in flags else None),
        universal_newlines='b' not in flags,
        shell='h' in flags,
        env={} if 'v' in flags else None,
        bufsize=-1,  # Buffered
    )
    if 'p' in flags:  # Run in the background
        return proc

    out, err = proc.communicate(indata)
    if outfile:
        outfile.close()

    code = proc.returncode
    ret = []
    if ('o' in flags or 'O' in flags):
        if convert:
            ret.append(convert(out))
        else:
            ret.append(out)
    if 'e' in flags:
        ret.append(err)
    if 'r' in flags:
        ret.append(code)
    else:  # The user won't check the return code, so do it now
        if code != 0 and 'n' not in flags:
            raise CalledProcessError(code, cmd, ret)
    # Return either the unique output, the list of outputs, or None
    return ret[0] if len(ret) == 1 else ret or None

#!./yap.py
# vim: set ft=python:

__doc__ = '''
Doc string
Usage: cmd.yp command argument
'''

if missingindex(sys.argv, 1) == 'list':
    print(gray('Listing nicely'))
    filenames = listdir(missingindex(sys.argv, 2) or '.')
    for name in filenames:
        print(
            blue(name.rjust(15)),
            joinfields(
                (yap_call(["file", str(name)], "fo", (None), str.split, None))[1:]
            )
        )

elif missingindex(sys.argv, 1) == 'write':
    yap_call(["echo", "Out"], "o", (None), None, open(missingindex(sys.argv, 2) or "default.txt", "w"))

elif missingindex(sys.argv, 1) == 'grep':
    print(concat(
        grep(missingindex(sys.argv, 2), open(missingindex(sys.argv, 3)))
    ))

elif missingindex(sys.argv, 1) == 'demo':
    (yap_call(["echo"], "", ("Hi!"), None, None))
    (yap_call(["cmd"], "", (open("input.txt" , "r")), None, None))
    (yap_call([], "o", ("data"), None, open("out.txt", "w")))
    (yap_call(["echo"], "", (open("input.txt" , "r")), None, None))

else:
    print(red('Unknown command: %s' % missingindex(sys.argv, 1)))


text:
require_relative '../../../libraries/helpers'

describe OpenSSLCookbook::Helpers do
  let(:instance) do
    Class.new { include OpenSSLCookbook::Helpers }.new
  end

  describe '.included' do
    it 'requires openssl' do
      instance
      expect(defined?(OpenSSL)).to_not be(false)
    end
  end

  # Path helpers
  describe '#get_key_filename' do
    context 'When the input is not a string' do
      it 'Throws a TypeError' do
        expect do
          instance.get_key_filename(33)
        end.to raise_error(TypeError)
      end
    end

    context 'when the input is a string' do
      it 'Generates valid keyfile names' do
        expect(instance.get_key_filename('/etc/temp.crt')).to match('/etc/temp.key')
      end
    end
  end

  # Validation helpers
  describe '#key_length_valid?' do
    context 'When the number is less than 1024' do
      it 'returns false' do
        expect(instance.key_length_valid?(1023)).to be_falsey
        expect(instance.key_length_valid?(2)).to be_falsey
        expect(instance.key_length_valid?(64)).to be_falsey
        expect(instance.key_length_valid?(512)).to be_falsey
      end
    end

    context 'When the number is greater than 1024 but is not a power of 2' do
      it 'returns false' do
        expect(instance.key_length_valid?(1025)).to be_falsey
        expect(instance.key_length_valid?(6666)).to be_falsey
        expect(instance.key_length_valid?(8191)).to be_falsey
      end
    end

    context 'When the number is a power of 2, equal to or greater than 1024' do
      it 'returns true' do
        expect(instance.key_length_valid?(1024)).to be_truthy
        expect(instance.key_length_valid?(2048)).to be_truthy
        expect(instance.key_length_valid?(4096)).to be_truthy
        expect(instance.key_length_valid?(8192)).to be_truthy
      end
    end
  end

  describe '#dhparam_pem_valid?' do
    require 'tempfile'

    before(:each) do
      @dhparam_file = Tempfile.new('dhparam')
    end

    context 'When the dhparam.pem file does not exist' do
      it 'returns false' do
        expect(instance.dhparam_pem_valid?('/tmp/bad_filename')).to be_falsey
      end
    end

    context 'When the dhparam.pem file does exist, but does not contain a valid dhparam key' do
      it 'Throws an OpenSSL::PKey::DHError exception' do
        expect do
          @dhparam_file.puts('I_am_not_a_key_I_am_a_free_man')
          @dhparam_file.close
          instance.dhparam_pem_valid?(@dhparam_file.path)
        end.to raise_error(OpenSSL::PKey::DHError)
      end
    end

    context 'When the dhparam.pem file does exist, and does contain a vaild dhparam key' do
      it 'returns true' do
        @dhparam_file.puts(OpenSSL::PKey::DH.new(1024).to_pem)
        @dhparam_file.close
        expect(instance.dhparam_pem_valid?(@dhparam_file.path)).to be_truthy
      end
    end

    after(:each) do
      @dhparam_file.unlink
    end
  end

  describe '#key_file_valid?' do
    require 'tempfile'
    require 'openssl' unless defined?(OpenSSL)

    cipher = OpenSSL::Cipher::Cipher.new('des3')

    before(:each) do
      @keyfile = Tempfile.new('keyfile')
    end

    context 'When the key file does not exist' do
      it 'returns false' do
        expect(instance.key_file_valid?('/tmp/bad_filename')).to be_falsey
      end
    end

    context 'When the key file does exist, but does not contain a valid rsa private key' do
      it 'Throws an OpenSSL::PKey::RSAError exception' do
        expect do
          @keyfile.puts('I_am_not_a_key_I_am_a_free_man')
          @keyfile.close
          instance.key_file_valid?(@keyfile.path)
        end.to raise_error(OpenSSL::PKey::RSAError)
      end
    end

    context 'When the key file does exist, and does contain a vaild rsa private key' do
      it 'returns true' do
        @keyfile.puts(OpenSSL::PKey::RSA.new(2048).to_pem)
        @keyfile.close
        expect(instance.key_file_valid?(@keyfile.path)).to be_truthy
      end
    end

    context 'When a valid keyfile requires a passphrase, and an invalid passphrase is supplied' do
      it 'Throws an OpenSSL::PKey::RSAError exception' do
        expect do
          @keyfile.puts(OpenSSL::PKey::RSA.new(2048).to_pem(cipher, 'oink'))
          @keyfile.close
          instance.key_file_valid?(@keyfile.path, 'poml')
        end.to raise_error(OpenSSL::PKey::RSAError)
      end
    end

    context 'When a valid keyfile requires a passphrase, and a valid passphrase is supplied' do
      it 'returns true' do
        @keyfile.puts(OpenSSL::PKey::RSA.new(2048).to_pem(cipher, 'oink'))
        @keyfile.close
        expect(instance.key_file_valid?(@keyfile.path, 'oink')).to be_truthy
      end
    end

    after(:each) do
      @keyfile.unlink
    end
  end

  # Generators
  describe '#gen_dhparam' do
    context 'When given an invalid key length' do
      it 'Throws an ArgumentError' do
        expect do
          instance.gen_dhparam(2046, 2)
        end.to raise_error(ArgumentError)
      end
    end

    context 'When given an invalid generator id' do
      it 'Throws a TypeError' do
        expect do
          instance.gen_dhparam(2048, 'bob')
        end.to raise_error(TypeError)
      end
    end

    context 'When a proper key length and generator id are given' do
      it 'Generates a dhparam object' do
        expect(instance.gen_dhparam(1024, 2)).to be_kind_of(OpenSSL::PKey::DH)
      end
    end
  end

  describe '#gen_rsa_key' do
    context 'When given an invalid key length' do
      it 'Throws an ArgumentError' do
        expect do
          instance.gen_rsa_key(4093)
        end.to raise_error(ArgumentError)
      end
    end

    context 'When a proper key length is given' do
      it 'Generates an RSA key object' do
        expect(instance.gen_rsa_key(1024)).to be_kind_of(OpenSSL::PKey::RSA)
      end
    end
  end

  describe '#encrypt_rsa_key' do
    before(:all) do
      @rsa_key = OpenSSL::PKey::RSA.new(1024)
    end

    context 'When given anything other than an RSA key object to encrypt' do
      it 'Raises a TypeError' do
        expect do
          instance.encrypt_rsa_key('abcd', 'defg')
        end.to raise_error(TypeError)
      end
    end

    context 'When given anything other than a string as the passphrase' do
      it 'Raises a TypeError' do
        expect do
          instance.encrypt_rsa_key(@rsa_key, 1234)
        end.to raise_error(TypeError)
      end
    end

    context 'When given a valid RSA key and a valid passphrase string' do
      it 'Generates a valid encrypted PEM' do
        @encrypted_key = instance.encrypt_rsa_key(@rsa_key, 'oink')
        expect(@encrypted_key).to be_kind_of(String)
        expect(OpenSSL::PKey::RSA.new(@encrypted_key, 'oink').private?).to be_truthy
      end
    end
  end
end


text:
namespace Synchronica.Schema
{

using FlatBuffers;

public sealed class StepKeyFrameData_Boolean : Table {
  public static StepKeyFrameData_Boolean GetRootAsStepKeyFrameData_Boolean(ByteBuffer _bb) { return GetRootAsStepKeyFrameData_Boolean(_bb, new StepKeyFrameData_Boolean()); }
  public static StepKeyFrameData_Boolean GetRootAsStepKeyFrameData_Boolean(ByteBuffer _bb, StepKeyFrameData_Boolean obj) { return (obj.__init(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
  public StepKeyFrameData_Boolean __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }

  public int Time { get { int o = __offset(4); return o != 0 ? bb.GetInt(o + bb_pos) : (int)0; } }
  public bool Value { get { int o = __offset(6); return o != 0 ? 0!=bb.Get(o + bb_pos) : (bool)false; } }

  public static Offset<StepKeyFrameData_Boolean> CreateStepKeyFrameData_Boolean(FlatBufferBuilder builder,
      int time = 0,
      bool value = false) {
    builder.StartObject(2);
    StepKeyFrameData_Boolean.AddTime(builder, time);
    StepKeyFrameData_Boolean.AddValue(builder, value);
    return StepKeyFrameData_Boolean.EndStepKeyFrameData_Boolean(builder);
  }

  public static void StartStepKeyFrameData_Boolean(FlatBufferBuilder builder) { builder.StartObject(2); }
  public static void AddTime(FlatBufferBuilder builder, int time) { builder.AddInt(0, time, 0); }
  public static void AddValue(FlatBufferBuilder builder, bool value) { builder.AddBool(1, value, false); }
  public static Offset<StepKeyFrameData_Boolean> EndStepKeyFrameData_Boolean(FlatBufferBuilder builder) {
    int o = builder.EndObject();
    return new Offset<StepKeyFrameData_Boolean>(o);
  }
};

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Upstar Music</title>


text:
/////////////////////////////////////////////////////////////////////////////
// fuzzy.cc
//
// SIMLIB version: 2.16.2
// Date: 2001-04-04
// Copyright (c) 1999-2001  David Martinek, Dr. Ing. Petr Peringer
//
// This library is licensed under GNU Library GPL. See the file COPYING.
//
// Warning: this is EXPERIMENTAL code, interfaces can be changed
//
// Fuzzy subsystem for SIMLIB
// version 0.6 --- We apr 4 10:33:52 CEST 2001
//
/////////////////////////////////////////////////////////////////////////////
// Implementation of fuzzy set and fuzzy variable.
/////////////////////////////////////////////////////////////////////////////

#include "simlib.h"
#include "fuzzy.h"
#include "internal.h"

#include <cstdio>
#include <cassert>
#include <cmath>

#include <string.h>

namespace simlib3 {

/**
 * Creates fuzzy set.
 * @param min Minimal value of universum.
Spodní mez univerza.
 * @param max Maximal value of universum.
Horní mez univerza.
 */
FuzzySet::FuzzySet(const char * name, double min, double max)
 : n(0), xmin(min), xmax(max)
{
  Name = strdup(name);
}

/**
 * Creates fuzzy set.
 * @param min Minimal value of universum.
Spodní mez univerza.
 * @param max Maximal value of universum.
Horní mez univerza.
 */
FuzzySet::FuzzySet(const char * name, double min, double max,
    const FuzzyMembershipFunction &m1)
 : n(0), xmin(min), xmax(max)
{
  Name = strdup(name);
  add(m1);
}

/**
 * Creates fuzzy set.
 * @param min Minimal value of universum.
Spodní mez univerza.
 * @param max Maximal value of universum.
Horní mez univerza.
 */
FuzzySet::FuzzySet(const char * name, double min, double max,
             const FuzzyMembershipFunction &m1,
	     const FuzzyMembershipFunction &m2)
 : n(0), xmin(min), xmax(max)
{
  Name = strdup(name);
  add(m1);
  add(m2);
}

/**
 * Creates fuzzy set.
 * @param min Minimal value of universum.
Spodní mez univerza.
 * @param max Maximal value of universum.
Horní mez univerza.
 */
FuzzySet::FuzzySet(const char * name, double min, double max,
             const FuzzyMembershipFunction &m1,
	     const FuzzyMembershipFunction &m2,
	     const FuzzyMembershipFunction &m3)
 : n(0), xmin(min), xmax(max)
{
  Name = strdup(name);
  add(m1);
  add(m2);
  add(m3);
}

/**
 * Creates fuzzy set.
 * @param min Minimal value of universum.
Spodní mez univerza.
 * @param max Maximal value of universum.
Horní mez univerza.
 */
FuzzySet::FuzzySet(const char * name, double min, double max,
             const FuzzyMembershipFunction &m1,
	     const FuzzyMembershipFunction &m2,
	     const FuzzyMembershipFunction &m3,
	     const FuzzyMembershipFunction &m4)
 : n(0), xmin(min), xmax(max)
{
  Name = strdup(name);
  add(m1);
  add(m2);
  add(m3);
  add(m4);
}

/**
 * Creates fuzzy set.
 * @param min Minimal value of universum.
Spodní mez univerza.
 * @param max Maximal value of universum.
Horní mez univerza.
 */
FuzzySet::FuzzySet(const char * name, double min, double max,
             const FuzzyMembershipFunction &m1,
	     const FuzzyMembershipFunction &m2,
	     const FuzzyMembershipFunction &m3,
	     const FuzzyMembershipFunction &m4,
	     const FuzzyMembershipFunction &m5)
 : n(0), xmin(min), xmax(max)
{
  Name = strdup(name);
  add(m1);
  add(m2);
  add(m3);
  add(m4);
  add(m5);
}

/**
 * It adds next word value into the universum.
Pøidá dal¹í slovní hodnotu do univerza.
 * @param x Membership function representing word value.
Funkce pøíslu¹nosti reprezentující slovní hodnotu.
 */
void FuzzySet::add(const FuzzyMembershipFunction &x)
{
  TRACE(printf("FuzzySet::add(%s)\n", x.wordValue()));
  if (n >= MAX) SIMLIB_error("FuzzySet limit exceeded");
  array[n++] = x.clone();
}

/** It duplicates object.
Duplikuje objekt. */
// implemented in fuzzy.cc
FuzzySet *FuzzySet::clone() const
{
  FuzzySet * result = new FuzzySet(*this);
  result->Name = strdup(Name);
  for (unsigned i = 0; i < n; i++)
  {
    result->array[i] = array[i]->clone();
  }
  return result;
}

/** It selects i-th member function.
Vybere i-tou funkci pøíslu¹nosti. */
const FuzzyMembershipFunction *FuzzySet::operator[] (int i) const
{
  if (unsigned(i) >= n)
  	SIMLIB_error("FuzzySet[]: index out of range");
  return array[i];
}

/** It computes i-th function value (membership).
Vypoète i-tou funkèní hodnotu (pøíslu¹nost). */
double FuzzySet::Membership(int i, double x) const
{
  if (unsigned(i) >= n)
    SIMLIB_error("FuzzySet::Membership: index out of range");
  return array[i]->Membership(x);
}

/** Destructor removes all membership functions.
Destruktor uvolní v¹echny funkce pøíslu¹nosti. */
FuzzySet::~FuzzySet()
{
  TRACE(printf("~FuzzySet()\n"));
  for (unsigned i = 0; i < n; i++)
	  delete array[i]; // clean memory
  delete [] Name;
}

//// info functions

/** Minimum of maxims.
Minimum z maxim. */
double FuzzySet::min1()
{
  double min;
  assert(count()>0);
  min = array[0]->min1();
  for(int i=1; i<count(); i++)
  {
    double m = array[i]->min1();
    if(m<min) min = m;
  }
  return min;
}

/** Maximum of maxims.
Maximum z maxim. */
double FuzzySet::max1()
{
  double max;
  assert(count()>0);
  max = array[0]->max1();
  for(int i=1; i<count(); i++)
  {
    double m = array[i]->max1();
    if(m<max) max = m;
  }
  return max;
}

extern FuzzyBlock *activeFuzzyBlock;

/////////////////////////////////////////////////////////////////////////////
// fuzzy set
//
// TODO: add refcount to setType
/**
 * It connects fuzzy set with variable.
Spojí fuzzy mno¾inu s fuzzy promìnnou.
 * @param t Fuzzy set.
Fuzzy mno¾ina.
 */
FuzzyVariable::FuzzyVariable(const FuzzySet &t) : n(t.count())
{
  TRACE(printf("FuzzyVariable::FuzzyVariable()\n"));
  assert(n > 0);
  m = t.clone();
  mval = new double[n];
  // create empty/zero Fuzzy set ???
  for(unsigned i = 0; i < n; i++) mval[i] = 0.0F;

  if (activeFuzzyBlock != 0)
    registerOwner(activeFuzzyBlock);
  // jinak se bude registrovat pozdeji explicitne.
/*
  where = activeFuzzyBlock;
  if(where==0) SIMLIB_error("Fuzzy set should be used inside FuzzyBlock only");
  where->Register(this); // register this object in list of block contents
*/
}

/**
 * It registers owner of this variable.
Zaregistruje vlastníka této promìnné.
 * @param owner Owner of this variable.
Vlastník této promìnné.
 */
void FuzzyVariable::registerOwner(FuzzyBlock *owner)
{
  where = owner;
  where->Register(this);
}

/** I-th member function.
I-tá funkce pøíslu¹nosti. */
// get membership function
const FuzzyMembershipFunction *FuzzyVariable::mf(int i) const
{
  if(unsigned(i)>=n)
    SIMLIB_error("FuzzyVariable::mf(i) index out of range");
  return (*m)[i];
}

/** It gets center of i-th member function.
Vrací støed i-té funkce pøíslu¹nosti. */
double FuzzyVariable::center(int i) const
{
  return mf(i)->center();
}

/** It gets i-th word value.
Vrací i-tou slovní hondotu. */
const char *FuzzyVariable::wordValue(int i) const
{
  return mf(i)->wordValue();
}

/** Get/set fuzzy value.
Vra»/nastav fuzzy hodnotu. */
double &FuzzyVariable::operator[] (int i) const
{
  if(unsigned(i)>=n)
    SIMLIB_error("FuzzyVariable::[i] index out of range");
  return mval[i];
}

// print fuzzy set contents
void FuzzyVariable::Print()
{
  printf("%s : {", m->name());
  for (unsigned i = 0; i < n; i++)
  {
    if(mval[i]<0.0||mval[i]>1.0) printf(" ***");
    if (mval[i] != 0) printf(" %s=%5.3f%c", wordValue(i), mval[i], (i<n-1)?',':' ');
  }
  printf("}\n");
}

/** Search by member name.
Hledá podle jména. */
unsigned FuzzyVariable::search(const char *s) const
{
  for (unsigned i = 0; i < n; i++)
    if (strcmp(s, (*m)[i]->wordValue()) == 0) return i;
  SIMLIB_error("FuzzyVariable::search(name) bad name '%s'",s); // no return
  return 0;
}

// compute and set membership of i-th member
double FuzzyVariable::SetMembership(int i, double x)
{
  return mval[i] = m->Membership(i,x);
}

} // namespace

// end


text:
module.exports = function (config) {
  config.set({
    browsers: ['PhantomJS'], // run in PhantomJS, Chrome, ...
    singleRun: false, // true = just run once by default
    autoWatch: true,
    basePath: '',
    frameworks: [
      'intl-shim',
      'tap'
    ],
    colors: true, // enable / disable colors in the output (reporters and logs)
    logLevel: config.LOG_DISABLE, // level of logging - possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    plugins: [
      'karma-spec-reporter',
      'karma-tap-pretty-reporter',
      'karma-chrome-launcher',
      'karma-phantomjs-launcher',
      'karma-tap',
      'karma-intl-shim',
      'karma-sourcemap-loader',
      'karma-webpack'
    ],
    files: [ // just load this file
      'node_modules/babel-polyfill/dist/polyfill.js',
      'webpack.config.tests.js'
    ],
    preprocessors: {
      'webpack.config.tests.js': [ // preprocess with webpack and our sourcemap loader
        'webpack',
        'sourcemap'
      ]
    },
    reporters: ['tap-pretty'], // report results in this format - ex. dots, progress, spec, tap-pretty
    tapReporter: {
      prettify: require('faucet'), // default 'standard TAP' output
      separator: '======= rerun tests'
    },
    // webpack: webpackConfig,
    webpack: {
      externals: {
        // Allow Enzyme to work with webpack
        'react/addons': true,
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true
      },
      node: {
        fs: 'empty'
      },
      devtool: 'sourcemap',
      resolve: {
        extensions: ['', '.js', '.jsx', '.json']
      },
      module: {
        loaders: [
          {
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            loader: 'babel',
            query: {
              presets: [
                "react",
                "es2015",
                "stage-0"
              ],
              plugins: [
                'react-html-attrs'
              ]
            }
          },
          // Allow Enzyme to work with webpack
          {
            test: /\.json$/,
            loader: 'json-loader'
          }
        ]
      }

    },

    phantomjsLauncher: {
      exitOnResourceError: true // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
    },
    webpackServer: {
      noInfo: true // please don't spam the console when running in karma!
    }
  });
};


text:
from google.net.proto import ProtocolBuffer
import array
import dummy_thread as thread

__pychecker__ = """maxreturns=0 maxbranches=0 no-callinit
                   unusednames=printElemNumber,debug_strs no-special"""

from google.appengine.api.api_base_pb import VoidProto
class BlobstoreServiceError(ProtocolBuffer.ProtocolMessage):

  OK           =    0
  INTERNAL_ERROR =    1
  URL_TOO_LONG =    2
  PERMISSION_DENIED =    3

  _ErrorCode_NAMES = {
    0: "OK",
    1: "INTERNAL_ERROR",
    2: "URL_TOO_LONG",
    3: "PERMISSION_DENIED",
  }

  def ErrorCode_Name(cls, x): return cls._ErrorCode_NAMES.get(x, "")
  ErrorCode_Name = classmethod(ErrorCode_Name)

  def __init__(self, contents=None):
    pass
    if contents is not None: self.MergeFromString(contents)

  def MergeFrom(self, x):
    assert x is not self

  def Equals(self, x):
    if x is self: return 1
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    return initialized

  def ByteSize(self):
    n = 0
    return n + 0

  def Clear(self):
    pass

  def OutputUnchecked(self, out):
    pass

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
  }, 0)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
  }, 0, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""
class CreateUploadURLRequest(ProtocolBuffer.ProtocolMessage):
  has_success_path_ = 0
  success_path_ = ""

  def __init__(self, contents=None):
    if contents is not None: self.MergeFromString(contents)

  def success_path(self): return self.success_path_

  def set_success_path(self, x):
    self.has_success_path_ = 1
    self.success_path_ = x

  def clear_success_path(self):
    if self.has_success_path_:
      self.has_success_path_ = 0
      self.success_path_ = ""

  def has_success_path(self): return self.has_success_path_

  def MergeFrom(self, x):
    assert x is not self
    if (x.has_success_path()): self.set_success_path(x.success_path())

  def Equals(self, x):
    if x is self: return 1
    if self.has_success_path_ != x.has_success_path_: return 0
    if self.has_success_path_ and self.success_path_ != x.success_path_: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    if (not self.has_success_path_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: success_path not set.')
    return initialized

  def ByteSize(self):
    n = 0
    n += self.lengthString(len(self.success_path_))
    return n + 1

  def Clear(self):
    self.clear_success_path()

  def OutputUnchecked(self, out):
    out.putVarInt32(10)
    out.putPrefixedString(self.success_path_)

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if tt == 10:
        self.set_success_path(d.getPrefixedString())
        continue
      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    if self.has_success_path_: res+=prefix+("success_path: %s\n" % self.DebugFormatString(self.success_path_))
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  ksuccess_path = 1

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
    1: "success_path",
  }, 1)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
    1: ProtocolBuffer.Encoder.STRING,
  }, 1, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""
class CreateUploadURLResponse(ProtocolBuffer.ProtocolMessage):
  has_url_ = 0
  url_ = ""

  def __init__(self, contents=None):
    if contents is not None: self.MergeFromString(contents)

  def url(self): return self.url_

  def set_url(self, x):
    self.has_url_ = 1
    self.url_ = x

  def clear_url(self):
    if self.has_url_:
      self.has_url_ = 0
      self.url_ = ""

  def has_url(self): return self.has_url_

  def MergeFrom(self, x):
    assert x is not self
    if (x.has_url()): self.set_url(x.url())

  def Equals(self, x):
    if x is self: return 1
    if self.has_url_ != x.has_url_: return 0
    if self.has_url_ and self.url_ != x.url_: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    if (not self.has_url_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: url not set.')
    return initialized

  def ByteSize(self):
    n = 0
    n += self.lengthString(len(self.url_))
    return n + 1

  def Clear(self):
    self.clear_url()

  def OutputUnchecked(self, out):
    out.putVarInt32(10)
    out.putPrefixedString(self.url_)

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if tt == 10:
        self.set_url(d.getPrefixedString())
        continue
      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    if self.has_url_: res+=prefix+("url: %s\n" % self.DebugFormatString(self.url_))
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  kurl = 1

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
    1: "url",
  }, 1)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
    1: ProtocolBuffer.Encoder.STRING,
  }, 1, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""
class DeleteBlobRequest(ProtocolBuffer.ProtocolMessage):

  def __init__(self, contents=None):
    self.blob_key_ = []
    if contents is not None: self.MergeFromString(contents)

  def blob_key_size(self): return len(self.blob_key_)
  def blob_key_list(self): return self.blob_key_

  def blob_key(self, i):
    return self.blob_key_[i]

  def set_blob_key(self, i, x):
    self.blob_key_[i] = x

  def add_blob_key(self, x):
    self.blob_key_.append(x)

  def clear_blob_key(self):
    self.blob_key_ = []

  def MergeFrom(self, x):
    assert x is not self
    for i in xrange(x.blob_key_size()): self.add_blob_key(x.blob_key(i))

  def Equals(self, x):
    if x is self: return 1
    if len(self.blob_key_) != len(x.blob_key_): return 0
    for e1, e2 in zip(self.blob_key_, x.blob_key_):
      if e1 != e2: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    return initialized

  def ByteSize(self):
    n = 0
    n += 1 * len(self.blob_key_)
    for i in xrange(len(self.blob_key_)): n += self.lengthString(len(self.blob_key_[i]))
    return n + 0

  def Clear(self):
    self.clear_blob_key()

  def OutputUnchecked(self, out):
    for i in xrange(len(self.blob_key_)):
      out.putVarInt32(10)
      out.putPrefixedString(self.blob_key_[i])

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if tt == 10:
        self.add_blob_key(d.getPrefixedString())
        continue
      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    cnt=0
    for e in self.blob_key_:
      elm=""
      if printElemNumber: elm="(%d)" % cnt
      res+=prefix+("blob_key%s: %s\n" % (elm, self.DebugFormatString(e)))
      cnt+=1
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  kblob_key = 1

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
    1: "blob_key",
  }, 1)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
    1: ProtocolBuffer.Encoder.STRING,
  }, 1, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""

__all__ = ['BlobstoreServiceError','CreateUploadURLRequest','CreateUploadURLResponse','DeleteBlobRequest']


text:
<template name="components_settings">

rpc provider: <input type="text" value="http://localhost:8080" class="form-control" placeholder="Address" id="rpcProvider">
 {{{i18n 'dapp.app.copyright'}}}

        <button class="btn btn-default btn-sm" style="margin-top: 10px;" id="connect">Connect </button>
        <button class="btn btn-default btn-sm" style="margin-top: 10px;" data-toggle="collapse" data-target="#recommendedSettings">GETH Settings</button>

geth --rpc --rpcaddr="{{$.Session.get 'providerHost'}}" --mine --unlock=primary --rpcport="{{$.Session.get 'providerPort'}}" --rpccorsdomain="http://meteor-dapp-cosmo.meteor.com" --loglevel=5 --maxpeers=0

</template>


text:
( function() {

	function setupAdvParams( element ) {
		var attrName = this.att;

		var value = element && element.hasAttribute( attrName ) && element.getAttribute( attrName ) || '';

		if ( value !== undefined )
			this.setValue( value );
	}

	function commitAdvParams() {
		// Dialogs may use different parameters in the commit list, so, by
		// definition, we take the first CKEDITOR.dom.element available.
		var element;

		for ( var i = 0; i < arguments.length; i++ ) {
			if ( arguments[ i ] instanceof CKEDITOR.dom.element ) {
				element = arguments[ i ];
				break;
			}
		}

		if ( element ) {
			var attrName = this.att,
				value = this.getValue();

			if ( value )
				element.setAttribute( attrName, value );
			else
				element.removeAttribute( attrName, value );
		}
	}

	var defaultTabConfig = { id: 1, dir: 1, classes: 1, styles: 1 };

	CKEDITOR.plugins.add( 'dialogadvtab', {
		requires: 'dialog',

		// Returns allowed content rule for the content created by this plugin.
		allowedContent: function( tabConfig ) {
			if ( !tabConfig )
				tabConfig = defaultTabConfig;

			var allowedAttrs = [];
			if ( tabConfig.id )
				allowedAttrs.push( 'id' );
			if ( tabConfig.dir )
				allowedAttrs.push( 'dir' );

			var allowed = '';

			if ( allowedAttrs.length )
				allowed += '[' + allowedAttrs.join( ',' ) +  ']';

			if ( tabConfig.classes )
				allowed += '(*)';
			if ( tabConfig.styles )
				allowed += '{*}';

			return allowed;
		},

		// @param tabConfig
		// id, dir, classes, styles
		createAdvancedTab: function( editor, tabConfig, element ) {
			if ( !tabConfig )
				tabConfig = defaultTabConfig;

			var lang = editor.lang.common;

			var result = {
				id: 'advanced',
				label: lang.advancedTab,
				title: lang.advancedTab,
				elements: [ {
					type: 'vbox',
					padding: 1,
					children: []
				} ]
			};

			var contents = [];

			if ( tabConfig.id || tabConfig.dir ) {
				if ( tabConfig.id ) {
					contents.push( {
						id: 'advId',
						att: 'id',
						type: 'text',
						requiredContent: element ? element + '[id]' : null,
						label: lang.id,
						setup: setupAdvParams,
						commit: commitAdvParams
					} );
				}

				if ( tabConfig.dir ) {
					contents.push( {
						id: 'advLangDir',
						att: 'dir',
						type: 'select',
						requiredContent: element ? element + '[dir]' : null,
						label: lang.langDir,
						'default': '',
						style: 'width:100%',
						items: [
							[ lang.notSet, '' ],
							[ lang.langDirLTR, 'ltr' ],
							[ lang.langDirRTL, 'rtl' ]
						],
						setup: setupAdvParams,
						commit: commitAdvParams
					} );
				}

				result.elements[ 0 ].children.push( {
					type: 'hbox',
					widths: [ '50%', '50%' ],
					children: [].concat( contents )
				} );
			}

			if ( tabConfig.styles || tabConfig.classes ) {
				contents = [];

				if ( tabConfig.styles ) {
					contents.push( {
						id: 'advStyles',
						att: 'style',
						type: 'text',
						requiredContent: element ? element + '{cke-xyz}' : null,
						label: lang.styles,
						'default': '',

						validate: CKEDITOR.dialog.validate.inlineStyle( lang.invalidInlineStyle ),
						onChange: function() {},

						getStyle: function( name, defaultValue ) {
							var match = this.getValue().match( new RegExp( '(?:^|;)\\s*' + name + '\\s*:\\s*([^;]*)', 'i' ) );
							return match ? match[ 1 ] : defaultValue;
						},

						updateStyle: function( name, value ) {
							var styles = this.getValue();

							var tmp = editor.document.createElement( 'span' );
							tmp.setAttribute( 'style', styles );
							tmp.setStyle( name, value );
							styles = CKEDITOR.tools.normalizeCssText( tmp.getAttribute( 'style' ) );

							this.setValue( styles, 1 );
						},

						setup: setupAdvParams,

						commit: commitAdvParams

					} );
				}

				if ( tabConfig.classes ) {
					contents.push( {
						type: 'hbox',
						widths: [ '45%', '55%' ],
						children: [ {
							id: 'advCSSClasses',
							att: 'class',
							type: 'text',
							requiredContent: element ? element + '(cke-xyz)' : null,
							label: lang.cssClasses,
							'default': '',
							setup: setupAdvParams,
							commit: commitAdvParams

						} ]
					} );
				}

				result.elements[ 0 ].children.push( {
					type: 'hbox',
					widths: [ '50%', '50%' ],
					children: [].concat( contents )
				} );
			}

			return result;
		}
	} );

} )();


text:
using ErrorProne.NET.Common;
using ErrorProne.NET.Rules.ExceptionHandling;
using NUnit.Framework;
using RoslynNunitTestRunner;

namespace ErrorProne.NET.Test.ExceptionHandlingRules
{
    [TestFixture]
    public class NonSynchronousPreconditionsInIteratorBlockTests : CSharpAnalyzerTestFixture<IteratorBlockPreconditionsAnalyzer>
    {
        [Test]
        public void WarnOnSingleIfThrow()
        {
            string code = @"
using System.Collections.Generic;
class Test
{
  public IEnumerable<string> Foo(string s)
  {
    if (s == null) [|throw new System.ArgumentException();|]
    yield break;
  }
}";
            HasDiagnostic(code, RuleIds.SuspiciousPreconditionInIteratorBlock);
        }

        [Test]
        public void WarnIfYieldIsInsideForeach()
        {
            string code = @"
using System.Collections.Generic;
class Test
{
    public IEnumerable<string> ReadFile2(string fileName, string[] ar)
    {
        if (fileName == null) [|throw new System.ArgumentNullException();|]
        foreach(var s in ar)
        {
            yield return s;
        }
    }
}";
            HasDiagnostic(code, RuleIds.SuspiciousPreconditionInIteratorBlock);
        }

        [Test]
        public void WarnOnFirstIfThrow()
        {
            string code = @"
using System.Collections.Generic;
class Test
{
  public IEnumerable<string> Foo(string s)
  {
    if (s == null) [|throw new System.ArgumentNullException();|]
    if (s.Length == 1) throw new System.Exception();
    yield break;
  }
}";
            HasDiagnostic(code, RuleIds.SuspiciousPreconditionInIteratorBlock);
        }

        [Test]
        public void WarnOnBothArgumentExcpetions()
        {
            string code = @"
using System.Collections.Generic;
class Test
{
  public IEnumerable<string> Foo(string s)
  {
    if (s == null) [|throw new System.ArgumentNullException();|]
    if (s.Length == 1) [|throw new System.ArgumentException();|]
    yield break;
  }
}";
            HasDiagnostic(code, RuleIds.SuspiciousPreconditionInIteratorBlock);
        }

        [Test]
        public void WarnOnFirstOnlyBecauseNextStatementIsNotIfThrow()
        {
            string code = @"
using System.Collections.Generic;
class Test
{
  public IEnumerable<string> Foo(string s)
  {
    if (s == null) [|throw new System.ArgumentNullException();|]
    System.Console.WriteLine(s);
    if (s.Length == 1) throw new System.ArgumentException();
    yield break;
  }
}";
            HasDiagnostic(code, RuleIds.SuspiciousPreconditionInIteratorBlock);
        }

        [Test]
        public void DoNotWarnIfMethodIsNotIteratorBlock()
        {
            string code = @"
using System.Collections.Generic;
class Test
{
  public IEnumerable<string> Foo(string s)
  {
    if (s == null) throw new System.ArgumentNullException();
    System.Console.WriteLine(s);
    if (s.Length == 1) throw new System.ArgumentException();
  }
}";
            NoDiagnostic(code, RuleIds.SuspiciousPreconditionInIteratorBlock);
        }
    }
}


text:
<?php

require $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';

use Cbix\Cbix;
use Cbix\CbixException;

$cbix = Cbix::make();

/*
 * Convert between CAD and BTC
 * Returns the currency conversion between BTC and CAD based on live index price
 */

try {
    $result = $cbix->convert(500, 'asas'); //Converts 500 CAD to BTC using defaults
    //var_dump($result);

    if ($result->success !== true) {
        //Validation errors
        var_dump($result->messages);
        die();
    }

    echo $result->result;

} catch (CbixException $e) {
    //There was an error more information in $e->getMessage();
    var_dump($e->getMessage());
    echo "Something went wrong!";
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;

import com.azure.cosmos.implementation.guava25.base.Strings;
import com.azure.cosmos.implementation.apachecommons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * Contains the configurations for tests.
 *
 * For running tests, you can pass a customized endpoint configuration in one of the following
 * ways:
 *

 *
-DACCOUNT_KEY="[your-key]" -ACCOUNT_HOST="[your-endpoint]" as JVM
 * command-line option.

 *
You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.

 *
You can have a properties file with ACCOUNT_KEY AND ACCOUNT_HOST, etc.

 *

 *
 * If none of the above is set, emulator endpoint will be used.
 */
public final class TestConfigurations {
    private static Logger logger = LoggerFactory.getLogger(TestConfigurations.class);
    private static Properties properties = loadProperties();

    private final static String COSMOS_EMULATOR_KEY = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
    private final static String COSMOS_EMULATOR_HOST = "https://localhost:8081/";

    // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account.
    // The default values are credentials of the local emulator, which are not used in any production environment.
    //
    public final static String MASTER_KEY =
        properties.getProperty("ACCOUNT_KEY",
                    StringUtils.defaultString(Strings.emptyToNull(
                            System.getenv().get("ACCOUNT_KEY")),
                            COSMOS_EMULATOR_KEY));

    public final static String SECONDARY_MASTER_KEY =
        properties.getProperty("SECONDARY_ACCOUNT_KEY",
            StringUtils.defaultString(Strings.emptyToNull(
                System.getenv().get("SECONDARY_ACCOUNT_KEY")),
                COSMOS_EMULATOR_KEY));

    public final static String HOST =
        properties.getProperty("ACCOUNT_HOST",
                    StringUtils.defaultString(Strings.emptyToNull(
                            System.getenv().get("ACCOUNT_HOST")),
                            COSMOS_EMULATOR_HOST));

    public final static String CONSISTENCY =
        properties.getProperty("ACCOUNT_CONSISTENCY",
                               StringUtils.defaultString(Strings.emptyToNull(
                                       System.getenv().get("ACCOUNT_CONSISTENCY")), "Strong"));

    public final static String PREFERRED_LOCATIONS =
        properties.getProperty("PREFERRED_LOCATIONS",
                               StringUtils.defaultString(Strings.emptyToNull(
                                       System.getenv().get("PREFERRED_LOCATIONS")), null));

    public final static String MAX_RETRY_LIMIT =
        properties.getProperty("MAX_RETRY_LIMIT",
                               StringUtils.defaultString(Strings.emptyToNull(
                                       System.getenv().get("MAX_RETRY_LIMIT")),
                                                         "2"));

    public final static String DESIRED_CONSISTENCIES =
        properties.getProperty("DESIRED_CONSISTENCIES",
                               StringUtils.defaultString(Strings.emptyToNull(
                                       System.getenv().get("DESIRED_CONSISTENCIES")),
                                                         null));

    public final static String PROTOCOLS =
        properties.getProperty("PROTOCOLS",
                               StringUtils.defaultString(Strings.emptyToNull(
                                       System.getenv().get("PROTOCOLS")),
                                                         null));

    /**
     * If ${ProjectPath}/cosmos-v4.properties is present, it will be used
     * otherwise, if ~/cosmos-v4.props is present, it will be used
     * otherwise, system properties will be used as default.
     * @return loaded properties
     */
    private static Properties loadProperties() {
        Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
        Path propertiesInProject = Paths.get(root.toString(),"../cosmos-v4.properties");

        Properties props = loadFromPathIfExists(propertiesInProject);
        if (props != null) {
            return props;
        }

        Path propertiesInUserHome = Paths.get(System.getProperty("user.home"), "cosmos-v4.properties");
        props = loadFromPathIfExists(propertiesInUserHome);
        if (props != null) {
            return props;
        }

        return System.getProperties();
    }

    private static Properties loadFromPathIfExists(Path propertiesFilePath) {
        if (Files.exists(propertiesFilePath)) {
            try (InputStream in = Files.newInputStream(propertiesFilePath)) {
                Properties props = new Properties();
                props.load(in);
                logger.info("properties loaded from {}", propertiesFilePath);
                return props;
            } catch (Exception e) {
                logger.error("Loading properties {} failed", propertiesFilePath, e);
            }
        }
        return null;
    }
}


text: export { default } from 'ember-fhir/serializers/substance';