text:
import json
import random
import os
import time
from datetime import datetime
from itertools import chain

from django.shortcuts import render
from django.core import serializers
from django.http import HttpResponse
from django.http import JsonResponse
import django_filters.rest_framework
from django.core.cache import cache
from django.test.utils import override_settings
from django.contrib.gis.geos import Point
from django.contrib.gis.db import models
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Polygon, MultiPolygon
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics
from celery.result import AsyncResult

from .models import *
from .serializers import *
from app.settings import DEBUG

def test(request, attribute):
    day = '2016-09-01'
    date = '2016-09-01 00:00:00'
    model = attribute
    data = {'content': 'Test',}
    data["attribute"] = attribute
    model = 'Chlorophyll'
    model = 'SeaSurfaceTemperature'
    # model = 'SeaIceCover'
    # Getting the region value
    try:
        region = Region.objects.get(slug=region)
    except:
        region = Region.objects.get(slug='default')

    start_time = time.time()
    print('Getting cache...')
    # Updating day cache and get cached result
    # cacheResult = create_qs_cache_byday_and_model(day, model)
    print("--- %s seconds ---" % (time.time() - start_time))

    start_time = time.time()
    startDate = day + ' 00:00:00'
    endDate = day + ' 23:59:59'
    print('Making query...')
    qs = eval(model).objects.filter(
    # qs = cacheResult.filter(
        datetime__range=(startDate, endDate),
        point__intersects=str(region.mpoly),
    # )[0:2000000]
    )[0:1000]
    serializer = eval(model + 'Serializer')(qs, many=True)
    data['qs'] = serializer.data
    print("--- %s seconds ---" % (time.time() - start_time))

    return JsonResponse(data, safe=False)
    # return JsonResponse({}, safe=False)

# Creating chache for query set object
# for default region by given date and model
def create_qs_cache_byday_and_model(date, model, renew=False):
    date = str(date)
    model = str(model)
    dateTime = date + ' 00:00:00'
    # Generating query set cache key
    cacheKey = 'qs' + date + model
    # Trying to get cached data
    if not cache.get(cacheKey) or renew:
        # If cache data in not set, making query
        print("Making day cache...")
        region = Region.objects.get(slug='default')
        qs = eval(model).objects.filter(
            datetime=dateTime,
            point__intersects=str(region.mpoly),
        )
        cache.set(cacheKey, qs)
    else:
        print("Got the cached data from memcached")

    return cache.get(cacheKey)

def get_filter(request):
    data = {'regions': [], 'characteristics': [],}

    qs = Region.objects.all()
    serializer = RegionSerializer(qs, many=True)
    data['regions'] = serializer.data

    qs = Characteristic.objects.all()
    serializer = CharacteristicSerializer(qs, many=True)
    data['characteristics'] = serializer.data

    return JsonResponse(data, safe=False)

def api_get_queryset(
        model, _date, region, needed, createDump=True):
    # Returned result array
    result = []

    # Convert date to datetime format
    date = _date + ' 00:00:00'

    # Max number of DB selects have to be done
    select = 20  # select = int(select)

    # Number of points you need
    needed = int(needed)
    if needed < 500:
        needed = 500

    # Getting the region value
    try:
        region = Region.objects.get(slug=region)
    except:
        region = Region.objects.get(slug='default')

    """
    # Creating query dump task if needed
    if createDump:
        task = create_dump_task.delay(
            model, date, str(region), str(region.mpoly))
    """
    # print("ID", task.task_id)
    # taskResult = AsyncResult(task.task_id)
    # time.sleep(5)
    # print(taskResult.ready())
    # print(task.AsyncResult(task.request.id).state)
    # return result  # 4 testing

    # Generating query set cache key
    cacheKey = str(_date) + '-' + str(region.slug) \
        + '-' + str(model) \
        + '-' + str(needed) + '-' \
        + str(select)

    # Define main DB query, execution is delayed
    qsTotal = eval(model).objects.filter(
        datetime=date,
        point__intersects=region.mpoly,
    )

    # Total points found using query filter
    total = qsTotal.count()

    print("Total points found:", total)  # 4 testing

    # Exit if no points found
    if total < 1:
        print("No points found")
        return result

    # Getting points queryset
    # using normalization algorithm
    step = int(round(total / select, -1))
    pull = int(round(step / (total / needed), -1))
    randStep = step - pull
    randStep = randStep if randStep > 0 else step

    # Trying to get cached data
    result = cache.get(cacheKey)

    # If cache data in not set, making query
    if not result:
        result = []
        print("Making query...")
        for i in range(select):
            shift = i * step + random.randint(0, randStep)
            print("Query shift:", shift)
            qs = qsTotal.filter()[shift:shift + pull]
            result = list(chain(result, qs))
        cache.set(cacheKey, result)
    else:
        print("Got the cached data from memcached")

    print("Points selected:", len(result))

    return result

class ApiChlor(generics.ListCreateAPIView):
    serializer_class = ChlorophyllSerializer

    def get_queryset(self):
        qs = api_get_queryset(
            'Chlorophyll',
            self.kwargs['date'],
            self.kwargs['region'],
            self.kwargs['needed'],
        )

        return qs

class ApiSST(generics.ListCreateAPIView):
    serializer_class = SSTSerializer

    def get_queryset(self):
        qs = api_get_queryset(
            'SST',
            self.kwargs['date'],
            self.kwargs['region'],
            self.kwargs['needed'],
        )

        return qs

class ApiBath(generics.ListCreateAPIView):
    serializer_class = BathymetricSerializer

    def get_queryset(self):
        qs = api_get_queryset(
            'Bathymetric',
            '2015-03-18',
            self.kwargs['region'],
            self.kwargs['needed'],
        )

        return qs

class CharacteristicsList(generics.ListCreateAPIView):
    queryset = Characteristic.objects.all()
    serializer_class = CharacteristicSerializer

class CharacteristicsDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Characteristic.objects.all()
    serializer_class = CharacteristicSerializer

class RegionsList(generics.ListCreateAPIView):
    queryset = Region.objects.all()
    serializer_class = RegionSerializer

class RegionsDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Region.objects.all()
    serializer_class = RegionSerializer

def regions_detail(request, argument):
    data = {}
    try:
        pk = int(argument)
        qs = Region.objects.filter(pk=pk)
    except:
        slug = str(argument)
        qs = Region.objects.filter(slug=slug)

    serializer = RegionSerializer(qs, many=True)
    data = serializer.data[0]
    return JsonResponse(data, safe=False)


text:
package com.dongdongxia.my.jdk8.rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

/**
 *
 *
Description: 远程服务的实现

 * @ClassName: AddServiceImpl
 * @author java_liudong@163.com  2017年12月6日 下午2:16:06
 */
public class AddServiceImpl extends UnicastRemoteObject implements AddServiceIntf {

    /**
     * @Fields serialVersionUID : TODO
     */
    private static final long serialVersionUID = 1L;

    public AddServiceImpl() throws RemoteException {

    }

    @Override
    public double add(double d1, double d2) throws RemoteException {
        System.out.format("你请求的入参: %s , %s %n", d1, d2);
        return d1 + d2;
    }
}

redpajama_set_name: RedPajamaGithub


text:
curl -sSL https://get.docker.com/| sh
sudo gpasswd -a tao docker


text:
package com.WazaBe.HoloEverywhere.app;

import com.WazaBe.HoloEverywhere.LayoutInflater;
import com.WazaBe.HoloEverywhere.ThemeManager.ThemedIntentStarter;
import com.WazaBe.HoloEverywhere.app.Application.Config;
import com.WazaBe.HoloEverywhere.preference.SharedPreferences;

public interface Base extends ThemedIntentStarter {
	public LayoutInflater getLayoutInflater();

	public Config getSettings();

	public SharedPreferences getSupportSharedPreferences(String name, int mode);

	public boolean isABSSupport();

	public boolean isForceThemeApply();
}


text:
require 'ruote-mon'

def new_storage(opts)

  #con = Mongo::Connection.new
    #
    # not thread-safe

  #con = Mongo::Connection.new(nil, nil, :refresh_mode => :sync)
    #
    # http://groups.google.com/group/mongodb-user/browse_thread/thread/7d09df9fa765891e
    #
    # but it doesn't work.

  con = Mongo::Connection.new(
    '127.0.0.1', 27017, :pool_size => 14, :pool_timeout => 3)

  Ruote::Mon::Storage.new(con['ruote_mon_test'], opts)
end


text:
namespace gdbplz
{
	class function_id : boost::totally_ordered<function_id>
	{
	private:
		struct impl;
		typedef wiertlo::pimpl_handle<impl, void*, 8> pimpl_handle_type;
		pimpl_handle_type pi;
	public:
		function_id(std::string name);
		function_id(function_id&&);
		function_id& operator=(function_id&&);
		function_id(const function_id&);
		function_id& operator=(const function_id&);
		~function_id();

		// ordering relation
		// don't count on it being reproducible across machines or program runs
		// it's only provided to enable usage as key in associative containers
		bool operator<(const function_id& other) const;
		// equality comparison
		// two function_id are the same when they refer to the same function
		bool operator==(const function_id& other) const;
		// get user-readable string representation of the function
		std::string to_string() const;
		friend std::hash<function_id>;
	};
}

namespace std
{
	template<>
	struct hash<::gdbplz::function_id>
	{
		std::size_t operator()(const ::gdbplz::function_id& id) const;
	};
}

#endif


text:
using System.Diagnostics;

namespace Microsoft.AspNetCore.Mvc.ModelBinding;

/// <summary>
/// This is a container for prefix values. It normalizes all the values into dotted-form and then stores
/// them in a sorted array. All queries for prefixes are also normalized to dotted-form, and searches
/// for ContainsPrefix are done with a binary search.
/// </summary>
public class PrefixContainer
{
    private static readonly char[] Delimiters = new char[] { '[', '.' };

    private readonly ICollection<string> _originalValues;
    private readonly string[] _sortedValues;

    /// <summary>
    /// Initializes a new instance of <see cref="PrefixContainer"/>.
    /// </summary>
    /// <param name="values">The values for the container.</param>
    public PrefixContainer(ICollection<string> values)
    {
        if (values == null)
        {
            throw new ArgumentNullException(nameof(values));
        }

        _originalValues = values;

        if (_originalValues.Count == 0)
        {
            _sortedValues = Array.Empty<string>();
        }
        else
        {
            _sortedValues = new string[_originalValues.Count];
            _originalValues.CopyTo(_sortedValues, 0);
            Array.Sort(_sortedValues, StringComparer.OrdinalIgnoreCase);
        }
    }

    /// <summary>
    /// Checks if a prefix is in the container.
    /// </summary>
    /// <param name="prefix">The prefix to check.</param>
    /// <returns>True if the prefix is present.</returns>
    public bool ContainsPrefix(string prefix)
    {
        if (prefix == null)
        {
            throw new ArgumentNullException(nameof(prefix));
        }

        if (_sortedValues.Length == 0)
        {
            return false;
        }

        if (prefix.Length == 0)
        {
            return true; // Empty prefix matches all elements.
        }

        return BinarySearch(prefix) > -1;
    }

    /// <summary>
    /// Gets the keys from a prefix.
    /// </summary>
    /// <remarks>
    /// Given "foo.bar", "foo.hello", "something.other", foo[abc].baz and asking for prefix "foo" will return:
    /// - "bar"/"foo.bar"
    /// - "hello"/"foo.hello"
    /// - "abc"/"foo[abc]"
    /// </remarks>
    /// <param name="prefix">The prefix to enumerate.</param>
    /// <returns>The keys for the prefix.</returns>
    public IDictionary<string, string> GetKeysFromPrefix(string prefix)
    {
        var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

        foreach (var entry in _originalValues)
        {
            if (entry != null)
            {
                if (entry.Length == prefix.Length)
                {
                    // No key in this entry
                    continue;
                }

                if (prefix.Length == 0)
                {
                    GetKeyFromEmptyPrefix(entry, result);
                }
                else if (entry.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
                {
                    GetKeyFromNonEmptyPrefix(prefix, entry, result);
                }
            }
        }

        return result;
    }

    private static void GetKeyFromEmptyPrefix(string entry, IDictionary<string, string> results)
    {
        string key;
        string fullName;
        var delimiterPosition = entry.AsSpan().IndexOfAny('[', '.');

        if (delimiterPosition == 0 && entry[0] == '[')
        {
            // Handle an entry such as "[key]".
            var bracketPosition = entry.IndexOf(']', 1);
            if (bracketPosition == -1)
            {
                // Malformed for dictionary.
                return;
            }

            key = entry.Substring(1, bracketPosition - 1);
            fullName = entry.Substring(0, bracketPosition + 1);
        }
        else
        {
            // Handle an entry such as "key", "key.property" and "key[index]".
            key = delimiterPosition == -1 ? entry : entry.Substring(0, delimiterPosition);
            fullName = key;
        }

        if (!results.ContainsKey(key))
        {
            results.Add(key, fullName);
        }
    }

    private static void GetKeyFromNonEmptyPrefix(string prefix, string entry, IDictionary<string, string> results)
    {
        string key;
        string fullName;
        var keyPosition = prefix.Length + 1;

        switch (entry[prefix.Length])
        {
            case '.':
                // Handle an entry such as "prefix.key", "prefix.key.property" and "prefix.key[index]".
                var delimiterPosition = entry.IndexOfAny(Delimiters, keyPosition);
                if (delimiterPosition == -1)
                {
                    // Neither '.' nor '[' found later in the name. Use rest of the string.
                    key = entry.Substring(keyPosition);
                    fullName = entry;
                }
                else
                {
                    key = entry.Substring(keyPosition, delimiterPosition - keyPosition);
                    fullName = entry.Substring(0, delimiterPosition);
                }
                break;

            case '[':
                // Handle an entry such as "prefix[key]".
                var bracketPosition = entry.IndexOf(']', keyPosition);
                if (bracketPosition == -1)
                {
                    // Malformed for dictionary
                    return;
                }

                key = entry.Substring(keyPosition, bracketPosition - keyPosition);
                fullName = entry.Substring(0, bracketPosition + 1);
                break;

            default:
                // Ignore an entry such as "prefixA".
                return;
        }

        if (!results.ContainsKey(key))
        {
            results.Add(key, fullName);
        }
    }

    // This is tightly coupled to the definition at ModelStateDictionary.StartsWithPrefix
    private int BinarySearch(string prefix)
    {
        var start = 0;
        var end = _sortedValues.Length - 1;

        while (start <= end)
        {
            var pivot = start + ((end - start) / 2);
            var candidate = _sortedValues[pivot];
            var compare = string.Compare(
                prefix,
                0,
                candidate,
                0,
                prefix.Length,
                StringComparison.OrdinalIgnoreCase);
            if (compare == 0)
            {
                Debug.Assert(candidate.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));

                // Okay, now we have a candidate that starts with the prefix. If the candidate is longer than
                // the prefix, we need to look at the next character and see if it's a delimiter.
                if (candidate.Length == prefix.Length)
                {
                    // Exact match
                    return pivot;
                }

                var c = candidate[prefix.Length];
                if (c == '.' || c == '[')
                {
                    // Match, followed by delimiter
                    return pivot;
                }

                // Okay, so the candidate has some extra text. We need to keep searching.
                //
                // Can often assume the candidate string is greater than the prefix e.g. that works for
                //  prefix: product
                //  candidate: productId
                // most of the time because "product", "product.id", etc. will sort earlier than "productId". But,
                // the assumption isn't correct if "product[0]" is also in _sortedValues because that value will
                // sort later than "productId".
                //
                // Fall back to brute force and cover all the cases.
                return LinearSearch(prefix, start, end);
            }

            if (compare > 0)
            {
                start = pivot + 1;
            }
            else
            {
                end = pivot - 1;
            }
        }

        return ~start;
    }

    private int LinearSearch(string prefix, int start, int end)
    {
        for (; start <= end; start++)
        {
            var candidate = _sortedValues[start];
            var compare = string.Compare(
                prefix,
                0,
                candidate,
                0,
                prefix.Length,
                StringComparison.OrdinalIgnoreCase);
            if (compare == 0)
            {
                Debug.Assert(candidate.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));

                // Okay, now we have a candidate that starts with the prefix. If the candidate is longer than
                // the prefix, we need to look at the next character and see if it's a delimiter.
                if (candidate.Length == prefix.Length)
                {
                    // Exact match
                    return start;
                }

                var c = candidate[prefix.Length];
                if (c == '.' || c == '[')
                {
                    // Match, followed by delimiter
                    return start;
                }

                // Keep checking until we've passed all StartsWith() matches.
            }

            if (compare < 0)
            {
                // Prefix is less than the candidate. No potential matches left.
                break;
            }
        }

        return ~start;
    }
}


text:
layout: docs
title: Expect Examples
prev_section: tclexample
next_section:
permalink: /docs/expectexample/
---

- [multi telnet session of expect]({% post_url 2014-12-14-multi-session-expect %})
- [bootup-board-from-terminal-server]({% post_url 2014-12-24-bootup-board-from-terminal-server %})
- [call another program in expect]({% post_url 2014-12-14-call-another-program-by-expect %})
{% highlight tcl %}
{% endhighlight %}


text:
    <input class="form-control" readonly>

    <input class="form-control" readonly>


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

namespace CarsSearch
{
    public class Extra
    {
        public string Name { get; set; }

        public Extra(string name)
        {
            this.Name = name;
        }
    }
}


text:
package com.lanceolata.leetcode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class Question_140_Word_Break_II {
    public List<String> wordBreak(String s, List<String> wordDict) {
        return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
    }

    List<String> DFS(String s, List<String> wordDict, HashMap<String, LinkedList<String>> map) {
        if (map.containsKey(s))
            return map.get(s);

        LinkedList<String>res = new LinkedList<String>();
        if (s.length() == 0) {
            res.add("");
            return res;
        }
        for (String word : wordDict) {
            if (s.startsWith(word)) {
                List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
                for (String sub : sublist)
                    res.add(word + (sub.isEmpty() ? "" : " ") + sub);
            }
        }
        map.put(s, res);
        return res;
    }
}


text:
/* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.)
******************************************************************************/

#include <string>
#include "Split.hpp"

using namespace std;
using namespace gxm;

SplitNode::SplitNode(SplitParams *p, MLEngine *e) : NNNode(p, e)
{
  nname_ = p->get_node_name();
  ntype_ = p->get_node_type();
  mode_ = p->get_mode();
  bottom_ = p->get_bottom_names();
  top_ = p->get_top_names();
  bp_flag_ = p->get_bprop_flag();
  has_weights_ = false;
  bot_compute_engine_ = p->get_compute_engine();

  if(nname_.find("label") != nname_.npos)
    tenBot_ = e->get_tensor(bottom_[0], LABEL);
  else
    tenBot_ = e->get_tensor(bottom_[0], ACT);

  assert(tenBot_ != NULL);
  NNNode *pnn = (NNNode*)tenBot_->getOwner();
  setPrevNode(pnn);
  bot_cengine_ = pnn->get_bot_compute_engine();
  pnn->set_top_compute_engine(p->get_compute_engine());
  pnn->set_next_node_type(ntype_);

  tenBotData_ = tenBot_->getBuf(DATA);
  int out_dtype = p->get_data_type();
  int in_dtype = tenBotData_->getDataType();

  Shape* bs = tenBot_->getShape();
  assert(bs->ndims <= MAX_DIMS);

  // number of splits
  gparams_.nOutput.resize(top_.size());
  tenTop_.resize(top_.size());
  tenTopData_.resize(top_.size());

  for(int i=0; i<top_.size(); i++)
  {
    tenTop_[i] = new Tensor(top_[i]);
    assert(tenTop_[i] != NULL);
    tenTop_[i]->setOwner(this);
    if(nname_.find("label") != nname_.npos)
      tenTop_[i]->setType(LABEL);
    else
      tenTop_[i]->setType(ACT);

    Shape ts;
    shape_setzero(&ts);

    ts.ndims = bs->ndims;
    for(int j=0; j<bs->ndims; j++)
      ts.dims[j] = bs->dims[j];

    tenTop_[i]->setShape(&ts);

    tenTopData_[i] = tenTop_[i]->getBuf(DATA);
    tenTopData_[i]->setBufferType(DATA);
    tenTopData_[i]->setDataType(in_dtype);

#if 0
    long long int tsize = 1;
    for(int d=0; d<ts.ndims; d++)
      tsize = tsize*ts.dims[d];

    if(dtype == DT_FLOAT)
      tsize = tsize*sizeof(float);
    else if(dtype == DT_INT)
      tsize = tsize*sizeof(int);

    // Set the logical size of the tensor buffer for bufId=0 (forward data buffer).
    // Note: we have no knowledge of the machine parameters here, so effectively this is single-machine config
    tenTopData_[i]->setBufferSize(tsize);
#endif

    bool inserted;

    if(nname_.find("label") != nname_.npos)
      inserted = e->register_tensor(NNNode::top_[i], LABEL, tenTop_[i]);
    else
      inserted = e->register_tensor(NNNode::top_[i], ACT, tenTop_[i]);

    if(!inserted)
      printf("Warning: Tensor %s already registered\n",NNNode::top_[i].c_str());
  }

  if(!e->is_inference_only())
  {
    if(bp_flag_)
    {
      tenBotDiff_ = tenBot_->addBuf();
      tenBotDiff_->setDataType(DT_FLOAT); //@TODO: This is a HACK. Must be fixed
      tenBotDiff_->setBufferType(DIFF);
      tenBotDiff_->setBufferSize(tenBotData_->getBufferSize());
    }
  }

  gparams_.bdims = bs->ndims;
  gparams_.tdims = bs->ndims;
  gparams_.batch_size = bs->dims[0];
  gparams_.nInput = bs->dims[1];
  for(int i=0; i<top_.size(); i++)
    gparams_.nOutput[i] = bs->dims[1];
  gparams_.iHeight = bs->dims[2];
  gparams_.iWidth = bs->dims[3];
  gparams_.oHeight = gparams_.iHeight;
  gparams_.oWidth = gparams_.iWidth;
  gparams_.num_threads = e->get_num_threads();

  eptr_ = e;
#if 0
#ifdef USE_MLSL
  if(nname_.find("label") == nname_.npos)
  {
    MLSL::DataType dt = MLSL::DT_FLOAT;
    MLSL::ComputeOpRegInfo *myRegInfo;
    myRegInfo = new MLSL::ComputeOpRegInfo(MLSL::COMP_OP_TYPE_BCAST);
    myRegInfo->SetName(nname_.c_str());

    if(gparams_.iWidth > 0 && gparams_.iHeight > 0)
      myRegInfo->AddInputFeatureMap(gparams_.nInput, gparams_.iWidth*gparams_.iHeight, dt);
    else
      myRegInfo->AddInputFeatureMap(gparams_.nInput, 1, dt);

    for(int i=0; i<gparams_.nOutput.size(); i++)
    {
      if(gparams_.oWidth > 0 && gparams_.oHeight > 0)
        myRegInfo->AddOutputFeatureMap(gparams_.nOutput[i], gparams_.oWidth*gparams_.oHeight, dt);
      else
        myRegInfo->AddOutputFeatureMap(gparams_.nOutput[i], 1, dt);
    }

    myRegInfo->Validate();
    this->op_ = new MLSL::ComputeOp(myRegInfo, e->get_distribution());
    delete myRegInfo;
  }
#endif
#endif

#if 0
  configure(p->get_compute_engine());
#else
  configure(XSMM);
#endif

}

void SplitNode::configure(int engine)
{
  switch(engine)
  {
    case XSMM:
      impl = new SplitLoop(&gparams_, engine);
      break;
  }
}

void SplitNode::forwardPropagate()
{
  impl->set_bot_compute_engine(bot_cengine_);
  for(int i=0; i<top_.size(); i++)
    impl->set_top_compute_engine(top_compute_engine_);

  impl->forwardPropagate(tenBotData_, tenTopData_);

#ifdef CHECK_BLOWUP_FP32
  for(int i=0; i<top_.size(); i++)
  {
    float* ptr = (float*)tenTopData_[i]->getBuffer();
    for(int j=0; j<16; j++)
    {
      if(isnan(ptr[j]) || isinf(ptr[j]))
      {
        printf("Warning! %s layer FP activations are NaN or Inf\n", nname_.c_str());
        exit(-1);
      }
    }
  }
#endif

#ifdef GETSTATS
#ifdef USE_MLSL
  size_t node_id = MLSL::Environment::GetEnv().GetProcessIdx();
#else
  size_t node_id = 0;
#endif
  if(node_id == 0 && eptr_->get_current_batch() % STATFREQ == 0)
  {
    float* bot = (float*) tenBotData_->getBuffer();
#ifdef DEBUG
    for(int i=0; i<top_.size(); i++)
    {
      float* top = (float*)tenTopData_[i]->getBuffer();
      printf("Executing FP %s: bot %p, top %p\n",nname_.c_str(), bot, top);
    }
#endif
    string s = nname_ + "_Inp";
    MeanOfLayer((char*)s.c_str(), bot, tenBotData_->getBufferSize()/sizeof(float));

    for(int i=0; i<top_.size(); i++)
    {
      float* top = (float*)tenTopData_[i]->getBuffer();
      s = nname_ + "_Outp_" + to_string(i);
      MeanOfLayer((char*)s.c_str(), top, tenTopData_[i]->getBufferSize()/sizeof(float));
    }
  }
#endif
}

void SplitNode::backPropagate()
{
  int num_gtops=0;
  int nni;

  for(int i=0; i<tenTop_.size(); i++)
  {
    if(tenTop_[i]->getBuf(DIFF) != NULL)
    {
      nni = i;
      num_gtops++;
    }
  }

  tenTopDiff_.resize(num_gtops);
  if(num_gtops == 1)
    tenTopDiff_[0] = tenTop_[nni]->getBuf(DIFF);
  else
  {
    for(int i=0; i<num_gtops; i++)
      tenTopDiff_[i] = tenTop_[i]->getBuf(DIFF);
  }

#ifdef DEBUG
  float *p, *pp, *ptr;
  for(int i=0; i<tenTopDiff_.size(); i++)
  {
    if(tenTopDiff_[i] != NULL)
    {
      p = (float*)tenTopDiff_[i]->getBuffer();
      pp = (float*)tenTopDiff_[i]->getPrivBuffer();
      ptr = (pp == NULL) ? p : pp;
      printf("Executing BP %s: gtop %p, gbot %p\n",nname_.c_str(), ptr, tenBotDiff_->getBuffer());
    }
  }
#endif

  impl->backPropagate(tenTopDiff_, tenBotDiff_);

#ifdef CHECK_BLOWUP_FP32
  for(int i=0; i<num_gtops; i++)
  {
    float* ptr = (float*)tenTopDiff_[i]->getBuffer();
    for(int j=0; j<16; j++)
    {
      if(isnan(ptr[j]) || isinf(ptr[j]))
      {
        printf("Warning! %s layer BP activations are NaN or Inf\n", nname_.c_str());
        exit(-1);
      }
    }
  }
#endif
#ifdef GETSTATS
#ifdef USE_MLSL
  size_t node_id = MLSL::Environment::GetEnv().GetProcessIdx();
#else
  size_t node_id = 0;
#endif
  if(node_id == 0 && eptr_->get_current_batch() % STATFREQ == 0)
  {
    int size;
#ifndef DEBUG
    float *p, *pp, *ptr;
#endif
    for(int i=0; i<tenTopDiff_.size(); i++)
    {
      if(tenTopDiff_[i] != NULL)
      {
        p = (float*)tenTopDiff_[i]->getBuffer();
        pp = (float*)tenTopDiff_[i]->getPrivBuffer();
        ptr = (pp == NULL) ? p : pp;

        size = tenTopData_[i]->getBufferSize()/sizeof(float);
        string s = nname_ + "_delOutp_" + to_string(i);
        MeanOfLayer((char*)s.c_str(), ptr, size);
      }
    }

    p = (float*)tenBotDiff_->getBuffer();
    pp = (float*)tenBotDiff_->getPrivBuffer();
    ptr = (pp == NULL) ? p : pp;
    size = tenBotData_->getBufferSize()/sizeof(float);

    string s = nname_ + "_delInp";
    MeanOfLayer((char*)s.c_str(), ptr, size);
  }
#endif
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<c2uistate>
    <!--This is a UI state file - its content describes the user interface settings when the event sheet was last open.
It is entirely optional and the project will load without it.  If you are placing the project under source control,
you probably do not want to add any .uistate.xml files to the repository.-->
    <show-addaction-links>1</show-addaction-links>
    <scroll-pos>0</scroll-pos>
    <conditions-column>160</conditions-column>
    <actions-namecolumn>18</actions-namecolumn>
    <condition-namecolumns>
        <nest>60</nest>
        <nest>42</nest>
        <nest>24</nest>
        <nest>15</nest>
    </condition-namecolumns>
    <events />
</c2uistate>


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

import * as mplayer_contracts from './contracts';
import * as mplayer_helpers from './helpers';
import * as vscode from 'vscode';

/**
 * Selects a track from a playlist of a player for being played.
 *
 * @param {mplayer_contracts.MediaPlayer} player The player.
 * @param {mplayer_helpers.ProgressContext<undefined>} [progress] The optional progress context.
 *
 * @returns {Promise<boolean>} The promise that indicates if operation was successful or not..
 */
export async function playTrack(player: mplayer_contracts.MediaPlayer,
                                progress?: mplayer_helpers.ProgressContext<undefined>): Promise<boolean> {
    return new Promise<boolean>(async (resolve, reject) => {
        const COMPLETED = mplayer_helpers.createSimpleCompletedAction(resolve, reject);

        try {
            const UPDATE_PROGRESS = (msg?: string) => {
                if (progress) {
                    progress.message = msg;
                }
            };

            const PLAYLISTS = ((await player.getPlaylists()) || []).filter(p => p);

            const QUICK_PICKS: mplayer_contracts.ActionQuickPickItem[] = [];

            for (let i = 0; i < PLAYLISTS.length; i++) {
                const PL = PLAYLISTS[i];

                UPDATE_PROGRESS(`Loading tracks ${i + 1} / ${PLAYLISTS.length} (${Math.floor(i / PLAYLISTS.length * 100.0)} %)`);

                const TRACKS = ((await PL.getTracks()) || []).filter(t => t);
                if (TRACKS.length < 1) {
                    continue;
                }

                let label = mplayer_helpers.toStringSafe(PL.name).trim();
                if ('' === label) {
                    let id = mplayer_helpers.toStringSafe(PL.id).trim();
                    if ('' === id) {
                        id = `#${i + 1}`;
                    }

                    label = `Playlist ${id}`;
                }

                const PL_ITEM: mplayer_contracts.ActionQuickPickItem = {
                    description: '',
                    action: async (currentList: mplayer_contracts.Playlist) => {
                        try {
                            await currentList.play();
                        }
                        catch (e) {
                            mplayer_helpers.log(`[ERROR] playlists.playTrack(5): ${mplayer_helpers.toStringSafe(e)}`);
                        }
                    },
                    label: '$(list-unordered)  ' + label,
                    state: PL,
                };
                QUICK_PICKS.push(PL_ITEM);

                for (let j = 0; j < TRACKS.length; j++) {
                    const T = TRACKS[j];

                    let label = mplayer_helpers.toStringSafe(T.name).trim();
                    if ('' === label) {
                        label = `Playlist #${j + 1}`;
                    }

                    const T_ITEM: mplayer_contracts.ActionQuickPickItem = {
                        action: async (track: mplayer_contracts.Track) => {
                            try {
                                await mplayer_helpers.withProgress(async (ctx) => {
                                    ctx.message = 'Playing track...';
                                    await track.play();
                                });
                            }
                            catch (e) {
                                mplayer_helpers.log(`[ERROR] playlists.playTrack(4): ${mplayer_helpers.toStringSafe(e)}`);
                            }
                        },
                        description: '',
                        label: "    $(triangle-right) " + ` [${j + 1}] ${label}`,
                        state: T,
                    };
                    QUICK_PICKS.push(T_ITEM);
                }
            }

            UPDATE_PROGRESS('');

            if (QUICK_PICKS.length > 0) {
                vscode.window.showQuickPick(QUICK_PICKS, {
                    placeHolder: 'Select an item of a playlist...',
                }).then(async (item) => {
                    try {
                        if (item) {
                            if (item.action) {
                                await mplayer_helpers.withProgress(async (ctx) => {
                                    ctx.message = 'Playing 1st track of playlist...';

                                    await Promise.resolve(item.action(item.state, item));
                                });

                                COMPLETED(null, true);
                            }
                            else {
                                COMPLETED(null, undefined);
                            }
                        }
                        else {
                            COMPLETED(null, null);
                        }
                    }
                    catch (e) {
                        mplayer_helpers.log(`[ERROR] playlists.playTrack(3): ${mplayer_helpers.toStringSafe(e)}`);

                        COMPLETED(e);
                    }
                }, (err) => {
                    mplayer_helpers.log(`[ERROR] playlists.playTrack(2): ${mplayer_helpers.toStringSafe(err)}`);

                    COMPLETED(err);
                });
            }
            else {
                vscode.window.showWarningMessage('[vs-media-player] No track found!').then(() => {
                    COMPLETED(null, false);
                }, (err) => {
                    mplayer_helpers.log(`[ERROR] playlists.playTrack(1): ${mplayer_helpers.toStringSafe(err)}`);

                    COMPLETED(null, false);
                });
            }
        }
        catch (e) {
            COMPLETED(e);
        }
    });
}


text:
require('module-alias/register')
require('./authentication-test')


text:
package com.twitter.distributedlog;

import com.twitter.distributedlog.exceptions.BKTransmitException;
import com.twitter.distributedlog.io.Abortables;
import com.twitter.distributedlog.util.FutureUtils;
import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.proto.BookieServer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

import static org.junit.Assert.*;

public class TestFailureAndRecovery extends TestDistributedLogBase {
    static final Log LOG = LogFactory.getLog(TestFailureAndRecovery.class);

    @Test(timeout = 60000)
    public void testSimpleRecovery() throws Exception {
        DLMTestUtil.BKLogPartitionWriteHandlerAndClients bkdlmAndClients = createNewBKDLM(conf, "distrlog-simplerecovery");
        BKLogSegmentWriter out = bkdlmAndClients.getWriteHandler().startLogSegment(1);
        long txid = 1;
        for (long i = 1; i <= 100; i++) {
            LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
            out.write(op);
            if ((i % 10) == 0) {
                FutureUtils.result(out.flushAndCommit());
            }

        }
        FutureUtils.result(out.flushAndCommit());

        Abortables.abort(out, false);
        FutureUtils.result(out.asyncClose());

        assertNull(zkc.exists(bkdlmAndClients.getWriteHandler().completedLedgerZNode(1, 100, out.getLogSegmentSequenceNumber()), false));
        assertNotNull(zkc.exists(bkdlmAndClients.getWriteHandler().inprogressZNode(out.getLogSegmentId(), 1, out.getLogSegmentSequenceNumber()), false));

        FutureUtils.result(bkdlmAndClients.getWriteHandler().recoverIncompleteLogSegments());

        assertNotNull(zkc.exists(bkdlmAndClients.getWriteHandler().completedLedgerZNode(1, 100, out.getLogSegmentSequenceNumber()), false));
        assertNull(zkc.exists(bkdlmAndClients.getWriteHandler().inprogressZNode(out.getLogSegmentId(), 1, out.getLogSegmentSequenceNumber()), false));
    }

    /**
     * Test that if enough bookies fail to prevent an ensemble,
     * writes the bookkeeper will fail. Test that when once again
     * an ensemble is available, it can continue to write.
     */
    @Test(timeout = 60000)
    public void testAllBookieFailure() throws Exception {
        BookieServer bookieToFail = bkutil.newBookie();
        BookieServer replacementBookie = null;

        try {
            int ensembleSize = numBookies + 1;
            assertEquals("Begin: New bookie didn't start",
                ensembleSize, bkutil.checkBookiesUp(ensembleSize, 10));

            // ensure that the journal manager has to use all bookies,
            // so that a failure will fail the journal manager
            DistributedLogConfiguration conf = new DistributedLogConfiguration();
            conf.setEnsembleSize(ensembleSize);
            conf.setWriteQuorumSize(ensembleSize);
            conf.setAckQuorumSize(ensembleSize);
            long txid = 1;
            DLMTestUtil.BKLogPartitionWriteHandlerAndClients bkdlmAndClients = createNewBKDLM(conf, "distrlog-allbookiefailure");
            BKLogSegmentWriter out = bkdlmAndClients.getWriteHandler().startLogSegment(txid);

            for (long i = 1; i <= 3; i++) {
                LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
                out.write(op);
            }
            FutureUtils.result(out.flushAndCommit());
            bookieToFail.shutdown();
            assertEquals("New bookie didn't die",
                numBookies, bkutil.checkBookiesUp(numBookies, 10));

            try {
                for (long i = 1; i <= 3; i++) {
                    LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
                    out.write(op);
                    txid++;
                }
                FutureUtils.result(out.flushAndCommit());
                fail("should not get to this stage");
            } catch (BKTransmitException bkte) {
                LOG.debug("Error writing to bookkeeper", bkte);
                assertEquals("Invalid exception message",
                        BKException.Code.NotEnoughBookiesException, bkte.getBKResultCode());
            }
            replacementBookie = bkutil.newBookie();

            assertEquals("Replacement: New bookie didn't start",
                numBookies + 1, bkutil.checkBookiesUp(numBookies + 1, 10));
            out = bkdlmAndClients.getWriteHandler().startLogSegment(txid);
            for (long i = 1; i <= 3; i++) {
                LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
                out.write(op);
            }

            FutureUtils.result(out.flushAndCommit());
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            throw e;
        } finally {
            if (replacementBookie != null) {
                replacementBookie.shutdown();
            }
            bookieToFail.shutdown();

            if (bkutil.checkBookiesUp(numBookies, 30) != numBookies) {
                LOG.warn("Not all bookies from this test shut down, expect errors");
            }
        }
    }

    /**
     * Test that a BookKeeper JM can continue to work across the
     * failure of a bookie. This should be handled transparently
     * by bookkeeper.
     */
    @Test(timeout = 60000)
    public void testOneBookieFailure() throws Exception {
        BookieServer bookieToFail = bkutil.newBookie();
        BookieServer replacementBookie = null;

        try {
            int ensembleSize = numBookies + 1;
            assertEquals("New bookie didn't start",
                ensembleSize, bkutil.checkBookiesUp(ensembleSize, 10));

            // ensure that the journal manager has to use all bookies,
            // so that a failure will fail the journal manager
            DistributedLogConfiguration conf = new DistributedLogConfiguration();
            conf.setEnsembleSize(ensembleSize);
            conf.setWriteQuorumSize(ensembleSize);
            conf.setAckQuorumSize(ensembleSize);
            long txid = 1;
            DLMTestUtil.BKLogPartitionWriteHandlerAndClients bkdlmAndClients = createNewBKDLM(conf, "distrlog-onebookiefailure");
            BKLogSegmentWriter out = bkdlmAndClients.getWriteHandler().startLogSegment(txid);
            for (long i = 1; i <= 3; i++) {
                LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
                out.write(op);
            }
            FutureUtils.result(out.flushAndCommit());

            replacementBookie = bkutil.newBookie();
            assertEquals("replacement bookie didn't start",
                ensembleSize + 1, bkutil.checkBookiesUp(ensembleSize + 1, 10));
            bookieToFail.shutdown();
            assertEquals("New bookie didn't die",
                ensembleSize, bkutil.checkBookiesUp(ensembleSize, 10));

            for (long i = 1; i <= 3; i++) {
                LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
                out.write(op);
            }
            FutureUtils.result(out.flushAndCommit());
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            throw e;
        } finally {
            if (replacementBookie != null) {
                replacementBookie.shutdown();
            }
            bookieToFail.shutdown();

            if (bkutil.checkBookiesUp(numBookies, 30) != numBookies) {
                LOG.warn("Not all bookies from this test shut down, expect errors");
            }
        }
    }

    @Test(timeout = 60000)
    public void testRecoveryEmptyLedger() throws Exception {
        DLMTestUtil.BKLogPartitionWriteHandlerAndClients bkdlmAndClients = createNewBKDLM(conf, "distrlog-recovery-empty-ledger");
        BKLogSegmentWriter out = bkdlmAndClients.getWriteHandler().startLogSegment(1);
        long txid = 1;
        for (long i = 1; i <= 100; i++) {
            LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
            out.write(op);
            if ((i % 10) == 0) {
                FutureUtils.result(out.flushAndCommit());
            }

        }
        FutureUtils.result(out.flushAndCommit());
        FutureUtils.result(out.asyncClose());
        bkdlmAndClients.getWriteHandler().completeAndCloseLogSegment(out.getLogSegmentSequenceNumber(), out.getLogSegmentId(), 1, 100, 100);
        assertNotNull(zkc.exists(bkdlmAndClients.getWriteHandler().completedLedgerZNode(1, 100, out.getLogSegmentSequenceNumber()), false));
        BKLogSegmentWriter outEmpty = bkdlmAndClients.getWriteHandler().startLogSegment(101);
        Abortables.abort(outEmpty, false);

        assertNull(zkc.exists(bkdlmAndClients.getWriteHandler().completedLedgerZNode(101, 101, outEmpty.getLogSegmentSequenceNumber()), false));
        assertNotNull(zkc.exists(bkdlmAndClients.getWriteHandler().inprogressZNode(outEmpty.getLogSegmentId(), 101, outEmpty.getLogSegmentSequenceNumber()), false));

        FutureUtils.result(bkdlmAndClients.getWriteHandler().recoverIncompleteLogSegments());

        assertNull(zkc.exists(bkdlmAndClients.getWriteHandler().inprogressZNode(outEmpty.getLogSegmentId(), outEmpty.getLogSegmentSequenceNumber(), 101), false));
        assertNotNull(zkc.exists(bkdlmAndClients.getWriteHandler().completedLedgerZNode(101, 101, outEmpty.getLogSegmentSequenceNumber()), false));
    }

    @Test(timeout = 60000)
    public void testRecoveryAPI() throws Exception {
        DistributedLogManager dlm = createNewDLM(conf, "distrlog-recovery-api");
        BKSyncLogWriter out = (BKSyncLogWriter) dlm.startLogSegmentNonPartitioned();
        long txid = 1;
        for (long i = 1; i <= 100; i++) {
            LogRecord op = DLMTestUtil.getLogRecordInstance(txid++);
            out.write(op);
            if ((i % 10) == 0) {
                out.setReadyToFlush();
                out.flushAndSync();
            }

        }
        BKLogSegmentWriter perStreamLogWriter = out.getCachedLogWriter();
        out.setReadyToFlush();
        out.flushAndSync();

        out.abort();

        BKLogWriteHandler blplm1 = ((BKDistributedLogManager) (dlm)).createWriteHandler(true);

        assertNull(zkc.exists(blplm1.completedLedgerZNode(1, 100,
                                                          perStreamLogWriter.getLogSegmentSequenceNumber()), false));
        assertNotNull(zkc.exists(blplm1.inprogressZNode(perStreamLogWriter.getLogSegmentId(), 1,
                                                        perStreamLogWriter.getLogSegmentSequenceNumber()), false));

        dlm.recover();

        assertNotNull(zkc.exists(blplm1.completedLedgerZNode(1, 100,
                                                             perStreamLogWriter.getLogSegmentSequenceNumber()), false));
        assertNull(zkc.exists(blplm1.inprogressZNode(perStreamLogWriter.getLogSegmentId(), 1,
                                                     perStreamLogWriter.getLogSegmentSequenceNumber()), false));
        FutureUtils.result(blplm1.asyncClose());
        assertEquals(100, dlm.getLogRecordCount());
        dlm.close();
    }
}


text:
'''
This file allows you to set up configuration variables to identify the
machine and port to test.

It needs some work, but in a nutshell, put a config.cfg in your "test"
directory with the following contents:

---- snip

[DEFAULT]
machine = www.dev.ekorp.com
port = 80

[dev-ekit]
# uses DEFAULT

[dev-lp]
machine = www.lonelyplanet.dev.ekorp.com
port = 80

---- snip

Then set the environment var "TEST_CONFIG" to the config to use.

'''
import ConfigParser, os

cfg = ConfigParser.ConfigParser()
cfg.read('test/config.cfg')

# figure the active config
active = os.environ.get('TEST_CONFIG', 'DEFAULT')

# fetch the actual config info
machine = cfg.get(active, 'machine')
port = cfg.getint(active, 'port')


text:
package com.tle.ims.service;

import com.tle.annotation.Nullable;
import com.tle.common.filesystem.handle.FileHandle;
import com.tle.core.util.ims.beans.IMSManifest;
import java.io.IOException;
import java.io.InputStream;

public interface IMSService {
  String getScormVersion(FileHandle stagingHandle, String pagename);

  /** Retrieve the title for an IMS package. */
  String getImsTitle(FileHandle handle, String packageName);

  void ensureIMSPackage(FileHandle handle, String packageExtractedFolder) throws IOException;

  /**
   * Retrieve the IMS manifest for an IMS package. Due to SCORM extensions, manifest may be split up
   * into several files. Using the manifest returned for this method will guarantee that the
   * manifest is combined into a single entity.
   *
   * @param handle The base directory handle
   * @param packageName the name of the ims package
   */
  InputStream getImsManifestAsStream(
      FileHandle handle, String packageExtractedFolder, boolean logNotFound) throws IOException;

  /**
   * @param handle
   * @param packageExtractedFolder
   * @param manifestName Leave null in the case of packageExtractedFolder being the actual XML file
   * @param logNotFound
   * @return
   * @throws IOException
   */
  InputStream getMetsManifestAsStream(
      FileHandle handle,
      String packageExtractedFolder,
      @Nullable String manifestName,
      boolean logNotFound)
      throws IOException;

  /**
   * Retrieve the IMS manifest for an IMS package as a bean hierarchy. Due to SCORM extensions,
   * manifest may be split up into several files. Using the manifest returned for this method will
   * guarantee that the manifest is combined into a single entity.
   *
   * @param handle The base directory handle
   * @param packageName the name of the ims package
   */
  IMSManifest getImsManifest(FileHandle handle, String packageExtractedFolder, boolean logNotFound)
      throws IOException;

  /**
   * Retrieve the IMS manifest for an IMS package as a bean hierarchy. Due to SCORM extensions,
   * manifest may be split up into several files. Using the manifest returned for this method will
   * guarantee that the manifest is combined into a single entity.
   *
   * @param in XML input stream
   */
  IMSManifest getImsManifest(InputStream in) throws IOException;
}


text:
const prod = process.env.NODE_ENV === 'production'

module.exports = {
  'process.env.BASE_URL': prod ? 'https://tebukuro-api.shinosakarb.org/' : 'http://localhost:3000/',
  'process.env.FRONT_URL': prod ? 'https://tebukuro.shinosakarb.org/' : 'http://localhost:4000/',
}


text:
namespace android.text.style
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class TabStopSpan_Standard : java.lang.Object, TabStopSpan
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected TabStopSpan_Standard(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		public new int TabStop
		{
			get
			{
				return getTabStop();
			}
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public virtual int getTabStop()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.style.TabStopSpan_Standard.staticClass, "getTabStop", "()I", ref global::android.text.style.TabStopSpan_Standard._m0);
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public TabStopSpan_Standard(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.text.style.TabStopSpan_Standard._m1.native == global::System.IntPtr.Zero)
				global::android.text.style.TabStopSpan_Standard._m1 = @__env.GetMethodIDNoThrow(global::android.text.style.TabStopSpan_Standard.staticClass, "<init>", "(I)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.style.TabStopSpan_Standard.staticClass, global::android.text.style.TabStopSpan_Standard._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
			Init(@__env, handle);
		}
		static TabStopSpan_Standard()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.text.style.TabStopSpan_Standard.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/style/TabStopSpan$Standard"));
		}
	}
}


text:
import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import {LOGS_DEFAULT_ACTIONBAR} from '@common/components/actionbars/routing';
import {BREADCRUMBS} from '../../../index.messages';
import {WORKLOADS_ROUTE} from '../routing';

import {JobDetailComponent} from './detail/component';
import {JobListComponent} from './list/component';

const JOB_LIST_ROUTE: Route = {
  path: '',
  component: JobListComponent,
  data: {
    breadcrumb: BREADCRUMBS.Jobs,
    parent: WORKLOADS_ROUTE,
  },
};

const JOB_DETAIL_ROUTE: Route = {
  path: ':resourceNamespace/:resourceName',
  component: JobDetailComponent,
  data: {
    breadcrumb: '{{ resourceName }}',
    parent: JOB_LIST_ROUTE,
  },
};

@NgModule({
  imports: [RouterModule.forChild([JOB_LIST_ROUTE, JOB_DETAIL_ROUTE, LOGS_DEFAULT_ACTIONBAR])],
  exports: [RouterModule],
})
export class JobRoutingModule {}


text:
package org.apache.camel.test.infra.common.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.DockerClientFactory;

public final class ContainerEnvironmentUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ContainerEnvironmentUtil.class);

    private static boolean dockerAvailable;
    private static boolean environmentCheckState;

    private ContainerEnvironmentUtil() {

    }

    public static synchronized boolean isDockerAvailable() {
        if (!environmentCheckState) {
            dockerAvailable = DockerClientFactory.instance().isDockerAvailable();
            if (!dockerAvailable) {
                LOG.warn("Docker environment is not available");
            }

            environmentCheckState = true;
        }

        return dockerAvailable;
    }
}


text:
.. _restful:

==========================================
Low level RESTful web service API
==========================================

.. currentmodule:: devilry.restful

http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services

This API was first introduced in this `github issue <https://github.com/devilry/devilry-django/issues/93>`_

Tutorial
########

For this tutorial, create the *myexample* django application. You can see the
result of everything we explain here in
``devilry/projects/dev/apps/restfulexample/``.

A simple RESTful example
------------------------

We will start with a creating a CRUD+s (create, read, update, delete and
search) interface. ``restfulexample/restful.py``:

.. literalinclude:: /../devilry/projects/dev/apps/restfulexample/restful.py

``@example_restful`` is a :class:`RestfulManager` where we register our ``RestfulExample``. The RestfulManager
is only used to simplify setting up URLs for big restful APIs.

Read, update and delete requires an identifier (``id``), because it makes no sense
to manipulate an object that we can not identify. Each method returns a :class:`SerializableResult`,
whose first argument is a serializable python object. The default serializer is
JSON, which means that our class returns JSON unless the HTTP request contains a
*HTTP Accept header* specifying another content type.

Registering urls for RestfulExample
-----------------------------------

Since we use a :class:`RestfulManager`, URL generation is very simple. ``restfulexample/urls.py`` looks like this:

.. literalinclude:: /../devilry/projects/dev/apps/restfulexample/urls.py

API
###

.. automodule:: devilry.restful


text:
(function () {
    var ajax = function (url, settings) {
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        settings = settings || {};
        xhr.open(settings.method || 'GET', url, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.setRequestHeader('Accept', 'text/html');
        xhr.onreadystatechange = function (state) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200 && settings.success) {
                    settings.success(xhr);
                } else if (xhr.status != 200 && settings.error) {
                    settings.error(xhr);
                }
            }
        };
        xhr.send(settings.data || '');
    };

    var e = document.getElementById('yii-debug-toolbar');
    if (e) {
        e.style.display = 'block';
        var url = e.getAttribute('data-url');
        ajax(url, {
            success: function (xhr) {
                var div = document.createElement('div');
                div.innerHTML = xhr.responseText;
                e.parentNode.replaceChild(div, e);
                if (window.localStorage) {
                    var pref = localStorage.getItem('yii-debug-toolbar');
                    if (pref == 'minimized') {
                        document.getElementById('yii-debug-toolbar').style.display = 'none';
                        //document.getElementById('yii-debug-toolbar-min').style.display = 'block';
                        document.getElementById('').style.display = 'block';
                    }
                }
            },
            error: function (xhr) {
                e.innerHTML = xhr.responseText;
            }
        });
    }
})();


text:
@import Foundation;
@import UIKit;

#import "KZPComponent.h"

// from - to - from - to

extern void __attribute__((overloadable)) KZPAnimate(CGFloat from, CGFloat to, void (^block)(CGFloat));

extern void __attribute__((overloadable)) KZPAnimate(float from, float to, void (^block)(float));
extern void __attribute__((overloadable)) KZPAnimateAR(float from, float to, void (^block)(float));

extern void __attribute__((overloadable)) KZPAnimate(void (^block)(void));

#define KZPAnimateValue(name, from, to) __block CGFloat name = from; KZPAnimate(from, to, ^(CGFloat f) { name = f; });
#define KZPAnimateValueAR(name, from, to) __block CGFloat name = from; KZPAnimate(0, M_PI, ^(CGFloat f) { name = sinf(f) * (to - from) + from; });

#define KZPWhenChanged(value, completion) __block typeof(value) kzp_previous__##value = value; KZPAnimate(^{ if (kzp_previous__##value != value) { kzp_previous__##value = value; completion(value); }})

@interface KZPAnimatorComponent : NSObject <KZPComponent>
+ (void)addAnimatorFromValue:(CGFloat)from toValue:(CGFloat)to withBlock:(void (^)(CGFloat))block;
@end


text:
package com.rockwellcollins.atc.agree.validation;

public class AgreeType {
	public static final AgreeType BOOL = new AgreeType("bool");
	public static final AgreeType INT = new AgreeType("int");
	public static final AgreeType REAL = new AgreeType("real");
	public static final AgreeType ERROR = new AgreeType("<error>");

	private String name;

	public AgreeType(String name) {
		this.name = name;
	}

	public boolean isPrimitive() {
		return equals(BOOL) || equals(INT) || equals(REAL);
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof AgreeType) {
			AgreeType other = (AgreeType) o;
			return name.equals(other.name);
		}
		return false;
	}

	@Override
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	public String toString() {
		return name;
	}
}


text:
@implementation WeatherInfo

@dynamic addi_data;
@dynamic addi_info;
@dynamic city;
@dynamic date_day;
@dynamic hour_period;
@dynamic is_analyzed;
@dynamic moisture;
@dynamic pm25;
@dynamic temperature;
@dynamic weather;
@dynamic wind;
@dynamic trip_owner;
@dynamic extend;

@end


text:
package org.surus.math;

import static org.junit.Assert.*;

import java.util.Random;

import org.junit.Test;

public class AugmentedDickeyFuller_Test {

	@Test
	public void testLinearTrend() {
		Random rand = new Random();
		double[] x = new double[100];
		for (int i = 0; i < x.length; i ++) {
			x[i] = (i+1) + 5*rand.nextDouble();
		}
		AugmentedDickeyFuller adf = new AugmentedDickeyFuller(x);
		assertTrue(adf.isNeedsDiff() == true);
	}

	@Test
	public void testLinearTrendWithOutlier() {
		Random rand = new Random();
		double[] x = new double[100];
		for (int i = 0; i < x.length; i ++) {
			x[i] = (i+1) + 5*rand.nextDouble();
		}
		x[50] = 100;
		AugmentedDickeyFuller adf = new AugmentedDickeyFuller(x);
		assertTrue(adf.isNeedsDiff() == true);
	}

}


text:
Duostaff::Application.configure do
  config.cache_classes = true
  config.eager_load = false

  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_dispatch.show_exceptions = false

  config.action_controller.allow_forgery_protection    = false

  config.action_mailer.delivery_method = :test

  config.active_support.deprecation = :stderr
  config.serve_static_assets = true
  config.static_cache_control = "public, max-age=3600"

  config.assets.allow_debugging = true

  BASE_URL = 'localhost'
  BASE_PORT = 3000
  WEBSITE_URL = 'http://test.duostraff.dn.ua'
end


text:
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TypeFamilies          #-}
module HelHUG.Part1 where

-- One approach would be to define:
--
-- > data PL' = PL'
-- >  { plId' :: EntityId
-- >  , ...
-- >  , plInfluenced' :: [PL]
-- >  }
--
-- And maybe some:
--
-- > class PLClass pl where
-- >   plId :: pl -> EntityId
-- >   ...
--
-- TL;DR so fun, much boilerplate, many loc, wow

import Control.Applicative
import Control.Monad.Error (throwError)
import Data.List           (intercalate, nub, sort)
import Data.Traversable    (traverse)
import HelHUG.DB
import HelHUG.DB.Attribute

-- | We could use DataKinds...
data Zero
data Succ a

newtype Reference (e :: * -> *) = Reference { unReference :: EntityId }

type family Ref n (e :: * -> *) :: * where
  Ref Zero e = Reference e
  Ref (Succ n) e = e n

data PL n = PL
  { plId         :: EntityId
  , plName       :: String
  , plUrl        :: String
  , plAppearedIn :: Maybe Int
  , plTypingDis  :: [String]
  , plInfluenced :: [Ref n PL]
  }

toPL :: Entity -> Maybe (PL Zero)
toPL ent = PL (entityId ent) <$> getAttr "title" ent
                             <*> getAttr "url" ent
                             <*> pure (getAttr "appearedIn" ent)
                             <*> getAttr "typingDiscipline" ent
                             <*> (fmap Reference <$> getAttr "influenced" ent)

-- $setup
-- >>> Right db <- readDB "pl.json"

mlEntityId :: EntityId
mlEntityId = EntityId 89

-- | Let's try ML
-- >>> fmap plName <$> runDBMonad ml db
-- Right (Just "ML")
ml :: DBMonad (Maybe (PL Zero))
ml = toPL <$> askEntity mlEntityId

-- And we can port what we had:
prettyPL' :: PL n -> String -> String
prettyPL' PL {..} influencedStr =
   intercalate "\n" [ "name:        " ++ plName
                    , "url:         " ++ plUrl
                    , "appeared in: " ++ maybe "-" show plAppearedIn
                    , "typing:      " ++ intercalate ", " plTypingDis
                    , "influenced:  " ++ influencedStr
                    ]

-- | And we can continue with what we had:
--
-- >>> let Right (Just pl) = runDBMonad ml db
-- >>> putStrLn $ prettyPL pl
-- name:        ML
-- url:         http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing:      static, strong, inferred, safe
-- influenced:  [88,98,105,108,117,122,185,277,287,288]
prettyPL :: PL Zero -> String
prettyPL pl @ PL { plInfluenced = influenced } =
  prettyPL' pl . show . sort . map (unEntityId . unReference) $ influenced

-- Let's write some magic!
class IsEntity (e :: * -> *) n where
  unwrap :: Ref n e -> DBMonad (e n)

instance IsEntity PL Zero where
  unwrap (Reference eid) = do
    entity <- askEntity eid
    case toPL entity of
      Just pl -> return pl
      Nothing -> throwError $ "can't parse entity as PL -- " ++ show eid

instance IsEntity PL n => IsEntity PL (Succ n) where
  unwrap pl = mk <$> traverse unwrap (plInfluenced pl)
    where mk influenced = pl { plInfluenced = influenced }

-- | Let's write more human friendly renderer:
--
-- >>> let Right (Just pl)  = runDBMonad ml db
-- >>> let Right pl'        = runDBMonad (unwrap pl) db
-- >>> putStrLn $ prettierPL pl'
-- name:        ML
-- url:         http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing:      static, strong, inferred, safe
-- influenced:  C++, Clojure, Cyclone, Erlang, F Sharp, Felix, Haskell, Miranda, Opa, Scala
prettierPL :: PL (Succ Zero) -> String
prettierPL pl @ PL { plInfluenced = influenced } =
  prettyPL' pl . intercalate ", " . sort . map plName $ influenced

-- | And we can generalise:
--
-- >>> let Right (Just pl)  = runDBMonad ml db
-- >>> let Right pl'        = runDBMonad (unwrap pl) db
-- >>> putStrLn $ prettierPL' pl'
-- name:        ML
-- url:         http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing:      static, strong, inferred, safe
-- influenced:  C++, Clojure, Cyclone, Erlang, F Sharp, Felix, Haskell, Miranda, Opa, Scala
prettierPL' :: PL (Succ n) -> String
prettierPL' pl @ PL { plInfluenced = influenced } =
  prettyPL' pl . intercalate ", " . sort . map plName $ influenced

-- So now we could go deeper into the hierarchy:
mlUnwrappedTwice :: DBMonad (PL (Succ (Succ Zero)))
mlUnwrappedTwice = return (Reference mlEntityId) >>= unwrap >>= unwrap >>= unwrap

-- | But we could apply `prettierPL'` still
--
-- >>> let Right pl = runDBMonad mlUnwrappedTwice db
-- >>> putStrLn $ prettierPL' pl
-- name:        ML
-- url:         http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing:      static, strong, inferred, safe
-- influenced:  C++, Clojure, Cyclone, Erlang, F Sharp, Felix, Haskell, Miranda, Opa, Scala

-- | An we can get influenced influenced:
--
-- >>> runDBMonad (Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced <$> mlUnwrappedTwice) db
-- Right ["Ada","Agda","Akka (toolkit)","Bluespec, Inc.","C Sharp","C++11","C99",...

-- | GHC is smart enough to infer types for complicated expressions like that:
--
-- >>> :t \pl -> Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced $ pl
-- \pl -> Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced $ pl
--   :: (Ref n2 PL ~ PL n1, Ref n1 PL ~ PL n) => PL n2 -> [String]

magic :: PL (Succ (Succ n)) -> [String]
magic pl = Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced $ pl

-- | Error case!
--
-- >>> runDBMonad (prettierPL' <$> return (Reference mlEntityId) >>= unwrap) db
-- ...
--     Couldn't match expected type ...
-- ...


text:
@implementation MapViewPreview
{
MapViewPreviewController *mapViewPreviewController_;
}

- (void) initializeCustomController
{
    mapViewPreviewController_ = [[MapViewPreviewController alloc] initWithNibName:@"MapViewPreviewController" bundle:nil];
}

-(UIView *)previewView
{
    return mapViewPreviewController_.view;
}

- (BOOL) reloadPreviewOnEdit
{
    return NO;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#eee"
    android:orientation="vertical" >

    <include layout="@layout/titlebar_base" />

    <EditText
        android:id="@+id/feedback_content_edit"
        android:layout_width="fill_parent"
        android:layout_height="0.0dp"
        android:layout_margin="5dp"
        android:layout_weight="1.0"
        android:background="@color/white"
        android:gravity="top"
        android:hint="请输入您的反馈意见"
        android:paddingBottom="14.0dp"
        android:paddingLeft="12.0dp"
        android:paddingTop="12.0dp"
        android:singleLine="false"
        android:textColor="#ff333333"
        android:textSize="18.0sp" />

    <EditText
        android:id="@+id/feedback_contact_edit"
        android:layout_width="fill_parent"
        android:layout_height="48.0dp"
        android:layout_margin="5dp"
        android:layout_marginTop="10.0dp"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:hint="联系方式/邮箱/QQ/手机号"
        android:paddingLeft="12.0dp"
        android:paddingRight="12.0dp"
        android:singleLine="true"
        android:textColor="#ff333333"
        android:textSize="18.0sp" />

    <Button
        android:id="@+id/feedback_submit_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_marginBottom="5.0dp"
        android:layout_marginTop="10.0dp"
        android:background="@drawable/base_btn"
        android:padding="10.0dp"
        android:text="提交"
        android:textColor="@color/white"
        android:textSize="18.0sp" />

</LinearLayout>


text:
from urllib.parse import unquote

from collections.abc import Iterable
from wtforms.widgets import html_params, HTMLString

class FileDisplayWidget(object):

    def __init__(self, input_type='string', text=''):
        self.input_type = input_type
        self.text = text

    def get_filename(self, name):
        return '-'.join(name.split('/')[-1].split('-')[1:])

    def __call__(self, field, **kwargs):
        kwargs.setdefault('id', field.id)
        html = [u'
' % html_params(id=field.id)]
        data = field.data
        if data:
            if not isinstance(data, Iterable):
                data = unquote(data)
                params = dict(href=data)
                html.append(u'
%s
' % (html_params(**params), self.get_filename(data)))
            else:
                for link in data:
                    if link:
                        link = unquote(link)
                        params = dict(href=link)
                        html.append(u'
%s
' % (html_params(**params), self.get_filename(link)))
        html.append(u'
')
        return HTMLString(u''.join(html))


text:
namespace MassTransit
{
    using System;

    [Serializable]
    public class JobNotFoundException :
        MassTransitException
    {
        public JobNotFoundException()
        {
        }

        public JobNotFoundException(string message)
            : base(message)
        {
        }
    }
}


text:
def largest_integer(list_of_nums)
largest = list_of_nums[0]
for num in list_of_nums do
  if num > largest
    largest = num
  end
end
largest
end


text:
package org.hisp.dhis.webapi.view;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.hisp.dhis.common.Grid;
import org.hisp.dhis.system.grid.GridUtils;
import org.hisp.dhis.webapi.utils.ContextUtils;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
public class CsvGridView extends AbstractGridView
{
    public CsvGridView()
    {
        setContentType( ContextUtils.CONTENT_TYPE_CSV );
    }

    @Override
    protected void renderGrids( List<Grid> grids, HttpServletResponse response ) throws Exception
    {
        if ( !grids.isEmpty() )
        {
            GridUtils.toCsv( grids.get( 0 ), response.getWriter() );
        }
    }
}


text:
Building Bitcoin Core with Visual Studio
========================================

Introduction
---------------------
Solution and project files to build the Bitcoin Core applications `msbuild` or Visual Studio can be found in the build_msvc directory. The build has been tested with Visual Studio 2017 and 2019.

Building with Visual Studio is an alternative to the Linux based [cross-compiler build](https://github.com/bitcoin/bitcoin/blob/master/doc/build-windows.md).

Quick Start
---------------------
The minimal steps required to build Bitcoin Core with the msbuild toolchain are below. More detailed instructions are contained in the following sections.

```
vcpkg install --triplet x64-windows-static berkeleydb boost-filesystem boost-multi-index boost-signals2 boost-test boost-thread libevent[thread] zeromq double-conversion
vcpkg integrate install
py -3 build_msvc\msvc-autogen.py
msbuild /m build_msvc\bitcoin.sln /p:Platform=x64 /p:Configuration=Release /t:build
```

Dependencies
---------------------
A number of [open source libraries](https://github.com/bitcoin/bitcoin/blob/master/doc/dependencies.md) are required in order to be able to build Bitcoin Core.

Options for installing the dependencies in a Visual Studio compatible manner are:

- Use Microsoft's [vcpkg](https://docs.microsoft.com/en-us/cpp/vcpkg) to download the source packages and build locally. This is the recommended approach.
- Download the source code, build each dependency, add the required include paths, link libraries and binary tools to the Visual Studio project files.
- Use [nuget](https://www.nuget.org/) packages with the understanding that any binary files have been compiled by an untrusted third party.

The [external dependencies](https://github.com/bitcoin/bitcoin/blob/master/doc/dependencies.md) required for building are:

- Berkeley DB
- Boost
- DoubleConversion
- libevent
- Qt5
- ZeroMQ

Qt
---------------------
In order to build the Bitcoin Core a static build of Qt is required. The runtime library version (e.g. v141, v142) and platform type (x86 or x64) must also match.

Some prebuilt x64 versions of Qt can be downloaded from [here](https://github.com/sipsorcery/qt_win_binary/releases). Please be aware these downloads are NOT officially sanctioned by Bitcoin Core and are provided for developer convenience only. They should NOT be used for builds that will be used in a production environment or with real funds.

To determine which Qt prebuilt version to download open the `.appveyor.yml` file and note the `QT_DOWNLOAD_URL`. When extracting the zip file the destination path must be set to `C:\`. This is due to the way that Qt includes, libraries and tools use internal paths.

To build Bitcoin Core without Qt unload or disable the `bitcoin-qt`, `libbitcoin_qt` and `test_bitcoin-qt` projects.

Building
---------------------
The instructions below use `vcpkg` to install the dependencies.

- Install [`vcpkg`](https://github.com/Microsoft/vcpkg).
- Install the required packages (replace x64 with x86 as required). The list of required packages can be found in the `build_msvc\vcpkg-packages.txt` file. The PowerShell command below will work if run from the repository root directory and `vcpkg` is in the path. Alternatively the contents of the packages text file can be pasted in place of the `Get-Content` cmdlet.

```
PS >.\vcpkg install --triplet x64-windows-static $(Get-Content -Path build_msvc\vcpkg-packages.txt).split()
PS >.\vcpkg integrate install
```

- Use Python to generate `*.vcxproj` from Makefile

```
PS >py -3 msvc-autogen.py
```

- An optional step is to adjust the settings in the build_msvc directory and the common.init.vcxproj file. This project file contains settings that are common to all projects such as the runtime library version and target Windows SDK version. The Qt directories can also be set.

- To build from the command line with the Visual Studio 2017 toolchain use:

```
msbuild /m bitcoin.sln /p:Platform=x64 /p:Configuration=Release /p:PlatformToolset=v141 /t:build
```

- To build from the command line with the Visual Studio 2019 toolchain use:

```
msbuild /m bitcoin.sln /p:Platform=x64 /p:Configuration=Release /t:build
```

- Alternatively open the `build_msvc\bitcoin.sln` file in Visual Studio.

AppVeyor
---------------------
The .appveyor.yml in the root directory is suitable to perform builds on [AppVeyor](https://www.appveyor.com/) Continuous Integration servers. The simplest way to perform an AppVeyor build is to fork Bitcoin Core and then configure a new AppVeyor Project pointing to the forked repository.

For safety reasons the Bitcoin Core .appveyor.yml file has the artifact options disabled. The build will be performed but no executable files will be available. To enable artifacts on a forked repository uncomment the lines shown below:

```
    #- 7z a bitcoin-%APPVEYOR_BUILD_VERSION%.zip %APPVEYOR_BUILD_FOLDER%\build_msvc\%platform%\%configuration%\*.exe
    #- path: bitcoin-%APPVEYOR_BUILD_VERSION%.zip
```


text:
[![dockerhub](https://img.shields.io/docker/automated/leonisandco/rds-mysql-slowlog-monitor.svg)](https://hub.docker.com/r/leonisandco/rds-mysql-slowlog-monitor/)

This repository provides a docker image which monitors the slow query logs in the RDS(mysql engine) and notifies the event to the slack channel.

## Architecture

```
[RDS(mysql)] --(slow query log)--> {[fluentd on docker]} --(incoming webhook)--> [slack channel]
```

# HowToUse

## Configuration

### RDS(mysql)

slow query logが出力されるようにRDSのparameter groupの設定値を調整してください。

### docker image

環境変数によって、対象にするRDS/slackの通知先を変更します。

see `sample.env`.

# HowToRun

環境変数は`sample.env`を参考に、dotenvのフォーマットでファイルにまとめておくと便利です。

```
# pull the docker image
docker pull leonisandco/rds-mysql-slowlog-monitor:latest

# just run , not as a daemon
docker run -it --rm --env-file dot.env leonisandco/rds-mysql-slowlog-monitor:latest

# run as a daemon
docker run -d --env-file dot.env leonisandco/rds-mysql-slowlog-monitor:latest
```

# Q&A

## 対象RDSのslow\_logテーブルからログデータが無くなる?

このdocker imageを使うと、RDS(mysql)上のslow\_logテーブルの中身が定期的にクリアされて無くなります。

**slow_logのデータを保存したい場合は、どこかのデータストアに保存する/fluent.confを調整してbackupするようにするなどが必要**です。

=> [fluent-plugin-rds-slowlogのOverview](https://github.com/kenjiskywalker/fluent-plugin-rds-slowlog#overview)

# License

MIT


text:
Getting Started App System Administration

			<a href="<?= $this->url('', '') ?>" class="btn back-to">back to list

				 Manage account

				<form class="ajax" action="<?= $this->url('change_password', 'auth') ?>">

						Change my password

						<fieldset>
							New password
							<input type="password" name="password" value="" id="new-password" />
						</fieldset>
						<fieldset>
							Confirm new password
							<input type="password" name="confirm_password" value="" id="comfirm-password" />
						</fieldset>
						<fieldset class="no-label">
							<button type="submit" class="btn btn-primary">
								Change password
							</button>
						</fieldset>

				</form>

		<? $this->partial('bottom_content') ?>


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta http-equiv="x-ua-compatible" content="ie=edge" />

        <title>Around the Corner · snowfall example by @drfollowmario</title>

	<link rel="stylesheet" href="res/css/bootstrap.min.css" />
	<link rel="stylesheet" href="res/css/bootstrap-theme-freelancer.css" />
        <link rel="stylesheet" href="res/css/jqmath-0.4.3.css" />
        <link rel="stylesheet" href="res/css/font-awesome.min.css" />
        <link rel="stylesheet" href="res/css/fonts.min.css" />
        <link rel="stylesheet" href="res/css/animate.min.css" />
	<link rel="stylesheet" href="res/css/main.css" />

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable_navbar">
                        Toggle navigation

                    </button>
                    Around the Corner

Try

Fail

Solve

Numbers

Rubik

Cubing

Derivates

                            Around the Corner

                            How a nerd's puzzle made its way to the mainstream. And back to nerds.

Try it!

I am pretty sure, you had one of these magic cubes (also called Rubik's cube®). Maybe you still have one. So in order to get into the right mood, grab it and go ahead: scramble (without sneak-peeks) and try to solve it.

                            Okay, tough start, I know. Maybe I give you a few hints first:

The ordinary 3×3×3 cube is made up from six dependent sides. That means that you cannot choose whether you'd like the green side next to the red one (that'll work) or next to the blue one (that won't work).

The cube is constructed with the center pieces of each side to be fixed. You may rotate but not move them.

Except for the center pieces, there are two other kinds of pieces:

Edge pieces contain two sides (= colors) and go into one of twelve positions as there are exactly twelve pieces of them.

Corner pieces are made up from three sides (colors). There are only eight of them and (you might guess already) there are eight positions where they could go.

Picture by Curis, CC BY-SA 3.0 license, via Wikimedia Commons

Fail!

Could you solve it?

                            Yes (I swear)
                            Nope (don't blame me)

Fail!

Don't worry, most people are not able to solve a 3×3×3 magic cube.

Let me help you:

Think of the cube as it would be made out of three layers (a layer's example is depicted in the image on the left).

Imagine some pale and pimply nerds with some very thick glasses during the 1980's to try'n'error the cube over and over again.

No, really: think of them!

Okay, now trust me to believe them that the best way to solve the cube is to approach it by following some basic principles:

try to solve it layer by layer

as the center pieces are not moveable, every side's color is determined by its center piece (that is, if a side's center piece is white, this side is gonna be white, no matter what)

for every piece (they are actually called cubies) you position, pay attention that they match each side's color

Now try again.

Picture by Thomas 003, CC BY-SA 3.0 license, via Wikimedia Commons

Solve it!

Remember the pale and pimply 1980's nerds? Well, they solved the cube. And they did so in multiple ways. Since finding these ways is an awful lot of work, everyone who found a new recipe to solve a scrambled magic cube, happy of having achieved this mental milestone, named this recipe after themselve. Hence, we now know of multiple methods to solve the cube, all named after their founders. Here are some of them (yet, there are more):

                                        Name
                                        Founder
                                        Year of discovery
                                        Fast to use
                                        Easy to use
                                        Efficient
                                        Easy to learn
                                        Link to description

                                        layer-by-layer
                                        n/a
                                        ?

                                        solve it

                                        Petrus
                                        Lars Petrus
                                        1981

                                        solve it

                                        Waterman
                                        Marc Waterman
                                        1981/1982

                                        solve it

                                        Fridrich
                                        Jessica Fridrich
                                        1997

                                        solve it

                                        Roux
                                        Gilles Roux
                                        2000's

                                        solve it

                                        ZZ
                                        Zbigniew Zborowski
                                        2006

                                        solve it

Every solving method (recipe) contains several steps of how to do this (e.g., put the corner stones in the right position) and how to do that (e.g., rotate the corner stones adequately). These single-step recipes are called algorithms and in order to solve the cube more than once—and I know that sounds hard—you will (need to) learn some of these algorithms.

Now, the easiest method for beginners is the so-called layer-by-layer method (as so many beginners are using it, it does not even deserve a founder's name). It means, that you'll start with one—say: the white—layer, solve it correctly (also according to the adjacent sides), then move on to the subsequent layer (the one in the middle), and ultimately you solve the top layer (= yellow, if you have started with white). Here's the full idea:

start with the white side up

solve the white center and edge cubies (called, the white cross)

solve the white corner cubies

turn the cube around in order to now have the yellow side up

solve the middle layer's edge cubies

position the yellow side's edge cubies

rotate the yellow side's edge cubies adequately (resulting in a yellow cross)

position the yellow layer's corner cubies

rotate the yellow layer's corner cubies

A little trivia: in Germany's weekly magazine Der Spiegel, back in 1981, there was an "article" telling its readers how to solve the cube. As the PDF version is still available, go ahead read'n'solve it. The article's title—by the way—says something like "yell hurrah, spend some drinks." As it is German, though, you may find this english method description more useful.

Notations

In order to learn new algorithms by hard, some people came up with a way of writing them down (One may also speculate that notations came up in order to avoid human contact among pale and thick-glassed ...).

Notations follow orientation.

That is, you have one side facing up (e.g., white), and notation tells you to move the right-handed layer in clockwise (R) or counter-clockwise (R') direction. The same goes with the left-handed layer (L and L' respectively), the upper (U) and lower (D for down) layer, as well as the front (F) and back (B) layer.

Image by matt2uy, CC license, via instructables.com

Numbers

Could you solve it?

                            Yes (this time, I mean it)
                            Still no (and that makes me sad)

Numbers

43 252 003 274 489 856 000

That's the number of possible combinations within one cube. It reads as some fourty-three quintillions.

Why that number? It's actually pretty simple. There are eight corner stones, giving us 8! (the exclamation mark is called faculty) possibilities. A corner stone can take one of three rotations, combined with the eight corner stones, that makes another 38 possibilities. There are twelve edge stones (12!), all capable of two rotations (212). If we multiply these possibilities we'd get a result larger than our 43 quintillions.

Luckily, both the 8th corner stone and the 12th edge stone cannot take all rotations as they are determined by the other corner and edge stones. We thus divide by the number of rotations, once for the corner stones (3) and once for the edge stones (2). Ultimately, as we do not have any free positions, we always need to change two stones or two sides. That is, we can divide our result by another 2, leaving us with the following neat formula:

$${8!⋅3^8⋅12!⋅2^12}/{3⋅2⋅2}=43.252.003.274.489.856.000$$

Ernő Rubik

We still do not know why the magic cube is sometimes referred to as Rubik's cube®, do we? The answer is rather simple, though—it's because of its initial founder, Ernő Rubik.

Rubik was born in 1944 and is a Hungarian architect and designer. He invented the cube in 1974 in order to puzzle his students and found it to be such a good puzzle that he applied for a patent only a few months later. He paired up with New-York-based Ideal Toys, a toy company that bought the license from Ernő and renamed the puzzle into Rubik's cube®.

I believe probably the most characteristic part of the cube is the contradiction between simplicity and complexity. I love the simplicity of the cube because it's a very clear geometrical shape, and I love geometry because it's the study of how the whole universe is structured.

                            Ernő Rubik in a CNN interview in 2012

Picture by Babak Mansouri, CC BY-SA 3.0 license, via Wikimedia Commons

It's international success followed suite. The cube was instantly awarded with the well-renowned "German Game of the Year" prize in 1980. As with 1980 the cube gained international popularity, selling over 350 million pieces until 2009 and thus making it one of the best-selling toys of all time. Today, plenty of copycats exist (explicitely called magic cubes rather than "Rubik"); however, despite the initial imitation, some of these versions are very popular among speedcubers (see the next section) as their mechanics move smoother.

Rubik's initial version was made out of wood and rubber bands, yet he quickly changed the materials to plastic. Today, almost all cubes are made from plastic. Yet, the basic mechanics have not changed ever since: a 3-dimensional cross in the middle of the cube fixates the center cubies and their relation to each other. All other cubies are inserted rather loosely.

These days, there's also a standardized size of the 3×3×3 cube in order to make Rubik's and others comparable. The official size is 57,5mm in length (as it's a cube, the full size declaration would be 57,5×57,5×57,5, obviously). Smaller and larger versions are available, but they are not allowed at official contests.

Picture by Roland Frisch, CC BY-SA 3.0 license, via Wikimedia Commons

The Cubing Scene

Yes, you read that one right: official contests. The cubing scene is big and it's growing. There are championships, there are world records (in multiple disciplines), and there is even a world cube association (of which, by the way, Gilles Roux used to be a board member). To get an impression of these tournaments, check out the variety of disciplines people try to solve cubes in:

2×2×2

Solve a smaller version of the cube as quickly as you can.

3×3×3

Just solve an ordinary cube within an adequate time.

fewest moves

Solve an ordinary cube with as fewest moves as you can get.

4×4×4

That cube is a little harder as the center cubies can actually move.

5×5×5

Getting tougher, that one's called "Professor's cube" by the way..

6×6×6

It's quite similar to the 4×4×4 cube although larger.

7×7×7

Okay, that's nerdy. And it has an own name: "V-Cube 7."

3×3×3 blindfolded

Look at the cube but don't solve it. Now close your eyes and solve.

4×4×4/5×5×5 blindfolded

Again, look at a (bigger) cube, close your eyes, and do it.

multiple blindfolded

Remember a few cubes at once before shutting your eyes and solving them.

one-handed

You are allowed to look and it's only a 3×3×3—but you are not allowed to use your second hand.

by feet

Solve it, using your feet. Only your feet. That one's called "stinky cube" (just kidding).

However, the supreme discipline is speedcubing with an official 3×3×3 (and thus 57,5×57,5×57,5mm) cube. Take a look:

Derivates

Ultimately, after you now know a lot about the 3×3×3 magic cube and are even capable of solving it (let's assume, at least), you may also be a little hooked on such puzzles. Well, I am. Luckily, there are some derivates of the cube that keep me puzzled. Find out, what kind of derivates exist by clicking on the images.

                                        There are smaller versions of the cube available. These seem to be beginner-savvy cubes and they are indeed a little easier to solve; however, they are not some sort of try-me-and-you-are-ready-for-the-next-dimension cubes as their solution differs completely from the solution a 3×3×3 or other cubes need.

                                        There are larger versions of the cube available, such as 4×4×4 or (as in the picture) 5×5×5. These variants are available up to 7 pieces per side, and their solution get harder with every additional piece.

                                        As you can see, there are also cubes without colored faces. This makes them slightly more complicated as you cannot focus on the colors anymore but need to keep in mind the pieces' belongings to the quasi-colored faces.

                                        The Tetraminx in the picture is only one example of weird non-cubic cubes. That is, these cubes either are no cubes at all or they change their shape through rotating sides. In addition, they sometimes also lock various moves, making them a little tougher to solve.

The Story

Cubing facts based on Wikipedia, images from Wikimedia.

The Storytelling

This page should, besides motivating your cubing self, explain how to easily set up a scrollytelling/snowfall page. If you want to find out more, start the tour.

The Imprint

Page and snowfall tour created by Mario Haim. Powered by jQuery, Bootstrap, animate.css, WOW.js, Font Awesome, jqMath, and the Freelance template.

                            to top
                            © by Mario Haim 2015 · Download source at GitHub

                                    Picture by , CC BY-SA 3.0 license, via Wikimedia Commons

                                <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
package clock

import (
	"time"
)

// NowFn is the function supplied to determine "now".
type NowFn func() time.Time

// Options represents the options for the clock.
type Options interface {
	// SetNowFn sets the NowFn.
	SetNowFn(value NowFn) Options

	// NowFn returns the NowFn.
	NowFn() NowFn

	// SetMaxPositiveSkew sets the maximum positive clock skew
	// with regard to a reference clock.
	SetMaxPositiveSkew(value time.Duration) Options

	// MaxPositiveSkew returns the maximum positive clock skew
	// with regard to a reference clock.
	MaxPositiveSkew() time.Duration

	// SetMaxNegativeSkew sets the maximum negative clock skew
	// with regard to a reference clock.
	SetMaxNegativeSkew(value time.Duration) Options

	// MaxNegativeSkew returns the maximum negative clock skew
	// with regard to a reference clock.
	MaxNegativeSkew() time.Duration
}

// ConditionFn specifies a predicate to check.
type ConditionFn func() bool

// WaitUntil returns true if the condition specified evaluated to
// true before the timeout, false otherwise.
func WaitUntil(fn ConditionFn, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		if fn() {
			return true
		}
		time.Sleep(100 * time.Millisecond)
	}
	return false
}


text:
.. automodule:: montreal_forced_aligner.textgrid

   .. autosummary::
      :toctree: generated/

       process_ctm_line
       export_textgrid
       output_textgrid_writing_errors