text:
package com.blazebit.persistence.examples.spring.data.webflux.view;

import com.blazebit.persistence.examples.spring.data.webflux.model.Cat;
import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.UpdatableEntityView;

/**
 * @author Christian Beikov
 * @since 1.4.0
 */
@UpdatableEntityView
@EntityView(Cat.class)
public interface CatUpdateView extends CatSimpleView {

    void setName(String name);

    Integer getAge();

    void setAge(Integer age);
}


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

<title>The GNU C Library: Synchronizing AIO Operations</title>

<meta name="description" content="The GNU C Library: Synchronizing AIO Operations">
<meta name="keywords" content="The GNU C Library: Synchronizing AIO Operations">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Asynchronous-I_002fO.html#Asynchronous-I_002fO" rel="up" title="Asynchronous I/O">
<link href="Cancel-AIO-Operations.html#Cancel-AIO-Operations" rel="next" title="Cancel AIO Operations">
<link href="Status-of-AIO-Operations.html#Status-of-AIO-Operations" rel="prev" title="Status of AIO Operations">

Next: Cancel AIO Operations, Previous: Status of AIO Operations, Up: Asynchronous I/O   [Contents][Index]

13.10.3 Getting into a Consistent State

When dealing with asynchronous operations it is sometimes necessary to
get into a consistent state.  This would mean for AIO that one wants to
know whether a certain request or a group of request were processed.
This could be done by waiting for the notification sent by the system
after the operation terminated, but this sometimes would mean wasting
resources (mainly computation time).  Instead POSIX.1b defines two
functions which will help with most kinds of consistency.

The aio_fsync and aio_fsync64 functions are only available
if the symbol _POSIX_SYNCHRONIZED_IO is defined in <samp>unistd.h</samp>.

Function: int aio_fsync (int <var>op</var>, struct aiocb *<var>aiocbp</var>)

Preliminary:
| MT-Safe
| AS-Unsafe lock heap
| AC-Unsafe lock mem
| See POSIX Safety Concepts.

Calling this function forces all I/O operations operating queued at the
time of the function call operating on the file descriptor
aiocbp->aio_fildes into the synchronized I/O completion state
(see Synchronizing I/O).  The aio_fsync function returns
immediately but the notification through the method described in
aiocbp->aio_sigevent will happen only after all requests for this
file descriptor have terminated and the file is synchronized.  This also
means that requests for this very same file descriptor which are queued
after the synchronization request are not affected.

If <var>op</var> is O_DSYNC the synchronization happens as with a call
to fdatasync.  Otherwise <var>op</var> should be O_SYNC and
the synchronization happens as with fsync.

As long as the synchronization has not happened, a call to
aio_error with the reference to the object pointed to by
<var>aiocbp</var> returns EINPROGRESS.  Once the synchronization is
done aio_error return 0 if the synchronization was not
successful.  Otherwise the value returned is the value to which the
fsync or fdatasync function would have set the
errno variable.  In this case nothing can be assumed about the
consistency for the data written to this file descriptor.

The return value of this function is 0 if the request was
successfully enqueued.  Otherwise the return value is -1 and
errno is set to one of the following values:

EAGAIN

The request could not be enqueued due to temporary lack of resources.

EBADF

The file descriptor <var>aiocbp</var>->aio_fildes is not valid.

EINVAL

The implementation does not support I/O synchronization or the <var>op</var>
parameter is other than O_DSYNC and O_SYNC.

ENOSYS

This function is not implemented.

When the sources are compiled with _FILE_OFFSET_BITS == 64 this
function is in fact aio_fsync64 since the LFS interface
transparently replaces the normal implementation.

Function: int aio_fsync64 (int <var>op</var>, struct aiocb64 *<var>aiocbp</var>)

Preliminary:
| MT-Safe
| AS-Unsafe lock heap
| AC-Unsafe lock mem
| See POSIX Safety Concepts.

This function is similar to aio_fsync with the only difference
that the argument is a reference to a variable of type struct
aiocb64.

When the sources are compiled with _FILE_OFFSET_BITS == 64 this
function is available under the name aio_fsync and so
transparently replaces the interface for small files on 32 bit
machines.

Another method of synchronization is to wait until one or more requests of a
specific set terminated.  This could be achieved by the aio_*
functions to notify the initiating process about the termination but in
some situations this is not the ideal solution.  In a program which
constantly updates clients somehow connected to the server it is not
always the best solution to go round robin since some connections might
be slow.  On the other hand letting the aio_* function notify the
caller might also be not the best solution since whenever the process
works on preparing data for on client it makes no sense to be
interrupted by a notification since the new client will not be handled
before the current client is served.  For situations like this
aio_suspend should be used.

Function: int aio_suspend (const struct aiocb *const <var>list</var>[], int <var>nent</var>, const struct timespec *<var>timeout</var>)

Preliminary:
| MT-Safe
| AS-Unsafe lock
| AC-Unsafe lock
| See POSIX Safety Concepts.

When calling this function, the calling thread is suspended until at
least one of the requests pointed to by the <var>nent</var> elements of the
array <var>list</var> has completed.  If any of the requests has already
completed at the time aio_suspend is called, the function returns
immediately.  Whether a request has terminated or not is determined by
comparing the error status of the request with EINPROGRESS.  If
an element of <var>list</var> is NULL, the entry is simply ignored.

If no request has finished, the calling process is suspended.  If
<var>timeout</var> is NULL, the process is not woken until a request
has finished.  If <var>timeout</var> is not NULL, the process remains
suspended at least as long as specified in <var>timeout</var>.  In this case,
aio_suspend returns with an error.

The return value of the function is 0 if one or more requests
from the <var>list</var> have terminated.  Otherwise the function returns
-1 and errno is set to one of the following values:

EAGAIN

None of the requests from the <var>list</var> completed in the time specified
by <var>timeout</var>.

EINTR

A signal interrupted the aio_suspend function.  This signal might
also be sent by the AIO implementation while signalling the termination
of one of the requests.

ENOSYS

The aio_suspend function is not implemented.

When the sources are compiled with _FILE_OFFSET_BITS == 64 this
function is in fact aio_suspend64 since the LFS interface
transparently replaces the normal implementation.

Function: int aio_suspend64 (const struct aiocb64 *const <var>list</var>[], int <var>nent</var>, const struct timespec *<var>timeout</var>)

Preliminary:
| MT-Safe
| AS-Unsafe lock
| AC-Unsafe lock
| See POSIX Safety Concepts.

This function is similar to aio_suspend with the only difference
that the argument is a reference to a variable of type struct
aiocb64.

When the sources are compiled with _FILE_OFFSET_BITS == 64 this
function is available under the name aio_suspend and so
transparently replaces the interface for small files on 32 bit
machines.

Next: Cancel AIO Operations, Previous: Status of AIO Operations, Up: Asynchronous I/O   [Contents][Index]

redpajama_set_name: RedPajamaGithub


text:
"""
Created on 7 Jun 2019

@author: Bruno Beloff (bruno.beloff@southcoastscience.com)

An abstract gas sensor interface
"""

from abc import ABC, abstractmethod

# --------------------------------------------------------------------------------------------------------------------

class GasSensorInterface(ABC):
    """
    classdocs
    """

    # ----------------------------------------------------------------------------------------------------------------
    # identity...

    @classmethod
    @abstractmethod
    def src(cls):
        pass

    # ----------------------------------------------------------------------------------------------------------------
    # business methods...

    @abstractmethod
    def adc_versions(self):
        pass

    @abstractmethod
    def sample(self, sht_datum):
        pass

    @abstractmethod
    def sample_station(self, sn, sht_datum):
        pass

    @abstractmethod
    def null_datum(self):
        pass

    # ----------------------------------------------------------------------------------------------------------------
    # electrochem callbacks...

    @abstractmethod
    def sample_raw_wrk_aux(self, sensor_index, gain_index):
        pass

    @abstractmethod
    def sample_raw_wrk(self, sensor_index, gain_index):
        pass


text:
@interface TextAreaWidget : AbstractUIWidget <ITextAreaWidget, UITextViewDelegate>{
    EOSTextView *textView;
}

@property (nonatomic, readonly) TextAreaM *model;
@property (nonatomic, readonly) TextAreaM *stableModel;

@end


text:
THRIFT_DIR=src_thrift

echo "-------------------------------------------------------------------------"
echo "1. generate files"
echo "-------------------------------------------------------------------------"

thrift -o   $THRIFT_DIR -strict -r -v --gen erl $THRIFT_DIR/erlang_python.thrift
thrift -out src_py      -strict -r -v --gen py  $THRIFT_DIR/erlang_python.thrift

echo "-------------------------------------------------------------------------"
echo "2. list content of generated file directories"
echo "-------------------------------------------------------------------------"

ls -l $THRIFT_DIR/gen-erl

echo "-------------------------------------------------------------------------"
echo "3. move the generated files"
echo "-------------------------------------------------------------------------"

mkdir -p include
mv $THRIFT_DIR/gen-erl/*.erl src
mv $THRIFT_DIR/gen-erl/*.hrl include

echo "-------------------------------------------------------------------------"
echo "4. delete generated file directories"
echo "-------------------------------------------------------------------------"

rm -r $THRIFT_DIR/gen-erl
ls -l $THRIFT_DIR


text:
package stellar

import (
	"context"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"

	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/msgpack"
	"github.com/keybase/client/go/protocol/keybase1"
	"github.com/keybase/client/go/protocol/stellar1"
	"golang.org/x/crypto/nacl/box"
	"golang.org/x/crypto/nacl/secretbox"
)

type noteBuildSecret struct {
	symmetricKey libkb.NaclSecretBoxKey
	sender       stellar1.NoteRecipient
	recipient    *stellar1.NoteRecipient
}

// noteSymmetricKey returns a symmetric key to be used in encrypting a note.
// The key is available to the current user and to the optional `other` recipient.
// If `other` is nil the key is derived from the latest PUK seed.
// If `other` is non-nil the key is derived from the nacl shared key of both users' latest PUK encryption keys.
func noteSymmetricKey(mctx libkb.MetaContext, other *keybase1.UserVersion) (res noteBuildSecret, err error) {
	meUV, err := mctx.G().GetMeUV(mctx.Ctx())
	if err != nil {
		return res, err
	}
	puk1Gen, puk1Seed, err := loadOwnLatestPuk(mctx)
	if err != nil {
		return res, err
	}
	symmetricKey, err := puk1Seed.DeriveSymmetricKey(libkb.DeriveReasonPUKStellarNoteSelf)
	if err != nil {
		return res, err
	}
	var recipient *stellar1.NoteRecipient
	if other != nil && !other.Eq(meUV) {
		u2, err := loadUvUpk(mctx, *other)
		if err != nil {
			return res, fmt.Errorf("error loading recipient: %v", err)
		}
		puk2 := u2.GetLatestPerUserKey()
		if puk2 == nil {
			return res, fmt.Errorf("recipient has no per-user key")
		}
		// Overwite symmetricKey with the shared key.
		symmetricKey, err = noteMixKeys(mctx, puk1Seed, puk2.EncKID)
		if err != nil {
			return res, err
		}
		recipient = &stellar1.NoteRecipient{
			User:   *other,
			PukGen: keybase1.PerUserKeyGeneration(puk2.Gen),
		}
	}
	return noteBuildSecret{
		symmetricKey: symmetricKey,
		sender: stellar1.NoteRecipient{
			User:   meUV,
			PukGen: puk1Gen,
		},
		recipient: recipient,
	}, nil
}

func noteSymmetricKeyForDecryption(mctx libkb.MetaContext, encNote stellar1.EncryptedNote) (res libkb.NaclSecretBoxKey, err error) {
	meUV, err := mctx.G().GetMeUV(mctx.Ctx())
	if err != nil {
		return res, err
	}
	var mePukGen keybase1.PerUserKeyGeneration
	var them *stellar1.NoteRecipient
	if encNote.Sender.User.Eq(meUV) {
		mePukGen = encNote.Sender.PukGen
		them = encNote.Recipient
	}
	if encNote.Recipient != nil && encNote.Recipient.User.Eq(meUV) {
		mePukGen = encNote.Recipient.PukGen
		them = &encNote.Sender
	}
	if mePukGen == 0 {
		return res, fmt.Errorf("note not encrypted for logged-in user")
	}
	pukring, err := mctx.G().GetPerUserKeyring(mctx.Ctx())
	if err != nil {
		return res, err
	}
	pukSeed, err := pukring.GetSeedByGenerationOrSync(mctx, mePukGen)
	if err != nil {
		return res, err
	}
	if them == nil {
		return pukSeed.DeriveSymmetricKey(libkb.DeriveReasonPUKStellarNoteSelf)
	}
	u2, err := loadUvUpk(mctx, them.User)
	if err != nil {
		return res, err
	}
	puk2 := u2.GetPerUserKeyByGen(them.PukGen)
	if puk2 == nil {
		return res, fmt.Errorf("could not find other user's key: %v %v", them.User.String(), them.PukGen)
	}
	return noteMixKeys(mctx, pukSeed, puk2.EncKID)
}

// noteMixKeys derives a shared symmetric key for two DH keys.
// The key is the last 32 bytes of the nacl box of 32 zeros with a use-specific nonce.
func noteMixKeys(mctx libkb.MetaContext, puk1 libkb.PerUserKeySeed, puk2EncKID keybase1.KID) (res libkb.NaclSecretBoxKey, err error) {
	puk1Enc, err := puk1.DeriveDHKey()
	if err != nil {
		return res, err
	}
	puk2EncGeneric, err := libkb.ImportKeypairFromKID(puk2EncKID)
	if err != nil {
		return res, err
	}
	puk2Enc, ok := puk2EncGeneric.(libkb.NaclDHKeyPair)
	if !ok {
		return res, fmt.Errorf("recipient per-user key was not a DH key")
	}
	var zeros [32]byte
	// This is a constant nonce used for key derivation.
	// The derived key will be used with one-time random nonces for the actual encryption/decryption.
	nonce := noteMixPukNonce()
	sharedSecretBox := box.Seal(nil, zeros[:], &nonce, (*[32]byte)(&puk2Enc.Public), (*[32]byte)(puk1Enc.Private))
	return libkb.MakeByte32Soft(sharedSecretBox[len(sharedSecretBox)-32:])
}

// noteMixPukNonce is a nonce used in key derivation for shared notes.
// 24-byte prefix of the sha256 hash of a constant string.
func noteMixPukNonce() (res [24]byte) {
	reasonHash := sha256.Sum256([]byte(libkb.DeriveReasonPUKStellarNoteShared))
	copy(res[:], reasonHash[:])
	return res
}

func NoteEncryptB64(mctx libkb.MetaContext, note stellar1.NoteContents, other *keybase1.UserVersion) (noteB64 string, err error) {
	if len(note.Note) > libkb.MaxStellarPaymentNoteLength {
		return "", fmt.Errorf("Note of size %d bytes exceeds the maximum length of %d bytes",
			len(note.Note), libkb.MaxStellarPaymentNoteLength)
	}
	obj, err := noteEncrypt(mctx, note, other)
	if err != nil {
		return "", err
	}
	pack, err := msgpack.Encode(obj)
	if err != nil {
		return "", err
	}
	noteB64 = base64.StdEncoding.EncodeToString(pack)
	if len(noteB64) > libkb.MaxStellarPaymentBoxedNoteLength {
		return "", fmt.Errorf("Encrypted note of size %d bytes exceeds the maximum length of %d bytes",
			len(noteB64), libkb.MaxStellarPaymentBoxedNoteLength)
	}
	return noteB64, nil
}

// noteEncrypt encrypts a note for the logged-in user as well as optionally for `other`.
func noteEncrypt(mctx libkb.MetaContext, note stellar1.NoteContents, other *keybase1.UserVersion) (res stellar1.EncryptedNote, err error) {
	nbs, err := noteSymmetricKey(mctx, other)
	if err != nil {
		return res, fmt.Errorf("error getting encryption key for note: %v", err)
	}
	if nbs.symmetricKey.IsZero() {
		// This should never happen
		return res, fmt.Errorf("unexpected zero key")
	}
	res, err = noteEncryptHelper(mctx.Ctx(), note, nbs.symmetricKey)
	if err != nil {
		return res, err
	}
	res.Sender = nbs.sender
	res.Recipient = nbs.recipient
	return res, nil
}

// noteEncryptHelper does the encryption part and returns a partially populated result.
func noteEncryptHelper(ctx context.Context, note stellar1.NoteContents, symmetricKey libkb.NaclSecretBoxKey) (res stellar1.EncryptedNote, err error) {
	// Msgpack
	clearpack, err := msgpack.Encode(note)
	if err != nil {
		return res, err
	}

	// Secretbox
	var nonce [libkb.NaclDHNonceSize]byte
	nonce, err = libkb.RandomNaclDHNonce()
	if err != nil {
		return res, err
	}
	secbox := secretbox.Seal(nil, clearpack, &nonce, (*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))

	return stellar1.EncryptedNote{
		V: 1,
		E: secbox,
		N: nonce,
	}, nil
}

func NoteDecryptB64(mctx libkb.MetaContext, noteB64 string) (res stellar1.NoteContents, err error) {
	pack, err := base64.StdEncoding.DecodeString(noteB64)
	if err != nil {
		return res, err
	}
	var obj stellar1.EncryptedNote
	err = msgpack.Decode(&obj, pack)
	if err != nil {
		return res, err
	}
	return noteDecrypt(mctx, obj)
}

func noteDecrypt(mctx libkb.MetaContext, encNote stellar1.EncryptedNote) (res stellar1.NoteContents, err error) {
	if encNote.V != 1 {
		return res, fmt.Errorf("unsupported note version: %v", encNote.V)
	}
	symmetricKey, err := noteSymmetricKeyForDecryption(mctx, encNote)
	if err != nil {
		return res, err
	}
	return noteDecryptHelper(mctx.Ctx(), encNote, symmetricKey)
}

func noteDecryptHelper(ctx context.Context, encNote stellar1.EncryptedNote, symmetricKey libkb.NaclSecretBoxKey) (res stellar1.NoteContents, err error) {
	// Secretbox
	clearpack, ok := secretbox.Open(nil, encNote.E,
		(*[libkb.NaclDHNonceSize]byte)(&encNote.N),
		(*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))
	if !ok {
		return res, errors.New("could not decrypt note secretbox")
	}

	// Msgpack
	err = msgpack.Decode(&res, clearpack)
	return res, err
}


text:
package me.legitmodern.Punishment.Utils;

import java.text.SimpleDateFormat;

public class TimeUtils {
    public static SimpleDateFormat dateFormat = new SimpleDateFormat("h:mm a - MMM d, yyyy");

    /**
     * Get the time unit for an amount
     *
     * @param amount Amount of time
     * @param unit   Unit of time
     * @return Amount of time
     */
    public static long getTime(long amount, String unit) {
        try {
            if (unit.equalsIgnoreCase("seconds")) {
                return amount * 1000L;
            } else if (unit.equalsIgnoreCase("minutes")) {
                return amount * 1000L * 60L;
            } else if (unit.equalsIgnoreCase("hours")) {
                return amount * 1000L * 60L * 60L;
            } else if (unit.equalsIgnoreCase("days")) {
                return amount * 1000L * 60L * 60L * 24L;
            } else if (unit.equalsIgnoreCase("months")) {
                return amount * 1000L * 60L * 60L * 24L * 31L;
            } else if (unit.equalsIgnoreCase("years")) {
                return amount * 1000L * 60L * 60L * 24L * 365L;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0L;
    }
}


text:
extern void BinkPlay(const char* filename, IDirectDrawSurface* lpdds, bool (*flip)());

extern void BinkMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);


text:
source conf/drillTestConfig.properties

set -x
set -e

${DRILL_HOME}/bin/sqlline -n ${USERNAME} -p ${PASSWORD} -u "jdbc:drill:schema=dfs.aggregation;drillbit=${DRILL_STORAGE_PLUGIN_SERVER}"  --run=${DRILL_TEST_DATA_DIR}/Datasources/limit0/aggregates/aggregation/bugs/create_bugs_view.sql

set +x


text:
import _plotly_utils.basevalidators

class AllowoverlapValidator(_plotly_utils.basevalidators.BooleanValidator):
    def __init__(
        self, plotly_name="allowoverlap", parent_name="scattermapbox.marker", **kwargs
    ):
        super(AllowoverlapValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            edit_type=kwargs.pop("edit_type", "calc"),
            role=kwargs.pop("role", "style"),
            **kwargs
        )


text:
'use strict';

module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-recommended-scss',
    'stylelint-config-rational-order'
  ],
  rules: {
    'at-rule-no-unknown': null,
    'at-rule-empty-line-before': null,
    'at-rule-name-space-after': 'always',
    'at-rule-no-vendor-prefix': true,
    'at-rule-semicolon-space-before': 'never',
    'block-closing-brace-empty-line-before': null,
    'block-closing-brace-newline-after': null,
    'block-opening-brace-space-before': null,
    'color-named': 'never',
    'declaration-block-semicolon-newline-before': 'never-multi-line',
    'declaration-empty-line-before': null,
    'declaration-no-important': null,
    'font-family-name-quotes': 'always-where-recommended',
    'font-weight-notation': [
      'numeric',
      {
        'ignore': [
          'relative'
        ]
      }
    ],
    'function-url-no-scheme-relative': true,
    'function-url-quotes': 'always',
    'max-empty-lines': 2,
    'max-line-length': null,
    'media-feature-name-no-vendor-prefix': true,
    'no-descending-specificity': null,
    'number-leading-zero': 'never',
    'property-no-vendor-prefix': true,
    'rule-empty-line-before': null,
    'selector-attribute-quotes': 'always',
    'selector-class-pattern': null,
    'selector-list-comma-newline-before': 'never-multi-line',
    'selector-list-comma-space-after': 'always-single-line',
    'selector-list-comma-space-before': 'never-single-line',
    'selector-max-attribute': null,
    'selector-max-class': null,
    'selector-max-combinators': null,
    'selector-max-compound-selectors': null,
    'selector-max-id': null,
    'selector-max-specificity': null,
    'selector-max-type': null,
    'selector-max-universal': null,
    'selector-no-qualifying-type': false,
    'selector-no-vendor-prefix': true,
    'shorthand-property-no-redundant-values': true,
    'string-quotes': 'double',
    'value-list-comma-newline-after': 'never-multi-line',
    'value-list-comma-newline-before': 'never-multi-line',
    'value-list-comma-space-after': 'always',
    'value-no-vendor-prefix': true,
    'scss/at-function-named-arguments': 'never',
    'scss/at-function-pattern': '^[a-z][a-z-]*$',
    'scss/at-function-parentheses-space-before': 'never',
    'scss/at-import-no-partial-leading-underscore': true,
    'scss/at-mixin-argumentless-call-parentheses': 'always',
    'scss/at-mixin-named-arguments': null,
    'scss/at-mixin-parentheses-space-before': 'never',
    'scss/at-rule-no-unknown': true,
    'scss/dollar-variable-colon-space-after': 'at-least-one-space',
    'scss/dollar-variable-colon-space-before': 'never',
    'scss/dollar-variable-no-missing-interpolation': true,
    'scss/dollar-variable-pattern': '^[a-z][a-z-\\d]*$',
    'scss/media-feature-value-dollar-variable': null,
    'scss/no-duplicate-dollar-variables': [
      null,
      {
        'ignoreInsideAtRules': [
          'if',
          'mixin'
        ]
      }
    ],
    'scss/no-duplicate-mixins': true,
    'scss/operator-no-newline-after': true,
    'scss/operator-no-newline-before': true,
    'scss/operator-no-unspaced': true
  }
};


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace OnlineExamPrep.DAL.Models.Mapping
{
    public class AnswerStepPictureEntityMap : EntityTypeConfiguration<AnswerStepPictureEntity>
    {
        public AnswerStepPictureEntityMap()
        {
            // Primary Key
            this.HasKey(t => t.Id);

            // Properties
            this.Property(t => t.Id)
                .IsRequired()
                .HasMaxLength(128);

            this.Property(t => t.AnswerStepId)
                .IsRequired()
                .HasMaxLength(128);

            this.Property(t => t.Image)
                .IsRequired();

            // Table & Column Mappings
            this.ToTable("AnswerStepPicture");
            this.Property(t => t.Id).HasColumnName("Id");
            this.Property(t => t.AnswerStepId).HasColumnName("AnswerStepId");
            this.Property(t => t.Image).HasColumnName("Image");

            // Relationships
            this.HasRequired(t => t.AnswerStep)
                .WithMany(t => t.AnswerStepPictures)
                .HasForeignKey(d => d.AnswerStepId);

        }
    }
}


text:
this_dir = File.expand_path(File.dirname(__FILE__))
lib_dir = File.join(File.dirname(File.dirname(this_dir)), 'lib')
pb_dir = File.dirname(this_dir)
$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
$LOAD_PATH.unshift(pb_dir) unless $LOAD_PATH.include?(pb_dir)

require 'optparse'
require 'logger'

require_relative '../../lib/grpc'
require 'google/protobuf'

require_relative '../src/proto/grpc/testing/empty_pb'
require_relative '../src/proto/grpc/testing/messages_pb'
require_relative '../src/proto/grpc/testing/test_services_pb'

class RpcConfig
  attr_reader :rpcs_to_send, :metadata_to_send, :timeout_sec
  def init(rpcs_to_send, metadata_to_send, timeout_sec = 0)
    @rpcs_to_send = rpcs_to_send
    @metadata_to_send = metadata_to_send
    @timeout_sec = timeout_sec
  end
end

# Some global constant mappings
$RPC_MAP = {
  'UnaryCall' => :UNARY_CALL,
  'EmptyCall' => :EMPTY_CALL,
}

# Some global variables to be shared by server and client
$watchers = Array.new
$watchers_mutex = Mutex.new
$watchers_cv = ConditionVariable.new
$shutdown = false
# These can be configured by the test runner dynamically
$rpc_config = RpcConfig.new
$rpc_config.init([:UNARY_CALL], {})
# These stats are shared across threads
$thread_results = Array.new
$thread_results_mu = Mutex.new
$accumulated_stats_mu = Mutex.new
$num_rpcs_started_by_method = {}
$num_rpcs_succeeded_by_method = {}
$num_rpcs_failed_by_method = {}
$accumulated_method_stats = {}

# RubyLogger defines a logger for gRPC based on the standard ruby logger.
module RubyLogger
  def logger
    LOGGER
  end

  LOGGER = Logger.new(STDOUT)
  LOGGER.level = Logger::INFO
end

# GRPC is the general RPC module
module GRPC
  # Inject the noop #logger if no module-level logger method has been injected.
  extend RubyLogger
end

# creates a test stub
def create_stub(opts)
  address = "#{opts.server}"
  GRPC.logger.info("... connecting insecurely to #{address}")
  Grpc::Testing::TestService::Stub.new(
    address,
    :this_channel_is_insecure,
  )
end

class StatsPerMethod
  attr_reader :rpcs_started, :result
  def initialize()
    @rpcs_started = 0
    @result = Hash.new(0)
  end
  def increment_rpcs_started()
    @rpcs_started += 1
  end
  def add_result(status_code)
    @result[status_code] += 1
  end
end

class ConfigureTarget < Grpc::Testing::XdsUpdateClientConfigureService::Service
  include Grpc::Testing

  def configure(req, _call)
    metadata_to_send = {}
    req.metadata.each do |m|
      rpc = m.type
      if !metadata_to_send.key?(rpc)
        metadata_to_send[rpc] = {}
      end
      metadata_key = m.key
      metadata_value = m.value
      metadata_to_send[rpc][metadata_key] = metadata_value
    end
    new_rpc_config = RpcConfig.new
    new_rpc_config.init(req['types'], metadata_to_send, req['timeout_sec'])
    $rpc_config = new_rpc_config
    ClientConfigureResponse.new()
  end
end

# This implements LoadBalancerStatsService required by the test runner
class TestTarget < Grpc::Testing::LoadBalancerStatsService::Service
  include Grpc::Testing

  def get_client_stats(req, _call)
    finish_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) +
                  req['timeout_sec']
    watcher = {}
    $watchers_mutex.synchronize do
      watcher = {
        "rpcs_by_method" => Hash.new(),
        "rpcs_by_peer" => Hash.new(0),
        "rpcs_needed" => req['num_rpcs'],
        "no_remote_peer" => 0
      }
      $watchers << watcher
      seconds_remaining = finish_time -
                          Process.clock_gettime(Process::CLOCK_MONOTONIC)
      while watcher['rpcs_needed'] > 0 && seconds_remaining > 0
        $watchers_cv.wait($watchers_mutex, seconds_remaining)
        seconds_remaining = finish_time -
                            Process.clock_gettime(Process::CLOCK_MONOTONIC)
      end
      $watchers.delete_at($watchers.index(watcher))
    end
    # convert results into proper proto object
    rpcs_by_method = {}
    watcher['rpcs_by_method'].each do |rpc_name, rpcs_by_peer|
      rpcs_by_method[rpc_name] = LoadBalancerStatsResponse::RpcsByPeer.new(
        rpcs_by_peer: rpcs_by_peer
      )
    end
    LoadBalancerStatsResponse.new(
      rpcs_by_method: rpcs_by_method,
      rpcs_by_peer: watcher['rpcs_by_peer'],
      num_failures: watcher['no_remote_peer'] + watcher['rpcs_needed']
    )
  end

  def get_client_accumulated_stats(req, _call)
    $accumulated_stats_mu.synchronize do
      all_stats_per_method = $accumulated_method_stats.map { |rpc, stats_per_method|
        [rpc,
         LoadBalancerAccumulatedStatsResponse::MethodStats.new(
          rpcs_started: stats_per_method.rpcs_started,
          result: stats_per_method.result
         )]
      }.to_h
      LoadBalancerAccumulatedStatsResponse.new(
        num_rpcs_started_by_method: $num_rpcs_started_by_method,
        num_rpcs_succeeded_by_method: $num_rpcs_succeeded_by_method,
        num_rpcs_failed_by_method: $num_rpcs_failed_by_method,
        stats_per_method: all_stats_per_method,
      )
    end
  end
end

def execute_rpc_in_thread(op, rpc)
  Thread.new {
    rpc_stats_key = rpc.to_s
    remote_peer = ""
    begin
      op.execute
      if op.metadata.key?('hostname')
        remote_peer = op.metadata['hostname']
      end
      $accumulated_stats_mu.synchronize do
        $num_rpcs_succeeded_by_method[rpc_stats_key] += 1
        $accumulated_method_stats[rpc_stats_key].add_result(0)
      end
    rescue GRPC::BadStatus => e
      $accumulated_stats_mu.synchronize do
        $num_rpcs_failed_by_method[rpc_stats_key] += 1
        $accumulated_method_stats[rpc_stats_key].add_result(e.code)
      end
    end
    $thread_results_mu.synchronize do
      $thread_results << [rpc, remote_peer]
    end
  }
end

# send 1 rpc every 1/qps second
def run_test_loop(stub, target_seconds_between_rpcs, fail_on_failed_rpcs)
  include Grpc::Testing
  simple_req = SimpleRequest.new()
  empty_req = Empty.new()
  target_next_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  # Some RPCs are meant to be "kept open". Since Ruby does not have an
  # async API, we are executing those RPCs in a thread so that they don't
  # block.
  keep_open_threads = Array.new
  while !$shutdown
    now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    sleep_seconds = target_next_start - now
    if sleep_seconds < 0
      target_next_start = now + target_seconds_between_rpcs
    else
      target_next_start += target_seconds_between_rpcs
      sleep(sleep_seconds)
    end
    deadline_sec = $rpc_config.timeout_sec > 0 ? $rpc_config.timeout_sec : 30
    deadline = GRPC::Core::TimeConsts::from_relative_time(deadline_sec)
    results = {}
    $rpc_config.rpcs_to_send.each do |rpc|
      # rpc is in the form of :UNARY_CALL or :EMPTY_CALL here
      metadata = $rpc_config.metadata_to_send.key?(rpc) ?
                   $rpc_config.metadata_to_send[rpc] : {}
      $accumulated_stats_mu.synchronize do
        $num_rpcs_started_by_method[rpc.to_s] += 1
        $accumulated_method_stats[rpc.to_s].increment_rpcs_started()
      end
      if rpc == :UNARY_CALL
        op = stub.unary_call(simple_req,
                             metadata: metadata,
                             deadline: deadline,
                             return_op: true)
      elsif rpc == :EMPTY_CALL
        op = stub.empty_call(empty_req,
                             metadata: metadata,
                             deadline: deadline,
                             return_op: true)
      else
        raise "Unsupported rpc #{rpc}"
      end
      keep_open_threads << execute_rpc_in_thread(op, rpc)
    end
    # collect results from threads
    $thread_results_mu.synchronize do
      $thread_results.each do |r|
        rpc_name, remote_peer = r
        results[rpc_name] = remote_peer
      end
      $thread_results = Array.new
    end
    $watchers_mutex.synchronize do
      $watchers.each do |watcher|
        # this is counted once when each group of all rpcs_to_send were done
        watcher['rpcs_needed'] -= 1
        results.each do |rpc_name, remote_peer|
          # These stats expect rpc_name to be in the form of
          # UnaryCall or EmptyCall, not the underscore-case all-caps form
          rpc_name = $RPC_MAP.invert()[rpc_name]
          if remote_peer.strip.empty?
            # error is counted per individual RPC
            watcher['no_remote_peer'] += 1
          else
            if not watcher['rpcs_by_method'].key?(rpc_name)
              watcher['rpcs_by_method'][rpc_name] = Hash.new(0)
            end
            # increment the remote hostname distribution histogram
            # both by overall, and broken down per RPC
            watcher['rpcs_by_method'][rpc_name][remote_peer] +=  1
            watcher['rpcs_by_peer'][remote_peer] += 1
          end
        end
      end
      $watchers_cv.broadcast
    end
  end
  keep_open_threads.each { |thd| thd.join }
end

# Args is used to hold the command line info.
Args = Struct.new(:fail_on_failed_rpcs, :num_channels,
                  :rpc, :metadata,
                  :server, :stats_port, :qps)

# validates the command line options, returning them as a Hash.
def parse_args
  args = Args.new
  args['fail_on_failed_rpcs'] = false
  args['num_channels'] = 1
  args['rpc'] = 'UnaryCall'
  args['metadata'] = ''
  OptionParser.new do |opts|
    opts.on('--fail_on_failed_rpcs BOOL', ['false', 'true']) do |v|
      args['fail_on_failed_rpcs'] = v == 'true'
    end
    opts.on('--num_channels CHANNELS', 'number of channels') do |v|
      args['num_channels'] = v.to_i
    end
    opts.on('--rpc RPCS_TO_SEND', 'list of RPCs to send') do |v|
      args['rpc'] = v
    end
    opts.on('--metadata METADATA_TO_SEND', 'metadata to send per RPC') do |v|
      args['metadata'] = v
    end
    opts.on('--server SERVER_HOST', 'server hostname') do |v|
      GRPC.logger.info("ruby xds: server address is #{v}")
      args['server'] = v
    end
    opts.on('--stats_port STATS_PORT', 'stats port') do |v|
      GRPC.logger.info("ruby xds: stats port is #{v}")
      args['stats_port'] = v
    end
    opts.on('--qps QPS', 'qps') do |v|
      GRPC.logger.info("ruby xds: qps is #{v}")
      args['qps'] = v
    end
  end.parse!
  args
end

def main
  opts = parse_args

  # This server hosts the LoadBalancerStatsService
  host = "0.0.0.0:#{opts['stats_port']}"
  s = GRPC::RpcServer.new
  s.add_http2_port(host, :this_port_is_insecure)
  s.handle(TestTarget)
  s.handle(ConfigureTarget)
  server_thread = Thread.new {
    # run the server until the main test runner terminates this process
    s.run_till_terminated_or_interrupted(['TERM'])
  }

  # Initialize stats
  $RPC_MAP.values.each do |rpc|
    $num_rpcs_started_by_method[rpc.to_s] = 0
    $num_rpcs_succeeded_by_method[rpc.to_s] = 0
    $num_rpcs_failed_by_method[rpc.to_s] = 0
    $accumulated_method_stats[rpc.to_s] = StatsPerMethod.new
  end

  # The client just sends rpcs continuously in a regular interval
  stub = create_stub(opts)
  target_seconds_between_rpcs = (1.0 / opts['qps'].to_f)
  # Convert 'metadata' input in the form of
  #   rpc1:k1:v1,rpc2:k2:v2,rpc1:k3:v3
  # into
  #   {
  #     'rpc1' => {
  #       'k1' => 'v1',
  #       'k3' => 'v3',
  #     },
  #     'rpc2' => {
  #       'k2' => 'v2'
  #     },
  #   }
  rpcs_to_send = []
  metadata_to_send = {}
  if opts['metadata']
    metadata_entries = opts['metadata'].split(',')
    metadata_entries.each do |e|
      (rpc_name, metadata_key, metadata_value) = e.split(':')
      rpc_name = $RPC_MAP[rpc_name]
      # initialize if we haven't seen this rpc_name yet
      if !metadata_to_send.key?(rpc_name)
        metadata_to_send[rpc_name] = {}
      end
      metadata_to_send[rpc_name][metadata_key] = metadata_value
    end
  end
  if opts['rpc']
    rpcs_to_send = opts['rpc'].split(',')
  end
  if rpcs_to_send.size > 0
    rpcs_to_send.map! { |rpc| $RPC_MAP[rpc] }
    new_rpc_config = RpcConfig.new
    new_rpc_config.init(rpcs_to_send, metadata_to_send)
    $rpc_config = new_rpc_config
  end
  client_threads = Array.new
  opts['num_channels'].times {
    client_threads << Thread.new {
      run_test_loop(stub, target_seconds_between_rpcs,
                    opts['fail_on_failed_rpcs'])
    }
  }

  server_thread.join
  $shutdown = true
  client_threads.each { |thd| thd.join }
end

if __FILE__ == $0
  main
end


text:
namespace WSOL.Custom.ContentMaker.Samples.Models
{
    using System;
    using System.Runtime.Serialization;
    using WSOL.EktronCms.ContentMaker.Attributes;
    using WSOL.EktronCms.ContentMaker.Interfaces;
    using WSOL.EktronCms.ContentMaker.Models;

    /// <summary>
    /// Simple model for out of the box calendar events
    /// </summary>
    [Serializable]
    [ContentDescriptor(XmlConfigId = -120, Description = "Ektron Calendar Event Example")]
    public class CalendarEventContent : ContentType<ContentTypes.CalendarEvent.root>
    {
        public CalendarEventContent() { }

        public CalendarEventContent(IContent c, string xml) : base(c, xml) { }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
        }

        protected CalendarEventContent(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {

        }
    }
}


text:
/*
go-start is a high level web-framework for Go,
like Django for Python or Rails for Ruby.

	* Source: https://github.com/ungerik/go-start/
	* Documentation: http://godoc.org/github.com/ungerik/go-start

Note: Don't use Go on 32 bit systems in production, it has severe memory leaks.
(If the documentation URL above doesn't work, then godoc -html has has crashed because of that issue)

## Intro:

Features:

	* HTML views can be defined in Go syntax
	* Optional template system
	* HTML5 Boilerplate page template (Mustache template, will be changed to Go v1 template)
	* Unified data model for forms and databases
	* Data models are simple Go structs
	* MongoDB as default database
	* User management/authentication out of the box
	* Additional packages for
		* Email (Google Mail defaults): http://github.com/ungerik/go-mail
		* Gravatar: http://github.com/ungerik/go-gravatar
		* RSS parsing: http://github.com/ungerik/go-rss
		* Amiando event management: http://github.com/ungerik/go-amiando
			(used by http://startuplive.in)

Planned Features:

	* medialib
	* CSRF protection
	* Tutorial App
	* Remove web.go
	* Controller of MVC implemented as REST service
	* Support for LESS CSS
	* Support for Twitter Bootstrap

## Views:

The philosophy for creating HTML views is (unlike Rails/Django) that you should
not have to learn yet another language to be able to write templates.
There are several very simple template languages out there that reduce program
code like logic within the template, but it's still yet another syntax to learn.

In go-start the HTML structure of a page is represented by a structure of
type safe Go objects.
It should feel like writing HTML but using the syntax of Go.
And no, it has nothing to do with the mess of intertwined markup and code in PHP.

Example of a static view:

	view := Views{
		DIV("myclass",
			H1("Example HTML structure"),
			P("This is a paragraph"),
			P(
				HTML("Some unescaped HTML:<br/>"),
				Printf("The number of the beast: %d", 666),
				Escape("Will be escaped: 666 < 999"),
			),
			A_blank("http://go-lang.org", "A very simple link"),
		),
		HR(),
		PRE("	<- pre formated text, followed by a list:"),
		UL("red", "green", "blue"),
		&Template{
			Filename: "mytemplate.html",
			GetContext: func(requestContext *Context) (interface{}, error) {
				return map[string]string{"Key": "Value"}, nil
			},
		},
	}

Example of a dynamic view:

	view := DynamicView(
		func(ctx *Context) (view View, err error) {
			var names []string
			i := models.Users.Sort("Name.First").Sort("Name.Last").Iterator();
			for doc := i.Next(); doc != nil; doc = i.Next() {
				names = append(names, doc.(*models.User).Name.String())
			}
			if i.Err() != nil {
				return nil, i.Err()
			}
			return &List{	// List = higher level abstraction, UL() = shortcut
				Class: "my-ol",
				Ordered: true,
				Model: EscapeStringsListModel(names),
			}, nil
		},
	)

Beside DynamicView there is also a ModelIteratorView. It takes a model.Iterator
and creates a dynamic view for every iterated data item:

	view := &ModelIteratorView{
		GetModelIterator: func(ctx *Context) model.Iterator {
			return models.Users.Sort("Name.First").Sort("Name.Last").Iterator()
		},
		GetModelIteratorView: func(model interface{}, ctx *Context) (view View, err error) {
			user := model.(*models.User)
			return PrintfEscape("%s, ", user.Name), nil
		},
	}

## Pages and URLs:

	Homepage := &Page{
		OnPreRender: func(page *Page, ctx *Context) (err error) {
			context.Data = &PerPageData{...} // Set global page data at request context
		},
		WriteTitle: func(response *Response, writer io.Writer) (err error) {
			writer.Write([]byte(context.Data.(*PerPageData).DynamicTitle))
			return nil
		},
		CSS:          HomepageCSS,
		WriteHeader:  RSS("go-start.org RSS Feed", &RssFeed)
		WriteScripts: PageWriters(
			Config.Page.DefaultWriteScripts,
			JQuery,   // jQuery/UI is built-in
			JQueryUI,
			JQueryUIAutocompleteFromURL(".select-username", IndirectURL(&API_Usernames), 2),
			GoogleAnalytics(GoogleAnalyticsID), // Google Analytics is built-in
		)
		Content: Views{},
	}

	Admin_Auth := NewBasicAuth("go-start.org", "admin", "password123")

	func Paths() *ViewPath {
		return &ViewPath{View: Homepage, Sub: []ViewPath{                           // /
			{Name: "style.css", View: HomepageCSS},                             // /style.css
			{Name: "feed", View: RssFeed},                                      // /feed/
			{Name: "admin", View: Admin, Auth: Admin_Auth, Sub: []ViewPath{     // /admin/
				{Name: "user", Args: 1, View: Admin_User, Auth: Admin_Auth}, // /admin/user/<USER_ID>/
			}},
			{Name: "api", Sub: []ViewPath{                                      // 404 because no view defined
				{Name: "users.json", View: API_Usernames},                  // /api/users.json
			}},
		}
	}

	view.Init("go-start.org", CookieSecret, "pkg/myproject", "pkg/gostart") // Set site name, cookie secret and static paths
	view.Config.RedirectSubdomains = []string{"www"}     // Redirect from www.
	view.Config.Page.DefaultMetaViewport = "width=960px" // Page width for mobile devices
	view.RunConfigFile(Paths(), "run.config")            // Run server with path structure and values from config file

## Models:

Data is abstacted as models. The same model abstraction and data validation is
used for HTML forms and for databases. So a model can be loaded from a database,
displayed as an HTML form and saved back to the database after submit.
This is not always a good practice, but it shows how easy things can be.

A model is a simple Go struct that uses gostart/model types as struct members.
Custom model wide validation is done by adding a Validate() method to the
struct type:

	type SignupFormModel struct {
		Email     model.Email    `model:"required"`
		Password1 model.Password `view:"label=Password" model:"minlen=6"`
		Password2 model.Password `view:"label=Repeat password"`
	}

	func (self *SignupFormModel) Validate(metaData *model.MetaData) error {
		if self.Password1 != self.Password2 {
			return model.NewValidationErrors(os.NewError("Passwords don't match"), metaData)
		}
	errors := NoValidationErrors
		return model.NoValidationErrors
	}

Here is how a HTML form is created that displays input fields for the SignupFormModel:

	form := &Form{
		ButtonText: "Signup",
		FormID:     "user_signup",
		GetModel: func(form *Form, ctx *Context) (interface{}, error) {
			return &SignupFormModel{}, nil
		},
		OnSubmit: func(form *Form, formModel interface{}, response *Response) (err error) {
			m := formModel.(*SignupFormModel)
			// ... create user in db and send confirmation email ...
			return err
		},
	}

MongoDB is the default database of go-start utilizing Gustavo Niemeyer's
great lib mgo (http://labix.org/mgo).

Mongo collections and queries are encapsulated to make them compatible with the
go-start data model concept, and a little bit easier to use.

Example of a collection and document struct:

	var ExampleDocs *mongo.Collection = mongo.NewCollection("exampledocs", (*ExampleDoc)(nil))

	type ExampleDoc struct {
		mongo.DocumentBase `bson:",inline"`               // Give it a Mongo ID
		Person             mongo.Ref  `model:"to=people"` // Mongo ID ref to a document in "people" collection
		LongerText         model.Text `model:"maxlen=400" view:"rows=5|cols=80"`
		Integer            model.Int  `model:"min=1|max=100"`
		Email              model.Email    // Normalization + special treament in forms
		PhoneNumber        model.Phone    // Normalization + special treament in forms
		Password           model.Password // Hashed + special treament in forms
		SubDoc             struct {
			Day       model.Date
			Drinks    []mongo.Choice `model:"options=Beer,Wine,Water"` // Mongo array of strings
			RealFloat model.Float    `model:"valid" // Must be a real float value, not NaN or Inf
		}
	}

Example query:

	i := models.Users.Filter("Name.Last", "Smith").Sort("Name.First").Iterator();
	for doc := i.Next(); doc != nil; doc = i.Next() {
		user := doc.(*models.User)
		// ...
	}
	// Err() returns any error after Next() returned nil:
	if i.Err() != nil {
		panic(i.Err())
	}

A new mongo.Document is always created by the corresponding collection object
to initialize it with meta information about its collection.
This way it is possible to implement Save() or Remove() methods for the document.

Example for creating, modifying and saving a document:

	user := models.Users.NewDocument().(*models.User)

	user.Name.First.Set("Erik")
	user.Name.Last.Set("Unger")

	err := user.Save()

*/
package gostart


text:
#include "berryIVariableResolver.h"

namespace berry {

IVariableResolver::~IVariableResolver()
{
}

}


text:
package org.jboss.netty.handler.codec.embedder;

import static org.jboss.netty.channel.Channels.*;

import java.lang.reflect.Array;
import java.util.ConcurrentModificationException;
import java.util.LinkedList;
import java.util.Queue;

import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineException;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.ChannelUpstreamHandler;
import org.jboss.netty.channel.DefaultChannelPipeline;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;

/**
 * A skeletal {@link CodecEmbedder} implementation.
 *
 * @author The Netty Project
 * @author Trustin Lee
 * @version $Rev: 2121 $, $Date: 2010-02-02 09:38:07 +0900 (Tue, 02 Feb 2010) $
 */
abstract class AbstractCodecEmbedder<E> implements CodecEmbedder<E> {

    private final Channel channel;
    private final ChannelPipeline pipeline;
    private final EmbeddedChannelSink sink = new EmbeddedChannelSink();

    final Queue<Object> productQueue = new LinkedList<Object>();

    /**
     * Creates a new embedder whose pipeline is composed of the specified
     * handlers.
     */
    protected AbstractCodecEmbedder(ChannelHandler... handlers) {
        pipeline = new EmbeddedChannelPipeline();
        configurePipeline(handlers);
        channel = new EmbeddedChannel(pipeline, sink);
        fireInitialEvents();
    }

    /**
     * Creates a new embedder whose pipeline is composed of the specified
     * handlers.
     *
     * @param bufferFactory the {@link ChannelBufferFactory} to be used when
     *                      creating a new buffer.
     */
    protected AbstractCodecEmbedder(ChannelBufferFactory bufferFactory, ChannelHandler... handlers) {
        this(handlers);
        getChannel().getConfig().setBufferFactory(bufferFactory);
    }

    private void fireInitialEvents() {
        // Fire the typical initial events.
        fireChannelOpen(channel);
        fireChannelBound(channel, channel.getLocalAddress());
        fireChannelConnected(channel, channel.getRemoteAddress());
    }

    private void configurePipeline(ChannelHandler... handlers) {
        if (handlers == null) {
            throw new NullPointerException("handlers");
        }

        if (handlers.length == 0) {
            throw new IllegalArgumentException(
                    "handlers should contain at least one " +
                    ChannelHandler.class.getSimpleName() + '.');
        }

        for (int i = 0; i < handlers.length; i ++) {
            ChannelHandler h = handlers[i];
            if (h == null) {
                throw new NullPointerException("handlers[" + i + "]");
            }
            pipeline.addLast(String.valueOf(i), handlers[i]);
        }
        pipeline.addLast("SINK", sink);
    }

    public boolean finish() {
        fireChannelDisconnected(channel);
        fireChannelUnbound(channel);
        fireChannelClosed(channel);
        return !productQueue.isEmpty();
    }

    /**
     * Returns the virtual {@link Channel} which will be used as a mock
     * during encoding and decoding.
     */
    protected final Channel getChannel() {
        return channel;
    }

    /**
     * Returns {@code true} if and only if the produce queue is empty and
     * therefore {@link #poll()} will return {@code null}.
     */
    protected final boolean isEmpty() {
        return productQueue.isEmpty();
    }

    @SuppressWarnings("unchecked")
    public final E poll() {
        return (E) productQueue.poll();
    }

    @SuppressWarnings("unchecked")
    public final E peek() {
        return (E) productQueue.peek();
    }

    public final Object[] pollAll() {
        final int size = size();
        Object[] a = new Object[size];
        for (int i = 0; i < size; i ++) {
            E product = poll();
            if (product == null) {
                throw new ConcurrentModificationException();
            }
            a[i] = product;
        }
        return a;
    }

    @SuppressWarnings("unchecked")
    public final <T> T[] pollAll(T[] a) {
        if (a == null) {
            throw new NullPointerException("a");
        }

        final int size = size();

        // Create a new array if the specified one is too small.
        if (a.length < size) {
            a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
        }

        for (int i = 0;; i ++) {
            T product = (T) poll();
            if (product == null) {
                break;
            }
            a[i] = product;
        }

        // Put the terminator if necessary.
        if (a.length > size) {
            a[size] = null;
        }

        return a;
    }

    public final int size() {
        return productQueue.size();
    }

    private final class EmbeddedChannelSink implements ChannelSink, ChannelUpstreamHandler {
        EmbeddedChannelSink() {
            super();
        }

        public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) {
            handleEvent(e);
        }

        public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) {
            handleEvent(e);
        }

        private void handleEvent(ChannelEvent e) {
            if (e instanceof MessageEvent) {
                boolean offered = productQueue.offer(((MessageEvent) e).getMessage());
                assert offered;
            } else if (e instanceof ExceptionEvent) {
                throw new CodecEmbedderException(((ExceptionEvent) e).getCause());
            }

            // Swallow otherwise.
        }

        public void exceptionCaught(
                ChannelPipeline pipeline, ChannelEvent e,
                ChannelPipelineException cause) throws Exception {
            Throwable actualCause = cause.getCause();
            if (actualCause == null) {
                actualCause = cause;
            }

            throw new CodecEmbedderException(actualCause);
        }
    }

    private static final class EmbeddedChannelPipeline extends DefaultChannelPipeline {

        EmbeddedChannelPipeline() {
            super();
        }

        @Override
        protected void notifyHandlerException(ChannelEvent e, Throwable t) {
            while (t instanceof ChannelPipelineException && t.getCause() != null) {
                t = t.getCause();
            }
            if (t instanceof CodecEmbedderException) {
                throw (CodecEmbedderException) t;
            } else {
                throw new CodecEmbedderException(t);
            }
        }
    }
}


text:
require "spec_helper"

describe ActiveRemote::RPCAdapters::ProtobufAdapter do
  let(:adapter) { ActiveRemote::RPCAdapters::ProtobufAdapter.new(Tag.service_class, Tag.endpoints) }
  let(:client) { double(:client) }

  subject { adapter }

  # The Protobuf RPC client relies on method missing and delegations
  # Provide a client double to make it possible to add expectations that specific methods are called
  before { allow(adapter).to receive(:client).and_return(client) }

  describe "#execute" do
    context "when a custom endpoint is defined" do
      before { adapter.endpoints[:create] = :register }
      after { adapter.endpoints[:create] = :create }

      it "calls the custom endpoint" do
        expect(adapter.client).to receive(:register)
        adapter.execute(:create, :name => "foo")
      end
    end
  end
end


text:
<stix:STIX_Package
    xmlns:marking="http://data-marking.mitre.org/Marking-1"
    xmlns:tlpMarking="http://data-marking.mitre.org/extensions/MarkingStructure#TLP-1"
    xmlns:indicator="http://stix.mitre.org/Indicator-2"
    xmlns:stix="http://stix.mitre.org/stix-1"
    xmlns:cybox="http://cybox.mitre.org/cybox-2"
    xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
    xmlns:AddressObject="http://cybox.mitre.org/objects#AddressObject-2"
    xmlns:URIObj="http://cybox.mitre.org/objects#URIObject-2"
    xmlns:FileObj="http://cybox.mitre.org/objects#FileObject-2"
    xmlns:EmailMessageObj="http://cybox.mitre.org/objects#EmailMessageObject-2"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
    xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    id="example:Package-88139233-3c7d-4913-bb5e-d2aeb079d029" version="1.2" timestamp="2015-02-26T21:00:37.453000Z">
    <stix:Indicators>
        <stix:Indicator id="example:Indicator-8a822399-5d8a-44e4-abeb-15d480ea93c5"  timestamp="2014-05-08T09:00:00.000000Z" xsi:type='indicator:IndicatorType'>
            <indicator:Title>Malicious site hosting downloader</indicator:Title>
            <indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.1">URL Watchlist</indicator:Type>
            <indicator:Observable id="example:Observable-ee59c28e-d922-480e-9b7b-a79502696505">
                <cybox:Object id="example:URI-b13ae3fc-80af-49c2-9de9-f713abc070ba">
                    <cybox:Properties xsi:type="URIObj:URIObjectType" type="URL">
                        <URIObj:Value condition="Equals">http://x4z9arb.cn/4712</URIObj:Value>
                    </cybox:Properties>
                </cybox:Object>
            </indicator:Observable>
            <indicator:Handling>
                <marking:Marking>
                    <marking:Controlled_Structure>../../../descendant-or-self::node() | ../../../descendant-or-self::node()/@*</marking:Controlled_Structure>
                    <marking:Marking_Structure xsi:type='tlpMarking:TLPMarkingStructureType' color='WHITE'/>
                </marking:Marking>
            </indicator:Handling>
        </stix:Indicator>
        <stix:Indicator id="example:Indicator-53fe3b22-0201-47cf-85d0-97c02164528d" timestamp="2014-05-08T09:00:00.000000Z" xsi:type='indicator:IndicatorType'>
            <indicator:Title>IP Address for known C2 channel</indicator:Title>
            <indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.1">IP Watchlist</indicator:Type>
            <indicator:Observable  id="example:Observable-1c798262-a4cd-434d-a958-884d6980c459">
                <cybox:Object id="example:Object-1980ce43-8e03-490b-863a-ea404d12242e">
                    <cybox:Properties xsi:type="AddressObject:AddressObjectType" category="ipv4-addr">
                        <AddressObject:Address_Value condition="Equals">10.0.0.0</AddressObject:Address_Value>
                    </cybox:Properties>
                </cybox:Object>
            </indicator:Observable>
            <indicator:Handling>
                <marking:Marking>
                    <marking:Controlled_Structure>../../../descendant-or-self::node() | ../../../descendant-or-self::node()/@*</marking:Controlled_Structure>
                    <marking:Marking_Structure xsi:type='tlpMarking:TLPMarkingStructureType' color='GREEN'/>
                </marking:Marking>
            </indicator:Handling>
        </stix:Indicator>
        <stix:Indicator id="example:Indicator-14975dea-86cd-4211-a5f8-9c2e4daab69a" timestamp="2015-07-20T19:52:13.853585+00:00" xsi:type='indicator:IndicatorType'>
            <indicator:Title>File Reputation for SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855</indicator:Title>
            <indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.1">File Hash Watchlist</indicator:Type>
            <indicator:Observable id="example:Observable-7b97c8a2-2d0b-4af7-bcf0-cad28f2fea5a">
                <cybox:Object id="example:File-b04bfc7c-04ae-4dfe-ba8e-a297f0717552">
                    <cybox:Properties xsi:type="FileObj:FileObjectType">
                        <FileObj:Hashes>
                            <cyboxCommon:Hash>
                                <cyboxCommon:Type condition="Equals" xsi:type="cyboxVocabs:HashNameVocab-1.0">SHA256</cyboxCommon:Type>
                                <cyboxCommon:Simple_Hash_Value condition="Equals">e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855</cyboxCommon:Simple_Hash_Value>
                            </cyboxCommon:Hash>
                        </FileObj:Hashes>
                    </cybox:Properties>
                </cybox:Object>
            </indicator:Observable>
            <indicator:Handling>
                <marking:Marking>
                    <marking:Controlled_Structure>../../../descendant-or-self::node() | ../../../descendant-or-self::node()/@*</marking:Controlled_Structure>
                    <marking:Marking_Structure xsi:type='tlpMarking:TLPMarkingStructureType' color='AMBER'/>
                </marking:Marking>
            </indicator:Handling>
        </stix:Indicator>
        <stix:Indicator id="example:Indicator-8cf9236f-1b96-493d-98be-0c1c1e8b62d7" timestamp="2014-10-31T15:52:13.127931+00:00" xsi:type='indicator:IndicatorType'>
            <indicator:Title>Malicious E-mail</indicator:Title>
            <indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.1">Malicious E-mail</indicator:Type>
            <indicator:Observable id="example:Observable-437f0c20-ab26-4400-9f6a-fc395da3ddd9">
                <cybox:Object id="example:EmailMessage-0dc3478e-153a-412f-8718-7e9ee65b8084">
                    <cybox:Properties xsi:type="EmailMessageObj:EmailMessageObjectType">
                        <EmailMessageObj:Header>
                            <EmailMessageObj:Subject condition="StartsWith">[IMPORTANT] Please Review Before</EmailMessageObj:Subject>
                        </EmailMessageObj:Header>
                    </cybox:Properties>
                </cybox:Object>
            </indicator:Observable>
            <indicator:Handling>
                <marking:Marking>
                    <marking:Controlled_Structure>../../../descendant-or-self::node() | ../../../descendant-or-self::node()/@*</marking:Controlled_Structure>
                    <marking:Marking_Structure xsi:type='tlpMarking:TLPMarkingStructureType' color='RED'/>
                </marking:Marking>
            </indicator:Handling>
        </stix:Indicator>
    </stix:Indicators>
</stix:STIX_Package>


text:
import { html, fixture, expect } from '@open-wc/testing'

import '../dist/index.es.js'

describe('o-counter ', () => {
  it('default prop', async () => {
    const el = await fixture(html`<o-counter></o-counter>`)
    expect(el.shadowRoot.innerHTML).to.equal(
      `<button>-</button><span>1</span><button>+</button>`
    )
  })

  it('count prop', async () => {
    const el = await fixture(html`<o-counter count="2"></o-counter>`)
    expect(el.shadowRoot.innerHTML).to.equal(
      `<button>-</button><span>2</span><button>+</button>`
    )
  })
})


text:
(function() {
  'use strict';

  describe('Cinder API', function() {
    var testCall, service;
    var apiService = {};
    var toastService = {};

    beforeEach(
      module('horizon.mock.openstack-service-api',
        function($provide, initServices) {
          testCall = initServices($provide, apiService, toastService);
        })
    );

    beforeEach(module('horizon.app.core.openstack-service-api'));

    beforeEach(inject(['horizon.app.core.openstack-service-api.cinder', function(cinderAPI) {
      service = cinderAPI;
    }]));

    it('defines the service', function() {
      expect(service).toBeDefined();
    });

    var tests = [
      {
        func: 'getVolumes',
        method: 'get',
        path: '/api/cinder/volumes/',
        data: { params: 'config' },
        error: 'Unable to retrieve the volumes.',
        testInput: [ 'config' ]
      },
      {
        func: 'getVolumes',
        method: 'get',
        path: '/api/cinder/volumes/',
        data: {},
        error: 'Unable to retrieve the volumes.'
      },
      {
        func: 'getVolume',
        method: 'get',
        path: '/api/cinder/volumes/1',
        error: 'Unable to retrieve the volume.',
        testInput: [1]
      },
      {
        func: 'getVolumeMetadata',
        method: 'get',
        path: '/api/cinder/volumes/1/metadata',
        error: 'Unable to retrieve the volume metadata.',
        testInput: [1]
      },
      {
        func: 'getVolumeTypes',
        method: 'get',
        path: '/api/cinder/volumetypes/',
        error: 'Unable to retrieve the volume types.',
        testInput: []
      },
      {
        func: 'getVolumeType',
        method: 'get',
        path: '/api/cinder/volumetypes/1',
        error: 'Unable to retrieve the volume type.',
        testInput: [1]
      },
      {
        func: 'getVolumeTypeMetadata',
        method: 'get',
        path: '/api/cinder/volumetypes/1/metadata',
        error: 'Unable to retrieve the volume type metadata.',
        testInput: [1]
      },
      {
        func: 'getDefaultVolumeType',
        method: 'get',
        path: '/api/cinder/volumetypes/default',
        error: 'Unable to retrieve the default volume type.',
        testInput: []
      },
      {
        'func': 'getExtensions',
        'method': 'get',
        'path': '/api/cinder/extensions/',
        'data': 'config',
        'error': 'Unable to retrieve the extensions.',
        'testInput': [
          'config'
        ]
      },
      { func: 'getServices',
        method: 'get',
        path: '/api/cinder/services/',
        error: 'Unable to retrieve the cinder services.' },

      { func: 'getVolumeSnapshots',
        method: 'get',
        path: '/api/cinder/volumesnapshots/',
        data: {},
        error: 'Unable to retrieve the volume snapshots.'
      },
      {
        func: 'getVolumeSnapshots',
        method: 'get',
        path: '/api/cinder/volumesnapshots/',
        data: { params: 'config' },
        error: 'Unable to retrieve the volume snapshots.',
        testInput: [ 'config' ]
      },
      {
        func: 'getVolumeSnapshotMetadata',
        method: 'get',
        path: '/api/cinder/volumesnapshots/1/metadata',
        error: 'Unable to retrieve the snapshot metadata.',
        testInput: [1]
      },
      {
        func: 'createVolume',
        method: 'post',
        path: '/api/cinder/volumes/',
        data: { params: 'config' },
        error: 'Unable to create the volume.',
        testInput: [
          {
            params: 'config'
          }
        ]
      },
      {
        func: 'getQoSSpecs',
        method: 'get',
        path: '/api/cinder/qosspecs/',
        data: {},
        error: 'Unable to retrieve the QoS Specs.'
      },
      {
        func: 'getQoSSpecs',
        method: 'get',
        path: '/api/cinder/qosspecs/',
        data: { params: 'config' },
        error: 'Unable to retrieve the QoS Specs.',
        testInput: [ 'config' ]
      },
      {
        func: 'getDefaultQuotaSets',
        method: 'get',
        path: '/api/cinder/quota-sets/defaults/',
        error: 'Unable to retrieve the default quotas.'
      },
      {
        func: 'setDefaultQuotaSets',
        "data": {
          "id": 42
        },
        "testInput": [
          {
            "id": 42
          }
        ],
        method: 'patch',
        path: '/api/cinder/quota-sets/defaults/',
        error: 'Unable to set the default quotas.'
      },
      { func: 'updateProjectQuota',
        method: 'patch',
        path: '/api/cinder/quota-sets/42',
        data: {'volumes': 42},
        error: 'Unable to update project quota data.',
        testInput: [{'volumes': 42}, 42]
      },
      { func: 'editVolumeMetadata',
        method: 'patch',
        path: '/api/cinder/volumes/42/metadata',
        data: {
          "updated": {a: '1', b: '2'},
          "removed": ['c', 'd']
        },
        error: "Unable to edit volume metadata.",
        testInput: [
          42, {a: '1', b: '2'}, ['c', 'd']
        ]
      },
      { func: 'editVolumeSnapshotMetadata',
        method: 'patch',
        path: '/api/cinder/volumesnapshots/42/metadata',
        data: {
          "updated": {a: '1', b: '2'},
          "removed": ['c', 'd']
        },
        error: "Unable to edit snapshot metadata.",
        testInput: [
          42, {a: '1', b: '2'}, ['c', 'd']
        ]
      },
      { func: 'editVolumeTypeMetadata',
        method: 'patch',
        path: '/api/cinder/volumetypes/42/metadata',
        data: {
          "updated": {a: '1', b: '2'},
          "removed": ['c', 'd']
        },
        error: "Unable to edit volume type metadata.",
        testInput: [
          42, {a: '1', b: '2'}, ['c', 'd']
        ]
      }
    ];

    // Iterate through the defined tests and apply as Jasmine specs.
    angular.forEach(tests, function(params) {
      it('defines the ' + params.func + ' call properly', function() {
        var callParams = [apiService, service, toastService, params];
        testCall.apply(this, callParams);
      });
    });

  });

})();


text:
define(["solv/array/is-empty"], function () {
	"use strict";

	describe("array.isEmpty", function () {
		var array;

		beforeEach(function () {
			array = [1,2,3];
		});

		it("should return true if array has 0 length", function () {
			expect([].isEmpty()).toBe(true);
		});

		it("should return false if array has length", function () {
			expect(array.isEmpty()).toBe(false);
		});

		it("should return true even if array used to have length", function () {
			array.length = 0;
			expect(array.isEmpty()).toBe(true);
		});

		it("should return true even if array items are falsey", function () {
			expect([null].isEmpty()).toBe(false);
		});

		it("should return false if items are added with push", function () {
			array = [];
			array.push(1);
			expect(array.isEmpty()).toBe(false);
		});

		it("should return true if all items are removed with pop", function () {
			array.pop();
			array.pop();
			array.pop();
			expect(array.isEmpty()).toBe(true);
		});
	});
});


text:
/*!
** @file PE_Const.h
** @version 01.00
** @brief
**         This component "PE_Const" contains internal definitions
**         of the constants.
*/
/*!
**  @addtogroup PE_Const_module PE_Const module documentation
**  @{
*/

#ifndef __PE_Const_H
#define __PE_Const_H

/* Constants for detecting running mode */
#define HIGH_SPEED        0x00U        /* High speed */
#define LOW_SPEED         0x01U        /* Low speed */
#define SLOW_SPEED        0x02U        /* Slow speed */

/* Reset cause constants */
#define RSTSRC_POR        0x80U        /* Power-on reset        */
#define RSTSRC_PIN        0x40U        /* External reset bit    */
#define RSTSRC_COP        0x20U        /* COP reset             */
#define RSTSRC_ILOP       0x10U        /* Illegal opcode reset  */
#define RSTSRC_ILAD       0x08U        /* Illegal address reset */
#define RSTSRC_MODRST     0x04U        /* Normal Monitor Mode Entry Reset*/
#define RSTSRC_MENRST     0x04U        /* Forced Monitor Mode Entry Reset*/
#define RSTSRC_LVI        0x02U        /* Low voltage inhibit reset */

#endif /* _PE_Const_H */
/*!
** @}
*/
/*
** ###################################################################
**
**     This file was created by Processor Expert 10.3 [05.09]
**     for the Freescale HCS08 series of microcontrollers.
**
** ###################################################################
*/


text:
namespace content {
namespace background_sync_test_util {

namespace {

StoragePartitionImpl* GetStoragePartition(WebContents* web_contents) {
  return static_cast<StoragePartitionImpl*>(
      web_contents->GetBrowserContext()->GetStoragePartition(
          web_contents->GetSiteInstance()));
}

}  // namespace

// static
void SetIgnoreNetworkChanges(bool ignore) {
  BackgroundSyncNetworkObserver::SetIgnoreNetworkChangesForTests(ignore);
}

// static
void SetOnline(WebContents* web_contents, bool online) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  BackgroundSyncContextImpl* sync_context =
      GetStoragePartition(web_contents)->GetBackgroundSyncContext();
  BackgroundSyncManager* sync_manager = sync_context->background_sync_manager();
  BackgroundSyncNetworkObserver* network_observer =
      sync_manager->GetNetworkObserverForTesting();
  if (online) {
    network_observer->NotifyManagerIfConnectionChangedForTesting(
        network::mojom::ConnectionType::CONNECTION_WIFI);
  } else {
    network_observer->NotifyManagerIfConnectionChangedForTesting(
        network::mojom::ConnectionType::CONNECTION_NONE);
  }

  base::RunLoop().RunUntilIdle();
}

}  // namespace background_sync_test_util

}  // namespace content


text:
package com.ycombinator.news.cache;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.ycombinator.news.dto.ItemDTO;
import com.ycombinator.news.dto.ItemId;

public interface QuickCache
{
    void put(@NonNull ItemDTO itemDTO);

    @Nullable ItemDTO get(@NonNull ItemId itemId);

    void clear();

    public static class Instance
    {
        // Poorman's dependency injection
        public static QuickCache get()
        {
            return QuickCacheImpl.getInstance();
        }
    }
}


text:
function Env(parent) {
    this.parent = parent;
    // I use JS's prototype inheritance to implement looking up
    // bindings in the parent scope.
    this.bindings = parent ? Object.create(parent.bindings) : {};
    this.macros = parent ? parent.macros : [];
};

Env.prototype.resolve = function (sym) {
    var res = this.bindings[sym];
    // We must avoid resolving default fields of objects like toString
    if (res !== {}[sym]) return res
    else throw Error("Could not resolve symbol: " + sym);
};

Env.prototype.register = function (guard, handler) {
    this.macros.push({guard: guard, handler: handler});
};

Env.prototype.getHandler = function (signature) {
    // signature is a string like "E + E" or "E ( E ) _" that
    // describes the kind of node we're trying to handle. E stands for
    // an expression whereas _ means there is nothing there.
    // Handlers either match the exact string or a regular expression
    for (var i = 0; i < this.macros.length; i++) {
        var m = this.macros[i];
        if (m.guard instanceof RegExp && signature.match(m.guard)
            || m.guard === signature)
            return m.handler;
    }
    throw Error("Unknown signature: " + signature);
};

Env.prototype.run = function(node) {
    switch (node.type) {
    case "op":
    case "id":  return this.resolve(node.token);
    case "num": return parseInt(node.token);
    case "str": return node.token.substring(1, node.token.length - 1).replace('\\"', '"');
    case "inner":
        // Handler for the node's signature is called with the node as
        // its first argument and the node's actual arguments as its
        // second, ... arguments. For instance, the handler for "a + b"
        // would be called as handler.call(this, node, a, b).
        return this.getHandler(node.signature).apply(this, [node].concat(node.args));
    default:
        throw SyntaxError("Unknown leaf type: " + node.type);
    }
};

function finalize(node) {
    // This is given to Parser::parse as a callback. It reformats the
    // parser's output to be a bit easier to manipulate.
    // a + b ==> [[null, tok(a), null], tok(+), [null, tok(b), null]] (parser)
    //       ==> {type: "inner", args: [tok(a), tok(b)], signature: "E + E"} (finalize)
    if (node.length === 3 && node[0] === null && node[2] === null)
        return node[1];
    return {type: "inner",
            orig: node,
            args: node.filter(function (x, i) { return i % 2 == 0; }),
            signature: node.map(function (x, i) {
                if (i % 2 == 0)
                    return x === null ? "_" : "E"
                else
                    return x.token
            }).join(" ")};
}

///////////////////
/// INTERPRETER ///
///////////////////

var base = new Env();

function applyCall(env, fargs) {
    var fn = env.run(fargs[0]);
    return fn.apply(null, fargs[1].map(function (arg) {
        if (fn.lazy) return function () {return env.run(arg);};
        else         return env.run(arg);
    }));
}

function makeFunction(env, argnames, body) {
    return function () {
        var args = arguments;
        var e = new Env(env);
        argnames.forEach(function (n, i) {
            e.bindings[n.token] = args[i];
        });
        return e.run(body);
    };
}

function extractArgs(guard, node, strict) {
    // This checks that the node has a certain form and returns a list
    // of its non-null arguments. For instance,
    // extractArgs("E + E", node) will check that node is an addition
    // and will return a list of its two operands. If it is not an
    // addition, it returns null or throws an error depending on the
    // value of strict.
    if (node && (node.signature
                 && guard instanceof RegExp
                 && node.signature.match(guard)
                 || guard === node.signature))
        return node.args.filter(function (x) { return x !== null; });
    if (strict)
        throw Error("Expected '"+guard+"' but got '"+node.signature+"'");
    return null;
}

function listify(node) {
    // Basically if given "a, b, c" this returns [a, b, c], and given
    // "a" this returns [a]. It's a kind of normalization, really.
    return extractArgs(/^[E_]( [;,\n] [E_])+$/, node) || (node ? [node] : []);
}

function normalizeCall(node) {
    // Given either "a + b" or "(+)(a, b)" this returns [+, [a, b]].
    var args;
    if (args = extractArgs(/^[E_] [^ ]+ [E_]$/, node))
        return [node.orig[1], args];
    else if (args = extractArgs(/^E \( [E_] \) _$/, node))
        return [args[0], listify(args[1])];
    return null;
}

function normalizeAssignment(node) {
    // Given "a = b" this returns [a, null, b]
    // Given "f(a) = b" this returns [f, [a], b]
    var lr = extractArgs("E = E", node, true);
    var fargs;
    if (fargs = normalizeCall(lr[0])) return [fargs[0], fargs[1], lr[1]];
    else return [lr[0], null, lr[1]];
}

// The language's basic features follow. I think they are mostly
// straightforward.

base.register(/^[E_]( [;,\n] [E_])+$/, function (node) {
    var self = this;
    return listify(node).map(function (arg) { return self.run(arg); }).pop();
});

base.register("_ ( E ) _", function (node, _, x, _) { return this.run(x); });
base.register("_ begin E end _", function(node, _, x, _) {return this.run(x);});
base.register(/^E \( [E_] \) _$/, function (node, f, x, _) {
    return applyCall(this, normalizeCall(node));
});

// [a, b, ...] defines a list
base.register("_ [ E ] _", function (node, _, x, _) {
    var self = this;
    return listify(x).map(function (x) { return self.run(x); });
});
// a[b] indexes a list; notice the E before the [, unlike above
base.register("E [ E ] _", function (node, l, x, _) {
    return this.run(l)[this.run(x)];
});

base.register(/^_ if E then E( elif E then E)* else E end _$/,
    function (node) {
        var args = [].slice.call(arguments, 2, -1);
        for (var i = 0; i < args.length - 1; i += 2) {
            if (this.run(args[i])) return this.run(args[i + 1]);
        }
        return this.run(args[i]);
    });

base.register("_ let E in E end _", function (node, _, defn, body, _) {
    var e = new Env(this);
    listify(defn).forEach(function (d) {
        var args = normalizeAssignment(d);
        if (args[1])
            e.bindings[args[0].token] = makeFunction(e, args[1], args[2]);
        else
            e.bindings[args[0].token] = e.run(args[2]);
    });
    return e.run(body);
});

base.register("E -> E", function (node, defn, body) {
    var argnames = listify((extractArgs("_ ( E ) _", defn) || [defn])[0]);
    return makeFunction(this, argnames, body);
});

base.register("E each E", function (node, lst, op) {
    return this.run(lst).map(this.run(op));
});

// Default fallback for unknown binary operators
base.register(/^[E_] [^ ()\[\]\{\}]+ [E_]$/, function (node) {
    return applyCall(this, normalizeCall(node));
});

function lazy(f) { f.lazy = true; return f; }
// These are the global bindings of the language.
base.bindings = {
    "+":  function (x, y) { return x + y; },
    "-":  function (x, y) { return y === undefined ? -x : x - y; },
    "*":  function (x, y) { return x * y; },
    "/":  function (x, y) { return x / y; },
    "^":  Math.pow,
    "==": function (x, y) { return x == y; },
    "!=": function (x, y) { return x != y; },
    "<":  function (x, y) { return x < y; },
    "<=": function (x, y) { return x <= y; },
    ">":  function (x, y) { return x > y; },
    ">=": function (x, y) { return x >= y; },
    "..": function (start, end) {
        return Array.apply(null, Array(end - start)).map(function (_, i) {
            return i + start;
        });
    },
    and:  lazy(function (x, y) { return x() && y(); }),
    or:   lazy(function (x, y) { return x() || y(); }),
    not:  function (x) { return !x; },
    log:  Math.log,
    sin:  Math.sin,
    cos:  Math.cos,
    tan:  Math.tan,
    true: true,
    false: false
}

function exec(s, parser) {
    var tree = parser.parse(s, finalize);
    var e = new Env(base);
    return e.run(tree);
}

exports.core = Env;
exports.exec = exec;


text:
//-----------------------------------------------------------------------
// <copyright file="WatchedActorTerminatedException.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System.Runtime.Serialization;
using Akka.Actor;
using Akka.Streams.Dsl;

namespace Akka.Streams
{
    /// <summary>
    /// Used as failure exception by an `ask` operator if the target actor terminates.
    /// </summary>
    /// <seealso cref="Flow{TIn,TOut,TMat}.Ask{TOut2}"/>
    /// <seealso cref="Source{TOut,TMat}.Ask{TOut2}"/>
    /// <seealso cref="FlowOperations.Watch{T,TMat}"/>
    /// <seealso cref="SourceOperations.Watch{T,TMat}"/>
    public class WatchedActorTerminatedException : AkkaException
    {
        public WatchedActorTerminatedException(string stageName, IActorRef actorRef)
            : base($"Actor watched by [{stageName}] has terminated! Was: {actorRef}")
        { }

#if SERIALIZATION
        /// <summary>
        /// Initializes a new instance of the <see cref="AkkaException"/> class.
        /// </summary>
        /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
        protected WatchedActorTerminatedException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.share.long_screenshots.bitmap_generation;

import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;

/**
 * The Java-side implementations of long_screenshots_tab_service_factory.cc. Provides an instance of
 * {@link LongScreenshotsTabService}.
 */
@JNINamespace("long_screenshots")
public class LongScreenshotsTabServiceFactory {
    public static LongScreenshotsTabService getServiceInstance() {
        return LongScreenshotsTabServiceFactoryJni.get().getServiceInstanceForCurrentProfile();
    }

    @NativeMethods
    interface Natives {
        LongScreenshotsTabService getServiceInstanceForCurrentProfile();
    }

    private LongScreenshotsTabServiceFactory() {}
}


text:
package resolver

import (
	"testing"

	"helm.sh/helm/v3/pkg/chart"
)

func TestResolve(t *testing.T) {
	tests := []struct {
		name   string
		req    []*chart.Dependency
		expect *chart.Lock
		err    bool
	}{
		{
			name: "version failure",
			req: []*chart.Dependency{
				{Name: "oedipus-rex", Repository: "http://example.com", Version: ">a1"},
			},
			err: true,
		},
		{
			name: "cache index failure",
			req: []*chart.Dependency{
				{Name: "oedipus-rex", Repository: "http://example.com", Version: "1.0.0"},
			},
			expect: &chart.Lock{
				Dependencies: []*chart.Dependency{
					{Name: "oedipus-rex", Repository: "http://example.com", Version: "1.0.0"},
				},
			},
		},
		{
			name: "chart not found failure",
			req: []*chart.Dependency{
				{Name: "redis", Repository: "http://example.com", Version: "1.0.0"},
			},
			err: true,
		},
		{
			name: "constraint not satisfied failure",
			req: []*chart.Dependency{
				{Name: "alpine", Repository: "http://example.com", Version: ">=1.0.0"},
			},
			err: true,
		},
		{
			name: "valid lock",
			req: []*chart.Dependency{
				{Name: "alpine", Repository: "http://example.com", Version: ">=0.1.0"},
			},
			expect: &chart.Lock{
				Dependencies: []*chart.Dependency{
					{Name: "alpine", Repository: "http://example.com", Version: "0.2.0"},
				},
			},
		},
		{
			name: "repo from valid local path",
			req: []*chart.Dependency{
				{Name: "signtest", Repository: "file://../../../../cmd/helm/testdata/testcharts/signtest", Version: "0.1.0"},
			},
			expect: &chart.Lock{
				Dependencies: []*chart.Dependency{
					{Name: "signtest", Repository: "file://../../../../cmd/helm/testdata/testcharts/signtest", Version: "0.1.0"},
				},
			},
		},
		{
			name: "repo from invalid local path",
			req: []*chart.Dependency{
				{Name: "notexist", Repository: "file://../testdata/notexist", Version: "0.1.0"},
			},
			err: true,
		},
		{
			name: "repo from valid path under charts path",
			req: []*chart.Dependency{
				{Name: "localdependency", Repository: "", Version: "0.1.0"},
			},
			expect: &chart.Lock{
				Dependencies: []*chart.Dependency{
					{Name: "localdependency", Repository: "", Version: "0.1.0"},
				},
			},
		},
		{
			name: "repo from invalid path under charts path",
			req: []*chart.Dependency{
				{Name: "nonexistentdependency", Repository: "", Version: "0.1.0"},
			},
			expect: &chart.Lock{
				Dependencies: []*chart.Dependency{
					{Name: "nonexistentlocaldependency", Repository: "", Version: "0.1.0"},
				},
			},
			err: true,
		},
	}

	repoNames := map[string]string{"alpine": "kubernetes-charts", "redis": "kubernetes-charts"}
	r := New("testdata/chartpath", "testdata/repository")
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			l, err := r.Resolve(tt.req, repoNames)
			if err != nil {
				if tt.err {
					return
				}
				t.Fatal(err)
			}

			if tt.err {
				t.Fatalf("Expected error in test %q", tt.name)
			}

			if h, err := HashReq(tt.req, tt.expect.Dependencies); err != nil {
				t.Fatal(err)
			} else if h != l.Digest {
				t.Errorf("%q: hashes don't match.", tt.name)
			}

			// Check fields.
			if len(l.Dependencies) != len(tt.req) {
				t.Errorf("%s: wrong number of dependencies in lock", tt.name)
			}
			d0 := l.Dependencies[0]
			e0 := tt.expect.Dependencies[0]
			if d0.Name != e0.Name {
				t.Errorf("%s: expected name %s, got %s", tt.name, e0.Name, d0.Name)
			}
			if d0.Repository != e0.Repository {
				t.Errorf("%s: expected repo %s, got %s", tt.name, e0.Repository, d0.Repository)
			}
			if d0.Version != e0.Version {
				t.Errorf("%s: expected version %s, got %s", tt.name, e0.Version, d0.Version)
			}
		})
	}
}

func TestHashReq(t *testing.T) {
	expect := "sha256:fb239e836325c5fa14b29d1540a13b7d3ba13151b67fe719f820e0ef6d66aaaf"

	tests := []struct {
		name         string
		chartVersion string
		lockVersion  string
		wantError    bool
	}{
		{
			name:         "chart with the expected digest",
			chartVersion: "0.1.0",
			lockVersion:  "0.1.0",
			wantError:    false,
		},
		{
			name:         "ranged version but same resolved lock version",
			chartVersion: "^0.1.0",
			lockVersion:  "0.1.0",
			wantError:    true,
		},
		{
			name:         "ranged version resolved as higher version",
			chartVersion: "^0.1.0",
			lockVersion:  "0.1.2",
			wantError:    true,
		},
		{
			name:         "different version",
			chartVersion: "0.1.2",
			lockVersion:  "0.1.2",
			wantError:    true,
		},
		{
			name:         "different version with a range",
			chartVersion: "^0.1.2",
			lockVersion:  "0.1.2",
			wantError:    true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := []*chart.Dependency{
				{Name: "alpine", Version: tt.chartVersion, Repository: "http://localhost:8879/charts"},
			}
			lock := []*chart.Dependency{
				{Name: "alpine", Version: tt.lockVersion, Repository: "http://localhost:8879/charts"},
			}
			h, err := HashReq(req, lock)
			if err != nil {
				t.Fatal(err)
			}
			if !tt.wantError && expect != h {
				t.Errorf("Expected %q, got %q", expect, h)
			} else if tt.wantError && expect == h {
				t.Errorf("Expected not %q, but same", expect)
			}
		})
	}
}

func TestGetLocalPath(t *testing.T) {
	tests := []struct {
		name      string
		repo      string
		chartpath string
		expect    string
		err       bool
	}{
		{
			name:   "absolute path",
			repo:   "file:////tmp",
			expect: "/tmp",
		},
		{
			name:      "relative path",
			repo:      "file://../../../../cmd/helm/testdata/testcharts/signtest",
			chartpath: "foo/bar",
			expect:    "../../cmd/helm/testdata/testcharts/signtest",
		},
		{
			name:      "current directory path",
			repo:      "../charts/localdependency",
			chartpath: "testdata/chartpath/charts",
			expect:    "testdata/chartpath/charts/localdependency",
		},
		{
			name:      "invalid local path",
			repo:      "file://../testdata/notexist",
			chartpath: "testdata/chartpath",
			err:       true,
		},
		{
			name:      "invalid path under current directory",
			repo:      "../charts/nonexistentdependency",
			chartpath: "testdata/chartpath/charts",
			err:       true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			p, err := GetLocalPath(tt.repo, tt.chartpath)
			if err != nil {
				if tt.err {
					return
				}
				t.Fatal(err)
			}
			if tt.err {
				t.Fatalf("Expected error in test %q", tt.name)
			}
			if p != tt.expect {
				t.Errorf("%q: expected %q, got %q", tt.name, tt.expect, p)
			}
		})
	}
}


text:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* child process */
execlp("/bin/ls","ls",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
wait(NULL);
printf("Child Complete");
}

return 0;
}


text:
JSON
====
Simple json parsing. Uses json-c. Will throw exceptions if wrong datatype is used.

```C++

#include <json/json.h>

JSon json;
int trackid;
string name;
json.add("uid", trackid);
json.add("name", name);
json.add("version", API_VERSION);
auto sl = json.add_array("songs");
for(const SongInfo &info : songs) {
    sl.add(info.path);
}
```

```C++
    JSon json = JSon::parse(result);
    for(auto pl : json["urls"]) {
        list.emplace_back(pl.to_string());
    }
```


text:
namespace Tradier.Features {
    public interface IWatchlistsFeature {
        TradierClient Client { get; }
    }
}


text:
context('Misc', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/misc');
  });

  it('.end() - end the command chain', () => {
    // https://on.cypress.io/end

    // cy.end is useful when you want to end a chain of commands
    // and force Cypress to re-query from the root element
    cy.get('.misc-table').within(() => {
      // ends the current chain and yields null
      cy.contains('Cheryl').click().end();

      // queries the entire table again
      cy.contains('Charles').click();
    });
  });

  it('cy.exec() - execute a system command', () => {
    // execute a system command.
    // so you can take actions necessary for
    // your test outside the scope of Cypress.
    // https://on.cypress.io/exec

    // we can use Cypress.platform string to
    // select appropriate command
    // https://on.cypress/io/platform
    cy.log(`Platform ${Cypress.platform} architecture ${Cypress.arch}`);

    // on CircleCI Windows build machines we have a failure to run bash shell
    // https://github.com/cypress-io/cypress/issues/5169
    // so skip some of the tests by passing flag "--env circle=true"
    const isCircleOnWindows = Cypress.platform === 'win32' && Cypress.env('circle');

    if (isCircleOnWindows) {
      return;
    }

    cy.exec('echo Jane Lane').its('stdout').should('contain', 'Jane Lane');

    if (Cypress.platform === 'win32') {
      cy.exec('print cypress.json').its('stderr').should('be.empty');
    } else {
      cy.exec('cat cypress.json').its('stderr').should('be.empty');

      cy.exec('pwd').its('code').should('eq', 0);
    }
  });

  it('cy.focused() - get the DOM element that has focus', () => {
    // https://on.cypress.io/focused
    cy.get('.misc-form').find('#name').click();
    cy.focused().should('have.id', 'name');

    cy.get('.misc-form').find('#description').click();
    cy.focused().should('have.id', 'description');
  });

  context('Cypress.Screenshot', function () {
    it('cy.screenshot() - take a screenshot', () => {
      // https://on.cypress.io/screenshot
      cy.screenshot('my-image');
    });

    it('Cypress.Screenshot.defaults() - change default config of screenshots', function () {
      Cypress.Screenshot.defaults({
        blackout: ['.foo'],
        capture: 'viewport',
        clip: { x: 0, y: 0, width: 200, height: 200 },
        scale: false,
        disableTimersAndAnimations: true,
        screenshotOnRunFailure: true,
        beforeScreenshot() {},
        afterScreenshot() {},
      });
    });
  });

  it('cy.wrap() - wrap an object', () => {
    // https://on.cypress.io/wrap
    cy.wrap({ foo: 'bar' }).should('have.property', 'foo').and('include', 'bar');
  });
});