text:
module Mail
    module IMAP
        class Query
            ALL = "ALL"
            ANSWERED = "ANSWERED"
            BCC = "BCC"
            BEFORE = "BEFORE"
            BODY = "BODY"
            CC = "CC"
            DELETED = "DELETED"
            DRAFT = "DRAFT"
            FLAGGED = "FLAGGED"
            FROM = "FROM"
            HEADER = "HEADER"
            KEYWORD = "KEYWORD"
            LARGER = "LARGER"
            NEW = "NEW"
            NOT = "NOT"
            OLD = "OLD"
            ON = "ON"
            OR = "OR"
            RECENT = "RECENT"
            SEEN = "SEEN"
            SENTBEFORE = "SENTBEFORE"
            SENTON = "SENTON"
            SENTSINCE = "SENTSINCE"
            SINCE = "SINCE"
            SMALLER = "SMALLER"
            SUBJECT = "SUBJECT"
            TEXT = "TEXT"
            TO = "TO"
            UID = "UID"
            UNANSWERED = "UNANSWERED"
            UNDELETED = "UNDELETED"
            UNDRAFT = "UNDRAFT"
            UNFLAGGED = "UNFLAGGED"
            UNKEYWORD = "UNKEYWORD"
            UNSEEN = "UNSEEN"

            def initialize
                @params = []
            end

            # Messages with message sequence numbers corresponding to the
            #  specified message sequence number set.
            def message_set(sequence_set)
                return add_params(sequence_set)
            end

            # All messages in the mailbox; the default initial key for
            #  ANDing.
            def all
                return add_params(ALL)
            end

            # Messages with the \Answered flag set.
            def answered
                return add_params(ANSWERED)
            end

            # Messages that contain the specified string in the envelope
            #  structure's BCC field.
            def bcc(string)
                return add_params(BCC, string)
            end

            # Messages whose internal date (disregarding time and timezone)
            #  is earlier than the specified date.
            def before(date)
                return add_params(BEFORE, date_to_s(date))
            end

            # Messages that contain the specified string in the body of the
            #  message.
            def body(string)
                return add_params(BODY, string)
            end

            # Messages that contain the specified string in the envelope
            #  structure's CC field.
            def cc(string)
                return add_params(CC, string)
            end

            # Messages with the \Deleted flag set.
            def deleted
                return add_params(DELETED)
            end

            # Messages with the \Draft flag set.
            def draft
                return add_params(DRAFT)
            end

            # Messages with the \Flagged flag set.
            def flagged
                return add_params(FLAGGED)
            end

            # Messages that contain the specified string in the envelope
            #  structure's FROM field.
            def from(string)
                return add_params(FROM, string)
            end

            # Messages that have a header with the specified field-name (as
            #  defined in [RFC-2822]) and that contains the specified string
            #  in the text of the header (what comes after the colon).  If the
            #  string to search is zero-length, this matches all messages that
            #  have a header line with the specified field-name regardless of
            #  the contents.
            def header(field_name, string)
                return add_params(HEADER, field_name, string)
            end

            # Messages with the specified keyword flag set.
            def keyword(flag)
                return add_params(KEYWORD, flag)
            end

            # Messages with an [RFC-2822] size larger than the specified
            #  number of octets.
            def larger(n)
                return add_params(LARGER, n)
            end

            # Messages that have the \Recent flag set but not the \Seen flag.
            #  This is functionally equivalent to "(RECENT UNSEEN)".
            def new
                return add_params(NEW)
            end

            # Messages that do not match the specified search key.
            def not
                if (block_given?) then
                    child = Query.new

                    yield child

                    return add_params(NOT, child)
                else
                    return add_params(NOT)
                end
            end

            # Messages that do not have the \Recent flag set.  This is
            #  functionally equivalent to "NOT RECENT" (as opposed to "NOT
            #  NEW").
            def old
                return add_params(OLD)
            end

            # Messages whose internal date (disregarding time and timezone)
            #  is within the specified date.
            def on(date)
                return add_params(ON, date_to_s(date))
            end

            # Messages that match either search key.
            def or
                left = Query.new
                right = Query.new

                yield left, right

                return add_params(OR, left, right)
            end

            # Messages that have the \Recent flag set.
            def recent
                return add_params(RECENT)
            end

            # Messages that have the \Seen flag set.
            def seen
                return add_params(SEEN)
            end

            # Messages whose [RFC-2822] Date: header (disregarding time and
            #  timezone) is earlier than the specified date.
            def sent_before(date)
                return add_params(SENTBEFORE, date_to_s(date))
            end

            # Messages whose [RFC-2822] Date: header (disregarding time and
            #  timezone) is within the specified date.
            def sent_on(date)
                return add_params(SENTON, date_to_s(date))
            end

            # Messages whose [RFC-2822] Date: header (disregarding time and
            #  timezone) is within or later than the specified date.
            def sent_since(date)
                return add_params(SENTSINCE, date_to_s(date))
            end

            # Messages whose internal date (disregarding time and timezone)
            #  is within or later than the specified date.
            def since(date)
                return add_params(SINCE, date_to_s(date))
            end

            # Messages with an [RFC-2822] size smaller than the specified
            #  number of octets.
            def smaller(n)
                return add_params(SMALLER, n)
            end

            # Messages that contain the specified string in the envelope
            #  structure's SUBJECT field.
            def subject(string)
                return add_params(SUBJECT, string)
            end

            # Messages that contain the specified string in the header or
            #  body of the message.
            def text(string)
                return add_params(TEXT, string)
            end

            # Messages that contain the specified string in the envelope
            #  structure's TO field.
            def to(string)
                return add_params(TO, string)
            end

            # Messages with unique identifiers corresponding to the specified
            #  unique identifier set.  Sequence set ranges are permitted.
            def uid(sequence_set)
                return add_params(UID, sequence_set)
            end

            # Messages that do not have the \Answered flag set.
            def unanswered
                return add_params(UNANSWERED)
            end

            # Messages that do not have the \Deleted flag set.
            def undeleted
                return add_params(UNDELETED)
            end

            # Messages that do not have the \Draft flag set.
            def undraft
                return add_params(UNDRAFT)
            end

            # Messages that do not have the \Flagged flag set.
            def unflagged
                return add_params(UNFLAGGED)
            end

            # Messages that do not have the specified keyword flag set.
            def unkeyword(flag)
                return add_params(UNKEYWORD, flag)
            end

            # Messages that do not have the \Seen flag set.
            def unseen
                return add_params(UNSEEN)
            end

            def add_params(*params)
                @params.concat(params)

                return self
            end

            def date_to_s(date)
                return date.strftime("%-d-%b-%Y")
            end

            def inspect
                return self.to_s
            end

            def to_s
                return @params.join(" ")
            end
        end
    end
end


text:
var passbook = exports;

var exec = require('cordova/exec');

/**
 * Pass
 *
 * @param {string} passTypeIdentifier
 * @param {string} serialNumber {string}
 * @param {string} passURL
 * @constructor
 */
var Pass = function (passTypeIdentifier, serialNumber, passURL) {
    this.passTypeIdentifier = passTypeIdentifier || null;
    this.serialNumber = serialNumber || null;
    this.passURL = passURL || null;
};

Pass.prototype.open = function () {
    passbook.openPass(this.passURL, null, null);
};

passbook.Pass = Pass;

/**
 *
 * @param resultCallback {Function} is called with result
 */
passbook.available = function (resultCallback) {
    exec(resultCallback, null, "Passbook", "available", []);
};
/**
 *
 * @param {Object}  url:String | { url:String, headers?:Object }
 * @param {Function} passCallback
 * @param {Function} errorCallback
 */
passbook.downloadPass = function (callData, passCallback, errorCallback) {
    exec(function (result) {
        if (typeof(passCallback) === 'function') {
            var pass = result.pass;
            passCallback(new Pass(pass.passTypeIdentifier, pass.serialNumber, pass.passURL), result.added);
        }
    }, errorCallback, "Passbook", "downloadPass", [callData]);
};

/**
 *
 * @param file Local File URL, e.g. file:///path/pass.pkpass
 * @param {Function} passCallback
 * @param {Function} errorCallback
 */
passbook.addPass = function (file, passCallback, errorCallback) {
    exec(function (result) {
        if (typeof(passCallback) === 'function') {
            var pass = result.pass;
            passCallback(new Pass(pass.passTypeIdentifier, pass.serialNumber, pass.passURL), result.added);
        }
    }, errorCallback, "Passbook", "addPass", [file]);
};

/**
 *
 * @param {Pass|string} passOrUrl
 * @param {Function} successCallback
 * @param {Function} errorCallback
 */
passbook.openPass = function (passOrUrl, successCallback, errorCallback) {
    exec(successCallback, errorCallback, "Passbook", "openPass", [passOrUrl]);
};

redpajama_set_name: RedPajamaGithub


text:
package writer

import (
	"context"
	"fmt"
	"sync"
	"time"

	ibatch "github.com/Jeffail/benthos/v3/internal/batch"
	"github.com/Jeffail/benthos/v3/internal/batch/policy"
	"github.com/Jeffail/benthos/v3/internal/bloblang/field"
	"github.com/Jeffail/benthos/v3/internal/component"
	"github.com/Jeffail/benthos/v3/internal/component/metrics"
	bredis "github.com/Jeffail/benthos/v3/internal/impl/redis/old"
	"github.com/Jeffail/benthos/v3/internal/interop"
	"github.com/Jeffail/benthos/v3/internal/log"
	"github.com/Jeffail/benthos/v3/internal/message"
	"github.com/go-redis/redis/v7"
)

//------------------------------------------------------------------------------

// RedisListConfig contains configuration fields for the RedisList output type.
type RedisListConfig struct {
	bredis.Config `json:",inline" yaml:",inline"`
	Key           string        `json:"key" yaml:"key"`
	MaxInFlight   int           `json:"max_in_flight" yaml:"max_in_flight"`
	Batching      policy.Config `json:"batching" yaml:"batching"`
}

// NewRedisListConfig creates a new RedisListConfig with default values.
func NewRedisListConfig() RedisListConfig {
	return RedisListConfig{
		Config:      bredis.NewConfig(),
		Key:         "",
		MaxInFlight: 1,
		Batching:    policy.NewConfig(),
	}
}

//------------------------------------------------------------------------------

// RedisList is an output type that serves RedisList messages.
type RedisList struct {
	log   log.Modular
	stats metrics.Type

	conf RedisListConfig

	keyStr *field.Expression

	client  redis.UniversalClient
	connMut sync.RWMutex
}

// NewRedisListV2 creates a new RedisList output type.
func NewRedisListV2(
	conf RedisListConfig,
	mgr interop.Manager,
	log log.Modular,
	stats metrics.Type,
) (*RedisList, error) {
	r := &RedisList{
		log:   log,
		stats: stats,
		conf:  conf,
	}

	var err error
	if r.keyStr, err = mgr.BloblEnvironment().NewField(conf.Key); err != nil {
		return nil, fmt.Errorf("failed to parse key expression: %v", err)
	}
	if _, err := conf.Config.Client(); err != nil {
		return nil, err
	}

	return r, nil
}

//------------------------------------------------------------------------------

// ConnectWithContext establishes a connection to an RedisList server.
func (r *RedisList) ConnectWithContext(ctx context.Context) error {
	return r.Connect()
}

// Connect establishes a connection to an RedisList server.
func (r *RedisList) Connect() error {
	r.connMut.Lock()
	defer r.connMut.Unlock()

	client, err := r.conf.Config.Client()
	if err != nil {
		return err
	}
	if _, err = client.Ping().Result(); err != nil {
		return err
	}

	r.client = client
	return nil
}

//------------------------------------------------------------------------------

// WriteWithContext attempts to write a message by pushing it to the end of a
// Redis list.
func (r *RedisList) WriteWithContext(ctx context.Context, msg *message.Batch) error {
	r.connMut.RLock()
	client := r.client
	r.connMut.RUnlock()

	if client == nil {
		return component.ErrNotConnected
	}

	if msg.Len() == 1 {
		key := r.keyStr.String(0, msg)
		if err := client.RPush(key, msg.Get(0).Get()).Err(); err != nil {
			_ = r.disconnect()
			r.log.Errorf("Error from redis: %v\n", err)
			return component.ErrNotConnected
		}
		return nil
	}

	pipe := client.Pipeline()
	_ = msg.Iter(func(i int, p *message.Part) error {
		key := r.keyStr.String(0, msg)
		_ = pipe.RPush(key, p.Get())
		return nil
	})
	cmders, err := pipe.Exec()
	if err != nil {
		_ = r.disconnect()
		r.log.Errorf("Error from redis: %v\n", err)
		return component.ErrNotConnected
	}

	var batchErr *ibatch.Error
	for i, res := range cmders {
		if res.Err() != nil {
			if batchErr == nil {
				batchErr = ibatch.NewError(msg, res.Err())
			}
			batchErr.Failed(i, res.Err())
		}
	}
	if batchErr != nil {
		return batchErr
	}
	return nil
}

// Write attempts to write a message by pushing it to the end of a Redis list.
func (r *RedisList) Write(msg *message.Batch) error {
	return r.WriteWithContext(context.Background(), msg)
}

// disconnect safely closes a connection to an RedisList server.
func (r *RedisList) disconnect() error {
	r.connMut.Lock()
	defer r.connMut.Unlock()
	if r.client != nil {
		err := r.client.Close()
		r.client = nil
		return err
	}
	return nil
}

// CloseAsync shuts down the RedisList output and stops processing messages.
func (r *RedisList) CloseAsync() {
	go func() {
		_ = r.disconnect()
	}()
}

// WaitForClose blocks until the RedisList output has closed down.
func (r *RedisList) WaitForClose(timeout time.Duration) error {
	return nil
}

//------------------------------------------------------------------------------


text:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.finsky.layout.play.FinskyViewPager android:id="@id/highlights_view_pager" android:layout_width="fill_parent" android:layout_height="0.0dip"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
import sublime
import sublime_plugin
import re

class PaginateExceptionCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		docRegion = sublime.Region(0, self.view.size())

		docText = self.view.substr(docRegion)

		docText = re.sub("\s+at ", "\nat ", docText)
		docText = re.sub("\n\n", "\n", docText)

		self.view.replace(edit, docRegion, docText)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>tn.zelda.projects.java8</groupId>
  <artifactId>java8-samples</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <description>java-8</description>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


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

  <title>Description of fig4_2</title>
  <meta name="keywords" content="fig4_2">
  <meta name="description" content="Local Regression and Likelihood, Figure 4.2.">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../m2html.css">

fig4_2

PURPOSE

Local Regression and Likelihood, Figure 4.2.

SYNOPSIS

This is a script file.

DESCRIPTION

 Local Regression and Likelihood, Figure 4.2.
 Author: Catherine Loader

 Local Likelihood (Logistic Regression), for the
 Henderson-Shepherd Mortality Data.

CROSS-REFERENCE INFORMATION

This function calls:

lfband	adds confidence bands around the plot of a locfit() fit.

lfplot	Plot (for one or two dimensions) a locfit() fit.

locfit	Smoothing noisy data using Local Regression and Likelihood.

This function is called by:

runbook

SOURCE CODE

0001 % Local Regression and Likelihood, Figure 4.2.
0002 % Author: Catherine Loader
0003 %
0004 % Local Likelihood (Logistic Regression), for the
0005 % Henderson-Shepherd Mortality Data.
0006
0007 load morths;
0008 fit = locfit(age,deaths,'weights',n,'family','binomial','alpha',0.5);
0009 figure('Name','fig4_2: Logistic Regression for the Henderson-Shepherd Mortality Data.');
0010 lfplot(fit);
0011 lfband(fit);

<address>Generated on Fri 12-Aug-2011 11:36:15 by m2html © 2005</address>


text:
require 'borrow_direct'
BorrowDirect::Defaults.api_base = ENV['EZBORROW_API_BASE']
BorrowDirect::Defaults.partnership_id = ENV['EZBORROW_PARTNERSHIP_ID']
BorrowDirect::Defaults.timeout = 60
# Override default production api base because engine config makes the above
# not work in a production environment
class BorrowDirect::Defaults
  PRODUCTION_API_BASE = ENV['EZBORROW_API_BASE']
end


text:
layout: post
status: publish
published: true
title: PowerShell and Null Values
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 94
wordpress_url: http://winterdom.com/2009/03/powershellandnullvalues
date: '2009-03-06 04:48:28 +0000'
date_gmt: '2009-03-06 04:48:28 +0000'
categories:
- PowerShell
tags: []
comments:
- id: 738
  author: Bruce Payette [msft]
  author_email: brucepay@microsoft.com
  author_url: ''
  date: '2009-05-02 00:33:03 +0000'
  date_gmt: '2009-05-02 00:33:03 +0000'
  content: "As an interactive shell, having PowerShell not error out on missing properties
    was pretty important.  However, when scripting, missing propertues can be a real
    source of bugs. This is why we added 'Set-PSDebug -strict' (V1, V2) or 'Set-StrictMode
    -version 2' (v2 only) to allow you to catch these errors.  Since there were no
    useful scenarios for method calls on null even in interactive cases, we never
    allowed it. \r\n\r\nThanks,\r\n-bruce"
- id: 739
  author: tomasr
  author_email: tomas@winterdom.com
  author_url: http://winterdom.com/
  date: '2009-05-02 01:30:22 +0000'
  date_gmt: '2009-05-02 01:30:22 +0000'
  content: "Thanks for the comment, Bruce. I agree with the general theme, but I'm
    not sure I completely agree that propagating the null value that way is always
    useful. It's hard to balance making the tool easier less in-your-face about errors,
    but also avoid pitfalls like this one.\r\n\r\nI'll be sure to check out set-strictmode
    in v2!"
- id: 2301
  author: Computer Eyes
  author_email: computereyes@live.com
  author_url: ''
  date: '2012-04-09 15:28:06 +0000'
  date_gmt: '2012-04-09 15:28:06 +0000'
  content: "Unable to process this code - Need help. Error is at the bottom of this
    code.\r\n\r\n[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SharePoint\")
    \r\n\r\n$site    =     new-object Microsoft.SharePoint.SPSite(\"http://sharepoint.mynetwork.com\")
    \   \r\n$relweburl = \"/regions/north/4v/apps/sods\"\r\n$web
    = $site.openweb($relweburl)\r\n\r\n$list    =    $web.Lists[\"SODSProcess\"]                                                              \r\nfor
    ($x=1;$x -le 500; $x++) \r\n{ \r\n  $deaditem= $list.GetItemById($x)\r\n  Write-Host(\"DELETED:
    \" + $list[$x].name)\r\n  $deaditem.Delete()\r\n}\r\n$web.Dispose()\r\n$site.Dispose()
    \r\n\r\nYou cannot call a method on a null-valued expression.\r\nline:11 char:34\r\n+
    \  Write-Host(\"DELETED: \" + $list[ <<<< $x].name)\r\n    + CategoryInfo          :
    InvalidOperation: (1:Int32) [], RuntimeException\r\n    + FullyQualifiedErrorId
    : NullArray\r\n\r\nand\r\n\r\ncannot index into a null array\r\nline:12 char:19\r\n\r\n+
    \  $deaditem.Delete <<<< ()\r\n    + CategoryInfo          : InvalidOperation:
    (Delete:String) [], RuntimeExcept \r\n   ion\r\n    + FullyQualifiedErrorId :
    InvokeMethodOnNull"
- id: 358335
  author: James
  author_email: starascendant@hotmail.com
  author_url: ''
  date: '2014-12-11 18:09:32 +0000'
  date_gmt: '2014-12-11 18:09:32 +0000'
  content: Here's some more null handling chaos in PowerShell. Null strings passed
    in to a commandlet or function don't stay null. See the Microsoft Connect bug
    at https://connect.microsoft.com/PowerShell/feedback/details/861093/nullstring-value-is-not-preserved-when-passed-to-functions.
---

I love Windows PowerShell, I really do. However, some of its language features drive me crazy sometimes. One of those is propagation of null values on expressions involving the ‘.’ operator for property access.

Basically the problem is this: Suppose you have a variable $x, and you reference a property on it. In languages like C#, if the $x holds a null value, you’d expect an error. In PowerShell, instead, the null value of $x propagates through as many chained property access expressions are there so that the end return of said expression is also a null value.

Let me explain with an example:

$xp = $null
$val = $xp.Site.Lists.Count
$val -eq $null
>> True

As you can see, referencing $xp.Site.Lists.Count above results in, well, nothing: You get a null value.

Given the nature of PowerShell and much of its intended audience, this behavior sort of make sense. My problem with it is that it can lead to subtle problems that will some times annoy me to no end; for example if you’ve got a complex expression involving several chained property accesses, it’s hard to know which of those returned the original null value that got propagated. It’s annoying to debug, at least.

It can also lead to more subtle behaviors. For example, if your expression was meant to return an enumerable object (such as an array or collection) and you were using that as input to a pipeline, you’ll get an unexpected behavior: The pipeline will execute with a single $null input value:

$xp.Site.Lists | %{
   "Holy Moses, `$</span><span class="String">_ is </span><span class="SpecialChar">`$null? $($_ -eq $null)"
}
>> Holy Moses, $_ is $null? True

This was a bit unexpected to me the first time it happened, though it sort of makes sense in sick sort of way :-).

An interesting asymmetry, however, is that the null value propagation stops if there’s a method call in there:

$xp.Site.Lists.Call()
>> You cannot call a method on a null-valued expression.
>> At line:1 char:20
>> + $xp.Site.Lists.Call( <<<< )


text:
/*
Package transit_realtime is a simple library for handling GTFS-realtime feeds.

GTFS-realtime is a feed specification that allows public transportation
agencies to provide realtime updates about their fleet to application
developers. It is an extension to GTFS (General Transit Feed Specification), an
open data format for public transportation schedules and associated geographic
information. GTFS-realtime was designed around ease of implementation, good
GTFS interoperability and a focus on passenger information.

     https://developers.google.com/transit/gtfs-realtime/

The GTFS-realtime data is encoded using protocol buffers, so this library contains
the generated Go class to be able to encode/decode this data.
*/
package transit_realtime


text:
package io.quarkus.undertow.deployment;

import io.quarkus.builder.item.MultiBuildItem;
import io.undertow.servlet.ServletExtension;

public final class ServletExtensionBuildItem extends MultiBuildItem {

    private final ServletExtension value;

    public ServletExtensionBuildItem(ServletExtension value) {
        this.value = value;
    }

    public ServletExtension getValue() {
        return value;
    }
}


text:
package org.apache.nifi.remote.protocol;

import java.io.IOException;

import org.apache.nifi.cluster.NodeInformant;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.remote.Peer;
import org.apache.nifi.remote.RootGroupPort;
import org.apache.nifi.remote.VersionedRemoteResource;
import org.apache.nifi.remote.codec.FlowFileCodec;
import org.apache.nifi.remote.exception.BadRequestException;
import org.apache.nifi.remote.exception.HandshakeException;
import org.apache.nifi.remote.exception.ProtocolException;

public interface ServerProtocol extends VersionedRemoteResource {

    /**
     *
     * @param rootGroup
     */
    void setRootProcessGroup(ProcessGroup rootGroup);

    RootGroupPort getPort();

    /**
     * Optional operation. Sets the NodeInformant to use in this Protocol, if a
     * NodeInformant is supported. Otherwise, throws
     * UnsupportedOperationException
     *
     * @param nodeInformant
     */
    void setNodeInformant(NodeInformant nodeInformant);

    /**
     * Receives the handshake from the Peer
     *
     * @param peer
     * @throws IOException
     * @throws HandshakeException
     */
    void handshake(Peer peer) throws IOException, HandshakeException;

    /**
     * Returns true if the handshaking process was completed
     * successfully, false if either the handshaking process has
     * not happened or the handshake failed
     *
     * @return
     */
    boolean isHandshakeSuccessful();

    /**
     * Negotiates the FlowFileCodec that is to be used for transferring
     * FlowFiles
     *
     * @param peer
     * @return
     * @throws IOException
     * @throws BadRequestException
     */
    FlowFileCodec negotiateCodec(Peer peer) throws IOException, ProtocolException;

    /**
     * Returns the codec that has already been negotiated by this Protocol, if
     * any.
     *
     * @return
     */
    FlowFileCodec getPreNegotiatedCodec();

    /**
     * Reads the Request Type of the next request from the Peer
     *
     * @return the RequestType that the peer would like to happen - or null, if
     * no data available
     */
    RequestType getRequestType(Peer peer) throws IOException;

    /**
     * Sends FlowFiles to the specified peer
     *
     * @param peer
     * @param context
     * @param session
     * @param codec
     *
     * @return the number of FlowFiles transferred
     */
    int transferFlowFiles(Peer peer, ProcessContext context, ProcessSession session, FlowFileCodec codec) throws IOException, ProtocolException;

    /**
     * Receives FlowFiles from the specified peer
     *
     * @param peer
     * @param context
     * @param session
     * @param codec
     * @throws IOException
     *
     * @return the number of FlowFiles received
     * @throws ProtocolException
     */
    int receiveFlowFiles(Peer peer, ProcessContext context, ProcessSession session, FlowFileCodec codec) throws IOException, ProtocolException;

    /**
     * Returns the number of milliseconds after a request is received for which
     * the request is still valid. A valid of 0 indicates that the request will
     * not expire.
     *
     * @return
     */
    long getRequestExpiration();

    /**
     * Sends a list of all nodes in the cluster to the specified peer. If not in
     * a cluster, sends info about itself
     *
     * @param peer
     */
    void sendPeerList(Peer peer) throws IOException;

    void shutdown(Peer peer);

    boolean isShutdown();
}


text:
Originally published: 2013-11-27 13:56:37
Last updated: 2013-11-27 13:56:38
Author: Anonimista

Basic Gtk.TreeView Example with two sortable columns


text:
layout:     post
title:      in sight
date:       2016-04-07 09:07:04
summary:
categories: drawing
---
![in sight](/images/diary/in-sight.png "I'd rather die.")


text:
package cn.jpush.im.android.demo.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {

	private List<Fragment> mFragmList;

	public ViewPagerAdapter(FragmentManager fm) {
		super(fm);
		// TODO Auto-generated constructor stub
	}

	public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
		super(fm);
		this.mFragmList = fragments;
	}

	@Override
	public Fragment getItem(int index) {
		// TODO Auto-generated method stub
		return mFragmList.get(index);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mFragmList.size();
	}

}


text:
module Sunspot
  class NullResult
    class Group < Struct.new(:value, :collection)

      def solr_docs
        collection.map { |item| "#{item.class.to_s} #{item.id}" }
      end

      def hits
        collection.map { |item| Hit.new item.id }
      end

    end
  end
end


text:
#pragma once

#include <ace/filesystem/Path.h>
#include <string>
#include <sys/stat.h>

namespace ace {
namespace fs {

class Node {
 public:

  enum class Type {
    Block     = S_IFBLK,
    Character = S_IFCHR,
    Directory = S_IFDIR,
    FIFO      = S_IFIFO,
    Regular   = S_IFREG,
    Link      = S_IFLNK,
    Socket    = S_IFSOCK,
    Unknown   = 0
  };

  typedef enum _Permission {
    SetUID      = S_ISUID,
    SetGID      = S_ISGID,
    Sticky      = S_ISVTX,
    UserRead    = S_IRUSR,
    UserWrite   = S_IWUSR,
    UserExec    = S_IXUSR,
    GroupRead   = S_IRGRP,
    GroupWrite  = S_IWGRP,
    GroupExec   = S_IXGRP,
    OtherRead   = S_IROTH,
    OtherWrite  = S_IWOTH,
    OtherExec   = S_IXOTH,
    None        = 0
  } Permission;

  Node();
  Node(Node const & o); // NOLINT(runtime/explicit)
  virtual ~Node();

  virtual bool isValid() const;
  fs::Path const & path() const;

  Type type() const;
  static Type type(fs::Path const & p, const bool follow = true);

  Permission permissions() const;
  static Permission permissions(fs::Path const & p, const bool follow = true);

  static Type parseType(std::string const & s);
  static std::string toString(const Type t);

  uid_t userID() const;
  static uid_t userID(fs::Path const & p, const bool follow = true);

  gid_t groupID() const;
  static gid_t groupID(fs::Path const & p, const bool follow = true);

  bool readable() const;
  static bool readable(fs::Path const & p, const bool follow = true);

  bool writeable() const;
  static bool writeable(fs::Path const & p, const bool follow = true);

  Node parent() const;

  Node & operator=(Node const & o);

 protected:

  static Type type(mode_t mode);
  static Permission permissions(mode_t mode);

  int           m_fd;
  fs::Path  m_path;
};

std::ostream &
operator<<(std::ostream & o, Node::Type const & t);

} // namespace ace
} // namespace fs


text:
class VideoHasSubCategory < ApplicationRecord
  belongs_to :video
  belongs_to :sub_category
end


text:
import store from 'infra/service/store';
import action from 'infra/service/action';
import graph from 'infra/service/graph';
import loc from 'infra/service/location';

const userRepo = {

  login() {
    let login;
    let profile;
    return graph.login()
      .then(res => (login = res))
      .then(() => graph.getUser())
      .then(res => (profile = res))
      .then(() => {
        store.dispatch(action.userSet({ profile, login, loggedIn: true }))
        loc.push('/')
      });
  },

  logout() {
    const profile = {
      facebookId: '',
      name: '',
      email: '',
    };
    return graph.logout()
      .then(() => {
        store.dispatch(action.userSet({ profile, login: {}, loggedIn: false }));
        loc.push('/login')
      });

  },

  checkLoginStatus() {
    store.dispatch(action.userSet({ loading: true }));
    let login;
    let profile;
    const emptyProfile = {
      facebookId: '',
      name: '',
      email: '',
    };
    return graph.getLoginStatus()
      .then(res => (login = res))
      .then(() => graph.getUser())
      .then(res => (profile = res))
      .then(() => {
        if (profile.facebookId) window.ga('set', 'userId', profile.facebookId);
        store.dispatch(action.userSet({ profile, login, loggedIn: true, loading: false }));
      })
      .catch(err => store.dispatch(action.userSet({ profile: emptyProfile, login: {}, loggedIn: false, loading: false })));
  },

};

export default userRepo;


text:
id: 1353
title: Map of disabled population in Nepal per district
date: 2016-07-23T14:38:07-04:00
author: codefornepal
layout: revision
guid: https://codefornepal.org/2016/07/1351-revision-v1/
permalink: /2016/07/1351-revision-v1/
---

_Photo Credit: Idex World_

In 2011, two percent (1.94%; 513,321) of the total population of Nepal reported to have “some kind of disability,” according to Nepal Census.

Disability: About two percent (1.94%; 513,321) of the total population reported to have
some kind of disability. Physical disability constitutes 36.3 percent of the population with
disability followed by Blindness/Low Vision (18.5%), Deaf/Hard to hearing (15.4%), Speech
problem (11.5%), Multiple Disability (7.5%), Mental Disability (6%), Intellectual Disability
(2.9%) and Deaf-Blind (1.8%).


text:
<?xml version="1.0" encoding="iso-8859-1"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

<title>mylib 1.0: Distance Transform Module Reference</title>
<link href="mydoc.css" rel="stylesheet" type="text/css" />

     Home ·
     Pages ·
     Index ·
     Overviews

Distance Transform Module Reference

Distance transforms and Voronoi, Delauney and geodesic partitioning based there upon.
More...

 #include <filters.h>

Routines

Float_Array *

       Squared_DistanceG
     (APart *image)

Float_Array *

       Manhattan_DistanceG
     (APart *image)

Float_Array *

       Binary_Euclidean_DistanceG
     (APart *image, int boundary)

Label_Array *

       Voronoi_LabelingG
     (int nseed, Indx_Type *seeds, Coordinate *shape F)

Partition *

       Delauney_PartitionG
     (int nseed, Indx_Type *seeds, Coordinate *shape F)

Label_Array *

       Geodesic_LabelingG
     (APart *image, boolean iscon2n, int *nregions O)

Partition *

       Geodesic_PartitionG
     (APart *image I, boolean iscon2n)

Detailed Description

The distance transform in its most common form is used to compute the distance of
every foreground pixel from the nearest background pixel in a binary image
(Binary_Euclidean_Distance).  More generally, given a grey scale image, the transfrom
computes:

     D[p] = minq ( I[q] + d(p,q) )

where D[p] is the distance transform of pixel p, I[q] is the value
of the image at pixel q, and d(p,q) is a measure of distance between the coordinates
of pixels p and q.  Using the linear time algorithm of Fezenszwalb and Hutenlocher
(Cornell Computing and Information Science Technical Report TR2004-1963, 2004) this
module provides functions for the squared Euclidean distance (Squared_Distance) and
Manhattan distance (Manhattan_Distance).

The Voronoi diagram and its dual Delauney triangulation are constructs that can be derived
from a set of N real-valued points in O(NlogN) time.  However, one can also, less
efficiently compute these with respect to a set of N pixels using the distance transform
in time proportional to the size of the array involved where in this form the Voroni
diagram is returned by Voronoi_Labeling as a label array that indicates which point
is closes to any given pixel, and the Delauney triangulation is returned by
Delauney_Partition as a Partition that models the underlying partition of
the Voronoi diagram.

Finally, given a collection of connected foreground objects, Geodesic_Labeling uses
the distance transform to determine a labeling that gives the foreground object each pixel
is closest to, and Geodesic_Partition returns a Partition that models the resulting
partition.

Routine Documentation

Float_Array *
     Squared_DistanceG (APart *image)

Generates a FLOAT32_TYPE array with the same shape as array or slice image, that contains the
distance transform of image with respect to the squared Euclidean metric.
That is, if D[p] is the
value of pixel p in the result, and I[q] is the value of image at a pixel
q, then:

     D[p] = minq ( I[q] + d(p,q) )

where the minimum is conceptually over all pixels q in image, and d(p,q) is
the square of the Euclidean distance between pixels p and q.  That is, if the coordinates
for p and q are
(x1, x2, ... xn)
and
(y1, y2, ... yn), respectively,
then:

     d(p,q) = Σi ( xi - yi )2

The routine take O(vn) time where v is the size of image and n is its dimensionality.

Float_Array *
     Manhattan_DistanceG (APart *image)

Generates a FLOAT32_TYPE array with the same shape as array or slice image, that contains the
distance transform of image with respect to the Manhattan metric.
That is, if D[p] is the
value of pixel p in the result, and I[q] is the value of image at a pixel
q, then:

     D[p] = minq ( I[q] + d(p,q) )

where the minimum is conceptually over all pixels q in image, and d(p,q) is
the Manhattan distance between pixels p and q.  That is, if the coordinates
for p and q are
(x1, x2, ... xn)
and
(y1, y2, ... yn), respectively,
then:

     d(p,q) = Σi | xi - yi |

The routine take O(vn) time where v is the size of image and n is its dimensionality.

Float_Array *
     Binary_Euclidean_DistanceG (APart *image, int boundary)

Generates a FLOAT32_TYPE array with the same shape as array or slice image, that contains the
Euclidean distance transform of the binarization of image where
non-zero pixels are considered foreground and zero pixels are considered background.
That is, if D[p] is the
value of pixel p in the result, and B is the set of all pixels in image that
are background (zero) then:

     D[p] = minq ∈ B d(p,q)

where d(p,q) is
the Euclidean distance between pixels p and q.  That is, if the coordinates
for p is
(x1, x2, ... xn)
and the coordinate for q is
(y1, y2, ... yn),
then:

     d(p,q) = ( Σi ( xi - yi )2 ).5

The routine take O(vn) time where v is the size of image and n is its dimensionality.

Label_Array *
     Voronoi_LabelingG (int nseed, Indx_Type *seeds, Coordinate *shape F)

Creates an UINT32_TYPE array L of shape shape for which L[p] = i if and only if
d(p,seeds[i-1] is minimal
over all possible choices of i ∈ [1,nseed], where d is Euclidean distance.
That is, L is a label field that for every pixel indicates which Voronoi region the pixel
is in, where the Voronoi diagram is that induced by the nseed points given by
seeds[0..nseed-1] with respect to the lattice of shape.

Partition *
     Delauney_PartitionG (int nseed, Indx_Type *seeds, Coordinate *shape F)

Returns a Partition graph that models the
Delauney decomposition of the collection of points seeds[0..nseed-1] with respect to the
lattice shape.  This decomposition is effectively the partition graph of the Voronoi decomposition
(see Voronoi_Labeling) of said points.  The depth of each region in this partition
is always 0, and the height of
each edge between Voronoi regions is the distance between their foci.

Label_Array *
     Geodesic_LabelingG (APart *image, boolean iscon2n, int *nregions O)

Creates an UINT32_TYPE array L with the same shape as array or slice image that gives
the labeling of pixels in the geodesic decomposition of image when it is interpreted as a binary
foreground/background image, where non-zero pixels are considered foreground and zero
pixels are considered background.  Every iscon2n-connected set of foreground pixels is
assigned an integer index from 1 to *nregion, and there after L[p] for each index
p is set to the index of the foreground region that is closest to it.

Partition *
     Geodesic_PartitionG (APart *image I, boolean iscon2n)

Returns a Partition graph that models the partitioning of image described in
Geodesic_Labeling immediately above.  The depth of each region in this partition is
always 0, and the height of an edge is the distance between the two
foreground objects of the regions.


text:
package org.squiddev.cctweaks.api.network;

import javax.annotation.Nonnull;

/**
 * A packet sent along a wired network
 *
 * Previously dan200.computercraft.shared.peripheral.modem.TileCable.Packet
 */
public final class Packet {
	/**
	 * The channel the packet is sent to
	 */
	public final int channel;

	/**
	 * The channel to reply to
	 */
	public final int replyChannel;

	/**
	 * Content of the packet
	 */
	@Nonnull
	public final Object payload;

	/**
	 * The sender of the packet
	 */
	@Nonnull
	public final Object senderObject;

	/**
	 * Construct a new packet
	 *
	 * @param channel      The channel the packet is sent to
	 * @param replyChannel The channel to reply to
	 * @param payload      Content of the packet
	 * @param senderObject The sender of the packet
	 */
	public Packet(int channel, int replyChannel, @Nonnull Object payload, @Nonnull Object senderObject) {
		this.channel = channel;
		this.replyChannel = replyChannel;
		this.payload = payload;
		this.senderObject = senderObject;
	}
}


text:
package domain;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

public class PancakeHouseMenu implements Menu
{
	private List<MenuItem> menuItems;

	public PancakeHouseMenu()
	{
		menuItems = new ArrayList<>();

		addItem("K&B's Pancake breakfast", "Pancake with scrambled eggs, and toast", true, 2.99);
		addItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99);
		addItem("BlueBerry Pancakes", "Pancakes made with fresh blueberries", true, 3.49);
		addItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59);
	}

	private void addItem(String name, String description, boolean vegetarian, double price)
	{
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		menuItems.add(menuItem);
	}

	public Iterator<MenuItem> createIterator()
	{
		return menuItems.iterator();
	}

}


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.collide.dto;

import com.google.collide.dtogen.shared.CompactJsonDto;
import com.google.collide.dtogen.shared.RoutingType;
import com.google.collide.dtogen.shared.SerializationIndex;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.shared.JsonArray;

/**
 * An interface representing a continuous namespace in the source code. It may
 * be a function, a class, an object or just anonymous namespace.
 *
 * Code blocks have start offset relative to the file start, length,
 * type and optional name.
 *
 * This interface is based on CodeBlock proto from Code Search
 */
@RoutingType(type = RoutingTypes.CODEBLOCK)
public interface CodeBlock extends ServerToClientDto, CompactJsonDto {
  /**
   * Enumeration of currently supported code block types.
   */
  public static enum Type {

    UNDEFINED(0),
    FUNCTION(1),
    FIELD(2),
    FILE(3),
    CLASS(4),
    UNRESOLVED_REFERENCE(5),
    PACKAGE(6);

    public static final int VALUE_UNDEFINED = 0;
    public static final int VALUE_FUNCTION = 1;
    public static final int VALUE_FIELD = 2;
    public static final int VALUE_FILE = 3;
    public static final int VALUE_CLASS = 4;
    public static final int VALUE_UNRESOLVED_REFERENCE = 5;
    public static final int VALUE_PACKAGE = 6;

    public final int value;

    public static Type valueOf(int value) {
      switch (value) {
        case VALUE_UNDEFINED: return UNDEFINED;
        case VALUE_FUNCTION: return FUNCTION;
        case VALUE_FIELD: return FIELD;
        case VALUE_FILE: return FILE;
        case VALUE_CLASS: return CLASS;
        case VALUE_UNRESOLVED_REFERENCE: return UNRESOLVED_REFERENCE;
        case VALUE_PACKAGE: return PACKAGE;
      }
      throw new IllegalStateException("Unknown type value: " + value);
    }

    Type(int serializedValue) {
      this.value = serializedValue;
    }
  }

  /**
   * The semantics of ID is different depending on code block type.
   * For FILE code blocks it is a workspace-unique long, for other code blocks
   * it is a file-unique int. Full ID will involve both components.
   *
   * @return id
   */
  @SerializationIndex(1)
  String getId();

  /**
   * @return the type of this code block
   */
  @SerializationIndex(2)
  int getBlockType();

  /**
   * @return the end column of this code block relative to the first column on the line
   */
  @SerializationIndex(3)
  int getEndColumn();

  /**
   * @return the end line number of this code block relative to the file start
   */
  @SerializationIndex(4)
  int getEndLineNumber();

  /**
   * @return the name of this code block or {@code null} if the code block
   *         is anonymous
   */
  @SerializationIndex(5)
  String getName();

  /**
   * @return the start column of this code block relative to the first column on the line
   */
  @SerializationIndex(6)
  int getStartColumn();

  /**
   * @return the start line number of this code block relative to the file start
   */
  @SerializationIndex(7)
  int getStartLineNumber();

  /**
   * @return the list of the nested code blocks
   */
  @SerializationIndex(8)
  JsonArray<CodeBlock> getChildren();
}


text:
package org.perfcake.reporting.reporter;

import org.perfcake.PerfCakeConst;
import org.perfcake.RunInfo;
import org.perfcake.TestSetup;
import org.perfcake.common.Period;
import org.perfcake.common.PeriodType;
import org.perfcake.reporting.Measurement;
import org.perfcake.reporting.MeasurementUnit;
import org.perfcake.reporting.Quantity;
import org.perfcake.reporting.ReportManager;
import org.perfcake.reporting.ReportManagerRetractor;
import org.perfcake.reporting.ReportingException;
import org.perfcake.reporting.destination.DummyDestination;
import org.perfcake.util.ObjectFactory;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Tests all {@link org.perfcake.reporting.reporter.StatsReporter} implemetations.
 *
 * @author Pavel Macík
 */
@Test(groups = { "unit" })
public class StatsReporterTest extends TestSetup {

   private static final long ITERATION_COUNT = 10L;

   private static final List<Throwable> throwablesFromThreads = new LinkedList<>();

   @Test
   public void testDefaults() throws InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException {
      final ThroughputStatsReporter tsr = (ThroughputStatsReporter) ObjectFactory.summonInstance(ThroughputStatsReporter.class.getName(), new Properties());
      Assert.assertTrue(tsr.isAverageEnabled());
      Assert.assertTrue(tsr.isMinimumEnabled());
      Assert.assertTrue(tsr.isMaximumEnabled());
      Assert.assertNull(tsr.getAccumulatedResult(StatsReporter.AVERAGE));
      Assert.assertNull(tsr.getAccumulatedResult(StatsReporter.MINIMUM));
      Assert.assertNull(tsr.getAccumulatedResult(StatsReporter.MAXIMUM));
      Assert.assertNull(tsr.getAccumulatedResult(Measurement.DEFAULT_RESULT));
      Assert.assertNull(tsr.getAccumulatedResult(PerfCakeConst.REQUEST_SIZE_TAG));
      Assert.assertNull(tsr.getAccumulatedResult(PerfCakeConst.RESPONSE_SIZE_TAG));

      final ResponseTimeStatsReporter rtsr = (ResponseTimeStatsReporter) ObjectFactory.summonInstance(ResponseTimeStatsReporter.class.getName(), new Properties());
      Assert.assertTrue(rtsr.isAverageEnabled());
      Assert.assertTrue(rtsr.isMinimumEnabled());
      Assert.assertTrue(rtsr.isMaximumEnabled());
      Assert.assertNull(rtsr.getAccumulatedResult(StatsReporter.AVERAGE));
      Assert.assertNull(rtsr.getAccumulatedResult(StatsReporter.MINIMUM));
      Assert.assertNull(rtsr.getAccumulatedResult(StatsReporter.MAXIMUM));
      Assert.assertNull(rtsr.getAccumulatedResult(Measurement.DEFAULT_RESULT));
      Assert.assertNull(rtsr.getAccumulatedResult(PerfCakeConst.REQUEST_SIZE_TAG));
      Assert.assertNull(rtsr.getAccumulatedResult(PerfCakeConst.RESPONSE_SIZE_TAG));
   }

   @DataProvider(name = "reporterProperties")
   public Object[][] createDataForReporters() {
      final int rep = 2;
      final int comb = 8;

      final Object[][] retVal = new Object[comb * rep][];

      final StatsReporter[] reps = new StatsReporter[] { new ThroughputStatsReporter(), new ResponseTimeStatsReporter() };

      int c = 0;
      for (int i = 0; i < rep; i++) {
         // reporter, averageEnabled, minimumEnabled, maximumEnabled
         retVal[c++] = new Object[] { reps[i], true, true, true };
         retVal[c++] = new Object[] { reps[i], true, true, false };
         retVal[c++] = new Object[] { reps[i], true, false, true };
         retVal[c++] = new Object[] { reps[i], true, false, false };
         retVal[c++] = new Object[] { reps[i], false, true, true };
         retVal[c++] = new Object[] { reps[i], false, true, false };
         retVal[c++] = new Object[] { reps[i], false, false, true };
         retVal[c++] = new Object[] { reps[i], false, false, false };
      }
      return retVal;
   }

   @Test(dataProvider = "reporterProperties")
   public void testReporters(final StatsReporter reporter, final boolean averageEnabled, final boolean minimumEnabled, final boolean maximumEnabled) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, InterruptedException {
      final String reporterName = reporter.getClass().getName();

      final Properties reporterProperties = new Properties();
      reporterProperties.put("averageEnabled", String.valueOf(averageEnabled));
      reporterProperties.put("minimumEnabled", String.valueOf(minimumEnabled));
      reporterProperties.put("maximumEnabled", String.valueOf(maximumEnabled));

      final ThroughputStatsReporter tsr = (ThroughputStatsReporter) ObjectFactory.summonInstance(ThroughputStatsReporter.class.getName(), reporterProperties);

      final ReportManager rm = new ReportManager();
      final DummyDestination dest = (DummyDestination) ObjectFactory.summonInstance(DummyDestination.class.getName(), new Properties());
      tsr.registerDestination(dest, new Period(PeriodType.ITERATION, 1));
      rm.registerReporter(tsr);
      final RunInfo ri = new RunInfo(new Period(PeriodType.ITERATION, ITERATION_COUNT));
      rm.setRunInfo(ri);
      rm.start();
      Measurement lastMeasurement = null;
      dest.resetObservedMeasurements();
      dest.setObserving(true);

      try {
         for (int i = 0; i < ITERATION_COUNT; i++) {
            final MeasurementUnit mu = rm.newMeasurementUnit();
            mu.startMeasure();
            Thread.sleep(1);
            mu.stopMeasure();
            rm.report(mu);
         }
      } catch (InterruptedException | ReportingException e) {
         e.printStackTrace();
         Assert.fail(reporterName + ": Exception should not be thrown.", e);
      }
      rm.stop();

      List<Measurement> measurementList = dest.getObservedMeasurements();
      int tries = 0;
      while (measurementList.size() < ITERATION_COUNT && tries++ < 10) {
         Thread.sleep(100);
         dest.getObservedMeasurements().forEach(item -> {
            if (!measurementList.contains(item)) {
               measurementList.add(item);
            }
         });
      }
      dest.setObserving(false);

      final int mls = measurementList.size();
      Assert.assertEquals(mls, ITERATION_COUNT, reporterName + ": Number of Measurement sent to destination");

      for (final Measurement m : measurementList) {
         if (averageEnabled) {
            Assert.assertNotNull(m.get(StatsReporter.AVERAGE), reporterName + ": Not null average result");
         } else {
            Assert.assertNull(m.get(StatsReporter.AVERAGE), reporterName + ": Null average result");
         }

         if (minimumEnabled) {
            Assert.assertNotNull(m.get(StatsReporter.MINIMUM), reporterName + ": Not null minimum result");
         } else {
            Assert.assertNull(m.get(StatsReporter.MINIMUM), reporterName + ": Null minimum result");
         }

         if (maximumEnabled) {
            Assert.assertNotNull(m.get(StatsReporter.MAXIMUM), reporterName + ": Not null maximum result");
         } else {
            Assert.assertNull(m.get(StatsReporter.MAXIMUM), reporterName + ": Null maximum result");
         }
      }
   }

   @Test
   @SuppressWarnings("unchecked")
   public void testHistogramReporting() throws ReportingException, InterruptedException {
      final ReportManager man = new ReportManager();
      man.setRunInfo(new RunInfo(new Period(PeriodType.ITERATION, 10)));

      final StatsReporter rep = new ResponseTimeStatsReporter();
      rep.setHistogram("0, 5, 20");
      rep.setHistogramPrefix("hist");
      man.registerReporter(rep);

      final DummyDestination dest = new DummyDestination();
      rep.registerDestination(dest, new Period(PeriodType.ITERATION, 1));

      man.start();

      for (int i = 0; i < 10; i++) {
         MeasurementUnit mu = man.newMeasurementUnit();
         mu.startMeasure();
         Thread.sleep(i);
         mu.stopMeasure();
         man.report(mu);
      }

      man.stop();

      Quantity<Double> firstInterval = (Quantity<Double>) dest.getLastMeasurement().get("hist<0.0:5.0)");
      Quantity<Double> secondInterval = (Quantity<Double>) dest.getLastMeasurement().get("hist<5.0:20.0)");

      Assert.assertEquals(firstInterval.getUnit(), "%");
      Assert.assertEquals(secondInterval.getUnit(), "%");

      Assert.assertTrue(firstInterval.getNumber() > 10.0);
      Assert.assertTrue(firstInterval.getNumber() < 90.0);

      Assert.assertTrue(secondInterval.getNumber() > 10.0);
      Assert.assertTrue(secondInterval.getNumber() < 90.0);

      Assert.assertTrue(firstInterval.getNumber() + secondInterval.getNumber() == 100.0);
   }

   @Test
   @SuppressWarnings("unchecked")
   public void testServiceTimeReporter() throws Exception {
      final Properties reporterProperties = new Properties();
      reporterProperties.put("averageEnabled", "true");
      reporterProperties.put("minimumEnabled", "true");
      reporterProperties.put("maximumEnabled", "true");

      final ServiceTimeStatsReporter stsr = (ServiceTimeStatsReporter) ObjectFactory.summonInstance(ServiceTimeStatsReporter.class.getName(), reporterProperties);

      final ReportManager rm = new ReportManager();
      final DummyDestination dest = (DummyDestination) ObjectFactory.summonInstance(DummyDestination.class.getName(), new Properties());
      stsr.registerDestination(dest, new Period(PeriodType.ITERATION, 1));
      rm.registerReporter(stsr);
      final RunInfo ri = new RunInfo(new Period(PeriodType.ITERATION, 10));
      rm.setRunInfo(ri);
      rm.start();

      final MeasurementUnit mus[] = new MeasurementUnit[10];

      for (int i = 0; i < 10; i++) {
         mus[i] = rm.newMeasurementUnit();
         Thread.sleep(1);
      }

      for (int i = 0; i < 10; i++) {
         mus[i].startMeasure();
         Thread.sleep(1);
         mus[i].stopMeasure();
         long tm = System.nanoTime();
      }

      for (int i = 0; i < 10; i++) {
         rm.report(mus[i]);
      }

      rm.stop();

      // it took us 10ms to enqueue all the tasks and another 10ms to run them
      // so we cannot get shorter than 10ms delay for minimum and maximum (we preserved the order of tasks)
      // E = enqueue, X = execute, . = 1ms delay
      // E0.E1.E2.E3.E4.E5.E6.E7.E8.E9.X0.X1.X2.X3.X4.X5.X6.X7.X8.X9
      Assert.assertTrue(((Quantity<Double>) dest.getLastMeasurement().get(StatsReporter.MINIMUM)).getNumber() > 10d);
      Assert.assertTrue(((Quantity<Double>) dest.getLastMeasurement().get(StatsReporter.MAXIMUM)).getNumber() > 10d);

      System.out.println(dest.getLastMeasurement());
   }

   @Test(groups = { "stress" })
   public void testTimeSlidingWindowThreadSafeness() throws Exception {

      final Properties reporterProperties = new Properties();
      reporterProperties.setProperty("windowType", "time");
      reporterProperties.setProperty("windowSize", "1000");

      final ResponseTimeStatsReporter rtsr = (ResponseTimeStatsReporter) ObjectFactory.summonInstance(ResponseTimeStatsReporter.class.getName(), reporterProperties);

      final ReportManager rm = new ReportManager();

      final DummyDestination dest = (DummyDestination) ObjectFactory.summonInstance(DummyDestination.class.getName(), new Properties());
      final long duration = 60000;

      rtsr.registerDestination(dest, new Period(PeriodType.TIME, 1000));
      rm.registerReporter(rtsr);
      final RunInfo ri = new RunInfo(new Period(PeriodType.TIME, duration));
      rm.setRunInfo(ri);
      rm.start();

      final ThreadPoolExecutor ex = (ThreadPoolExecutor) Executors.newFixedThreadPool(100);

      final ReportManagerRetractor rmr = new ReportManagerRetractor(rm);
      rmr.getPeriodicThread().setUncaughtExceptionHandler((t, e) -> {
         throwablesFromThreads.add(e);
      });

      final long start = System.nanoTime();
      while (throwablesFromThreads.size() == 0 && (System.nanoTime() - start) < duration * 1e6) {
         if (ex.getQueue().size() < 1000000) {
            ex.submit(new Worker(rm));
         }
      }
      ex.shutdown();

      if (throwablesFromThreads.size() > 0) {
         final StringWriter sw = new StringWriter();
         final PrintWriter pw = new PrintWriter(sw);
         throwablesFromThreads.forEach(t -> {
            t.printStackTrace(pw);
         });
         Assert.fail("Some of the threads threw an exception: " + sw.toString());
      }

      Assert.assertNotNull(dest.getLastMeasurement(), "Destination should have registered some measurements.");
   }

   private static class Worker implements Runnable {
      private ReportManager rm;

      public Worker(ReportManager rm) {
         this.rm = rm;
      }

      @Override
      public void run() {
         final MeasurementUnit mu = rm.newMeasurementUnit();

         try {
            Thread.sleep(1);
            mu.startMeasure();
            Thread.sleep(1);
            mu.stopMeasure();
            Thread.sleep(1);
            rm.report(mu);
         } catch (ReportingException | InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<link rel="stylesheet" href="../css/fsa-card/back.css">

Firefox

Student Ambassadors

www.mozilla.org


text:
""""Windows Registry plugin for the Microsoft Office MRU."""

from __future__ import unicode_literals

import re

from dfdatetime import filetime as dfdatetime_filetime
from dfdatetime import semantic_time as dfdatetime_semantic_time

from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers import winreg
from plaso.parsers.winreg_plugins import interface

class OfficeMRUWindowsRegistryEventData(events.EventData):
  """Microsoft Office MRU Windows Registry event data.

  Attributes:
    key_path (str): Windows Registry key path.
    value_string (str): MRU value.
  """
  DATA_TYPE = 'windows:registry:office_mru'

  def __init__(self):
    """Initializes event data."""
    super(OfficeMRUWindowsRegistryEventData, self).__init__(
        data_type=self.DATA_TYPE)
    self.key_path = None
    self.value_string = None

class OfficeMRUListWindowsRegistryEventData(events.EventData):
  """Microsoft Office MRU list Windows Registry event data.

  Attributes:
    entries (str): most recently used (MRU) entries.
    key_path (str): Windows Registry key path.
  """
  DATA_TYPE = 'windows:registry:office_mru_list'

  def __init__(self):
    """Initializes event data."""
    super(OfficeMRUListWindowsRegistryEventData, self).__init__(
        data_type=self.DATA_TYPE)
    self.entries = None
    self.key_path = None

class OfficeMRUPlugin(interface.WindowsRegistryPlugin):
  """Plugin that parses Microsoft Office MRU keys."""

  NAME = 'microsoft_office_mru'
  DATA_FORMAT = 'Microsoft Office MRU Registry data'

  FILTERS = frozenset([
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'Access\\File MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'Access\\Place MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'Excel\\File MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'Excel\\Place MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'PowerPoint\\File MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'PowerPoint\\Place MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'Word\\File MRU'),
      interface.WindowsRegistryKeyPathFilter(
          'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\'
          'Word\\Place MRU')])

  _RE_VALUE_NAME = re.compile(r'^Item [0-9]+$', re.I)

  # The Office 12 item MRU is formatted as:
  # [F00000000][T%FILETIME%]*\\%FILENAME%

  # The Office 14 item MRU is formatted as:
  # [F00000000][T%FILETIME%][O00000000]*%FILENAME%
  _RE_VALUE_DATA = re.compile(r'\[F00000000\]\[T([0-9A-Z]+)\].*\*[\\]?(.*)')

  def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
    """Extracts events from a Windows Registry key.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
    """
    # TODO: Test other Office versions to make sure this plugin is applicable.
    entries = []
    for registry_value in registry_key.GetValues():
      # Ignore any value not in the form: 'Item [0-9]+'.
      if not registry_value.name or not self._RE_VALUE_NAME.search(
          registry_value.name):
        continue

      # Ignore any value that is empty or that does not contain a string.
      if not registry_value.data or not registry_value.DataIsString():
        continue

      value_string = registry_value.GetDataAsObject()
      values = self._RE_VALUE_DATA.findall(value_string)

      # Values will contain a list containing a tuple containing 2 values.
      if len(values) != 1 or len(values[0]) != 2:
        continue

      try:
        timestamp = int(values[0][0], 16)
      except ValueError:
        parser_mediator.ProduceExtractionWarning((
            'unable to convert filetime string to an integer for '
            'value: {0:s}.').format(registry_value.name))
        continue

      event_data = OfficeMRUWindowsRegistryEventData()
      event_data.key_path = registry_key.path
      # TODO: split value string in individual values.
      event_data.value_string = value_string

      entries.append('{0:s}: {1:s}'.format(registry_value.name, value_string))

      if not timestamp:
        date_time = dfdatetime_semantic_time.NotSet()
      else:
        date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)

      # TODO: determine if this should be last written time.
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_WRITTEN)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    event_data = OfficeMRUListWindowsRegistryEventData()
    event_data.entries = ' '.join(entries) or None
    event_data.key_path = registry_key.path

    event = time_events.DateTimeValuesEvent(
        registry_key.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN)
    parser_mediator.ProduceEventWithEventData(event, event_data)

winreg.WinRegistryParser.RegisterPlugin(OfficeMRUPlugin)


text:
/* ----------------------------------------------------------------------
 * Project:      CMSIS DSP Library
 * Title:        arm_correlate_fast_q15.c
 * Description:  Fast Q15 Correlation
 *
 * $Date:        18. March 2019
 * $Revision:    V1.6.0
 *
 * Target Processor: Cortex-M cores
 * -------------------------------------------------------------------- */
/*
 * Copyright (C) 2010-2019 ARM Limited or its affiliates. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "arm_math.h"

/**
  @ingroup groupFilters
 */

/**
  @addtogroup Corr
  @{
 */

/**
  @brief         Correlation of Q15 sequences (fast version).
  @param[in]     pSrcA      points to the first input sequence
  @param[in]     srcALen    length of the first input sequence
  @param[in]     pSrcB      points to the second input sequence
  @param[in]     srcBLen    length of the second input sequence
  @param[out]    pDst       points to the location where the output result is written.  Length 2 * max(srcALen, srcBLen) - 1.
  @return        none

  @par           Scaling and Overflow Behavior
                   This fast version uses a 32-bit accumulator with 2.30 format.
                   The accumulator maintains full precision of the intermediate multiplication results but provides only a single guard bit.
                   There is no saturation on intermediate additions.
                   Thus, if the accumulator overflows it wraps around and distorts the result.
                   The input signals should be scaled down to avoid intermediate overflows.
                   Scale down one of the inputs by 1/min(srcALen, srcBLen) to avoid overflow since a
                   maximum of min(srcALen, srcBLen) number of additions is carried internally.
                   The 2.30 accumulator is right shifted by 15 bits and then saturated to 1.15 format to yield the final result.

  @remark
                   Refer to \ref arm_correlate_q15() for a slower implementation of this function which uses a 64-bit accumulator to avoid wrap around distortion.
 */

void arm_correlate_fast_q15(
	const q15_t *pSrcA,
	uint32_t srcALen,
	const q15_t *pSrcB,
	uint32_t srcBLen,
	q15_t *pDst)
{
	const q15_t *pIn1;                                   /* InputA pointer */
	const q15_t *pIn2;                                   /* InputB pointer */
	q15_t *pOut = pDst;                            /* Output pointer */
	q31_t sum, acc0, acc1, acc2, acc3;             /* Accumulators */
	const q15_t *px;                                     /* Intermediate inputA pointer */
	const q15_t *py;                                     /* Intermediate inputB pointer */
	const q15_t *pSrc1;                                  /* Intermediate pointers */
	q31_t x0, x1, x2, x3, c0;                      /* Temporary variables for holding input and coefficient values */
	uint32_t blockSize1, blockSize2, blockSize3;   /* Loop counters */
	uint32_t j, k, count, blkCnt;                  /* Loop counters */
	uint32_t outBlockSize;
	int32_t inc = 1;                               /* Destination address modifier */

	/* The algorithm implementation is based on the lengths of the inputs. */
	/* srcB is always made to slide across srcA. */
	/* So srcBLen is always considered as shorter or equal to srcALen */
	/* But CORR(x, y) is reverse of CORR(y, x) */
	/* So, when srcBLen > srcALen, output pointer is made to point to the end of the output buffer */
	/* and the destination pointer modifier, inc is set to -1 */
	/* If srcALen > srcBLen, zero pad has to be done to srcB to make the two inputs of same length */
	/* But to improve the performance,
	 * we include zeroes in the output instead of zero padding either of the the inputs*/
	/* If srcALen > srcBLen,
	 * (srcALen - srcBLen) zeroes has to included in the starting of the output buffer */
	/* If srcALen < srcBLen,
	 * (srcALen - srcBLen) zeroes has to included in the ending of the output buffer */
	if (srcALen >= srcBLen) {
		/* Initialization of inputA pointer */
		pIn1 = pSrcA;

		/* Initialization of inputB pointer */
		pIn2 = pSrcB;

		/* Number of output samples is calculated */
		outBlockSize = (2U * srcALen) - 1U;

		/* When srcALen > srcBLen, zero padding is done to srcB
		 * to make their lengths equal.
		 * Instead, (outBlockSize - (srcALen + srcBLen - 1))
		 * number of output samples are made zero */
		j = outBlockSize - (srcALen + (srcBLen - 1U));

		/* Updating the pointer position to non zero value */
		pOut += j;

	} else {
		/* Initialization of inputA pointer */
		pIn1 = pSrcB;

		/* Initialization of inputB pointer */
		pIn2 = pSrcA;

		/* srcBLen is always considered as shorter or equal to srcALen */
		j = srcBLen;
		srcBLen = srcALen;
		srcALen = j;

		/* CORR(x, y) = Reverse order(CORR(y, x)) */
		/* Hence set the destination pointer to point to the last output sample */
		pOut = pDst + ((srcALen + srcBLen) - 2U);

		/* Destination address modifier is set to -1 */
		inc = -1;

	}

	/* The function is internally
	 * divided into three stages according to the number of multiplications that has to be
	 * taken place between inputA samples and inputB samples. In the first stage of the
	 * algorithm, the multiplications increase by one for every iteration.
	 * In the second stage of the algorithm, srcBLen number of multiplications are done.
	 * In the third stage of the algorithm, the multiplications decrease by one
	 * for every iteration. */

	/* The algorithm is implemented in three stages.
	   The loop counters of each stage is initiated here. */
	blockSize1 = srcBLen - 1U;
	blockSize2 = srcALen - (srcBLen - 1U);
	blockSize3 = blockSize1;

	/* --------------------------
	 * Initializations of stage1
	 * -------------------------*/

	/* sum = x[0] * y[srcBlen - 1]
	 * sum = x[0] * y[srcBlen - 2] + x[1] * y[srcBlen - 1]
	 * ....
	 * sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen - 1] * y[srcBLen - 1]
	 */

	/* In this stage the MAC operations are increased by 1 for every iteration.
	   The count variable holds the number of MAC operations performed */
	count = 1U;

	/* Working pointer of inputA */
	px = pIn1;

	/* Working pointer of inputB */
	pSrc1 = pIn2 + (srcBLen - 1U);
	py = pSrc1;

	/* ------------------------
	 * Stage1 process
	 * ----------------------*/

	/* The first loop starts here */
	while (blockSize1 > 0U) {
		/* Accumulator is made zero for every iteration */
		sum = 0;

		/* Apply loop unrolling and compute 4 MACs simultaneously. */
		k = count >> 2U;

		/* First part of the processing with loop unrolling.  Compute 4 MACs at a time.
		 ** a second loop below computes MACs for the remaining 1 to 3 samples. */
		while (k > 0U) {
			/* x[0] * y[srcBLen - 4] , x[1] * y[srcBLen - 3] */
			sum = __SMLAD(read_q15x2_ia((q15_t **) &px), read_q15x2_ia((q15_t **) &py), sum);
			/* x[3] * y[srcBLen - 1] , x[2] * y[srcBLen - 2] */
			sum = __SMLAD(read_q15x2_ia((q15_t **) &px), read_q15x2_ia((q15_t **) &py), sum);

			/* Decrement loop counter */
			k--;
		}

		/* If the count is not a multiple of 4, compute any remaining MACs here.
		   No loop unrolling is used. */
		k = count % 0x4U;

		while (k > 0U) {
			/* Perform the multiply-accumulates */
			/* x[0] * y[srcBLen - 1] */
			sum = __SMLAD(*px++, *py++, sum);

			/* Decrement the loop counter */
			k--;
		}

		/* Store the result in the accumulator in the destination buffer. */
		*pOut = (q15_t)(sum >> 15);
		/* Destination pointer is updated according to the address modifier, inc */
		pOut += inc;

		/* Update the inputA and inputB pointers for next MAC calculation */
		py = pSrc1 - count;
		px = pIn1;

		/* Increment MAC count */
		count++;

		/* Decrement loop counter */
		blockSize1--;
	}

	/* --------------------------
	 * Initializations of stage2
	 * ------------------------*/

	/* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen-1] * y[srcBLen-1]
	 * sum = x[1] * y[0] + x[2] * y[1] +...+ x[srcBLen] * y[srcBLen-1]
	 * ....
	 * sum = x[srcALen-srcBLen-2] * y[0] + x[srcALen-srcBLen-1] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
	 */

	/* Working pointer of inputA */
	px = pIn1;

	/* Working pointer of inputB */
	py = pIn2;

	/* count is the index by which the pointer pIn1 to be incremented */
	count = 0U;

	/* --------------------
	 * Stage2 process
	 * -------------------*/

	/* Stage2 depends on srcBLen as in this stage srcBLen number of MACS are performed.
	 * So, to loop unroll over blockSize2,
	 * srcBLen should be greater than or equal to 4 */
	if (srcBLen >= 4U) {
		/* Loop unroll over blockSize2, by 4 */
		blkCnt = blockSize2 >> 2U;

		while (blkCnt > 0U) {
			/* Set all accumulators to zero */
			acc0 = 0;
			acc1 = 0;
			acc2 = 0;
			acc3 = 0;

			/* read x[0], x[1] samples */
			x0 = read_q15x2((q15_t *) px);
			/* read x[1], x[2] samples */
			x1 = read_q15x2((q15_t *) px + 1);
			px += 2U;

			/* Apply loop unrolling and compute 4 MACs simultaneously. */
			k = srcBLen >> 2U;

			/* First part of the processing with loop unrolling.  Compute 4 MACs at a time.
			 ** a second loop below computes MACs for the remaining 1 to 3 samples. */
			do {
				/* Read the first two inputB samples using SIMD:
				 * y[0] and y[1] */
				c0 = read_q15x2_ia((q15_t **) &py);

				/* acc0 +=  x[0] * y[0] + x[1] * y[1] */
				acc0 = __SMLAD(x0, c0, acc0);

				/* acc1 +=  x[1] * y[0] + x[2] * y[1] */
				acc1 = __SMLAD(x1, c0, acc1);

				/* Read x[2], x[3] */
				x2 = read_q15x2((q15_t *) px);

				/* Read x[3], x[4] */
				x3 = read_q15x2((q15_t *) px + 1);

				/* acc2 +=  x[2] * y[0] + x[3] * y[1] */
				acc2 = __SMLAD(x2, c0, acc2);

				/* acc3 +=  x[3] * y[0] + x[4] * y[1] */
				acc3 = __SMLAD(x3, c0, acc3);

				/* Read y[2] and y[3] */
				c0 = read_q15x2_ia((q15_t **) &py);

				/* acc0 +=  x[2] * y[2] + x[3] * y[3] */
				acc0 = __SMLAD(x2, c0, acc0);

				/* acc1 +=  x[3] * y[2] + x[4] * y[3] */
				acc1 = __SMLAD(x3, c0, acc1);

				/* Read x[4], x[5] */
				x0 = read_q15x2((q15_t *) px + 2);

				/* Read x[5], x[6] */
				x1 = read_q15x2((q15_t *) px + 3);
				px += 4U;

				/* acc2 +=  x[4] * y[2] + x[5] * y[3] */
				acc2 = __SMLAD(x0, c0, acc2);

				/* acc3 +=  x[5] * y[2] + x[6] * y[3] */
				acc3 = __SMLAD(x1, c0, acc3);

			} while (--k);

			/* For the next MAC operations, SIMD is not used
			 * So, the 16 bit pointer if inputB, py is updated */

			/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
			 ** No loop unrolling is used. */
			k = srcBLen % 0x4U;

			if (k == 1U) {
				/* Read y[4] */
				c0 = *py;

#ifdef  ARM_MATH_BIG_ENDIAN
				c0 = c0 << 16U;
#else
				c0 = c0 & 0x0000FFFF;
#endif /* #ifdef  ARM_MATH_BIG_ENDIAN */

				/* Read x[7] */
				x3 = read_q15x2((q15_t *) px);
				px++;

				/* Perform the multiply-accumulates */
				acc0 = __SMLAD(x0, c0, acc0);
				acc1 = __SMLAD(x1, c0, acc1);
				acc2 = __SMLADX(x1, c0, acc2);
				acc3 = __SMLADX(x3, c0, acc3);
			}

			if (k == 2U) {
				/* Read y[4], y[5] */
				c0 = read_q15x2((q15_t *) py);

				/* Read x[7], x[8] */
				x3 = read_q15x2((q15_t *) px);

				/* Read x[9] */
				x2 = read_q15x2((q15_t *) px + 1);
				px += 2U;

				/* Perform the multiply-accumulates */
				acc0 = __SMLAD(x0, c0, acc0);
				acc1 = __SMLAD(x1, c0, acc1);
				acc2 = __SMLAD(x3, c0, acc2);
				acc3 = __SMLAD(x2, c0, acc3);
			}

			if (k == 3U) {
				/* Read y[4], y[5] */
				c0 = read_q15x2_ia((q15_t **) &py);

				/* Read x[7], x[8] */
				x3 = read_q15x2((q15_t *) px);

				/* Read x[9] */
				x2 = read_q15x2((q15_t *) px + 1);

				/* Perform the multiply-accumulates */
				acc0 = __SMLAD(x0, c0, acc0);
				acc1 = __SMLAD(x1, c0, acc1);
				acc2 = __SMLAD(x3, c0, acc2);
				acc3 = __SMLAD(x2, c0, acc3);

				c0 = (*py);
				/* Read y[6] */
#ifdef  ARM_MATH_BIG_ENDIAN
				c0 = c0 << 16U;
#else
				c0 = c0 & 0x0000FFFF;
#endif /* #ifdef  ARM_MATH_BIG_ENDIAN */

				/* Read x[10] */
				x3 = read_q15x2((q15_t *) px + 2);
				px += 3U;

				/* Perform the multiply-accumulates */
				acc0 = __SMLADX(x1, c0, acc0);
				acc1 = __SMLAD(x2, c0, acc1);
				acc2 = __SMLADX(x2, c0, acc2);
				acc3 = __SMLADX(x3, c0, acc3);
			}

			/* Store the result in the accumulator in the destination buffer. */
			*pOut = (q15_t)(acc0 >> 15);
			/* Destination pointer is updated according to the address modifier, inc */
			pOut += inc;

			*pOut = (q15_t)(acc1 >> 15);
			pOut += inc;

			*pOut = (q15_t)(acc2 >> 15);
			pOut += inc;

			*pOut = (q15_t)(acc3 >> 15);
			pOut += inc;

			/* Increment the pointer pIn1 index, count by 4 */
			count += 4U;

			/* Update the inputA and inputB pointers for next MAC calculation */
			px = pIn1 + count;
			py = pIn2;

			/* Decrement loop counter */
			blkCnt--;
		}

		/* If the blockSize2 is not a multiple of 4, compute any remaining output samples here.
		 ** No loop unrolling is used. */
		blkCnt = blockSize2 % 0x4U;

		while (blkCnt > 0U) {
			/* Accumulator is made zero for every iteration */
			sum = 0;

			/* Apply loop unrolling and compute 4 MACs simultaneously. */
			k = srcBLen >> 2U;

			/* First part of the processing with loop unrolling.  Compute 4 MACs at a time.
			 ** a second loop below computes MACs for the remaining 1 to 3 samples. */
			while (k > 0U) {
				/* Perform the multiply-accumulates */
				sum += ((q31_t) * px++ * *py++);
				sum += ((q31_t) * px++ * *py++);
				sum += ((q31_t) * px++ * *py++);
				sum += ((q31_t) * px++ * *py++);

				/* Decrement loop counter */
				k--;
			}

			/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
			 ** No loop unrolling is used. */
			k = srcBLen % 0x4U;

			while (k > 0U) {
				/* Perform the multiply-accumulates */
				sum += ((q31_t) * px++ * *py++);

				/* Decrement loop counter */
				k--;
			}

			/* Store the result in the accumulator in the destination buffer. */
			*pOut = (q15_t)(sum >> 15);
			/* Destination pointer is updated according to the address modifier, inc */
			pOut += inc;

			/* Increment the pointer pIn1 index, count by 1 */
			count++;

			/* Update the inputA and inputB pointers for next MAC calculation */
			px = pIn1 + count;
			py = pIn2;

			/* Decrement loop counter */
			blkCnt--;
		}
	} else {
		/* If the srcBLen is not a multiple of 4,
		 * the blockSize2 loop cannot be unrolled by 4 */
		blkCnt = blockSize2;

		while (blkCnt > 0U) {
			/* Accumulator is made zero for every iteration */
			sum = 0;

			/* srcBLen number of MACS should be performed */
			k = srcBLen;

			while (k > 0U) {
				/* Perform the multiply-accumulate */
				sum += ((q31_t) * px++ * *py++);

				/* Decrement loop counter */
				k--;
			}

			/* Store the result in the accumulator in the destination buffer. */
			*pOut = (q15_t)(sum >> 15);
			/* Destination pointer is updated according to the address modifier, inc */
			pOut += inc;

			/* Increment MAC count */
			count++;

			/* Update the inputA and inputB pointers for next MAC calculation */
			px = pIn1 + count;
			py = pIn2;

			/* Decrement loop counter */
			blkCnt--;
		}
	}

	/* --------------------------
	 * Initializations of stage3
	 * -------------------------*/

	/* sum += x[srcALen-srcBLen+1] * y[0] + x[srcALen-srcBLen+2] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
	 * sum += x[srcALen-srcBLen+2] * y[0] + x[srcALen-srcBLen+3] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
	 * ....
	 * sum +=  x[srcALen-2] * y[0] + x[srcALen-1] * y[1]
	 * sum +=  x[srcALen-1] * y[0]
	 */

	/* In this stage the MAC operations are decreased by 1 for every iteration.
	   The count variable holds the number of MAC operations performed */
	count = srcBLen - 1U;

	/* Working pointer of inputA */
	pSrc1 = (pIn1 + srcALen) - (srcBLen - 1U);
	px = pSrc1;

	/* Working pointer of inputB */
	py = pIn2;

	/* -------------------
	 * Stage3 process
	 * ------------------*/

	while (blockSize3 > 0U) {
		/* Accumulator is made zero for every iteration */
		sum = 0;

		/* Apply loop unrolling and compute 4 MACs simultaneously. */
		k = count >> 2U;

		/* First part of the processing with loop unrolling.  Compute 4 MACs at a time.
		 ** a second loop below computes MACs for the remaining 1 to 3 samples. */
		while (k > 0U) {
			/* Perform the multiply-accumulates */
			/* sum += x[srcALen - srcBLen + 4] * y[3] , sum += x[srcALen - srcBLen + 3] * y[2] */
			sum = __SMLAD(read_q15x2_ia((q15_t **) &px), read_q15x2_ia((q15_t **) &py), sum);
			/* sum += x[srcALen - srcBLen + 2] * y[1] , sum += x[srcALen - srcBLen + 1] * y[0] */
			sum = __SMLAD(read_q15x2_ia((q15_t **) &px), read_q15x2_ia((q15_t **) &py), sum);

			/* Decrement loop counter */
			k--;
		}

		/* If the count is not a multiple of 4, compute any remaining MACs here.
		 ** No loop unrolling is used. */
		k = count % 0x4U;

		while (k > 0U) {
			/* Perform the multiply-accumulates */
			sum = __SMLAD(*px++, *py++, sum);

			/* Decrement loop counter */
			k--;
		}

		/* Store the result in the accumulator in the destination buffer. */
		*pOut = (q15_t)(sum >> 15);
		/* Destination pointer is updated according to the address modifier, inc */
		pOut += inc;

		/* Update the inputA and inputB pointers for next MAC calculation */
		px = ++pSrc1;
		py = pIn2;

		/* Decrement the MAC count */
		count--;

		/* Decrement the loop counter */
		blockSize3--;
	}

}

/**
  @} end of Corr group
 */


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20151218204526 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE user (id INT AUTO_INCREMENT NOT NULL, login VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, hash VARCHAR(255) NOT NULL, confirm TINYINT(1) NOT NULL, in_rest TINYINT(1) NOT NULL, left_rest INT NOT NULL, gone_in_rest TIME NOT NULL, class VARCHAR(1) NOT NULL, rating INT NOT NULL, win INT NOT NULL, draw INT NOT NULL, lose INT NOT NULL, lose_time INT NOT NULL, last_auth TIME NOT NULL, immortal_id INT NOT NULL, another_login VARCHAR(255) NOT NULL, last_move TIME NOT NULL, balance BIGINT NOT NULL, UNIQUE INDEX UNIQ_8D93D649AA08CB10 (login), UNIQUE INDEX UNIQ_8D93D649E7927C74 (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE user');
    }
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Angular2Testing.Data
{
    [Table("ItemDetail.InitialAmount")]
    public partial class InitialAmount
    {
        [Key]
        public int PkID { get; set; }

        [Required]
        [StringLength(75)]
        public string UserName { get; set; }

        public double? Amount { get; set; }

        [Column(TypeName = "date")]
        public DateTime? BeginDate { get; set; }
    }
}


text:
Thin grunt wrapper arround https://github.com/foreverjs/forever-monitor

Read the docs at https://github.com/foreverjs/forever-monitor#options-available-when-using-forever-in-nodejs

Options that do not work:
 * pidFile
 * logFile

Not tested
 * spawnWith
 * parser
 * killTree


text:
import {ApiRequest} from "./ApiRequest";

export class Page {
    public Name : string = "";

    public model : string = "";
    public view : string = "";
    public title : string ="";
    public controller() { };

    private ready : number = -1;
    protected data : any = null;
    protected html : string = "";

    public load() {
        let page = this;
        let loadview = new ApiRequest(this.view, function (response) {
            console.log(response);
            page.html = response;
            page.ready++;
            if (page.ready == 1) page.render();
        });
        if(this.model) {
            let loadmodel = new ApiRequest(this.model, function (response) {
                page.data = response;
                page.ready++;
                if (page.ready == 1) page.render();
            });
            loadmodel.execute();
        } else {
            page.ready++;
            if (page.ready == 1) page.render();
        }

        loadview.execute();
    }

    private render() {
        this.ready = -1;
        this.updateTitle();
        document.querySelector('main').innerHTML = this.html;
        this.controller();
    }

    protected updateTitle()
    {
        document.title = this.title;
    }
}


text:
package org.jtheque.collections.impl;

import org.jtheque.collections.DaoCollections;
import org.jtheque.schemas.DefaultSchema;
import org.jtheque.utils.bean.Version;

/**
 * A collection schema. This schema describe the database part to store the collection.
 *
 * @author Baptiste Wicht
 */
public final class CollectionSchema extends DefaultSchema {
    /**
     * Construct a new CollectionSchema.
     */
    public CollectionSchema() {
        super(Version.get("1.0"), "jtheque-collection-schema");
    }

    @Override
    public void install() {
        updateTable(DaoCollections.TABLE,
                "CREATE TABLE IF NOT EXISTS {} (ID INT IDENTITY PRIMARY KEY, TITLE VARCHAR(150) NOT NULL UNIQUE, PROTECTED BOOLEAN, PASSWORD VARCHAR(150))");
        updateTable(DaoCollections.TABLE, "CREATE INDEX IF NOT EXISTS COLLECTIONS_IDX ON {} (ID)");
    }

    @Override
    public void update(Version from) {
        //First version, no updates possible
    }
}


text:
"""Tests for JSON data storage."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)

from os.path import exists, join
from shutil import rmtree

import pytest

from cwmud import settings
from cwmud.core.json import JSONStore

class TestJSONStores:

    """A collection of tests for JSON stores."""

    store = None
    store_path = join(settings.DATA_DIR, "json", "test")
    json_path = join(store_path, "test.json")
    data = {"test": 123, "yeah": "okay"}

    @classmethod
    def setup_class(cls):
        """Clean up any previous test data directory."""
        # In case tests were previously interrupted.
        if exists(cls.store_path):
            rmtree(cls.store_path)

    @classmethod
    def teardown_class(cls):
        """Clean up our test data directory."""
        if exists(cls.store_path):
            rmtree(cls.store_path)

    def test_jsonstore_create(self):
        """Test that we can create a new JSON data store."""
        # The path to this store's data shouldn't exist yet.
        assert not exists(self.store_path)
        type(self).store = JSONStore("test")
        # The directory for this store's data should have been created.
        assert exists(self.store_path)
        assert self.store

    def test_jsonstore_create_second(self):
        """Test that we can create a second JSON store with the same path."""
        assert JSONStore("test")

    def test_jsonstore_get_key_path(self):
        """Test that we can get the full path of a JSON file by key."""
        assert self.store._get_key_path("test") == self.json_path

    def test_jsonstore_get_key_path_key_not_string(self):
        """Test that trying to use a non-string as a JSON key fails."""
        with pytest.raises(TypeError):
            self.store._get_key_path(5)
        with pytest.raises(TypeError):
            self.store._get_key_path(False)

    def test_jsonstore_get_key_path_invalid_path(self):
        """Test that trying to get a key path outside a store fails."""
        with pytest.raises(OSError):
            self.store._get_key_path("../../test")

    def test_jsonstore_no_keys(self):
        """Test that we can check if a JSON store has no keys."""
        assert not tuple(self.store.keys())

    def test_jsonstore_put(self):
        """Test that we can put data into a JSON store."""
        assert not exists(self.json_path)
        self.store._put("test", self.data)
        assert exists(self.json_path)

    def test_jsonstore_has(self):
        """Test that we can tell if a JSON store has a key."""
        assert self.store._has("test")
        assert not self.store._has("nonexistent_key")

    def test_jsonstore_keys(self):
        """Test that we can iterate through a JSON store's keys."""
        # We need to stick a non-JSON file in there to ensure it isn't
        # picked up as a key.
        with open(join(self.store_path, "nope.pkl"), "w") as out:
            out.write("\n")
        # And let's put another valid key in for good measure.
        self.store._put("yeah", {})
        assert tuple(sorted(self.store._keys())) == ("test", "yeah")

    def test_jsonstore_get(self):
        """Test that we can get data from a JSON store."""
        assert self.store._get("test") == self.data

    def test_jsonstore_delete(self):
        """Test that we can delete data from a JSON store."""
        assert exists(self.json_path)
        assert self.store._has("test")
        self.store._delete("test")
        assert not exists(self.json_path)
        assert not self.store._has("test")


text:
set -x -e

#bower install

rm -rf vendor
mkdir -p vendor/{css,fonts,js}

cp -r bower_components/bootstrap/dist/js/* vendor/js
cp -r bower_components/bootstrap/dist/fonts/* vendor/fonts
wget -P vendor/css https://bootswatch.com/readable/bootstrap.min.css
wget -P vendor/css https://bootswatch.com/readable/bootstrap.css

cp -r bower_components/academicons/css/* vendor/css
cp -r bower_components/academicons/fonts/* vendor/fonts
cp -r bower_components/font-awesome/* vendor

cp -r bower_components/MathJax/unpacked vendor/MathJax
cp -r bower_components/pygments/css vendor/pygments

cp bower_components/jquery/dist/* vendor/js


text:
module BeerList
  module Establishments
    class Establishment
      include BeerList::Listable

      def name
        class_name = self.class.name.split('::').last
        class_name.split(/([A-Z]{1}[a-z]+)/).reject(&:empty?).join(' ')
      end
    end
  end
end


text:
const ava = require('ava')
const testMirror = require('../../index.js')

testMirror({
  wrapper: (info, test, mod) => test(mod),
  srcPath: '/../core',
  rootPath: __dirname
})