text:
CREATE DATABASE Exercises
USE Exercises

--Problem 1.One-To-One Relationship
CREATE TABLE Passports
(
PassportId INT NOT NULL,
PassportNumber NVARCHAR(50) NOT NULL,
)
CREATE TABLE Persons
(
PersonId INT NOT NULL,
FirstName NVARCHAR(50) NOT NULL,
Salary DECIMAL(8,2),
PassportId INT NOT NULL
)

INSERT INTO Persons VALUES
(1,'Roberto',43300.00,102),
(2,'Tom',56100.00,103),
(3,'Yana',60200.00,101)

INSERT INTO Passports VALUES
(101,'N34FG21B'),
(102,'K65LO4R7'),
(103,'ZE657QP2')

ALTER TABLE Persons
ADD CONSTRAINT PK_PersonId
PRIMARY KEY (PersonId)

ALTER TABLE Passports
ADD CONSTRAINT PK_PassportsId
PRIMARY KEY (PassportId)

ALTER TABLE Persons
ADD CONSTRAINT FK_PassportId
FOREIGN KEY (PassportId)
REFERENCES Passports(PassportId)

--Problem 2.One-To-Many Relationship
CREATE  TABLE Models
(
	ModelID int NOT NULL,
	Name varchar(50),
	ManufacturerID int NOT NULL
)

CREATE TABLE Manufacturers
(
	ManufacturerID int NOT NULL,
	Name varchar(50),
	EstablishedOn date
)

INSERT INTO Models VALUES
(101,'X1',1),
(102,'i6',1),
(103,'Model S',2),
(104,'Model X',2),
(105,'Model 3',2),
(106,'Nova',3)

INSERT INTO Manufacturers VALUES
(1,'BMW','1916-03-07'),
(2,'Tesla','2003-01-01'),
(3,'Lada','1966-05-01')

ALTER TABLE Manufacturers
ADD CONSTRAINT PK_ManufacterId
PRIMARY KEY (ManufacturerID)

ALTER TABLE Models
ADD CONSTRAINT PK_ModelID
PRIMARY KEY (ModelID)

ALTER TABLE Models
ADD CONSTRAINT FK_ManufacturerID
FOREIGN KEY (ManufacturerID)
REFERENCES Manufacturers(ManufacturerID)

--Problem 3.Many-To-Many Relationship
CREATE TABLE Students
(
	StudentID int NOT NULL,
	Name varchar(50) NOT NULL,
)

CREATE TABLE Exams
(
	ExamID int NOT NULL,
	Name varchar(50) NOT NULL
)

CREATE TABLE StudentsExams
(
	StudentID int NOT NULL,
	ExamID int NOT NULL
)

INSERT INTO Students VALUES
(1,'Mila'),
(2,'Toni'),
(3,'Ron')

INSERT INTO Exams VALUES
(101,'SpringMVC'),
(102,'Neo4j'),
(103,'Oracle 11g')

INSERT INTO StudentsExams VALUES
(1,101),
(1,102),
(2,101),
(3,103),
(2,102),
(2,103)

ALTER TABLE Students
ADD CONSTRAINT PK_StudentID
PRIMARY KEY (StudentID)

ALTER TABLE Exams
ADD CONSTRAINT PK_ExamID
PRIMARY KEY (ExamID)

ALTER TABLE StudentsExams
ADD CONSTRAINT PK_StudentID_ExamID
PRIMARY KEY (StudentID, ExamID)

ALTER TABLE StudentsExams
ADD CONSTRAINT FK_StudentID_StudentsID
FOREIGN KEY (StudentID)
REFERENCES Students(StudentID)

ALTER TABLE StudentsExams
ADD CONSTRAINT FK_ExamID_ExamID
FOREIGN KEY (ExamID)
REFERENCES Exams(ExamID)

--Problem 4.Self-Referencing
CREATE TABLE Teachers
(
	TeacherID int PRIMARY KEY IDENTITY(101,1),
	Name varchar(50) NOT NULL,
	ManagerID int
)

INSERT INTO Teachers VALUES
('John', NULL),
('Maya', 106),
('Silvia', 106),
('Ted', 105),
('Mark', 101),
('Greta', 101)

ALTER TABLE Teachers
ADD CONSTRAINT FK_TeacherID_ManagerID
FOREIGN KEY (ManagerID)
REFERENCES Teachers(TeacherID)

--Problem 5.Online Store Database
CREATE TABLE Orders
(
	OrderID int PRIMARY KEY,
	CustomerID int
)

CREATE TABLE Customers
(
	CustomerID int PRIMARY KEY,
	Name varchar(50) NOT NULL,
	Birthday date,
	CityID int
)

CREATE TABLE Cities
(
	CityID int PRIMARY KEY,
	Name varchar(50)
)

CREATE TABLE OrderItems
(
	OrderID int NOT NULL,
	ItemID int NOT NULL
)

CREATE TABLE Items
(
	ItemID int PRIMARY KEY,
	Name varchar(50),
	ItemTypeID int
)

CREATE TABLE ItemTypes
(
	ItemTypeID int PRIMARY KEY,
	Name varchar(50)
)
ALTER TABLE OrderItems
ADD CONSTRAINT PK_OrderID_ItemID
PRIMARY KEY (OrderId, ItemID)

ALTER TABLE Orders
ADD CONSTRAINT FK_CustomerID_CustomerID
FOREIGN KEY (CustomerID)
REFERENCES Customers (CustomerID)

ALTER TABLE Customers
ADD CONSTRAINT FK_CityID_CityID
FOREIGN KEY (CityID)
REFERENCES Cities(CityID)

ALTER TABLE OrderItems
ADD CONSTRAINT FK_OrderID_OrderID
FOREIGN KEY (OrderID)
REFERENCES Orders(OrderID)

ALTER TABLE OrderItems
ADD CONSTRAINT FK_ItemID_ItemID
FOREIGN KEY (ItemID)
REFERENCES Items(ItemID)

ALTER TABLE Items
ADD CONSTRAINT FK_ItemTypeID_ItemTypeID
FOREIGN KEY (ItemTypeId)
REFERENCES ItemTypes(ItemTypeID)

--Problem 6.University Database
CREATE TABLE Majors
(
	MajorID int PRIMARY KEY,
	Name varchar(50)
)

CREATE TABLE Students
(
	StudentID int PRIMARY KEY,
	StudentNumber int,
	StudentName varchar(50),
	MajorID int
)

CREATE TABLE Payments
(
	PaymentID int PRIMARY KEY,
	PaymentDate date,
	PaymentAmount decimal(8,2),
	StudentID int
)

CREATE TABLE Agenda
(
	StudentID int NOT NULL,
	SubjectID int NOT NULL
)

CREATE TABLE Subjects
(
	SubjectID int PRIMARY KEY,
	SubjectName varchar(50)
)

ALTER TABLE Agenda
ADD CONSTRAINT PK_StudentID_SubjectID
PRIMARY KEY (StudentID, SubjectID)

ALTER TABLE Students
ADD CONSTRAINT FK_MajorID_MajorID
FOREIGN KEY (MajorID)
REFERENCES Majors(MajorID)

ALTER TABLE Payments
ADD CONSTRAINT FK_StudenID_StudentID
FOREIGN KEY (StudentID)
REFERENCES Students(StudentID)

ALTER TABLE Agenda
ADD CONSTRAINT FK_StudentID_StudentID
FOREIGN KEY (StudentID)
REFERENCES Students(StudentID)

ALTER TABLE Agenda
ADD CONSTRAINT FK_SubjectID_SubjectID
FOREIGN KEY (SubjectID)
REFERENCES Subjects(SubjectID)


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

<title>All Classes</title>
<meta name="date" content="2015-08-06">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

CommandComponent

Component

Database

ListenerComponent

MainComponent

Minigame

MinigameAPI

TimerComponent

redpajama_set_name: RedPajamaGithub


text:
package org.dol.encrypt;

import java.security.Provider;
import java.security.Security;

public class CoderBase {
    public static final String DEFAULT_CHARSET_STRING = "UTF-8";
	static
	{
		if (Security.getProvider("BC") == null) {
			try {
				Class<?> clazz = CoderBase.class.getClassLoader().loadClass("org.bouncycastle.jce.provider.BouncyCastleProvider");
				Provider provider = (Provider) clazz.newInstance();
				Security.addProvider(provider);
			} catch (Exception ignored) {

			}

		}
	}
}


text:
package tcontainer

import (
	"fmt"
	"github.com/trivago/tgo/treflect"
	"reflect"
	"strconv"
	"strings"
	"time"
)

// MarshalMap is a wrapper type to attach converter methods to maps normally
// returned by marshalling methods, i.e. key/value parsers.
// All methods that do a conversion will return an error if the value stored
// behind key is not of the expected type or if the key is not existing in the
// map.
type MarshalMap map[string]interface{}

const (
	// MarshalMapSeparator defines the rune used for path separation
	MarshalMapSeparator = '/'
	// MarshalMapArrayBegin defines the rune starting array index notation
	MarshalMapArrayBegin = '['
	// MarshalMapArrayEnd defines the rune ending array index notation
	MarshalMapArrayEnd = ']'
)

// NewMarshalMap creates a new marshal map (string -> interface{})
func NewMarshalMap() MarshalMap {
	return make(map[string]interface{})
}

// TryConvertToMarshalMap converts collections to MarshalMap if possible.
// This is a deep conversion, i.e. each element in the collection will be
// traversed. You can pass a formatKey function that will be applied to all
// string keys that are detected.
func TryConvertToMarshalMap(value interface{}, formatKey func(string) string) interface{} {
	valueMeta := reflect.ValueOf(value)
	switch valueMeta.Kind() {
	default:
		return value

	case reflect.Array, reflect.Slice:
		arrayLen := valueMeta.Len()
		converted := make([]interface{}, arrayLen)
		for i := 0; i < arrayLen; i++ {
			converted[i] = TryConvertToMarshalMap(valueMeta.Index(i).Interface(), formatKey)
		}
		return converted

	case reflect.Map:
		converted := NewMarshalMap()
		keys := valueMeta.MapKeys()

		for _, keyMeta := range keys {
			strKey, isString := keyMeta.Interface().(string)
			if !isString {
				continue
			}
			if formatKey != nil {
				strKey = formatKey(strKey)
			}
			val := valueMeta.MapIndex(keyMeta).Interface()
			converted[strKey] = TryConvertToMarshalMap(val, formatKey)
		}
		return converted // ### return, converted MarshalMap ###
	}
}

// ConvertToMarshalMap tries to convert a compatible map type to a marshal map.
// Compatible types are map[interface{}]interface{}, map[string]interface{} and of
// course MarshalMap. The same rules as for ConvertValueToMarshalMap apply.
func ConvertToMarshalMap(value interface{}, formatKey func(string) string) (MarshalMap, error) {
	converted := TryConvertToMarshalMap(value, formatKey)
	if result, isMap := converted.(MarshalMap); isMap {
		return result, nil
	}
	return nil, fmt.Errorf("Root value cannot be converted to MarshalMap")
}

// Bool returns a value at key that is expected to be a boolean
func (mmap MarshalMap) Bool(key string) (bool, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return false, fmt.Errorf(`"%s" is not set`, key)
	}

	boolValue, isBool := val.(bool)
	if !isBool {
		return false, fmt.Errorf(`"%s" is expected to be a boolean`, key)
	}
	return boolValue, nil
}

// Uint returns a value at key that is expected to be an uint64 or compatible
// integer value.
func (mmap MarshalMap) Uint(key string) (uint64, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return 0, fmt.Errorf(`"%s" is not set`, key)
	}

	if intVal, isNumber := treflect.Uint64(val); isNumber {
		return intVal, nil
	}

	return 0, fmt.Errorf(`"%s" is expected to be an unsigned number type`, key)
}

// Int returns a value at key that is expected to be an int64 or compatible
// integer value.
func (mmap MarshalMap) Int(key string) (int64, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return 0, fmt.Errorf(`"%s" is not set`, key)
	}

	if intVal, isNumber := treflect.Int64(val); isNumber {
		return intVal, nil
	}

	return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key)
}

// Float returns a value at key that is expected to be a float64 or compatible
// float value.
func (mmap MarshalMap) Float(key string) (float64, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return 0, fmt.Errorf(`"%s" is not set`, key)
	}

	if floatVal, isNumber := treflect.Float64(val); isNumber {
		return floatVal, nil
	}

	return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key)
}

// Duration returns a value at key that is expected to be a string
func (mmap MarshalMap) Duration(key string) (time.Duration, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return time.Duration(0), fmt.Errorf(`"%s" is not set`, key)
	}

	switch val.(type) {
	case time.Duration:
		return val.(time.Duration), nil
	case string:
		return time.ParseDuration(val.(string))
	}

	return time.Duration(0), fmt.Errorf(`"%s" is expected to be a duration or string`, key)
}

// String returns a value at key that is expected to be a string
func (mmap MarshalMap) String(key string) (string, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return "", fmt.Errorf(`"%s" is not set`, key)
	}

	strValue, isString := val.(string)
	if !isString {
		return "", fmt.Errorf(`"%s" is expected to be a string`, key)
	}
	return strValue, nil
}

// Array returns a value at key that is expected to be a []interface{}
func (mmap MarshalMap) Array(key string) ([]interface{}, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	arrayValue, isArray := val.([]interface{})
	if !isArray {
		return nil, fmt.Errorf(`"%s" is expected to be an array`, key)
	}
	return arrayValue, nil
}

// Map returns a value at key that is expected to be a
// map[interface{}]interface{}.
func (mmap MarshalMap) Map(key string) (map[interface{}]interface{}, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	mapValue, isMap := val.(map[interface{}]interface{})
	if !isMap {
		return nil, fmt.Errorf(`"%s" is expected to be a map`, key)
	}
	return mapValue, nil
}

func castToStringArray(key string, value interface{}) ([]string, error) {
	switch value.(type) {
	case string:
		return []string{value.(string)}, nil

	case []interface{}:
		arrayVal := value.([]interface{})
		stringArray := make([]string, 0, len(arrayVal))

		for _, val := range arrayVal {
			strValue, isString := val.(string)
			if !isString {
				return nil, fmt.Errorf(`"%s" does not contain string keys`, key)
			}
			stringArray = append(stringArray, strValue)
		}
		return stringArray, nil

	case []string:
		return value.([]string), nil

	default:
		return nil, fmt.Errorf(`"%s" is not a valid string array type`, key)
	}
}

// StringArray returns a value at key that is expected to be a []string
// This function supports conversion (by copy) from
//  * []interface{}
func (mmap MarshalMap) StringArray(key string) ([]string, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	return castToStringArray(key, val)
}

func castToInt64Array(key string, value interface{}) ([]int64, error) {
	switch value.(type) {
	case int:
		return []int64{value.(int64)}, nil

	case []interface{}:
		arrayVal := value.([]interface{})
		intArray := make([]int64, 0, len(arrayVal))

		for _, val := range arrayVal {
			intValue, isInt := val.(int64)
			if !isInt {
				return nil, fmt.Errorf(`"%s" does not contain int keys`, key)
			}
			intArray = append(intArray, intValue)
		}
		return intArray, nil

	case []int64:
		return value.([]int64), nil

	default:
		return nil, fmt.Errorf(`"%s" is not a valid string array type`, key)
	}
}

// IntArray returns a value at key that is expected to be a []int64
// This function supports conversion (by copy) from
//  * []interface{}
func (mmap MarshalMap) Int64Array(key string) ([]int64, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	return castToInt64Array(key, val)
}

// StringMap returns a value at key that is expected to be a map[string]string.
// This function supports conversion (by copy) from
//  * map[interface{}]interface{}
//  * map[string]interface{}
func (mmap MarshalMap) StringMap(key string) (map[string]string, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	switch val.(type) {
	case map[string]string:
		return val.(map[string]string), nil

	default:
		valueMeta := reflect.ValueOf(val)
		if valueMeta.Kind() != reflect.Map {
			return nil, fmt.Errorf(`"%s" is expected to be a map[string]string but is %T`, key, val)
		}

		result := make(map[string]string)
		for _, keyMeta := range valueMeta.MapKeys() {
			strKey, isString := keyMeta.Interface().(string)
			if !isString {
				return nil, fmt.Errorf(`"%s" is expected to be a map[string]string. Key is not a string`, key)
			}

			value := valueMeta.MapIndex(keyMeta)
			strValue, isString := value.Interface().(string)
			if !isString {
				return nil, fmt.Errorf(`"%s" is expected to be a map[string]string. Value is not a string`, key)
			}

			result[strKey] = strValue
		}

		return result, nil
	}
}

// StringArrayMap returns a value at key that is expected to be a
// map[string][]string. This function supports conversion (by copy) from
//  * map[interface{}][]interface{}
//  * map[interface{}]interface{}
//  * map[string]interface{}
func (mmap MarshalMap) StringArrayMap(key string) (map[string][]string, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	switch val.(type) {
	case map[string][]string:
		return val.(map[string][]string), nil

	default:
		valueMeta := reflect.ValueOf(val)
		if valueMeta.Kind() != reflect.Map {
			return nil, fmt.Errorf(`"%s" is expected to be a map[string][]string but is %T`, key, val)
		}

		result := make(map[string][]string)
		for _, keyMeta := range valueMeta.MapKeys() {
			strKey, isString := keyMeta.Interface().(string)
			if !isString {
				return nil, fmt.Errorf(`"%s" is expected to be a map[string][]string. Key is not a string`, key)
			}

			value := valueMeta.MapIndex(keyMeta)
			arrayValue, err := castToStringArray(strKey, value.Interface())
			if err != nil {
				return nil, fmt.Errorf(`"%s" is expected to be a map[string][]string. Value is not a []string`, key)
			}

			result[strKey] = arrayValue
		}

		return result, nil
	}
}

// MarshalMap returns a value at key that is expected to be another MarshalMap
// This function supports conversion (by copy) from
//  * map[interface{}]interface{}
func (mmap MarshalMap) MarshalMap(key string) (MarshalMap, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	return ConvertToMarshalMap(val, nil)
}

// Value returns a value from a given value path.
// Fields can be accessed by their name. Nested fields can be accessed by using
// "/" as a separator. Arrays can be addressed using the standard array
// notation "[<index>]".
// Examples:
// "key"         -> mmap["key"]              single value
// "key1/key2"   -> mmap["key1"]["key2"]     nested map
// "key1[0]"     -> mmap["key1"][0]          nested array
// "key1[0]key2" -> mmap["key1"][0]["key2"]  nested array, nested map
func (mmap MarshalMap) Value(key string) (interface{}, bool) {
	return mmap.resolvePath(key, mmap)
}

func (mmap MarshalMap) resolvePathKey(key string) (int, int) {
	keyEnd := len(key)
	nextKeyStart := keyEnd
	pathIdx := strings.IndexRune(key, MarshalMapSeparator)
	arrayIdx := strings.IndexRune(key, MarshalMapArrayBegin)

	if pathIdx > -1 && pathIdx < keyEnd {
		keyEnd = pathIdx
		nextKeyStart = pathIdx + 1 // don't include slash
	}
	if arrayIdx > -1 && arrayIdx < keyEnd {
		keyEnd = arrayIdx
		nextKeyStart = arrayIdx // include bracket because of multidimensional arrays
	}

	// a       -> key: "a", remain: ""       -- value
	// a/b/c   -> key: "a", remain: "b/c"    -- nested map
	// a[1]b/c -> key: "a", remain: "[1]b/c" -- nested array

	return keyEnd, nextKeyStart
}

func (mmap MarshalMap) resolvePath(key string, value interface{}) (interface{}, bool) {
	if len(key) == 0 {
		return value, true // ### return, found requested value ###
	}

	valueMeta := reflect.ValueOf(value)
	switch valueMeta.Kind() {
	case reflect.Array, reflect.Slice:
		startIdx := strings.IndexRune(key, MarshalMapArrayBegin) // Must be first char, otherwise malformed
		endIdx := strings.IndexRune(key, MarshalMapArrayEnd)     // Must be > startIdx, otherwise malformed

		if startIdx == -1 || endIdx == -1 {
			return nil, false
		}

		if startIdx == 0 && endIdx > startIdx {
			index, err := strconv.Atoi(key[startIdx+1 : endIdx])

			// [1]    -> index: "1", remain: ""    -- value
			// [1]a/b -> index: "1", remain: "a/b" -- nested map
			// [1][2] -> index: "1", remain: "[2]" -- nested array

			if err == nil && index < valueMeta.Len() {
				item := valueMeta.Index(index).Interface()
				key := key[endIdx+1:]
				return mmap.resolvePath(key, item) // ### return, nested array ###
			}
		}

	case reflect.Map:
		keyMeta := reflect.ValueOf(key)
		if storedValue := valueMeta.MapIndex(keyMeta); storedValue.IsValid() {
			return storedValue.Interface(), true
		}

		keyEnd, nextKeyStart := mmap.resolvePathKey(key)
		pathKey := key[:keyEnd]
		keyMeta = reflect.ValueOf(pathKey)

		if storedValue := valueMeta.MapIndex(keyMeta); storedValue.IsValid() {
			remain := key[nextKeyStart:]
			return mmap.resolvePath(remain, storedValue.Interface()) // ### return, nested map ###
		}
	}

	return nil, false
}


text:
  <url:file:///~/Dropbox (Personal)/projects/study/study/stackoverflow_questions.md>

## sof q 20171027

I have two tables: A and B with a one-to-many relationship between them.

  create table A (
    a_id serial primary key
  )
  create table B ()

## sof q1 20170527

  https://stackoverflow.com/questions/44218060/capacity-assignment-without-for-loops-and-conditional-branches

I have the following data frame:

    items = data_frame( id = 1:4, due = c(1,1,1,2), size = c(5,4,3,2), day = NA )
    capacity = 8
    items
    # # A tibble: 4 × 4
    #      id   due  size   day
    #   <int> <dbl> <dbl> <lgl>
    # 1     1     1     5    NA
    # 2     2     1     4    NA
    # 3     3     1     3    NA
    # 4     4     2     2    NA

My goal is to assign a `day` to each item such that the daily capacity `8` is not exceeded. The items are sorted and assigned by their `due` date.

So the target data frame that I want to obtain for this example is this:

    goal = data_frame( id = 1:4, due = c(1,1,1,2), size = c(5,4,3,2), day = c(1,2,1,2) )
    goal
    # # A tibble: 4 × 4
    #      id   due  size   day
    #   <int> <dbl> <dbl> <dbl>
    # 1     1     1     5     1
    # 2     2     1     4     2
    # 3     3     1     3     1
    # 4     4     2     2     2

I can solve this problem using two for loops and one if condition like that:

    result = data_frame( id = integer(), due = integer(), size = integer(), day = integer() )
    df = items
    will_drop = integer()
    for (day in 1:2) {
      cum_size = 0
      for (i in 1:nrow(df)) {
        item = df[i, ]
        if (cum_size + item$size <= capacity) {
          cum_size = cum_size + item$size
          item$day = day
          result = rbind(result, item)
          will_drop = c(will_drop, i)
        }
      }
      df = df[-will_drop, ]
    }

But I don't like this solution because it is error prone and hard to modify.

I would like to ask if you might come up with a solution without using any for loop and if branching using dplyr or data.table or higher order functions such as lapply or Reduce?

### sof q 20170530

  https://stackoverflow.com/questions/44265783/remove-rows-from-data-frame-using-row-indices-where-row-indices-might-be-zero-le

I want to drop some rows from some dataframe using numeric indices of the rows. But sometimes the indices vector that I am going to drop becomes zero length vector. In this case, I expect that nothing should be dropped from the original data frame. But instead of nothing everything is dropped.

For example, here `drop` works as expected

    df = data_frame( a = 10:12 )
    drop = c(1,2)
    df[ -drop, ]
    # # A tibble: 1 × 1
    # a
    # <int>
    # 1    12

But when `drop` is zero length vector, then removing those rows doesn't work as I expect.

    drop = integer()
    df[ -drop, ]
    # A tibble: 0 × 1
    # ... with 1 variables: a <int>

How to remove rows from a data frame using row indices safely?

Solutions:

  df %>%
     filter(!row_number() %in% drop)

  df[!seq_len(nrow(df)) %in% drop, ]

  df[ setdiff(1:nrow(df), drop), ]

### sof 20170601

  https://stackoverflow.com/questions/44304547/mutate-an-empty-data-frames-column-safely

I have an empty data frame. I try to assign some value to a column of this data frame. Since the data frame is empty, I expect to obtain an empty data frame in return as follows:

    df = data_frame(a = integer())
    df %>%
      mutate(a = 1)
    # A tibble: 0 × 1
    # ... with 1 variables: a <dbl>

The problem occurs when assigned value is a vector. Then I get the following error:

    df %>%
      mutate(a = 1:2)
    # Error: wrong result size (2), expected 0 or 1

When I try to assign a value using `$` operator, then even assigning a single value produces error:

    df$a = 1
    # Error in `$<-.data.frame`(`*tmp*`, "a", value = 1) :
    # replacement has 1 row, data has 0

What is the correct and safe way to try to mutate an empty dataframe's column?

## sof 20170606

I have a data frame of some items to produce with certain sizes. There is a capacity limit for total size of items to produce. I want to obtain list of items such that they just surpass the capacity limit.

For example, this is the data frame of items:

    df = data_frame( id = 1:4, size = 100 ) %>%
      mutate( cum_size = cumsum(size) )
    # # A tibble: 4 × 3
    # id  size cum_size
    # <int> <dbl>    <dbl>
    # 1     1   100      100
    # 2     2   100      200
    # 3     3   100      300
    # 4     4   100      400
    capacity = 250

I can obtain the list of items such that they don't exceed the capacity limit
as such:

    df2 = df %>%
      filter( cum_size < capacity )
    df2
    #      id  size cum_size
    # <int> <dbl>    <dbl>
    # 1     1   100      100
    # 2     2   100      200

But I want to include the row that can be partially produced as well. To find that row, I use the following code:

    partial_item = df %>%
      mutate( remains = cum_size - capacity ) %>%
      filter( remains < size & remains > 0 ) %>%
      select( -remains )
    target = bind_rows(df2, partial_item)
    target
    #      id  size cum_size
    # <int> <dbl>    <dbl>
    # 1     1   100      100
    # 2     2   100      200
    # 3     3   100      300

Solution:

    df3 = df %>%
      filter( cum_size < capacity + size)


text:
package dev.jokr.localnet;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.NotificationCompat;
import android.text.format.Formatter;
import android.util.Log;

import java.util.HashMap;

import dev.jokr.localnet.discovery.models.DiscoveryReply;
import dev.jokr.localnet.models.ConnectedClients;
import dev.jokr.localnet.models.Payload;
import dev.jokr.localnet.models.RegisterMessage;
import dev.jokr.localnet.models.SessionMessage;
import dev.jokr.localnet.utils.NetworkUtil;

/**
 * Created by JoKr on 8/28/2016.
 */
public class ServerService extends Service implements ServerSocketThread.ServiceCallback, Communicator {

    public static final String ACTION = "action";
    public static final int NOTIFICATION_ID = 521;

    // Keys for extras
    public static final String CLASS = "class";
    public static final String BUNDLE = "bundle";
    public static final String PAYLOAD = "payload";

    // Possible service actions:
    public static final int START_SESSION = 1;
    public static final int SESSION_EVENT = 2;

    private HashMap<Long, RegisterMessage> registeredClients;
    private LocalSession session;
    private LocalBroadcastManager manager;
    private Thread serverSocketThread;
    private Thread discoverySocketThread;

    @Override
    public void onCreate() {
        super.onCreate();

        this.manager = LocalBroadcastManager.getInstance(this);
        registeredClients = new HashMap<>();

        serverSocketThread = new Thread(new ServerSocketThread(this));
        serverSocketThread.start();

        runServiceInForeground();
    }

    /*
        Multiple calls to Context.startService() will result in multiple calls to onStartCommand,
        but only one call to onCreate, so we use it as a way to send data to Service.
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("USER", "onStartCommand called");

        int action = intent.getIntExtra(ACTION, 0);
        processAction(action, intent);

        return START_NOT_STICKY;
    }

    private void processAction(int action, Intent intent) {
        if (action == 0)
            return;

        if (action == START_SESSION)
            startSession((Class) intent.getSerializableExtra(CLASS), intent.getBundleExtra(BUNDLE));
        else if (action == SESSION_EVENT)
            session.onEvent((Payload<?>) intent.getSerializableExtra(PAYLOAD));
    }

    private void startSession(Class c, Bundle b) {
        try {
            Object o = c.newInstance();
            if (!LocalSession.class.isInstance(o)) {
                throw new IllegalArgumentException("Class " + c.getName() + " is not instance of LocalSession");
            }
            session = (LocalSession) o;
            session.preCreateInit(this);
            session.onCreate(b, new ConnectedClients(registeredClients));
            sendSessionStartMessage();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void sendSessionStartMessage() {
        SessionMessage message = new SessionMessage(null, SessionMessage.START);
        for (RegisterMessage client : registeredClients.values()) {
            Thread t = new Thread(new SendHandler(message, client.getIp(), client.getPort()));
            t.start();
        }
    }

    private void runServiceInForeground() {
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("LocalNet Session")
                .setContentText("Session is currently running")
                .setSmallIcon(R.drawable.ic_play_circle_filled_black_24dp)
                .build();
        startForeground(NOTIFICATION_ID, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onInitializedSocket(int port) {
        discoverySocketThread = new Thread(new DiscoverySocketThread(new DiscoveryReply(getLocalIp(), port)));
        discoverySocketThread.start();
    }

    @Override
    public void onClientConnected(RegisterMessage message) {
        Log.d("USER", "onClientConnected: " + message.getPayload());
        Long id = NetworkUtil.getIdFromIpAddress(message.getIp());
        registeredClients.put(id, message);

        Intent i = new Intent(LocalServer.CONNECTED_CLIENT);
        i.putExtra(RegisterMessage.class.getName(), message);
        manager.sendBroadcast(i);
    }

    @Override
    public void onSessionMessage(SessionMessage message, String senderIp) {
        if (session != null) {
            session.onReceiveMessage(NetworkUtil.getIdFromIpAddress(senderIp), message.getPayload());
        }
    }

    private String getLocalIp() {
        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
        return Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    }

    @Override
    public void sendMessage(long recipientId, Payload payload) {
        SessionMessage message = new SessionMessage(payload);
        RegisterMessage client = null;
        if (registeredClients.containsKey(recipientId)) {
            client = registeredClients.get(recipientId);
        } else {
            throw new IllegalArgumentException("Recipient id " + recipientId + " is not in registered clients list");
        }
        Thread t = new Thread(new SendHandler(message, client.getIp(), client.getPort()));
        t.start();
    }

    @Override
    public void sendBroadcastMessage(Payload<?> payload) {
        SessionMessage message = new SessionMessage(payload);
        for (RegisterMessage client : registeredClients.values()) {
            Thread t = new Thread(new SendHandler(message, client.getIp(), client.getPort()));
            t.start();
        }
    }

    @Override
    public void sendUiEvent(Payload<?> payload) {
        Intent i = new Intent(LocalServer.UI_EVENT);
        SessionMessage sessionMessage = new SessionMessage(payload);
        i.putExtra(SessionMessage.class.getName(), sessionMessage);
        manager.sendBroadcast(i);
    }

}


text:
module Louisville
  module Extensions
    module History

      module ClassMethods

        def historical_slug_sluggable_type
          self.sti_name
        end

      end

      def self.included(base)
        base.class_eval do

          extend ::Louisville::Extensions::History::ClassMethods

          # If our slug has changed we should manage the history.
          after_save :delete_matching_historical_slug,  :if => :louisville_slug_changed?
          after_save :generate_historical_slug,         :if => :louisville_slug_changed?

          before_destroy :destroy_historical_slugs!
        end
      end

      def historical_slugs
        return ::Louisville::Slug.where('1=0') unless persisted?
        ::Louisville::Slug.where(:sluggable_id => id, :sluggable_type => ::Louisville::Util.polymorphic_name(self.class))
      end

      protected

      def destroy_historical_slugs!
        historical_slugs.destroy_all
      end

      # First, we delete any previous slugs that this record owned that match the current slug.
      # This allows a record to return to a previous slug without duplication in the history table.
      def delete_matching_historical_slug
        current_value = self.louisville_slug

        return unless current_value

        base, seq = Louisville::Util.slug_parts(current_value)

        self.historical_slugs.where(:slug_base => base, :slug_sequence => seq).delete_all
      end

      # Then we generate a new historical slug for the previous value (if there is one).
      def generate_historical_slug
        previous_value = self.send("#{louisville_config[:column]}_was")

        return unless previous_value

        base, seq = Louisville::Util.slug_parts(previous_value)

        self.historical_slugs.create(:slug_base => base, :slug_sequence => seq)
      end
    end
  end
end


text:
{% extends "layout.html" %}

{% block pageTitle %}
	GOV.UK prototyping kit
{% endblock %}

{% block content %}

{% import "pip18/elements.html" as elements %}
{% for page in data %}
{% for checkYourAnswers in dataCheckChange %}
{% for question in checkYourAnswers.checkYourAnswers %}

			<form action="/pip18/checkYourAnswers{% if edit %}?edit=true{% endif %}" method="post" class="form">

					{{ elements.header(page,question) }}

About you

Personal details

								{{ elements.EnterChangeAnswers(helper,"helper",page) }}

You and your condition

Your conditions and disabilities

								{{ elements.EnterChangeAnswers(conditionDetails,"conditionDetails",page) }}

Your medication

								{{ elements.EnterChangeAnswers(medications,"medications",page) }}

Managing your medication

								{{ elements.EnterChangeAnswers(manageMedications,"manageMedications",page) }}

Your treatments and therapy

								{{ elements.EnterChangeAnswers(treatments,"treatments",page) }}

Side effects

								{{ elements.EnterChangeAnswers(sideEffects,"sideEffects",page) }}

Changes in your condition

								{{ elements.EnterChangeAnswers(conditionAffects,"conditionAffects",page) }}

Monitoring your condition

								{{ elements.EnterChangeAnswers(monitoringCondition,"monitoringCondition",page) }}

Professionals who know about your condition

								{{ elements.EnterChangeAnswers(healthcareprofessional,"healthcareprofessional",page) }}

Information you can send

								{{ elements.EnterChangeAnswers(submitEvidence,"submitEvidence",page) }}

Any aids and adaptations you have

								{{ elements.EnterChangeAnswers(specialAids,"specialAids",page) }}

Your sight

								{{ elements.EnterChangeAnswers(sight,"sight",page) }}

Your speech

								{{ elements.EnterChangeAnswers(speech,"speech",page) }}

Your hearing

								{{ elements.EnterChangeAnswers(hearing,"hearing",page) }}

You and your home

Getting up and moving around

									{{ elements.EnterChangeAnswers(gettingUp,"gettingUp",page) }}

Using the toilet

									{{ elements.EnterChangeAnswers(toilet,"toilet",page) }}

Washing yourself

									{{ elements.EnterChangeAnswers(washing,"washing",page) }}

Getting dressed

									{{ elements.EnterChangeAnswers(gettingDressed,"gettingDressed",page) }}

Making a hot meal from fresh ingredients

									{{ elements.EnterChangeAnswers(hotMeal,"hotMeal",page) }}

Eating and drinking

									{{ elements.EnterChangeAnswers(eatingAndDrinking,"eatingAndDrinking",page) }}

Getting out and about

Getting out and about

									{{ elements.EnterChangeAnswers(gettingOut,"gettingOut",page) }}

Mixing with people

									{{ elements.EnterChangeAnswers(mixing,"mixing",page) }}

Making sense of things

Planning a local journey

									{{ elements.EnterChangeAnswers(localJourney,"localJourney",page) }}

Following a route

									{{ elements.EnterChangeAnswers(somewhereNeverBeenBefore,"somewhereNeverBeenBefore",page) }}

Understanding written information

									{{ elements.EnterChangeAnswers(understanding,"understanding",page) }}

Dealing with money

									{{ elements.EnterChangeAnswers(money,"money",page) }}

You will not be able to change your answers after you send your application.

						    <input type="submit" class="button" value="Save and go to next question" name="saveAndMenu">
						    Back

      </form>

{% endfor %}
{% endfor %}
{% endfor %}
{% endblock %}


text:
using System.Linq;
using Should;
using Typewriter.CodeModel;
using Typewriter.Tests.TestInfrastructure;
using Xunit;

namespace Typewriter.Tests.CodeModel
{
    [Trait("CodeModel", "Delegates"), Collection(nameof(CodeDomFixture))]
    public class CodeDomDelegateTests : DelegateTests
    {
        public CodeDomDelegateTests(CodeDomFixture fixture) : base(fixture)
        {
        }
    }

    [Trait("CodeModel", "Delegates"), Collection(nameof(RoslynFixture))]
    public class RoslynDelegateTests : DelegateTests
    {
        public RoslynDelegateTests(RoslynFixture fixture) : base(fixture)
        {
        }
    }

    public abstract class DelegateTests : TestBase
    {
        private readonly File fileInfo;

        protected DelegateTests(ITestFixture fixture) : base(fixture)
        {
            fileInfo = GetFile(@"Tests\CodeModel\Support\DelegateInfo.cs");
        }

        [Fact]
        public void Expect_name_to_match_delegate_name()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Delegate");

            delegateInfo.Name.ShouldEqual("Delegate");
            delegateInfo.FullName.ShouldEqual("Typewriter.Tests.CodeModel.Support.DelegateInfo.Delegate");
            delegateInfo.Parent.ShouldEqual(classInfo);
        }

        [Fact]
        public void Expect_to_find_attributes()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Delegate");
            var attributeInfo = delegateInfo.Attributes.First();

            delegateInfo.Attributes.Count.ShouldEqual(1);
            attributeInfo.Name.ShouldEqual("AttributeInfo");
            attributeInfo.FullName.ShouldEqual("Typewriter.Tests.CodeModel.Support.AttributeInfoAttribute");
        }

        [Fact]
        public void Expect_to_find_parameters()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Delegate");
            var parameterInfo = delegateInfo.Parameters.First();

            delegateInfo.Parameters.Count.ShouldEqual(1);
            parameterInfo.Name.ShouldEqual("parameter");
        }

        [Fact]
        public void Expect_to_find_parameter_attributes()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Delegate");
            var parameterInfo = delegateInfo.Parameters.First();
            var attributeInfo = parameterInfo.Attributes.First();

            parameterInfo.Attributes.Count.ShouldEqual(1);
            attributeInfo.Name.ShouldEqual("AttributeInfo");
            attributeInfo.FullName.ShouldEqual("Typewriter.Tests.CodeModel.Support.AttributeInfoAttribute");
        }

        [Fact]
        public void Expect_void_delegates_to_return_void()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Delegate");

            delegateInfo.Type.FullName.ShouldEqual("System.Void");
            delegateInfo.Type.Name.ShouldEqual("void");
            delegateInfo.Type.OriginalName.ShouldEqual("Void");
            delegateInfo.Type.IsEnum.ShouldBeFalse("IsEnum");
            delegateInfo.Type.IsEnumerable.ShouldBeFalse("IsEnumerable");
            delegateInfo.Type.IsGeneric.ShouldBeFalse("IsGeneric");
            delegateInfo.Type.IsNullable.ShouldBeFalse("IsNullable");
            delegateInfo.Type.IsTask.ShouldBeFalse("IsTask");
            delegateInfo.Type.IsPrimitive.ShouldBeFalse("IsPrimitive");
        }

        [Fact]
        public void Expect_generic_delegates_to_handle_generic_type_arguments()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Generic");
            var genericTypeInfo = delegateInfo.TypeParameters.First();
            var parameterTypeInfo = delegateInfo.Parameters.First().Type;

            delegateInfo.IsGeneric.ShouldBeTrue("IsGeneric");
            delegateInfo.TypeParameters.Count.ShouldEqual(1);

            delegateInfo.Type.Name.ShouldEqual("T");
            delegateInfo.Type.FullName.ShouldEqual("T");
            genericTypeInfo.Name.ShouldEqual("T");
            parameterTypeInfo.Name.ShouldEqual("T");
            parameterTypeInfo.FullName.ShouldEqual("T");
        }

        [Fact]
        public void Expect_delegates_to_handle_generic_type_arguments_from_class()
        {
            var classInfo = fileInfo.Classes.First(c => c.Name == "GenericDelegateInfo");
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Delegate");
            var parameterTypeInfo = delegateInfo.Parameters.First().Type;

            delegateInfo.IsGeneric.ShouldBeFalse("IsGeneric");
            delegateInfo.TypeParameters.Count.ShouldEqual(0);

            delegateInfo.Type.Name.ShouldEqual("T");
            delegateInfo.Type.FullName.ShouldEqual("T");
            parameterTypeInfo.Name.ShouldEqual("T");
            parameterTypeInfo.FullName.ShouldEqual("T");
        }

        [Fact]
        public void Expect_generic_delegates_to_handle_generic_type_arguments_from_class_and_delegate()
        {
            var classInfo = fileInfo.Classes.First(c => c.Name == "GenericDelegateInfo");
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Generic");
            var firstParameterTypeInfo = delegateInfo.Parameters.First(p => p.Name == "parameter1").Type;
            var secondParameterTypeInfo = delegateInfo.Parameters.First(p => p.Name == "parameter2").Type;

            delegateInfo.IsGeneric.ShouldBeTrue("IsGeneric");
            delegateInfo.TypeParameters.Count.ShouldEqual(1);

            delegateInfo.Type.Name.ShouldEqual("T1");
            delegateInfo.Type.FullName.ShouldEqual("T1");
            firstParameterTypeInfo.Name.ShouldEqual("T1");
            firstParameterTypeInfo.FullName.ShouldEqual("T1");
            secondParameterTypeInfo.Name.ShouldEqual("T");
            secondParameterTypeInfo.FullName.ShouldEqual("T");
        }

        [Fact]
        public void Expect_task_delegates_to_return_void()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "Task");

            delegateInfo.Type.FullName.ShouldEqual("System.Void");
            delegateInfo.Type.Name.ShouldEqual("void");
            delegateInfo.Type.OriginalName.ShouldEqual("Void");
            delegateInfo.Type.IsEnum.ShouldBeFalse("IsEnum");
            delegateInfo.Type.IsEnumerable.ShouldBeFalse("IsEnumerable");
            delegateInfo.Type.IsGeneric.ShouldBeFalse("IsGeneric");
            delegateInfo.Type.IsNullable.ShouldBeFalse("IsNullable");
            delegateInfo.Type.IsTask.ShouldBeTrue("IsTask");
            delegateInfo.Type.IsPrimitive.ShouldBeFalse("IsPrimitive");
        }

        [Fact]
        public void Expect_task_string_delegates_to_return_string()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "TaskString");

            delegateInfo.Type.FullName.ShouldEqual("System.String");
            delegateInfo.Type.Name.ShouldEqual("string");
            delegateInfo.Type.OriginalName.ShouldEqual("string");
            delegateInfo.Type.IsEnum.ShouldBeFalse("IsEnum");
            delegateInfo.Type.IsEnumerable.ShouldBeFalse("IsEnumerable");
            delegateInfo.Type.IsGeneric.ShouldBeFalse("IsGeneric");
            delegateInfo.Type.IsNullable.ShouldBeFalse("IsNullable");
            delegateInfo.Type.IsTask.ShouldBeTrue("IsTask");
            delegateInfo.Type.IsPrimitive.ShouldBeTrue("IsPrimitive");
        }

        [Fact]
        public void Expect_task_nullable_int_delegates_to_return_int()
        {
            var classInfo = fileInfo.Classes.First();
            var delegateInfo = classInfo.Delegates.First(p => p.Name == "TaskNullableInt");

            delegateInfo.Type.FullName.ShouldEqual("System.Int32?");
            delegateInfo.Type.Name.ShouldEqual("number");
            delegateInfo.Type.OriginalName.ShouldEqual("int?");
            delegateInfo.Type.IsEnum.ShouldBeFalse("IsEnum");
            delegateInfo.Type.IsEnumerable.ShouldBeFalse("IsEnumerable");
            delegateInfo.Type.IsGeneric.ShouldBeFalse("IsGeneric");
            delegateInfo.Type.IsNullable.ShouldBeTrue("IsNullable");
            delegateInfo.Type.IsTask.ShouldBeTrue("IsTask");
            delegateInfo.Type.IsPrimitive.ShouldBeTrue("IsPrimitive");
        }
    }
}


text:
package definitions

type InstantMessageEvent_CallerInfo struct {
	ExtensionNumber string `json:"extensionNumber,omitempty"`
	Location        string `json:"location,omitempty"`
	Name            string `json:"name,omitempty"`
	PhoneNumber     string `json:"phoneNumber,omitempty"`
}


text:
type: post
layout: post
title: OKR - 7x4
eye_catch: /assets/img/acw.png
tags:
- agile-chuck-wagon
comments: true
categories:
- professional
- podcast
status: publish
published: true
meta:
_edit_last: "1"
---

### Agile Chuck Wagon, season 7, episode 4

In this episode of the Agile Chuck Wagon, Chuck talks about objectives and key results. This framework is useful when cascading goals down to others. (length: 9 min)


text:
{% load static %}

{% include "admin/edit_inline/tabular.html" %}


text:
""" md5Hash_test.py
    Unit tests for md5Hash.py  (not the default python library!)
    MD5 defined in RFC 1321
"""

from   crypto.hash.md5Hash import MD5
import unittest
from binascii import a2b_hex

class MD5_TestCases(unittest.TestCase):
    """ MD5 tests from ..."""

    def testFIPS180_1_Appendix_A(self):
        """ APPENDIX A.  A SAMPLE MESSAGE AND ITS MESSAGE DIGEST """
        hashAlg = MD5()
        message        = 'abc'
        message_digest = '900150983cd24fb0d6963f7d28e17f72'
        md_string      = a2b_hex(message_digest)
        assert( hashAlg(message) == md_string ), 'md5 test Failed'

if __name__ == '__main__':
    # Run the tests from the command line
    unittest.main()


text:
package org.bndtools.utils.jar;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

import aQute.lib.io.IO;

/**
 * A utility for reading either JAR files or directories that have the same
 * layout as a JAR file.
 */
public class PseudoJar implements Closeable {

	private final File			base;

	private JarInputStream		jarStream		= null;
	private Iterator<String>	dirIndex		= null;

	private JarEntry			lastJarEntry	= null;
	private String				lastIndexEntry	= null;

	public PseudoJar(File file) {
		this.base = file;
	}

	private void initJarStream() throws IOException {
		if (jarStream != null)
			return;

		if (!base.isFile())
			throw new IOException("Cannot read as JAR, file does not exist or is not a plain file: " + base);

		jarStream = new JarInputStream(IO.stream(base));
	}

	private void initDirIndex() throws IOException {
		if (dirIndex != null)
			return;

		if (!base.isDirectory())
			throw new IOException("Cannot read as directory, does not exist or is not a plain directory: " + base);

		List<String> tmpIndex = new LinkedList<>();
		index("", base, tmpIndex);
		dirIndex = tmpIndex.iterator();
	}

	private static void index(String prefix, File dir, List<String> index) {
		File[] children = dir.listFiles();
		Arrays.sort(children, (f1, f2) -> f1.getName()
			.compareTo(f2.getName()));
		if (children != null)
			for (File child : children) {
				String path = prefix + child.getName();
				if (child.isDirectory())
					path += "/";

				index.add(path);

				if (child.isDirectory())
					index(path, child, index);
			}
	}

	public Manifest readManifest() throws IOException {
		if (base.isDirectory()) {
			File manifest = new File(base, "META-INF/MANIFEST.MF");
			if (!manifest.isFile()) {
				return null;
			}
			try (InputStream in = IO.stream(manifest)) {
				return new Manifest(in);
			}
		}
		initJarStream();
		return jarStream.getManifest();
	}

	public String nextEntry() throws IOException {
		String path;

		if (base.isDirectory()) {
			initDirIndex();
			path = dirIndex.hasNext() ? dirIndex.next() : null;
			lastIndexEntry = path;
		} else {
			initJarStream();

			lastJarEntry = jarStream.getNextJarEntry();
			path = lastJarEntry != null ? lastJarEntry.getName() : null;
		}

		return path;
	}

	public boolean isDirectoryEntry() {
		if (lastJarEntry != null)
			return lastJarEntry.isDirectory();

		if (lastIndexEntry != null)
			return lastIndexEntry.endsWith("/");

		throw new IllegalStateException("No entry is current");
	}

	public InputStream openEntry() throws IOException {
		final InputStream result;

		if (jarStream != null) {
			if (lastJarEntry == null)
				throw new IOException("No more entries available");
			result = new InputStream() {
				@Override
				public int read() throws IOException {
					return jarStream.read();
				}

				@Override
				public int read(byte[] b) throws IOException {
					return jarStream.read(b);
				}

				@Override
				public int read(byte[] b, int off, int len) throws IOException {
					return jarStream.read(b, off, len);
				}

				@Override
				public void close() throws IOException {
					// swallow the close, which would otherwise close the whole
					// JAR stream
				}
			};
		} else {
			if (lastIndexEntry == null)
				throw new IOException("No more entries available");
			result = IO.stream(new File(base, lastIndexEntry));
		}

		return result;
	}

	@Override
	public void close() throws IOException {
		if (jarStream != null)
			jarStream.close();
	}

}


text:
describe("Ext.menu.CheckItem", function(){

    var menu, c;

    function makeItem(cfg) {
        menu = Ext.widget({
            xtype: 'menu',
            renderTo: document.body,
            items: [
                Ext.apply({
                    xtype: 'menucheckitem'
                }, cfg)
            ]
        });
        c = menu.items.getAt(0);
    }

    afterEach(function(){
        Ext.destroy(menu);
        c = null;
    });

    describe("initial config", function(){

        it("should have the checked property as false by default", function(){
            makeItem();
            expect(c.checked).toBe(false);
        });

    });

    describe("setChecked", function() {

        it("should set the checked state on the component", function(){
            makeItem();
            c.setChecked(true);
            expect(c.checked).toBe(true);

            c.setChecked(false);
            expect(c.checked).toBe(false);
        });

        describe("element classes", function(){
            it("should add the checkedCls and remove uncheckedCls when checking", function(){
                makeItem();
                c.setChecked(true);
                expect(c.el.hasCls(c.checkedCls)).toBe(true);
                expect(c.el.hasCls(c.uncheckedCls)).toBe(false);
            });

            it("should add the uncheckedCls and remove checkedCls when unchecking", function(){
                makeItem({
                    checked: true
                });
                c.setChecked(false);
                expect(c.el.hasCls(c.uncheckedCls)).toBe(true);
                expect(c.el.hasCls(c.checkedCls)).toBe(false);
            });
        });

        describe("events", function() {
            describe("no state change", function() {
                it("should not fire any events setting checked: false when not checked", function() {
                    var called = false;
                    makeItem();
                    c.on('beforecheckchange', function(){
                        called = true;
                    });
                    c.setChecked(false);
                    expect(called).toBe(false);
                });

                it("should not fire any events setting checked: true when checked", function() {
                    var called = false;
                    makeItem({
                        checked: true
                    });
                    c.on('beforecheckchange', function(){
                        called = true;
                    });
                    c.setChecked(true);
                    expect(called).toBe(false);
                });
            });

            describe("supressEvents", function(){
                it("should not fire beforecheckchange", function(){
                    var called = false;
                    makeItem();
                    c.on('beforecheckchange', function(){
                        called = true;
                    });
                    c.setChecked(true, true);
                    expect(called).toBe(false);
                });

                it("should not fire checkchange", function(){
                    var called = false;
                    makeItem();
                    c.on('checkchange', function(){
                        called = true;
                    });
                    c.setChecked(true, true);
                    expect(called).toBe(false);
                });

                it("should not trigger a checkHandler", function(){
                    var called = false;
                    makeItem({
                        checkHandler: function(){
                            called = true;
                        }
                    });
                    c.setChecked(true, true);
                    expect(called).toBe(false);
                })
            });

            describe("veto", function(){
                it("should not trigger a change if beforecheckchange returns false", function(){
                    makeItem();
                    c.on('beforecheckchange', function(){
                        return false;
                    });
                    c.setChecked(true);
                    expect(c.checked).toBe(false);
                })
            });

            describe("params", function(){
                it("should fire beforecheckchange with the item and the new checked state", function(){
                    var comp, state;
                    makeItem();
                    c.on('beforecheckchange', function(arg1, arg2){
                        comp = arg1;
                        state = arg2;
                    });
                    c.setChecked(true);
                    expect(comp).toBe(c);
                    expect(state).toBe(true);
                });

                it("should fire checkchange with the item and the new checked state", function(){
                    var comp, state;
                    makeItem();
                    c.on('checkchange', function(arg1, arg2){
                        comp = arg1;
                        state = arg2;
                    });
                    c.setChecked(true);
                    expect(comp).toBe(c);
                    expect(state).toBe(true);
                });

                it("should trigger checkHandler with the item and the new checked state", function(){
                    var comp, state;
                    makeItem({
                        checkHandler: function(arg1, arg2){
                            comp = arg1;
                            state = arg2;
                        }
                    });
                    c.setChecked(true);
                    expect(comp).toBe(c);
                    expect(state).toBe(true);
                });

                describe("checkHandler scope", function(){
                    it("should default the scope to the component", function(){
                        var scope;
                        makeItem({
                            checkHandler: function(){
                                scope = this;
                            }
                        });
                        c.setChecked(true);
                        expect(scope).toBe(c);
                    });

                    it("should use a passed scope", function(){
                        var o = {},
                            scope;

                        makeItem({
                            scope: o,
                            checkHandler: function(){
                                scope = this;
                            }
                        });
                        c.setChecked(true);
                        expect(scope).toBe(o);
                    });
                })
            });
        });
    });
});


text:
import { usersController } from '../controllers/users-controller.js'
import { notificator } from '../helpers/notificator.js'
import { blogController } from '../controllers/blog-controller.js';

let homeEvents = (function() {
    function startCarousel() {
        // Activate Carousel
        $("#carousel-example-generic").carousel();
        // media bar options
        $('#media').carousel({
            pause: true,
            interval: 10000,
        });
        $('#media').hover(function() {
            $(this).carousel('pause')
        }, function() {
            $(this).carousel('cycle')
        })
    }

    function singInOutShowHide() {
        $("#sign-in-out").click(function() {
            var text = $(this).html();
            if (text === "SIGN IN") {
                text = "SIGN OUT";
                $('#nav-collapse2').addClass('in')
                $("#sign-in-out").addClass("selectedMenu")
            } else if (text === "SIGN OUT") {
                text = "SIGN IN";
                $("#sign-in-out").addClass("selectedMenu")
                $('#nav-collapse2').removeClass('in')
                if ($('#main-content').hasClass('logged-in')) {
                    usersController.logout();
                }
            }
            $(this).html(text);
        });

        $('#sign-in-btn').click(function() {
            usersController.signInUp();
        });
        $('#register-btn').click(function() {
            usersController.register();
        });
    }

    function facebookShare() {
        $("#facebook-login").click(function() {
            FB.ui({
                method: 'share',
                display: 'popup',
                href: 'https://rawgit.com/composer2/Amazing-Sales/master/index.html',
            }, function(response) {});
        })
    }

    function changeTheSelectedMainMenuColor() {
        $("#nav-menu").on('click', 'li', function() {
            let currentLi = $(this);
            $("#nav-menu li").children().removeClass("selectedMenu");
            currentLi.children(":first").addClass("selectedMenu")
        })
    }

    function searchByTopicName() {
        $("#search-box-input").on('input', function() {
            let searchPhrase = $(this).val();
            if (searchPhrase.length >= 3) {
                blogController.searchThreadsByPhrase(searchPhrase);
            }
        });
    }
    return {
        startCarousel,
        singInOutShowHide,
        facebookShare,
        changeTheSelectedMainMenuColor,
        searchByTopicName
    }

})();

export { homeEvents }


text:
<?php

namespace App\Validation\Rules;

use App\Validation\Exceptions\ComponentException;

abstract class AbstractFilterRule extends AbstractRule
{
    public $additionalChars = '';

    abstract protected function validateClean($input);

    public function __construct($additionalChars = '')
    {
        if (!is_string($additionalChars)) {
            throw new ComponentException('Invalid list of additional characters to be loaded');
        }

        $this->additionalChars .= $additionalChars;
    }

    protected function filter($input)
    {
        return str_replace(str_split($this->additionalChars), '', $input);
    }

    public function validate($input)
    {
        if (!is_scalar($input)) {
            return false;
        }

        $stringInput = (string) $input;
        if ('' === $stringInput) {
            return false;
        }

        $cleanInput = $this->filter($stringInput);

        return $cleanInput === '' || $this->validateClean($cleanInput);
    }
}


text:
<?php

namespace Magento\Sales\Test\Unit\Model\ResourceModel\Order\Invoice;

/**
 * Class RelationTest
 */
class RelationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Relation
     */
    protected $relationProcessor;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $invoiceItemResourceMock;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Invoice\Comment|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $invoiceCommentResourceMock;

    /**
     * @var \Magento\Sales\Model\Order\Invoice|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $invoiceMock;

    /**
     * @var \Magento\Sales\Model\Order\Invoice\Item|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $invoiceItemMock;

    /**
     * @var \Magento\Sales\Model\Order\Invoice\Comment|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $invoiceCommentMock;

    /**
     * @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $orderItemMock;

    public function setUp()
    {
        $this->invoiceItemResourceMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Invoice\Item')
            ->disableOriginalConstructor()
            ->setMethods(
                [
                    'save'
                ]
            )
            ->getMock();
        $this->invoiceCommentResourceMock =
            $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Invoice\Comment')
            ->disableOriginalConstructor()
            ->setMethods(
                [
                    'save'
                ]
            )
            ->getMock();
        $this->invoiceMock = $this->getMockBuilder('Magento\Sales\Model\Order\Invoice')
            ->disableOriginalConstructor()
            ->setMethods(
                [
                    'getId',
                    'getItems',
                    'getComments'
                ]
            )
            ->getMock();
        $this->invoiceItemMock = $this->getMockBuilder('Magento\Sales\Model\Order\Invoice\Item')
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMock();
        $this->invoiceCommentMock = $this->getMockBuilder('Magento\Sales\Model\Order\Invoice\Comment')
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMock();
        $this->orderItemMock = $this->getMockBuilder('Magento\Sales\Model\Order\Item')
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMock();
        $this->relationProcessor = new \Magento\Sales\Model\ResourceModel\Order\Invoice\Relation(
            $this->invoiceItemResourceMock,
            $this->invoiceCommentResourceMock
        );
    }

    public function testProcessRelation()
    {
        $this->invoiceMock->expects($this->once())
            ->method('getId')
            ->willReturn('invoice-id-value');
        $this->invoiceMock->expects($this->exactly(2))
            ->method('getItems')
            ->willReturn([$this->invoiceItemMock]);
        $this->invoiceItemMock->expects($this->once())
            ->method('setParentId')
            ->with('invoice-id-value')
            ->willReturnSelf();
        $this->invoiceItemMock->expects($this->once())
            ->method('getOrderItem')
            ->willReturn($this->orderItemMock);
        $this->invoiceItemMock->expects($this->once())
            ->method('setOrderItem')
            ->with($this->orderItemMock)
            ->willReturnSelf();
        $this->invoiceItemResourceMock->expects($this->once())
            ->method('save')
            ->with($this->invoiceItemMock)
            ->willReturnSelf();
        $this->invoiceMock->expects($this->exactly(2))
            ->method('getComments')
            ->willReturn([$this->invoiceCommentMock]);
        $this->invoiceCommentResourceMock->expects($this->once())
            ->method('save')
            ->with($this->invoiceCommentMock)
            ->willReturnSelf();
        $this->relationProcessor->processRelation($this->invoiceMock);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 37(5): 883 (1959)

#### Original name
Helminthosporium rostratum Drechsler, 1923

### Remarks
null


text:
<!DOCTYPE html SYSTEM "about:legacy-compat">

<META http-equiv="Content-Type" content="text/html; charset=iso-8859-15">
<title>Apache JMeter
          -
          Apache JMeter HTTP(S) Test Script Recorder</title>
<meta name="author" value="JMeter developers">
<meta name="email" value="dev@jmeter.apache.org">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Merriweather:400normal" rel="stylesheet" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="../css/new-style.css">
<link rel="apple-touch-icon-precomposed" href="../images/apple-touch-icon.png">
<link rel="icon" href="../images/favicon.png">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="../images/mstile-144x144.png">
<meta name="theme-color" content="#ffffff">

Main content

About

Overview

License

Download

Download Releases

Release Notes

Documentation

Get Started

User Manual

Best Practices

Component Reference

Functions Reference

Properties Reference

Change History

Javadocs

JMeter Wiki

FAQ (Wiki)

Tutorials

Distributed Testing

Recording Tests

JUnit Sampler

Access Log Sampler

Extending JMeter

Community

Issue Tracking

Security

Mailing Lists

Source Repositories

Building and Contributing

Project info at Apache

Contributors

Foundation

The Apache Software Foundation (ASF)

Get Involved in the ASF

Sponsorship

Thanks

Twitter

github

< Prev

Index

Next >

26. Apache JMeter HTTP(S) Test Script Recorder¶

This tutorial attempts to explain the exact steps for recording HTTP/HTTPS. For those new to JMeter, one easy way to create a test plan is to use the Recorder.

26.1 JMeter configuration¶

Since JMeter 2.10, recording has been improved to better handle embedded resources and creation of certificates on the fly.
To enable these features, JMeter uses keytool utility (available in JRE/JDK) so you need to ensure your
configuration is correct, read this wiki page before starting.

26.2 Basic Instructions¶

Go to JMETER_HOME/bin and start JMeter with jmeterw.cmd on Windows
      and jmeter on Linux/Unix

Select Templates... on the menu bar

Select Recording template on the list

A complete Test Plan is generated

In the HTTP Request Defaults element:

Server name

enter example.com

Path

leave blank

Return to HTTP(S) Test Script Recorder, and click the Start button at the top.

This will start the JMeter proxy server which is used to intercept the browser requests.
A file called ApacheJMeterTemporaryRootCA.crt will be generated in jmeter/bin
folder. Install this certificate in your browser, if you don't know how to do it,
read Installing the JMeter CA certificate for HTTPS recording

26.3 Configure your browser to use the JMeter Proxy¶

At this point, JMeter's proxy is running. For this exercise, we will use Iceweasel/Firefox
to view some pages on the JMeter website.

Start Iceweasel/Firefox, but do not close JMeter.

From the tool bar, click
      Edit → Preferences (or
      Tools → Preferences or type about:preferences#advanced
      as URL). This should bring up the options.

Select the Advanced tab, and Network tab

Click Settings button near the top.

On the new pop-up, check Manual proxy configuration. The address and
      port fields should be enabled now.

Address

enter localhost or the IP address of your system

Port

enter 8888.

Check Use this proxy server for all protocols

Click OK button. This should return you to the browser

26.4 Record your navigation¶

With your browser, in the Address bar at the top, enter http://example.com/index.html (replace example.com with your websites address).
  and hit the enter key.

Click on a few links on your sites pages.

Close your browser and bring up the JMeter window.

Expand the Thread Group and there should be several samplers. At this point, the test plan can
be saved as is.

If you forget to add default HTTP Request settings, you will have to manually
delete the server name, and port.

In this sample, there aren't any default request parameters. If a particular request parameter
is required by all pages, the request defaults is where one would add the entries.

Select Thread Group and change a few defaults:

Number of Threads

enter 5

Ramp-Up Period

do not change

Loop Count

enter 100

26.5 Validate the script¶

Now we need to validate the script before to run our test plan. Save the test plan.

Right click on the Thread Group
  Validate

Check with View Results Tree element if all is ok.

26.6 Variabilize and Correlate the script¶

In some scripts, we will need to:

Variabilize some input (login, password, search words...)

Correlate some data (session variable...) between two requests

To variabilize, we can use:

CSV Data Set Config to get input data from csv file

JMeter functions like __counter, __time...

etc.

To correlate, we can get data from a request with Post Processors like JSON Extractor, Regular Expression Extractor... and inject it in another request.

To find data to correlate, the easiest way to do it is to use the Search function in View Results Tree.

26.7 Start the test¶

At this point, we are ready to run our test plan and see what happens. When you're
ready to run the test, there are two ways:

With the gui, but it's not recommended to big load test.

With the command line.

Solution 1, with the gui, but just during debug phase, use Non GUI for your load test.

Run → Start
or use the keyboard and press Ctrl + R

  Before you start the test,  add a Summary Report element and select it. As the test runs, the statistics will change
  until the test is done. At the end of the test, the summary report should look like this.

  While the test is running, in the upper right-hand corner, there should be a green circle. When the test is done, the circle should be grey.

Solution 2, in command line, use jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder]

At the end of the test, an HTML report will be generated and available in [Path to output folder] used in command line.

< Prev

Index

Next >

      Share this page:

share

tweet

share

            Copyright ©
            1999 –
            2017
            , Apache Software Foundation

Apache, Apache JMeter, JMeter, the Apache
            feather, and the Apache JMeter logo are
            trademarks of the
            Apache Software Foundation.


text:
// Generated by xsd compiler for ios/objective-c
// DO NOT CHANGE!

#import <Foundation/Foundation.h>
#import "PicoClassSchema.h"
#import "PicoPropertySchema.h"
#import "PicoConstants.h"
#import "PicoBindable.h"

/**
 (public class)

 @ingroup AWSECommerceServicePortType
*/
@interface TopItem : NSObject <PicoBindable> {

@private
    NSString *_asin;
    NSString *_title;
    NSString *_detailPageURL;
    NSString *_productGroup;
    NSMutableArray *_author;
    NSMutableArray *_artist;
    NSMutableArray *_actor;

}

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, strong) NSString *asin;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, strong) NSString *title;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, strong) NSString *detailPageURL;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, strong) NSString *productGroup;

/**
 (public property)

 entry type : NSString, wrapper for primitive string
*/

@property (nonatomic, strong) NSMutableArray *author;

/**
 (public property)

 entry type : NSString, wrapper for primitive string
*/

@property (nonatomic, strong) NSMutableArray *artist;

/**
 (public property)

 entry type : NSString, wrapper for primitive string
*/

@property (nonatomic, strong) NSMutableArray *actor;

@end


text:
export * from './auth.service';
export * from './auth-guard.service';
export * from './chat.service';
export * from './comments.service';
export * from './faq.service';
export * from './news.service';
export * from './support.service';


text:
@p.I package p;

public @interface I {
public int x() ;
}
@p.I public class A {
@p.I public A() {}
}
public class useAnno extends groovy.lang.Script {
public static void main(java.lang.String[] args) {
new p.useAnno(new groovy.lang.Binding(args)).run();
}

public java.lang.Object run() {

@p.I public java.lang.Integer var = 3;

return null;

}

@p.I public void foo(@p.I final java.lang.Object x) {
@p.I java.lang.Object a;
}

public useAnno(groovy.lang.Binding binding) {
super(binding);
}
public useAnno() {
super();
}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. gén. struct. (Paris) 145 (1984)

#### Original name
Melanoleucaceae Locq.

### Remarks
null


text:
const snekfetch = require('snekfetch')

const MY_GIT = require('../../../package.json').repository.replace(/^github:/, '')

exports.run = async (bot, msg, args) => {
  if (!bot.utils.hasEmbedPermission(msg.channel)) {
    return msg.error('No permission to use embed in this channel!')
  }

  if (!args.length) {
    return msg.error('You must specify something to search!')
  }

  const prev = msg.content

  if (args[0].indexOf('/') !== -1) {
    const repo = safeRepo(args[0])
    await msg.edit(`${consts.p}Loading info for \`${repo}\`\u2026`)
    try {
      const res = await snekfetch.get(`https://api.github.com/repos/${repo}`)
      if (res.status !== 200) {
        return msg.error('Could not connect to GitHub server!')
      }

      return msg.edit(prev, {
        embed: buildEmbedFromJson(res.body)
      })
    } catch (err) {
      if (new RegExp('404 Not Found', 'i').test(err.toString())) {
        return msg.error('That repository could not be found!')
      } else {
        throw err
      }
    }
  } else {
    const query = args.join(' ')
    await msg.edit(`${consts.p}Searching for \`${query}\`\u2026`)

    const res = await snekfetch.get(`https://api.github.com/search/repositories?q=${args.join('+')}`)
    if (res.status !== 200) {
      return msg.error('Could not connect to GitHub server!')
    }

    if (res.body.items.length < 1) {
      return msg.error(`${consts.e}No results found for '${args.join(' ')}'`)
    }

    const count = res.body.items.length = Math.min(3, res.body.items.length)
    await msg.edit(`${consts.s}Top ${count} result${count !== 1 ? 's' : ''} for \`${query}\`:`)

    const send = async i => {
      if (!res.body.items[i]) {
        return
      }
      await msg.channel.send({
        embed: buildEmbedFromJson(res.body.items[i])
      })
      await send(i + 1)
    }
    return send(0)
  }
}

const safeRepo = input => {
  if (input.indexOf('/') === -1) {
    return
  }

  const user = input.substr(0, input.indexOf('/'))
  input = input.substr(input.indexOf('/') + 1)
  const repo = input.indexOf('/') === -1 ? input : input.substr(0, input.indexOf('/'))
  return `${user}/${repo}`
}

const buildEmbedFromJson = json => {
  // Special treatment
  const isMyGit = json.full_name === MY_GIT

  return bot.utils.formatEmbed('', json.description || 'No description provided.',
    [
      {
        title: 'Information',
        fields: [
          {
            name: 'Owner',
            value: `[${json.owner.login}](${json.owner.html_url})`
          },
          {
            name: 'Primary language',
            value: json.language || 'N/A'
          }
        ]
      },
      {
        title: 'Links',
        fields: [
          {
            name: '',
            value: `[Home page](${json.html_url})`
          },
          {
            name: '',
            value: `[Downloads](${json.html_url}/releases)`
          },
          {
            name: '',
            value: `[Issues](${json.html_url}/issues)`
          }
        ],
        inline: true
      },
      {
        title: 'Statistics',
        fields: [
          {
            name: 'Open issues',
            value: json.open_issues_count
          },
          {
            name: 'Stars',
            value: json.stargazers_count
          },
          {
            name: 'Watchers',
            value: json.subscribers_count || json.watchers_count
          }
        ],
        inline: true
      },
      ['Clone', bot.utils.formatCode(`git clone ${json.clone_url}`)]
    ],
    {
      author: {
        name: json.full_name,
        icon: 'https://the.fiery.me/ftpk.png',
        url: json.html_url
      },
      color: isMyGit ? '#ff0000' : '#4078c0',
      thumbnail: isMyGit ? 'https://the.fiery.me/X5rD.png' : ''
    }
  )
}

exports.info = {
  name: 'github',
  usage: 'github <user/repo>',
  description: 'Links to a GitHub repository',
  aliases: ['git']
}


text:
@rem Filename: dojo-example-build.bat
@rem Date: 1-20-15
@rem Author: Richard Scott Smith

@rem The windows version of this file

build.bat -p profiles/dojo-build.profile.js


text:
<?php

$tplEngine->post = new Post($page['params']['id']);
$tplEngine->replies = $tplEngine->post->getReplies();
$tplEngine->title = $tplEngine->post->getTitle();
$tplEngine->render('post', 'main');


text:
=head1 NAME

PPIx::Regexp::Token::Quantifier - Represent an atomic quantifier.

=head1 SYNOPSIS

 use PPIx::Regexp::Dumper;
 PPIx::Regexp::Dumper->new( 'qr{\w+}smx' )
     ->print();

=head1 INHERITANCE

C<PPIx::Regexp::Token::Quantifier> is a
L<PPIx::Regexp::Token|PPIx::Regexp::Token>.

C<PPIx::Regexp::Token::Quantifier> has no descendants.

=head1 DESCRIPTION

This class represents an atomic quantifier; that is, one of the
characters C<*>, C<+>, or C<?>.

=head1 METHODS

This class provides the following public methods. Methods not documented
here are private, and unsupported in the sense that the author reserves
the right to change or remove them without notice.

=cut

package PPIx::Regexp::Token::Quantifier;

use strict;
use warnings;

use base qw{ PPIx::Regexp::Token };

our $VERSION = '0.028';

# Return true if the token can be quantified, and false otherwise
sub can_be_quantified { return };

# Return true if the token is a quantifier.
sub is_quantifier { return 1 };

my %quantifier = map { $_ => 1 } qw{ * + ? };

=head2 could_be_quantifier

 PPIx::Regexp::Token::Quantifier->could_be_quantifier( '*' );

This method returns true if the given string could be a quantifier; that
is, if it is '*', '+', or '?'.

=cut

sub could_be_quantifier {
    my ( $class, $string ) = @_;
    return $quantifier{$string};
}

sub __PPIX_TOKENIZER__regexp {
    my ( $class, $tokenizer, $character ) = @_;

    $tokenizer->prior( 'can_be_quantified' )
	or return;

    return $quantifier{$character};
}

1;

__END__

=head1 SUPPORT

Support is by the author. Please file bug reports at
L<http://rt.cpan.org>, or in electronic mail to the author.

=head1 AUTHOR

Thomas R. Wyant, III F<wyant at cpan dot org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009-2012 by Thomas R. Wyant, III

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
of the licenses in the directory LICENSES.

This program is distributed in the hope that it will be useful, but
without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.

=cut

# ex: set textwidth=72 :


text:
using namespace seqan;

// Program entry point
int main(int argc, char const ** argv) {
	String<AminoAcid> aaString = "MQDRVKRPMNAFIVWSRDQRRKMALEN";

	Iterator<String<AminoAcid> >::Type it = begin(aaString);

	while (atEnd(it)) {
		if (*it == 'A') {
			*it = 'R';
		}
		it++;
	}

	typedef Size<String<AminoAcid> >::Type TSize;
	String<TSize> counterString;
	TSize alphabetSize = ValueSize<AminoAcid>::VALUE;
	resize(counterString, alphabetSize);

	it = begin(aaString);

	while (atEnd(it)) {
		value(counterString, ordValue(value(it))) += 1;
		it++;
	}

	Iterator<String<TSize> >::Type it2 = begin(counterString);
	while (atEnd(it2)) {
		std::cout << AminoAcid(*it2) << " " << *it2 << std::endl;
		it2++;
	}

	std::cout << aaString << std::endl;
}


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.clients.commerce.catalog.admin;

import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

import com.mozu.api.DataViewMode;
/**
 * Use the Product Sort Definition resource to create, update, and delete sort order definitions used in visual merchandising.You can use these definitions to apply organization rules to a category defined by a product property or custom attribute. The sort order determines the order that products are displayed in, such as newest to oldest, so that they can be rearranged.
 *
 */
public class ProductSortDefinitionClient {

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection> mozuClient=GetProductSortDefinitionsClient(dataViewMode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinitionPagedCollection productSortDefinitionPagedCollection = client.Result();
	 *

	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection> getProductSortDefinitionsClient(com.mozu.api.DataViewMode dataViewMode) throws Exception
	{
		return getProductSortDefinitionsClient(dataViewMode,  null,  null,  null,  null,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection> mozuClient=GetProductSortDefinitionsClient(dataViewMode,  startIndex,  pageSize,  sortBy,  filter,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinitionPagedCollection productSortDefinitionPagedCollection = client.Result();
	 *

	 * @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
	 * @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information.
	 * @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection> getProductSortDefinitionsClient(com.mozu.api.DataViewMode dataViewMode, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.ProductSortDefinitionUrl.getProductSortDefinitionsUrl(filter, pageSize, responseFields, sortBy, startIndex);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection.class;
		MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinitionPagedCollection>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString());
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient=GetProductSortDefinitionClient(dataViewMode,  productSortDefinitionId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinition productSortDefinition = client.Result();
	 *

	 * @param productSortDefinitionId Unique identifier of the product sort definition.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinition>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> getProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, Integer productSortDefinitionId) throws Exception
	{
		return getProductSortDefinitionClient(dataViewMode,  productSortDefinitionId,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient=GetProductSortDefinitionClient(dataViewMode,  productSortDefinitionId,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinition productSortDefinition = client.Result();
	 *

	 * @param productSortDefinitionId Unique identifier of the product sort definition.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinition>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> getProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, Integer productSortDefinitionId, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.ProductSortDefinitionUrl.getProductSortDefinitionUrl(productSortDefinitionId, responseFields);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.productadmin.ProductSortDefinition.class;
		MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString());
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient=AddProductSortDefinitionClient(dataViewMode,  definition);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinition productSortDefinition = client.Result();
	 *

	 * @param definition Properties of the new product sort definition. Required properties of StartDate and Name.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinition>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> addProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductSortDefinition definition) throws Exception
	{
		return addProductSortDefinitionClient(dataViewMode,  definition,  null,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient=AddProductSortDefinitionClient(dataViewMode,  definition,  useProvidedId,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinition productSortDefinition = client.Result();
	 *

	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param useProvidedId If true, the provided Id value will be used as the ProductSortDefinitionId. If omitted or false, the system will generate a ProductSortDefinitionId
	 * @param definition Properties of the new product sort definition. Required properties of StartDate and Name.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinition>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> addProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductSortDefinition definition, Boolean useProvidedId, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.ProductSortDefinitionUrl.addProductSortDefinitionUrl(responseFields, useProvidedId);
		String verb = "POST";
		Class<?> clz = com.mozu.api.contracts.productadmin.ProductSortDefinition.class;
		MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(definition);
		mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString());
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient=UpdateProductSortDefinitionClient(dataViewMode,  definition,  productSortDefinitionId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinition productSortDefinition = client.Result();
	 *

	 * @param productSortDefinitionId Unique identifier of the product sort definition.
	 * @param definition The details of the product sort definition to update.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinition>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> updateProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductSortDefinition definition, Integer productSortDefinitionId) throws Exception
	{
		return updateProductSortDefinitionClient(dataViewMode,  definition,  productSortDefinitionId,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient=UpdateProductSortDefinitionClient(dataViewMode,  definition,  productSortDefinitionId,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * ProductSortDefinition productSortDefinition = client.Result();
	 *

	 * @param productSortDefinitionId Unique identifier of the product sort definition.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param definition The details of the product sort definition to update.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.ProductSortDefinition>
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 * @see com.mozu.api.contracts.productadmin.ProductSortDefinition
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> updateProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductSortDefinition definition, Integer productSortDefinitionId, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.ProductSortDefinitionUrl.updateProductSortDefinitionUrl(productSortDefinitionId, responseFields);
		String verb = "PUT";
		Class<?> clz = com.mozu.api.contracts.productadmin.ProductSortDefinition.class;
		MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.ProductSortDefinition>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(definition);
		mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString());
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=DeleteProductSortDefinitionClient(dataViewMode,  productSortDefinitionId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param productSortDefinitionId Unique identifier of the product sort definition.
	 * @return Mozu.Api.MozuClient
	 */
	public static MozuClient deleteProductSortDefinitionClient(com.mozu.api.DataViewMode dataViewMode, Integer productSortDefinitionId) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.ProductSortDefinitionUrl.deleteProductSortDefinitionUrl(productSortDefinitionId);
		String verb = "DELETE";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString());
		return mozuClient;

	}

}


text:
/**
 * Module dependencies.
 */
var passport = require('passport-strategy')
  , util = require('util');

/**
 * Creates an instance of `Strategy`.
 *
 * The anonymous authentication strategy passes authentication without verifying
 * credentials.
 *
 * Applications typically use this as a fallback on endpoints that can respond
 * to both authenticated and unauthenticated requests.  If credentials are not
 * supplied, this stategy passes authentication while leaving `req.user` set to
 * `undefined`, allowing the route to handle unauthenticated requests as
 * desired.
 *
 * Examples:
 *
 *     passport.use(new AnonymousStrategy());
 *
 * @constructor
 * @api public
 */
function Strategy() {
  passport.Strategy.call(this);
  this.name = 'anonymous';
}

/**
 * Inherit from `passport.Strategy`.
 */
util.inherits(Strategy, passport.Strategy);

/**
 * Pass authentication without verifying credentials.
 *
 * @param {Object} req
 * @api protected
 */
Strategy.prototype.authenticate = function() {
  this.pass();
};

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;


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

    angular
        .module('smn-ui')
        .directive('uiHour', uiHour);

    function uiHour(uiHourFilter) {
        var directive = {
            restrict: 'A',
            link: link,
            require: 'ngModel',
            scope: { }
        };
        return directive;

        function link(scope, element, attrs, ctrl) {
            ctrl.$parsers.push(function(value){
                var viewValue = formatValue(value);
                ctrl.$setViewValue(viewValue);
                ctrl.$render();
                viewValue = /^([0-9]|1[0-9]|2[0-3])$/.test(viewValue) ? viewValue : undefined;
                return viewValue;
            });
            ctrl.$formatters.push(formatValue);

            function formatValue(value) {
                return uiHourFilter(value);
            }
        }
    }

})();


text:
mapObject* st_navigateTo(address_t address, size_t bytes_needed);
void st_releasePages(mapObject* map_obj);

byte* mt_navigateTo(address_t address, size_t bytes_needed);
void mt_releasePages(address_t address, size_t bytes_needed);

#endif //NAVIGATE_H


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six

#from mpl_toolkits.axes_grid1.axes_rgb import *
from mpl_toolkits.axes_grid1.axes_rgb import make_rgb_axes, imshow_rgb, RGBAxesBase

#import mpl_toolkits.axes_grid1.axes_rgb as axes_rgb_orig
from .axislines import Axes

class RGBAxes(RGBAxesBase):
    _defaultAxesClass = Axes


text:
require "spec_helper"

describe Refinery do
  describe "Hooks" do
    describe "Admin" do
      describe "hooks" do
        login_refinery_user

        it "should not have 'Add New Hook'" do
          page.should_not have_content("Add New Hook")
        end
      end
    end
  end
end