text stringlengths 2 1.04M | meta dict |
|---|---|
require 'utils/view_helper'
module Utils
class Railtie < Rails::Railtie
initializer "utils.view_helper" do
ActionView::Base.send :include, ViewHelper
end
end
end | {
"content_hash": "4f1343f39e04fffef864c860ce512a4a",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 48,
"avg_line_length": 22.375,
"alnum_prop": 0.7206703910614525,
"repo_name": "wangfuhai2013/utils-rails",
"id": "ab0c06569b11fc23353aac9d85c0ecc3c01b6504",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/utils/railtie.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "34779"
}
],
"symlink_target": ""
} |
<div id="main">
<h1>Contact Us</h1>
<p>If you have any questions, feedback or propositions you can email us at info@calendarscripts.info or fill the form below:</p>
<form class="form" id="contactFrm">
<div><label>Your email:</label> <input type="text" name="email" class="required email"></div>
<div><label>Subject:</label> <input type="text" name="subject" class="required"></div>
<div>Message:<br> <textarea name="message" rows="10" cols="60" class="required"></textarea></div>
<div><input type="submit" value="Send Email"></div>
<input type="hidden" name="ok" value="1">
<input type="hidden" name="gender" value="male">
</form>
</div>
<script type="text/javascript">
$('#contactFrm').validate();
$('#contactFrm input[name=gender]').val('abv475');
</script> | {
"content_hash": "3476bc3a3ffce2f38f356300e6c302eb",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 128,
"avg_line_length": 38.095238095238095,
"alnum_prop": 0.65625,
"repo_name": "pimteam/Pyrostia",
"id": "5b55cc2c6fa910cdb263c23d1cafdab5d798f483",
"size": "800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/contact.html",
"mode": "33204",
"license": "mit",
"language": [],
"symlink_target": ""
} |
json_value *access_json_hash(const json_value *p, const json_char *key) {
if (p->type != json_object) return NULL;
for (unsigned i=0; i < p->u.object.length; i++) {
if (strcmp(p->u.object.values[i].name, key)==0) {
return p->u.object.values[i].value;
}
}
return NULL;
}
bool assertinteger(const char *varname, const json_value *val) {
if (val->type != json_integer) {
fprintf(stderr, "Expected integer for parameter %s\n", varname);
return false;
}
return true;
}
bool try_assign_integer_variable(unsigned short *out, const char *varname, const char *key, const json_value *val) {
if (strcmp(key, varname)==0) {
if (assertinteger(varname, val)) {*out = val->u.integer;return true;}
else return false;
}
return true;
}
bool json_assign_double(double *out, const json_value *val) {
if (val->type == json_double) {*out = val->u.dbl;return true;}
if (val->type == json_integer) {*out = val->u.integer;return true;}
return false;
}
bool json_assign_float(float *out, const json_value *val) {
double x=*out;
bool r = json_assign_double(&x, val);
*out = x;
return r;
}
bool try_assign_double_variable(double *out, const char *varname, const char *key, const json_value *val) {
if (strcmp(key, varname)==0) {
if (!json_assign_double(out,val)) {
fprintf(stderr, "Expected numeric parameter %s\n", varname);
return false;
}
return true;
}
return false;
}
bool try_assign_float_variable(float *out, const char *varname, const char *key, const json_value *val) {
double x=*out;
bool r = try_assign_double_variable(&x, varname, key, val);
*out = x;
return r;
}
char *json_string_to_cstring(const json_value *val) {
if (val->type != json_string) return NULL;
const char *p = val->u.string.ptr;
size_t ln = val->u.string.length;
char *res = (char*)malloc(ln+1);
if (!res) return NULL;
memcpy(res, p, ln);
res[ln]=0;
return res;
}
json_value *json_parse_file(const char *path, const char *type_name) {
unsigned long file_size=0;
char *json = (char*)load_file(path, &file_size);
if (!json) {
fprintf(stderr, "Failed to load json file %s\n", path);
return NULL;
}
json_value *p = json_parse(json, file_size);
free(json);
if (!p) {
fprintf(stderr, "Failed to parse json file %s\n", path);
return NULL;
}
if (type_name && !json_check_magic(p, type_name)) {
json_value_free(p);
return NULL;
}
return p;
}
bool json_check_magic(const json_value *p, const char *type_name) {
if (p->type != json_object) {
fprintf(stderr, "JSON must be an associative array!");
return false;
}
const json_value *map_type = access_json_hash(p, "type");
if (!map_type) {
fprintf(stderr, "JSON is not a %s (no type field)!", type_name);
return false;
}
if (!(map_type->type == json_string && strcmp(map_type->u.string.ptr, type_name)==0)) {
fprintf(stderr, "JSON is not a %s (type field is not %s)!", type_name, type_name);
return false;
}
return true;
}
| {
"content_hash": "77b2aa5c2db16de3b5ed3125573335b7",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 116,
"avg_line_length": 29.806122448979593,
"alnum_prop": 0.656966792194454,
"repo_name": "dridk/tankfighter",
"id": "f37def14e7d79f90f285d0d6913a3800eefa2628",
"size": "3023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "parse_json.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "37456"
},
{
"name": "C++",
"bytes": "201360"
},
{
"name": "Shell",
"bytes": "4842"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "1b6d9e61da3f395cfde6e72d77f2d8ff",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "2d5010091e52fd60f94208ef61ab2a40b9721b20",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Cymbopogon/Cymbopogon flexuosus/ Syn. Cymbopogon travancorensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <lib.h>
#include <fcntl.h> /* for the proto; emphasize varargs kludge */
PUBLIC int fcntl(fd, cmd, barf)
int fd;
int cmd;
int barf; /* varargs; fix it when open is fixed */
{
return(callm1(FS, FCNTL, fd, cmd, barf, NIL_PTR, NIL_PTR, NIL_PTR));
}
| {
"content_hash": "6963aa43f280ab5f00b06e972c0aefa1",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 70,
"avg_line_length": 26.1,
"alnum_prop": 0.6551724137931034,
"repo_name": "macminix/MacMinix",
"id": "7c6d3eb2c273143aa36250e407b0a57548453af3",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lib/posix/fcntl.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "360566"
},
{
"name": "C",
"bytes": "3820041"
},
{
"name": "C++",
"bytes": "18889"
},
{
"name": "IDL",
"bytes": "54"
},
{
"name": "Smalltalk",
"bytes": "3572"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>railroad-crossing: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.11.dev / railroad-crossing - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
railroad-crossing
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2020-07-16 03:01:33 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-16 03:01:33 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/railroad-crossing"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/RailroadCrossing"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:ctl" "keyword:tctl" "keyword:real time systems" "keyword:timed automatas" "keyword:safety" "keyword:concurrency" "keyword:properties" "keyword:invariants" "keyword:nonzeno" "keyword:discrete time" "category:Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols" "date:February-March 2000" ]
authors: [ "Carlos Daniel Luna <http://www.fing.edu.uy/~cluna>" ]
bug-reports: "https://github.com/coq-contribs/railroad-crossing/issues"
dev-repo: "git+https://github.com/coq-contribs/railroad-crossing.git"
synopsis: "The Railroad Crossing Example"
description: """
This library present the specification and verification of
one real time system: the Railroad Crossing Problem, which has been
proposed as a benchmark for the comparison of real-time formalisms. We
specify the system using timed automatas (timed graphs) with discrete
time and we prove invariants, the system safety property and the NonZeno
property, using the logics CTL and TCTL."""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/railroad-crossing/archive/v8.5.0.tar.gz"
checksum: "md5=aa5d5cef3b3a7a723b2040f90219f866"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-railroad-crossing.8.5.0 coq.8.11.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev).
The following dependencies couldn't be met:
- coq-railroad-crossing -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-railroad-crossing.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "559261e042971c21a4f61cae98c6b72b",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 457,
"avg_line_length": 44.50588235294118,
"alnum_prop": 0.5672746497488765,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "c765e8cfa32ab70b6dae6b1c14b27291e0597704",
"size": "7591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/extra-dev/8.11.dev/railroad-crossing/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#!/bin/bash
#
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
set -e
set -u
DIR="$( cd -P "$( dirname "$0" )" && pwd )"
SYSTEM_EXT_DIR="${DIR}/../ext"
JAVA_OPTIONS=${JAVA_OPTIONS:-}
if [ ! -z "${JAVA_OPTIONS}" ]; then
USER_EXT_DIR=$(grep -o '\-Dtinkerpop.ext=\(\([^"][^ ]*\)\|\("[^"]*"\)\)' <<< "${JAVA_OPTIONS}" | cut -f2 -d '=' | xargs -0 echo)
if [ ! -z "${USER_EXT_DIR}" -a ! -d "${USER_EXT_DIR}" ]; then
mkdir -p "${USER_EXT_DIR}"
cp -R ${SYSTEM_EXT_DIR}/* ${USER_EXT_DIR}/
fi
fi
case `uname` in
CYGWIN*)
CP="`dirname $0`"/../config
CP="$CP":$( echo `dirname $0`/../lib/*.jar . | sed 's/ /;/g')
;;
*)
CP="`dirname $0`"/../config
CP="$CP":$( echo `dirname $0`/../lib/*.jar . | sed 's/ /:/g')
esac
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
CP=$CP:$( find -L "${SYSTEM_EXT_DIR}" "${USER_EXT_DIR:-${SYSTEM_EXT_DIR}}" -mindepth 1 -maxdepth 1 -type d | \
sort -u | sed 's/$/\/plugin\/*/' | tr '\n' ':' )
export CLASSPATH="${CLASSPATH:-}:$CP"
# Find Java
if [ -z "${JAVA_HOME:-}" ]; then
JAVA="java -server"
else
JAVA="$JAVA_HOME/bin/java -server"
fi
# Set default message threshold for Log4j Gremlin's console appender
if [ -z "${GREMLIN_LOG_LEVEL:-}" ]; then
GREMLIN_LOG_LEVEL=WARN
fi
# Script debugging is disabled by default, but can be enabled with -l
# TRACE or -l DEBUG or enabled by exporting
# SCRIPT_DEBUG=nonemptystring to gremlin.sh's environment
if [ -z "${SCRIPT_DEBUG:-}" ]; then
SCRIPT_DEBUG=
fi
# Process options
MAIN_CLASS=org.apache.tinkerpop.gremlin.console.Console
while getopts "elv" opt; do
case "$opt" in
e) MAIN_CLASS=org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptExecutor
# For compatibility with behavior pre-Titan-0.5.0, stop
# processing gremlin.sh arguments as soon as the -e switch is
# seen; everything following -e becomes arguments to the
# ScriptExecutor main class
break;;
l) eval GREMLIN_LOG_LEVEL=\$$OPTIND
OPTIND="$(( $OPTIND + 1 ))"
if [ "$GREMLIN_LOG_LEVEL" = "TRACE" -o \
"$GREMLIN_LOG_LEVEL" = "DEBUG" ]; then
SCRIPT_DEBUG=y
fi
;;
v) MAIN_CLASS=org.apache.tinkerpop.gremlin.util.Gremlin
esac
done
# Remove processed options from $@. Anything after -e is preserved by the break;; in the case
shift $(( $OPTIND - 1 ))
JAVA_OPTIONS="${JAVA_OPTIONS} -Dtinkerpop.ext=${USER_EXT_DIR:-${SYSTEM_EXT_DIR}} -Dlog4j.configuration=conf/log4j-console.properties -Dgremlin.log4j.level=$GREMLIN_LOG_LEVEL"
JAVA_OPTIONS=$(awk -v RS=' ' '!/^$/ {if (!x[$0]++) print}' <<< "${JAVA_OPTIONS}" | grep -v '^$' | paste -sd ' ' -)
if [ -n "$SCRIPT_DEBUG" ]; then
echo "CLASSPATH: $CLASSPATH"
set -x
fi
# include the following in $JAVA_OPTIONS "-Divy.message.logger.level=4 -Dgroovy.grape.report.downloads=true" to debug :install
# Start the JVM, execute the application, and return its exit code
exec $JAVA $JAVA_OPTIONS $MAIN_CLASS "$@"
| {
"content_hash": "f58c37b627444fd2f5bf7a5f04c073ea",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 174,
"avg_line_length": 33.92035398230089,
"alnum_prop": 0.635794416905818,
"repo_name": "mike-tr-adamson/incubator-tinkerpop",
"id": "84ba81791bf19fa22fdefbf14d43fb96fdc948cf",
"size": "3833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gremlin-console/src/main/bin/gremlin.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4544"
},
{
"name": "Groovy",
"bytes": "382411"
},
{
"name": "Java",
"bytes": "6707824"
},
{
"name": "Python",
"bytes": "1481"
},
{
"name": "Shell",
"bytes": "32352"
}
],
"symlink_target": ""
} |
package org.hswebframework.web.system.authorization.api.entity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import org.hswebframework.ezorm.rdb.mapping.annotation.ColumnType;
import org.hswebframework.ezorm.rdb.mapping.annotation.Comment;
import org.hswebframework.ezorm.rdb.mapping.annotation.DefaultValue;
import org.hswebframework.ezorm.rdb.mapping.annotation.JsonCodec;
import org.hswebframework.web.api.crud.entity.GenericEntity;
import org.hswebframework.web.api.crud.entity.RecordCreationEntity;
import org.hswebframework.web.api.crud.entity.RecordModifierEntity;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.crud.generator.Generators;
import org.hswebframework.web.validator.CreateGroup;
import org.springframework.util.CollectionUtils;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.sql.JDBCType;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Table(name = "s_permission")
@Comment("权限信息")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PermissionEntity extends GenericEntity<String> implements RecordCreationEntity, RecordModifierEntity {
@Override
@Pattern(regexp = "^[0-9a-zA-Z_\\-]+$", message = "ID只能由数字,字母,下划线和中划线组成", groups = CreateGroup.class)
public String getId() {
return super.getId();
}
@Column
@Comment("权限名称")
@Schema(description = "权限名称")
@NotBlank(message = "权限名称不能为空", groups = CreateGroup.class)
private String name;
@Column
@Comment("说明")
@Schema(description = "说明")
private String describe;
@Column(nullable = false)
@Comment("状态")
@Schema(description = "状态")
@DefaultValue("1")
private Byte status;
@Column
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("可选操作")
@Schema(description = "可选操作")
private List<ActionEntity> actions;
@Column(name = "optional_fields")
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("可操作的字段")
@Schema(description = "可操作字段")
private List<OptionalField> optionalFields;
@Column
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("关联权限")
@Schema(description = "关联权限")
private List<ParentPermission> parents;
@Column
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("其他配置")
@Schema(description = "其他配置")
private Map<String, Object> properties;
@Schema(description = "创建时间")
@Column(updatable = false)
@DefaultValue(generator = Generators.CURRENT_TIME)
private Long createTime;
@Schema(description = "创建人ID")
@Column(length = 64, updatable = false)
private String creatorId;
@Schema(description = "修改时间")
@Column
@DefaultValue(generator = Generators.CURRENT_TIME)
private Long modifyTime;
@Schema(description = "修改人ID")
@Column(length = 64, updatable = false)
private String modifierId;
public PermissionEntity copy(Predicate<ActionEntity> actionFilter,
Predicate<OptionalField> fieldFilter) {
PermissionEntity entity = FastBeanCopier.copy(this, new PermissionEntity());
if (!CollectionUtils.isEmpty(entity.getActions())) {
entity.setActions(entity.getActions().stream().filter(actionFilter).collect(Collectors.toList()));
}
if (!CollectionUtils.isEmpty(entity.getOptionalFields())) {
entity.setOptionalFields(entity
.getOptionalFields()
.stream()
.filter(fieldFilter)
.collect(Collectors.toList()));
}
return entity;
}
}
| {
"content_hash": "038c60146f15b31ca59bbbe1ea93d9a3",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 115,
"avg_line_length": 32.768595041322314,
"alnum_prop": 0.6870113493064313,
"repo_name": "hs-web/hsweb-framework",
"id": "dd596d6fa0a171d666df836371b1d5a82aa8e49a",
"size": "4151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hsweb-system/hsweb-system-authorization/hsweb-system-authorization-api/src/main/java/org/hswebframework/web/system/authorization/api/entity/PermissionEntity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1352858"
},
{
"name": "JavaScript",
"bytes": "3965"
},
{
"name": "Shell",
"bytes": "91"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.0.3328.4
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by Microsoft.VSDesigner, Version 1.0.3328.4.
//
namespace hsProxy.myAlertsNs {
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Web.Services;
/// <remarks/>
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="myAlertsBinding", Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts/wsdl")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(myAlertsType))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(string[]))]
public class myAlerts : System.Web.Services.Protocols.SoapHttpClientProtocol {
public pathType path;
public licenses licensesValue;
public requestType request;
public echoBackType echoBack;
public responseType response;
/// <remarks/>
public myAlerts() {
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("insertResponse", Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public insertResponse insert([System.Xml.Serialization.XmlElementAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")] insertRequestType insertRequest) {
object[] results = this.Invoke("insert", new object[] {
insertRequest});
return ((insertResponse)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Begininsert(insertRequestType insertRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("insert", new object[] {
insertRequest}, callback, asyncState);
}
/// <remarks/>
public insertResponse Endinsert(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((insertResponse)(results[0]));
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("deleteResponse", Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public deleteResponse delete([System.Xml.Serialization.XmlElementAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")] deleteRequestType deleteRequest) {
object[] results = this.Invoke("delete", new object[] {
deleteRequest});
return ((deleteResponse)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Begindelete(deleteRequestType deleteRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete", new object[] {
deleteRequest}, callback, asyncState);
}
/// <remarks/>
public deleteResponse Enddelete(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((deleteResponse)(results[0]));
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("replaceResponse", Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public replaceResponse replace([System.Xml.Serialization.XmlElementAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")] replaceRequestType replaceRequest) {
object[] results = this.Invoke("replace", new object[] {
replaceRequest});
return ((replaceResponse)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Beginreplace(replaceRequestType replaceRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("replace", new object[] {
replaceRequest}, callback, asyncState);
}
/// <remarks/>
public replaceResponse Endreplace(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((replaceResponse)(results[0]));
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("updateResponse", Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public updateResponseType update([System.Xml.Serialization.XmlArrayAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")] [System.Xml.Serialization.XmlArrayItemAttribute("updateBlock", Namespace="http://schemas.microsoft.com/hs/2001/10/core", IsNullable=false)] updateBlockType[] updateRequest) {
object[] results = this.Invoke("update", new object[] {
updateRequest});
return ((updateResponseType)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Beginupdate(updateBlockType[] updateRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("update", new object[] {
updateRequest}, callback, asyncState);
}
/// <remarks/>
public updateResponseType Endupdate(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((updateResponseType)(results[0]));
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("queryResponse", Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public queryResponseType query([System.Xml.Serialization.XmlElementAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")] queryRequestType queryRequest) {
object[] results = this.Invoke("query", new object[] {
queryRequest});
return ((queryResponseType)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Beginquery(queryRequestType queryRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("query", new object[] {
queryRequest}, callback, asyncState);
}
/// <remarks/>
public queryResponseType Endquery(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((queryResponseType)(results[0]));
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", RequestNamespace="http://schemas.microsoft.com/hs/2001/10/core", ResponseNamespace="http://schemas.microsoft.com/hs/2001/10/core", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
public void sendXml([System.Xml.Serialization.XmlAnyElementAttribute()] ref System.Xml.XmlElement any) {
object[] results = this.Invoke("sendXml", new object[] {
any});
any = ((System.Xml.XmlElement)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginsendXml(System.Xml.XmlElement any, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("sendXml", new object[] {
any}, callback, asyncState);
}
/// <remarks/>
public void EndsendXml(System.IAsyncResult asyncResult, out System.Xml.XmlElement any) {
object[] results = this.EndInvoke(asyncResult);
any = ((System.Xml.XmlElement)(results[0]));
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", OneWay=true, Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
public void notify([System.Xml.Serialization.XmlArrayAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")] [System.Xml.Serialization.XmlArrayItemAttribute("notification", Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts", IsNullable=false)] notificationType[] notifyRequest) {
this.Invoke("notify", new object[] {
notifyRequest});
}
/// <remarks/>
public System.IAsyncResult Beginnotify(notificationType[] notifyRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("notify", new object[] {
notifyRequest}, callback, asyncState);
}
/// <remarks/>
public void Endnotify(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
[Microsoft.Hs.HsSoapExtensionAttribute(true)]
[System.Web.Services.Protocols.SoapHeaderAttribute("echoBack", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut, Required=false)]
[System.Web.Services.Protocols.SoapHeaderAttribute("response", Direction=System.Web.Services.Protocols.SoapHeaderDirection.Out)]
[System.Web.Services.Protocols.SoapHeaderAttribute("licensesValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("request")]
[System.Web.Services.Protocols.SoapHeaderAttribute("path", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://schemas.microsoft.com/hs/2001/10/core#request", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("pollResponse", Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public pollResponse poll([System.Xml.Serialization.XmlElementAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")] pollRequest pollRequest) {
object[] results = this.Invoke("poll", new object[] {
pollRequest});
return ((pollResponse)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Beginpoll(pollRequest pollRequest, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("poll", new object[] {
pollRequest}, callback, asyncState);
}
/// <remarks/>
public pollResponse Endpoll(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((pollResponse)(results[0]));
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
[System.Xml.Serialization.XmlRootAttribute("echoBack", Namespace="http://schemas.microsoft.com/hs/2001/10/core", IsNullable=false)]
public class echoBackType : SoapHeader {
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class pollResponse {
/// <remarks/>
public notificationType notification;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class notificationType {
/// <remarks/>
public fromType from;
/// <remarks/>
public toType to;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("contents")]
public System.Xml.XmlElement[] contents;
/// <remarks/>
public routingType routing;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class fromType {
/// <remarks/>
public identityHeaderType identityHeader;
/// <remarks/>
public expiresType expiresAt;
/// <remarks/>
public string acknowledge;
/// <remarks/>
public categoryType category;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class identityHeaderType {
/// <remarks/>
public string onBehalfOfUser;
/// <remarks/>
public string licenseHolder;
/// <remarks/>
public string platformId;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class expiresType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ttl;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string onDate;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string replace;
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class categoryType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class toType {
/// <remarks/>
public string originalUser;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class routingType {
/// <remarks/>
public string timestamp;
/// <remarks/>
public string hops;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class pollRequest {
/// <remarks/>
public string parkInterval;
/// <remarks/>
[System.Xml.Serialization.XmlNamespaceDeclarationsAttribute()]
public System.Xml.Serialization.XmlSerializerNamespaces xmlns;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class deletedBlueType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class queryResponseTypeChangeQueryResponse {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("changedBlue")]
public System.Xml.XmlElement[] changedBlue;
/// <remarks/>
public deletedBlueType deletedBlue;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string baseChangeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int selectedNodeCount;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool selectedNodeCountSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public responseStatus status;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum responseStatus {
/// <remarks/>
success,
/// <remarks/>
failure,
/// <remarks/>
rollback,
/// <remarks/>
notAttempted,
/// <remarks/>
accessDenied,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(myAlerts1))]
public class myAlertsType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("stream")]
public streamType[] stream;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("connection")]
public connectionType[] connection;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("subscription")]
public subscriptionType[] subscription;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class streamType {
/// <remarks/>
public streamClassType @class;
/// <remarks/>
public string expiration;
/// <remarks/>
public streamPositionType position;
/// <remarks/>
public notificationQueryType argotQuery;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool argotQuerySpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("argot")]
public argotType[] argot;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string changeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="hexBinary")]
public System.Byte[] creator;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public enum streamClassType {
/// <remarks/>
buffer,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public enum streamPositionType {
/// <remarks/>
atFront,
/// <remarks/>
atEnd,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public enum notificationQueryType {
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("*")]
Item,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class argotType {
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")]
public string argotURI;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class connectionType {
/// <remarks/>
public connectionClassType @class;
/// <remarks/>
public connectionStatusType status;
/// <remarks/>
public connectionCharacteristicsType characteristics;
/// <remarks/>
public string expiration;
/// <remarks/>
public notificationQueryType argotQuery;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("argot")]
public argotType[] argot;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string changeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="hexBinary")]
public System.Byte[] creator;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public enum connectionClassType {
/// <remarks/>
push_http,
/// <remarks/>
pull_http,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public enum connectionStatusType {
/// <remarks/>
active,
/// <remarks/>
inactive,
/// <remarks/>
busy,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public enum connectionCharacteristicsType {
/// <remarks/>
reliable,
/// <remarks/>
unreliable,
/// <remarks/>
connectionPoll,
/// <remarks/>
userAgentPoll,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class subscriptionType {
/// <remarks/>
public subscriptionTypeTrigger trigger;
/// <remarks/>
public System.DateTime expiresAt;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool expiresAtSpecified;
/// <remarks/>
public subscriptionTypeContext context;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string to;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string changeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="hexBinary")]
public System.Byte[] creator;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class subscriptionTypeTrigger {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public subscriptionTypeTriggerMode mode;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string baseChangeNumber;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum subscriptionTypeTriggerMode {
/// <remarks/>
includeData,
/// <remarks/>
excludeData,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class subscriptionTypeContext {
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")]
public string uri;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(TypeName="myAlerts", Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public class myAlerts1 : myAlertsType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string changeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string instanceId;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class queryResponseTypeXpQueryResponse {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("myAlerts", typeof(myAlerts1), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("stream", typeof(streamType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("connection", typeof(connectionType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("subscription", typeof(subscriptionType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public object[] Items;
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int selectedNodeCount;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool selectedNodeCountSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public responseStatus status;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class queryResponseType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("xpQueryResponse")]
public queryResponseTypeXpQueryResponse[] xpQueryResponse;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("changeQueryResponse")]
public queryResponseTypeChangeQueryResponse[] changeQueryResponse;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class changeQueryType {
/// <remarks/>
public queryOptionsType options;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string baseChangeNumber;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class queryOptionsType {
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("sort")]
public sortType[] sort;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("range")]
public rangeType[] range;
/// <remarks/>
public shapeType shape;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class sortType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(sortTypeDirection.ascending)]
public sortTypeDirection direction = sortTypeDirection.ascending;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string key;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum sortTypeDirection {
/// <remarks/>
ascending,
/// <remarks/>
descending,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class rangeType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string first;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int count;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class shapeType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("include")]
public shapeAtomType[] include;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("exclude")]
public shapeAtomType[] exclude;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public shapeTypeBase @base;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool baseSpecified;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class shapeAtomType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum shapeTypeBase {
/// <remarks/>
t,
/// <remarks/>
nil,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class xpQueryType {
/// <remarks/>
public queryOptionsType options;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int minOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool minOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int maxOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxOccursSpecified;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class queryRequestType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("xpQuery")]
public xpQueryType[] xpQuery;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("changeQuery")]
public changeQueryType[] changeQuery;
/// <remarks/>
[System.Xml.Serialization.XmlNamespaceDeclarationsAttribute()]
public System.Xml.Serialization.XmlSerializerNamespaces xmlns;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class updateResponseTypeUpdateBlockStatus {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("insertResponse")]
public insertResponse[] insertResponse;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("deleteResponse")]
public deleteResponse[] deleteResponse;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("replaceResponse")]
public replaceResponse[] replaceResponse;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int selectedNodeCount;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool selectedNodeCountSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public responseStatus status;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class insertResponse {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("newBlueId")]
public newBlueIdType[] newBlueId;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string newChangeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int selectedNodeCount;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool selectedNodeCountSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public responseStatus status;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class newBlueIdType {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class deleteResponse {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string newChangeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int selectedNodeCount;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool selectedNodeCountSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public responseStatus status;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class replaceResponse {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("newBlueId")]
public newBlueIdType[] newBlueId;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string newChangeNumber;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int selectedNodeCount;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool selectedNodeCountSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public responseStatus status;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class updateResponseType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("updateBlockStatus")]
public updateResponseTypeUpdateBlockStatus[] updateBlockStatus;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")]
public string newChangeNumber;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class updateBlockType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("insertRequest")]
public insertRequestType[] insertRequest;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("deleteRequest")]
public deleteRequestType[] deleteRequest;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("replaceRequest")]
public replaceRequestType[] replaceRequest;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public updateBlockTypeOnError onError;
/// <remarks/>
[System.Xml.Serialization.XmlNamespaceDeclarationsAttribute()]
public System.Xml.Serialization.XmlSerializerNamespaces xmlns;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class insertRequestType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("options")]
public System.Xml.XmlElement[] options;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("stream", typeof(streamType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("connection", typeof(connectionType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("subscription", typeof(subscriptionType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public object[] Items;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("attributes")]
public redAttributeType[] attributes;
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public useClientIdsType useClientIds;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool useClientIdsSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int minOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool minOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int maxOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlNamespaceDeclarationsAttribute()]
public System.Xml.Serialization.XmlSerializerNamespaces xmlns;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class redAttributeType {
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum useClientIdsType {
/// <remarks/>
@true,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class deleteRequestType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("options")]
public System.Xml.XmlElement[] options;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int minOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool minOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int maxOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlNamespaceDeclarationsAttribute()]
public System.Xml.Serialization.XmlSerializerNamespaces xmlns;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class replaceRequestType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("options")]
public System.Xml.XmlElement[] options;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("stream", typeof(streamType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("connection", typeof(connectionType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
[System.Xml.Serialization.XmlElementAttribute("subscription", typeof(subscriptionType), Namespace="http://schemas.microsoft.com/hs/2001/10/myAlerts")]
public object[] Items;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("attributes")]
public redAttributeType[] attributes;
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string select;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public useClientIdsType useClientIds;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool useClientIdsSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int minOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool minOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int maxOccurs;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxOccursSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlNamespaceDeclarationsAttribute()]
public System.Xml.Serialization.XmlSerializerNamespaces xmlns;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum updateBlockTypeOnError {
/// <remarks/>
rollbackBlockAndFail,
/// <remarks/>
rollbackBlockAndContinue,
/// <remarks/>
ignore,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class requestTypeKey {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string puid;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string instance;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string cluster;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public class identityType {
/// <remarks/>
public int kerberos;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.xmlsoap.org/rp/")]
public class pathTypeFault {
/// <remarks/>
public int faultcode;
/// <remarks/>
public string faultreason;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string endpoint;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("at", DataType="anyURI", IsNullable=false)]
public string[] found;
/// <remarks/>
public int maxsize;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxsizeSpecified;
/// <remarks/>
public int maxtime;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxtimeSpecified;
/// <remarks/>
public int retryAfter;
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool retryAfterSpecified;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.xmlsoap.org/rp/")]
public class viaChainTypeVia {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")]
public string vid;
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute(DataType="anyURI")]
public string Value;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
[System.Xml.Serialization.XmlRootAttribute("response", Namespace="http://schemas.microsoft.com/hs/2001/10/core", IsNullable=false)]
public class responseType : SoapHeader {
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string role;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.xmlsoap.org/soap/security/2000-12")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://schemas.xmlsoap.org/soap/security/2000-12", IsNullable=false)]
public class licenses : SoapHeader {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public identityType identity;
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any;
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
[System.Xml.Serialization.XmlRootAttribute("request", Namespace="http://schemas.microsoft.com/hs/2001/10/core", IsNullable=false)]
public class requestType : SoapHeader {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("key")]
public requestTypeKey[] key;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string service;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public requestTypeDocument document;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string method;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public requestTypeGenResponse genResponse;
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum requestTypeDocument {
/// <remarks/>
content,
/// <remarks/>
roleList,
/// <remarks/>
policy,
/// <remarks/>
system,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/hs/2001/10/core")]
public enum requestTypeGenResponse {
/// <remarks/>
always,
/// <remarks/>
never,
/// <remarks/>
faultOnly,
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.xmlsoap.org/rp/")]
[System.Xml.Serialization.XmlRootAttribute("path", Namespace="http://schemas.xmlsoap.org/rp/", IsNullable=false)]
public class pathType : SoapHeader {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string action;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string to;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("via", IsNullable=false)]
public viaChainTypeVia[] fwd;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("via", IsNullable=false)]
public viaChainTypeVia[] rev;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string from;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string id;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string relatesTo;
/// <remarks/>
public pathTypeFault fault;
}
}
| {
"content_hash": "0d868150fd6e22c90de29ab093bf6e30",
"timestamp": "",
"source": "github",
"line_count": 1437,
"max_line_length": 384,
"avg_line_length": 39.84620737647877,
"alnum_prop": 0.615431635201453,
"repo_name": "theill/iquomi",
"id": "80ab1cb5b201774e37e521ef0968e0a623abac17",
"size": "57261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "research/myVoices/source/hsProxy/Web References/myAlertsNs/Reference.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "224842"
},
{
"name": "C#",
"bytes": "5393659"
},
{
"name": "CSS",
"bytes": "30092"
},
{
"name": "HTML",
"bytes": "247898"
},
{
"name": "JavaScript",
"bytes": "60563"
},
{
"name": "Shell",
"bytes": "3892"
},
{
"name": "Visual Basic",
"bytes": "3664"
},
{
"name": "XSLT",
"bytes": "27235"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Debtor_FindByTelephoneAndFaxNumberResponse xmlns="http://e-conomic.com">
<Debtor_FindByTelephoneAndFaxNumberResult>
<DebtorHandle>
<Number>1</Number>
</DebtorHandle>
</Debtor_FindByTelephoneAndFaxNumberResult>
</Debtor_FindByTelephoneAndFaxNumberResponse>
</soap:Body>
</soap:Envelope> | {
"content_hash": "1805243bd52b1618c65f68a499b615db",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 169,
"avg_line_length": 46.416666666666664,
"alnum_prop": 0.7127468581687613,
"repo_name": "substancelab/rconomic",
"id": "d0c614f520fa8de4b71a9480b7dc350b6943bc67",
"size": "557",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spec/fixtures/debtor_find_by_telephone_and_fax_number/found.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "193764"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_63a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-63a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sinks: memmove
* BadSink : Copy TwoIntsClass array to data using memmove
* Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_63
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(TwoIntsClass * * dataPtr);
void bad()
{
TwoIntsClass * data;
data = NULL;
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new TwoIntsClass[50];
badSink(&data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(TwoIntsClass * * data);
static void goodG2B()
{
TwoIntsClass * data;
data = NULL;
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new TwoIntsClass[100];
goodG2BSink(&data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_63; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "d3551ec90ed66ba5e355211b131f2234",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 131,
"avg_line_length": 27.885057471264368,
"alnum_prop": 0.6735366859027205,
"repo_name": "maurer/tiamat",
"id": "5b1bdf165ab11e640311b43927c7990ec6ef242b",
"size": "2426",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s03/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_63a.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
namespace MIG.Interfaces.HomeAutomation.Api
{
public class ModuleProperties
{
public string Name { get; set; }
public string Description { get; set; }
public string Value { get; set; }
public string UpdateTime { get; set; }
public bool NeedsUpdate { get; set; }
}
}
| {
"content_hash": "3346d7b614e773f1a78cd3ac256a7857",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 47,
"avg_line_length": 21.533333333333335,
"alnum_prop": 0.6037151702786377,
"repo_name": "davidwallis3101/HomegenieEchoBridge",
"id": "415b55a28599eaf1ddcc6dbb65a790b7b2edf566",
"size": "325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MIG-Interface/Api/ModuleProperties.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "79184"
},
{
"name": "HTML",
"bytes": "3668"
},
{
"name": "PowerShell",
"bytes": "3379"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Procto, '.call' do
subject { klass.call(text) }
context 'with no name' do
include_context 'procto'
let(:klass) do
Class.new do
include Procto.call
def initialize(text)
@text = text
end
def call
"Hello #{@text}"
end
end
end
end
context 'with a name' do
include_context 'procto'
let(:name) { double('name', to_sym: :print) }
let(:klass) do
method_name = name
Class.new do
include Procto.call(method_name)
def initialize(text)
@text = text
end
def print
"Hello #{@text}"
end
end
end
end
end
| {
"content_hash": "bfed2a1f189c27e66ca302e801d7e371",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 49,
"avg_line_length": 16.295454545454547,
"alnum_prop": 0.5230125523012552,
"repo_name": "snusnu/procto",
"id": "bcff982a3c195c6cf1a9aafd0cf2bfe2d103dd76",
"size": "736",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/unit/procto/call_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "5253"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "3a8184be0320058ac15f0c8554f64ff9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f7d901ad093a4dc287f416f714aaf4525814dc83",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Proteales/Proteaceae/Banksia/Dryandra pteridifolia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'htable'
class ServicesController < ApplicationController
before_action :set_service, only: [:show, :edit, :update, :destroy, :updateAccessToken]
before_action :set_active
# GET /services
def index
user = User.find(session[:user_id])
@authority = user.authority
if @authority == 'master'
@services = Service.all.order(:service_name)
else
authorities = Authority.where(user_id: session[:user_id]).select("service_id")
@services = Service.where(id: authorities).order(:service_name)
end
end
# GET /services/1
def show
# @service_columns = ServiceColumn.joins(:column_metas).where(service_id: @service.id).select("service_columns.*, column_metas.*")
@service_columns = ServiceColumn.joins('LEFT OUTER JOIN column_metas ON column_metas.column_id = service_columns.id')
.where(service_id: @service.id)
.select("service_columns.*, column_metas.id as meta_id, column_metas.name, column_metas.column_id, column_metas.seq, column_metas.data_type")
@labels = Label.where(service_id: @service.id)
createService = {"serviceName" => @service.service_name, "hTableName" => @service.hbase_table_name, "preSplitSize" => @service.pre_split_size}
if @service.hbase_table_ttl != nil
createService["hTableTTL"] = @service.hbase_table_ttl
end
createServiceCURL = "curl -XPOST localhost:9000/graphs/createService -H 'Content-Type: Application/json' -d '\n#{JSON.pretty_generate(createService)}\n'"
@createCURLs = createServiceCURL
@labels.each do | label |
# curl -XPOST localhost:9000/graphs/createLabel -H 'Content-Type: Application/json' -d '
# {
# "label": "user_article_liked",
# "srcServiceName": "s2graph",
# "srcColumnName": "user_id",
# "srcColumnType": "long",
# "tgtServiceName": "s2graph_news",
# "tgtColumnName": "article_id",
# "tgtColumnType": "string",
# "indices": [], // _timestamp will be used as default
# "props": [],
# "serviceName": "s2graph_news"
# }
# '
labelPostfix = label.label.split("_").last
next if (labelPostfix == "counts" || labelPostfix == "topK")
labelMetas = LabelMetum.where(label_id: label.id)
labelIndices = LabelIndex.where(label_id: label.id).order(seq: :asc)
props = labelMetas.map do | meta |
{"name" => meta.name, "defaultValue" => meta.default_value, "dataType" => meta.data_type}
end
indices = labelIndices.map do | index |
logger.error(index.meta_seqs)
prop_names = index.meta_seqs.split(",").map do |meta_seq|
meta_seq = meta_seq.to_i
if meta_seq == 0
"_timestamp"
elsif meta_seq == -5
"_to"
elsif meta_seq == -8
"_from_hash"
else
labelMetas.where(seq: meta_seq).first.name
end
end
{"name" => index.name, "propNames" => prop_names}
end
createLabel = {"label" => label.label, "srcServiceName" => Service.find(label.src_service_id).service_name, "srcColumnName" => label.src_column_name, "srcColumnType" => label.src_column_type,
"srcServiceName" => Service.find(label.src_service_id).service_name, "srcColumnName" => label.src_column_name, "srcColumnType" => label.src_column_type,
"indices" => indices, "props" => props, "serviceName" => Service.find(label.service_id).service_name,
"consistencyLevel" => label.consistency_level, "hTableName" => label.hbase_table_name}
if label.is_directed == 1
createLabel["isDirected"] = "true"
else
createLabel["isDirected"] = "false"
end
if label.hbase_table_ttl != nil
createLabel["hTableTTL"] = label.hbase_table_ttl
end
createLabelCURL = "curl -XPOST localhost:9000/graphs/createLabel -H 'Content-Type: Application/json' -d '\n#{JSON.pretty_generate(createLabel)}\n'"
@createCURLs = @createCURLs + "\n\n" + createLabelCURL
end
end
# GET /services/new
def new
user = User.find(session[:user_id])
@authority = user.authority
if @authority != "master" then
head :forbidden
else
@service = Service.new
end
end
# GET /services/1/edit
def edit
end
# POST /services
def create
@service = Service.new(service_params)
result = HTable.createTable(@service.cluster, @service.hbase_table_name, @service.pre_split_size, @service.hbase_table_ttl, nil)
if result
if @service.save
redirect_to services_url, notice: 'Service was successfully created.'
else
render :new
end
else
render :new
end
end
# PATCH/PUT /services/1
def update
if @service.update(service_params)
redirect_to @service, notice: 'Service was successfully updated.'
else
render :edit
end
end
def updateAccessToken
if @service.update(access_token: params[:access_token])
result = Hash["status" => "success"]
render json: result.to_json
else
result = Hash["status" => "fail"]
render json: result.to_json
end
end
# DELETE /services/1
def destroy
@service.destroy
redirect_to services_url, notice: 'Service was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_service
@service = Service.find(params[:id])
has_authority
end
def has_authority
user = User.find(session[:user_id])
@authority = user.authority
if @authority != "master" then
authorities = Authority.where(user_id: session[:user_id], service_id: @service.id)
if authorities.size <= 0
head :forbidden
end
end
end
# Only allow a trusted parameter "white list" through.
def service_params
params.require(:service).permit(:service_name, :access_token, :cluster, :hbase_table_name, :pre_split_size, :hbase_table_ttl)
end
def set_active
@active = "s2graph"
end
end
| {
"content_hash": "76860b135b2f3a151c33ea09c6963023",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 197,
"avg_line_length": 34.293785310734464,
"alnum_prop": 0.6319604612850083,
"repo_name": "kakao/s2graph-admin",
"id": "0fb4b42d2b84a788da6a4aa98af62db03944f80a",
"size": "6070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/services_controller.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "63022"
},
{
"name": "HTML",
"bytes": "66857"
},
{
"name": "JavaScript",
"bytes": "1647880"
},
{
"name": "Ruby",
"bytes": "130274"
},
{
"name": "Shell",
"bytes": "675"
}
],
"symlink_target": ""
} |
<!-- Copyright 2012-2017 Raytheon BBN Technologies Corp. All Rights Reserved. -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_20) on Wed Nov 15 19:26:04 EST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>adept-api 2.7.4 API</title>
<script type="text/javascript">
targetPage = "" + window.location.search;
if (targetPage != "" && targetPage != "undefined")
targetPage = targetPage.substring(1);
if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage)))
targetPage = "undefined";
function validURL(url) {
try {
url = decodeURIComponent(url);
}
catch (error) {
return false;
}
var pos = url.indexOf(".html");
if (pos == -1 || pos != url.length - 5)
return false;
var allowNumber = false;
var allowSep = false;
var seenDot = false;
for (var i = 0; i < url.length - 5; i++) {
var ch = url.charAt(i);
if ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
ch == '$' ||
ch == '_' ||
ch.charCodeAt(0) > 127) {
allowNumber = true;
allowSep = true;
} else if ('0' <= ch && ch <= '9'
|| ch == '-') {
if (!allowNumber)
return false;
} else if (ch == '/' || ch == '.') {
if (!allowSep)
return false;
allowNumber = false;
allowSep = false;
if (ch == '.')
seenDot = true;
if (ch == '/' && seenDot)
return false;
} else {
return false;
}
}
return true;
}
function loadFrames() {
if (targetPage != "" && targetPage != "undefined")
top.classFrame.location = top.targetPage;
}
</script>
</head>
<frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()">
<frameset rows="30%,70%" title="Left frames" onload="top.loadFrames()">
<frame src="overview-frame.html" name="packageListFrame" title="All Packages">
<frame src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)">
</frameset>
<frame src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes">
<noframes>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<h2>Frame Alert</h2>
<p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="overview-summary.html">Non-frame version</a>.</p>
</noframes>
</frameset>
</html>
| {
"content_hash": "6c019d221903c8549978383ab0db94c1",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 205,
"avg_line_length": 38.94805194805195,
"alnum_prop": 0.5305101700566855,
"repo_name": "BBN-E/Adept",
"id": "3b4326e1c2d0dcfd47f11f79465eae0b88f5b43a",
"size": "2999",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadocs/adept-api/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25616"
},
{
"name": "HTML",
"bytes": "15089709"
},
{
"name": "Java",
"bytes": "2467577"
},
{
"name": "JavaScript",
"bytes": "1654"
},
{
"name": "Python",
"bytes": "7958"
},
{
"name": "Scheme",
"bytes": "255519"
},
{
"name": "XSLT",
"bytes": "489564"
}
],
"symlink_target": ""
} |
<?php
namespace Enlighter\compatibility;
use Enlighter\skltn\HtmlUtil;
use Enlighter\filter\InputFilter;
class Crayon{
// used by Crayon
// note: full filtering is used to avoid wpautop issues!
public static function getRegex(){
// opening tag, language identifier (required), additional attributes (optional)
return '/<pre\s+class="(.*lang:.+)"\s*(?:title="(.+)")?\s*>' .
// arbitrary multi-line content
'([\S\s]*)' .
// closing tag
'<\/pre>' .
// ungreedy, case insensitive, multiline
'/Uim';
}
// convert regex match to enlighter codeblock
public static function convert($match){
// enlighter html tag standard attributes
$htmlAttributes = array(
'class' => 'EnlighterJSRAW'
);
// list of cryon attributes
$crayonAttributes = array();
// separate options; remove multiple whitespaces
$options = explode(' ', preg_replace('/\s+/', ' ', $match[1]));
// parse
foreach ($options as $opt){
$parts = explode(':', $opt);
// key:value pair provided ?
if (count($parts) === 2){
$key = preg_replace('/[^a-z]/', '_', $parts[0]);
$crayonAttributes[$key] = $parts[1];
}
}
// supported attributes
// -------------------------
// start-line
// lang
// nums
// mark
// language set ?
if (isset($crayonAttributes['lang'])){
$htmlAttributes['data-enlighter-language'] = InputFilter::filterLanguage($crayonAttributes['lang']);
}
// line offset set ?
if (isset($crayonAttributes['start-line'])){
$htmlAttributes['data-enlighter-lineoffset'] = intval($crayonAttributes['start-line']);
}
// highlight set ?
if (isset($crayonAttributes['mark'])){
$htmlAttributes['data-enlighter-highlight'] = $crayonAttributes['mark'];
}
// linenumbers set ?
if (isset($crayonAttributes['nums'])){
$htmlAttributes['data-enlighter-linenumbers'] = $crayonAttributes['nums'];
}
// title set ?
if (isset($match[2])){
$htmlAttributes['data-enlighter-title'] = trim($match[2]);
}
// generate new html tag
return HtmlUtil::generateTag('pre', $htmlAttributes, true, $match[3]);
}
} | {
"content_hash": "c95b145f64f60222d5af4f938aa5e76b",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 112,
"avg_line_length": 28.75581395348837,
"alnum_prop": 0.5333602911443591,
"repo_name": "AndiDittrich/WordPress.Enlighter",
"id": "b74fb8f468a904c3ce8ae1fe24716dd209a5f7d1",
"size": "2473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/compatibility/Crayon.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39061"
},
{
"name": "HTML",
"bytes": "57992"
},
{
"name": "JavaScript",
"bytes": "19959"
},
{
"name": "PHP",
"bytes": "273814"
},
{
"name": "Shell",
"bytes": "792"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.config.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.config.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeConformancePackComplianceRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeConformancePackComplianceRequestMarshaller {
private static final MarshallingInfo<String> CONFORMANCEPACKNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ConformancePackName").build();
private static final MarshallingInfo<StructuredPojo> FILTERS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Filters").build();
private static final MarshallingInfo<Integer> LIMIT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Limit").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("NextToken").build();
private static final DescribeConformancePackComplianceRequestMarshaller instance = new DescribeConformancePackComplianceRequestMarshaller();
public static DescribeConformancePackComplianceRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DescribeConformancePackComplianceRequest describeConformancePackComplianceRequest, ProtocolMarshaller protocolMarshaller) {
if (describeConformancePackComplianceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeConformancePackComplianceRequest.getConformancePackName(), CONFORMANCEPACKNAME_BINDING);
protocolMarshaller.marshall(describeConformancePackComplianceRequest.getFilters(), FILTERS_BINDING);
protocolMarshaller.marshall(describeConformancePackComplianceRequest.getLimit(), LIMIT_BINDING);
protocolMarshaller.marshall(describeConformancePackComplianceRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {
"content_hash": "14cac4d2b2406855f428ec8f647862f1",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 159,
"avg_line_length": 49.58490566037736,
"alnum_prop": 0.7785388127853882,
"repo_name": "aws/aws-sdk-java",
"id": "e6c9d0d1547b66b636349a063699416633d64060",
"size": "3208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/DescribeConformancePackComplianceRequestMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <shm_pool.h>
#include <gtest/gtest.h>
class ShmPoolTestSuite : public ::testing::Test {
public:
};
TEST_F(ShmPoolTestSuite, CreateDestroyShmPool) {
shm_pool_t *shmPool = nullptr;
celix_status_t status = shmPool_create(10240, &shmPool);
EXPECT_EQ(CELIX_SUCCESS, status);
EXPECT_TRUE(shmPool != nullptr);
EXPECT_LE(0, shmPool_getShmId(shmPool));
shmPool_destroy(shmPool);
}
TEST_F(ShmPoolTestSuite, CreationFailedDueToInvalidArgument) {
shm_pool_t *shmPool = nullptr;
celix_status_t status = shmPool_create(1, &shmPool);
EXPECT_EQ(CELIX_ILLEGAL_ARGUMENT, status);
EXPECT_TRUE(shmPool == nullptr);
status = shmPool_create(8192, NULL);
EXPECT_EQ(CELIX_ILLEGAL_ARGUMENT, status);
}
TEST_F(ShmPoolTestSuite, DestroyForNullPool) {
shmPool_destroy(nullptr);
}
TEST_F(ShmPoolTestSuite, GetShmIdForNullPool) {
EXPECT_EQ(-1, shmPool_getShmId(nullptr));
}
TEST_F(ShmPoolTestSuite, MallocFreeMemory) {
shm_pool_t *shmPool = nullptr;
celix_status_t status = shmPool_create(8192, &shmPool);
EXPECT_EQ(CELIX_SUCCESS, status);
void *addr = shmPool_malloc(shmPool, 128);
EXPECT_TRUE(addr != NULL);
EXPECT_LT(0, shmPool_getMemoryOffset(shmPool, addr));
shmPool_free(shmPool, addr);
shmPool_destroy(shmPool);
}
TEST_F(ShmPoolTestSuite, MallocMemoryFailedDueToRequestingSizeTooLarge) {
shm_pool_t *shmPool = nullptr;
celix_status_t status = shmPool_create(8192, &shmPool);
EXPECT_EQ(CELIX_SUCCESS, status);
void *addr = shmPool_malloc(shmPool, 10240);
EXPECT_TRUE(addr == NULL);
shmPool_destroy(shmPool);
}
TEST_F(ShmPoolTestSuite, MallocMemoryForNullPool) {
void *addr = shmPool_malloc(nullptr, 128);
EXPECT_TRUE(addr == NULL);
}
TEST_F(ShmPoolTestSuite, FreeMemoryForNullPool) {
shmPool_free(nullptr, nullptr);
}
TEST_F(ShmPoolTestSuite, GetMemoryOffsetForNullPtrOrNullPool) {
EXPECT_EQ(-1, shmPool_getMemoryOffset(nullptr, nullptr));
shm_pool_t *shmPool = nullptr;
celix_status_t status = shmPool_create(8192, &shmPool);
EXPECT_EQ(CELIX_SUCCESS, status);
EXPECT_EQ(-1, shmPool_getMemoryOffset(shmPool, nullptr));
shmPool_destroy(shmPool);
}
TEST_F(ShmPoolTestSuite, FreeNullPtr) {
shm_pool_t *shmPool = nullptr;
celix_status_t status = shmPool_create(8192, &shmPool);
EXPECT_EQ(CELIX_SUCCESS, status);
shmPool_free(shmPool, nullptr);
shmPool_destroy(shmPool);
}
| {
"content_hash": "b67e7e59df82ae5574b2120dea9e25e9",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 73,
"avg_line_length": 29.36144578313253,
"alnum_prop": 0.7078375051292572,
"repo_name": "apache/celix",
"id": "39df4cae8f797cc5983c4a74c1d51561a79b9ee6",
"size": "3245",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bundles/remote_services/remote_service_admin_shm_v2/shm_pool/gtest/src/ShmPoolTestSuite.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2190"
},
{
"name": "C",
"bytes": "4907267"
},
{
"name": "C++",
"bytes": "1718056"
},
{
"name": "CMake",
"bytes": "466066"
},
{
"name": "HTML",
"bytes": "3361"
},
{
"name": "JavaScript",
"bytes": "27661"
},
{
"name": "Python",
"bytes": "12206"
},
{
"name": "Shell",
"bytes": "14359"
}
],
"symlink_target": ""
} |
<?php
/**
* @file
* Contains \Drupal\Console\Command\Generate\CacheContextCommand.
*/
namespace Drupal\Console\Command\Generate;
use Drupal\Console\Utils\Validator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\Shared\ModuleTrait;
use Drupal\Console\Generator\CacheContextGenerator;
use Drupal\Console\Command\Shared\ConfirmationTrait;
use Drupal\Console\Core\Command\ContainerAwareCommand;
use Drupal\Console\Core\Utils\ChainQueue;
use Drupal\Console\Extension\Manager;
use Drupal\Console\Command\Shared\ServicesTrait;
use Drupal\Console\Core\Utils\StringConverter;
class CacheContextCommand extends ContainerAwareCommand
{
use ModuleTrait;
use ConfirmationTrait;
use ServicesTrait;
/**
* @var CacheContextGenerator
*/
protected $generator;
/**
* @var ChainQueue
*/
protected $chainQueue;
/**
* @var Manager
*/
protected $extensionManager;
/**
* @var StringConverter
*/
protected $stringConverter;
/**
* @var Validator
*/
protected $validator;
/**
* CacheContextCommand constructor.
*
* @param CacheContextGenerator $generator
* @param ChainQueue $chainQueue
* @param Manager $extensionManager
* @param StringConverter $stringConverter
* @param Validator $validator
*/
public function __construct(
CacheContextGenerator $generator,
ChainQueue $chainQueue,
Manager $extensionManager,
StringConverter $stringConverter,
Validator $validator
) {
$this->generator = $generator;
$this->chainQueue = $chainQueue;
$this->extensionManager = $extensionManager;
$this->stringConverter = $stringConverter;
$this->validator = $validator;
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('generate:cache:context')
->setDescription($this->trans('commands.generate.cache.context.description'))
->setHelp($this->trans('commands.generate.cache.context.description'))
->addOption(
'module',
null,
InputOption::VALUE_REQUIRED,
$this->trans('commands.common.options.module')
)
->addOption(
'cache-context',
null,
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.cache.context.options.name')
)
->addOption(
'class',
null,
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.cache.context.options.class')
)
->addOption(
'services',
null,
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
$this->trans('commands.common.options.services')
)->setAliases(['gcc']);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
// @see use Drupal\Console\Command\Shared\ConfirmationTrait::confirmOperation
if (!$this->confirmOperation()) {
return 1;
}
$module = $input->getOption('module');
$cache_context = $input->getOption('cache-context');
$class = $this->validator->validateClassName($input->getOption('class'));
$services = $input->getOption('services');
// @see Drupal\Console\Command\Shared\ServicesTrait::buildServices
$buildServices = $this->buildServices($services);
$this->generator->generate([
'module' => $module,
'cache_context' => $cache_context,
'class' => $class,
'services' => $buildServices,
]);
$this->chainQueue->addCommand('cache:rebuild', ['cache' => 'all']);
}
/**
* {@inheritdoc}
*/
protected function interact(InputInterface $input, OutputInterface $output)
{
// --module option
$module = $this->getModuleOption();
// --cache_context option
$cache_context = $input->getOption('cache-context');
if (!$cache_context) {
$cache_context = $this->getIo()->ask(
$this->trans('commands.generate.cache.context.questions.name'),
sprintf('%s', $module)
);
$input->setOption('cache-context', $cache_context);
}
// --class option
$class = $input->getOption('class');
if (!$class) {
$class = $this->getIo()->ask(
$this->trans('commands.generate.cache.context.questions.class'),
'DefaultCacheContext',
function ($class) {
return $this->validator->validateClassName($class);
}
);
$input->setOption('class', $class);
}
// --services option
$services = $input->getOption('services');
if (!$services) {
// @see Drupal\Console\Command\Shared\ServicesTrait::servicesQuestion
$services = $this->servicesQuestion();
$input->setOption('services', $services);
}
}
}
| {
"content_hash": "9c15890732cf682f105e37d9400e2300",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 89,
"avg_line_length": 30.405555555555555,
"alnum_prop": 0.57445642243742,
"repo_name": "leorawe/sci-base",
"id": "3d29bdf6d6c207ec213cf57eb2d3e7c0e9b27899",
"size": "5473",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "vendor/drupal/console/src/Command/Generate/CacheContextCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "891567"
},
{
"name": "Gherkin",
"bytes": "3374"
},
{
"name": "HTML",
"bytes": "809692"
},
{
"name": "JavaScript",
"bytes": "1514397"
},
{
"name": "PHP",
"bytes": "36312357"
},
{
"name": "Ruby",
"bytes": "63696"
},
{
"name": "Shell",
"bytes": "59930"
}
],
"symlink_target": ""
} |
require 'helper'
class TestCloud < AVTestCase
# functions stored in test/cloud_functions/MyCloudCode
# see https://parse.com/docs/cloud_code_guide to learn how to use AV Cloud Code
#
# AV.Cloud.define('trivial', function(request, response) {
# response.success(request.params);
# });
def test_cloud_function_initialize
assert_not_equal nil, AV::Cloud::Function.new("trivial")
end
def test_request_sms
VCR.use_cassette('test_request_sms', :record => :new_episodes) do
assert_equal (AV::Cloud.request_sms :mobilePhoneNumber => "18668012283",:op => "test",:ttl => 5), {}
puts AV::Cloud.verify_sms_code('18668012283', '123456').inspect
end
end
def test_cloud_function
omit("this should automate the parse deploy command by committing that binary to the repo")
VCR.use_cassette('test_cloud_function', :record => :new_episodes) do
function = AV::Cloud::Function.new("trivial")
params = {"foo" => "bar"}
resp = function.call(params)
assert_equal resp, params
end
end
end
| {
"content_hash": "215ac4a0301099b69711662c6ccc921b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 108,
"avg_line_length": 32.40625,
"alnum_prop": 0.6885245901639344,
"repo_name": "lostpupil/leancloud-ruby-client",
"id": "730c1da6eeffb01c62318c47d37b039135832564",
"size": "1037",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_cloud.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "122"
},
{
"name": "Ruby",
"bytes": "95143"
}
],
"symlink_target": ""
} |
namespace base {
class FilePath;
}
namespace google_apis {
class DriveUploaderInterface;
}
namespace drive {
class DriveCache;
class DriveFileSystemInterface;
class DriveScheduler;
namespace file_system {
class CopyOperation;
class MoveOperation;
class OperationObserver;
class RemoveOperation;
class UpdateOperation;
// Passes notifications from Drive operations back to the file system.
class DriveOperations {
public:
DriveOperations();
~DriveOperations();
// Allocates the operation objects and initializes the operation pointers.
void Init(DriveScheduler* drive_scheduler,
DriveFileSystemInterface* drive_file_system,
DriveCache* cache,
DriveResourceMetadata* metadata,
google_apis::DriveUploaderInterface* uploader,
scoped_refptr<base::SequencedTaskRunner> blocking_task_runner,
OperationObserver* observer);
// Initializes the operation pointers. For testing only.
void InitForTesting(CopyOperation* copy_operation,
MoveOperation* move_operation,
RemoveOperation* remove_operation,
UpdateOperation* update_operation);
// Wrapper function for copy_operation_.
// |callback| must not be null.
void Copy(const base::FilePath& src_file_path,
const base::FilePath& dest_file_path,
const FileOperationCallback& callback);
// Wrapper function for copy_operation_.
// |callback| must not be null.
void TransferFileFromRemoteToLocal(const base::FilePath& remote_src_file_path,
const base::FilePath& local_dest_file_path,
const FileOperationCallback& callback);
// Wrapper function for copy_operation_.
// |callback| must not be null.
void TransferFileFromLocalToRemote(
const base::FilePath& local_src_file_path,
const base::FilePath& remote_dest_file_path,
const FileOperationCallback& callback);
// Wrapper function for copy_operation_.
// |callback| must not be null.
void TransferRegularFile(const base::FilePath& local_src_file_path,
const base::FilePath& remote_dest_file_path,
const FileOperationCallback& callback);
// Wrapper function for move_operation_.
// |callback| must not be null.
void Move(const base::FilePath& src_file_path,
const base::FilePath& dest_file_path,
const FileOperationCallback& callback);
// Wrapper function for remove_operation_.
// |callback| must not be null.
void Remove(const base::FilePath& file_path,
bool is_recursive,
const FileOperationCallback& callback);
// Wrapper function for update_operation_.
// |callback| must not be null.
void UpdateFileByResourceId(const std::string& resource_id,
const FileOperationCallback& callback);
private:
scoped_ptr<CopyOperation> copy_operation_;
scoped_ptr<MoveOperation> move_operation_;
scoped_ptr<RemoveOperation> remove_operation_;
scoped_ptr<UpdateOperation> update_operation_;
};
} // namespace file_system
} // namespace drive
#endif // CHROME_BROWSER_CHROMEOS_DRIVE_FILE_SYSTEM_DRIVE_OPERATIONS_H_
| {
"content_hash": "b880fe4c74def3968e34e22e1e872757",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 80,
"avg_line_length": 33.979166666666664,
"alnum_prop": 0.6827099938687922,
"repo_name": "nacl-webkit/chrome_deps",
"id": "1f188ace8b12a1ad0a4bafea6a5a3ca07c9b5e23",
"size": "3717",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/browser/chromeos/drive/file_system/drive_operations.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1173441"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "74568368"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "156174457"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "3088381"
},
{
"name": "JavaScript",
"bytes": "18179048"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "M",
"bytes": "2190"
},
{
"name": "Matlab",
"bytes": "3044"
},
{
"name": "Objective-C",
"bytes": "6965520"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "932725"
},
{
"name": "Python",
"bytes": "8458718"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3621"
},
{
"name": "Shell",
"bytes": "1526176"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XSLT",
"bytes": "13493"
}
],
"symlink_target": ""
} |
package apimanagement
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// PropertyClient is the apiManagement Client
type PropertyClient struct {
BaseClient
}
// NewPropertyClient creates an instance of the PropertyClient client.
func NewPropertyClient(subscriptionID string) PropertyClient {
return NewPropertyClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewPropertyClientWithBaseURI creates an instance of the PropertyClient client.
func NewPropertyClientWithBaseURI(baseURI string, subscriptionID string) PropertyClient {
return PropertyClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates a property.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// propID - identifier of the property.
// parameters - create parameters.
func (client PropertyClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, propID string, parameters PropertyCreateParameters) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: serviceName,
Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}},
{TargetValue: propID,
Constraints: []validation.Constraint{{Target: "propID", Name: validation.MaxLength, Rule: 256, Chain: nil},
{Target: "propID", Name: validation.Pattern, Rule: `^[^*#&+:<>?]+$`, Chain: nil}}},
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "parameters.Name", Name: validation.MaxLength, Rule: 256, Chain: nil},
{Target: "parameters.Name", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "parameters.Name", Name: validation.Pattern, Rule: `^[A-Z0-9-._]+$`, Chain: nil},
}},
{Target: "parameters.Value", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "parameters.Value", Name: validation.MaxLength, Rule: 4096, Chain: nil},
{Target: "parameters.Value", Name: validation.MinLength, Rule: 1, Chain: nil},
}},
{Target: "parameters.Tags", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.Tags", Name: validation.MaxItems, Rule: 32, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("apimanagement.PropertyClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, propID, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "CreateOrUpdate", resp, "Failure responding to request")
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client PropertyClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, propID string, parameters PropertyCreateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"propId": autorest.Encode("path", propID),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": autorest.Encode("path", serviceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-07-07"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client PropertyClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client PropertyClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Delete deletes specific property from the the API Management service instance.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// propID - identifier of the property.
// ifMatch - the entity state (Etag) version of the property to delete. A value of "*" can be used for If-Match
// to unconditionally apply the operation.
func (client PropertyClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, propID string, ifMatch string) (result ErrorBodyContract, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: serviceName,
Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("apimanagement.PropertyClient", "Delete", err.Error())
}
req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, propID, ifMatch)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client PropertyClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, propID string, ifMatch string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"propId": autorest.Encode("path", propID),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": autorest.Encode("path", serviceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-07-07"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}", pathParameters),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("If-Match", autorest.String(ifMatch)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client PropertyClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client PropertyClient) DeleteResponder(resp *http.Response) (result ErrorBodyContract, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusMethodNotAllowed),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Get gets the details of the property specified by its identifier.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// propID - identifier of the property.
func (client PropertyClient) Get(ctx context.Context, resourceGroupName string, serviceName string, propID string) (result PropertyContract, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: serviceName,
Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("apimanagement.PropertyClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, propID)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client PropertyClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, propID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"propId": autorest.Encode("path", propID),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": autorest.Encode("path", serviceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-07-07"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client PropertyClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PropertyClient) GetResponder(resp *http.Response) (result PropertyContract, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByService lists a collection of properties defined within a service instance.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// filter - | Field | Supported operators | Supported functions |
// |-------|------------------------|-------------------------------------------------------|
// | tags | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith, any, all |
// | name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |
// top - number of records to return.
// skip - number of records to skip.
func (client PropertyClient) ListByService(ctx context.Context, resourceGroupName string, serviceName string, filter string, top *int32, skip *int32) (result PropertyCollectionPage, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: serviceName,
Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}},
{TargetValue: top,
Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}}}}},
{TargetValue: skip,
Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("apimanagement.PropertyClient", "ListByService", err.Error())
}
result.fn = client.listByServiceNextResults
req, err := client.ListByServicePreparer(ctx, resourceGroupName, serviceName, filter, top, skip)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "ListByService", nil, "Failure preparing request")
return
}
resp, err := client.ListByServiceSender(req)
if err != nil {
result.pc.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "ListByService", resp, "Failure sending request")
return
}
result.pc, err = client.ListByServiceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "ListByService", resp, "Failure responding to request")
}
return
}
// ListByServicePreparer prepares the ListByService request.
func (client PropertyClient) ListByServicePreparer(ctx context.Context, resourceGroupName string, serviceName string, filter string, top *int32, skip *int32) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": autorest.Encode("path", serviceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-07-07"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
if top != nil {
queryParameters["$top"] = autorest.Encode("query", *top)
}
if skip != nil {
queryParameters["$skip"] = autorest.Encode("query", *skip)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByServiceSender sends the ListByService request. The method will close the
// http.Response Body if it receives an error.
func (client PropertyClient) ListByServiceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByServiceResponder handles the response to the ListByService request. The method always
// closes the http.Response Body.
func (client PropertyClient) ListByServiceResponder(resp *http.Response) (result PropertyCollection, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByServiceNextResults retrieves the next set of results, if any.
func (client PropertyClient) listByServiceNextResults(lastResults PropertyCollection) (result PropertyCollection, err error) {
req, err := lastResults.propertyCollectionPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "listByServiceNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByServiceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "listByServiceNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByServiceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "listByServiceNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByServiceComplete enumerates all values, automatically crossing page boundaries as required.
func (client PropertyClient) ListByServiceComplete(ctx context.Context, resourceGroupName string, serviceName string, filter string, top *int32, skip *int32) (result PropertyCollectionIterator, err error) {
result.page, err = client.ListByService(ctx, resourceGroupName, serviceName, filter, top, skip)
return
}
// Update updates the specific property.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// propID - identifier of the property.
// parameters - update parameters.
// ifMatch - the entity state (Etag) version of the property to update. A value of "*" can be used for If-Match
// to unconditionally apply the operation.
func (client PropertyClient) Update(ctx context.Context, resourceGroupName string, serviceName string, propID string, parameters PropertyUpdateParameters, ifMatch string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: serviceName,
Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("apimanagement.PropertyClient", "Update", err.Error())
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, propID, parameters, ifMatch)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.PropertyClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client PropertyClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, propID string, parameters PropertyUpdateParameters, ifMatch string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"propId": autorest.Encode("path", propID),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": autorest.Encode("path", serviceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-07-07"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("If-Match", autorest.String(ifMatch)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client PropertyClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client PropertyClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
| {
"content_hash": "b5b3b2ff0ef1f9d8e5795fc262eae2c8",
"timestamp": "",
"source": "github",
"line_count": 498,
"max_line_length": 210,
"avg_line_length": 45.963855421686745,
"alnum_prop": 0.746264744429882,
"repo_name": "sferich888/origin",
"id": "c65c4650b1470c54af63836573baa93c2282be20",
"size": "22890",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2016-07-07/apimanagement/property.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Dockerfile",
"bytes": "9805"
},
{
"name": "Go",
"bytes": "13133534"
},
{
"name": "Makefile",
"bytes": "8268"
},
{
"name": "Python",
"bytes": "16068"
},
{
"name": "Shell",
"bytes": "825010"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "483a2aca30ec9f8ff05d681d251216f2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "88c929d81e10f96d30164c5029dd40c95814c756",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Abarema/Abarema jupunba/Abarema jupunba jupunba/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Ojs\ApiBundle\Controller;
use Doctrine\Common\Collections\Collection;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Patch;
use FOS\RestBundle\Controller\Annotations\View as RestView;
use FOS\RestBundle\Controller\FOSRestController;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Ojs\JournalBundle\Entity\Article;
use Ojs\JournalBundle\Entity\ArticleRepository;
use Ojs\JournalBundle\Entity\Citation;
use Ojs\JournalBundle\Entity\CitationSetting;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ArticleRestController extends FOSRestController
{
/**
*
* @ApiDoc(
* resource=true,
* description="Get Articles"
* )
* @Get("/articles/bulk/{page}/{limit}")
*
* @param int $page
* @param int $limit
* @return Article[]|array
*/
public function getArticlesAction($page = 0, $limit = 10)
{
/** @var ArticleRepository $articleRepo */
$articleRepo = $this->getDoctrine()->getManager()->getRepository('OjsJournalBundle:Article');
$articles = $articleRepo->findAllByLimits($page, $limit);
if (!is_array($articles)) {
throw new HttpException(404, 'Not found. The record is not found or route is not defined.');
}
return $articles;
}
/**
*
* @param $id
* @return object
*
* @ApiDoc(
* resource=true,
* description="Get Specific Article"
* )
* @Get("/article/{id}")
*/
public function getArticleDetailAction($id)
{
$article = $this->getDoctrine()->getRepository('OjsJournalBundle:Article')->find($id);
if (!is_object($article)) {
throw new HttpException(404, 'Not found. The record is not found or route is not defined.');
}
return $article;
}
/**
* @param $id
* @param Request $request
*
* @ApiDoc(
* resource=true,
* description="Add bulk citation data to an article" ,
* method="POST",
* requirements={
* {
* "name"="cites",
* "dataType"="string",
* "requirement"="\d+",
* "description"="json encoded citations"
* }
* },
* statusCodes={
* 204="Returned when successful"
* }
* )
*/
public function postArticleBulkCitationAction($id, Request $request)
{
$citesStr = $request->get('cites');
if (empty($citesStr)) {
throw new HttpException(400, 'Missing parameter : cites ');
}
$cites = json_decode($citesStr, true);
if (empty($cites) || !is_array($cites)) {
throw new HttpException(400, 'Missing parameter : cites ');
}
foreach ($cites as $cite) {
$citation = new Citation();
$citation->setRaw($cite['raw']);
$citation->setOrderNum(isset($cite['orderNum']) ? $cite['orderNum'] : 0);
$citation->setType($cite['type']);
$settings = $cite['settings'];
$this->addCitation2Article($id, $citation, $settings);
}
}
/**
*
* @param integer $id
* @param Citation $citation
* @param Request $request
* @return Article
*/
private function addCitation2Article($id, Citation $citation, $request)
{
$em = $this->getDoctrine()->getManager();
$em->persist($citation);
$em->flush();
$citationSettingKeys = $this->container->getParameter('citation_setting_keys');
// check and insert citation
/* @var $article Article */
$article = $em->getRepository('OjsJournalBundle:Article')->find($id);
if (!$article) {
return array();
}
$article->addCitation($citation);
$em->persist($citation);
$em->flush();
foreach ($citationSettingKeys as $key => $desc) {
$param = is_array($request) ? (isset($request[$key]) ? $request[$key] : null) : $request->get(
'setting_'.$key
);
if (!empty($param)) {
$citationSetting = new CitationSetting();
$citationSetting->setCitation($citation);
$citationSetting->setSetting($key);
$citationSetting->setValue($param);
$em->persist($citationSetting);
}
}
$em->flush();
return $article;
}
/**
* @param $id
* @param Request $request
* @return Article
*
*
* @ApiDoc(
* resource=true,
* description="Add a citation data to an article" ,
* method="POST",
* requirements={
* {
* "name"="raw",
* "dataType"="string",
* "requirement"="\d+",
* "description"="raw citation in any format"
* }
* }
* )
*/
public function postArticleCitationAction($id, Request $request)
{
$citation = new Citation();
$citation->setRaw($request->get('raw'));
$citation->setOrderNum($request->get('orderNum', 0));
$citation->setType($request->get('type'));
$article = $this->addCitation2Article($id, $citation, $request);
return $article;
}
/**
* @param $id
* @return Collection|Citation[]|void
*
* @ApiDoc(
* resource=true,
* description="Get citation data of an article"
* )
* @Get("/article/{id}/citations")
*/
public function getArticleCitationsAction($id)
{
$em = $this->getDoctrine()->getManager();
/** @var Article $article */
$article = $em->getRepository('OjsJournalBundle:Article')->find($id);
if (!$article) {
return array();
}
return $article->getCitations();
}
/**
* @param Request $request
* @param $article_id
* @return object
*
* @ApiDoc(
* description="Change article 'orderNum'",
* method="PATCH",
* requirements={
* {
* "name"="orderNum",
* "dataType"="integer",
* "requirement"="\d+",
* "description"="change Article issue order"
* }
* }
* )
* @RestView()
*/
public function orderArticlesAction(Request $request, $article_id)
{
return $this->patch('orderNum', $article_id, $request);
}
/**
* @param $field
* @param $article_id
* @param Request $request
* @return object
*/
protected function patch($field, $article_id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$article = $this->getDoctrine()->getRepository('OjsJournalBundle:Article')->find($article_id);
if (!is_object($article)) {
throw new HttpException(404, 'Not found. The record is not found or route is not defined.');
}
switch ($field) {
case 'orderNum':
$article->setOrderNum($request->get('orderNum'));
break;
case
'status':
$article->setStatus($request->get('status'));
break;
default:
break;
}
$em->flush();
return $article;
}
/**
* @param $articleId
* @return Article
*
*
* @ApiDoc(
* description="Increment Article 'orderNum'",
* method="PATCH"
* )
* @RestView()
* @Patch("/articles/{articleId}/order/up")
*/
public function incrementOrderNumArticlesAction($articleId)
{
return $this->upDownOrder($articleId, true);
}
protected function upDownOrder($articleId, $up = true)
{
$em = $this->getDoctrine()->getManager();
/** @var Article $article */
$article = $em->getRepository('OjsJournalBundle:Article')->find($articleId);
if (!is_object($article)) {
throw new HttpException(404, 'Not found. The record is not found or route is not defined.');
}
$o = $article->getOrderNum();
$article->setOrderNum($up ? ($o + 1) : ($o - 1));
$em->flush();
return $article;
}
/**
* @param $articleId
* @return Article
*
* @ApiDoc(
* description="Increment Article 'orderNum'",
* method="PATCH"
* )
* @RestView()
* @Patch("/articles/{articleId}/order/down")
*/
public function decrementOrderNumArticlesAction($articleId)
{
return $this->upDownOrder($articleId, false);
}
/**
*
* @param Request $request
* @param $article_id
* @return object
*
* @ApiDoc(
* description="Change article 'status'",
* method="PATCH",
* requirements={
* {
* "name"="status",
* "dataType"="integer",
* "requirement"="\d+",
* "description"="Change Article status"
* }
* }
* )
* @RestView()
*/
public function statusArticlesAction(Request $request, $article_id)
{
return $this->patch('status', $article_id, $request);
}
}
| {
"content_hash": "d15f064d75f77e42376d34f30c9e6e49",
"timestamp": "",
"source": "github",
"line_count": 326,
"max_line_length": 106,
"avg_line_length": 28.45398773006135,
"alnum_prop": 0.5354678740836567,
"repo_name": "zaferkanbur/ojs",
"id": "0d8c2278509087fe5fd59a52757ea3f60eba6709",
"size": "9276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Ojs/ApiBundle/Controller/ArticleRestController.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "55359"
},
{
"name": "CoffeeScript",
"bytes": "1080"
},
{
"name": "HTML",
"bytes": "986475"
},
{
"name": "JavaScript",
"bytes": "57665"
},
{
"name": "PHP",
"bytes": "1643587"
},
{
"name": "XSLT",
"bytes": "30085"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "329881114e0ff128896ab242b9c5a438",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "f4b3de2df10b2a3d4db79fddea145dbea0da8cdd",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Chromista/Ochrophyta/Phaeophyceae/Fucales/Cystoseiraceae/Cystoseira/Cystoseira wildpretii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
const assert = require("assert");
const { Builder, By, Key } = require("selenium-webdriver");
const firefox = require("selenium-webdriver/firefox");
const fs = require("fs");
const path = require("path");
describe("File download", function() {
let driver;
const tmpDir = path.join(__dirname, "tmp");
beforeEach(async function() {
if (!fs.existsSync(tmpDir)) fs.mkdirSync(tmpDir);
let options = new firefox.Options()
.setPreference("browser.download.dir", tmpDir)
.setPreference("browser.download.folderList", 2)
.setPreference(
"browser.helperApps.neverAsk.saveToDisk",
"images/jpeg, application/pdf, application/octet-stream"
)
.setPreference("pdfjs.disabled", true);
driver = await new Builder()
.forBrowser("firefox")
.setFirefoxOptions(options)
.build();
});
function cleanupTmpDir() {
if (fs.existsSync(tmpDir)) {
const files = fs.readdirSync(tmpDir).map(file => path.join(tmpDir, file));
files.forEach(file => fs.unlinkSync(file));
fs.rmdirSync(tmpDir);
}
}
afterEach(async function() {
await driver.quit();
cleanupTmpDir();
});
it("should automatically download to local disk", async function() {
await driver.get("http://the-internet.herokuapp.com/download");
await driver.findElement(By.css(".example a")).click();
const files = fs.readdirSync(tmpDir).map(file => path.join(tmpDir, file));
assert(files.length);
assert(fs.statSync(files[0]).size);
});
});
| {
"content_hash": "0f4fb01d135276e1181c0d9a45815b11",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 80,
"avg_line_length": 31.6875,
"alnum_prop": 0.6554898093359632,
"repo_name": "tourdedave/elemental-selenium-tips",
"id": "76d3fb6bb59fd531556264dd254e59ed7a18cdbe",
"size": "1521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "02-download-a-file/javascript/test/download.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "33563"
},
{
"name": "HTML",
"bytes": "30241"
},
{
"name": "Java",
"bytes": "63961"
},
{
"name": "JavaScript",
"bytes": "99272"
},
{
"name": "Python",
"bytes": "25954"
},
{
"name": "Ruby",
"bytes": "79856"
}
],
"symlink_target": ""
} |
permalink: /components/input/overviewservice/overview
title: "Form service components"
comp: "overviewService"
---
{% include base_path %}
{% include toc %}
Form service components are component that must be placed inside a [form]({{ base_path }}/docs/components/form/){:target="_blank"}. This components display a set of options provided by a service and allow the user to select one or more of them. The form service components offered by **OntimizeWeb** are combo, list picker and radio.
All form service components in **OntimizeWeb** extend the `OFormServiceComponent` class, that is a subclass of [`OFormDataComponent`]({{ base_path }}/components/input/overview/){:target="_blank"}. This class provides a set of methods and attributes inherited by all the form service components. This methods and attributes are explained on the **API** section of this page.
## Parent keys
The `parent-keys` attribute allows the developer to define filtering keys used in the request the component makes to the server in order to populate its options. This filtering keys must be defined as a string, separating them with a semicolon ';'. The component will look for this keys on its parent form and in the route parameters in order to build the filter for querying.
```html
parent-keys="factory_id;device_id"
```
In some cases, the values you will need for filtering the component request will be present in the parent form or the route parameter with a different name than the used in the component. For matching the component parent keys with these names, you can define an alias for each key you need separating the component parent key and its alias with two dots ':'.
```html
parent-keys="factory_id:factory;device_id:device"
```
So far this is the behavior of the parent keys attribute in all the components **OntimizeWeb** defines.
Form service components extends this behaviour and go one step forward, they allow the component to look for a key value in the data of another service components. This can be done by defining the column you want to get between brackets '[]'. Check the example below.
```html
<o-form>
<o-combo attr="user" keys="user_id" columns="user_id;user_name;user_type"></o-combo>
<o-combo attr="role" keys="role_id" columns="role_id;role_name;profile_id"
parent-keys="user_type_id:user[user_type]"></o-combo>
</o-form>
```
In this example there is a form for linking users and roles, the roles the user may be linked with depend on the type of the user. The user type is part of the user information queried in the first combo. Notice that the the parent keys attribute for the roles combo has an alias and a column defined for the alias. This will make the roles component to look for the value of its parent key in the component with attr `user` and it will take the `user_type` column value as its parent key value.
The construction of dependant list-pickers is the same as done in the combo component. The first one is the selector of users, this will be the one that affects the second one.
```html
<o-form>
<o-list-picker attr="user" label="User" keys="user_id" columns="user_id;user_name;user_type"></o-list-picker>
<o-list-picker attr="role" label="Role" keys="role_id" columns="role_id;role_name;profile_id"
parent-keys="user_type_id:user[user_type]"></o-list-picker>
</o-form>
```
| {
"content_hash": "d80d2849fa7c7d21e4f4811127f82ce0",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 495,
"avg_line_length": 68.51020408163265,
"alnum_prop": 0.7548406315162347,
"repo_name": "OntimizeWeb/docs",
"id": "c0075d1f7a7cfed280e9b160de4badbaf284b218",
"size": "3361",
"binary": false,
"copies": "1",
"ref": "refs/heads/8.x.x",
"path": "_o_components/00-overview.service-component.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7337"
},
{
"name": "HTML",
"bytes": "75290"
},
{
"name": "JavaScript",
"bytes": "174898"
},
{
"name": "Ruby",
"bytes": "784"
},
{
"name": "SCSS",
"bytes": "80605"
},
{
"name": "Shell",
"bytes": "484"
}
],
"symlink_target": ""
} |
;(function ($, window, document, undefined) {
"use strict";
var _module = module;
module.exports = function(parameters) {
var
$allModules = $(this),
$document = $(document),
$window = $(window),
$body = $('body'),
moduleSelector = $allModules.selector || '',
hasTouch = (true),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, _module.exports.settings, parameters)
: $.extend({}, _module.exports.settings),
selector = settings.selector,
className = settings.className,
error = settings.error,
metadata = settings.metadata,
namespace = settings.namespace,
eventNamespace = '.' + settings.namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$target = (settings.target)
? $(settings.target)
: $module,
$popup,
$offsetParent,
searchDepth = 0,
triedPositions = false,
openedWithTouch = false,
element = this,
instance = $module.data(moduleNamespace),
elementNamespace,
id,
module
;
module = {
// binds events
initialize: function() {
module.debug('Initializing', $module);
module.createID();
module.bind.events();
if( !module.exists() && settings.preserve) {
module.create();
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance', module);
instance = module;
$module
.data(moduleNamespace, instance)
;
},
refresh: function() {
if(settings.popup) {
$popup = $(settings.popup).eq(0);
}
else {
if(settings.inline) {
$popup = $target.nextAll(selector.popup).eq(0);
settings.popup = $popup;
}
}
if(settings.popup) {
$popup.addClass(className.loading);
$offsetParent = module.get.offsetParent();
$popup.removeClass(className.loading);
if(settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) {
module.debug('Moving popup to the same offset parent as activating element');
$popup
.detach()
.appendTo($offsetParent)
;
}
}
else {
$offsetParent = (settings.inline)
? module.get.offsetParent($target)
: module.has.popup()
? module.get.offsetParent($popup)
: $body
;
}
if( $offsetParent.is('html') && $offsetParent[0] !== $body[0] ) {
module.debug('Setting page as offset parent');
$offsetParent = $body;
}
if( module.get.variation() ) {
module.set.variation();
}
},
reposition: function() {
module.refresh();
module.set.position();
},
destroy: function() {
module.debug('Destroying previous module');
// remove element only if was created dynamically
if($popup && !settings.preserve) {
module.removePopup();
}
// clear all timeouts
clearTimeout(module.hideTimer);
clearTimeout(module.showTimer);
// remove events
$window.off(elementNamespace);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
event: {
start: function(event) {
var
delay = ($.isPlainObject(settings.delay))
? settings.delay.show
: settings.delay
;
clearTimeout(module.hideTimer);
if(!openedWithTouch) {
module.showTimer = setTimeout(module.show, delay);
}
},
end: function() {
var
delay = ($.isPlainObject(settings.delay))
? settings.delay.hide
: settings.delay
;
clearTimeout(module.showTimer);
module.hideTimer = setTimeout(module.hide, delay);
},
touchstart: function(event) {
openedWithTouch = true;
module.show();
},
resize: function() {
if( module.is.visible() ) {
module.set.position();
}
},
hideGracefully: function(event) {
// don't close on clicks inside popup
if(event && $(event.target).closest(selector.popup).length === 0) {
module.debug('Click occurred outside popup hiding popup');
module.hide();
}
else {
module.debug('Click was inside popup, keeping popup open');
}
}
},
// generates popup html from metadata
create: function() {
var
html = module.get.html(),
title = module.get.title(),
content = module.get.content()
;
if(html || content || title) {
module.debug('Creating pop-up html');
if(!html) {
html = settings.templates.popup({
title : title,
content : content
});
}
$popup = $('<div/>')
.addClass(className.popup)
.data(metadata.activator, $module)
.html(html)
;
if(settings.inline) {
module.verbose('Inserting popup element inline', $popup);
$popup
.insertAfter($module)
;
}
else {
module.verbose('Appending popup element to body', $popup);
$popup
.appendTo( $context )
;
}
module.refresh();
module.set.variation();
if(settings.hoverable) {
module.bind.popup();
}
settings.onCreate.call($popup, element);
}
else if($target.next(selector.popup).length !== 0) {
module.verbose('Pre-existing popup found');
settings.inline = true;
settings.popups = $target.next(selector.popup).data(metadata.activator, $module);
module.refresh();
if(settings.hoverable) {
module.bind.popup();
}
}
else if(settings.popup) {
$(settings.popup).data(metadata.activator, $module);
module.verbose('Used popup specified in settings');
module.refresh();
if(settings.hoverable) {
module.bind.popup();
}
}
else {
module.debug('No content specified skipping display', element);
}
},
createID: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
},
// determines popup state
toggle: function() {
module.debug('Toggling pop-up');
if( module.is.hidden() ) {
module.debug('Popup is hidden, showing pop-up');
module.unbind.close();
module.show();
}
else {
module.debug('Popup is visible, hiding pop-up');
module.hide();
}
},
show: function(callback) {
callback = callback || function(){};
module.debug('Showing pop-up', settings.transition);
if(module.is.hidden() && !( module.is.active() && module.is.dropdown()) ) {
if( !module.exists() ) {
module.create();
}
if(settings.onShow.call($popup, element) === false) {
module.debug('onShow callback returned false, cancelling popup animation');
return;
}
else if(!settings.preserve && !settings.popup) {
module.refresh();
}
if( $popup && module.set.position() ) {
module.save.conditions();
if(settings.exclusive) {
module.hideAll();
}
module.animate.show(callback);
}
}
},
hide: function(callback) {
callback = callback || function(){};
if( module.is.visible() || module.is.animating() ) {
if(settings.onHide.call($popup, element) === false) {
module.debug('onHide callback returned false, cancelling popup animation');
return;
}
module.remove.visible();
module.unbind.close();
module.restore.conditions();
module.animate.hide(callback);
}
},
hideAll: function() {
$(selector.popup)
.filter('.' + className.visible)
.each(function() {
$(this)
.data(metadata.activator)
.popup('hide')
;
})
;
},
exists: function() {
if(!$popup) {
return false;
}
if(settings.inline || settings.popup) {
return ( module.has.popup() );
}
else {
return ( $popup.closest($context).length >= 1 )
? true
: false
;
}
},
removePopup: function() {
if( module.has.popup() && !settings.popup) {
module.debug('Removing popup', $popup);
$popup.remove();
$popup = undefined;
settings.onRemove.call($popup, element);
}
},
save: {
conditions: function() {
module.cache = {
title: $module.attr('title')
};
if (module.cache.title) {
$module.removeAttr('title');
}
module.verbose('Saving original attributes', module.cache.title);
}
},
restore: {
conditions: function() {
if(module.cache && module.cache.title) {
$module.attr('title', module.cache.title);
module.verbose('Restoring original attributes', module.cache.title);
}
return true;
}
},
animate: {
show: function(callback) {
callback = $.isFunction(callback) ? callback : function(){};
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.set.visible();
$popup
.transition({
animation : settings.transition + ' in',
queue : false,
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
onComplete : function() {
module.bind.close();
callback.call($popup, element);
settings.onVisible.call($popup, element);
}
})
;
}
else {
module.error(error.noTransition);
}
},
hide: function(callback) {
callback = $.isFunction(callback) ? callback : function(){};
module.debug('Hiding pop-up');
if(settings.onHide.call($popup, element) === false) {
module.debug('onHide callback returned false, cancelling popup animation');
return;
}
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
$popup
.transition({
animation : settings.transition + ' out',
queue : false,
duration : settings.duration,
debug : settings.debug,
verbose : settings.verbose,
onComplete : function() {
module.reset();
callback.call($popup, element);
settings.onHidden.call($popup, element);
}
})
;
}
else {
module.error(error.noTransition);
}
}
},
change: {
content: function(html) {
$popup.html(html);
}
},
get: {
html: function() {
$module.removeData(metadata.html);
return $module.data(metadata.html) || settings.html;
},
title: function() {
$module.removeData(metadata.title);
return $module.data(metadata.title) || settings.title;
},
content: function() {
$module.removeData(metadata.content);
return $module.data(metadata.content) || $module.attr('title') || settings.content;
},
variation: function() {
$module.removeData(metadata.variation);
return $module.data(metadata.variation) || settings.variation;
},
popup: function() {
return $popup;
},
popupOffset: function() {
return $popup.offset();
},
calculations: function() {
var
targetElement = $target[0],
targetPosition = (settings.inline || (settings.popup && settings.movePopup))
? $target.position()
: $target.offset(),
calculations = {},
screen
;
calculations = {
// element which is launching popup
target : {
element : $target[0],
width : $target.outerWidth(),
height : $target.outerHeight(),
top : targetPosition.top,
left : targetPosition.left,
margin : {}
},
// popup itself
popup : {
width : $popup.outerWidth(),
height : $popup.outerHeight()
},
// offset container (or 3d context)
parent : {
width : $offsetParent.outerWidth(),
height : $offsetParent.outerHeight()
},
// screen boundaries
screen : {
scroll: {
top : $window.scrollTop(),
left : $window.scrollLeft()
},
width : $window.width(),
height : $window.height()
}
};
// add in container calcs if fluid
if( settings.setFluidWidth && module.is.fluid() ) {
calculations.container = {
width: $popup.parent().outerWidth()
};
calculations.popup.width = calculations.container.width;
}
// add in margins if inline
calculations.target.margin.top = (settings.inline)
? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10)
: 0
;
calculations.target.margin.left = (settings.inline)
? module.is.rtl()
? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10)
: parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-left') , 10)
: 0
;
// calculate screen boundaries
screen = calculations.screen;
calculations.boundary = {
top : screen.scroll.top,
bottom : screen.scroll.top + screen.height,
left : screen.scroll.left,
right : screen.scroll.left + screen.width
};
return calculations;
},
id: function() {
return id;
},
startEvent: function() {
if(settings.on == 'hover') {
return 'mouseenter';
}
else if(settings.on == 'focus') {
return 'focus';
}
return false;
},
scrollEvent: function() {
return 'scroll';
},
endEvent: function() {
if(settings.on == 'hover') {
return 'mouseleave';
}
else if(settings.on == 'focus') {
return 'blur';
}
return false;
},
distanceFromBoundary: function(offset, calculations) {
var
distanceFromBoundary = {},
popup,
boundary
;
offset = offset || module.get.offset();
calculations = calculations || module.get.calculations();
// shorthand
popup = calculations.popup;
boundary = calculations.boundary;
if(offset) {
distanceFromBoundary = {
top : (offset.top - boundary.top),
left : (offset.left - boundary.left),
right : (boundary.right - (offset.left + popup.width) ),
bottom : (boundary.bottom - (offset.top + popup.height) )
};
module.verbose('Distance from boundaries determined', offset, distanceFromBoundary);
}
return distanceFromBoundary;
},
offsetParent: function($target) {
var
element = ($target !== undefined)
? $target[0]
: $module[0],
parentNode = element.parentNode,
$node = $(parentNode)
;
if(parentNode) {
var
is2D = ($node.css('transform') === 'none'),
isStatic = ($node.css('position') === 'static'),
isHTML = $node.is('html')
;
while(parentNode && !isHTML && isStatic && is2D) {
parentNode = parentNode.parentNode;
$node = $(parentNode);
is2D = ($node.css('transform') === 'none');
isStatic = ($node.css('position') === 'static');
isHTML = $node.is('html');
}
}
return ($node && $node.length > 0)
? $node
: $()
;
},
positions: function() {
return {
'top left' : false,
'top center' : false,
'top right' : false,
'bottom left' : false,
'bottom center' : false,
'bottom right' : false,
'left center' : false,
'right center' : false
};
},
nextPosition: function(position) {
var
positions = position.split(' '),
verticalPosition = positions[0],
horizontalPosition = positions[1],
opposite = {
top : 'bottom',
bottom : 'top',
left : 'right',
right : 'left'
},
adjacent = {
left : 'center',
center : 'right',
right : 'left'
},
backup = {
'top left' : 'top center',
'top center' : 'top right',
'top right' : 'right center',
'right center' : 'bottom right',
'bottom right' : 'bottom center',
'bottom center' : 'bottom left',
'bottom left' : 'left center',
'left center' : 'top left'
},
adjacentsAvailable = (verticalPosition == 'top' || verticalPosition == 'bottom'),
oppositeTried = false,
adjacentTried = false,
nextPosition = false
;
if(!triedPositions) {
module.verbose('All available positions available');
triedPositions = module.get.positions();
}
module.debug('Recording last position tried', position);
triedPositions[position] = true;
if(settings.prefer === 'opposite') {
nextPosition = [opposite[verticalPosition], horizontalPosition];
nextPosition = nextPosition.join(' ');
oppositeTried = (triedPositions[nextPosition] === true);
module.debug('Trying opposite strategy', nextPosition);
}
if((settings.prefer === 'adjacent') && adjacentsAvailable ) {
nextPosition = [verticalPosition, adjacent[horizontalPosition]];
nextPosition = nextPosition.join(' ');
adjacentTried = (triedPositions[nextPosition] === true);
module.debug('Trying adjacent strategy', nextPosition);
}
if(adjacentTried || oppositeTried) {
module.debug('Using backup position', nextPosition);
nextPosition = backup[position];
}
return nextPosition;
}
},
set: {
position: function(position, calculations) {
// exit conditions
if($target.length === 0 || $popup.length === 0) {
module.error(error.notFound);
return;
}
var
offset,
distanceAway,
target,
popup,
parent,
positioning,
popupOffset,
distanceFromBoundary
;
calculations = calculations || module.get.calculations();
position = position || $module.data(metadata.position) || settings.position;
offset = $module.data(metadata.offset) || settings.offset;
distanceAway = settings.distanceAway;
// shorthand
target = calculations.target;
popup = calculations.popup;
parent = calculations.parent;
if(target.width === 0 && target.height === 0 && !(target.element instanceof SVGGraphicsElement)) {
module.debug('Popup target is hidden, no action taken');
return false;
}
if(settings.inline) {
module.debug('Adding margin to calculation', target.margin);
if(position == 'left center' || position == 'right center') {
offset += target.margin.top;
distanceAway += -target.margin.left;
}
else if (position == 'top left' || position == 'top center' || position == 'top right') {
offset += target.margin.left;
distanceAway -= target.margin.top;
}
else {
offset += target.margin.left;
distanceAway += target.margin.top;
}
}
module.debug('Determining popup position from calculations', position, calculations);
if (module.is.rtl()) {
position = position.replace(/left|right/g, function (match) {
return (match == 'left')
? 'right'
: 'left'
;
});
module.debug('RTL: Popup position updated', position);
}
// if last attempt use specified last resort position
if(searchDepth == settings.maxSearchDepth && typeof settings.lastResort === 'string') {
position = settings.lastResort;
}
switch (position) {
case 'top left':
positioning = {
top : 'auto',
bottom : parent.height - target.top + distanceAway,
left : target.left + offset,
right : 'auto'
};
break;
case 'top center':
positioning = {
bottom : parent.height - target.top + distanceAway,
left : target.left + (target.width / 2) - (popup.width / 2) + offset,
top : 'auto',
right : 'auto'
};
break;
case 'top right':
positioning = {
bottom : parent.height - target.top + distanceAway,
right : parent.width - target.left - target.width - offset,
top : 'auto',
left : 'auto'
};
break;
case 'left center':
positioning = {
top : target.top + (target.height / 2) - (popup.height / 2) + offset,
right : parent.width - target.left + distanceAway,
left : 'auto',
bottom : 'auto'
};
break;
case 'right center':
positioning = {
top : target.top + (target.height / 2) - (popup.height / 2) + offset,
left : target.left + target.width + distanceAway,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom left':
positioning = {
top : target.top + target.height + distanceAway,
left : target.left + offset,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom center':
positioning = {
top : target.top + target.height + distanceAway,
left : target.left + (target.width / 2) - (popup.width / 2) + offset,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom right':
positioning = {
top : target.top + target.height + distanceAway,
right : parent.width - target.left - target.width - offset,
left : 'auto',
bottom : 'auto'
};
break;
}
if(positioning === undefined) {
module.error(error.invalidPosition, position);
}
module.debug('Calculated popup positioning values', positioning);
// tentatively place on stage
$popup
.css(positioning)
.removeClass(className.position)
.addClass(position)
.addClass(className.loading)
;
popupOffset = module.get.popupOffset();
// see if any boundaries are surpassed with this tentative position
distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations);
if( module.is.offstage(distanceFromBoundary, position) ) {
module.debug('Position is outside viewport', position);
if(searchDepth < settings.maxSearchDepth) {
searchDepth++;
position = module.get.nextPosition(position);
module.debug('Trying new position', position);
return ($popup)
? module.set.position(position, calculations)
: false
;
}
else {
if(settings.lastResort) {
module.debug('No position found, showing with last position');
}
else {
module.debug('Popup could not find a position to display', $popup);
module.error(error.cannotPlace, element);
module.remove.attempts();
module.remove.loading();
module.reset();
settings.onUnplaceable.call($popup, element);
return false;
}
}
}
module.debug('Position is on stage', position);
module.remove.attempts();
module.remove.loading();
if( settings.setFluidWidth && module.is.fluid() ) {
module.set.fluidWidth(calculations);
}
return true;
},
fluidWidth: function(calculations) {
calculations = calculations || module.get.calculations();
module.debug('Automatically setting element width to parent width', calculations.parent.width);
$popup.css('width', calculations.container.width);
},
variation: function(variation) {
variation = variation || module.get.variation();
if(variation && module.has.popup() ) {
module.verbose('Adding variation to popup', variation);
$popup.addClass(variation);
}
},
visible: function() {
$module.addClass(className.visible);
}
},
remove: {
loading: function() {
$popup.removeClass(className.loading);
},
variation: function(variation) {
variation = variation || module.get.variation();
if(variation) {
module.verbose('Removing variation', variation);
$popup.removeClass(variation);
}
},
visible: function() {
$module.removeClass(className.visible);
},
attempts: function() {
module.verbose('Resetting all searched positions');
searchDepth = 0;
triedPositions = false;
}
},
bind: {
events: function() {
module.debug('Binding popup events to module');
if(settings.on == 'click') {
$module
.on('click' + eventNamespace, module.toggle)
;
}
if(settings.on == 'hover' && hasTouch) {
$module
.on('touchstart' + eventNamespace, module.event.touchstart)
;
}
if( module.get.startEvent() ) {
$module
.on(module.get.startEvent() + eventNamespace, module.event.start)
.on(module.get.endEvent() + eventNamespace, module.event.end)
;
}
if(settings.target) {
module.debug('Target set to element', $target);
}
$window.on('resize' + elementNamespace, module.event.resize);
},
popup: function() {
module.verbose('Allowing hover events on popup to prevent closing');
if( $popup && module.has.popup() ) {
$popup
.on('mouseenter' + eventNamespace, module.event.start)
.on('mouseleave' + eventNamespace, module.event.end)
;
}
},
close: function() {
if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
$document
.one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
;
$context
.one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
;
}
if(settings.on == 'hover' && openedWithTouch) {
module.verbose('Binding popup close event to document');
$document
.on('touchstart' + elementNamespace, function(event) {
module.verbose('Touched away from popup');
module.event.hideGracefully.call(element, event);
})
;
}
if(settings.on == 'click' && settings.closable) {
module.verbose('Binding popup close event to document');
$document
.on('click' + elementNamespace, function(event) {
module.verbose('Clicked away from popup');
module.event.hideGracefully.call(element, event);
})
;
}
}
},
unbind: {
close: function() {
if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
$document
.off('scroll' + elementNamespace, module.hide)
;
$context
.off('scroll' + elementNamespace, module.hide)
;
}
if(settings.on == 'hover' && openedWithTouch) {
$document
.off('touchstart' + elementNamespace)
;
openedWithTouch = false;
}
if(settings.on == 'click' && settings.closable) {
module.verbose('Removing close event from document');
$document
.off('click' + elementNamespace)
;
}
}
},
has: {
popup: function() {
return ($popup && $popup.length > 0);
}
},
is: {
offstage: function(distanceFromBoundary, position) {
var
offstage = []
;
// return boundaries that have been surpassed
$.each(distanceFromBoundary, function(direction, distance) {
if(distance < -settings.jitter) {
module.debug('Position exceeds allowable distance from edge', direction, distance, position);
offstage.push(direction);
}
});
if(offstage.length > 0) {
return true;
}
else {
return false;
}
},
active: function() {
return $module.hasClass(className.active);
},
animating: function() {
return ($popup !== undefined && $popup.hasClass(className.animating) );
},
fluid: function() {
return ($popup !== undefined && $popup.hasClass(className.fluid));
},
visible: function() {
return ($popup !== undefined && $popup.hasClass(className.visible));
},
dropdown: function() {
return $module.hasClass(className.dropdown);
},
hidden: function() {
return !module.is.visible();
},
rtl: function () {
return $module.css('direction') == 'rtl';
}
},
reset: function() {
module.remove.visible();
if(settings.preserve) {
if($.fn.transition !== undefined) {
$popup
.transition('remove transition')
;
}
}
else {
module.removePopup();
}
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
_module.exports.settings = {
name : 'Popup',
// module settings
debug : false,
verbose : false,
performance : true,
namespace : 'popup',
// callback only when element added to dom
onCreate : function(){},
// callback before element removed from dom
onRemove : function(){},
// callback before show animation
onShow : function(){},
// callback after show animation
onVisible : function(){},
// callback before hide animation
onHide : function(){},
// callback when popup cannot be positioned in visible screen
onUnplaceable: function(){},
// callback after hide animation
onHidden : function(){},
// when to show popup
on : 'hover',
// whether to add touchstart events when using hover
addTouchEvents : true,
// default position relative to element
position : 'top left',
// name of variation to use
variation : '',
// whether popup should be moved to context
movePopup : true,
// element which popup should be relative to
target : false,
// jq selector or element that should be used as popup
popup : false,
// popup should remain inline next to activator
inline : false,
// popup should be removed from page on hide
preserve : false,
// popup should not close when being hovered on
hoverable : false,
// explicitly set content
content : false,
// explicitly set html
html : false,
// explicitly set title
title : false,
// whether automatically close on clickaway when on click
closable : true,
// automatically hide on scroll
hideOnScroll : 'auto',
// hide other popups on show
exclusive : false,
// context to attach popups
context : 'body',
// position to prefer when calculating new position
prefer : 'opposite',
// specify position to appear even if it doesn't fit
lastResort : false,
// delay used to prevent accidental refiring of animations due to user error
delay : {
show : 50,
hide : 70
},
// whether fluid variation should assign width explicitly
setFluidWidth : true,
// transition settings
duration : 200,
transition : 'scale',
// distance away from activating element in px
distanceAway : 0,
// number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
jitter : 2,
// offset on aligning axis from calculated position
offset : 0,
// maximum times to look for a position before failing (9 positions total)
maxSearchDepth : 15,
error: {
invalidPosition : 'The position you specified is not a valid position',
cannotPlace : 'Popup does not fit within the boundaries of the viewport',
method : 'The method you called is not defined.',
noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>',
notFound : 'The target or popup you specified does not exist on the page'
},
metadata: {
activator : 'activator',
content : 'content',
html : 'html',
offset : 'offset',
position : 'position',
title : 'title',
variation : 'variation'
},
className : {
active : 'active',
animating : 'animating',
dropdown : 'dropdown',
fluid : 'fluid',
loading : 'loading',
popup : 'ui popup',
position : 'top left center bottom right',
visible : 'visible'
},
selector : {
popup : '.ui.popup'
},
templates: {
escape: function(string) {
var
badChars = /[&<>"'`]/g,
shouldEscape = /[&<>"'`]/,
escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
},
escapedChar = function(chr) {
return escape[chr];
}
;
if(shouldEscape.test(string)) {
return string.replace(badChars, escapedChar);
}
return string;
},
popup: function(text) {
var
html = '',
escape = _module.exports.settings.templates.escape
;
if(typeof text !== undefined) {
if(typeof text.title !== undefined && text.title) {
text.title = escape(text.title);
html += '<div class="header">' + text.title + '</div>';
}
if(typeof text.content !== undefined && text.content) {
text.content = escape(text.content);
html += '<div class="content">' + text.content + '</div>';
}
}
return html;
}
}
};
})( require("jquery"), window, document );
| {
"content_hash": "15e07ced8cef4966ee27a8d7985150f6",
"timestamp": "",
"source": "github",
"line_count": 1405,
"max_line_length": 117,
"avg_line_length": 33.02989323843416,
"alnum_prop": 0.4701230417824897,
"repo_name": "jalota16/cooklah",
"id": "70e4250dafccd5f5fa0262009e7a8ccd56808743",
"size": "46604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bower_components/semantic-ui-popup/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2082325"
},
{
"name": "HTML",
"bytes": "448876"
},
{
"name": "JavaScript",
"bytes": "3060785"
}
],
"symlink_target": ""
} |
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stddef.h>
#include <limits.h>
#include "aplib.h"
/*
* Calling convention for the callback.
*/
#ifndef CB_CALLCONV
# if defined(AP_DLL)
# define CB_CALLCONV __stdcall
# elif defined(__GNUC__)
# define CB_CALLCONV
# else
# define CB_CALLCONV __cdecl
# endif
#endif
/*
* Unsigned char type.
*/
typedef unsigned char byte;
/*
* Compute ratio between two numbers.
*/
unsigned int ratio(unsigned int x, unsigned int y)
{
if (x <= UINT_MAX / 100) x *= 100; else y /= 100;
if (y == 0) y = 1;
return x / y;
}
/*
* Compression callback.
*/
int CB_CALLCONV callback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam)
{
printf("\rcompressed %u -> %u bytes (%u%% done)", inpos, outpos, ratio(inpos, insize));
return 1;
}
/*
* Compress a file.
*/
int compress_file(const char *oldname, const char *packedname)
{
FILE *oldfile;
FILE *packedfile;
unsigned int insize, outsize;
clock_t clocks;
byte *data, *packed, *workmem;
/* open input file */
if ((oldfile = fopen(oldname, "rb")) == NULL)
{
printf("\nERR: unable to open input file\n");
return 1;
}
/* get size of input file */
fseek(oldfile, 0, SEEK_END);
insize = (unsigned int) ftell(oldfile);
fseek(oldfile, 0, SEEK_SET);
/* allocate memory */
if ((data = (byte *) malloc(insize)) == NULL ||
(packed = (byte *) malloc(aP_max_packed_size(insize))) == NULL ||
(workmem = (byte *) malloc(aP_workmem_size(insize))) == NULL)
{
printf("\nERR: not enough memory\n");
return 1;
}
if (fread(data, 1, insize, oldfile) != insize)
{
printf("\nERR: error reading from input file\n");
return 1;
}
clocks = clock();
/* compress data block */
outsize = aP_pack(data, packed, insize, workmem, callback, NULL);
clocks = clock() - clocks;
/* check for compression error */
if (outsize == APLIB_ERROR)
{
printf("\nERR: an error occured while compressing\n");
return 1;
}
/* create output file */
if ((packedfile = fopen(packedname, "wb")) == NULL)
{
printf("\nERR: unable to create output file\n");
return 1;
}
fwrite(packed, 1, outsize, packedfile);
/* show result */
printf("\rcompressed %u -> %u bytes (%u%%) in %.2f seconds\n",
insize, outsize, ratio(outsize, insize),
(double)clocks / (double)CLOCKS_PER_SEC);
/* close files */
fclose(packedfile);
fclose(oldfile);
/* free memory */
free(workmem);
free(packed);
free(data);
return 0;
}
/*
* Decompress a file.
*/
int decompress_file(const char *packedname, const char *newname)
{
FILE *newfile;
FILE *packedfile;
unsigned int insize, outsize;
clock_t clocks;
byte *data, *packed;
unsigned int depackedsize;
/* open input file */
if ((packedfile = fopen(packedname, "rb")) == NULL)
{
printf("\nERR: unable to open input file\n");
return 1;
}
/* get size of input file */
fseek(packedfile, 0, SEEK_END);
insize = (unsigned int) ftell(packedfile);
fseek(packedfile, 0, SEEK_SET);
/* allocate memory */
if ((packed = (byte *) malloc(insize)) == NULL)
{
printf("\nERR: not enough memory\n");
return 1;
}
if (fread(packed, 1, insize, packedfile) != insize)
{
printf("\nERR: error reading from input file\n");
return 1;
}
depackedsize = 0x800000;//aPsafe_get_orig_size(packed);
/*if (depackedsize == APLIB_ERROR)
{
printf("\nERR: compressed data error\n");
return 1;
}*/
/* allocate memory */
if ((data = (byte *) malloc(depackedsize)) == NULL)
{
printf("\nERR: not enough memory\n");
return 1;
}
clocks = clock();
/* decompress data */
outsize = aP_depack_asm(packed, data);
clocks = clock() - clocks;
/* check for decompression error */
/*if (outsize != depackedsize)
{
printf("\nERR: an error occured while decompressing\n");
return 1;
}*/
/* create output file */
if ((newfile = fopen(newname, "wb")) == NULL)
{
printf("\nERR: unable to create output file\n");
return 1;
}
/* write decompressed data */
fwrite(data, 1, outsize, newfile);
/* show result */
printf("decompressed %u -> %u bytes in %.2f seconds\n",
insize, outsize,
(double)clocks / (double)CLOCKS_PER_SEC);
/* close files */
fclose(packedfile);
fclose(newfile);
/* free memory */
free(packed);
free(data);
return 0;
}
/*
* Show program syntax.
*/
void show_syntax(void)
{
printf("syntax:\n\n"
" compress : appack c <file> <packed_file>\n"
" decompress : appack d <packed_file> <depacked_file>\n\n");
}
/*
* Main.
*/
int main(int argc, char *argv[])
{
/* show banner */
printf("===============================================================================\n"
"aPLib example Copyright (c) 1998-2009 by Joergen Ibsen / Jibz\n"
" All Rights Reserved\n\n"
" http://www.ibsensoftware.com/\n"
"===============================================================================\n\n");
/* check number of arguments */
if (argc != 4)
{
show_syntax();
return 1;
}
#ifdef __WATCOMC__
/* OpenWatcom 1.2 line buffers stdout, so we unbuffer stdout manually
to make the progress indication in the callback work.
*/
setbuf(stdout, NULL);
#endif
/* check first character of first argument to determine action */
if (argv[1][0] && argv[1][1] == '\0')
{
switch (argv[1][0])
{
/* compress file */
case 'c':
case 'C': return compress_file(argv[2], argv[3]);
/* decompress file */
case 'd':
case 'D': return decompress_file(argv[2], argv[3]);
}
}
/* show program syntax */
show_syntax();
return 1;
}
| {
"content_hash": "cdd80bb14c4e53a461fac15a5f0e26c7",
"timestamp": "",
"source": "github",
"line_count": 275,
"max_line_length": 101,
"avg_line_length": 23.14909090909091,
"alnum_prop": 0.5300031416902293,
"repo_name": "SONIC3D/gendev-macos",
"id": "961320137b1b9e2af80a033281725e3360d9484a",
"size": "6560",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/files/applib/example/appack.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "139900"
},
{
"name": "C",
"bytes": "148839"
},
{
"name": "Makefile",
"bytes": "20488"
},
{
"name": "Python",
"bytes": "33959"
},
{
"name": "Shell",
"bytes": "905"
}
],
"symlink_target": ""
} |
<?php
/**
* Cart Page
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
wc_print_notices();
do_action( 'woocommerce_before_cart' ); ?>
<form action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post">
<?php do_action( 'woocommerce_before_cart_table' ); ?>
<div class="table-responsive">
<table class="shop_table cart table" cellspacing="0">
<thead>
<tr>
<th class="product-remove"> </th>
<th class="product-thumbnail"> </th>
<th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th>
<th class="product-price"><?php _e( 'Price', 'woocommerce' ); ?></th>
<th class="product-quantity"><?php _e( 'Quantity', 'woocommerce' ); ?></th>
<th class="product-subtotal"><?php _e( 'Total', 'woocommerce' ); ?></th>
</tr>
</thead>
<tbody>
<?php do_action( 'woocommerce_before_cart_contents' ); ?>
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
?>
<tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">
<td class="product-remove">
<?php
echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf( '<a href="%s" class="remove text-danger" title="%s"><i class="fa fa-times"></i></a>', esc_url( WC()->cart->get_remove_url( $cart_item_key ) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key );
?>
</td>
<td class="product-thumbnail">
<?php
$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
if ( ! $_product->is_visible() )
echo $thumbnail;
else
printf( '<a href="%s">%s</a>', $_product->get_permalink(), $thumbnail );
?>
</td>
<td class="product-name">
<?php
if ( ! $_product->is_visible() )
echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key );
else
echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', $_product->get_permalink(), $_product->get_title() ), $cart_item, $cart_item_key );
// Meta data
echo WC()->cart->get_item_data( $cart_item );
// Backorder notification
if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) )
echo '<p class="backorder_notification">' . __( 'Available on backorder', 'woocommerce' ) . '</p>';
?>
</td>
<td class="product-price">
<?php
echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
?>
</td>
<td class="product-quantity">
<?php
if ( $_product->is_sold_individually() ) {
$product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
} else {
$product_quantity = woocommerce_quantity_input( array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
), $_product, false );
}
echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key );
?>
</td>
<td class="product-subtotal">
<?php
echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
?>
</td>
</tr>
<?php
}
}
do_action( 'woocommerce_cart_contents' );
?>
</tbody>
</table>
</div>
<div class="row actions">
<div class="col-sm-6 top-buffer">
<?php if ( WC()->cart->coupons_enabled() ) { ?>
<label for="coupon_code" class="sr-only"><?php _e( 'Coupon', 'woocommerce' ); ?>:</label>
<div class="coupon input-group">
<input type="text" name="coupon_code" class="input-text form-control" id="coupon_code" value="" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" />
<span class="input-group-btn">
<input type="submit" class="button btn btn-default" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" />
</span>
</div>
<?php do_action('woocommerce_cart_coupon'); ?>
<?php } ?>
</div>
<div class="col-sm-6 top-buffer text-right">
<input type="submit" class="button btn btn-default" name="update_cart" value="<?php _e( 'Update Cart', 'woocommerce' ); ?>" />
<input type="submit" class="checkout-button button alt wc-forward btn btn-success" name="proceed" value="<?php _e( 'Proceed to Checkout', 'woocommerce' ); ?>" />
<?php //do_action( 'woocommerce_proceed_to_checkout' ); ?>
<?php wp_nonce_field( 'woocommerce-cart' ); ?>
</div>
</div>
<?php do_action( 'woocommerce_after_cart_contents' ); ?>
<?php do_action( 'woocommerce_after_cart_table' ); ?>
</form>
<div class="cart-collaterals row">
<?php do_action( 'woocommerce_cart_collaterals' ); ?>
<?php woocommerce_cart_totals(); ?>
<?php woocommerce_shipping_calculator(); ?>
</div>
<?php do_action( 'woocommerce_after_cart' ); ?> | {
"content_hash": "0081db8e1666bf30d0974f81ed626c68",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 276,
"avg_line_length": 36.2,
"alnum_prop": 0.5849447513812155,
"repo_name": "harrygr/samarkand",
"id": "6b98379a49bf16ae9ecf6c726c26fa7471de67e8",
"size": "5792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "woocommerce/cart/cart.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "36469"
},
{
"name": "JavaScript",
"bytes": "8695"
},
{
"name": "PHP",
"bytes": "214080"
}
],
"symlink_target": ""
} |
import * as React from "react";
import { ContainerContext } from "./container";
import { MapStoresToProps, StoreMap, Unsubscribe } from "./types";
import { Store } from "./Store";
export function connect<TInjectedProps, TAllProps extends TInjectedProps>(
mapStoresToProps: MapStoresToProps<TInjectedProps>,
Cmp: React.ComponentType<TAllProps | {}>
) {
return class ConnectedComponent extends React.PureComponent<
Omit<TAllProps, keyof TInjectedProps>
> {
subscribedStores: {
[storeName: string]: Unsubscribe;
} = {};
render() {
const allStores: StoreMap = this.withAutoSubscribers(this.context);
return <Cmp {...mapStoresToProps(allStores)} {...this.props} />;
}
componentWillUnmount() {
Object.values(this.subscribedStores).forEach(u => u());
}
subscribeToStore(name: string, store: Store) {
const unsubscribe = store.subscribe(() => {
this.forceUpdate();
});
this.subscribedStores[name] = unsubscribe;
}
withAutoSubscribers(stores: StoreMap): StoreMap {
const watchedStores: StoreMap = {};
Object.keys(stores).forEach(key => {
Object.defineProperty(watchedStores, key, {
get: () => {
if (!this.subscribedStores[key]) {
this.subscribeToStore(key, stores[key]);
this.subscribedStores[key];
}
return stores[key];
}
});
});
return watchedStores;
}
static displayName: string = `Connect(${Cmp.name || Cmp.displayName})`;
static contextType = ContainerContext;
};
}
| {
"content_hash": "4a085d9b4730666a6d7dca02554be81f",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 75,
"avg_line_length": 30.846153846153847,
"alnum_prop": 0.628428927680798,
"repo_name": "alisabzevari/reastore",
"id": "ae3452719fd5068190814442ca91eccebd5fb402",
"size": "1604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/connect.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "88"
},
{
"name": "TypeScript",
"bytes": "8261"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "fe1b51cc0b1a27fdeacf774203069ad2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "d09668dcc86ce29c8fbe6ca159d7b4092422fb35",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Centaurea/Centaurea glaberrima/Centaurea glaberrima glaberrima/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/**
* @namespace
*/
namespace ShiftTest\Unit\ShiftContentNew\Type\Field\Attribute\Validator;
use Mockery;
use ShiftTest\TestCase;
use ShiftContentNew\Type\Field\Attribute\Validator\OptionTypeValidator;
/**
* Option type validator test
* This holds unit tests for attribute option variable type validator.
*
* @category Projectshift
* @package ShiftContentNew
* @subpackage Tests
*
* @group unit
*/
class OptionTypeValidatorTest extends TestCase
{
/**
* Test that we can instantiate validator
* @test
*/
public function canInstantiateValidator()
{
$type = 'ShiftContentNew\Type\Field\Attribute\Validator';
$type .= '\OptionTypeValidator';
$validator = new OptionTypeValidator;
$this->assertInstanceOf($type, $validator);
}
/**
* Test that invalid type fails validation.
* @test
*/
public function invalidTypeFailsValidation()
{
$type = 'INVALID';
$validator = new OptionTypeValidator;
$this->assertFalse($validator->isValid($type));
$errors = $validator->getMessages();
$this->assertTrue(isset($errors['invalidVariableType']));
}
/**
* Test that valid type passes validation
*/
public function validTypePassesValidation()
{
$validator = new OptionTypeValidator;
$this->assertTrue($validator->isValid('bool'));
$this->assertTrue($validator->isValid('string'));
$this->assertTrue($validator->isValid('int'));
$errors = $validator->getMessages();
$this->assertTrue(empty($errors));
}
}//class ends here | {
"content_hash": "4065096275f1d76a0addd4b81117236f",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 72,
"avg_line_length": 23.267605633802816,
"alnum_prop": 0.6422518159806295,
"repo_name": "dmitrybelyakov/shift-content-new",
"id": "551ca046dc35a724025512f68ac9fb29d3d7469c",
"size": "2352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/ShiftContentNew/Type/Field/Attribute/Validator/OptionTypeValidatorTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "408334"
},
{
"name": "JavaScript",
"bytes": "1018115"
},
{
"name": "PHP",
"bytes": "522323"
},
{
"name": "Ruby",
"bytes": "1919"
}
],
"symlink_target": ""
} |
require "rom/core"
RSpec.describe ROM, ".components" do
let(:components) do
ROM.components
end
around do |example|
components.keys.tap do |keys|
example.run
(components.keys - keys).each { |key| components._container.delete(key) }
end
end
it "registers a component handler with default key and namespace" do
module Test
class Serializer
end
end
ROM.components do
register(:serializer, Test::Serializer)
end
expect(components[:serializer].key).to be(:serializer)
expect(components[:serializer].namespace).to be(:serializers)
expect(components[:serializer].constant).to be(Test::Serializer)
end
end
| {
"content_hash": "f0e8cb9875431fb7ade0b0ad0f822c06",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 79,
"avg_line_length": 23.586206896551722,
"alnum_prop": 0.6842105263157895,
"repo_name": "rom-rb/rom",
"id": "ac5ef9d3503e7b2e14b28ffe73f61bc8e8a918e9",
"size": "715",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spec/suite/rom/global/components_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "166"
},
{
"name": "HTML",
"bytes": "1478"
},
{
"name": "Ruby",
"bytes": "894035"
},
{
"name": "Shell",
"bytes": "341"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Ascophora nucum Corda
### Remarks
null | {
"content_hash": "24f8528d598b841ffdecec3fc6ee572d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 21,
"avg_line_length": 9.615384615384615,
"alnum_prop": 0.704,
"repo_name": "mdoering/backbone",
"id": "8ad74dadd6131d8b5aa0075c8fe78e48d8ca6894",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Zygomycota/Mucorales/Mucoraceae/Mucor/Ascophora nucuum/ Syn. Ascophora nucum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* Author: 陈志杭 Caspar
* Contact: 279397942@qq.com qq:279397942
* Description: 逻辑层接口契约文件
* 文件由模板生成,请不要直接修改文件,如需修改请创建一个对应的partial文件
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Zh.DAL.Define.Entities;
using Zh.BLL.Define.Entities;
using Zh.BLL.Base.Define;
namespace Zh.BLL.Define.Contracts
{
public partial interface IActivityAttentionService : IBaseService< ActivityAttentionDto,Activity_Attention>
{
}
} | {
"content_hash": "7c8850a26bce1b37d02115bf14f32c5b",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 111,
"avg_line_length": 24.894736842105264,
"alnum_prop": 0.758985200845666,
"repo_name": "Caspar12/Csharp",
"id": "629d102eaa179daed08a5547ad7fe494f3291c88",
"size": "559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Zh.BLL.Define/Contracts/AutoCode/IActivityAttentionService.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "345"
},
{
"name": "Batchfile",
"bytes": "85"
},
{
"name": "C#",
"bytes": "2496338"
},
{
"name": "CSS",
"bytes": "4500"
},
{
"name": "HTML",
"bytes": "8844"
},
{
"name": "JavaScript",
"bytes": "21236"
},
{
"name": "PHP",
"bytes": "59313"
},
{
"name": "Pascal",
"bytes": "133111"
},
{
"name": "PowerShell",
"bytes": "139820"
},
{
"name": "Puppet",
"bytes": "972"
}
],
"symlink_target": ""
} |
package org.renci.databridge.persistence.metadata;
import java.util.*;
public class VariableTransferObject {
private String name;
private String description; // Free text metadata about the study
private HashMap<String, String> extra;
// These attributes are specific to the DataBridge
private int version;
private int insertTime; // Seconds since the epoch
private String dataStoreId; // The id generated at insertion time.
private String fileDataStoreId;
/**
* Get name.
*
* @return name as String.
*/
public String getName()
{
return name;
}
/**
* Set name.
*
* @param name the value to set.
*/
public void setName(String name)
{
this.name = name;
}
/**
* Get description.
*
* @return description as String.
*/
public String getDescription()
{
return description;
}
/**
* Set description.
*
* @param description the value to set.
*/
public void setDescription(String description)
{
this.description = description;
}
/**
* Get version.
*
* @return version as int.
*/
public int getVersion()
{
return version;
}
/**
* Set version.
*
* @param version the value to set.
*/
public void setVersion(int version)
{
this.version = version;
}
/**
* Get fileDataStoreId.
*
* @return fileDataStoreId as String.
*/
public String getFileDataStoreId()
{
return fileDataStoreId;
}
/**
* Set fileDataStoreId.
*
* @param fileDataStoreId the value to set.
*/
public void setFileDataStoreId(String fileDataStoreId)
{
this.fileDataStoreId = fileDataStoreId;
}
/**
* Get dataStoreId.
*
* @return dataStoreId as String.
*/
public String getDataStoreId()
{
return dataStoreId;
}
/**
* Set dataStoreId.
*
* @param dataStoreId the value to set.
*/
public void setDataStoreId(String dataStoreId)
{
this.dataStoreId = dataStoreId;
}
/**
* Get extra.
*
* @return extra as HashMap<String, String>
*/
public HashMap<String, String> getExtra()
{
return extra;
}
/**
* Set extra.
*
* @param extra the value to set.
*/
public void setExtra(HashMap<String, String> extra)
{
this.extra = extra;
}
@Override
public String toString ()
{
return "{" + getClass ().getName () + ": name: " + getName () + ", description: " + getDescription () + ", extra: " + getExtra () + ", version: " + getVersion () + ", dataStoreId: " + getDataStoreId () + ", fileDataStoreId: " + getFileDataStoreId () + "}";
}
/**
* Get insertTime.
*
* @return insertTime as int.
*/
public int getInsertTime()
{
return insertTime;
}
/**
* Set insertTime.
*
* @param insertTime the value to set.
*/
public void setInsertTime(int insertTime)
{
this.insertTime = insertTime;
}
}
| {
"content_hash": "9bc08a3564f170b490eae8b41533bf1d",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 265,
"avg_line_length": 20.229813664596275,
"alnum_prop": 0.5431378569235493,
"repo_name": "HowardLander/DataBridge",
"id": "89d550fc3bfdf8c25346e0a9694f9e99d38ef317",
"size": "3257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "persistence/src/main/java/org/renci/databridge/persistence/metadata/VariableTransferObject.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "2842"
},
{
"name": "HTML",
"bytes": "4259"
},
{
"name": "Java",
"bytes": "822249"
},
{
"name": "JavaScript",
"bytes": "31621"
},
{
"name": "Shell",
"bytes": "23977"
}
],
"symlink_target": ""
} |
layout: default
---
<article class="post" itemscope itemtype="http://schema.org/BlogPosting">
<header class="post-header">
<h1 class="post-title" itemprop="name headline">{{ page.title }}</h1>
<p class="post-meta"><time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">{{ page.date | date: "%b %-d, %Y" }}</time>{% if page.author %} • <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">{{ page.author }}</span></span>{% endif %}</p>
</header>
<div class="post-content" itemprop="articleBody">
{{ content }}
</div>
</article>
| {
"content_hash": "43925cbd42d6ad5411055267eccbbcc3",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 307,
"avg_line_length": 50.833333333333336,
"alnum_prop": 0.6459016393442623,
"repo_name": "evan-erdos/evan-erdos.github.io",
"id": "2ba0f1d4fcf556bc473a3651aaf97b3544fe6987",
"size": "616",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_layouts/post.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "92937"
},
{
"name": "CoffeeScript",
"bytes": "69387"
},
{
"name": "HTML",
"bytes": "30085"
},
{
"name": "JavaScript",
"bytes": "1351811"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="PortabilityAnalysis0">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
5cb0c56c-b0c2-4325-b987-89c8b2c5532f
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#ASCOM.Exceptions">ASCOM.Exceptions</a></strong></td>
<td class="text-center">89.29 %</td>
<td class="text-center">89.29 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">89.29 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
<a name="ASCOM.Exceptions"><h3>ASCOM.Exceptions</h3></a>
<table>
<tbody>
<tr>
<th>Target type</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
<th>Recommended changes</th>
</tr>
<tr>
<td>System.Exception</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove. Ctor overload taking SerializationInfo is not applicable in new surface area</td>
</tr>
<tr>
<td style="padding-left:2em">#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove. Ctor overload taking SerializationInfo is not applicable in new surface area</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.NonSerializedAttribute</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove usage</td>
</tr>
<tr>
<td style="padding-left:2em">#ctor</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove usage</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Runtime.Serialization.SerializationInfo</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove serialization constructors on custom Exception types</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.SerializableAttribute</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove this attribute</td>
</tr>
<tr>
<td style="padding-left:2em">#ctor</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove this attribute</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<p>
<a href="#Portability Summary">Back to Summary</a>
</p>
</div>
</div>
</body>
</html> | {
"content_hash": "463c63d2fa8ab5081eb6b4b55ee8f2b0",
"timestamp": "",
"source": "github",
"line_count": 359,
"max_line_length": 562,
"avg_line_length": 42.42339832869081,
"alnum_prop": 0.4788575180564675,
"repo_name": "kuhlenh/port-to-core",
"id": "132d014c2dd59821a35962d4566d2673cb24bdf4",
"size": "15230",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "Reports/as/ascom.platform.6.1.1.9/ASCOM.Exceptions-net452.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2323514650"
}
],
"symlink_target": ""
} |
package net.authorize.data;
import java.io.Serializable;
/**
* Product shipping address.
*/
public class ShippingAddress extends Address implements Serializable {
private static final long serialVersionUID = 2L;
private ShippingAddress() {
super();
}
public static ShippingAddress createShippingAddress() {
return new ShippingAddress();
}
}
| {
"content_hash": "59cf17bb9edd02453abb7ea6da14375d",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 70,
"avg_line_length": 16.363636363636363,
"alnum_prop": 0.75,
"repo_name": "YOTOV-LIMITED/sdk-android",
"id": "20244986e0d2e8cd47cc92a42d908af36fd314fb",
"size": "360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/net/authorize/data/ShippingAddress.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "637466"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Basic Page Needs
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<meta charset="utf-8">
<title>Savy Lacombe</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<link rel="stylesheet" type="text/css" href="https://cloud.typography.com/6276294/6089152/css/fonts.css" />
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<link rel="icon" type="image/png" href="assets/favicon.png">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67060904-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body class="portfolio">
<div class="container">
<div class="box">
<h3>Portfolio</h3>
<p>Below are two case studies from recent projects at Sprout Social. The links each go to a Figma deck, use [z] to adjust them to fit to your screen when viewing.</p>
<a class="case_study" href="https://www.figma.com/proto/hR0HHJFMY4NprGzrxUwBqx/Case-Studies-2021?node-id=9%3A1&viewport=-477%2C1402%2C0.5464087128639221&scaling=min-zoom" target="_blank">View the <b>Link Sharing</b> Case Study</a>
<br>
<br>
<a class="case_study" href="https://www.figma.com/proto/hR0HHJFMY4NprGzrxUwBqx/Case-Studies-2021?node-id=46%3A445&viewport=-303%2C681%2C0.4243191182613373&scaling=min-zoom" target="_blank">View the <b>User Roles</b> Case Study</a>
</div>
</div>
</body>
</html>
| {
"content_hash": "b5801f27b7deea669560d5aa2dd2e74a",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 236,
"avg_line_length": 44.03703703703704,
"alnum_prop": 0.5941968040370059,
"repo_name": "xmwl/homepage",
"id": "d1a27f4b71013e4635aa1cddb710423daf58c198",
"size": "2878",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "portfolio.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "763"
},
{
"name": "HTML",
"bytes": "3315"
}
],
"symlink_target": ""
} |
'use strict';
//Form相关操作
//获取表单的值
var input1 = document.getElementById('email');
console.log(input1.value);
//修改
input1.value = "kris.dacpc@gmail.com";
//是否勾选
var label1 = document.getElementById('monday');
console.log(label1.checked);
label1.checked = true;
//提交表单
function doSubmitForm(){
var form = document.getElementById('test-form-input');
form.value="success";
}
function checkForm(){
var pwd = document.getElementById('password');
pwd.value = toMD5(pwd.value);
console.log('t');
return true;
}
//简单校验
var checkRegisterForm = function () {
var user = document.getElementById('username-1').value,
psd = document.getElementById('password-1').value,
psd2 = document.getElementById('password-2').value,
usertest = /(\w){3,10}/;
if(!usertest){
alert('用户名必须是3-10位英文字母或数字');
return false;
} else if (psd.length>20 || psd.length<6){
alert('口令必须是6-20位');
return false;
} else if (psd !== psd2){
alert('两次输入口令必须一致');
} else {
return true;
}
}
| {
"content_hash": "dbf9788e6830467377cad528d49f194c",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 59,
"avg_line_length": 23.355555555555554,
"alnum_prop": 0.6384395813510942,
"repo_name": "KrisCheng/HackerPractice",
"id": "115afeda7081444477590c1e22f8d18406059985",
"size": "1159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JavaScript/Basic/Past/Demo5/static5.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "305"
},
{
"name": "HTML",
"bytes": "57696"
},
{
"name": "JavaScript",
"bytes": "83921"
},
{
"name": "Python",
"bytes": "18233"
}
],
"symlink_target": ""
} |
import React from 'react';
import './Header.scss';
import WingButton from '../WingButton/WingButton';
import FieldEditor from '../FieldEditor/FieldEditor';
const Header = (props) => (
<div className="header-wrapper">
<WingButton onClick={props.autoPlay}></WingButton>
<FieldEditor value={props.email} onChange= {props.editEmail}></FieldEditor>
</div>
);
Header.propTypes = {
autoPlay: React.PropTypes.func.isRequired,
editEmail: React.PropTypes.func.isRequired,
email: React.PropTypes.string.isRequired
};
export default Header;
| {
"content_hash": "52cdb9b298cad4bfdfb844aeca700e37",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 79,
"avg_line_length": 27.55,
"alnum_prop": 0.7332123411978222,
"repo_name": "rainbowland302/hangman",
"id": "d79d142dafa37b03a2519ed8de870248a59cb73f",
"size": "551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/Header/Header.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4729"
},
{
"name": "HTML",
"bytes": "345"
},
{
"name": "JavaScript",
"bytes": "61705"
}
],
"symlink_target": ""
} |
import { extra, autoService } from 'knifecycle';
import { readArgs } from '../libs/args.js';
import { YError } from 'yerror';
import camelCase from 'camelcase';
import { HANDLER_REG_EXP } from '@whook/whook';
import _inquirer from 'inquirer';
import path from 'path';
import { OPEN_API_METHODS, noop } from '@whook/whook';
import { default as fsExtra } from 'fs-extra';
import type { Answers } from 'inquirer';
import type {
WhookCommandHandler,
WhookCommandDefinition,
PromptArgs,
} from '../services/promptArgs.js';
import type { LogService } from 'common-services';
import type { OpenAPIV3 } from 'openapi-types';
const {
writeFile: _writeFile,
ensureDir: _ensureDir,
pathExists: _pathExists,
} = fsExtra;
// Currently, we rely on a static list of services but
// best would be to use TypeScript introspection and
// the autoloader to allow to retrieve a dynamic list
// of constants from the CONFIGS service, the WhookConfigs
// type and the autoloader service.
const commonServicesTypes = {
time: 'TimeService',
log: 'LogService',
random: 'RandomService',
delay: 'DelayService',
process: 'ProcessService',
};
const whookSimpleTypes = {
HOST: 'string',
PORT: 'number',
PROJECT_DIR: 'string',
PROJECT_SRC: 'string',
NODE_ENV: 'string',
DEBUG_NODE_ENVS: 'string[]',
WHOOK_PLUGINS_PATHS: 'string[]',
};
const whookServicesTypes = {
API_DEFINITIONS: 'DelayService',
ENV: 'ENVService',
APM: 'APMService',
CONFIGS: 'CONFIGSService',
};
const allTypes = {
...commonServicesTypes,
...whookSimpleTypes,
...whookServicesTypes,
};
export const definition: WhookCommandDefinition = {
description: 'A command helping to create new Whook files easily',
example: `whook create --type service --name "db"`,
arguments: {
type: 'object',
additionalProperties: false,
required: ['type', 'name'],
properties: {
type: {
description: 'Type',
type: 'string',
enum: ['handler', 'service', 'provider', 'command'],
},
name: {
description: 'Name',
type: 'string',
},
},
},
};
export default extra(definition, autoService(initCreateCommand));
async function initCreateCommand({
PROJECT_DIR,
API,
inquirer = _inquirer,
promptArgs,
writeFile = _writeFile,
ensureDir = _ensureDir,
pathExists = _pathExists,
log = noop,
}: {
PROJECT_DIR: string;
API: OpenAPIV3.Document;
inquirer: typeof _inquirer;
promptArgs: PromptArgs;
writeFile: typeof _writeFile;
ensureDir: typeof _ensureDir;
pathExists: typeof _pathExists;
log?: LogService;
}): Promise<WhookCommandHandler> {
return async () => {
const {
namedArguments: { type, name },
} = readArgs<{ type: string; name: string }>(
definition.arguments,
await promptArgs(),
);
const finalName = camelCase(name);
if (name !== finalName) {
log('warning', `🐪 - Camelized the name "${finalName}".`);
}
if (type === 'handler' && !HANDLER_REG_EXP.test(finalName)) {
log(
'error',
`💥 - The handler name is invalid, "${finalName}" does not match "${HANDLER_REG_EXP}".`,
);
throw new YError('E_BAD_HANDLER_NAME', finalName, HANDLER_REG_EXP);
}
const { services } = (await inquirer.prompt([
{
name: 'services',
type: 'checkbox',
message: 'Which services do you want to use?',
choices: [
...Object.keys(commonServicesTypes),
...Object.keys(whookSimpleTypes),
...Object.keys(whookServicesTypes),
],
},
])) as { services: string[] };
const servicesTypes = services
.sort()
.map((name) => ({
name,
type: allTypes[name],
}))
.concat(
type === 'command' ? [{ name: 'promptArgs', type: 'PromptArgs' }] : [],
);
const parametersDeclaration = servicesTypes.length
? `{${servicesTypes
.map(
({ name }) => `
${name},`,
)
.join('')}
}`
: '';
const typesDeclaration = servicesTypes.length
? `{${servicesTypes
.map(
({ name, type }) => `
${name}: ${type};`,
)
.join('')}
}`
: '';
const commonServices = services.filter(
(service) => commonServicesTypes[service],
);
const whookServices = services.filter(
(service) => whookServicesTypes[service],
);
const imports = `${
type === 'command'
? `
import {
readArgs,
} from '@whook/cli';
import type {
PromptArgs,
WhookCommandArgs,
WhookCommandDefinition,
WhookCommandHandler,
} from '@whook/cli';`
: ''
}${
commonServices.length
? `
import type { ${commonServices
.map((name) => commonServicesTypes[name])
.join(', ')} } from 'common-services';`
: ''
}${
whookServices.length
? `
import type { ${whookServices
.map((name) => whookServicesTypes[name])
.join(', ')} } from '@whook/whook';`
: ''
}
`;
let fileSource = '';
if (type === 'handler') {
let baseQuestions = [
{
name: 'method',
type: 'list',
message: 'Give the handler method',
choices: OPEN_API_METHODS,
default: [(HANDLER_REG_EXP.exec(finalName) as string[])[1]].filter(
(maybeMethod) => OPEN_API_METHODS.includes(maybeMethod),
)[0],
},
{
name: 'path',
type: 'input',
message: 'Give the handler path',
},
{
name: 'description',
type: 'input',
message: 'Give the handler description',
},
] as Answers[];
if (API.tags && API.tags.length) {
baseQuestions = [
...baseQuestions,
{
name: 'tags',
type: 'checkbox',
message: 'Assing one or more tags to the handler',
choices: API.tags.map(({ name }) => name),
},
];
}
const { method, path, description, tags } = (await inquirer.prompt(
baseQuestions,
)) as {
method: string;
path: string;
description: string;
tags: string[];
};
fileSource = buildHandlerSource(
name,
path,
method,
description,
tags,
parametersDeclaration,
typesDeclaration,
imports,
);
} else if (type === 'service') {
fileSource = buildServiceSource(
name,
parametersDeclaration,
typesDeclaration,
imports,
);
} else if (type === 'provider') {
fileSource = buildProviderSource(
name,
parametersDeclaration,
typesDeclaration,
imports,
);
} else if (type === 'command') {
const { description } = (await inquirer.prompt([
{
name: 'description',
message: 'Give the command description',
},
])) as { description: string };
fileSource = buildCommandSource(
name,
description,
parametersDeclaration,
typesDeclaration,
imports,
);
} else {
throw new YError('E_UNEXPECTED_TYPE');
}
const fileDir = path.join(
PROJECT_DIR,
'src',
['service', 'provider'].includes(type)
? 'services'
: type === 'handler'
? 'handlers'
: 'commands',
);
await ensureDir(fileDir);
const filePath = path.join(fileDir, `${name}.ts`);
if (await pathExists(filePath)) {
log('warning', '⚠️ - The file already exists !');
const { erase } = (await inquirer.prompt([
{
name: 'Erase ?',
type: 'confirm',
},
])) as {
erase: boolean;
};
if (!erase) {
return;
}
}
await writeFile(filePath, fileSource);
};
}
function buildHandlerSource(
name: string,
path: string,
method: string,
description = '',
tags: string[] = [],
parametersDeclaration,
typesDeclaration,
imports: string,
) {
const APIHandlerName = name[0].toUpperCase() + name.slice(1);
return `import { autoHandler } from 'knifecycle';
import type { WhookAPIHandlerDefinition } from '@whook/whook';${imports}
export const definition: WhookAPIHandlerDefinition = {
path: '${path}',
method: '${method}',
operation: {
operationId: '${name}',
summary: '${description.replace(/'/g, "\\'")}',
tags: [${tags.map((tag) => `'${tag}'`).join(', ')}],
parameters: [
{
name: 'param',
in: 'query',
required: false,
schema: { type: 'number' },
},
],${
['post', 'put', 'patch'].includes(method)
? `
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
},
},
},
},`
: ''
}
responses: {
200: {
description: 'Success',
content: {
'application/json': {
schema: {
type: 'object',
},
},
},
},
},
},
};
type HandlerDependencies = ${typesDeclaration || '{}'};
export default autoHandler(${name});
async function ${name}(${parametersDeclaration || '_'}: HandlerDependencies, {
param,${
['post', 'put'].includes(method)
? `
body,`
: ''
}
} : API.${APIHandlerName}.Input): Promise<API.${APIHandlerName}.Output> {
return {
status: 200,
headers: {},
body: { param },
};
}
`;
}
function buildServiceSource(
name: string,
parametersDeclaration: string,
typesDeclaration: string,
imports: string,
) {
const upperCamelizedName = name[0].toLocaleUpperCase() + name.slice(1);
return `import { autoService } from 'knifecycle';${imports}
export type ${upperCamelizedName}Service = {};
export type ${upperCamelizedName}Dependencies = ${typesDeclaration || '{}'};
export default autoService(init${upperCamelizedName});
async function init${upperCamelizedName}(${
parametersDeclaration || '_'
}: ${upperCamelizedName}Dependencies): Promise<${upperCamelizedName}Service> {
// Instantiate and return your service
return {};
}
`;
}
function buildProviderSource(
name: string,
parametersDeclaration: string,
typesDeclaration: string,
imports: string,
) {
const upperCamelizedName = name[0].toLocaleUpperCase() + name.slice(1);
return `import { autoProvider, Provider } from 'knifecycle';${imports}
export type ${upperCamelizedName}Service = {};
export type ${upperCamelizedName}Provider = Provider<${upperCamelizedName}Service>;
export type ${upperCamelizedName}Dependencies = ${typesDeclaration || '{}'};
export default autoProvider(init${upperCamelizedName});
async function init${upperCamelizedName}(${
parametersDeclaration || '_'
}: ${upperCamelizedName}Dependencies): Promise<${upperCamelizedName}Provider> {
// Instantiate and return your service
return {
service: {},
dispose: async () => {
// Do any action before the process shutdown
// (closing db connections... etc)
},
// You can also set a promise for unexpected errors
// that shutdown the app when it happens
// errorPromise: new Promise(),
};
}
`;
}
function buildCommandSource(
name: string,
description: string,
parametersDeclaration: string,
typesDeclaration: string,
imports: string,
) {
const upperCamelizedName = name[0].toLocaleUpperCase() + name.slice(1);
return `import { extra, autoService } from 'knifecycle';${imports}
export const definition: WhookCommandDefinition = {
description: '${description.replace(/'/g, "\\'")}',
example: \`whook ${name} --param "value"\`,
arguments: {
type: 'object',
additionalProperties: false,
required: ['param'],
properties: {
param: {
description: 'A parameter',
type: 'string',
default: 'A default value',
},
},
},
};
export default extra(definition, autoService(init${upperCamelizedName}Command));
async function init${upperCamelizedName}Command(${
parametersDeclaration || '_'
}: ${typesDeclaration || {}}): Promise<WhookCommandHandler> {
return async () => {
const { param } = readArgs(
definition.arguments,
await promptArgs(),
) as { param: string; };
// Implement your command here
}
}
`;
}
| {
"content_hash": "481afac356d4fabb7d29b1547e0caeff",
"timestamp": "",
"source": "github",
"line_count": 494,
"max_line_length": 95,
"avg_line_length": 25.149797570850204,
"alnum_prop": 0.5798454603992274,
"repo_name": "nfroidure/whook",
"id": "676b0faee22e3a19a0bf460204dd76a984658384",
"size": "12434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/whook-cli/src/commands/create.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "887"
},
{
"name": "TypeScript",
"bytes": "973685"
}
],
"symlink_target": ""
} |
package com.zfxf.douniu.view.fragment;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zfxf.douniu.R;
import com.zfxf.douniu.activity.askstock.ActivityAnswer;
import com.zfxf.douniu.activity.askstock.ActivityAnswerDetail;
import com.zfxf.douniu.activity.askstock.ActivityAskAdvisor;
import com.zfxf.douniu.activity.askstock.ActivityAskStock;
import com.zfxf.douniu.activity.pay.ActivityToPay;
import com.zfxf.douniu.activity.login.ActivityLogin;
import com.zfxf.douniu.adapter.recycleView.ZhenguAdvisorAdapter;
import com.zfxf.douniu.adapter.recycleView.ZhenguAnswerAdapter;
import com.zfxf.douniu.base.BaseFragment;
import com.zfxf.douniu.bean.AnswerListInfo;
import com.zfxf.douniu.bean.IndexResult;
import com.zfxf.douniu.internet.NewsInternetRequest;
import com.zfxf.douniu.utils.CommonUtils;
import com.zfxf.douniu.utils.Constants;
import com.zfxf.douniu.utils.SpTools;
import com.zfxf.douniu.view.FullyGridLayoutManager;
import com.zfxf.douniu.view.FullyLinearLayoutManager;
import com.zfxf.douniu.view.RecycleViewDivider;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* @author IMXU
* @time 2017/5/3 13:38
* @des 首席 微问答
* 邮箱:butterfly_xu@sina.com
*
*/
public class FragmentAdvisorAllAsking extends BaseFragment implements View.OnClickListener{
private View view;
@BindView(R.id.rl_zhengu_advisor_detail)
RelativeLayout advisor_detail;
@BindView(R.id.rl_zhengu_answer_detail)
RelativeLayout answer_detail;
@BindView(R.id.iv_zhengu_ask)
ImageView ask;
@BindView(R.id.tv_zhengu_text)
TextView text_advisor;
@BindView(R.id.tv_zhengu_answer)
TextView text_answer;
@BindView(R.id.tv_all_ask_refresh)
TextView text_refresh;
@BindView(R.id.rv_zhengu_advisor)
RecyclerView mAdvisorRecyclerView;//在线分析师recycleview
private LinearLayoutManager mAdvisorManager;
private ZhenguAdvisorAdapter mAdvisorAdapter;
@BindView(R.id.rv_zhengu_answer)
RecyclerView mAnswerRecyclerView;//精彩回答recycleview
private LinearLayoutManager mAnswerManager;
private ZhenguAnswerAdapter mAnswerAdapter;
private RecycleViewDivider mDivider;
private boolean isShow = false;
@Override
public View initView(LayoutInflater inflater) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_advisor_all_asking, null);
}
ViewGroup parent = (ViewGroup) view.getParent();
if(parent !=null){
parent.removeView(view);
}
ButterKnife.bind(this,view);
text_advisor.getPaint().setFakeBoldText(true);//加粗
text_answer.getPaint().setFakeBoldText(true);//加粗
return view;
}
@Override
public void init() {
super.init();
}
@Override
public void initdata() {
super.initdata();
if(!isShow){
isShow = true;
visitInternet();
}
}
private void visitInternet() {
CommonUtils.showProgressDialog(getActivity(),"加载中……");
NewsInternetRequest.getAnswerIndexInformation(new NewsInternetRequest.ForResultAnswerIndexListener() {
@Override
public void onResponseMessage(final IndexResult result) {
if(result == null){
text_refresh.setVisibility(View.VISIBLE);
CommonUtils.dismissProgressDialog();
return;
}
if(result.online_chief ==null){
CommonUtils.dismissProgressDialog();
return;
}
if(result.bright_answer ==null){
CommonUtils.dismissProgressDialog();
return;
}
if(result.online_chief.size() ==0 ){
CommonUtils.dismissProgressDialog();
return;
}
if(result.bright_answer.size() ==0 ){
CommonUtils.dismissProgressDialog();
return;
}
/**
* 在线首席
*/
if(mAdvisorManager == null){
mAdvisorManager = new FullyGridLayoutManager(getActivity(),2);
}
if(mAdvisorAdapter == null){
mAdvisorAdapter = new ZhenguAdvisorAdapter(getActivity(), result.online_chief);
}
mAdvisorRecyclerView.setLayoutManager(mAdvisorManager);
mAdvisorRecyclerView.setAdapter(mAdvisorAdapter);
mAdvisorAdapter.setOnItemClickListener(new ZhenguAdvisorAdapter.MyItemClickListener() {
@Override
public void onItemClick(View v, int positon) {
if(!SpTools.getBoolean(CommonUtils.getContext(), Constants.isLogin,false)){
Intent intent = new Intent(getActivity(), ActivityLogin.class);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(0,0);
return;
}
Intent intent = new Intent(CommonUtils.getContext(), ActivityAskStock.class);
intent.putExtra("name",result.online_chief.get(positon).ud_nickname);
intent.putExtra("fee",result.online_chief.get(positon).df_fee);
intent.putExtra("sx_id",result.online_chief.get(positon).sx_ub_id);
startActivity(intent);
getActivity().overridePendingTransition(0,0);
}
});
/**
* 精彩回答
*/
if(mAnswerManager == null){
mAnswerManager = new FullyLinearLayoutManager(getActivity());
}
if(mAnswerAdapter == null){
mAnswerAdapter = new ZhenguAnswerAdapter(getActivity(), result.bright_answer);
}
mAnswerRecyclerView.setLayoutManager(mAnswerManager);
mAnswerRecyclerView.setAdapter(mAnswerAdapter);
if(mDivider == null){
mDivider = new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL);
mAnswerRecyclerView.addItemDecoration(mDivider);
}
mAnswerAdapter.setOnItemClickListener(new ZhenguAnswerAdapter.MyItemClickListener() {
@Override
public void onItemClick(View v, int positon,AnswerListInfo bean) {
if(!SpTools.getBoolean(CommonUtils.getContext(), Constants.isLogin,false)){
Intent intent = new Intent(getActivity(), ActivityLogin.class);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(0,0);
return;
}
if (bean.zc_sfjf.equals("0")){
Intent intent = new Intent(CommonUtils.getContext(), ActivityToPay.class);
intent.putExtra("info","微问答,"+bean.sx_ub_id+","+bean.zc_id+",一元");
intent.putExtra("type","一元偷偷看");
intent.putExtra("count",bean.zc_fee);
intent.putExtra("sx_id",bean.sx_ub_id);
intent.putExtra("from",bean.ud_nickname);
intent.putExtra("planId",Integer.parseInt(bean.zc_id));
startActivity(intent);
getActivity().overridePendingTransition(0,0);
}else{
Intent intent = new Intent(CommonUtils.getContext(), ActivityAnswerDetail.class);
intent.putExtra("id",bean.zc_id);
startActivity(intent);
getActivity().overridePendingTransition(0,0);
}
}
});
text_refresh.setVisibility(View.GONE);
CommonUtils.dismissProgressDialog();
}
});
// if(mAdvisorAdapter == null & mAnswerAdapter==null){
// text_refresh.setVisibility(View.VISIBLE);
// }
}
@Override
public void initListener() {
super.initListener();
advisor_detail.setOnClickListener(this);
answer_detail.setOnClickListener(this);
ask.setOnClickListener(this);
text_refresh.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent;
switch (v.getId()){
case R.id.rl_zhengu_advisor_detail:
intent = new Intent(getActivity(), ActivityAskAdvisor.class);
startActivity(intent);
getActivity().overridePendingTransition(0,0);
break;
case R.id.rl_zhengu_answer_detail:
if(!SpTools.getBoolean(CommonUtils.getContext(), Constants.isLogin,false)){
intent = new Intent(getActivity(), ActivityLogin.class);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(0,0);
return;
}
intent = new Intent(getActivity(), ActivityAnswer.class);
startActivity(intent);
getActivity().overridePendingTransition(0,0);
break;
case R.id.iv_zhengu_ask:
if(!SpTools.getBoolean(CommonUtils.getContext(), Constants.isLogin,false)){
intent = new Intent(getActivity(), ActivityLogin.class);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(0,0);
return;
}
intent = new Intent(getActivity(), ActivityAskStock.class);
startActivity(intent);
getActivity().overridePendingTransition(0,0);
break;
case R.id.tv_all_ask_refresh:
text_refresh.setVisibility(View.GONE);
visitInternet();
break;
}
}
private void finishAll() {
mAdvisorManager = null;
mAdvisorAdapter = null;
}
@Override
public void onResume() {
super.onResume();
if(SpTools.getBoolean(getActivity(), Constants.buy,false)){
mAnswerAdapter = null;
visitInternet();
SpTools.setBoolean(getActivity(), Constants.buy,false);
final AlertDialog mDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //先得到构造器
mDialog = builder.create();
mDialog.show();
View view = View.inflate(getActivity(), R.layout.activity_pay_ok_dialog, null);
mDialog.getWindow().setContentView(view);
view.findViewById(R.id.tv_pay_ok_dialog_confirm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
if(SpTools.getBoolean(getActivity(), Constants.yiyuanbuy,false)){
mAnswerAdapter = null;
visitInternet();
SpTools.setBoolean(getActivity(), Constants.yiyuanbuy, false);
}
if(SpTools.getBoolean(getActivity(), Constants.read,false)){
mAnswerAdapter = null;
visitInternet();
SpTools.setBoolean(getActivity(), Constants.read,false);
}
if(SpTools.getBoolean(getActivity(), Constants.alreadyLogin,false)){
mAnswerAdapter = null;
visitInternet();
SpTools.setBoolean(getActivity(), Constants.alreadyLogin,false);
}
}
} | {
"content_hash": "90f1f89258522c4d630d8e73f4af2522",
"timestamp": "",
"source": "github",
"line_count": 294,
"max_line_length": 104,
"avg_line_length": 33.41836734693877,
"alnum_prop": 0.7262086513994911,
"repo_name": "chsimon99/myDouNiu",
"id": "a0ce4271abc7d552554039964dd2966ebda902ea",
"size": "9925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/zfxf/douniu/view/fragment/FragmentAdvisorAllAsking.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1951660"
}
],
"symlink_target": ""
} |
package s2
import (
"math"
"github.com/golang/geo/r2"
)
const EPSILON float64 = 1e-14
// Number of bits in the mantissa of a double.
const EXPONENT_SHIFT uint = 52
// Mask to extract the exponent from a double.
const EXPONENT_MASK uint64 = 0x7ff0000000000000
func min(a, b int) int {
if a > b {
return b
}
return a
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
func exp(v float64) int {
if v == 0 {
return 0
}
bits := math.Float64bits(v)
return (int)((EXPONENT_MASK&bits)>>EXPONENT_SHIFT) - 1022
}
/**
* Return the angle at the vertex B in the triangle ABC. The return value is
* always in the range [0, Pi]. The points do not need to be normalized.
* Ensures that Angle(a,b,c) == Angle(c,b,a) for all a,b,c.
*
* The angle is undefined if A or C is diametrically opposite from B, and
* becomes numerically unstable as the length of edge AB or BC approaches 180
* degrees.
*/
func angle(a, b, c Point) float64 {
return a.Cross(b.Vector).Angle(c.Cross(b.Vector)).Radians()
}
func approxEqualsNumber(a, b, maxError float64) bool {
return math.Abs(a-b) <= maxError
}
/**
* Return the area of triangle ABC. The method used is about twice as
* expensive as Girard's formula, but it is numerically stable for both large
* and very small triangles. The points do not need to be normalized. The area
* is always positive.
*
* The triangle area is undefined if it contains two antipodal points, and
* becomes numerically unstable as the length of any edge approaches 180
* degrees.
*/
func Area(a, b, c Point) float64 {
// This method is based on l'Huilier's theorem,
//
// tan(E/4) = sqrt(tan(s/2) tan((s-a)/2) tan((s-b)/2) tan((s-c)/2))
//
// where E is the spherical excess of the triangle (i.e. its area),
// a, b, c, are the side lengths, and
// s is the semiperimeter (a + b + c) / 2 .
//
// The only significant source of error using l'Huilier's method is the
// cancellation error of the terms (s-a), (s-b), (s-c). This leads to a
// *relative* error of about 1e-16 * s / min(s-a, s-b, s-c). This compares
// to a relative error of about 1e-15 / E using Girard's formula, where E is
// the true area of the triangle. Girard's formula can be even worse than
// this for very small triangles, e.g. a triangle with a true area of 1e-30
// might evaluate to 1e-5.
//
// So, we prefer l'Huilier's formula unless dmin < s * (0.1 * E), where
// dmin = min(s-a, s-b, s-c). This basically includes all triangles
// except for extremely long and skinny ones.
//
// Since we don't know E, we would like a conservative upper bound on
// the triangle area in terms of s and dmin. It's possible to show that
// E <= k1 * s * sqrt(s * dmin), where k1 = 2*sqrt(3)/Pi (about 1).
// Using this, it's easy to show that we should always use l'Huilier's
// method if dmin >= k2 * s^5, where k2 is about 1e-2. Furthermore,
// if dmin < k2 * s^5, the triangle area is at most k3 * s^4, where
// k3 is about 0.1. Since the best case error using Girard's formula
// is about 1e-15, this means that we shouldn't even consider it unless
// s >= 3e-4 or so.
// We use volatile doubles to force the compiler to truncate all of these
// quantities to 64 bits. Otherwise it may compute a value of dmin > 0
// simply because it chose to spill one of the intermediate values to
// memory but not one of the others.
sa := b.Angle(c.Vector).Radians()
sb := c.Angle(a.Vector).Radians()
sc := a.Angle(b.Vector).Radians()
s := 0.5 * (sa + sb + sc)
if s >= 3e-4 {
// Consider whether Girard's formula might be more accurate.
s2 := s * s
dmin := s - math.Max(sa, math.Max(sb, sc))
if dmin < 1e-2*s*s2*s2 {
// This triangle is skinny enough to consider Girard's formula.
area := GirardArea(a, b, c)
if dmin < s*(0.1*area) {
return area
}
}
}
// Use l'Huilier's formula.
return 4 * math.Atan(
math.Sqrt(
math.Max(0.0, math.Tan(0.5*s)*math.Tan(0.5*(s-sa))*math.Tan(0.5*(s-sb))*math.Tan(0.5*(s-sc)))))
}
/**
* Return the area of the triangle computed using Girard's formula. This is
* slightly faster than the Area() method above is not accurate for very small
* triangles.
*/
func GirardArea(a, b, c Point) float64 {
// This is equivalent to the usual Girard's formula but is slightly
// more accurate, faster to compute, and handles a == b == c without
// a special case.
ab := a.Cross(b.Vector)
bc := b.Cross(c.Vector)
ac := a.Cross(c.Vector)
return math.Max(0.0, ab.Angle(ac).Radians()-ab.Angle(bc).Radians()+bc.Angle(ac).Radians())
}
/**
* Like Area(), but returns a positive value for counterclockwise triangles
* and a negative value otherwise.
*/
func SignedArea(a, b, c Point) float64 {
return Area(a, b, c) * float64(RobustCCW(a, b, c))
}
// About centroids:
// ----------------
//
// There are several notions of the "centroid" of a triangle. First, there
// // is the planar centroid, which is simply the centroid of the ordinary
// (non-spherical) triangle defined by the three vertices. Second, there is
// the surface centroid, which is defined as the intersection of the three
// medians of the spherical triangle. It is possible to show that this
// point is simply the planar centroid projected to the surface of the
// sphere. Finally, there is the true centroid (mass centroid), which is
// defined as the area integral over the spherical triangle of (x,y,z)
// divided by the triangle area. This is the point that the triangle would
// rotate around if it was spinning in empty space.
//
// The best centroid for most purposes is the true centroid. Unlike the
// planar and surface centroids, the true centroid behaves linearly as
// regions are added or subtracted. That is, if you split a triangle into
// pieces and compute the average of their centroids (weighted by triangle
// area), the result equals the centroid of the original triangle. This is
// not true of the other centroids.
//
// Also note that the surface centroid may be nowhere near the intuitive
// "center" of a spherical triangle. For example, consider the triangle
// with vertices A=(1,eps,0), B=(0,0,1), C=(-1,eps,0) (a quarter-sphere).
// The surface centroid of this triangle is at S=(0, 2*eps, 1), which is
// within a distance of 2*eps of the vertex B. Note that the median from A
// (the segment connecting A to the midpoint of BC) passes through S, since
// this is the shortest path connecting the two endpoints. On the other
// hand, the true centroid is at M=(0, 0.5, 0.5), which when projected onto
// the surface is a much more reasonable interpretation of the "center" of
// this triangle.
/**
* Return the centroid of the planar triangle ABC. This can be normalized to
* unit length to obtain the "surface centroid" of the corresponding spherical
* triangle, i.e. the intersection of the three medians. However, note that
* for large spherical triangles the surface centroid may be nowhere near the
* intuitive "center" (see example above).
*/
func PlanarCentroid(a, b, c Point) Point {
return PointFromCoordsRaw((a.X+b.X+c.X)/3.0, (a.Y+b.Y+c.Y)/3.0, (a.Z+b.Z+c.Z)/3.0)
}
/**
* Returns the true centroid of the spherical triangle ABC multiplied by the
* signed area of spherical triangle ABC. The reasons for multiplying by the
* signed area are (1) this is the quantity that needs to be summed to compute
* the centroid of a union or difference of triangles, and (2) it's actually
* easier to calculate this way.
*/
func TrueCentroid(a, b, c Point) Point {
// I couldn't find any references for computing the true centroid of a
// spherical triangle... I have a truly marvellous demonstration of this
// formula which this margin is too narrow to contain :)
// assert (isUnitLength(a) && isUnitLength(b) && isUnitLength(c));
sina := b.Cross(c.Vector).Norm()
sinb := c.Cross(a.Vector).Norm()
sinc := a.Cross(b.Vector).Norm()
var ra float64 = 1
var rb float64 = 1
var rc float64 = 1
if sina != 0 {
ra = math.Asin(sina) / sina
}
if sinb != 0 {
rb = math.Asin(sinb) / sinb
}
if sinc != 0 {
rc = math.Asin(sinc) / sinc
}
// Now compute a point M such that M.X = rX * det(ABC) / 2 for X in A,B,C.
x := PointFromCoordsRaw(a.X, b.X, c.X)
y := PointFromCoordsRaw(a.Y, b.Y, c.Y)
z := PointFromCoordsRaw(a.Z, b.Z, c.Z)
r := PointFromCoordsRaw(ra, rb, rc)
return PointFromCoordsRaw(
0.5*y.Cross(z.Vector).Dot(r.Vector),
0.5*z.Cross(x.Vector).Dot(r.Vector),
0.5*x.Cross(y.Vector).Dot(r.Vector),
)
}
/**
* Return true if the points A, B, C are strictly counterclockwise. Return
* false if the points are clockwise or colinear (i.e. if they are all
* contained on some great circle).
*
* Due to numerical errors, situations may arise that are mathematically
* impossible, e.g. ABC may be considered strictly CCW while BCA is not.
* However, the implementation guarantees the following:
*
* If SimpleCCW(a,b,c), then !SimpleCCW(c,b,a) for all a,b,c.
*
* In other words, ABC and CBA are guaranteed not to be both CCW
*/
func simpleCCW(a, b, c Point) bool {
// We compute the signed volume of the parallelepiped ABC. The usual
// formula for this is (AxB).C, but we compute it here using (CxA).B
// in order to ensure that ABC and CBA are not both CCW. This follows
// from the following identities (which are true numerically, not just
// mathematically):
//
// (1) x.CrossProd(y) == -(y.CrossProd(x))
// (2) (-x).DotProd(y) == -(x.DotProd(y))
return c.Cross(a.Vector).Dot(b.Vector) > 0
}
/**
* WARNING! This requires arbitrary precision arithmetic to be truly robust.
* This means that for nearly colinear AB and AC, this function may return the
* wrong answer.
*
* <p>
* Like SimpleCCW(), but returns +1 if the points are counterclockwise and -1
* if the points are clockwise. It satisfies the following conditions:
*
* (1) RobustCCW(a,b,c) == 0 if and only if a == b, b == c, or c == a (2)
* RobustCCW(b,c,a) == RobustCCW(a,b,c) for all a,b,c (3) RobustCCW(c,b,a)
* ==-RobustCCW(a,b,c) for all a,b,c
*
* In other words:
*
* (1) The result is zero if and only if two points are the same. (2)
* Rotating the order of the arguments does not affect the result. (3)
* Exchanging any two arguments inverts the result.
*
* This function is essentially like taking the sign of the determinant of
* a,b,c, except that it has additional logic to make sure that the above
* properties hold even when the three points are coplanar, and to deal with
* the limitations of floating-point arithmetic.
*
* Note: a, b and c are expected to be of unit length. Otherwise, the results
* are undefined.
*/
func RobustCCW(a, b, c Point) int {
return RobustCCWWithCross(a, b, c, Point{a.Cross(b.Vector)})
}
/**
* A more efficient version of RobustCCW that allows the precomputed
* cross-product of A and B to be specified.
*
* Note: a, b and c are expected to be of unit length. Otherwise, the results
* are undefined
*/
func RobustCCWWithCross(a, b, c, aCrossB Point) int {
// assert (isUnitLength(a) && isUnitLength(b) && isUnitLength(c));
// There are 14 multiplications and additions to compute the determinant
// below. Since all three points are normalized, it is possible to show
// that the average rounding error per operation does not exceed 2**-54,
// the maximum rounding error for an operation whose result magnitude is in
// the range [0.5,1). Therefore, if the absolute value of the determinant
// is greater than 2*14*(2**-54), the determinant will have the same sign
// even if the arguments are rotated (which produces a mathematically
// equivalent result but with potentially different rounding errors).
kMinAbsValue := 1.6e-15 // 2 * 14 * 2**-54
det := aCrossB.Dot(c.Vector)
// Double-check borderline cases in debug mode.
// assert ((Math.abs(det) < kMinAbsValue) || (Math.abs(det) > 1000 * kMinAbsValue)
// || (det * expensiveCCW(a, b, c) > 0));
if det > kMinAbsValue {
return 1
}
if det < -kMinAbsValue {
return -1
}
return ExpensiveCCW(a, b, c)
}
/**
* A relatively expensive calculation invoked by RobustCCW() if the sign of
* the determinant is uncertain.
*/
func ExpensiveCCW(a, b, c Point) int {
// Return zero if and only if two points are the same. This ensures (1).
if a.Equals(b) || b.Equals(c) || c.Equals(a) {
return 0
}
// Now compute the determinant in a stable way. Since all three points are
// unit length and we know that the determinant is very close to zero, this
// means that points are very nearly colinear. Furthermore, the most common
// situation is where two points are nearly identical or nearly antipodal.
// To get the best accuracy in this situation, it is important to
// immediately reduce the magnitude of the arguments by computing either
// A+B or A-B for each pair of points. Note that even if A and B differ
// only in their low bits, A-B can be computed very accurately. On the
// other hand we can't accurately represent an arbitrary linear combination
// of two vectors as would be required for Gaussian elimination. The code
// below chooses the vertex opposite the longest edge as the "origin" for
// the calculation, and computes the different vectors to the other two
// vertices. This minimizes the sum of the lengths of these vectors.
//
// This implementation is very stable numerically, but it still does not
// return consistent results in all cases. For example, if three points are
// spaced far apart from each other along a great circle, the sign of the
// result will basically be random (although it will still satisfy the
// conditions documented in the header file). The only way to return
// consistent results in all cases is to compute the result using
// arbitrary-precision arithmetic. I considered using the Gnu MP library,
// but this would be very expensive (up to 2000 bits of precision may be
// needed to store the intermediate results) and seems like overkill for
// this problem. The MP library is apparently also quite particular about
// compilers and compilation options and would be a pain to maintain.
// We want to handle the case of nearby points and nearly antipodal points
// accurately, so determine whether A+B or A-B is smaller in each case.
var sab float64 = 1
var sbc float64 = 1
var sca float64 = 1
if a.Dot(b.Vector) > 0 {
sab = -1
}
if b.Dot(c.Vector) > 0 {
sbc = -1
}
if c.Dot(a.Vector) > 0 {
sca = -1
}
vab := a.Add(b.Mul(sab))
vbc := b.Add(c.Mul(sbc))
vca := c.Add(a.Mul(sca))
dab := vab.Norm2()
dbc := vbc.Norm2()
dca := vca.Norm2()
// Sort the difference vectors to find the longest edge, and use the
// opposite vertex as the origin. If two difference vectors are the same
// length, we break ties deterministically to ensure that the symmetry
// properties guaranteed in the header file will be true.
var sign float64
if dca < dbc || (dca == dbc && a.LessThan(b)) {
if dab < dbc || (dab == dbc && a.LessThan(c)) {
// The "sab" factor converts A +/- B into B +/- A.
sign = vab.Cross(vca).Dot(a.Vector) * sab // BC is longest
// edge
} else {
sign = vca.Cross(vbc).Dot(c.Vector) * sca // AB is longest
// edge
}
} else {
if dab < dca || (dab == dca && b.LessThan(c)) {
sign = vbc.Cross(vab).Dot(b.Vector) * sbc // CA is longest
// edge
} else {
sign = vca.Cross(vbc).Dot(c.Vector) * sca // AB is longest
// edge
}
}
if sign > 0 {
return 1
}
if sign < 0 {
return -1
}
// The points A, B, and C are numerically indistinguishable from coplanar.
// This may be due to roundoff error, or the points may in fact be exactly
// coplanar. We handle this situation by perturbing all of the points by a
// vector (eps, eps**2, eps**3) where "eps" is an infinitesmally small
// positive number (e.g. 1 divided by a googolplex). The perturbation is
// done symbolically, i.e. we compute what would happen if the points were
// perturbed by this amount. It turns out that this is equivalent to
// checking whether the points are ordered CCW around the origin first in
// the Y-Z plane, then in the Z-X plane, and then in the X-Y plane.
ccw := PlanarOrderedCCW(r2.Vector{a.Y, a.Z}, r2.Vector{b.Y, b.Z}, r2.Vector{c.Y, c.Z})
if ccw == 0 {
ccw = PlanarOrderedCCW(r2.Vector{a.Z, a.X}, r2.Vector{b.Z, b.X}, r2.Vector{c.Z, c.X})
if ccw == 0 {
ccw = PlanarOrderedCCW(
r2.Vector{a.X, a.Y}, r2.Vector{b.X, b.Y}, r2.Vector{c.X, c.Y})
// assert (ccw != 0);
}
}
return ccw
}
func PlanarCCW(a, b r2.Vector) int {
// Return +1 if the edge AB is CCW around the origin, etc.
var sab float64 = 1
if a.Dot(b) > 0 {
sab = -1
}
vab := a.Add(b.Mul(sab))
da := a.Norm2()
db := b.Norm2()
var sign float64
if da < db || (da == db && a.LessThan(b)) {
sign = a.Cross(vab) * sab
} else {
sign = vab.Cross(b)
}
if sign > 0 {
return 1
}
if sign < 0 {
return -1
}
return 0
}
func PlanarOrderedCCW(a, b, c r2.Vector) int {
sum := 0
sum += PlanarCCW(a, b)
sum += PlanarCCW(b, c)
sum += PlanarCCW(c, a)
if sum > 0 {
return 1
}
if sum < 0 {
return -1
}
return 0
}
/**
* Return true if the edges OA, OB, and OC are encountered in that order while
* sweeping CCW around the point O. You can think of this as testing whether
* A <= B <= C with respect to a continuous CCW ordering around O.
*
* Properties:
* <ol>
* <li>If orderedCCW(a,b,c,o) && orderedCCW(b,a,c,o), then a == b</li>
* <li>If orderedCCW(a,b,c,o) && orderedCCW(a,c,b,o), then b == c</li>
* <li>If orderedCCW(a,b,c,o) && orderedCCW(c,b,a,o), then a == b == c</li>
* <li>If a == b or b == c, then orderedCCW(a,b,c,o) is true</li>
* <li>Otherwise if a == c, then orderedCCW(a,b,c,o) is false</li>
* </ol>
*/
func OrderedCCW(a, b, c, o Point) bool {
// The last inequality below is ">" rather than ">=" so that we return true
// if A == B or B == C, and otherwise false if A == C. Recall that
// RobustCCW(x,y,z) == -RobustCCW(z,y,x) for all x,y,z.
sum := 0
if RobustCCW(b, o, a) >= 0 {
sum++
}
if RobustCCW(c, o, b) >= 0 {
sum++
}
if RobustCCW(a, o, c) > 0 {
sum++
}
return sum >= 2
}
// Defines an area or a length cell metric.
type Metric struct {
deriv float64
dim uint
}
// Defines a cell metric of the given dimension (1 == length, 2 == area).
func NewMetric(dim uint, deriv float64) Metric {
return Metric{deriv, dim}
}
// The "deriv" value of a metric is a derivative, and must be multiplied by
// a length or area in (s,t)-space to get a useful value.
func (m Metric) Deriv() float64 { return m.deriv }
// Return the value of a metric for cells at the given level.
func (m Metric) GetValue(level int) float64 {
return m.deriv * math.Pow(2, float64(int(m.dim)*(1-level)))
}
/**
* Return the level at which the metric has approximately the given value.
* For example, S2::kAvgEdge.GetClosestLevel(0.1) returns the level at which
* the average cell edge length is approximately 0.1. The return value is
* always a valid level.
*/
func (m Metric) getClosestLevel(value float64) int {
if m.dim == 1 {
return m.getMinLevel(math.Sqrt2 * value)
}
return m.getMinLevel(2 * value)
}
/**
* Return the minimum level such that the metric is at most the given value,
* or S2CellId::kMaxLevel if there is no such level. For example,
* S2::kMaxDiag.GetMinLevel(0.1) returns the minimum level such that all
* cell diagonal lengths are 0.1 or smaller. The return value is always a
* valid level.
*/
func (m Metric) getMinLevel(value float64) int {
if value <= 0 {
return MAX_LEVEL
}
// This code is equivalent to computing a floating-point "level"
// value and rounding up.
exponent := exp(value / (float64(int(1)<<m.dim) * m.deriv))
level := max(0, min(MAX_LEVEL, -((exponent-1)>>(m.dim-1))))
// assert (level == S2CellId.MAX_LEVEL || getValue(level) <= value);
// assert (level == 0 || getValue(level - 1) > value);
return level
}
/**
* Return the maximum level such that the metric is at least the given
* value, or zero if there is no such level. For example,
* S2.kMinWidth.GetMaxLevel(0.1) returns the maximum level such that all
* cells have a minimum width of 0.1 or larger. The return value is always a
* valid level.
*/
func (m Metric) getMaxLevel(value float64) int {
if value <= 0 {
return MAX_LEVEL
}
// This code is equivalent to computing a floating-point "level"
// value and rounding down.
exponent := exp(float64(int(1)<<m.dim) * m.deriv / value)
level := max(0, min(MAX_LEVEL, ((exponent-1)>>(m.dim-1))))
// assert (level == 0 || getValue(level) >= value);
// assert (level == S2CellId.MAX_LEVEL || getValue(level + 1) < value);
return level
}
| {
"content_hash": "8ea112ea6f9c0adfb2f9261c9b8ff526",
"timestamp": "",
"source": "github",
"line_count": 577,
"max_line_length": 98,
"avg_line_length": 35.705372616984405,
"alnum_prop": 0.6798369090379575,
"repo_name": "Logician/geo",
"id": "b023a571e29d68433173d112996722d1f2d4e18c",
"size": "20602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "s2/s2.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "352633"
}
],
"symlink_target": ""
} |
package lstring
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test_rotateString(t *testing.T) {
assert := assert.New(t)
assert.False(rotateString("abcde", "cdeab111"))
assert.True(rotateString("abcde", "bcdea"))
assert.True(rotateString("abcde", "cdeab"))
assert.False(rotateString("abcde", "abced"))
assert.True(rotateString("ckahkzpikz", "hkzpikzcka"))
}
| {
"content_hash": "a9713f69465b21a60cc2fb16807afe21",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 54,
"avg_line_length": 24.0625,
"alnum_prop": 0.7194805194805195,
"repo_name": "TTWShell/algorithms",
"id": "de9b8ad69c2bef5d11b26bf76657d31d44821a31",
"size": "385",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "leetcode/string/rotateString_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "943143"
},
{
"name": "Makefile",
"bytes": "368"
},
{
"name": "Shell",
"bytes": "421"
}
],
"symlink_target": ""
} |
import { useMemo, FC, Dispatch, SetStateAction, useCallback } from "react";
import { createEditor, Descendant } from "slate";
import { Slate, Editable, withReact } from "slate-react";
import { withHistory } from "slate-history";
import isHotkey from "is-hotkey";
import { EditorToolbar } from "./EditorToolbar";
import { SlateElement } from "./SlateElement";
import { HOTKEYS, SlateLeaf } from "./SlateLeaf";
import { toggleMark } from "./utils";
import styles from "./Editor.module.scss";
interface EditorProps {
content: Descendant[];
setContent: Dispatch<SetStateAction<Descendant[]>>;
}
const Editor: FC<EditorProps> = ({ content, setContent }) => {
const editor = useMemo(() => withHistory(withReact(createEditor())), []);
const renderElement = useCallback((props) => <SlateElement {...props} />, []);
const renderLeaf = useCallback((props) => <SlateLeaf {...props} />, []);
return (
<section className={styles.container}>
<Slate value={content} onChange={(newValue) => setContent(newValue)} editor={editor}>
<EditorToolbar />
<Editable
renderElement={renderElement}
renderLeaf={renderLeaf}
className={styles.editable}
spellCheck={false}
autoCorrect="false"
autoCapitalize="false"
onKeyDown={(event) => {
for (const hotkey in HOTKEYS) {
if (isHotkey(hotkey, event)) {
event.preventDefault();
const mark = HOTKEYS[hotkey];
toggleMark(editor, mark);
}
}
}}
/>
</Slate>
</section>
);
};
export default Editor;
| {
"content_hash": "5e4ca0d90b250e8b72d3fbf75c7e7f27",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 91,
"avg_line_length": 33.775510204081634,
"alnum_prop": 0.6120845921450151,
"repo_name": "matthewkeil/CODEified",
"id": "119391443c479ec8701b3b74507dfd3bdc7eafe0",
"size": "1655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/frontend/components/Editor/Editor.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "103464"
},
{
"name": "HTML",
"bytes": "259078"
},
{
"name": "Java",
"bytes": "14804"
},
{
"name": "JavaScript",
"bytes": "460267"
},
{
"name": "SCSS",
"bytes": "2189"
},
{
"name": "Solidity",
"bytes": "294229"
},
{
"name": "TypeScript",
"bytes": "86898"
}
],
"symlink_target": ""
} |
function initContentHeight(){
var win = $(window);
var header = $('.header');
var contentframe = $('.content-center');
var footer = $('.footer');
var out_height = win.height() - header.outerHeight(true) - footer.outerHeight(true) - 130;
contentframe.css('height', out_height);
}
function divresize(block, headerHeight, footerHeight) {
// var windowHeight = $(".wrapper").height(); //определяем высоту окна браузера
windowHeight = $(window).height();
$(block).css('height', windowHeight - headerHeight - footerHeight); //устанавливаем высоту блока(равно высоте окна за вычетом шапки и подвала)
}
function setTopPadding(){
var padding_main = $(".header").height() + 45;
$(".main").css('padding-top', padding_main);
}
function initHeights(){
//setTopPadding();
initContentHeight();
//divresize('.goal', 100, 118);
}
setInterval(initHeights, 300);
$(function(){
window.onresize = function(){
initContentHeight();
//divresize('.goal', 125, 118);
};
$('body').on('click', '.btn-chat', function(){
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).parent().animate({marginRight: "0"}, { duration: 200, queue: false });
$('#pop-up-chat').animate({marginRight: "0"}, { duration: 200, queue: false });
$(this).parent().find('#pop-up-chat').hide(50);
}
else
{
$(this).addClass('open');
$('#pop-up-chat').show();
$(this).parent().animate({marginRight: "166"}, { duration: 200, queue: false });
$('#pop-up-chat').animate({marginRight: "166"}, { duration: 200, queue: false });
$('.list-friends').css('height', $(window).height() - 282);
$(window).resize(function(){
$('.list-friends').css('height', $(window).height() - 282);
});
}
return false;
});
}); | {
"content_hash": "c7769c8c2a7228da792242ea1f7a4533",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 146,
"avg_line_length": 32.131147540983605,
"alnum_prop": 0.5571428571428572,
"repo_name": "mordarij/edela",
"id": "0e60461a58eb6317ba26935dfcb350ba310d01a5",
"size": "2049",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Acme/EdelaBundle/Resources/public/js/jquery/script.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2907"
},
{
"name": "CSS",
"bytes": "252417"
},
{
"name": "HTML",
"bytes": "231174"
},
{
"name": "JavaScript",
"bytes": "276756"
},
{
"name": "PHP",
"bytes": "700204"
},
{
"name": "Shell",
"bytes": "355"
}
],
"symlink_target": ""
} |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/containous/traefik/autogen"
"github.com/containous/traefik/safe"
"github.com/containous/traefik/types"
"github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/mux"
"github.com/thoas/stats"
"github.com/unrolled/render"
)
var metrics = stats.New()
// WebProvider is a provider.Provider implementation that provides the UI.
// FIXME to be handled another way.
type WebProvider struct {
Address string
CertFile, KeyFile string
ReadOnly bool
server *Server
}
var (
templatesRenderer = render.New(render.Options{
Directory: "nowhere",
})
)
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *WebProvider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error {
systemRouter := mux.NewRouter()
// health route
systemRouter.Methods("GET").Path("/health").HandlerFunc(provider.getHealthHandler)
// API routes
systemRouter.Methods("GET").Path("/api").HandlerFunc(provider.getConfigHandler)
systemRouter.Methods("GET").Path("/api/providers").HandlerFunc(provider.getConfigHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}").HandlerFunc(provider.getProviderHandler)
systemRouter.Methods("PUT").Path("/api/providers/{provider}").HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if provider.ReadOnly {
response.WriteHeader(http.StatusForbidden)
fmt.Fprintf(response, "REST API is in read-only mode")
return
}
vars := mux.Vars(request)
if vars["provider"] != "web" {
response.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(response, "Only 'web' provider can be updated through the REST API")
return
}
configuration := new(types.Configuration)
body, _ := ioutil.ReadAll(request.Body)
err := json.Unmarshal(body, configuration)
if err == nil {
configurationChan <- types.ConfigMessage{"web", configuration}
provider.getConfigHandler(response, request)
} else {
log.Errorf("Error parsing configuration %+v", err)
http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest)
}
})
systemRouter.Methods("GET").Path("/api/providers/{provider}/backends").HandlerFunc(provider.getBackendsHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/backends/{backend}").HandlerFunc(provider.getBackendHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/backends/{backend}/servers").HandlerFunc(provider.getServersHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/backends/{backend}/servers/{server}").HandlerFunc(provider.getServerHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/frontends").HandlerFunc(provider.getFrontendsHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}").HandlerFunc(provider.getFrontendHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}/routes").HandlerFunc(provider.getRoutesHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}/routes/{route}").HandlerFunc(provider.getRouteHandler)
// Expose dashboard
systemRouter.Methods("GET").Path("/").HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
http.Redirect(response, request, "/dashboard/", 302)
})
systemRouter.Methods("GET").PathPrefix("/dashboard/").Handler(http.StripPrefix("/dashboard/", http.FileServer(&assetfs.AssetFS{Asset: autogen.Asset, AssetDir: autogen.AssetDir, Prefix: "static"})))
go func() {
if len(provider.CertFile) > 0 && len(provider.KeyFile) > 0 {
err := http.ListenAndServeTLS(provider.Address, provider.CertFile, provider.KeyFile, systemRouter)
if err != nil {
log.Fatal("Error creating server: ", err)
}
} else {
err := http.ListenAndServe(provider.Address, systemRouter)
if err != nil {
log.Fatal("Error creating server: ", err)
}
}
}()
return nil
}
func (provider *WebProvider) getHealthHandler(response http.ResponseWriter, request *http.Request) {
templatesRenderer.JSON(response, http.StatusOK, metrics.Data())
}
func (provider *WebProvider) getConfigHandler(response http.ResponseWriter, request *http.Request) {
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
templatesRenderer.JSON(response, http.StatusOK, currentConfigurations)
}
func (provider *WebProvider) getProviderHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
templatesRenderer.JSON(response, http.StatusOK, provider)
} else {
http.NotFound(response, request)
}
}
func (provider *WebProvider) getBackendsHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
templatesRenderer.JSON(response, http.StatusOK, provider.Backends)
} else {
http.NotFound(response, request)
}
}
func (provider *WebProvider) getBackendHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
backendID := vars["backend"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
if backend, ok := provider.Backends[backendID]; ok {
templatesRenderer.JSON(response, http.StatusOK, backend)
return
}
}
http.NotFound(response, request)
}
func (provider *WebProvider) getServersHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
backendID := vars["backend"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
if backend, ok := provider.Backends[backendID]; ok {
templatesRenderer.JSON(response, http.StatusOK, backend.Servers)
return
}
}
http.NotFound(response, request)
}
func (provider *WebProvider) getServerHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
backendID := vars["backend"]
serverID := vars["server"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
if backend, ok := provider.Backends[backendID]; ok {
if server, ok := backend.Servers[serverID]; ok {
templatesRenderer.JSON(response, http.StatusOK, server)
return
}
}
}
http.NotFound(response, request)
}
func (provider *WebProvider) getFrontendsHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
templatesRenderer.JSON(response, http.StatusOK, provider.Frontends)
} else {
http.NotFound(response, request)
}
}
func (provider *WebProvider) getFrontendHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
frontendID := vars["frontend"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
if frontend, ok := provider.Frontends[frontendID]; ok {
templatesRenderer.JSON(response, http.StatusOK, frontend)
return
}
}
http.NotFound(response, request)
}
func (provider *WebProvider) getRoutesHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
frontendID := vars["frontend"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
if frontend, ok := provider.Frontends[frontendID]; ok {
templatesRenderer.JSON(response, http.StatusOK, frontend.Routes)
return
}
}
http.NotFound(response, request)
}
func (provider *WebProvider) getRouteHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
providerID := vars["provider"]
frontendID := vars["frontend"]
routeID := vars["route"]
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
if provider, ok := currentConfigurations[providerID]; ok {
if frontend, ok := provider.Frontends[frontendID]; ok {
if route, ok := frontend.Routes[routeID]; ok {
templatesRenderer.JSON(response, http.StatusOK, route)
return
}
}
}
http.NotFound(response, request)
}
| {
"content_hash": "858a820d3574566e1df5d0e35860a189",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 198,
"avg_line_length": 38.36909871244635,
"alnum_prop": 0.7479865771812081,
"repo_name": "goguardian/traefik",
"id": "445a83bce4176bf7187848a3da270e2e9d43af66",
"size": "8940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1431"
},
{
"name": "Go",
"bytes": "181026"
},
{
"name": "HTML",
"bytes": "7097"
},
{
"name": "JavaScript",
"bytes": "26102"
},
{
"name": "Makefile",
"bytes": "2461"
},
{
"name": "Shell",
"bytes": "10529"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_92) on Fri Apr 26 10:03:31 BST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.github.rvesse.airline.io.decorations.sources (Airline - IO Library 2.7.0 API)</title>
<meta name="date" content="2019-04-26">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../../../com/github/rvesse/airline/io/decorations/sources/package-summary.html" target="classFrame">com.github.rvesse.airline.io.decorations.sources</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AnsiDecorationSource.html" title="class in com.github.rvesse.airline.io.decorations.sources" target="classFrame">AnsiDecorationSource</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "7ac906f57d90e4bebf292809073b2c01",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 194,
"avg_line_length": 51.19047619047619,
"alnum_prop": 0.6744186046511628,
"repo_name": "rvesse/airline",
"id": "882a35a671d03b523c97d278694cace4cf6774e7",
"size": "1075",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/javadoc/2.7.0/airline-io/com/github/rvesse/airline/io/decorations/sources/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "91"
},
{
"name": "Java",
"bytes": "2176058"
},
{
"name": "Shell",
"bytes": "4550"
}
],
"symlink_target": ""
} |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = testEvents;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _parse = _interopRequireDefault(require("./cst/parse"));
var _Document = _interopRequireDefault(require("./Document"));
// test harness for yaml-test-suite event tests
function testEvents(src, options) {
var opt = Object.assign({
keepCstNodes: true,
keepNodeTypes: true,
version: '1.2'
}, options);
var docs = (0, _parse.default)(src).map(function (cstDoc) {
return new _Document.default(opt).parse(cstDoc);
});
var errDoc = docs.find(function (doc) {
return doc.errors.length > 0;
});
var error = errDoc ? errDoc.errors[0].message : null;
var events = ['+STR'];
try {
for (var i = 0; i < docs.length; ++i) {
var doc = docs[i];
var root = doc.contents;
if (Array.isArray(root)) root = root[0];
var _ref = doc.range || [0, 0],
_ref2 = (0, _slicedToArray2.default)(_ref, 2),
rootStart = _ref2[0],
rootEnd = _ref2[1];
var e = doc.errors[0] && doc.errors[0].source;
if (e && e.type === 'SEQ_ITEM') e = e.node;
if (e && (e.type === 'DOCUMENT' || e.range.start < rootStart)) throw new Error();
var docStart = '+DOC';
var pre = src.slice(0, rootStart);
var explicitDoc = /---\s*$/.test(pre);
if (explicitDoc) docStart += ' ---';else if (!doc.contents) continue;
events.push(docStart);
addEvents(events, doc, e, root);
if (doc.contents && doc.contents.length > 1) throw new Error();
var docEnd = '-DOC';
if (rootEnd) {
var post = src.slice(rootEnd);
if (/^\.\.\./.test(post)) docEnd += ' ...';
}
events.push(docEnd);
}
} catch (e) {
return {
events: events,
error: error || e
};
}
events.push('-STR');
return {
events: events,
error: error
};
}
function addEvents(events, doc, e, node) {
if (!node) {
events.push('=VAL :');
return;
}
if (e && node.cstNode === e) throw new Error();
var props = '';
var anchor = doc.anchors.getName(node);
if (anchor) {
if (/\d$/.test(anchor)) {
var alt = anchor.replace(/\d$/, '');
if (doc.anchors.getNode(alt)) anchor = alt;
}
props = " &".concat(anchor);
}
if (node.cstNode && node.cstNode.tag) {
var _node$cstNode$tag = node.cstNode.tag,
handle = _node$cstNode$tag.handle,
suffix = _node$cstNode$tag.suffix;
props += handle === '!' && !suffix ? ' <!>' : " <".concat(node.tag, ">");
}
var scalar = null;
switch (node.type) {
case 'ALIAS':
{
var alias = doc.anchors.getName(node.source);
if (/\d$/.test(alias)) {
var _alt = alias.replace(/\d$/, '');
if (doc.anchors.getNode(_alt)) alias = _alt;
}
events.push("=ALI".concat(props, " *").concat(alias));
}
break;
case 'BLOCK_FOLDED':
scalar = '>';
break;
case 'BLOCK_LITERAL':
scalar = '|';
break;
case 'PLAIN':
scalar = ':';
break;
case 'QUOTE_DOUBLE':
scalar = '"';
break;
case 'QUOTE_SINGLE':
scalar = "'";
break;
case 'PAIR':
events.push("+MAP".concat(props));
addEvents(events, doc, e, node.key);
addEvents(events, doc, e, node.value);
events.push('-MAP');
break;
case 'FLOW_SEQ':
case 'SEQ':
events.push("+SEQ".concat(props));
node.items.forEach(function (item) {
addEvents(events, doc, e, item);
});
events.push('-SEQ');
break;
case 'FLOW_MAP':
case 'MAP':
events.push("+MAP".concat(props));
node.items.forEach(function (_ref3) {
var key = _ref3.key,
value = _ref3.value;
addEvents(events, doc, e, key);
addEvents(events, doc, e, value);
});
events.push('-MAP');
break;
default:
throw new Error("Unexpected node type ".concat(node.type));
}
if (scalar) {
var value = node.cstNode.strValue.replace(/\\/g, '\\\\').replace(/\0/g, '\\0').replace(/\x07/g, '\\a').replace(/\x08/g, '\\b').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\v/g, '\\v').replace(/\f/g, '\\f').replace(/\r/g, '\\r').replace(/\x1b/g, '\\e');
events.push("=VAL".concat(props, " ").concat(scalar).concat(value));
}
} | {
"content_hash": "8bd5de4df57c7c5d712184007a58d02a",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 265,
"avg_line_length": 25.965714285714284,
"alnum_prop": 0.5459947183098591,
"repo_name": "jpoeng/jpoeng.github.io",
"id": "73c0c1b2be6609c442494f04de74f6a3c3a6ae8f",
"size": "4544",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/yaml/browser/dist/test-events.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5765"
},
{
"name": "HTML",
"bytes": "53947"
},
{
"name": "JavaScript",
"bytes": "1885"
},
{
"name": "PHP",
"bytes": "9773"
}
],
"symlink_target": ""
} |
package com.izettle.java;
import static com.izettle.java.CollectionUtils.partition;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.internal.util.collections.Sets;
public class CollectionUtilsSpec {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldPartition() {
Set<String> set = Sets.newSet("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11");
List<Collection<String>> partitions1 = partition(set, 1);
assertTrue(partitions1.size() == 11);
assertTrue(partitions1.get(0).size() == 1);
List<Collection<String>> partitions2 = partition(set, 7);
assertTrue(partitions2.size() == 2);
assertTrue(partitions2.get(0).size() == 7);
assertTrue(partitions2.get(1).size() == 4);
}
@Test
public void testPartition_badSize() {
Set<Integer> source = Sets.newSet(1);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Illegal partitionSize, was: 0");
partition(source, 0);
}
@Test
public void testPartition_empty() {
Set<Integer> source = Collections.emptySet();
List<Collection<Integer>> partitions = partition(source, 1);
assertTrue(partitions.isEmpty());
assertEquals(0, partitions.size());
}
@Test
public void testPartition_null() throws Exception {
List<Collection<Integer>> partitions = partition(null, 1);
assertNull(partitions);
}
@Test
public void testPartition_1_1() {
Set<Integer> source = Sets.newSet(1);
List<Collection<Integer>> partitions = partition(source, 1);
assertEquals(1, partitions.size());
assertEquals(Sets.newSet(1), partitions.get(0));
}
@Test
public void testPartition_1_2() {
Set<Integer> source = Sets.newSet(1);
List<Collection<Integer>> partitions = partition(source, 2);
assertEquals(1, partitions.size());
assertEquals(Sets.newSet(1), partitions.get(0));
}
@Test
public void testPartition_2_1() {
Set<Integer> source = Sets.newSet(1, 2);
List<Collection<Integer>> partitions = partition(source, 1);
assertEquals(2, partitions.size());
assertEquals(Sets.newSet(1), partitions.get(0));
assertEquals(Sets.newSet(2), partitions.get(1));
}
@Test
public void testPartition_3_2() {
Set<Integer> source = Sets.newSet(1, 2, 3);
List<Collection<Integer>> partitions = partition(source, 2);
assertEquals(2, partitions.size());
assertEquals(Sets.newSet(1, 2), partitions.get(0));
assertEquals(Sets.newSet(3), partitions.get(1));
}
@Test
public void testPartitionSize_1() {
Set<Integer> list = Sets.newSet(1, 2, 3);
assertEquals(1, partition(list, Integer.MAX_VALUE).size());
assertEquals(1, partition(list, Integer.MAX_VALUE - 1).size());
}
@Test
public void testPartitionSize_2_2() {
Set<Integer> list = Sets.newSet(1, 2, 3, 4);
assertEquals(2, partition(list, 2).get(0).size());
assertEquals(2, partition(list, 2).get(1).size());
}
@Test
public void itShouldPartitionCorrectCollectionClass() {
Collection<Integer> collection1 = new HashSet<>(Arrays.asList(6, 5, 4, 3));
//Just verify that the result is a set
List<Collection<Integer>> parts1 = partition(collection1, 2);
assertTrue(parts1.get(0) instanceof Set);
Collection<Integer> collection2 = new TreeSet<>(Arrays.asList(6, 5, 4, 3));
//Verify that the result is a set
List<Collection<Integer>> parts2 = partition(collection2, 2);
assertTrue(parts2.get(0) instanceof Set);
//Also verify that the natural ordering is respected
assertTrue(parts2.get(0).iterator().next() == 3);
assertTrue(parts2.get(1).iterator().next() == 5);
Collection<Integer> collection3 = new ArrayList<>(Arrays.asList(6, 5, 4, 3));
collection3.add(6);
collection3.add(5);
collection3.add(4);
collection3.add(3);
//Verify that the result is a list
List<Collection<Integer>> parts3 = partition(collection3, 2);
assertTrue(parts3.get(0) instanceof List);
//Also verify that the original ordering is respected
assertTrue(parts3.get(0).iterator().next() == 6);
assertTrue(parts3.get(1).iterator().next() == 4);
}
@Test
public void itShouldThrowExceptionForUnhandledCollectionType() {
Collection<Integer> collection = new PriorityQueue<>(Arrays.asList(6, 5, 4, 3));
thrown.expect(UnsupportedOperationException.class);
thrown.expectMessage("Not prepared for this type of collection: class java.util.PriorityQueue");
partition(collection, 2);
}
@Test
public void itShouldToStringProperly() {
Set<String> set = new TreeSet<>();
set.add("A");
set.add("B");
set.add("C");
assertEquals("A, B, C", CollectionUtils.toString(set));
}
@Test
public void itShouldToStringEmpty() {
Set<String> set = new TreeSet<>();
assertEquals("", CollectionUtils.toString(set));
}
@Test
public void itShouldToStringNull() {
assertNull(null, CollectionUtils.toString(null));
}
@Test
public void itShouldHandleNullElements() {
assertEquals(null, CollectionUtils.toString(Collections.singletonList(null)), "null");
}
}
| {
"content_hash": "2f4a74423d52608ce5191196514e2e30",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 104,
"avg_line_length": 35.218934911242606,
"alnum_prop": 0.6429771505376344,
"repo_name": "iZettle/izettle-toolbox",
"id": "0a04d44cb46e1bb459b92596497f5ea5d4ec6357",
"size": "5952",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "izettle-java/src/test/java/com/izettle/java/CollectionUtilsSpec.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "557171"
},
{
"name": "Kotlin",
"bytes": "5828"
}
],
"symlink_target": ""
} |
namespace std
{
namespace tr1
{
typedef short test_type;
template struct is_floating_point<test_type>;
}
}
| {
"content_hash": "1ff738fd6014e290a05d5a030a3d2cc9",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 49,
"avg_line_length": 15.125,
"alnum_prop": 0.6694214876033058,
"repo_name": "the-linix-project/linix-kernel-source",
"id": "0ca78b42762e8633f402ffd1aa6245922cdddaa7",
"size": "1054",
"binary": false,
"copies": "42",
"ref": "refs/heads/master",
"path": "gccsrc/gcc-4.7.2/libstdc++-v3/testsuite/tr1/4_metaprogramming/is_floating_point/requirements/explicit_instantiation.cc",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ada",
"bytes": "38139979"
},
{
"name": "Assembly",
"bytes": "3723477"
},
{
"name": "Awk",
"bytes": "83739"
},
{
"name": "C",
"bytes": "103607293"
},
{
"name": "C#",
"bytes": "55726"
},
{
"name": "C++",
"bytes": "38577421"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "32588"
},
{
"name": "Emacs Lisp",
"bytes": "13451"
},
{
"name": "FORTRAN",
"bytes": "4294984"
},
{
"name": "GAP",
"bytes": "13089"
},
{
"name": "Go",
"bytes": "11277335"
},
{
"name": "Haskell",
"bytes": "2415"
},
{
"name": "Java",
"bytes": "45298678"
},
{
"name": "JavaScript",
"bytes": "6265"
},
{
"name": "Matlab",
"bytes": "56"
},
{
"name": "OCaml",
"bytes": "148372"
},
{
"name": "Objective-C",
"bytes": "995127"
},
{
"name": "Objective-C++",
"bytes": "436045"
},
{
"name": "PHP",
"bytes": "12361"
},
{
"name": "Pascal",
"bytes": "40318"
},
{
"name": "Perl",
"bytes": "358808"
},
{
"name": "Python",
"bytes": "60178"
},
{
"name": "SAS",
"bytes": "1711"
},
{
"name": "Scilab",
"bytes": "258457"
},
{
"name": "Shell",
"bytes": "2610907"
},
{
"name": "Tcl",
"bytes": "17983"
},
{
"name": "TeX",
"bytes": "1455571"
},
{
"name": "XSLT",
"bytes": "156419"
}
],
"symlink_target": ""
} |
require "spec_helper"
require "hamster/tuple"
describe Hamster::Tuple do
describe "#first" do
before do
@tuple = Hamster::Tuple.new("A", "B")
end
it "returns the first value" do
@tuple.first.should == "A"
end
end
end | {
"content_hash": "4175d42b3b6362b912ebd18f89958e7c",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 43,
"avg_line_length": 17.857142857142858,
"alnum_prop": 0.624,
"repo_name": "alexdowad/hamster",
"id": "b8e6a7a723b24a5efd19943d0915743581b21c64",
"size": "250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/hamster/tuple/first_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "274953"
}
],
"symlink_target": ""
} |
ROOT = process.cwd()
var config = require(ROOT+'/config.json');
console.log("logs go to: "+ROOT+config.log_path);
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: ROOT+config.log_path+'debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: ROOT+config.log_path+'exceptions.log', json: false })
],
exitOnError: false
});
module.exports = logger;
/*
var winston = require('winston');
module.exports = function (module) {
var filename = module.id;
return {
info : function (msg, vars) {
winston.info(filename + ': ' + msg, vars);
}
}
};
*/ | {
"content_hash": "46dc0c519fa90c7366d0c44d9e838eda",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 97,
"avg_line_length": 22.72972972972973,
"alnum_prop": 0.6492271105826397,
"repo_name": "nikkis/OrchestratorJS",
"id": "f41ee2776237867acaf63c6793d744ade48c2288",
"size": "841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "orchestratorjs/logs/log.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "284454"
},
{
"name": "HTML",
"bytes": "419580"
},
{
"name": "JavaScript",
"bytes": "1131173"
},
{
"name": "PHP",
"bytes": "15326"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.daef.controllers;
import com.daef.models.Post;
import com.daef.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author abj
*/
@RestController
public class PostSimulatorController {
@Autowired
private PostRepository repository;
@RequestMapping(value = "/post", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> createPost(@RequestBody Post post) {
repository.save(post);
return new ResponseEntity<>(post, HttpStatus.OK);
}
}
| {
"content_hash": "614ea7eb214d79d2a4948c356006b40c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 115,
"avg_line_length": 31.78048780487805,
"alnum_prop": 0.7743668457405987,
"repo_name": "gode-ting/hackernews-clone-backend",
"id": "54611341810f0c9ec130d93a15286729c9a913e2",
"size": "1303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/daef/controllers/PostSimulatorController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5036"
},
{
"name": "CSS",
"bytes": "6654"
},
{
"name": "HTML",
"bytes": "43520"
},
{
"name": "Java",
"bytes": "47935"
},
{
"name": "JavaScript",
"bytes": "38006"
},
{
"name": "Shell",
"bytes": "6860"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hive.ql.udf.generic;
import java.text.DecimalFormat;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.DoubleObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.FloatObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;
/**
* Generic UDF for format_number function
* <code>FORMAT_NUMBER(X, D or F)</code>.
* This is supposed to function like MySQL's FORMAT,
* http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#
* function_format
*
* @see org.apache.hadoop.hive.ql.udf.generic.GenericUDF
*/
@Description(name = "format_number",
value = "_FUNC_(X, D or F) - Formats the number X to "
+ "a format like '#,###,###.##', rounded to D decimal places, Or"
+ " Uses the format specified F to format,"
+ " and returns the result as a string. If D is 0, the result"
+ " has no decimal point or fractional part."
+ " This is supposed to function like MySQL's FORMAT",
extended = "Example:\n"
+ " > SELECT _FUNC_(12332.123456, 4) FROM src LIMIT 1;\n"
+ " '12,332.1235'\n"
+ " > SELECT _FUNC_(12332.123456, '##################.###') FROM"
+ " src LIMIT 1;\n"
+ " '12332.123'")
public class GenericUDFFormatNumber extends GenericUDF {
private transient ObjectInspector[] argumentOIs;
private transient final Text resultText = new Text();
private transient final StringBuilder pattern = new StringBuilder("");
private transient final DecimalFormat numberFormat = new DecimalFormat("");
private transient int lastDValue = -1;
private transient PrimitiveCategory dType;
@Override
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
if (arguments.length != 2) {
throw new UDFArgumentLengthException(
"The function FORMAT_NUMBER(X, D or F) needs two arguments.");
}
switch (arguments[0].getCategory()) {
case PRIMITIVE:
break;
default:
throw new UDFArgumentTypeException(0, "Argument 1"
+ " of function FORMAT_NUMBER must be \""
+ serdeConstants.TINYINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.SMALLINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.INT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.BIGINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.DOUBLE_TYPE_NAME + "\""
+ " or \"" + serdeConstants.FLOAT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.DECIMAL_TYPE_NAME + "\", but \""
+ arguments[0].getTypeName() + "\" was found.");
}
switch (arguments[1].getCategory()) {
case PRIMITIVE:
break;
default:
throw new UDFArgumentTypeException(1, "Argument 2"
+ " of function FORMAT_NUMBER must be \""
+ serdeConstants.TINYINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.SMALLINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.INT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.BIGINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.STRING_TYPE_NAME + "\", but \""
+ arguments[1].getTypeName() + "\" was found.");
}
PrimitiveObjectInspector xObjectInspector = (PrimitiveObjectInspector)arguments[0];
PrimitiveObjectInspector dObjectInspector = (PrimitiveObjectInspector)arguments[1];
switch (xObjectInspector.getPrimitiveCategory()) {
case VOID:
case BYTE:
case SHORT:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
case DECIMAL:
break;
default:
throw new UDFArgumentTypeException(0, "Argument 1"
+ " of function FORMAT_NUMBER must be \""
+ serdeConstants.TINYINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.SMALLINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.INT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.BIGINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.DOUBLE_TYPE_NAME + "\""
+ " or \"" + serdeConstants.FLOAT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.DECIMAL_TYPE_NAME + "\", but \""
+ arguments[0].getTypeName() + "\" was found.");
}
dType = dObjectInspector.getPrimitiveCategory();
switch (dType) {
case VOID:
case BYTE:
case SHORT:
case INT:
case LONG:
break;
case STRING:
if (!(arguments[1] instanceof ConstantObjectInspector)) {
throw new UDFArgumentTypeException(1, "Format string passed must be a constant STRING." + arguments[1]
.toString());
}
ConstantObjectInspector constantOI = (ConstantObjectInspector)arguments[1];
String fValue = constantOI.getWritableConstantValue().toString();
DecimalFormat dFormat = new DecimalFormat(fValue);
numberFormat.applyPattern(dFormat.toPattern());
break;
default:
throw new UDFArgumentTypeException(1, "Argument 2"
+ " of function FORMAT_NUMBER must be \""
+ serdeConstants.TINYINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.SMALLINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.INT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.BIGINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.STRING_TYPE_NAME + "\", but \""
+ arguments[1].getTypeName() + "\" was found.");
}
argumentOIs = arguments;
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
}
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
Object arg0;
Object arg1;
if ((arg0 = arguments[0].get()) == null || (arg1 = arguments[1].get()) == null) {
return null;
}
if (!dType.equals(PrimitiveCategory.STRING)) {
int dValue = ((IntObjectInspector) argumentOIs[1]).get(arg1);
if (dValue < 0) {
throw new HiveException("Argument 2 of function FORMAT_NUMBER must be >= 0, but \""
+ dValue + "\" was found");
}
if (dValue != lastDValue) {
// construct a new DecimalFormat only if a new dValue
pattern.delete(0, pattern.length());
pattern.append("#,###,###,###,###,###,##0");
//decimal place
if (dValue > 0) {
pattern.append(".");
for (int i = 0; i < dValue; i++) {
pattern.append("0");
}
}
DecimalFormat dFormat = new DecimalFormat(pattern.toString());
lastDValue = dValue;
numberFormat.applyPattern(dFormat.toPattern());
}
}
double xDoubleValue = 0.0;
float xFloatValue = 0.0f;
HiveDecimal xDecimalValue = null;
int xIntValue = 0;
long xLongValue = 0L;
PrimitiveObjectInspector xObjectInspector = (PrimitiveObjectInspector)argumentOIs[0];
switch (xObjectInspector.getPrimitiveCategory()) {
case VOID:
case DOUBLE:
xDoubleValue = ((DoubleObjectInspector) argumentOIs[0]).get(arg0);
resultText.set(numberFormat.format(xDoubleValue));
break;
case FLOAT:
xFloatValue = ((FloatObjectInspector) argumentOIs[0]).get(arg0);
resultText.set(numberFormat.format(xFloatValue));
break;
case DECIMAL:
xDecimalValue = ((HiveDecimalObjectInspector) argumentOIs[0])
.getPrimitiveJavaObject(arg0);
resultText.set(numberFormat.format(xDecimalValue.bigDecimalValue()));
break;
case BYTE:
case SHORT:
case INT:
xIntValue = ((IntObjectInspector) argumentOIs[0]).get(arg0);
resultText.set(numberFormat.format(xIntValue));
break;
case LONG:
xLongValue = ((LongObjectInspector) argumentOIs[0]).get(arg0);
resultText.set(numberFormat.format(xLongValue));
break;
default:
throw new HiveException("Argument 1 of function FORMAT_NUMBER must be "
+ serdeConstants.TINYINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.SMALLINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.INT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.BIGINT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.DOUBLE_TYPE_NAME + "\""
+ " or \"" + serdeConstants.FLOAT_TYPE_NAME + "\""
+ " or \"" + serdeConstants.DECIMAL_TYPE_NAME + "\", but \""
+ argumentOIs[0].getTypeName() + "\" was found.");
}
return resultText;
}
@Override
public String getDisplayString(String[] children) {
assert (children.length == 2);
return getStandardDisplayString("format_number", children);
}
}
| {
"content_hash": "121463650091ab93f311511cd5102554",
"timestamp": "",
"source": "github",
"line_count": 240,
"max_line_length": 112,
"avg_line_length": 40.12083333333333,
"alnum_prop": 0.635268459860837,
"repo_name": "vergilchiu/hive",
"id": "ed03b395ece0d027c703a67f9602e6cee0e81ea8",
"size": "10435",
"binary": false,
"copies": "2",
"ref": "refs/heads/branch-2.3-htdc",
"path": "ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFFormatNumber.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "54494"
},
{
"name": "Batchfile",
"bytes": "845"
},
{
"name": "C",
"bytes": "28218"
},
{
"name": "C++",
"bytes": "76808"
},
{
"name": "CSS",
"bytes": "4263"
},
{
"name": "GAP",
"bytes": "155326"
},
{
"name": "HTML",
"bytes": "50822"
},
{
"name": "Java",
"bytes": "39751326"
},
{
"name": "JavaScript",
"bytes": "25851"
},
{
"name": "M4",
"bytes": "2276"
},
{
"name": "PHP",
"bytes": "148097"
},
{
"name": "PLSQL",
"bytes": "8797"
},
{
"name": "PLpgSQL",
"bytes": "339745"
},
{
"name": "Perl",
"bytes": "319842"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Protocol Buffer",
"bytes": "8769"
},
{
"name": "Python",
"bytes": "386664"
},
{
"name": "Roff",
"bytes": "5379"
},
{
"name": "SQLPL",
"bytes": "20290"
},
{
"name": "Shell",
"bytes": "313510"
},
{
"name": "Thrift",
"bytes": "107584"
},
{
"name": "XSLT",
"bytes": "7619"
}
],
"symlink_target": ""
} |
var t = db.max_time_ms;
var exceededTimeLimit = 50; // ErrorCodes::ExceededTimeLimit
var cursor;
var res;
//
// Simple positive test for query: a ~300ms query with a 100ms time limit should be aborted.
//
t.drop();
t.insert([{}, {}, {}]);
cursor = t.find({
$where: function() {
sleep(100);
return true;
}
});
cursor.maxTimeMS(100);
assert.throws(function() {
cursor.itcount();
}, [], "expected query to abort due to time limit");
//
// Simple negative test for query: a ~300ms query with a 10s time limit should not hit the time
// limit.
//
t.drop();
t.insert([{}, {}, {}]);
cursor = t.find({
$where: function() {
sleep(100);
return true;
}
});
cursor.maxTimeMS(10 * 1000);
assert.doesNotThrow(function() {
cursor.itcount();
}, [], "expected query to not hit the time limit");
//
// Simple positive test for getmore:
// - Issue a find() that returns 2 batches: a fast batch, then a slow batch.
// - The find() has a 1-second time limit; the first batch should run "instantly", but the second
// batch takes ~15 seconds, so the getmore should be aborted.
//
t.drop();
t.insert([{}, {}, {}]); // fast batch
t.insert([{slow: true}, {slow: true}, {slow: true}]); // slow batch
cursor = t.find({
$where: function() {
if (this.slow) {
sleep(5 * 1000);
}
return true;
}
});
cursor.batchSize(3);
cursor.maxTimeMS(1000);
assert.doesNotThrow(function() {
cursor.next();
cursor.next();
cursor.next();
}, [], "expected batch 1 (query) to not hit the time limit");
assert.throws(function() {
cursor.next();
cursor.next();
cursor.next();
}, [], "expected batch 2 (getmore) to abort due to time limit");
//
// Simple negative test for getmore:
// - Issue a find() that returns 2 batches: a fast batch, then a slow batch.
// - The find() has a 10-second time limit; the first batch should run "instantly", and the second
// batch takes only ~2 seconds, so both the query and getmore should not hit the time limit.
//
t.drop();
t.insert([{}, {}, {}]); // fast batch
t.insert([{}, {}, {slow: true}]); // slow batch
cursor = t.find({
$where: function() {
if (this.slow) {
sleep(2 * 1000);
}
return true;
}
});
cursor.batchSize(3);
cursor.maxTimeMS(10 * 1000);
assert.doesNotThrow(function() {
cursor.next();
cursor.next();
cursor.next();
}, [], "expected batch 1 (query) to not hit the time limit");
assert.doesNotThrow(function() {
cursor.next();
cursor.next();
cursor.next();
}, [], "expected batch 2 (getmore) to not hit the time limit");
//
// Many-batch positive test for getmore:
// - Issue a many-batch find() with a 6-second time limit where the results take 10 seconds to
// generate; one of the later getmore ops should be aborted.
//
t.drop();
for (var i = 0; i < 5; i++) {
t.insert([{}, {}, {slow: true}]);
}
cursor = t.find({
$where: function() {
if (this.slow) {
sleep(2 * 1000);
}
return true;
}
});
cursor.batchSize(3);
cursor.maxTimeMS(6 * 1000);
assert.throws(function() {
cursor.itcount();
}, [], "expected find() to abort due to time limit");
//
// Many-batch negative test for getmore:
// - Issue a many-batch find() with a 20-second time limit where the results take 10 seconds to
// generate; the find() should not hit the time limit.
//
t.drop();
for (var i = 0; i < 5; i++) {
t.insert([{}, {}, {slow: true}]);
}
cursor = t.find({
$where: function() {
if (this.slow) {
sleep(2 * 1000);
}
return true;
}
});
cursor.batchSize(3);
cursor.maxTimeMS(20 * 1000);
assert.doesNotThrow(function() {
cursor.itcount();
}, [], "expected find() to not hit the time limit");
//
// Simple positive test for commands: a ~300ms command with a 100ms time limit should be aborted.
//
t.drop();
res = t.getDB().adminCommand({sleep: 1, millis: 300, maxTimeMS: 100});
assert(res.ok == 0 && res.code == exceededTimeLimit,
"expected sleep command to abort due to time limit, ok=" + res.ok + ", code=" + res.code);
//
// Simple negative test for commands: a ~300ms command with a 10s time limit should not hit the
// time limit.
//
t.drop();
res = t.getDB().adminCommand({sleep: 1, millis: 300, maxTimeMS: 10 * 1000});
assert(res.ok == 1,
"expected sleep command to not hit the time limit, ok=" + res.ok + ", code=" + res.code);
//
// Tests for input validation.
//
t.drop();
t.insert({});
// Verify lower boundary for acceptable input (0 is acceptable, 1 isn't).
assert.doesNotThrow.automsg(function() {
t.find().maxTimeMS(0).itcount();
});
assert.doesNotThrow.automsg(function() {
t.find().maxTimeMS(NumberInt(0)).itcount();
});
assert.doesNotThrow.automsg(function() {
t.find().maxTimeMS(NumberLong(0)).itcount();
});
assert.eq(1, t.getDB().runCommand({ping: 1, maxTimeMS: 0}).ok);
assert.eq(1, t.getDB().runCommand({ping: 1, maxTimeMS: NumberInt(0)}).ok);
assert.eq(1, t.getDB().runCommand({ping: 1, maxTimeMS: NumberLong(0)}).ok);
assert.throws.automsg(function() {
t.find().maxTimeMS(-1).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS(NumberInt(-1)).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS(NumberLong(-1)).itcount();
});
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: -1}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: NumberInt(-1)}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: NumberLong(-1)}).ok);
// Verify upper boundary for acceptable input (2^31-1 is acceptable, 2^31 isn't).
var maxValue = Math.pow(2, 31) - 1;
assert.doesNotThrow.automsg(function() {
t.find().maxTimeMS(maxValue).itcount();
});
assert.doesNotThrow.automsg(function() {
t.find().maxTimeMS(NumberInt(maxValue)).itcount();
});
assert.doesNotThrow.automsg(function() {
t.find().maxTimeMS(NumberLong(maxValue)).itcount();
});
assert.eq(1, t.getDB().runCommand({ping: 1, maxTimeMS: maxValue}).ok);
assert.eq(1, t.getDB().runCommand({ping: 1, maxTimeMS: NumberInt(maxValue)}).ok);
assert.eq(1, t.getDB().runCommand({ping: 1, maxTimeMS: NumberLong(maxValue)}).ok);
assert.throws.automsg(function() {
t.find().maxTimeMS(maxValue + 1).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS(NumberInt(maxValue + 1)).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS(NumberLong(maxValue + 1)).itcount();
});
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: maxValue + 1}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: NumberInt(maxValue + 1)}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: NumberLong(maxValue + 1)}).ok);
// Verify invalid values are rejected.
assert.throws.automsg(function() {
t.find().maxTimeMS(0.1).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS(-0.1).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS().itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS("").itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS(true).itcount();
});
assert.throws.automsg(function() {
t.find().maxTimeMS({}).itcount();
});
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: 0.1}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: -0.1}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: undefined}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: ""}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: true}).ok);
assert.eq(0, t.getDB().runCommand({ping: 1, maxTimeMS: {}}).ok);
// Verify that the maxTimeMS command argument can be sent with $query-wrapped commands.
cursor = t.getDB().$cmd.find({ping: 1, maxTimeMS: 0}).limit(-1);
cursor._ensureSpecial();
assert.eq(1, cursor.next().ok);
// Verify that the server rejects invalid command argument $maxTimeMS.
cursor = t.getDB().$cmd.find({ping: 1, $maxTimeMS: 0}).limit(-1);
cursor._ensureSpecial();
assert.eq(0, cursor.next().ok);
// Verify that the $maxTimeMS query option can't be sent with $query-wrapped commands.
// the shell will throw here as it will validate itself when sending the command.
// The server uses the same logic.
// TODO: rewrite to use runCommandWithMetadata when we have a shell helper so that
// we can test server side validation.
assert.throws(function() {
cursor = t.getDB().$cmd.find({ping: 1}).limit(-1).maxTimeMS(0);
cursor._ensureSpecial();
cursor.next();
});
//
// Tests for fail points maxTimeAlwaysTimeOut and maxTimeNeverTimeOut.
//
// maxTimeAlwaysTimeOut positive test for command.
t.drop();
assert.eq(
1, t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "alwaysOn"}).ok);
res = t.getDB().runCommand({ping: 1, maxTimeMS: 10 * 1000});
assert(res.ok == 0 && res.code == exceededTimeLimit,
"expected command to trigger maxTimeAlwaysTimeOut fail point, ok=" + res.ok + ", code=" +
res.code);
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "off"}).ok);
// maxTimeNeverTimeOut positive test for command.
t.drop();
assert.eq(1,
t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "alwaysOn"}).ok);
res = t.getDB().adminCommand({sleep: 1, millis: 300, maxTimeMS: 100});
assert(res.ok == 1,
"expected command to trigger maxTimeNeverTimeOut fail point, ok=" + res.ok + ", code=" +
res.code);
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "off"}).ok);
// maxTimeAlwaysTimeOut positive test for query.
t.drop();
assert.eq(
1, t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "alwaysOn"}).ok);
assert.throws(function() {
t.find().maxTimeMS(10 * 1000).itcount();
}, [], "expected query to trigger maxTimeAlwaysTimeOut fail point");
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "off"}).ok);
// maxTimeNeverTimeOut positive test for query.
assert.eq(1,
t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "alwaysOn"}).ok);
t.drop();
t.insert([{}, {}, {}]);
cursor = t.find({
$where: function() {
sleep(100);
return true;
}
});
cursor.maxTimeMS(100);
assert.doesNotThrow(function() {
cursor.itcount();
}, [], "expected query to trigger maxTimeNeverTimeOut fail point");
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "off"}).ok);
// maxTimeAlwaysTimeOut positive test for getmore.
t.drop();
t.insert([{}, {}, {}]);
cursor = t.find().maxTimeMS(10 * 1000).batchSize(2);
assert.doesNotThrow.automsg(function() {
cursor.next();
cursor.next();
});
assert.eq(
1, t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "alwaysOn"}).ok);
assert.throws(function() {
cursor.next();
}, [], "expected getmore to trigger maxTimeAlwaysTimeOut fail point");
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "off"}).ok);
// maxTimeNeverTimeOut positive test for getmore.
t.drop();
t.insert([{}, {}, {}]); // fast batch
t.insert([{slow: true}, {slow: true}, {slow: true}]); // slow batch
cursor = t.find({
$where: function() {
if (this.slow) {
sleep(2 * 1000);
}
return true;
}
});
cursor.batchSize(3);
cursor.maxTimeMS(2 * 1000);
assert.doesNotThrow(function() {
cursor.next();
cursor.next();
cursor.next();
}, [], "expected batch 1 (query) to not hit the time limit");
assert.eq(1,
t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "alwaysOn"}).ok);
assert.doesNotThrow(function() {
cursor.next();
cursor.next();
cursor.next();
}, [], "expected batch 2 (getmore) to trigger maxTimeNeverTimeOut fail point");
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "off"}).ok);
//
// Test that maxTimeMS is accepted by commands that have an option whitelist.
//
// "aggregate" command.
res = t.runCommand("aggregate", {pipeline: [], cursor: {}, maxTimeMS: 60 * 1000});
assert(res.ok == 1,
"expected aggregate with maxtime to succeed, ok=" + res.ok + ", code=" + res.code);
// "collMod" command.
res = t.runCommand("collMod", {usePowerOf2Sizes: true, maxTimeMS: 60 * 1000});
assert(res.ok == 1,
"expected collmod with maxtime to succeed, ok=" + res.ok + ", code=" + res.code);
//
// Test maxTimeMS for parallelCollectionScan
//
res = t.runCommand({parallelCollectionScan: t.getName(), numCursors: 1, maxTimeMS: 60 * 1000});
assert.commandWorked(res);
var cursor = new DBCommandCursor(t.getDB().getMongo(), res.cursors[0], 5);
assert.commandWorked(
t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "alwaysOn"}));
assert.throws(function() {
cursor.itcount();
}, [], "expected query to abort due to time limit");
assert.commandWorked(
t.getDB().adminCommand({configureFailPoint: "maxTimeAlwaysTimeOut", mode: "off"}));
//
// test count shell helper SERVER-13334
//
t.drop();
assert.eq(1,
t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "alwaysOn"}).ok);
assert.doesNotThrow(function() {
t.find({}).maxTimeMS(1).count();
});
assert.eq(1, t.getDB().adminCommand({configureFailPoint: "maxTimeNeverTimeOut", mode: "off"}).ok);
| {
"content_hash": "3954ef1321171289f9d8048cec0a1cc6",
"timestamp": "",
"source": "github",
"line_count": 412,
"max_line_length": 100,
"avg_line_length": 32.69660194174757,
"alnum_prop": 0.649691930814342,
"repo_name": "christkv/mongo-shell",
"id": "471e84690b8c399d8f26f8da9a30274ea4c9a419",
"size": "13514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/jstests/core/max_time_ms.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "392"
},
{
"name": "JavaScript",
"bytes": "6633558"
},
{
"name": "Makefile",
"bytes": "422"
}
],
"symlink_target": ""
} |
layout: post
title: "Testing a TypeScript Custom Component"
tags: [coveo-search-ui, Custom Component, TypeScript, CoveoFeelingLucky]
author:
name: François Lachance-Guillemette
bio: Coveo for Sitecore Developer
image: flguillemette.jpg
---
Now that we have [created a custom component](http://source.coveo.com/2017/11/30/randomizer-as-a-component/), we want to test its interactions with the Coveo JavaScript Search Framework.
This post offers a deep dive into the Custom Coveo JavaScript component testing world.
<!-- more -->
## Understanding the coveo-search-ui-tests library
Our last project started with the [search-ui-seed](https://github.com/coveo/search-ui-seed) starter project, which is written in [TypeScript](https://www.typescriptlang.org/).
This starter project references the [coveo-search-ui-tests](https://github.com/coveo/search-ui-tests), which is a simple library used to initialize environment variables that match the Coveo JavaScript Search Framework behavior.
It uses the [jasmine](https://jasmine.github.io/) framework for testing, so this article will use jasmine too. However, other frameworks should also work.
We already have a test file for the `HelloWorld` component in the `tests/ui` folder. Duplicate the `HelloWorld.spec.ts` file, and name it `CoveoFeelingLucky.spec.ts`.
Replace some names in this file, scrap the code that does not belong to the `CoveoFeelingLucky` component, and you should end up with something that looks similar to this:
```ts
import { CoveoFeelingLucky, ICoveoFeelingLuckyOptions } from '../../src/ui/CoveoFeelingLucky';
import { Mock, Fake, Simulate } from 'coveo-search-ui-tests';
import { $$, InitializationEvents, QueryEvents, IBuildingQueryEventArgs } from 'coveo-search-ui';
describe('CoveoFeelingLucky', () => {
let feelingLucky: Mock.IBasicComponentSetup<CoveoFeelingLucky>;
beforeEach(() => {
feelingLucky = Mock.basicComponentSetup<CoveoFeelingLucky>(CoveoFeelingLucky);
});
afterEach(() => {
// Safe-guard to ensure that you don't use `feelingLucky` inbetween tests.
feelingLucky = null;
});
// Remove this after you have validated that tests from this file are run.
it('should work', () => {
// Run fast if this test fails.
expect(true).toBe(true);
});
});
```
We have added a simple test to ensure that the tests are run. Execute the `npm run test` command (defined in the `coveo-search-ui-seed`'s `package.json` file) and validate that your test is executed (and passing 🙏).
`Mock.basicComponentSetup<CoveoFeelingLucky>(CoveoFeelingLucky);` is a utility that creates the given component with a mocked environment. `feelingLucky` is now an object that has two properties: `cmp` and `env`.
`cmp` should be used when you want to interact with the component.
`env` should be used when you want to interact with the environment.
## Our first tests
Let's start with a very simple test. We want to ensure that the component is `disabled` by default.
```ts
it('should be disabled on initialization', () => {
expect(feelingLucky.cmp.getCurrentState()).toBe(false);
});
```
Now, the main functionality of this component is to add a random query ranking function and pick the first result out of the query. We should at least validate that we set the number of results:
```ts
describe('when active and with the default options', () => {
beforeEach(() => {
feelingLucky.cmp.toggle();
});
it('should set in the query builder the number of results to 1', () => {
const result = Simulate.query(feelingLucky.env);
expect(result.queryBuilder.numberOfResults).toBe(1);
});
});
```
The first part in the `beforeEach` block activates the component. We will reuse this block when we want the component to be active; As you have guessed, testing a disabled components has some limitations.
`Simulate.query` is a very useful helper from the `coveo-search-ui-tests` library that simulates [the whole query event stack](https://developers.coveo.com/x/bYGfAQ#Events-QueryEvents), similar to when a user enters a new query in the search box.
It returns an object containing the results of the complete event flow, which is very useful to validate that some attributes have changed.
We have proof that our component, when enabled, modifies the number of results.
Even more important, we also want to be sure that the component does *not* override the number of results when disabled. That would be disastrous.
```ts
describe('when disabled', () => {
const originalNumberOfResults = 240;
let queryBuilder;
beforeEach(() => {
queryBuilder = new QueryBuilder();
queryBuilder.numberOfResults = originalNumberOfResults;
});
it('should not update the number of results', () => {
const result = Simulate.query(feelingLucky.env, {
queryBuilder: queryBuilder
});
expect(result.queryBuilder.numberOfResults).toBe(originalNumberOfResults);
});
});
```
In this example, we provided our own query builder. This simulates an existing environment that has already configured the query builder.
We now have basic testing and can safely explore into more dangerous fields\*.
<sub><sup>\*aforementioned fields are not actually dangerous.</sup></sub>
## Testing the component options
We want to set the `randomField` to some specific value and test that my new, (arguably) better name is used instead of the (arguably) ugly default one.
So, let's validate this with the `aq` part of the query.
```ts
describe('when active and setting the randomfield option', () => {
const someRandomField = 'heyimrandom';
beforeEach(() => {
const options: ICoveoFeelingLuckyOptions = {
title: null,
classesToHide: null,
hiddenComponentClass: null,
maximumRandomRange: null,
numberOfResults: null,
randomField: someRandomField
};
feelingLucky = Mock.optionsComponentSetup<CoveoFeelingLucky, ICoveoFeelingLuckyOptions>(CoveoFeelingLucky, options);
feelingLucky.cmp.toggle();
});
it('should set the random field in the advanced expression', () => {
const result = Simulate.query(feelingLucky.env);
expect(result.queryBuilder.advancedExpression.build()).toContain(`@${someRandomField}`);
});
});
```
The first difference is that we use another initialization method: `Mock.optionsComponentSetup<CoveoFeelingLucky, ICoveoFeelingLuckyOptions>(CoveoFeelingLucky, options);`.
This method is the same as `basicComponentSetup` but ensures that you pass the correct options type as a second argument, and type safety is always better! Kudos to TypeScript for type-safing my tests! 👏
We could also validate that we have a query ranking function that defines this random field:
```ts
it('should add the random field in the ranking function expression', () => {
const result = Simulate.query(feelingLucky.env);
expect(result.queryBuilder.rankingFunctions[0].expression).toContain(`@${someRandomField}`);
});
```
We could test the other options, but they would be tested similarly and would be redundant. Let's skip to another fun part.
## Core features testing
Our component is a button, so it would be very useful to validate that it gets activated when the button is clicked:
```ts
describe('when clicking on the button', () => {
it('should toggle the state', () => {
$$(feelingLucky.cmp.element).trigger('click');
expect(feelingLucky.cmp.getCurrentState()).toBe(true);
});
});
```
Here, to trigger a click event, we use the `$$` library from `coveo-search-ui`, which is a lightweight DOM manipulation library. It might look like `jQuery`, but really, it is not. Refer to the [DOM class](https://coveo.github.io/search-ui/classes/dom.html) documentation if you want an extensive list of features for this small library.
We could also check that toggling the state triggered a query. We can do that by overriding the method that we want to validate:
```ts
it('should execute a new query', () => {
const executeQueryHandler = jasmine.createSpy('executeQueryHandler');
feelingLucky.env.queryController.executeQuery = executeQueryHandler;
$$(feelingLucky.cmp.element).trigger('click');
expect(executeQueryHandler).toHaveBeenCalledTimes(1);
});
```
Remember how this is a randomizer? We should check that the ranking changes between queries:
```ts
it('should return different ranking function expressions for each query', () => {
const firstQueryResult = Simulate.query(feelingLucky.env);
const secondQueryResult = Simulate.query(feelingLucky.env);
const firstExpression = firstQueryResult.queryBuilder.rankingFunctions[0].expression;
const secondExpression = secondQueryResult.queryBuilder.rankingFunctions[0].expression;
expect(firstExpression).not.toBe(secondExpression);
});
```
See that we can simulate two queries and compare them? Pretty useful!
## Wrapping it up
There are many more things that we could test, like:
* Validating the other attributes.
* Validating that specified components are hidden when the randomizer is active and displayed when the randomizer is deactivated.
* Other possibilities, only limited by human creativity.
The tests in this post cover many scenarios that you might come across when you want to test your own components, so the rest will be left as an "exercise to the reader" <sup>tm</sup>.
In the next and final installment, we will integrate this component in the Coveo for Sitecore Hive Framework.
| {
"content_hash": "ebd3ed6fddb773ca198b67e5ef3e6df3",
"timestamp": "",
"source": "github",
"line_count": 224,
"max_line_length": 337,
"avg_line_length": 42.888392857142854,
"alnum_prop": 0.7345685437701676,
"repo_name": "acverrette/source.coveo.com",
"id": "4b43325680214637130d8bc9d8adccd707187878",
"size": "9618",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_posts/2017-12-01-testing-custom-component.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "322857"
},
{
"name": "HTML",
"bytes": "21318"
},
{
"name": "JavaScript",
"bytes": "4353"
}
],
"symlink_target": ""
} |
package org.apache.sshd.common.keyprovider;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.sshd.common.session.SessionContext;
import org.apache.sshd.util.test.JUnitTestSupport;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
/**
* TODO Add javadoc
*
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MultiKeyIdentityProviderTest extends JUnitTestSupport {
public MultiKeyIdentityProviderTest() {
super();
}
@Test // see SSHD-860
public void testLazyKeyIdentityMultiProvider() throws IOException, GeneralSecurityException {
List<KeyPair> expected = new ArrayList<>();
for (int index = 1; index <= Short.SIZE; index++) {
PublicKey pub = Mockito.mock(PublicKey.class);
PrivateKey prv = Mockito.mock(PrivateKey.class);
expected.add(new KeyPair(pub, prv));
}
Collection<KeyIdentityProvider> providers = new ArrayList<>();
AtomicInteger position = new AtomicInteger(0);
for (int startIndex = 0, count = expected.size(), slice = count / 3; startIndex < count;) {
int nextIndex = Math.min(count, startIndex + slice);
Collection<KeyPair> keys = expected.subList(startIndex, nextIndex);
providers.add(wrapKeyPairs(position, keys));
startIndex = nextIndex;
}
KeyIdentityProvider multiProvider = KeyIdentityProvider.multiProvider(providers);
assertObjectInstanceOf(MultiKeyIdentityProvider.class.getSimpleName(), MultiKeyIdentityProvider.class, multiProvider);
Iterable<KeyPair> keys = multiProvider.loadKeys(null);
Iterator<KeyPair> iter = keys.iterator();
for (int index = 0, count = expected.size(); index < count; index++) {
KeyPair kpExpected = expected.get(index);
assertTrue("Premature keys exhaustion after " + index + " iterations", iter.hasNext());
KeyPair kpActual = iter.next();
assertSame("Mismatched key at index=" + index, kpExpected, kpActual);
assertEquals("Mismatched requested lazy key position", index + 1, position.get());
}
assertFalse("Not all keys exhausted", iter.hasNext());
}
private static KeyIdentityProvider wrapKeyPairs(AtomicInteger position, Iterable<KeyPair> keys) {
return new KeyIdentityProvider() {
@Override
public Iterable<KeyPair> loadKeys(SessionContext session) {
return new Iterable<KeyPair>() {
@Override
public Iterator<KeyPair> iterator() {
return new Iterator<KeyPair>() {
private final Iterator<KeyPair> iter = keys.iterator();
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public KeyPair next() {
position.incrementAndGet();
return iter.next();
}
};
}
};
}
};
}
}
| {
"content_hash": "0f19ddca28e1c949c58a8f353c1e5e7d",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 126,
"avg_line_length": 39.202127659574465,
"alnum_prop": 0.6113975576662144,
"repo_name": "lgoldstein/mina-sshd",
"id": "a1a2dca8691330f8301200dc9fc1185c0449c791",
"size": "4486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sshd-common/src/test/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProviderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "15035"
},
{
"name": "HTML",
"bytes": "5769"
},
{
"name": "Java",
"bytes": "6840795"
},
{
"name": "Python",
"bytes": "11690"
},
{
"name": "Shell",
"bytes": "34849"
}
],
"symlink_target": ""
} |
import Yoga from '@react-pdf/yoga';
import setAlignContent from '../../src/node/setAlignContent';
describe('node setAlignContent', () => {
const mock = jest.fn();
const node = { yogaNode: { setAlignContent: mock } };
beforeEach(() => {
mock.mockReset();
});
test('should return node if no yoga node available', () => {
const emptyNode = { box: { width: 10, height: 20 } };
const result = setAlignContent(null)(emptyNode);
expect(result).toBe(emptyNode);
});
test('Should set align auto by default', () => {
const result = setAlignContent(null)(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_AUTO);
expect(result).toBe(node);
});
test('Should set flex-start', () => {
const result = setAlignContent('flex-start')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_FLEX_START);
expect(result).toBe(node);
});
test('Should set center', () => {
const result = setAlignContent('center')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_CENTER);
expect(result).toBe(node);
});
test('Should set flex-end', () => {
const result = setAlignContent('flex-end')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_FLEX_END);
expect(result).toBe(node);
});
test('Should set stretch', () => {
const result = setAlignContent('stretch')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_STRETCH);
expect(result).toBe(node);
});
test('Should set baseline', () => {
const result = setAlignContent('baseline')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_BASELINE);
expect(result).toBe(node);
});
test('Should set space-between', () => {
const result = setAlignContent('space-between')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_SPACE_BETWEEN);
expect(result).toBe(node);
});
test('Should set space-around', () => {
const result = setAlignContent('space-around')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.ALIGN_SPACE_AROUND);
expect(result).toBe(node);
});
});
| {
"content_hash": "60fac76e83d45f1dfec48bb0d360ff5c",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 65,
"avg_line_length": 29.132530120481928,
"alnum_prop": 0.6406120760959471,
"repo_name": "diegomura/react-pdf",
"id": "b8d23d7618f1965a014995defd846409519722a5",
"size": "2418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/layout/tests/node/setAlignContent.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2239741"
},
{
"name": "Shell",
"bytes": "693"
}
],
"symlink_target": ""
} |
//
// LYCategoriesMacro.h
// LYCategories <https://github.com/DeveloperLY/LYCategories>
//
// Created by Liu Y on 16/4/2.
// Copyright © 2016年 DeveloperLY. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
#ifndef LYCategoriesMacro_h
#define LYCategoriesMacro_h
// 动态Get方法
#define ly_categoryPropertyGet(property) return objc_getAssociatedObject(self, @#property);
// 动态Set方法
#define ly_categoryPropertySet(property) objc_setAssociatedObject(self,@#property, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
/**
Add this macro before each category implementation, so we don't have to use
-all_load or -force_load to load object files from static libraries that only
contain categories and no classes.
More info: http://developer.apple.com/library/mac/#qa/qa2006/qa1490.html .
*******************************************************************************
Example:
LYSYNTH_DUMMY_CLASS(NSString_LYAdd)
*/
#ifndef LYSYNTH_DUMMY_CLASS
#define LYSYNTH_DUMMY_CLASS(_name_) \
@interface LYSYNTH_DUMMY_CLASS_ ## _name_ : NSObject @end \
@implementation LYSYNTH_DUMMY_CLASS_ ## _name_ @end
#endif
//ios系统版本
#define ios9x [[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f
#define ios8x [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f
#define ios7x ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) && ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0f)
#define ios6x [[[UIDevice currentDevice] systemVersion] floatValue] < 7.0f
#define iosNot6x [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f
#define iphone4x_3_5 ([UIScreen mainScreen].bounds.size.height==480.0f)
#define iphone5x_4_0 ([UIScreen mainScreen].bounds.size.height==568.0f)
#define iphone6_4_7 ([UIScreen mainScreen].bounds.size.height==667.0f)
#define iphone6Plus_5_5 ([UIScreen mainScreen].bounds.size.height==736.0f || [UIScreen mainScreen].bounds.size.height==414.0f)
#endif /* LYCategoriesMacro_h */
| {
"content_hash": "e9f6c96bd7d8910b6db4576aeafe9572",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 143,
"avg_line_length": 37.17857142857143,
"alnum_prop": 0.7223823246878002,
"repo_name": "DeveloperLY/LYCategories",
"id": "3a99ea93f597be1109fd312293e8b877d26a4fb2",
"size": "2109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LYCategories/LYCategoriesMacro.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "237585"
},
{
"name": "Ruby",
"bytes": "1029"
}
],
"symlink_target": ""
} |
/* GLOBAL STYLES
-------------------------------------------------- */
/* Padding below the footer and lighter body text */
body {
padding-bottom: 40px;
color: #5a5a5a;
}
/* CUSTOMIZE THE NAVBAR
-------------------------------------------------- */
/* Special class on .container surrounding .navbar, used for positioning it into place. */
.navbar-wrapper {
position: fixed;
top: 0;
right: 0;
left: 0;
z-index: 20;
}
/* Flip around the padding for proper display in narrow viewports */
.navbar-wrapper > .container {
padding-right: 0;
padding-left: 0;
}
.navbar-wrapper .navbar {
padding-right: 15px;
padding-left: 15px;
}
.navbar-wrapper .navbar .container {
width: auto;
}
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
/* Carousel base class */
.carousel {
height: 500px;
margin-bottom: 60px;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
z-index: 10;
}
/* Declare heights because of positioning of img element */
.carousel .item {
height: 500px;
background-color: #777;
}
.carousel-inner > .item > img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 500px;
}
/* MARKETING CONTENT
-------------------------------------------------- */
/* Center align the text within the three columns below the carousel */
.marketing .col-lg-4 {
margin-bottom: 20px;
text-align: center;
}
.marketing h2 {
font-weight: normal;
}
.marketing .col-lg-4 p {
margin-right: 10px;
margin-left: 10px;
}
/* Featurettes
------------------------- */
.featurette-divider {
margin: 80px 0; /* Space out the Bootstrap <hr> more */
}
/* Thin out the marketing headings */
.featurette-heading {
font-weight: 300;
line-height: 1;
letter-spacing: -1px;
}
/* RESPONSIVE CSS
-------------------------------------------------- */
@media (min-width: 768px) {
/* Navbar positioning foo */
.navbar-wrapper {
margin-top: 20px;
}
.navbar-wrapper .container {
padding-right: 15px;
padding-left: 15px;
}
.navbar-wrapper .navbar {
padding-right: 0;
padding-left: 0;
}
/* The navbar becomes detached from the top, so we round the corners */
.navbar-wrapper .navbar {
border-radius: 4px;
}
/* Bump up size of carousel content */
.carousel-caption p {
margin-bottom: 20px;
font-size: 21px;
line-height: 1.4;
}
.featurette-heading {
font-size: 50px;
}
}
@media (min-width: 992px) {
.featurette-heading {
margin-top: 120px;
}
} | {
"content_hash": "165cbcfbcbc97394756bfc27f63f6b32",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 90,
"avg_line_length": 18.91044776119403,
"alnum_prop": 0.5777426992896606,
"repo_name": "edutronics/Edutronics.github.io",
"id": "40a5928476fe42ab97c9faae61d0d31148fff769",
"size": "2534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "carousel.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4073"
},
{
"name": "HTML",
"bytes": "58568"
}
],
"symlink_target": ""
} |
{-# LANGUAGE OverloadedStrings #-}
module Blah where
import Data.Aeson ((.:), (.:?), decode, FromJSON(..), Value(..))
import Control.Applicative ((<$>), (<*>))
import Data.Scientific as Scientific
import Data.Time.Format (parseTime)
import Data.Time.Clock (UTCTime)
import System.Locale (defaultTimeLocale)
import Control.Monad (liftM)
import Data.Attoparsec.Number (Number(..))
import qualified Data.HashMap.Strict as HM
import qualified Data.ByteString.Lazy.Char8 as BS
------------------------------------------------------------------------
parseRHTime :: String -> Maybe UTCTime
parseRHTime = parseTime defaultTimeLocale "%FT%X%QZ"
-- match objects
data Paste = Paste { getLines :: Scientific -- note difference from example
, getDate :: Maybe UTCTime
, getID :: String
, getLanguage :: String
, getPrivate :: Bool
, getURL :: String
, getUser :: Maybe String
, getBody :: String
} deriving (Show)
-- define instance to make it possible to decode
instance FromJSON Paste where
parseJSON (Object v) =
Paste <$>
(v .: "lines") <*>
liftM parseRHTime (v .: "date") <*>
(v .: "paste-id") <*>
(v .: "language") <*>
(v .: "private") <*>
(v .: "url") <*>
(v .:? "user") <*>
(v .: "contents")
-- .:? allows keys to be null or not exist
-- nested structures `((v .: "stuff") >>= (.: "language"))`
-- { stuff: { language: en} }
-- --function to extract the number of lines from the json
getRHLines :: String -> Scientific -- note difference from example
getRHLines json =
case HM.lookup "lines" hm of
Just (Number n) -> n
Nothing -> error "Y U NO HAZ NUMBER?"
where (Just (Object hm)) = decode (BS.pack json) :: Maybe Value
------------------------------------------------------------------------
{-
# REFERENCE & LINKS
This file comes from a tutorial published in Nov 2012. Some types have
been changed to make it work with the latest version of Aeson 0.7.0.3
The original version is published at:
http://blog.raynes.me/blog/2012/11/27/easy-json-parsing-in-haskell-with-aeson/
The main change from original version published in 2012 was the input
type change due to the Aeson library updates since then. The current as of Spring 2015
aeson version 0.7.0.3 takes Scientific instead of Integer type. You can find
types by typing `:t Number` into your ghci console.
Reference for aeson 0.7.0.3 types can be found on hackage:
http://hackage.haskell.org/package/aeson-0.7.0.3/docs/Data-Aeson-Types.html
# Usage
inside ghci, load the file with :load blah.hs
then you can call the function and pass in json data
getRHLines "{\"lines\":1,\"date\":\"2012-01-04T01:44:22.964Z\",\"paste-id\":\"1\",\"fork\":null,\"random-id\":\"f1fc1181fb294950ca4df7008\",\"language\":\"Clojure\",\"private\":false,\"url\":\"https://www.refheap.com/paste/1\",\"user\":\"raynes\",\"contents\":\"(begin)\"}"
-}
| {
"content_hash": "043e8659c0b5ed4a82b1f424babf5445",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 273,
"avg_line_length": 38.42168674698795,
"alnum_prop": 0.5779241141423643,
"repo_name": "katychuang/getting-started-with-haskell",
"id": "d7ce64ae7fc5da9ea60d1ed558e42ce94496660a",
"size": "3189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tutorials/blah.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "259"
},
{
"name": "Haskell",
"bytes": "23328"
},
{
"name": "Jupyter Notebook",
"bytes": "10395"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>All That Is Solid Melts into Air</title>
<meta name="description" content="360° Image Gallery - A-Frame">
<script src="https://aframe.io/releases/0.4.0/aframe.min.js"></script>
<script src="https://npmcdn.com/aframe-animation-component@3.0.1"></script>
<script src="https://npmcdn.com/aframe-event-set-component@3.0.1"></script>
<script src="https://npmcdn.com/aframe-layout-component@3.0.1"></script>
<script src="https://npmcdn.com/aframe-template-component@3.1.1"></script>
<script src="components/set-image.js"></script>
</head>
<body>
<a-scene>
<a-assets>
<img id="city" crossorigin="anonymous" src="img/img00010.jpg">
<img id="far" crossorigin="anonymous" src="img/one.jpg">
<img id="near" crossorigin="anonymous" src="img/two.jpg">
<img id="sechelt-thumb" crossorigin="anonymous" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-sechelt.jpg">
<audio id="click-sound" crossorigin="anonymous" src="https://cdn.aframe.io/360-image-gallery-boilerplate/audio/click.ogg"></audio>
<img id="cubes" crossorigin="anonymous" src="img/img02076.jpg">
<img id="sechelt" crossorigin="anonymous" src="img/img02733.jpg">
<!-- Image link template to be reused. -->
<script id="link" type="text/html">
<a-entity class="link"
geometry="primitive: box; height: 1; width: 1; length: 1"
material="shader: flat; src: ${thumb}"
event-set__1="_event: mousedown; scale: 1 1 1"
event-set__2="_event: mouseup; scale: 1.2 1.2 1"
event-set__3="_event: mouseenter; scale: 1.2 1.2 1"
event-set__4="_event: mouseleave; scale: 1 1 1"
set-image="on: click; target: #image-360; src: ${src}"
sound="on: click; src: #click-sound"></a-entity>
</script>
</a-assets>
<!-- 360-degree image. -->
<a-sky id="image-360" radius="10" src="#city"></a-sky>
<!-- Image links. -->
<a-entity id="links" layout="type: line; margin: 1.5" position="0 -1 -4">
<a-entity template="src: #link" data-src="#cubes" data-thumb="#near"></a-entity>
<a-entity template="src: #link" data-src="#city" data-thumb="#far"></a-entity>
</a-entity>
<!-- Camera + cursor. -->
<a-entity camera look-controls>
<a-cursor id="cursor"
animation__click="property: scale; startEvents: click; from: 0.1 0.1 0.1; to: 1 1 1; dur: 150"
animation__fusing="property: fusing; startEvents: fusing; from: 1 1 1; to: 0.1 0.1 0.1; dur: 1500"
event-set__1="_event: mouseenter; color: springgreen"
event-set__2="_event: mouseleave; color: black"
raycaster="objects: .link"></a-cursor>
</a-entity>
</a-scene>
</body>
</html>
| {
"content_hash": "ff558b190a4dd100edd928bd2d6c5b44",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 138,
"avg_line_length": 49.05084745762712,
"alnum_prop": 0.598479612992398,
"repo_name": "ganttmd87/ganttmd87.github.io",
"id": "08497f216dd0cda9551aea4568a220f1fae0a7e1",
"size": "2894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "indexAIR.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10111"
},
{
"name": "JavaScript",
"bytes": "1232"
}
],
"symlink_target": ""
} |
package org.marre.xml;
import java.io.IOException;
/**
* Interface for objects that can be represented in xml form.
*
* @author Markus
* @version $Id$
*/
public interface XmlDocument
{
/**
* Returns the content-type of this xml document.
*
* @return Content-type. Ex: "text/xml".
*/
String getContentType();
/**
* Writes this object to the given XmlWriter.
*
* @param xmlWriter XmlWriter to write to.
* @throws IOException Thrown if failed to write to xmlwriter.
*/
void writeXmlTo(XmlWriter xmlWriter) throws IOException;
}
| {
"content_hash": "4d94709f2fda1ad3411c2e60c73ac651",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 66,
"avg_line_length": 21.5,
"alnum_prop": 0.6395348837209303,
"repo_name": "Lihuanghe/CMPPGate",
"id": "1742993e4a995814fc884a7b1c92e55db68e8d4b",
"size": "2296",
"binary": false,
"copies": "1",
"ref": "refs/heads/netty4",
"path": "src/main/java/org/marre/xml/XmlDocument.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2707185"
},
{
"name": "Shell",
"bytes": "2346"
}
],
"symlink_target": ""
} |
import { useEffect } from "react";
import { UnityArguments } from "../types/unity-arguments";
import { UnityProvider } from "../types/unity-provider";
import { UnityLoaderStatus } from "../enums/unity-loader-status";
import { isBrowserEnvironment } from "../constants/is-browser-environment";
/**
* Creates a Unity Instance.
* @param unityLoaderStatus The loader status.
* @param htmlCanvasElement A reference to the html canvas element.
* @param unityArguments The Unity instance arguments.
* @param unityProvider The Unity provider.
* @returns the Unity Instance among with the status of the Unity Instance.
*/
const useUnityInstance = (
unityLoaderStatus: UnityLoaderStatus,
htmlCanvasElement: HTMLCanvasElement | null,
unityArguments: UnityArguments,
unityProvider: UnityProvider
): void => {
// Effect invoked when the Unity Loader status or canvas reference changes.
useEffect(() => {
(async () => {
// It is possible for the application being rendered server side. In
// this scenario, the window is not available. We can't create the
// Unity Instance in this case.
if (isBrowserEnvironment === false) {
return;
}
if (
unityLoaderStatus !== UnityLoaderStatus.Loaded ||
htmlCanvasElement === null
) {
// If the loader is not loaded, or the canvas is not available,
// we can't create the Unity instance yet. In case of a fresh load,
// we'll clear the initialisation error as well.
unityProvider.setUnityInstance(null);
unityProvider.setInitialisationError(null);
return;
}
// Creates the Unity Instance, this method is made available globally by
// the Unity Loader.
try {
/**
* The internal Unity Instance which has been initialized usign the
* create Unity Instance method exposed by the Unity Loader.
*/
const unityInstance = await window.createUnityInstance(
htmlCanvasElement,
unityArguments,
unityProvider.setLoadingProgression
);
// When the Unity Instance is created, its reference is stored in the
// state while the error state is cleared.
unityProvider.setUnityInstance(unityInstance);
unityProvider.setInitialisationError(null);
} catch (error: any) {
// When the Unity Instance catches due to a fail during the creation,
// the Unity Instnace reference will be cleared while the error is
// placed into the state.
unityProvider.setUnityInstance(null);
unityProvider.setInitialisationError(error);
}
})();
}, [unityLoaderStatus, htmlCanvasElement, unityArguments, unityProvider]);
};
export { useUnityInstance };
| {
"content_hash": "8776c0bf48dee19b84861124552b3a36",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 78,
"avg_line_length": 40.69117647058823,
"alnum_prop": 0.6783520057824358,
"repo_name": "jeffreylanters/react-unity-webgl",
"id": "ca325feab0343d90929757e60c1e53223ada037d",
"size": "2767",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "module/source/hooks/use-unity-instance.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "TypeScript",
"bytes": "48333"
}
],
"symlink_target": ""
} |
const Color Color::BLACK = createColorHexRGB(0x000000);
const Color Color::WHITE = createColorHexRGB(0xFFFFFF);
const Color Color::GREY = createColorHexRGB(0x808080);
const Color Color::RED = createColorHexRGB(0xFF0000);
const Color Color::GREEN = createColorHexRGB(0x00FF00);
const Color Color::BLUE = createColorHexRGB(0x0000FF);
const Color Color::CYAN = createColorHexRGB(0x00FFFF);
const Color Color::MAGENTA = createColorHexRGB(0xFF00FF);
const Color Color::YELLOW = createColorHexRGB(0xFFFF00);
Color::Color() : r(0), g(0), b(0), a(1) {}
Color::Color(float32 r, float32 g, float32 b, float32 a) : r(r), g(g), b(b), a(a) {}
Color::Color(uint8 r, uint8 g, uint8 b, uint8 a) : Color( r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f) {}
Color::~Color() {}
Color Color::createColorHexRGB(uint32 rgb) {
return { (uint8)(rgb >> 16), (rgb & 0x00FF00) >> 8, (rgb & 0x0000FF)};
}
| {
"content_hash": "4c5384819727d4f13f1d724fdc50251a",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 108,
"avg_line_length": 42,
"alnum_prop": 0.7018140589569161,
"repo_name": "simon-bourque/2D-Game-Engine-Cpp",
"id": "38d23afeb60bcf44ccfde8d7daf27a4781acbb34",
"size": "902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/OGF-Core/Core/Graphics/Color.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2760"
},
{
"name": "C++",
"bytes": "356596"
},
{
"name": "GLSL",
"bytes": "19022"
}
],
"symlink_target": ""
} |
// This header file defines node specs for quantization and the methods to parse
// command line flags to these specs.
#ifndef TENSORFLOW_COMPILER_MLIR_LITE_QUANTIZATION_QUANTIZATION_CONFIG_H_
#define TENSORFLOW_COMPILER_MLIR_LITE_QUANTIZATION_QUANTIZATION_CONFIG_H_
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/strings/string_view.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/lite/tools/optimize/reduced_precision_support.h"
namespace mlir {
namespace TFL {
// Stores information about how to quantize a user-specified custom operation.
struct CustomOpInfo {
std::vector<std::int32_t> quantizable_input_indices;
bool is_weight_only = false;
bool no_side_effect = true;
};
using ::tflite::optimize::ReducedPrecisionSupport;
using StringSet = absl::flat_hash_set<std::string>;
using CustomOpMap = std::unordered_map<std::string, CustomOpInfo>;
enum CustomOpUpdateOptions { kINputIndices, kWeightOnly, kNoSideEffect };
struct QuantizationSpecs {
// Which function this node quant specifications belong to.
std::string target_func = "main";
// Whether the quantization passes are triggered for post-training
// quantization. If it is true, the model input doesn't require user specified
// input ranges.
bool post_training_quantization = false;
// Whether allow dynamic range quantization. This is the easiest quantization
// mode which doesn't require QAT or sample inputs. But it can only target
// DT_HALF and DT_QINT8 inference type.
bool weight_quantization = false;
// Whether use the MLIR dynamic range quantizer instead of the old TOCO one.
bool enable_mlir_dynamic_range_quantizer = false;
// Whether allow weight-only quantization. This scheme quantize weights but
// will dequantize them back at runtime which is useful to save memory when
// the kernel support is not yet avilable in lower precisions. Used in MLIR
// dynamic range quantizer.
bool weight_only_quantization = false;
// The minimum number of elements in a weights array required to apply
// quantization. This is especially useful not to quantize small tensors as
// it is hard to get performance benefits from them with quantization. Used
// in MLIR dynamic range quantizer with int8 weight data type.
int64_t minimum_elements_for_weights = 1024;
// Calculate scales in float to keep quantized values the same with old TOCO
// quantizer.
bool legacy_float_scale = false;
// When set to true, quantization will be done per-tensor. Currently, this
// option is only valid when the quantization parameters need to be created by
// scanning the constant content (post-training quantization or QAT without
// weight FakeQuant).
bool disable_per_channel = false;
// When set to true, the fixed output ranges of the activation ops (tanh,
// sigmoid, etc.) and the weight constants are not inferred. Then, to quantize
// these ops, quantization emulation ops should be placed after the ops in the
// input graph. This flag should be set to false for post-training
// quantization.
bool disable_infer_tensor_range = false;
// The node type when the model is exported. Currently this is limited to
// DT_FLOAT, DT_HALF, DT_QINT8, and DT_QUINT8. When DT_HALF is used, the
// `weight_quantization` flag needs to set to true. When DT_QUINT8 is used,
// the `weight_quantization` flag needs to set to false.
tensorflow::DataType inference_type = tensorflow::DT_FLOAT;
// The input and output data type during inference. This flag is only used
// when `inference_type` is different from DT_FLOAT. This flag can only be set
// to DT_FLOAT or as same as `inference_type`. If this flag is different
// from `inference_type`, adaptor ops are inserted as heading and tailing ops
// in the result model.
tensorflow::DataType inference_input_type = tensorflow::DT_FLOAT;
// Input node ranges. These ranges are stored as the same order of function
// arguments. They are only used when `weight_quantization` is set to false,
// and the model is required to have quantization parameters, either from
// quantization aware training or calibration, for the remaining tensors.
std::vector<std::pair<llvm::Optional<double>, llvm::Optional<double>>>
input_ranges;
// The default ranges can be used when a tensor doesn't have quantization
// parameters and couldn't be quantized. Used only for latency tests.
std::pair<llvm::Optional<double>, llvm::Optional<double>> default_ranges;
// A serialized "QuantizationInfo" object to specify value ranges for some of
// the tensors with known names.
std::string serialized_quant_stats = "";
// A bitmask to encode support for reduced precision inference in the model.
ReducedPrecisionSupport support_mask = ReducedPrecisionSupport::None;
// Whether run the passes to propagate the quantization parameters and graph
// rewrites. Returns false if the inference_type is DT_FLOAT or
// `weight_quantization` flag is set.
bool RunPropagationAndRewriteQuantizationPasses() const {
return inference_type != tensorflow::DT_FLOAT && !weight_quantization;
}
// TODO(b/202075505): make implicit weight type clearer
// Whether run the passes and graph rewrites for dynamic range quantization.
bool RunAndRewriteDynamicRangeQuantizationPasses() const {
// TODO(b/201389248): add condition that symmetric, signed, int8 only
// If fail, log will appear to let user know nothing happened.
bool dynamic_range_quantize =
(inference_type != tensorflow::DT_FLOAT) && weight_quantization &&
!post_training_quantization && !disable_infer_tensor_range &&
enable_mlir_dynamic_range_quantizer;
return dynamic_range_quantize;
}
// Whether this inference type represents a signed storage type.
bool IsSignedInferenceType() const {
switch (inference_type) {
case tensorflow::DT_QUINT8:
case tensorflow::DT_QUINT16:
return false;
default:
return true;
}
}
// Gets the width of this quantization type. Returns 0 if it isn't a
// quantization type.
int64_t GetQuantizationTypeWidth() const {
switch (inference_type) {
case tensorflow::DT_QINT8:
case tensorflow::DT_QUINT8:
return 8;
case tensorflow::DT_QINT16:
case tensorflow::DT_QUINT16:
return 16;
case tensorflow::DT_QINT32:
return 32;
default:
return 0;
}
}
// Whether add the NumericVerify ops to verify numbers before and after
// quantization.
bool verify_numeric = false;
// Whether to add verification for layer by layer, or on whole model. When
// disabled (per-layer) float and quantized ops will be run from same input
// (output of previous quantized layer). When enabled, float and quantized ops
// will run with respective float and quantized output of previous ops.
bool whole_model_verify = false;
// Whether to use fake quant attributes to calculate quantization parameters.
bool use_fake_quant_num_bits = false;
// Names of ops to block from quantization. Used in QuantizePass.
// For dynamic range quantization, ops in blocklist are quantized in weight-
// only manner.
StringSet ops_blocklist;
// Names of locations to block from quantization. Used in QuantizePass.
StringSet nodes_blocklist;
// Map from custom op code to custom op quantization information.
// For dynamic range quantization, among the custom ops in the graph those
// specified in this map are subject to quantization.
CustomOpMap custom_map;
};
// Parses the command line flag strings to the CustomOpMap specification.
void ParseCustomOpSpecs(absl::string_view node_names,
const CustomOpUpdateOptions& update_option,
CustomOpMap& custom_op_map);
// Parses the command line flag strings to the quantization specification for
// input arrays of a graph. The array names are not stored in the spec, and will
// be matched by position. Returns true if failed.
bool ParseInputNodeQuantSpecs(absl::string_view node_names,
absl::string_view min_values,
absl::string_view max_values,
absl::string_view inference_type,
QuantizationSpecs* quant_specs);
// Gets the quantization specification for input arrays. The array names are not
// stored in the spec, and will be matched by position. The min/max will be
// ignored if the inference_type isn't a quantized type. Returns true if failed.
bool GetInputNodeQuantSpecs(
const std::vector<std::string>& node_names,
const std::vector<llvm::Optional<double>>& node_mins,
const std::vector<llvm::Optional<double>>& node_maxs,
tensorflow::DataType inference_type, QuantizationSpecs* quant_specs);
} // namespace TFL
} // namespace mlir
#endif // TENSORFLOW_COMPILER_MLIR_LITE_QUANTIZATION_QUANTIZATION_CONFIG_H_
| {
"content_hash": "a21d9985c42e0792c53bfa042b2d9e8b",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 80,
"avg_line_length": 43.02358490566038,
"alnum_prop": 0.7277710777327048,
"repo_name": "Intel-Corporation/tensorflow",
"id": "ea76823a8f3290f3ccf1414c907e891529073926",
"size": "9789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/compiler/mlir/lite/quantization/quantization_config.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7481"
},
{
"name": "C",
"bytes": "183416"
},
{
"name": "C++",
"bytes": "24549804"
},
{
"name": "CMake",
"bytes": "160888"
},
{
"name": "Go",
"bytes": "849081"
},
{
"name": "HTML",
"bytes": "681293"
},
{
"name": "Java",
"bytes": "307123"
},
{
"name": "Jupyter Notebook",
"bytes": "1833659"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "37393"
},
{
"name": "Objective-C",
"bytes": "7037"
},
{
"name": "Objective-C++",
"bytes": "64142"
},
{
"name": "Protocol Buffer",
"bytes": "218430"
},
{
"name": "Python",
"bytes": "21875003"
},
{
"name": "Shell",
"bytes": "337846"
},
{
"name": "TypeScript",
"bytes": "849555"
}
],
"symlink_target": ""
} |
<?php
namespace CybozuHttp\Middleware;
use GuzzleHttp\Psr7\Stream;
use PHPUnit\Framework\TestCase;
class JsonStreamTest extends TestCase
{
public function testJsonSerialize(): void
{
$data = ['test' => 'data'];
$string = json_encode($data);
$jsonStream = new JsonStream(new Stream(fopen('data://text/plain,'.$string, 'rb')));
$this->assertEquals($jsonStream->jsonSerialize(), $data);
}
public function testJsonSerializeNull(): void
{
$string = '';
$jsonStream = new JsonStream(new Stream(fopen('data://text/plain,'.$string, 'rb')));
$this->assertNull($jsonStream->jsonSerialize());
}
public function testJsonSerializeError(): void
{
$string = '{"';
$jsonStream = new JsonStream(new Stream(fopen('data://text/plain,'.$string, 'rb')));
try {
$jsonStream->jsonSerialize();
} catch (\RuntimeException $e) {
$this->assertTrue(true);
}
}
}
| {
"content_hash": "55a19a8ef7af73f9edfc3fe3bc84cafd",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 92,
"avg_line_length": 26.263157894736842,
"alnum_prop": 0.5951903807615231,
"repo_name": "ochi51/cybozu-http",
"id": "67d6b3806aca9e268f0620abb14aaabc1dedcf94",
"size": "998",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Middleware/JsonStreamTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "14"
},
{
"name": "PHP",
"bytes": "226625"
}
],
"symlink_target": ""
} |
package com.google.gerrit.server.plugins;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class PluginScannerThread extends Thread {
private final CountDownLatch done = new CountDownLatch(1);
private final PluginLoader loader;
private final long checkFrequencyMillis;
PluginScannerThread(PluginLoader loader, long checkFrequencyMillis) {
this.loader = loader;
this.checkFrequencyMillis = checkFrequencyMillis;
setDaemon(true);
setName("PluginScanner");
}
@Override
public void run() {
for (; ; ) {
try {
if (done.await(checkFrequencyMillis, TimeUnit.MILLISECONDS)) {
return;
}
} catch (InterruptedException e) {
// Ignored
}
loader.rescan();
}
}
void end() {
done.countDown();
Uninterruptibles.joinUninterruptibly(this);
}
}
| {
"content_hash": "d1d0e7476e0f01c51a7203e2c263f895",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 71,
"avg_line_length": 25.216216216216218,
"alnum_prop": 0.6956055734190782,
"repo_name": "GerritCodeReview/gerrit",
"id": "1c2c8366974497ecf364ecf3fea590e2f3c49ec9",
"size": "1542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/com/google/gerrit/server/plugins/PluginScannerThread.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10735"
},
{
"name": "Closure Templates",
"bytes": "87947"
},
{
"name": "Dockerfile",
"bytes": "2833"
},
{
"name": "GAP",
"bytes": "5268"
},
{
"name": "Go",
"bytes": "2731"
},
{
"name": "HTML",
"bytes": "65080"
},
{
"name": "Java",
"bytes": "19516048"
},
{
"name": "JavaScript",
"bytes": "73591"
},
{
"name": "Makefile",
"bytes": "367"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "27464"
},
{
"name": "Python",
"bytes": "86775"
},
{
"name": "Roff",
"bytes": "25754"
},
{
"name": "Scala",
"bytes": "49306"
},
{
"name": "Shell",
"bytes": "91452"
},
{
"name": "Starlark",
"bytes": "280825"
},
{
"name": "TypeScript",
"bytes": "6249575"
}
],
"symlink_target": ""
} |
/**
* @license Highcharts JS v7.0.0 (2018-12-11)
* Sonification module
*
* (c) 2012-2018 Øystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var Instrument = (function (H) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Instrument class for sonification module.
*
* License: www.highcharts.com/license
*
* */
/**
* A set of options for the Instrument class.
*
* @requires module:modules/sonification
*
* @interface Highcharts.InstrumentOptionsObject
*//**
* The type of instrument. Currently only `oscillator` is supported. Defaults
* to `oscillator`.
* @name Highcharts.InstrumentOptionsObject#type
* @type {string|undefined}
*//**
* The unique ID of the instrument. Generated if not supplied.
* @name Highcharts.InstrumentOptionsObject#id
* @type {string|undefined}
*//**
* When using functions to determine frequency or other parameters during
* playback, this options specifies how often to call the callback functions.
* Number given in milliseconds. Defaults to 20.
* @name Highcharts.InstrumentOptionsObject#playCallbackInterval
* @type {number|undefined}
*//**
* A list of allowed frequencies for this instrument. If trying to play a
* frequency not on this list, the closest frequency will be used. Set to `null`
* to allow all frequencies to be used. Defaults to `null`.
* @name Highcharts.InstrumentOptionsObject#allowedFrequencies
* @type {Array<number>|undefined}
*//**
* Options specific to oscillator instruments.
* @name Highcharts.InstrumentOptionsObject#oscillator
* @type {Highcharts.OscillatorOptionsObject|undefined}
*/
/**
* Options for playing an instrument.
*
* @requires module:modules/sonification
*
* @interface Highcharts.InstrumentPlayOptionsObject
*//**
* The frequency of the note to play. Can be a fixed number, or a function. The
* function receives one argument: the relative time of the note playing (0
* being the start, and 1 being the end of the note). It should return the
* frequency number for each point in time. The poll interval of this function
* is specified by the Instrument.playCallbackInterval option.
* @name Highcharts.InstrumentPlayOptionsObject#frequency
* @type {number|Function}
*//**
* The duration of the note in milliseconds.
* @name Highcharts.InstrumentPlayOptionsObject#duration
* @type {number}
*//**
* The minimum frequency to allow. If the instrument has a set of allowed
* frequencies, the closest frequency is used by default. Use this option to
* stop too low frequencies from being used.
* @name Highcharts.InstrumentPlayOptionsObject#minFrequency
* @type {number|undefined}
*//**
* The maximum frequency to allow. If the instrument has a set of allowed
* frequencies, the closest frequency is used by default. Use this option to
* stop too high frequencies from being used.
* @name Highcharts.InstrumentPlayOptionsObject#maxFrequency
* @type {number|undefined}
*//**
* The volume of the instrument. Can be a fixed number between 0 and 1, or a
* function. The function receives one argument: the relative time of the note
* playing (0 being the start, and 1 being the end of the note). It should
* return the volume for each point in time. The poll interval of this function
* is specified by the Instrument.playCallbackInterval option. Defaults to 1.
* @name Highcharts.InstrumentPlayOptionsObject#volume
* @type {number|Function|undefined}
*//**
* The panning of the instrument. Can be a fixed number between -1 and 1, or a
* function. The function receives one argument: the relative time of the note
* playing (0 being the start, and 1 being the end of the note). It should
* return the panning value for each point in time. The poll interval of this
* function is specified by the Instrument.playCallbackInterval option.
* Defaults to 0.
* @name Highcharts.InstrumentPlayOptionsObject#pan
* @type {number|Function|undefined}
*//**
* Callback function to be called when the play is completed.
* @name Highcharts.InstrumentPlayOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* @requires module:modules/sonification
*
* @interface Highcharts.OscillatorOptionsObject
*//**
* The waveform shape to use for oscillator instruments. Defaults to `sine`.
* @name Highcharts.OscillatorOptionsObject#waveformShape
* @type {string|undefined}
*/
// Default options for Instrument constructor
var defaultOptions = {
type: 'oscillator',
playCallbackInterval: 20,
oscillator: {
waveformShape: 'sine'
}
};
/**
* The Instrument class. Instrument objects represent an instrument capable of
* playing a certain pitch for a specified duration.
*
* @sample highcharts/sonification/instrument/
* Using Instruments directly
* @sample highcharts/sonification/instrument-advanced/
* Using callbacks for instrument parameters
*
* @requires module:modules/sonification
*
* @class
* @name Highcharts.Instrument
*
* @param {Highcharts.InstrumentOptionsObject} options
* Options for the instrument instance.
*/
function Instrument(options) {
this.init(options);
}
Instrument.prototype.init = function (options) {
if (!this.initAudioContext()) {
H.error(29);
return;
}
this.options = H.merge(defaultOptions, options);
this.id = this.options.id = options && options.id || H.uniqueKey();
// Init the audio nodes
var ctx = H.audioContext;
this.gainNode = ctx.createGain();
this.setGain(0);
this.panNode = ctx.createStereoPanner && ctx.createStereoPanner();
if (this.panNode) {
this.setPan(0);
this.gainNode.connect(this.panNode);
this.panNode.connect(ctx.destination);
} else {
this.gainNode.connect(ctx.destination);
}
// Oscillator initialization
if (this.options.type === 'oscillator') {
this.initOscillator(this.options.oscillator);
}
// Init timer list
this.playCallbackTimers = [];
};
/**
* Return a copy of an instrument. Only one instrument instance can play at a
* time, so use this to get a new copy of the instrument that can play alongside
* it. The new instrument copy will receive a new ID unless one is supplied in
* options.
*
* @function Highcharts.Instrument#copy
*
* @param {Highcharts.InstrumentOptionsObject} [options]
* Options to merge in for the copy.
*
* @return {Highcharts.Instrument}
* A new Instrument instance with the same options.
*/
Instrument.prototype.copy = function (options) {
return new Instrument(H.merge(this.options, { id: null }, options));
};
/**
* Init the audio context, if we do not have one.
* @private
* @return {boolean} True if successful, false if not.
*/
Instrument.prototype.initAudioContext = function () {
var Context = H.win.AudioContext || H.win.webkitAudioContext,
hasOldContext = !!H.audioContext;
if (Context) {
H.audioContext = H.audioContext || new Context();
if (
!hasOldContext &&
H.audioContext &&
H.audioContext.state === 'running'
) {
H.audioContext.suspend(); // Pause until we need it
}
return !!(
H.audioContext &&
H.audioContext.createOscillator &&
H.audioContext.createGain
);
}
return false;
};
/**
* Init an oscillator instrument.
* @private
* @param {object} oscillatorOptions - The oscillator options passed to
* Highcharts.Instrument#init.
*/
Instrument.prototype.initOscillator = function (options) {
var ctx = H.audioContext;
this.oscillator = ctx.createOscillator();
this.oscillator.type = options.waveformShape;
this.oscillator.connect(this.gainNode);
this.oscillatorStarted = false;
};
/**
* Set pan position.
* @private
* @param {number} panValue - The pan position to set for the instrument.
*/
Instrument.prototype.setPan = function (panValue) {
if (this.panNode) {
this.panNode.pan.setValueAtTime(panValue, H.audioContext.currentTime);
}
};
/**
* Set gain level. A maximum of 1.2 is allowed before we emit a warning. The
* actual volume is not set above this level regardless of input.
* @private
* @param {number} gainValue - The gain level to set for the instrument.
* @param {number} [rampTime=0] - Gradually change the gain level, time given in
* milliseconds.
*/
Instrument.prototype.setGain = function (gainValue, rampTime) {
if (this.gainNode) {
if (gainValue > 1.2) {
console.warn( // eslint-disable-line
'Highcharts sonification warning: ' +
'Volume of instrument set too high.'
);
gainValue = 1.2;
}
if (rampTime) {
this.gainNode.gain.setValueAtTime(
this.gainNode.gain.value, H.audioContext.currentTime
);
this.gainNode.gain.linearRampToValueAtTime(
gainValue,
H.audioContext.currentTime + rampTime / 1000
);
} else {
this.gainNode.gain.setValueAtTime(
gainValue, H.audioContext.currentTime
);
}
}
};
/**
* Cancel ongoing gain ramps.
* @private
*/
Instrument.prototype.cancelGainRamp = function () {
if (this.gainNode) {
this.gainNode.gain.cancelScheduledValues(0);
}
};
/**
* Get the closest valid frequency for this instrument.
* @private
* @param {number} frequency - The target frequency.
* @param {number} [min] - Minimum frequency to return.
* @param {number} [max] - Maximum frequency to return.
* @return {number} The closest valid frequency to the input frequency.
*/
Instrument.prototype.getValidFrequency = function (frequency, min, max) {
var validFrequencies = this.options.allowedFrequencies,
maximum = H.pick(max, Infinity),
minimum = H.pick(min, -Infinity);
return !validFrequencies || !validFrequencies.length ?
// No valid frequencies for this instrument, return the target
frequency :
// Use the valid frequencies and return the closest match
validFrequencies.reduce(function (acc, cur) {
// Find the closest allowed value
return Math.abs(cur - frequency) < Math.abs(acc - frequency) &&
cur < maximum && cur > minimum ?
cur : acc;
}, Infinity);
};
/**
* Clear existing play callback timers.
* @private
*/
Instrument.prototype.clearPlayCallbackTimers = function () {
this.playCallbackTimers.forEach(function (timer) {
clearInterval(timer);
});
this.playCallbackTimers = [];
};
/**
* Set the current frequency being played by the instrument. The closest valid
* frequency between the frequency limits is used.
* @param {number} frequency - The frequency to set.
* @param {object} [frequencyLimits] - Object with maxFrequency and minFrequency
*/
Instrument.prototype.setFrequency = function (frequency, frequencyLimits) {
var limits = frequencyLimits || {},
validFrequency = this.getValidFrequency(
frequency, limits.min, limits.max
);
if (this.options.type === 'oscillator') {
this.oscillatorPlay(validFrequency);
}
};
/**
* Play oscillator instrument.
* @private
* @param {number} frequency - The frequency to play.
*/
Instrument.prototype.oscillatorPlay = function (frequency) {
if (!this.oscillatorStarted) {
this.oscillator.start();
this.oscillatorStarted = true;
}
this.oscillator.frequency.setValueAtTime(
frequency, H.audioContext.currentTime
);
};
/**
* Prepare instrument before playing. Resumes the audio context and starts the
* oscillator.
* @private
*/
Instrument.prototype.preparePlay = function () {
this.setGain(0.001);
if (H.audioContext.state === 'suspended') {
H.audioContext.resume();
}
if (this.oscillator && !this.oscillatorStarted) {
this.oscillator.start();
this.oscillatorStarted = true;
}
};
/**
* Play the instrument according to options.
*
* @sample highcharts/sonification/instrument/
* Using Instruments directly
* @sample highcharts/sonification/instrument-advanced/
* Using callbacks for instrument parameters
*
* @function Highcharts.Instrument#play
*
* @param {Highcharts.InstrumentPlayOptionsObject} options
* Options for the playback of the instrument.
*/
Instrument.prototype.play = function (options) {
var instrument = this,
duration = options.duration || 0,
// Set a value, or if it is a function, set it continously as a timer.
// Pass in the value/function to set, the setter function, and any
// additional data to pass through to the setter function.
setOrStartTimer = function (value, setter, setterData) {
var target = options.duration,
currentDurationIx = 0,
callbackInterval = instrument.options.playCallbackInterval;
if (typeof value === 'function') {
var timer = setInterval(function () {
currentDurationIx++;
var curTime = currentDurationIx * callbackInterval / target;
if (curTime >= 1) {
instrument[setter](value(1), setterData);
clearInterval(timer);
} else {
instrument[setter](value(curTime), setterData);
}
}, callbackInterval);
instrument.playCallbackTimers.push(timer);
} else {
instrument[setter](value, setterData);
}
};
if (!instrument.id) {
// No audio support - do nothing
return;
}
// If the AudioContext is suspended we have to resume it before playing
if (
H.audioContext.state === 'suspended' ||
this.oscillator && !this.oscillatorStarted
) {
instrument.preparePlay();
// Try again in 10ms
setTimeout(function () {
instrument.play(options);
}, 10);
return;
}
// Clear any existing play timers
if (instrument.playCallbackTimers.length) {
instrument.clearPlayCallbackTimers();
}
// Clear any gain ramps
instrument.cancelGainRamp();
// Clear stop oscillator timer
if (instrument.stopOscillatorTimeout) {
clearTimeout(instrument.stopOscillatorTimeout);
delete instrument.stopOscillatorTimeout;
}
// If a note is playing right now, clear the stop timeout, and call the
// callback.
if (instrument.stopTimeout) {
clearTimeout(instrument.stopTimeout);
delete instrument.stopTimeout;
if (instrument.stopCallback) {
// We have a callback for the play we are interrupting. We do not
// allow this callback to start a new play, because that leads to
// chaos. We pass in 'cancelled' to indicate that this note did not
// finish, but still stopped.
instrument._play = instrument.play;
instrument.play = function () { };
instrument.stopCallback('cancelled');
instrument.play = instrument._play;
}
}
// Stop the note without fadeOut if the duration is too short to hear the
// note otherwise.
var immediate = duration < H.sonification.fadeOutDuration + 20;
// Stop the instrument after the duration of the note
instrument.stopCallback = options.onEnd;
var onStop = function () {
delete instrument.stopTimeout;
instrument.stop(immediate);
};
if (duration) {
instrument.stopTimeout = setTimeout(
onStop,
immediate ? duration :
duration - H.sonification.fadeOutDuration
);
// Play the note
setOrStartTimer(options.frequency, 'setFrequency', null, {
minFrequency: options.minFrequency,
maxFrequency: options.maxFrequency
});
// Set the volume and panning
setOrStartTimer(H.pick(options.volume, 1), 'setGain', 4); // Slight ramp
setOrStartTimer(H.pick(options.pan, 0), 'setPan');
} else {
// No note duration, so just stop immediately
onStop();
}
};
/**
* Mute an instrument that is playing. If the instrument is not currently
* playing, this function does nothing.
*
* @function Highcharts.Instrument#mute
*/
Instrument.prototype.mute = function () {
this.setGain(0.0001, H.sonification.fadeOutDuration * 0.8);
};
/**
* Stop the instrument playing.
*
* @function Highcharts.Instrument#stop
*
* @param {boolean} immediately
* Whether to do the stop immediately or fade out.
*
* @param {Function} onStopped
* Callback function to be called when the stop is completed.
*
* @param {*} callbackData
* Data to send to the onEnd callback functions.
*/
Instrument.prototype.stop = function (immediately, onStopped, callbackData) {
var instr = this,
reset = function () {
// Remove timeout reference
if (instr.stopOscillatorTimeout) {
delete instr.stopOscillatorTimeout;
}
// The oscillator may have stopped in the meantime here, so allow
// this function to fail if so.
try {
instr.oscillator.stop();
} catch (e) {}
instr.oscillator.disconnect(instr.gainNode);
// We need a new oscillator in order to restart it
instr.initOscillator(instr.options.oscillator);
// Done stopping, call the callback from the stop
if (onStopped) {
onStopped(callbackData);
}
// Call the callback for the play we finished
if (instr.stopCallback) {
instr.stopCallback(callbackData);
}
};
// Clear any existing timers
if (instr.playCallbackTimers.length) {
instr.clearPlayCallbackTimers();
}
if (instr.stopTimeout) {
clearTimeout(instr.stopTimeout);
}
if (immediately) {
instr.setGain(0);
reset();
} else {
instr.mute();
// Stop the oscillator after the mute fade-out has finished
instr.stopOscillatorTimeout =
setTimeout(reset, H.sonification.fadeOutDuration + 100);
}
};
return Instrument;
}(Highcharts));
var frequencies = (function () {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* List of musical frequencies from C0 to C8.
*
* License: www.highcharts.com/license
*
* */
var frequencies = [
16.351597831287414, // C0
17.323914436054505,
18.354047994837977,
19.445436482630058,
20.601722307054366,
21.826764464562746,
23.12465141947715,
24.499714748859326,
25.956543598746574,
27.5, // A0
29.13523509488062,
30.86770632850775,
32.70319566257483, // C1
34.64782887210901,
36.70809598967594,
38.890872965260115,
41.20344461410875,
43.653528929125486,
46.2493028389543,
48.999429497718666,
51.91308719749314,
55, // A1
58.27047018976124,
61.7354126570155,
65.40639132514966, // C2
69.29565774421802,
73.41619197935188,
77.78174593052023,
82.4068892282175,
87.30705785825097,
92.4986056779086,
97.99885899543733,
103.82617439498628,
110, // A2
116.54094037952248,
123.47082531403103,
130.8127826502993, // C3
138.59131548843604,
146.8323839587038,
155.56349186104046,
164.81377845643496,
174.61411571650194,
184.9972113558172,
195.99771799087463,
207.65234878997256,
220, // A3
233.08188075904496,
246.94165062806206,
261.6255653005986, // C4
277.1826309768721,
293.6647679174076,
311.1269837220809,
329.6275569128699,
349.2282314330039,
369.9944227116344,
391.99543598174927,
415.3046975799451,
440, // A4
466.1637615180899,
493.8833012561241,
523.2511306011972, // C5
554.3652619537442,
587.3295358348151,
622.2539674441618,
659.2551138257398,
698.4564628660078,
739.9888454232688,
783.9908719634985,
830.6093951598903,
880, // A5
932.3275230361799,
987.7666025122483,
1046.5022612023945, // C6
1108.7305239074883,
1174.6590716696303,
1244.5079348883237,
1318.5102276514797,
1396.9129257320155,
1479.9776908465376,
1567.981743926997,
1661.2187903197805,
1760, // A6
1864.6550460723597,
1975.533205024496,
2093.004522404789, // C7
2217.4610478149766,
2349.31814333926,
2489.0158697766474,
2637.02045530296,
2793.825851464031,
2959.955381693075,
3135.9634878539946,
3322.437580639561,
3520, // A7
3729.3100921447194,
3951.066410048992,
4186.009044809578 // C8
];
return frequencies;
}());
var utilities = (function (musicalFrequencies) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Utility functions for sonification.
*
* License: www.highcharts.com/license
*
* */
/**
* The SignalHandler class. Stores signal callbacks (event handlers), and
* provides an interface to register them, and emit signals. The word "event" is
* not used to avoid confusion with TimelineEvents.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.SignalHandler
*
* @param {Array<string>} supportedSignals
* List of supported signal names.
*/
function SignalHandler(supportedSignals) {
this.init(supportedSignals || []);
}
SignalHandler.prototype.init = function (supportedSignals) {
this.supportedSignals = supportedSignals;
this.signals = {};
};
/**
* Register a set of signal callbacks with this SignalHandler.
* Multiple signal callbacks can be registered for the same signal.
* @private
* @param {object} signals - An object that contains a mapping from the signal
* name to the callbacks. Only supported events are considered.
*/
SignalHandler.prototype.registerSignalCallbacks = function (signals) {
var signalHandler = this;
signalHandler.supportedSignals.forEach(function (supportedSignal) {
if (signals[supportedSignal]) {
(
signalHandler.signals[supportedSignal] =
signalHandler.signals[supportedSignal] || []
).push(
signals[supportedSignal]
);
}
});
};
/**
* Clear signal callbacks, optionally by name.
* @private
* @param {Array<string>} [signalNames] - A list of signal names to clear. If
* not supplied, all signal callbacks are removed.
*/
SignalHandler.prototype.clearSignalCallbacks = function (signalNames) {
var signalHandler = this;
if (signalNames) {
signalNames.forEach(function (signalName) {
if (signalHandler.signals[signalName]) {
delete signalHandler.signals[signalName];
}
});
} else {
signalHandler.signals = {};
}
};
/**
* Emit a signal. Does nothing if the signal does not exist, or has no
* registered callbacks.
* @private
* @param {string} signalNames - Name of signal to emit.
* @param {*} data - Data to pass to the callback.
*/
SignalHandler.prototype.emitSignal = function (signalName, data) {
var retval;
if (this.signals[signalName]) {
this.signals[signalName].forEach(function (handler) {
var result = handler(data);
retval = result !== undefined ? result : retval;
});
}
return retval;
};
var utilities = {
// List of musical frequencies from C0 to C8
musicalFrequencies: musicalFrequencies,
// SignalHandler class
SignalHandler: SignalHandler,
/**
* Get a musical scale by specifying the semitones from 1-12 to include.
* 1: C, 2: C#, 3: D, 4: D#, 5: E, 6: F,
* 7: F#, 8: G, 9: G#, 10: A, 11: Bb, 12: B
* @private
* @param {Array<number>} semitones - Array of semitones from 1-12 to
* include in the scale. Duplicate entries are ignored.
* @return {Array<number>} Array of frequencies from C0 to C8 that are
* included in this scale.
*/
getMusicalScale: function (semitones) {
return musicalFrequencies.filter(function (freq, i) {
var interval = i % 12 + 1;
return semitones.some(function (allowedInterval) {
return allowedInterval === interval;
});
});
},
/**
* Calculate the extreme values in a chart for a data prop.
* @private
* @param {Highcharts.Chart} chart - The chart
* @param {string} prop - The data prop to find extremes for
* @return {object} Object with min and max properties
*/
calculateDataExtremes: function (chart, prop) {
return chart.series.reduce(function (extremes, series) {
// We use cropped points rather than series.data here, to allow
// users to zoom in for better fidelity.
series.points.forEach(function (point) {
var val = point[prop] !== undefined ?
point[prop] : point.options[prop];
extremes.min = Math.min(extremes.min, val);
extremes.max = Math.max(extremes.max, val);
});
return extremes;
}, {
min: Infinity,
max: -Infinity
});
},
/**
* Translate a value on a virtual axis. Creates a new, virtual, axis with a
* min and max, and maps the relative value onto this axis.
* @private
* @param {number} value - The relative data value to translate.
* @param {object} dataExtremes - The possible extremes for this value.
* @param {object} limits - Limits for the virtual axis.
* @return {number} The value mapped to the virtual axis.
*/
virtualAxisTranslate: function (value, dataExtremes, limits) {
var lenValueAxis = dataExtremes.max - dataExtremes.min,
lenVirtualAxis = limits.max - limits.min,
virtualAxisValue = limits.min +
lenVirtualAxis * (value - dataExtremes.min) / lenValueAxis;
return lenValueAxis > 0 ?
Math.max(Math.min(virtualAxisValue, limits.max), limits.min) :
limits.min;
}
};
return utilities;
}(frequencies));
var instruments = (function (Instrument, utilities) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Instrument definitions for sonification module.
*
* License: www.highcharts.com/license
*
* */
var instruments = {};
['sine', 'square', 'triangle', 'sawtooth'].forEach(function (waveform) {
// Add basic instruments
instruments[waveform] = new Instrument({
oscillator: { waveformShape: waveform }
});
// Add musical instruments
instruments[waveform + 'Musical'] = new Instrument({
allowedFrequencies: utilities.musicalFrequencies,
oscillator: { waveformShape: waveform }
});
// Add scaled instruments
instruments[waveform + 'Major'] = new Instrument({
allowedFrequencies: utilities.getMusicalScale([1, 3, 5, 6, 8, 10, 12]),
oscillator: { waveformShape: waveform }
});
});
return instruments;
}(Instrument, utilities));
var Earcon = (function (H) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Earcons for the sonification module in Highcharts.
*
* License: www.highcharts.com/license
*
* */
/**
* Define an Instrument and the options for playing it.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconInstrument
*//**
* An instrument instance or the name of the instrument in the
* Highcharts.sonification.instruments map.
* @name Highcharts.EarconInstrument#instrument
* @type {Highcharts.Instrument|String}
*//**
* The options to pass to Instrument.play.
* @name Highcharts.EarconInstrument#playOptions
* @type {object}
*/
/**
* Options for an Earcon.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconOptionsObject
*//**
* The instruments and their options defining this earcon.
* @name Highcharts.EarconOptionsObject#instruments
* @type {Array<Highcharts.EarconInstrument>}
*//**
* The unique ID of the Earcon. Generated if not supplied.
* @name Highcharts.EarconOptionsObject#id
* @type {string|undefined}
*//**
* Global panning of all instruments. Overrides all panning on individual
* instruments. Can be a number between -1 and 1.
* @name Highcharts.EarconOptionsObject#pan
* @type {number|undefined}
*//**
* Master volume for all instruments. Volume settings on individual instruments
* can still be used for relative volume between the instruments. This setting
* does not affect volumes set by functions in individual instruments. Can be a
* number between 0 and 1. Defaults to 1.
* @name Highcharts.EarconOptionsObject#volume
* @type {number|undefined}
*//**
* Callback function to call when earcon has finished playing.
* @name Highcharts.EarconOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The Earcon class. Earcon objects represent a certain sound consisting of
* one or more instruments playing a predefined sound.
*
* @sample highcharts/sonification/earcon/
* Using earcons directly
*
* @requires module:modules/sonification
*
* @class
* @name Highcharts.Earcon
*
* @param {Highcharts.EarconOptionsObject} options
* Options for the Earcon instance.
*/
function Earcon(options) {
this.init(options || {});
}
Earcon.prototype.init = function (options) {
this.options = options;
if (!this.options.id) {
this.options.id = this.id = H.uniqueKey();
}
this.instrumentsPlaying = {};
};
/**
* Play the earcon, optionally overriding init options.
*
* @sample highcharts/sonification/earcon/
* Using earcons directly
*
* @function Highcharts.Earcon#sonify
*
* @param {Highcharts.EarconOptionsObject} options
* Override existing options.
*/
Earcon.prototype.sonify = function (options) {
var playOptions = H.merge(this.options, options);
// Find master volume/pan settings
var masterVolume = H.pick(playOptions.volume, 1),
masterPan = playOptions.pan,
earcon = this,
playOnEnd = options && options.onEnd,
masterOnEnd = earcon.options.onEnd;
// Go through the instruments and play them
playOptions.instruments.forEach(function (opts) {
var instrument = typeof opts.instrument === 'string' ?
H.sonification.instruments[opts.instrument] : opts.instrument,
instrumentOpts = H.merge(opts.playOptions),
instrOnEnd,
instrumentCopy,
copyId;
if (instrument && instrument.play) {
if (opts.playOptions) {
// Handle master pan/volume
if (typeof opts.playOptions.volume !== 'function') {
instrumentOpts.volume = H.pick(masterVolume, 1) *
H.pick(opts.playOptions.volume, 1);
}
instrumentOpts.pan = H.pick(masterPan, instrumentOpts.pan);
// Handle onEnd
instrOnEnd = instrumentOpts.onEnd;
instrumentOpts.onEnd = function () {
delete earcon.instrumentsPlaying[copyId];
if (instrOnEnd) {
instrOnEnd.apply(this, arguments);
}
if (!Object.keys(earcon.instrumentsPlaying).length) {
if (playOnEnd) {
playOnEnd.apply(this, arguments);
}
if (masterOnEnd) {
masterOnEnd.apply(this, arguments);
}
}
};
// Play the instrument. Use a copy so we can play multiple at
// the same time.
instrumentCopy = instrument.copy();
copyId = instrumentCopy.id;
earcon.instrumentsPlaying[copyId] = instrumentCopy;
instrumentCopy.play(instrumentOpts);
}
} else {
H.error(30);
}
});
};
/**
* Cancel any current sonification of the Earcon. Calls onEnd functions.
*
* @function Highcharts.Earcon#cancelSonify
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the earcon is
* cancelled synchronously.
*/
Earcon.prototype.cancelSonify = function (fadeOut) {
var playing = this.instrumentsPlaying,
instrIds = playing && Object.keys(playing);
if (instrIds && instrIds.length) {
instrIds.forEach(function (instr) {
playing[instr].stop(!fadeOut, null, 'cancelled');
});
this.instrumentsPlaying = {};
}
};
return Earcon;
}(Highcharts));
var pointSonifyFunctions = (function (H, utilities) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Code for sonifying single points.
*
* License: www.highcharts.com/license
*
* */
/**
* Define the parameter mapping for an instrument.
*
* @requires module:modules/sonification
*
* @interface Highcharts.PointInstrumentMappingObject
*//**
* Define the volume of the instrument. This can be a string with a data
* property name, e.g. `'y'`, in which case this data property is used to define
* the volume relative to the `y`-values of the other points. A higher `y` value
* would then result in a higher volume. This option can also be a fixed number
* or a function. If it is a function, this function is called in regular
* intervals while the note is playing. It receives three arguments: The point,
* the dataExtremes, and the current relative time - where 0 is the beginning of
* the note and 1 is the end. The function should return the volume of the note
* as a number between 0 and 1.
* @name Highcharts.PointInstrumentMappingObject#volume
* @type {string|number|Function}
*//**
* Define the duration of the notes for this instrument. This can be a string
* with a data property name, e.g. `'y'`, in which case this data property is
* used to define the duration relative to the `y`-values of the other points. A
* higher `y` value would then result in a longer duration. This option can also
* be a fixed number or a function. If it is a function, this function is called
* once before the note starts playing, and should return the duration in
* milliseconds. It receives two arguments: The point, and the dataExtremes.
* @name Highcharts.PointInstrumentMappingObject#duration
* @type {string|number|Function}
*//**
* Define the panning of the instrument. This can be a string with a data
* property name, e.g. `'x'`, in which case this data property is used to define
* the panning relative to the `x`-values of the other points. A higher `x`
* value would then result in a higher panning value (panned further to the
* right). This option can also be a fixed number or a function. If it is a
* function, this function is called in regular intervals while the note is
* playing. It receives three arguments: The point, the dataExtremes, and the
* current relative time - where 0 is the beginning of the note and 1 is the
* end. The function should return the panning of the note as a number between
* -1 and 1.
* @name Highcharts.PointInstrumentMappingObject#pan
* @type {string|number|Function|undefined}
*//**
* Define the frequency of the instrument. This can be a string with a data
* property name, e.g. `'y'`, in which case this data property is used to define
* the frequency relative to the `y`-values of the other points. A higher `y`
* value would then result in a higher frequency. This option can also be a
* fixed number or a function. If it is a function, this function is called in
* regular intervals while the note is playing. It receives three arguments:
* The point, the dataExtremes, and the current relative time - where 0 is the
* beginning of the note and 1 is the end. The function should return the
* frequency of the note as a number (in Hz).
* @name Highcharts.PointInstrumentMappingObject#frequency
* @type {string|number|Function}
*/
/**
* @requires module:modules/sonification
*
* @interface Highcharts.PointInstrumentOptionsObject
*//**
* The minimum duration for a note when using a data property for duration. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.duration. Defaults to 20.
* @name Highcharts.PointInstrumentOptionsObject#minDuration
* @type {number|undefined}
*//**
* The maximum duration for a note when using a data property for duration. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.duration. Defaults to 2000.
* @name Highcharts.PointInstrumentOptionsObject#maxDuration
* @type {number|undefined}
*//**
* The minimum pan value for a note when using a data property for panning. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.pan. Defaults to -1 (fully left).
* @name Highcharts.PointInstrumentOptionsObject#minPan
* @type {number|undefined}
*//**
* The maximum pan value for a note when using a data property for panning. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.pan. Defaults to 1 (fully right).
* @name Highcharts.PointInstrumentOptionsObject#maxPan
* @type {number|undefined}
*//**
* The minimum volume for a note when using a data property for volume. Can be
* overridden by using either a fixed number or a function for
* instrumentMapping.volume. Defaults to 0.1.
* @name Highcharts.PointInstrumentOptionsObject#minVolume
* @type {number|undefined}
*//**
* The maximum volume for a note when using a data property for volume. Can be
* overridden by using either a fixed number or a function for
* instrumentMapping.volume. Defaults to 1.
* @name Highcharts.PointInstrumentOptionsObject#maxVolume
* @type {number|undefined}
*//**
* The minimum frequency for a note when using a data property for frequency.
* Can be overridden by using either a fixed number or a function for
* instrumentMapping.frequency. Defaults to 220.
* @name Highcharts.PointInstrumentOptionsObject#minFrequency
* @type {number|undefined}
*//**
* The maximum frequency for a note when using a data property for frequency.
* Can be overridden by using either a fixed number or a function for
* instrumentMapping.frequency. Defaults to 2200.
* @name Highcharts.PointInstrumentOptionsObject#maxFrequency
* @type {number|undefined}
*/
/**
* An instrument definition for a point, specifying the instrument to play and
* how to play it.
*
* @interface Highcharts.PointInstrumentObject
*//**
* An Instrument instance or the name of the instrument in the
* Highcharts.sonification.instruments map.
* @name Highcharts.PointInstrumentObject#instrument
* @type {Highcharts.Instrument|string}
*//**
* Mapping of instrument parameters for this instrument.
* @name Highcharts.PointInstrumentObject#instrumentMapping
* @type {Highcharts.PointInstrumentMappingObject}
*//**
* Options for this instrument.
* @name Highcharts.PointInstrumentObject#instrumentOptions
* @type {Highcharts.PointInstrumentOptionsObject|undefined}
*//**
* Callback to call when the instrument has stopped playing.
* @name Highcharts.PointInstrumentObject#onEnd
* @type {Function|undefined}
*/
/**
* Options for sonifying a point.
* @interface Highcharts.PointSonifyOptionsObject
*//**
* The instrument definitions for this point.
* @name Highcharts.PointSonifyOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>}
*//**
* Optionally provide the minimum/maximum values for the points. If this is not
* supplied, it is calculated from the points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.PointSonifyOptionsObject#dataExtremes
* @type {object|undefined}
*//**
* Callback called when the sonification has finished.
* @name Highcharts.PointSonifyOptionsObject#onEnd
* @type {Function|undefined}
*/
// Defaults for the instrument options
// NOTE: Also change defaults in Highcharts.PointInstrumentOptionsObject if
// making changes here.
var defaultInstrumentOptions = {
minDuration: 20,
maxDuration: 2000,
minVolume: 0.1,
maxVolume: 1,
minPan: -1,
maxPan: 1,
minFrequency: 220,
maxFrequency: 2200
};
/**
* Sonify a single point.
*
* @sample highcharts/sonification/point-basic/
* Click on points to sonify
* @sample highcharts/sonification/point-advanced/
* Sonify bubbles
*
* @requires module:modules/sonification
*
* @function Highcharts.Point#sonify
*
* @param {Highcharts.PointSonifyOptionsObject} options
* Options for the sonification of the point.
*/
function pointSonify(options) {
var point = this,
chart = point.series.chart,
dataExtremes = options.dataExtremes || {},
// Get the value to pass to instrument.play from the mapping value
// passed in.
getMappingValue = function (
value, makeFunction, allowedExtremes, allowedValues
) {
// Fixed number, just use that
if (typeof value === 'number' || value === undefined) {
return value;
}
// Function. Return new function if we try to use callback,
// otherwise call it now and return result.
if (typeof value === 'function') {
return makeFunction ?
function (time) {
return value(point, dataExtremes, time);
} :
value(point, dataExtremes);
}
// String, this is a data prop.
if (typeof value === 'string') {
// Find data extremes if we don't have them
dataExtremes[value] = dataExtremes[value] ||
utilities.calculateDataExtremes(
point.series.chart, value
);
// Find the value
return utilities.virtualAxisTranslate(
H.pick(point[value], point.options[value]),
dataExtremes[value],
allowedExtremes,
allowedValues
);
}
};
// Register playing point on chart
chart.sonification.currentlyPlayingPoint = point;
// Keep track of instruments playing
point.sonification = point.sonification || {};
point.sonification.instrumentsPlaying =
point.sonification.instrumentsPlaying || {};
// Register signal handler for the point
var signalHandler = point.sonification.signalHandler =
point.sonification.signalHandler ||
new utilities.SignalHandler(['onEnd']);
signalHandler.clearSignalCallbacks();
signalHandler.registerSignalCallbacks({ onEnd: options.onEnd });
// If we have a null point or invisible point, just return
if (point.isNull || !point.visible || !point.series.visible) {
signalHandler.emitSignal('onEnd');
return;
}
// Go through instruments and play them
options.instruments.forEach(function (instrumentDefinition) {
var instrument = typeof instrumentDefinition.instrument === 'string' ?
H.sonification.instruments[instrumentDefinition.instrument] :
instrumentDefinition.instrument,
mapping = instrumentDefinition.instrumentMapping || {},
extremes = H.merge(
defaultInstrumentOptions,
instrumentDefinition.instrumentOptions
),
id = instrument.id,
onEnd = function (cancelled) {
// Instrument on end
if (instrumentDefinition.onEnd) {
instrumentDefinition.onEnd.apply(this, arguments);
}
// Remove currently playing point reference on chart
if (
chart.sonification &&
chart.sonification.currentlyPlayingPoint
) {
delete chart.sonification.currentlyPlayingPoint;
}
// Remove reference from instruments playing
if (
point.sonification && point.sonification.instrumentsPlaying
) {
delete point.sonification.instrumentsPlaying[id];
// This was the last instrument?
if (
!Object.keys(
point.sonification.instrumentsPlaying
).length
) {
signalHandler.emitSignal('onEnd', cancelled);
}
}
};
// Play the note on the instrument
if (instrument && instrument.play) {
point.sonification.instrumentsPlaying[instrument.id] = instrument;
instrument.play({
frequency: getMappingValue(
mapping.frequency,
true,
{ min: extremes.minFrequency, max: extremes.maxFrequency }
),
duration: getMappingValue(
mapping.duration,
false,
{ min: extremes.minDuration, max: extremes.maxDuration }
),
pan: getMappingValue(
mapping.pan,
true,
{ min: extremes.minPan, max: extremes.maxPan }
),
volume: getMappingValue(
mapping.volume,
true,
{ min: extremes.minVolume, max: extremes.maxVolume }
),
onEnd: onEnd,
minFrequency: extremes.minFrequency,
maxFrequency: extremes.maxFrequency
});
} else {
H.error(30);
}
});
}
/**
* Cancel sonification of a point. Calls onEnd functions.
*
* @requires module:modules/sonification
*
* @function Highcharts.Point#cancelSonify
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the points are
* cancelled synchronously.
*/
function pointCancelSonify(fadeOut) {
var playing = this.sonification && this.sonification.instrumentsPlaying,
instrIds = playing && Object.keys(playing);
if (instrIds && instrIds.length) {
instrIds.forEach(function (instr) {
playing[instr].stop(!fadeOut, null, 'cancelled');
});
this.sonification.instrumentsPlaying = {};
this.sonification.signalHandler.emitSignal('onEnd', 'cancelled');
}
}
var pointSonifyFunctions = {
pointSonify: pointSonify,
pointCancelSonify: pointCancelSonify
};
return pointSonifyFunctions;
}(Highcharts, utilities));
var chartSonifyFunctions = (function (H, utilities) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Sonification functions for chart/series.
*
* License: www.highcharts.com/license
*
* */
/**
* An Earcon configuration, specifying an Earcon and when to play it.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconConfiguration
*//**
* An Earcon instance.
* @name Highcharts.EarconConfiguration#earcon
* @type {Highcharts.Earcon}
*//**
* The ID of the point to play the Earcon on.
* @name Highcharts.EarconConfiguration#onPoint
* @type {string|undefined}
*//**
* A function to determine whether or not to play this earcon on a point. The
* function is called for every point, receiving that point as parameter. It
* should return either a boolean indicating whether or not to play the earcon,
* or a new Earcon instance - in which case the new Earcon will be played.
* @name Highcharts.EarconConfiguration#condition
* @type {Function|undefined}
*/
/**
* Options for sonifying a series.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonifySeriesOptionsObject
*//**
* The duration for playing the points. Note that points might continue to play
* after the duration has passed, but no new points will start playing.
* @name Highcharts.SonifySeriesOptionsObject#duration
* @type {number}
*//**
* The axis to use for when to play the points. Can be a string with a data
* property (e.g. `x`), or a function. If it is a function, this function
* receives the point as argument, and should return a numeric value. The points
* with the lowest numeric values are then played first, and the time between
* points will be proportional to the distance between the numeric values.
* @name Highcharts.SonifySeriesOptionsObject#pointPlayTime
* @type {string|Function}
*//**
* The instrument definitions for the points in this series.
* @name Highcharts.SonifySeriesOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>}
*//**
* Earcons to add to the series.
* @name Highcharts.SonifySeriesOptionsObject#earcons
* @type {Array<Highcharts.EarconConfiguration>|undefined}
*//**
* Optionally provide the minimum/maximum data values for the points. If this is
* not supplied, it is calculated from all points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.SonifySeriesOptionsObject#dataExtremes
* @type {object|undefined}
*//**
* Callback before a point is played.
* @name Highcharts.SonifySeriesOptionsObject#onPointStart
* @type {Function|undefined}
*//**
* Callback after a point has finished playing.
* @name Highcharts.SonifySeriesOptionsObject#onPointEnd
* @type {Function|undefined}
*//**
* Callback after the series has played.
* @name Highcharts.SonifySeriesOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* Get the relative time value of a point.
* @private
* @param {Highcharts.Point} point - The point.
* @param {Function|string} timeProp - The time axis data prop or the time
* function.
* @return {number} The time value.
*/
function getPointTimeValue(point, timeProp) {
return typeof timeProp === 'function' ?
timeProp(point) :
H.pick(point[timeProp], point.options[timeProp]);
}
/**
* Get the time extremes of this series. This is handled outside of the
* dataExtremes, as we always want to just sonify the visible points, and we
* always want the extremes to be the extremes of the visible points.
* @private
* @param {Highcharts.Series} series - The series to compute on.
* @param {Function|string} timeProp - The time axis data prop or the time
* function.
* @return {object} Object with min/max extremes for the time values.
*/
function getTimeExtremes(series, timeProp) {
// Compute the extremes from the visible points.
return series.points.reduce(function (acc, point) {
var value = getPointTimeValue(point, timeProp);
acc.min = Math.min(acc.min, value);
acc.max = Math.max(acc.max, value);
return acc;
}, {
min: Infinity,
max: -Infinity
});
}
/**
* Calculate value extremes for used instrument data properties.
* @private
* @param {Highcharts.Chart} chart - The chart to calculate extremes from.
* @param {Array<Highcharts.PointInstrumentObject>} instruments - The instrument
* definitions used.
* @param {object} [dataExtremes] - Predefined extremes for each data prop.
* @return {object} New extremes with data properties mapped to min/max objects.
*/
function getExtremesForInstrumentProps(chart, instruments, dataExtremes) {
return (
instruments || []
).reduce(function (newExtremes, instrumentDefinition) {
Object.keys(instrumentDefinition.instrumentMapping || {}).forEach(
function (instrumentParameter) {
var value = instrumentDefinition.instrumentMapping[
instrumentParameter
];
if (typeof value === 'string' && !newExtremes[value]) {
// This instrument parameter is mapped to a data prop.
// If we don't have predefined data extremes, find them.
newExtremes[value] = utilities.calculateDataExtremes(
chart, value
);
}
}
);
return newExtremes;
}, H.merge(dataExtremes));
}
/**
* Get earcons for the point if there are any.
* @private
* @param {Highcharts.Point} point - The point to find earcons for.
* @param {Array<Highcharts.EarconConfiguration>} earconDefinitions - Earcons to
* check.
* @return {Array<Highcharts.Earcon>} Array of earcons to be played with this
* point.
*/
function getPointEarcons(point, earconDefinitions) {
return earconDefinitions.reduce(
function (earcons, earconDefinition) {
var cond,
earcon = earconDefinition.earcon;
if (earconDefinition.condition) {
// We have a condition. This overrides onPoint
cond = earconDefinition.condition(point);
if (cond instanceof H.sonification.Earcon) {
// Condition returned an earcon
earcons.push(cond);
} else if (cond) {
// Condition returned true
earcons.push(earcon);
}
} else if (
earconDefinition.onPoint &&
point.id === earconDefinition.onPoint
) {
// We have earcon onPoint
earcons.push(earcon);
}
return earcons;
}, []
);
}
/**
* Utility function to get a new list of instrument options where all the
* instrument references are copies.
* @private
* @param {Array<Highcharts.PointInstrumentObject>} instruments - The instrument
* options.
* @return {Array<Highcharts.PointInstrumentObject>} Array of copied instrument
* options.
*/
function makeInstrumentCopies(instruments) {
return instruments.map(function (instrumentDef) {
var instrument = instrumentDef.instrument,
copy = (typeof instrument === 'string' ?
H.sonification.instruments[instrument] :
instrument).copy();
return H.merge(instrumentDef, { instrument: copy });
});
}
/**
* Create a TimelinePath from a series. Takes the same options as seriesSonify.
* To intuitively allow multiple series to play simultaneously we make copies of
* the instruments for each series.
* @private
* @param {Highcharts.Series} series - The series to build from.
* @param {object} options - The options for building the TimelinePath.
* @return {Highcharts.TimelinePath} A timeline path with events.
*/
function buildTimelinePathFromSeries(series, options) {
// options.timeExtremes is internal and used so that the calculations from
// chart.sonify can be reused.
var timeExtremes = options.timeExtremes || getTimeExtremes(
series, options.pointPlayTime, options.dataExtremes
),
// Get time offset for a point, relative to duration
pointToTime = function (point) {
return utilities.virtualAxisTranslate(
getPointTimeValue(point, options.pointPlayTime),
timeExtremes,
{ min: 0, max: options.duration }
);
},
// Compute any data extremes that aren't defined yet
dataExtremes = getExtremesForInstrumentProps(
series.chart, options.instruments, options.dataExtremes
),
// Make copies of the instruments used for this series, to allow
// multiple series with the same instrument to play together
instruments = makeInstrumentCopies(options.instruments),
// Go through the points, convert to events, optionally add Earcons
timelineEvents = series.points.reduce(function (events, point) {
var earcons = getPointEarcons(point, options.earcons || []),
time = pointToTime(point);
return events.concat(
// Event object for point
new H.sonification.TimelineEvent({
eventObject: point,
time: time,
id: point.id,
playOptions: {
instruments: instruments,
dataExtremes: dataExtremes
}
}),
// Earcons
earcons.map(function (earcon) {
return new H.sonification.TimelineEvent({
eventObject: earcon,
time: time
});
})
);
}, []);
// Build the timeline path
return new H.sonification.TimelinePath({
events: timelineEvents,
onStart: function () {
if (options.onStart) {
options.onStart(series);
}
},
onEventStart: function (event) {
var eventObject = event.options && event.options.eventObject;
if (eventObject instanceof H.Point) {
// Check for hidden series
if (
!eventObject.series.visible &&
!eventObject.series.chart.series.some(function (series) {
return series.visible;
})
) {
// We have no visible series, stop the path.
event.timelinePath.timeline.pause();
event.timelinePath.timeline.resetCursor();
return false;
}
// Emit onPointStart
if (options.onPointStart) {
options.onPointStart(event, eventObject);
}
}
},
onEventEnd: function (eventData) {
var eventObject = eventData.event && eventData.event.options &&
eventData.event.options.eventObject;
if (eventObject instanceof H.Point && options.onPointEnd) {
options.onPointEnd(eventData.event, eventObject);
}
},
onEnd: function () {
if (options.onEnd) {
options.onEnd(series);
}
}
});
}
/**
* Sonify a series.
*
* @sample highcharts/sonification/series-basic/
* Click on series to sonify
* @sample highcharts/sonification/series-earcon/
* Series with earcon
* @sample highcharts/sonification/point-play-time/
* Play y-axis by time
* @sample highcharts/sonification/earcon-on-point/
* Earcon set on point
*
* @requires module:modules/sonification
*
* @function Highcharts.Series#sonify
*
* @param {Highcharts.SonifySeriesOptionsObject} options
* The options for sonifying this series.
*/
function seriesSonify(options) {
var timelinePath = buildTimelinePathFromSeries(this, options),
chartSonification = this.chart.sonification;
// Only one timeline can play at a time. If we want multiple series playing
// at the same time, use chart.sonify.
if (chartSonification.timeline) {
chartSonification.timeline.pause();
}
// Create new timeline for this series, and play it.
chartSonification.timeline = new H.sonification.Timeline({
paths: [timelinePath]
});
chartSonification.timeline.play();
}
/**
* Utility function to assemble options for creating a TimelinePath from a
* series when sonifying an entire chart.
* @private
* @param {Highcharts.Series} series - The series to return options for.
* @param {object} dataExtremes - Pre-calculated data extremes for the chart.
* @param {object} chartSonifyOptions - Options passed in to chart.sonify.
* @return {object} Options for buildTimelinePathFromSeries.
*/
function buildSeriesOptions(series, dataExtremes, chartSonifyOptions) {
var seriesOptions = chartSonifyOptions.seriesOptions || {};
return H.merge(
{
// Calculated dataExtremes for chart
dataExtremes: dataExtremes,
// We need to get timeExtremes for each series. We pass this
// in when building the TimelinePath objects to avoid
// calculating twice.
timeExtremes: getTimeExtremes(
series, chartSonifyOptions.pointPlayTime
),
// Some options we just pass on
instruments: chartSonifyOptions.instruments,
onStart: chartSonifyOptions.onSeriesStart,
onEnd: chartSonifyOptions.onSeriesEnd,
earcons: chartSonifyOptions.earcons
},
// Merge in the specific series options by ID
H.isArray(seriesOptions) ? (
H.find(seriesOptions, function (optEntry) {
return optEntry.id === H.pick(series.id, series.options.id);
}) || {}
) : seriesOptions,
{
// Forced options
pointPlayTime: chartSonifyOptions.pointPlayTime
}
);
}
/**
* Utility function to normalize the ordering of timeline paths when sonifying
* a chart.
* @private
* @param {string|Array<string|Highcharts.Earcon|Array<string|Highcharts.Earcon>>} orderOptions -
* Order options for the sonification.
* @param {Highcharts.Chart} chart - The chart we are sonifying.
* @param {Function} seriesOptionsCallback - A function that takes a series as
* argument, and returns the series options for that series to be used with
* buildTimelinePathFromSeries.
* @return {Array<object|Array<object|Highcharts.TimelinePath>>} If order is
* sequential, we return an array of objects to create series paths from. If
* order is simultaneous we return an array of an array with the same. If there
* is a custom order, we return an array of arrays of either objects (for
* series) or TimelinePaths (for earcons and delays).
*/
function buildPathOrder(orderOptions, chart, seriesOptionsCallback) {
var order;
if (orderOptions === 'sequential' || orderOptions === 'simultaneous') {
// Just add the series from the chart
order = chart.series.reduce(function (seriesList, series) {
if (series.visible) {
seriesList.push({
series: series,
seriesOptions: seriesOptionsCallback(series)
});
}
return seriesList;
}, []);
// If order is simultaneous, group all series together
if (orderOptions === 'simultaneous') {
order = [order];
}
} else {
// We have a specific order, and potentially custom items - like
// earcons or silent waits.
order = orderOptions.reduce(function (orderList, orderDef) {
// Return set of items to play simultaneously. Could be only one.
var simulItems = H.splat(orderDef).reduce(function (items, item) {
var itemObject;
// Is this item a series ID?
if (typeof item === 'string') {
var series = chart.get(item);
if (series.visible) {
itemObject = {
series: series,
seriesOptions: seriesOptionsCallback(series)
};
}
// Is it an earcon? If so, just create the path.
} else if (item instanceof H.sonification.Earcon) {
// Path with a single event
itemObject = new H.sonification.TimelinePath({
events: [new H.sonification.TimelineEvent({
eventObject: item
})]
});
// Is this item a silent wait? If so, just create the path.
} if (item.silentWait) {
itemObject = new H.sonification.TimelinePath({
silentWait: item.silentWait
});
}
// Add to items to play simultaneously
if (itemObject) {
items.push(itemObject);
}
return items;
}, []);
// Add to order list
if (simulItems.length) {
orderList.push(simulItems);
}
return orderList;
}, []);
}
return order;
}
/**
* Utility function to add a silent wait after all series.
* @private
* @param {Array<object|Array<object|TimelinePath>>} order - The order of items.
* @param {number} wait - The wait in milliseconds to add.
* @return {Array<object|Array<object|TimelinePath>>} The order with waits inserted.
*/
function addAfterSeriesWaits(order, wait) {
if (!wait) {
return order;
}
return order.reduce(function (newOrder, orderDef, i) {
var simultaneousPaths = H.splat(orderDef);
newOrder.push(simultaneousPaths);
// Go through the simultaneous paths and see if there is a series there
if (
i < order.length - 1 && // Do not add wait after last series
simultaneousPaths.some(function (item) {
return item.series;
})
) {
// We have a series, meaning we should add a wait after these
// paths have finished.
newOrder.push(new H.sonification.TimelinePath({
silentWait: wait
}));
}
return newOrder;
}, []);
}
/**
* Utility function to find the total amout of wait time in the TimelinePaths.
* @private
* @param {Array<object|Array<object|TimelinePath>>} order - The order of
* TimelinePaths/items.
* @return {number} The total time in ms spent on wait paths between playing.
*/
function getWaitTime(order) {
return order.reduce(function (waitTime, orderDef) {
var def = H.splat(orderDef);
return waitTime + (
def.length === 1 && def[0].options && def[0].options.silentWait || 0
);
}, 0);
}
/**
* Utility function to ensure simultaneous paths have start/end events at the
* same time, to sync them.
* @private
* @param {Array<Highcharts.TimelinePath>} paths - The paths to sync.
*/
function syncSimultaneousPaths(paths) {
// Find the extremes for these paths
var extremes = paths.reduce(function (extremes, path) {
var events = path.events;
if (events && events.length) {
extremes.min = Math.min(events[0].time, extremes.min);
extremes.max = Math.max(
events[events.length - 1].time, extremes.max
);
}
return extremes;
}, {
min: Infinity,
max: -Infinity
});
// Go through the paths and add events to make them fit the same timespan
paths.forEach(function (path) {
var events = path.events,
hasEvents = events && events.length,
eventsToAdd = [];
if (!(hasEvents && events[0].time <= extremes.min)) {
eventsToAdd.push(new H.sonification.TimelineEvent({
time: extremes.min
}));
}
if (!(hasEvents && events[events.length - 1].time >= extremes.max)) {
eventsToAdd.push(new H.sonification.TimelineEvent({
time: extremes.max
}));
}
if (eventsToAdd.length) {
path.addTimelineEvents(eventsToAdd);
}
});
}
/**
* Utility function to find the total duration span for all simul path sets
* that include series.
* @private
* @param {Array<object|Array<object|Highcharts.TimelinePath>>} order - The
* order of TimelinePaths/items.
* @return {number} The total time value span difference for all series.
*/
function getSimulPathDurationTotal(order) {
return order.reduce(function (durationTotal, orderDef) {
return durationTotal + H.splat(orderDef).reduce(
function (maxPathDuration, item) {
var timeExtremes = item.series && item.seriesOptions &&
item.seriesOptions.timeExtremes;
return timeExtremes ?
Math.max(
maxPathDuration, timeExtremes.max - timeExtremes.min
) : maxPathDuration;
}, 0);
}, 0);
}
/**
* Function to calculate the duration in ms for a series.
* @private
* @param {number} seriesValueDuration - The duration of the series in value
* difference.
* @param {number} totalValueDuration - The total duration of all (non
* simultaneous) series in value difference.
* @param {number} totalDurationMs - The desired total duration for all series
* in milliseconds.
* @return {number} The duration for the series in milliseconds.
*/
function getSeriesDurationMs(
seriesValueDuration, totalValueDuration, totalDurationMs
) {
// A series spanning the whole chart would get the full duration.
return utilities.virtualAxisTranslate(
seriesValueDuration,
{ min: 0, max: totalValueDuration },
{ min: 0, max: totalDurationMs }
);
}
/**
* Convert series building objects into paths and return a new list of
* TimelinePaths.
* @private
* @param {Array<object|Array<object|Highcharts.TimelinePath>>} order - The
* order list.
* @param {number} duration - Total duration to aim for in milliseconds.
* @return {Array<Array<Highcharts.TimelinePath>>} Array of TimelinePath objects
* to play.
*/
function buildPathsFromOrder(order, duration) {
// Find time used for waits (custom or after series), and subtract it from
// available duration.
var totalAvailableDurationMs = Math.max(
duration - getWaitTime(order), 0
),
// Add up simultaneous path durations to find total value span duration
// of everything
totalUsedDuration = getSimulPathDurationTotal(order);
// Go through the order list and convert the items
return order.reduce(function (allPaths, orderDef) {
var simultaneousPaths = H.splat(orderDef).reduce(
function (simulPaths, item) {
if (item instanceof H.sonification.TimelinePath) {
// This item is already a path object
simulPaths.push(item);
} else if (item.series) {
// We have a series.
// We need to set the duration of the series
item.seriesOptions.duration =
item.seriesOptions.duration || getSeriesDurationMs(
item.seriesOptions.timeExtremes.max -
item.seriesOptions.timeExtremes.min,
totalUsedDuration,
totalAvailableDurationMs
);
// Add the path
simulPaths.push(buildTimelinePathFromSeries(
item.series,
item.seriesOptions
));
}
return simulPaths;
}, []
);
// Add in the simultaneous paths
allPaths.push(simultaneousPaths);
return allPaths;
}, []);
}
/**
* Options for sonifying a chart.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonifyChartOptionsObject
*//**
* Duration for sonifying the entire chart. The duration is distributed across
* the different series intelligently, but does not take earcons into account.
* It is also possible to set the duration explicitly per series, using
* `seriesOptions`. Note that points may continue to play after the duration has
* passed, but no new points will start playing.
* @name Highcharts.SonifyChartOptionsObject#duration
* @type {number}
*//**
* Define the order to play the series in. This can be given as a string, or an
* array specifying a custom ordering. If given as a string, valid values are
* `sequential` - where each series is played in order - or `simultaneous`,
* where all series are played at once. For custom ordering, supply an array as
* the order. Each element in the array can be either a string with a series ID,
* an Earcon object, or an object with a numeric `silentWait` property
* designating a number of milliseconds to wait before continuing. Each element
* of the array will be played in order. To play elements simultaneously, group
* the elements in an array.
* @name Highcharts.SonifyChartOptionsObject#order
* @type {string|Array<string|Highcharts.Earcon|Array<string|Highcharts.Earcon>>}
*//**
* The axis to use for when to play the points. Can be a string with a data
* property (e.g. `x`), or a function. If it is a function, this function
* receives the point as argument, and should return a numeric value. The points
* with the lowest numeric values are then played first, and the time between
* points will be proportional to the distance between the numeric values. This
* option can not be overridden per series.
* @name Highcharts.SonifyChartOptionsObject#pointPlayTime
* @type {string|Function}
*//**
* Milliseconds of silent waiting to add between series. Note that waiting time
* is considered part of the sonify duration.
* @name Highcharts.SonifyChartOptionsObject#afterSeriesWait
* @type {number|undefined}
*//**
* Options as given to `series.sonify` to override options per series. If the
* option is supplied as an array of options objects, the `id` property of the
* object should correspond to the series' id. If the option is supplied as a
* single object, the options apply to all series.
* @name Highcharts.SonifyChartOptionsObject#seriesOptions
* @type {Object|Array<object>|undefined}
*//**
* The instrument definitions for the points in this chart.
* @name Highcharts.SonifyChartOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>|undefined}
*//**
* Earcons to add to the chart. Note that earcons can also be added per series
* using `seriesOptions`.
* @name Highcharts.SonifyChartOptionsObject#earcons
* @type {Array<Highcharts.EarconConfiguration>|undefined}
*//**
* Optionally provide the minimum/maximum data values for the points. If this is
* not supplied, it is calculated from all points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.SonifyChartOptionsObject#dataExtremes
* @type {object|undefined}
*//**
* Callback before a series is played.
* @name Highcharts.SonifyChartOptionsObject#onSeriesStart
* @type {Function|undefined}
*//**
* Callback after a series has finished playing.
* @name Highcharts.SonifyChartOptionsObject#onSeriesEnd
* @type {Function|undefined}
*//**
* Callback after the chart has played.
* @name Highcharts.SonifyChartOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* Sonify a chart.
*
* @sample highcharts/sonification/chart-sequential/
* Sonify a basic chart
* @sample highcharts/sonification/chart-simultaneous/
* Sonify series simultaneously
* @sample highcharts/sonification/chart-custom-order/
* Custom defined order of series
* @sample highcharts/sonification/chart-earcon/
* Earcons on chart
* @sample highcharts/sonification/chart-events/
* Sonification events on chart
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#sonify
*
* @param {Highcharts.SonifyChartOptionsObject} options
* The options for sonifying this chart.
*/
function chartSonify(options) {
// Only one timeline can play at a time.
if (this.sonification.timeline) {
this.sonification.timeline.pause();
}
// Calculate data extremes for the props used
var dataExtremes = getExtremesForInstrumentProps(
this, options.instruments, options.dataExtremes
);
// Figure out ordering of series and custom paths
var order = buildPathOrder(options.order, this, function (series) {
return buildSeriesOptions(series, dataExtremes, options);
});
// Add waits after simultaneous paths with series in them.
order = addAfterSeriesWaits(order, options.afterSeriesWait || 0);
// We now have a list of either TimelinePath objects or series that need to
// be converted to TimelinePath objects. Convert everything to paths.
var paths = buildPathsFromOrder(order, options.duration);
// Sync simultaneous paths
paths.forEach(function (simultaneousPaths) {
syncSimultaneousPaths(simultaneousPaths);
});
// We have a set of paths. Create the timeline, and play it.
this.sonification.timeline = new H.sonification.Timeline({
paths: paths,
onEnd: options.onEnd
});
this.sonification.timeline.play();
}
/**
* Get a list of the points currently under cursor.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#getCurrentSonifyPoints
*
* @return {Array<Highcharts.Point>}
* The points currently under the cursor.
*/
function getCurrentPoints() {
var cursorObj;
if (this.sonification.timeline) {
cursorObj = this.sonification.timeline.getCursor(); // Cursor per pathID
return Object.keys(cursorObj).map(function (path) {
// Get the event objects under cursor for each path
return cursorObj[path].eventObject;
}).filter(function (eventObj) {
// Return the events that are points
return eventObj instanceof H.Point;
});
}
return [];
}
/**
* Set the cursor to a point or set of points in different series.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#setSonifyCursor
*
* @param {Highcharts.Point|Array<Highcharts.Point>} points
* The point or points to set the cursor to. If setting multiple points
* under the cursor, the points have to be in different series that are
* being played simultaneously.
*/
function setCursor(points) {
var timeline = this.sonification.timeline;
if (timeline) {
H.splat(points).forEach(function (point) {
// We created the events with the ID of the points, which makes
// this easy. Just call setCursor for each ID.
timeline.setCursor(point.id);
});
}
}
/**
* Pause the running sonification.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#pauseSonify
*
* @param {boolean} [fadeOut=true]
* Fade out as we pause to avoid clicks.
*/
function pause(fadeOut) {
if (this.sonification.timeline) {
this.sonification.timeline.pause(H.pick(fadeOut, true));
} else if (this.sonification.currentlyPlayingPoint) {
this.sonification.currentlyPlayingPoint.cancelSonify(fadeOut);
}
}
/**
* Resume the currently running sonification. Requires series.sonify or
* chart.sonify to have been played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resumeSonify
*
* @param {Function} onEnd
* Callback to call when play finished.
*/
function resume(onEnd) {
if (this.sonification.timeline) {
this.sonification.timeline.play(onEnd);
}
}
/**
* Play backwards from cursor. Requires series.sonify or chart.sonify to have
* been played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#rewindSonify
*
* @param {Function} onEnd
* Callback to call when play finished.
*/
function rewind(onEnd) {
if (this.sonification.timeline) {
this.sonification.timeline.rewind(onEnd);
}
}
/**
* Cancel current sonification and reset cursor.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#cancelSonify
*
* @param {boolean} [fadeOut=true]
* Fade out as we pause to avoid clicks.
*/
function cancel(fadeOut) {
this.pauseSonify(fadeOut);
this.resetSonifyCursor();
}
/**
* Reset cursor to start. Requires series.sonify or chart.sonify to have been
* played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resetSonifyCursor
*/
function resetCursor() {
if (this.sonification.timeline) {
this.sonification.timeline.resetCursor();
}
}
/**
* Reset cursor to end. Requires series.sonify or chart.sonify to have been
* played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resetSonifyCursorEnd
*/
function resetCursorEnd() {
if (this.sonification.timeline) {
this.sonification.timeline.resetCursorEnd();
}
}
// Export functions
var chartSonifyFunctions = {
chartSonify: chartSonify,
seriesSonify: seriesSonify,
pause: pause,
resume: resume,
rewind: rewind,
cancel: cancel,
getCurrentPoints: getCurrentPoints,
setCursor: setCursor,
resetCursor: resetCursor,
resetCursorEnd: resetCursorEnd
};
return chartSonifyFunctions;
}(Highcharts, utilities));
var timelineClasses = (function (H, utilities) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* TimelineEvent class definition.
*
* License: www.highcharts.com/license
*
* */
/**
* A set of options for the TimelineEvent class.
*
* @requires module:modules/sonification
*
* @private
* @interface Highcharts.TimelineEventOptionsObject
*//**
* The object we want to sonify when playing the TimelineEvent. Can be any
* object that implements the `sonify` and `cancelSonify` functions. If this is
* not supplied, the TimelineEvent is considered a silent event, and the onEnd
* event is immediately called.
* @name Highcharts.TimelineEventOptionsObject#eventObject
* @type {*}
*//**
* Options to pass on to the eventObject when playing it.
* @name Highcharts.TimelineEventOptionsObject#playOptions
* @type {object|undefined}
*//**
* The time at which we want this event to play (in milliseconds offset). This
* is not used for the TimelineEvent.play function, but rather intended as a
* property to decide when to call TimelineEvent.play. Defaults to 0.
* @name Highcharts.TimelineEventOptionsObject#time
* @type {number|undefined}
*//**
* Unique ID for the event. Generated automatically if not supplied.
* @name Highcharts.TimelineEventOptionsObject#id
* @type {string|undefined}
*//**
* Callback called when the play has finished.
* @name Highcharts.TimelineEventOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The TimelineEvent class. Represents a sound event on a timeline.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.TimelineEvent
*
* @param {Highcharts.TimelineEventOptionsObject} options
* Options for the TimelineEvent.
*/
function TimelineEvent(options) {
this.init(options || {});
}
TimelineEvent.prototype.init = function (options) {
this.options = options;
this.time = options.time || 0;
this.id = this.options.id = options.id || H.uniqueKey();
};
/**
* Play the event. Does not take the TimelineEvent.time option into account,
* and plays the event immediately.
*
* @function Highcharts.TimelineEvent#play
*
* @param {Highcharts.TimelineEventOptionsObject} [options]
* Options to pass in to the eventObject when playing it.
*/
TimelineEvent.prototype.play = function (options) {
var eventObject = this.options.eventObject,
masterOnEnd = this.options.onEnd,
playOnEnd = options && options.onEnd,
playOptionsOnEnd = this.options.playOptions &&
this.options.playOptions.onEnd,
playOptions = H.merge(this.options.playOptions, options);
if (eventObject && eventObject.sonify) {
// If we have multiple onEnds defined, use all
playOptions.onEnd = masterOnEnd || playOnEnd || playOptionsOnEnd ?
function () {
var args = arguments;
[masterOnEnd, playOnEnd, playOptionsOnEnd].forEach(
function (onEnd) {
if (onEnd) {
onEnd.apply(this, args);
}
}
);
} : undefined;
eventObject.sonify(playOptions);
} else {
if (playOnEnd) {
playOnEnd();
}
if (masterOnEnd) {
masterOnEnd();
}
}
};
/**
* Cancel the sonification of this event. Does nothing if the event is not
* currently sonifying.
*
* @function Highcharts.TimelineEvent#cancel
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the event is
* cancelled synchronously.
*/
TimelineEvent.prototype.cancel = function (fadeOut) {
this.options.eventObject.cancelSonify(fadeOut);
};
/**
* A set of options for the TimelinePath class.
*
* @requires module:modules/
*
* @private
* @interface Highcharts.TimelinePathOptionsObject
*//**
* List of TimelineEvents to play on this track.
* @name Highcharts.TimelinePathOptionsObject#events
* @type {Array<Highcharts.TimelineEvent>}
*//**
* If this option is supplied, this path ignores all events and just waits for
* the specified number of milliseconds before calling onEnd.
* @name Highcharts.TimelinePathOptionsObject#silentWait
* @type {number|undefined}
*//**
* Unique ID for this timeline path. Automatically generated if not supplied.
* @name Highcharts.TimelinePathOptionsObject#id
* @type {string|undefined}
*//**
* Callback called before the path starts playing.
* @name Highcharts.TimelinePathOptionsObject#onStart
* @type {Function|undefined}
*//**
* Callback function to call before an event plays.
* @name Highcharts.TimelinePathOptionsObject#onEventStart
* @type {Function|undefined}
*//**
* Callback function to call after an event has stopped playing.
* @name Highcharts.TimelinePathOptionsObject#onEventEnd
* @type {Function|undefined}
*//**
* Callback called when the whole path is finished.
* @name Highcharts.TimelinePathOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The TimelinePath class. Represents a track on a timeline with a list of
* sound events to play at certain times relative to each other.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.TimelinePath
*
* @param {Highcharts.TimelinePathOptionsObject} options
* Options for the TimelinePath.
*/
function TimelinePath(options) {
this.init(options);
}
TimelinePath.prototype.init = function (options) {
this.options = options;
this.id = this.options.id = options.id || H.uniqueKey();
this.cursor = 0;
this.eventsPlaying = {};
// Handle silent wait, otherwise use events from options
this.events =
options.silentWait ?
[
new TimelineEvent({ time: 0 }),
new TimelineEvent({ time: options.silentWait })
] :
this.options.events;
// We need to sort our events by time
this.sortEvents();
// Get map from event ID to index
this.updateEventIdMap();
// Signal events to fire
this.signalHandler = new utilities.SignalHandler(
['playOnEnd', 'masterOnEnd', 'onStart', 'onEventStart', 'onEventEnd']
);
this.signalHandler.registerSignalCallbacks(
H.merge(options, { masterOnEnd: options.onEnd })
);
};
/**
* Sort the internal event list by time.
* @private
*/
TimelinePath.prototype.sortEvents = function () {
this.events = this.events.sort(function (a, b) {
return a.time - b.time;
});
};
/**
* Update the internal eventId to index map.
* @private
*/
TimelinePath.prototype.updateEventIdMap = function () {
this.eventIdMap = this.events.reduce(function (acc, cur, i) {
acc[cur.id] = i;
return acc;
}, {});
};
/**
* Add events to the path. Should not be done while the path is playing.
* The new events are inserted according to their time property.
* @private
* @param {Array<Highcharts.TimelineEvent>} newEvents - The new timeline events
* to add.
*/
TimelinePath.prototype.addTimelineEvents = function (newEvents) {
this.events = this.events.concat(newEvents);
this.sortEvents(); // Sort events by time
this.updateEventIdMap(); // Update the event ID to index map
};
/**
* Get the current TimelineEvent under the cursor.
* @private
* @return {Highcharts.TimelineEvent} The current timeline event.
*/
TimelinePath.prototype.getCursor = function () {
return this.events[this.cursor];
};
/**
* Set the current TimelineEvent under the cursor.
* @private
* @param {string} eventId - The ID of the timeline event to set as current.
* @return {boolean} True if there is an event with this ID in the path. False
* otherwise.
*/
TimelinePath.prototype.setCursor = function (eventId) {
var ix = this.eventIdMap[eventId];
if (ix !== undefined) {
this.cursor = ix;
return true;
}
return false;
};
/**
* Play the timeline from the current cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
TimelinePath.prototype.play = function (onEnd) {
this.pause();
this.signalHandler.emitSignal('onStart');
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playEvents(1);
};
/**
* Play the timeline backwards from the current cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
TimelinePath.prototype.rewind = function (onEnd) {
this.pause();
this.signalHandler.emitSignal('onStart');
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playEvents(-1);
};
/**
* Reset the cursor to the beginning.
* @private
*/
TimelinePath.prototype.resetCursor = function () {
this.cursor = 0;
};
/**
* Reset the cursor to the end.
* @private
*/
TimelinePath.prototype.resetCursorEnd = function () {
this.cursor = this.events.length - 1;
};
/**
* Cancel current playing. Leaves the cursor intact.
* @private
* @param {boolean} [fadeOut=false] - Whether or not to fade out as we stop. If
* false, the path is cancelled synchronously.
*/
TimelinePath.prototype.pause = function (fadeOut) {
var timelinePath = this;
// Cancel next scheduled play
clearTimeout(timelinePath.nextScheduledPlay);
// Cancel currently playing events
Object.keys(timelinePath.eventsPlaying).forEach(function (id) {
if (timelinePath.eventsPlaying[id]) {
timelinePath.eventsPlaying[id].cancel(fadeOut);
}
});
timelinePath.eventsPlaying = {};
};
/**
* Play the events, starting from current cursor, and going in specified
* direction.
* @private
* @param {number} direction - The direction to play, 1 for forwards and -1 for
* backwards.
*/
TimelinePath.prototype.playEvents = function (direction) {
var timelinePath = this,
curEvent = timelinePath.events[this.cursor],
nextEvent = timelinePath.events[this.cursor + direction],
timeDiff,
onEnd = function (signalData) {
timelinePath.signalHandler.emitSignal(
'masterOnEnd', signalData
);
timelinePath.signalHandler.emitSignal(
'playOnEnd', signalData
);
};
// Store reference to path on event
curEvent.timelinePath = timelinePath;
// Emit event, cancel if returns false
if (
timelinePath.signalHandler.emitSignal(
'onEventStart', curEvent
) === false
) {
onEnd({
event: curEvent,
cancelled: true
});
return;
}
// Play the current event
timelinePath.eventsPlaying[curEvent.id] = curEvent;
curEvent.play({
onEnd: function (cancelled) {
var signalData = {
event: curEvent,
cancelled: !!cancelled
};
// Keep track of currently playing events for cancelling
delete timelinePath.eventsPlaying[curEvent.id];
// Handle onEventEnd
timelinePath.signalHandler.emitSignal('onEventEnd', signalData);
// Reached end of path?
if (!nextEvent) {
onEnd(signalData);
}
}
});
// Schedule next
if (nextEvent) {
timeDiff = Math.abs(nextEvent.time - curEvent.time);
if (timeDiff < 1) {
// Play immediately
timelinePath.cursor += direction;
timelinePath.playEvents(direction);
} else {
// Schedule after the difference in ms
this.nextScheduledPlay = setTimeout(function () {
timelinePath.cursor += direction;
timelinePath.playEvents(direction);
}, timeDiff);
}
}
};
/* ************************************************************************** *
* TIMELINE *
* ************************************************************************** */
/**
* A set of options for the Timeline class.
*
* @requires module:modules/sonification
*
* @private
* @interface Highcharts.TimelineOptionsObject
*//**
* List of TimelinePaths to play. Multiple paths can be grouped together and
* played simultaneously by supplying an array of paths in place of a single
* path.
* @name Highcharts.TimelineOptionsObject#paths
* @type {Array<Highcharts.TimelinePath|Array<Highcharts.TimelinePath>>}
*//**
* Callback function to call before a path plays.
* @name Highcharts.TimelineOptionsObject#onPathStart
* @type {Function|undefined}
*//**
* Callback function to call after a path has stopped playing.
* @name Highcharts.TimelineOptionsObject#onPathEnd
* @type {Function|undefined}
*//**
* Callback called when the whole path is finished.
* @name Highcharts.TimelineOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The Timeline class. Represents a sonification timeline with a list of
* timeline paths with events to play at certain times relative to each other.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.Timeline
*
* @param {Highcharts.TimelineOptionsObject} options
* Options for the Timeline.
*/
function Timeline(options) {
this.init(options || {});
}
Timeline.prototype.init = function (options) {
this.options = options;
this.cursor = 0;
this.paths = options.paths;
this.pathsPlaying = {};
this.signalHandler = new utilities.SignalHandler(
['playOnEnd', 'masterOnEnd', 'onPathStart', 'onPathEnd']
);
this.signalHandler.registerSignalCallbacks(
H.merge(options, { masterOnEnd: options.onEnd })
);
};
/**
* Play the timeline forwards from cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
Timeline.prototype.play = function (onEnd) {
this.pause();
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playPaths(1);
};
/**
* Play the timeline backwards from cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
Timeline.prototype.rewind = function (onEnd) {
this.pause();
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playPaths(-1);
};
/**
* Play the timeline in the specified direction.
* @private
* @param {number} direction - Direction to play in. 1 for forwards, -1 for
* backwards.
*/
Timeline.prototype.playPaths = function (direction) {
var curPaths = H.splat(this.paths[this.cursor]),
nextPaths = this.paths[this.cursor + direction],
timeline = this,
signalHandler = this.signalHandler,
pathsEnded = 0,
// Play a path
playPath = function (path) {
// Emit signal and set playing state
signalHandler.emitSignal('onPathStart', path);
timeline.pathsPlaying[path.id] = path;
// Do the play
path[direction > 0 ? 'play' : 'rewind'](function (callbackData) {
// Play ended callback
// Data to pass to signal callbacks
var cancelled = callbackData && callbackData.cancelled,
signalData = {
path: path,
cancelled: cancelled
};
// Clear state and send signal
delete timeline.pathsPlaying[path.id];
signalHandler.emitSignal('onPathEnd', signalData);
// Handle next paths
pathsEnded++;
if (pathsEnded >= curPaths.length) {
// We finished all of the current paths for cursor.
if (nextPaths && !cancelled) {
// We have more paths, move cursor along
timeline.cursor += direction;
// Reset upcoming path cursors before playing
H.splat(nextPaths).forEach(function (nextPath) {
nextPath[
direction > 0 ? 'resetCursor' : 'resetCursorEnd'
]();
});
// Play next
timeline.playPaths(direction);
} else {
// If it is the last path in this direction, call onEnd
signalHandler.emitSignal('playOnEnd', signalData);
signalHandler.emitSignal('masterOnEnd', signalData);
}
}
});
};
// Go through the paths under cursor and play them
curPaths.forEach(function (path) {
if (path) {
// Store reference to timeline
path.timeline = timeline;
// Leave a timeout to let notes fade out before next play
setTimeout(function () {
playPath(path);
}, H.sonification.fadeOutTime);
}
});
};
/**
* Stop the playing of the timeline. Cancels all current sounds, but does not
* affect the cursor.
* @private
* @param {boolean} [fadeOut=false] - Whether or not to fade out as we stop. If
* false, the timeline is cancelled synchronously.
*/
Timeline.prototype.pause = function (fadeOut) {
var timeline = this;
// Cancel currently playing events
Object.keys(timeline.pathsPlaying).forEach(function (id) {
if (timeline.pathsPlaying[id]) {
timeline.pathsPlaying[id].pause(fadeOut);
}
});
timeline.pathsPlaying = {};
};
/**
* Reset the cursor to the beginning of the timeline.
* @private
*/
Timeline.prototype.resetCursor = function () {
this.paths.forEach(function (paths) {
H.splat(paths).forEach(function (path) {
path.resetCursor();
});
});
this.cursor = 0;
};
/**
* Reset the cursor to the end of the timeline.
* @private
*/
Timeline.prototype.resetCursorEnd = function () {
this.paths.forEach(function (paths) {
H.splat(paths).forEach(function (path) {
path.resetCursorEnd();
});
});
this.cursor = this.paths.length - 1;
};
/**
* Set the current TimelineEvent under the cursor. If multiple paths are being
* played at the same time, this function only affects a single path (the one
* that contains the eventId that is passed in).
* @private
* @param {string} eventId - The ID of the timeline event to set as current.
* @return {boolean} True if the cursor was set, false if no TimelineEvent was
* found for this ID.
*/
Timeline.prototype.setCursor = function (eventId) {
return this.paths.some(function (paths) {
return H.splat(paths).some(function (path) {
return path.setCursor(eventId);
});
});
};
/**
* Get the current TimelineEvents under the cursors. This function will return
* the event under the cursor for each currently playing path, as an object
* where the path ID is mapped to the TimelineEvent under that path's cursor.
* @private
* @return {object} The TimelineEvents under each path's cursors.
*/
Timeline.prototype.getCursor = function () {
return this.getCurrentPlayingPaths().reduce(function (acc, cur) {
acc[cur.id] = cur.getCursor();
return acc;
}, {});
};
/**
* Check if timeline is reset or at start.
* @private
* @return {boolean} True if timeline is at the beginning.
*/
Timeline.prototype.atStart = function () {
return !this.getCurrentPlayingPaths().some(function (path) {
return path.cursor;
});
};
/**
* Get the current TimelinePaths being played.
* @private
* @return {Array<Highcharts.TimelinePath>} The TimelinePaths currently being
* played.
*/
Timeline.prototype.getCurrentPlayingPaths = function () {
return H.splat(this.paths[this.cursor]);
};
// Export the classes
var timelineClasses = {
TimelineEvent: TimelineEvent,
TimelinePath: TimelinePath,
Timeline: Timeline
};
return timelineClasses;
}(Highcharts, utilities));
(function (H, Instrument, instruments, Earcon, pointSonifyFunctions, chartSonifyFunctions, utilities, TimelineClasses) {
/* *
*
* (c) 2009-2018 Øystein Moseng
*
* Sonification module for Highcharts
*
* License: www.highcharts.com/license
*
* */
// Expose on the Highcharts object
/**
* Global classes and objects related to sonification.
*
* @requires module:modules/sonification
*
* @name Highcharts.sonification
* @type {Highcharts.SonificationObject}
*/
/**
* Global classes and objects related to sonification.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonificationObject
*//**
* Note fade-out-time in milliseconds. Most notes are faded out quickly by
* default if there is time. This is to avoid abrupt stops which will cause
* perceived clicks.
* @name Highcharts.SonificationObject#fadeOutDuration
* @type {number}
*//**
* Utility functions.
* @name Highcharts.SonificationObject#utilities
* @private
* @type {object}
*//**
* The Instrument class.
* @name Highcharts.SonificationObject#Instrument
* @type {Function}
*//**
* Predefined instruments, given as an object with a map between the instrument
* name and the Highcharts.Instrument object.
* @name Highcharts.SonificationObject#instruments
* @type {Object}
*//**
* The Earcon class.
* @name Highcharts.SonificationObject#Earcon
* @type {Function}
*//**
* The TimelineEvent class.
* @private
* @name Highcharts.SonificationObject#TimelineEvent
* @type {Function}
*//**
* The TimelinePath class.
* @private
* @name Highcharts.SonificationObject#TimelinePath
* @type {Function}
*//**
* The Timeline class.
* @private
* @name Highcharts.SonificationObject#Timeline
* @type {Function}
*/
H.sonification = {
fadeOutDuration: 20,
// Classes and functions
utilities: utilities,
Instrument: Instrument,
instruments: instruments,
Earcon: Earcon,
TimelineEvent: TimelineClasses.TimelineEvent,
TimelinePath: TimelineClasses.TimelinePath,
Timeline: TimelineClasses.Timeline
};
// Chart specific
H.Point.prototype.sonify = pointSonifyFunctions.pointSonify;
H.Point.prototype.cancelSonify = pointSonifyFunctions.pointCancelSonify;
H.Series.prototype.sonify = chartSonifyFunctions.seriesSonify;
H.extend(H.Chart.prototype, {
sonify: chartSonifyFunctions.chartSonify,
pauseSonify: chartSonifyFunctions.pause,
resumeSonify: chartSonifyFunctions.resume,
rewindSonify: chartSonifyFunctions.rewind,
cancelSonify: chartSonifyFunctions.cancel,
getCurrentSonifyPoints: chartSonifyFunctions.getCurrentPoints,
setSonifyCursor: chartSonifyFunctions.setCursor,
resetSonifyCursor: chartSonifyFunctions.resetCursor,
resetSonifyCursorEnd: chartSonifyFunctions.resetCursorEnd,
sonification: {}
});
}(Highcharts, Instrument, instruments, Earcon, pointSonifyFunctions, chartSonifyFunctions, utilities, timelineClasses));
return (function () {
}());
})); | {
"content_hash": "fd06fb88be3aefbc3a4e9b43c643a5cd",
"timestamp": "",
"source": "github",
"line_count": 3295,
"max_line_length": 121,
"avg_line_length": 34.092564491654024,
"alnum_prop": 0.6065963413005742,
"repo_name": "sufuf3/cdnjs",
"id": "425d518ca257cc7b2cab3d5d9f36bccdf3a040a0",
"size": "112345",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ajax/libs/highcharts/7.0.0/modules/sonification.src.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
- pretty
- foxy
- charming
- breathtaking
- a head turner
- easy on eyes
- irresistible
##### pull it off 真不简单
#### aches and pains
#### fair and square
| {
"content_hash": "086b1d31cb6909e91954f8465d25b0d9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 22,
"avg_line_length": 12.307692307692308,
"alnum_prop": 0.6375,
"repo_name": "zharuosi/2017",
"id": "361e915d60fd138513ae3de0596b81d811494199",
"size": "217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "seed/words/W4.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "3759"
},
{
"name": "CSS",
"bytes": "11637"
},
{
"name": "HTML",
"bytes": "1653512"
},
{
"name": "JavaScript",
"bytes": "102808"
},
{
"name": "Makefile",
"bytes": "176"
},
{
"name": "Python",
"bytes": "14321"
}
],
"symlink_target": ""
} |
/**
* @file modules/mailer/resender.js
* @author Daniele Belardi
*/
'use strict';
const inz = require('inz')();
const async = require('async');
/**
* @module messages
*/
class ReSender {
constructor(options) {
let o = _validateOptions(options);
let internal = inz(this);
Object.defineProperty(this, 'scanInterval', {
enumerable: false,
configurable: false,
writable: false,
value: o.scanInterval
});
internal.bus = o.bus;
if (this.scanInterval) {
internal.scanId = setInterval(()=>{
this.send();
}, this.scanInterval);
}
internal.onMailerError = _onMailerError.bind(this);
internal.onMailerSuccess = _onMailerSuccess.bind(this);
internal.bus.on('mailer/error', internal.onMailerError)
.on('mailer/success', internal.onMailerSuccess);
}
destroyEvents() {
let internal = inz(this);
if(this.scanId) {
clearInterval(this.scanId);
}
internal.bus.removeListener('mailer/error', internal.onMailerError);
internal.bus.removeListener('mailer/success', internal.onMailerSuccess);
}
send() {
let bus = inz(this).bus;
let self = this;
bus.emit('messages/get', {nextPending:true}, (err, message)=>{
if (!message) return;
bus.emit('logger/log', 'info', {
module: 'messages/resender',
event: `resending message ${message.subject}`,
data: message
});
bus.emit('mailer/send', message);
self.send();
});
}
onError(err) {
inz(this).bus.emit('logger/log', 'error', {
module: 'mailer/resender',
event: 'error removing message',
data: err
});
/**
* Throwing an error here
* and make it intercept by the Mlr application
* to make the process restart
*/
throw new Error(err);
}
}
function _onMailerError(info) {
/* jshint validthis: true */
let err = info.error;
let isAppError = err.code === "ENOENT" ||
err.message === "No recipients defined" ||
err.message === "The info field is missing. Please specifiy it." ;
let bus = inz(this).bus;
if (!(isAppError || (info.message && info.message._id))) {
bus.emit('messages/save', info.message, (err, res)=>{
return err ? this.onError(err) : null;
});
}
if (info && info.message && info.message._id) {
bus.emit('messages/update', { _id: info.message._id }, { processing: false }, (err, res)=>{
return err ? this.onError(err) : null;
});
}
}
function _onMailerSuccess(info) {
/* jshint validthis: true */
let email = info.message;
if (email && email._id) {
inz(this).bus.emit('messages/remove', {
_id: email._id
}, (err, result)=>{
if (err) return this.onError(err);
});
}
}
function _validateOptions(options) {
let o = options || {};
if (! (o.bus && o.bus.constructor && o.bus.constructor.name === "EventEmitter")) {
throw new Error('Please specify an application bus instance.');
}
/** 10 minutes scan interval by default */
o.scanInterval = o.scanInterval || 600000;
return o;
}
module.exports = ReSender;
| {
"content_hash": "697e331a435348306fc1ada163320d51",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 95,
"avg_line_length": 25.104,
"alnum_prop": 0.6016571064372211,
"repo_name": "eca-automs/mlr",
"id": "0672dff2efd60c9f2c38dcb26e0ed92b013e8210",
"size": "3138",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/mailer/resender.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "466"
},
{
"name": "HTML",
"bytes": "303"
},
{
"name": "JavaScript",
"bytes": "103408"
}
],
"symlink_target": ""
} |
<?php
namespace backend\controllers;
use Yii;
use common\models\Categories;
use common\models\CategoriesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\PermissionHelpers;
use yii\filters\AccessControl;
/**
* CategoriesController implements the CRUD actions for Categories model.
*/
class CategoriesController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Categories models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new CategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Categories model.
* @param string $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Categories model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Categories();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Categories model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Categories model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param string $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Categories model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param string $id
* @return Categories the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Categories::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| {
"content_hash": "c44e2bcb3c02d4554f9463728c0a31bc",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 85,
"avg_line_length": 25.77777777777778,
"alnum_prop": 0.5431034482758621,
"repo_name": "rob94/BlogYii",
"id": "684667c77a8d675b8b3a6d288f58eb7c746f13db",
"size": "3248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/controllers/CategoriesController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "10062"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "2728"
},
{
"name": "PHP",
"bytes": "200737"
}
],
"symlink_target": ""
} |
from django.apps import AppConfig
class PretixBaseConfig(AppConfig):
name = 'pretix.base'
label = 'pretixbase'
default_app_config = 'pretix.base.PretixBaseConfig'
| {
"content_hash": "b899bd4c1ba7af6c1bb5821c5e410d2a",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 51,
"avg_line_length": 21.75,
"alnum_prop": 0.7471264367816092,
"repo_name": "Unicorn-rzl/pretix",
"id": "2455a458a3a9d1b77f798f670b3710070524b29d",
"size": "174",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/pretix/base/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "39129"
},
{
"name": "HTML",
"bytes": "153518"
},
{
"name": "JavaScript",
"bytes": "8986"
},
{
"name": "Makefile",
"bytes": "423"
},
{
"name": "Python",
"bytes": "593486"
},
{
"name": "Shell",
"bytes": "287"
}
],
"symlink_target": ""
} |
module.exports = function () {
function create(app, config, io) {
var context = config.store.context || '/dns/api/v1',
interval = config.store.interval || interval,
prefix = config.dns.prefix || 'dns:',
prefixSize = prefix.length,
store = config.store;
// GET
app.get(context + '/hostname/:hostname?', function (req, res) {
var hostname = req.params.hostname || '*',
exact = hostname.indexOf('*') === -1;
res.header('X-tomahawk-http-method', 'GET');
res.header('X-tomahawk-operation', 'get');
res.header('X-tomahawk-multi-hostname', !exact);
res.header('X-tomahawk-hostname', hostname);
store.get(prefix+hostname, function (err, values) {
if (err) {
return res.status(500).json({hostname:hostname,error:err}).end();
}
if (values) {
var records;
try {
records = values;
if (records instanceof(Array)) {
var recordsWithoutPrefix = records.map(function (record) {
return {hostname:record.key.substring(prefixSize), record:JSON.parse(record.value)};
});
records = recordsWithoutPrefix;
}
} catch (e) {
console.log('GET:' + prefix+hostname + "=", values, " >>> ", e);
return res.status(500).json({hostname:hostname,error:err}).end();
}
return res.json(records).end();
}
return res.status(404).json({hostname:hostname}).end();
});
});
// PUT
app.put(context + '/hostname/:hostname', function (req, res) {
res.header('X-tomahawk-http-method', 'PUT');
res.header('X-tomahawk-operation', 'set');
res.header('X-tomahawk-multi-hostname', false);
res.header('X-tomahawk-hostname', req.params.hostname);
var record = {
host : req.params.hostname,
PTR : null
};
if (req.body) {
if (req.body.ipv4) {
record.A = req.body.ipv4 instanceof Array ? req.body.ipv4 : [req.body.ipv4];
}
if (req.body.ipv6) {
record.AAAA = req.body.ipv4 instanceof Array ? req.body.ipv6 : [req.body.ipv6];
}
}
store.set(prefix+req.params.hostname, JSON.stringify(record), function (err, result) {
if (err) {
return res.status(500).json({hostname:req.params.hostname,error:err}).end();
}
io.sockets.emit('/set', {hostname:req.params.hostname, record:record});
var successes = 0,
failures = 0;
function createArpa(hostnames) {
if (!hostnames || hostnames.length < 1) {
if (failures)
return res.status(500).json({hostname:req.params.hostname,error:failures}).end();
else
return res.status(204).end();
}
var hostname = ''+hostnames.shift(); // Make sure it is a string
var arpa = hostname.split('.').reverse().join('.') + '.in-addr.arpa';
store.set(prefix + arpa, JSON.stringify(record), function (err, result) {
if (err) {
failures += 1;
} else {
successes += 1;
io.sockets.emit(context+'/set', {hostname: arpa, record: record});
}
process.nextTick(function () {
createArpa(hostnames);
});
});
}
createArpa(record.A ? record.A instanceof(Array) ? record.A.slice(0) : [record.A] : []);
});
});
// DELETE
app.delete(context + '/hostname/:hostname?', function (req, res) {
var hostname = req.params.hostname || '*',
exact = hostname.indexOf('*') === -1;
res.header('X-tomahawk-http-method', 'DELETE');
res.header('X-tomahawk-operation', 'del');
res.header('X-tomahawk-multi-hostname', !exact);
res.header('X-tomahawk-hostname', hostname);
if (hostname === '*' && req.query.force !== 'true') {
return res.status(400).json({error:"To delete all the entries, you must use the 'force' option"}).end();
}
store.delete(prefix+hostname, function (err, value) {
if (err) {
return res.status(500).json({hostname:hostname,error:err}).end();
}
io.sockets.emit('/del', {hostname:hostname});
return res.status(204).end();
});
});
app.get(context + '/zone', function (req, res) {
res.header('X-tomahawk-http-method', 'GET');
res.header('X-tomahawk-operation', 'zone');
return res.json({zone:config.dns.zone}).end();
});
// GET status
app.get(context + '/status', function (req, res) {
res.header('X-tomahawk-http-method', 'GET');
res.header('X-tomahawk-operation', 'status');
store.status(function (err, value) {
if (err) {
return res.status(500).json({error:err}).end();
}
return res.status(204).end();
});
});
////////////////////////////////////////////////////////////////////////
return {
constructor : function (next) {
if (next) process.nextTick(next);
},
shutdown : function (next) {
if (next) process.nextTick(next);
}
};
}
return create;
}();
| {
"content_hash": "9e0d586ee317ba949192a1743a1d3f36",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 120,
"avg_line_length": 41.973333333333336,
"alnum_prop": 0.44599745870393903,
"repo_name": "chone/mem",
"id": "dc12305f3e3ef40b5c53958b48b66d7ac1278d7b",
"size": "6296",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "proton-proxy/node_modules/dns/lib/routes.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2290"
},
{
"name": "CSS",
"bytes": "125232"
},
{
"name": "Emacs Lisp",
"bytes": "2410"
},
{
"name": "HTML",
"bytes": "1096665"
},
{
"name": "JavaScript",
"bytes": "20392128"
},
{
"name": "Python",
"bytes": "80606"
},
{
"name": "Shell",
"bytes": "11050"
}
],
"symlink_target": ""
} |
/**
* @author reetsee.com
* @date 20161007
*/
var path = require('path');
var ROOT_PATH = path.resolve(__dirname, '..');
var basic = require("./basic");
var session = require("./session/session");
var validationConf = {};
try {
settings = require(ROOT_PATH + "/conf/settings.secret");
validationConf = basic.safeGet(settings, ["validation"], {});
} catch(e) {
validationConf = {};
}
var sg = basic.safeGet;
function validateSession(req, res, next) {
var vconf = sg(validationConf, ["conf"]);
var needWriteValidation = sg(vconf, ["needWriteValidation"], false);
if (!vconf || !needWriteValidation) {
return null;
}
var cookies = req.cookies;
var reqSession = sg(cookies, ["session"], "");
if (!reqSession || reqSession.length == 0) {
return "请先登录";
}
var tupleList = reqSession.split("_");
if (tupleList.length < 3) {
return "登录状态已失效,请重新登录";
}
var isAdmin = false;
var adminIdList = sg(vconf, ["adminIdList"], []);
for (var i = 0; i < adminIdList; ++i) {
if (tupleList[1] == adminIdList[i]) {
isAdmin = true;
break;
}
}
if (!isAdmin) {
return "当前帐号非管理员帐号,无法继续操作";
}
var isValid = session.isValid({
"source": tupleList[0],
"uid": tupleList[1],
"access_token": tupleList[2],
});
if (!isValid) {
return "登录状态已失效,请重新登录";
}
return null;
}
exports.validateSession = validateSession;
| {
"content_hash": "06e945290ab92d7015baa157c66e08c9",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 72,
"avg_line_length": 24.14516129032258,
"alnum_prop": 0.571810287241149,
"repo_name": "fanfank/aap",
"id": "5561cdeef521e5bddeceab2ca073f301500d6454",
"size": "1591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/src/libs/hdlrmw.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2511"
},
{
"name": "HTML",
"bytes": "66310"
},
{
"name": "JavaScript",
"bytes": "266718"
},
{
"name": "Python",
"bytes": "49878"
},
{
"name": "Shell",
"bytes": "374"
}
],
"symlink_target": ""
} |
package play.mvc;
import java.lang.annotation.*;
/**
* A body parser parses the HTTP request body content.
*/
public interface BodyParser {
play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength);
/**
* Specify the body parser to use for an Action method.
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Of {
Class<? extends BodyParser> value();
int maxLength() default -1;
}
/**
* Guess the body content by checking the Content-Type header.
*/
public static class AnyContent implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.anyContent(maxLength);
}
}
/**
* Parse the body as Json if the Content-Type is text/json or application/json.
*/
public static class Json implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.json(maxLength);
}
}
/**
* Parse the body as Json without checking the Content-Type.
*/
public static class TolerantJson implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.tolerantJson(maxLength);
}
}
/**
* Parse the body as Xml if the Content-Type is text/xml.
*/
public static class Xml implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.xml(maxLength);
}
}
/**
* Parse the body as Xml without checking the Content-Type.
*/
public static class TolerantXml implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.tolerantXml(maxLength);
}
}
/**
* Parse the body as text if the Content-Type is text/plain.
*/
public static class Text implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.text(maxLength);
}
}
/**
* Parse the body as text without checking the Content-Type.
*/
public static class TolerantText implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.tolerantText(maxLength);
}
}
/**
* Store the body content in a RawBuffer.
*/
public static class Raw implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.raw(maxLength);
}
}
/**
* Parse the body as form url encoded if the Content-Type is application/x-www-form-urlencoded.
*/
public static class FormUrlEncoded implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.formUrlEncoded(maxLength);
}
}
/**
* Parse the body as form url encoded without checking the Content-Type.
*/
public static class MultipartFormData implements BodyParser {
public play.api.mvc.BodyParser<Http.RequestBody> parser(int maxLength) {
return play.core.j.JavaParsers.multipartFormData(maxLength);
}
}
} | {
"content_hash": "e5859ea835d097b74495278ae5d9c864",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 99,
"avg_line_length": 31.892857142857142,
"alnum_prop": 0.6503359462486002,
"repo_name": "noel-yap/setter-for-catan",
"id": "e0fa118027353a8263b8860426112b60893668dd",
"size": "3572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play-2.1.1/framework/src/play/src/main/java/play/mvc/BodyParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "6386"
},
{
"name": "Java",
"bytes": "463689"
},
{
"name": "JavaScript",
"bytes": "841409"
},
{
"name": "Scala",
"bytes": "1510018"
},
{
"name": "Shell",
"bytes": "7220"
}
],
"symlink_target": ""
} |
package org.eclipse.bpmn2;
import java.util.List;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Sub Choreography</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.eclipse.bpmn2.SubChoreography#getArtifacts <em>Artifacts</em>}</li>
* </ul>
* </p>
*
* @see org.eclipse.bpmn2.Bpmn2Package#getSubChoreography()
* @model extendedMetaData="name='tSubChoreography' kind='elementOnly'"
* @generated
*/
public interface SubChoreography extends ChoreographyActivity, FlowElementsContainer {
/**
* Returns the value of the '<em><b>Artifacts</b></em>' containment reference list.
* The list contents are of type {@link org.eclipse.bpmn2.Artifact}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Artifacts</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Artifacts</em>' containment reference list.
* @see org.eclipse.bpmn2.Bpmn2Package#getSubChoreography_Artifacts()
* @model containment="true" ordered="false"
* extendedMetaData="kind='element' name='artifact' namespace='http://www.omg.org/spec/BPMN/20100524/MODEL' group='http://www.omg.org/spec/BPMN/20100524/MODEL#artifact'"
* @generated
*/
List<Artifact> getArtifacts();
} // SubChoreography
| {
"content_hash": "602745236d5aae08e94a2e5b100c852a",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 180,
"avg_line_length": 36.475,
"alnum_prop": 0.6620973269362577,
"repo_name": "MetSystem/fixflow",
"id": "662c5271da5a669ee483cfc6d77c37cc3ab57875",
"size": "1900",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "modules/fixflow-core/src/main/java/org/eclipse/bpmn2/SubChoreography.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1011611"
},
{
"name": "HTML",
"bytes": "110708"
},
{
"name": "Java",
"bytes": "7659954"
},
{
"name": "JavaScript",
"bytes": "4130424"
},
{
"name": "PLSQL",
"bytes": "23816"
},
{
"name": "XSLT",
"bytes": "1832"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2020 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M21,6h-2v9L6,15v2c0,0.55 0.45,1 1,1h11l4,4L22,7c0,-0.55 -0.45,-1 -1,-1zM17,12L17,3c0,-0.55 -0.45,-1 -1,-1L3,2c-0.55,0 -1,0.45 -1,1v14l4,-4h10c0.55,0 1,-0.45 1,-1z" />
</vector>
| {
"content_hash": "60cea9b9b144c9be36ae71e79b9f743b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 192,
"avg_line_length": 44.73076923076923,
"alnum_prop": 0.6921754084264833,
"repo_name": "chrisbanes/cheesesquare",
"id": "dc9b90a67d9622c7a533aa99693830dcddb4fe88",
"size": "1163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/ic_forum.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "26955"
}
],
"symlink_target": ""
} |
<?php
namespace App\Modules\Cups\Http\Controllers;
use App\Modules\Cups\Cup;
use App\Modules\Cups\Team;
use Config;
use Contentify\GlobalSearchInterface;
use DB;
use FrontController;
use Illuminate\Http\RedirectResponse;
use MsgException;
use Redirect;
use Request;
use Response;
use URL;
use User;
class TeamsController extends FrontController implements GlobalSearchInterface
{
public function __construct()
{
$this->modelClass = Cup::class;
parent::__construct();
}
/**
* Show all cup teams if $userId is null or show only the cup teams of a specific user
*
* @param int|null $userId
* @throws \Exception
*/
public function overview(int $userId = null)
{
if ($userId) {
$user = User::findOrFail($userId);
$teams = (new Team())->teamsOfUser($user);
$this->pageView('cups::teams_overview_user', compact('user', 'teams'));
} else { // Show all Teams
$perPage = Config::get('app.frontItemsPerPage');
$teams = Team::orderBy('title', 'asc')->paginate($perPage);
$this->pageView('cups::teams_overview', compact('teams'));
}
}
/**
* Shows a cup team
*
* @param int $id The ID of the team
* @return void
* @throws \Exception
*/
public function show(int $id)
{
/** @var Team $team */
$team = Team::findOrFail($id);
$organizer = user() ? $team->isOrganizer(user()) : false;
$this->title($team->title);
$this->pageView('cups::show_team', compact('team', 'organizer'));
}
/**
* Changes the organizer right of a team member
*
* @param int $teamId
* @param int $userId
* @return \Illuminate\Http\Response|null
*/
public function organizer(int $teamId, int $userId)
{
/** @var Team $team */
$team = Team::findOrFail($teamId);
$user = User::findOrFail($userId); // We do not use the $user var but we use findOrFail() for a check
$isOrganizer = (bool) Request::get('organizer');
if (! user()) {
return Response::make(trans('app.no_auth'), 403); // 403: Not allowed
}
if ($team->isOrganizer(user()) or user()->isSuperAdmin()) {
if (! $isOrganizer and sizeof($team->organizers) == 1) {
return Response::make(trans('cups::min_organizers'), 403); // 403: Not allowed
}
DB::table('cups_team_members')->whereTeamId($teamId)->whereUserId($userId)
->update(['organizer' => $isOrganizer]);
return Response::make(null, 200);
} else {
return Response::make(trans('app.access_denied'), 403); // 403: Not allowed
}
}
/**
* The current user wants to join a team.
*
* @param int $teamId The team ID
* @return RedirectResponse|null
* @throws \Exception
*/
public function join(int $teamId)
{
/** @var Team $team */
$team = Team::findOrFail($teamId);
if (! user()) {
$this->alertError(trans('app.not_possible'));
return null;
}
if ($team->password) {
$password = Request::get('password');
if ($password === null) {
$this->pageView('cups::password_form', compact('team'));
return null;
}
if ($password !== $team->password) {
return Redirect::to('cups/teams/join/'.$teamId)->withErrors(trans('cups::wrong_password'));
}
}
try {
$team->tryAddMember(user());
} catch (MsgException $exception) {
$this->alertError($exception->getMessage());
return null;
}
$this->alertFlash(trans('app.successful'));
return Redirect::to('cups/teams/'.$team->id.'/'.$team->slug);
}
/**
* Makes a user leave a cup team
*
* @param int $teamId The ID of the team
* @param int $userId The ID of the user
* @return RedirectResponse|null
*/
public function leave(int $teamId, int $userId)
{
/** @var Team $team */
$team = Team::findOrFail($teamId);
$user = User::findOrFail($userId);
if (! user()) {
$this->alertError(trans('app.no_auth'));
return null;
}
$organizer = $team->isOrganizer(user());
if (user()->id == $userId or $organizer or user()->isSuperAdmin()) {
if ($team->isLocked()) {
$this->alertError(trans('cups::team_locked'));
return null;
}
if (sizeof($team->organizers) == 1) {
foreach ($team->organizers as $organizer) {
if ($organizer->id == $userId) {
$this->alertError(trans('cups::min_organizers'));
return null;
}
}
}
$team->removeMembers([$userId]);
$this->alertFlash(trans('app.successful'));
return Redirect::to('cups/teams/'.$team->id.'/'.$team->slug);
} else {
$this->alertError(trans('app.access_denied'));
return null;
}
}
/**
* Shows a form that allows the user to create a team.
*
* @return void
* @throws \Exception
*/
public function create()
{
if (! user()) {
$this->alertError(trans('app.no_auth'));
return;
}
$this->pageView('cups::team_form', ['team' => null]);
}
/**
* Creates a new team.
*
* @return RedirectResponse|null
* @throws \Exception
*/
public function store()
{
if (! user()) {
$this->alertError(trans('app.no_auth'));
return null;
}
$team = new Team;
$team->title = trim(Request::get('title'));
$team->createSlug();
$team->password = Request::get('password');
$team->creator_id = user()->id;
$okay = $team->save();
if (! $okay) {
return Redirect::to('cups/teams/create')->withInput()->withErrors($team->getErrors());
}
$tmp = $team->id; // We need to do that to force Eloquent to refresh the id attribute.
$team->addMember(user(), true);
$result = $team->uploadFile('image', true);
if ($result) {
return Redirect::to('cups/teams/edit/'.$team->id)->withInput()->withErrors($result);
}
$this->alertFlash(trans('app.successful'));
return Redirect::to('cups/teams/'.$team->id.'/'.$team->slug);
}
/**
* Shows a form that allows the user to edit a team.
*
* @param int $id The ID of the team
* @return void
* @throws \Exception
*/
public function edit(int $id)
{
/** @var Team $team */
$team = Team::findOrFail($id);
if (! user()) {
$this->alertError(trans('app.no_auth'));
return;
}
if ($team->isOrganizer(user()) or user()->isSuperAdmin()) {
$this->pageView('cups::team_form', compact('team'));
} else {
$this->alertError(trans('app.access_denied'));
return;
}
}
/**
* Updates the team
*
* @param int $id The ID of the team
* @return RedirectResponse|null
* @throws \Exception
*/
public function update(int $id)
{
if (! user()) {
$this->alertError(trans('app.no_auth'));
return null;
}
/** @var Team $team */
$team = Team::findOrFail($id);
$team->title = trim(Request::get('title'));
$team->createSlug();
$team->password = Request::get('password');
$team->updater_id = user()->id;
$okay = $team->save();
if (! $okay) {
return Redirect::to('cups/teams/edit/'.$id)->withInput()->withErrors($team->getErrors());
}
$result = $team->uploadFile('image', true);
if ($result) {
return Redirect::to('cups/teams/edit/'.$id)->withInput()->withErrors($result);
}
$this->alertFlash(trans('app.successful'));
return Redirect::to('cups/teams/'.$team->id.'/'.$team->slug);
}
/**
* "Deletes" a team. Actually it won't be deleted but just marked as deleted.
*
* @param int $id The ID of the team
* @return RedirectResponse|null
* @throws \Exception
*/
public function delete(int $id)
{
if (! user()) {
$this->alertError(trans('app.no_auth'));
return null;
}
/** @var Team $team */
$team = Team::findOrFail($id);
if ($team->isLocked()) {
$this->alertError(trans('app.team_locked'));
return null;
}
if ($team->isOrganizer(user()) or user()->isSuperAdmin()) {
$team->invisible = true;
$team->title = 'Deleted';
$team->createSlug();
$team->forceSave();
$team->removeMembers();
$this->alertSuccess(trans('app.successful'));
return Redirect::to('cups/teams/overview/'.user()->id);
} else {
$this->alertError(trans('app.access_denied'));
return null;
}
}
/**
* This method is called by the global search (SearchController->postCreate()).
* Its purpose is to return an array with results for a specific search query.
*
* @param string $subject The search term
* @return string[]
*/
public function globalSearch(string $subject) : array
{
$teams = Team::where('title', 'LIKE', '%'.$subject.'%')->get();
$results = [];
foreach ($teams as $team) {
$results[$team->title] = URL::to('cups/teams/'.$team->id.'/'.$team->slug);
}
return $results;
}
}
| {
"content_hash": "61cf7e8475f6eee6db2f497c33bce9ca",
"timestamp": "",
"source": "github",
"line_count": 355,
"max_line_length": 109,
"avg_line_length": 28.208450704225353,
"alnum_prop": 0.5140802875973637,
"repo_name": "Contentify/Contentify",
"id": "3ac0587f6644ae89e5c25cedefc039a925e4a26a",
"size": "10014",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.2-dev",
"path": "app/Modules/Cups/Http/Controllers/TeamsController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "236956"
},
{
"name": "CSS",
"bytes": "744828"
},
{
"name": "Dockerfile",
"bytes": "692"
},
{
"name": "JavaScript",
"bytes": "3045"
},
{
"name": "Less",
"bytes": "280512"
},
{
"name": "PHP",
"bytes": "1582905"
},
{
"name": "Shell",
"bytes": "780"
}
],
"symlink_target": ""
} |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.engine.impl.agenda;
import org.flowable.bpmn.model.BoundaryEvent;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.impl.delegate.ActivityBehavior;
import org.flowable.engine.impl.delegate.TriggerableActivityBehavior;
import org.flowable.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
/**
* Operation that triggers a wait state and continues the process, leaving that activity.
*
* The {@link ExecutionEntity} for this operations should be in a wait state (receive task for example)
* and have a {@link FlowElement} that has a behaviour that implements the {@link TriggerableActivityBehavior}.
*
* @author Joram Barrez
*/
public class TriggerExecutionOperation extends AbstractOperation {
public TriggerExecutionOperation(CommandContext commandContext, ExecutionEntity execution) {
super(commandContext, execution);
}
@Override
public void run() {
FlowElement currentFlowElement = getCurrentFlowElement(execution);
if (currentFlowElement instanceof FlowNode) {
ActivityBehavior activityBehavior = (ActivityBehavior) ((FlowNode) currentFlowElement).getBehavior();
if (activityBehavior instanceof TriggerableActivityBehavior) {
if (currentFlowElement instanceof BoundaryEvent) {
commandContext.getHistoryManager().recordActivityStart(execution);
}
((TriggerableActivityBehavior) activityBehavior).trigger(execution, null, null);
if (currentFlowElement instanceof BoundaryEvent) {
commandContext.getHistoryManager().recordActivityEnd(execution, null);
}
} else {
throw new FlowableException("Invalid behavior: " + activityBehavior + " should implement " + TriggerableActivityBehavior.class.getName());
}
} else {
throw new FlowableException("Programmatic error: no current flow element found or invalid type: " + currentFlowElement + ". Halting.");
}
}
}
| {
"content_hash": "8684aa61d78f7e2ae08244769f56d672",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 146,
"avg_line_length": 41.52307692307692,
"alnum_prop": 0.7465728047424972,
"repo_name": "motorina0/flowable-engine",
"id": "c79175b9b80f3ec47863ab27bb5c1cb11c507bde",
"size": "2699",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/flowable-engine/src/main/java/org/flowable/engine/impl/agenda/TriggerExecutionOperation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "96556"
},
{
"name": "Batchfile",
"bytes": "166"
},
{
"name": "CSS",
"bytes": "681931"
},
{
"name": "HTML",
"bytes": "858905"
},
{
"name": "Java",
"bytes": "22289599"
},
{
"name": "JavaScript",
"bytes": "12782950"
},
{
"name": "Shell",
"bytes": "18731"
}
],
"symlink_target": ""
} |
"""Test the wallet keypool and interaction with wallet encryption/locking."""
import time
from decimal import Decimal
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
class KeyPoolTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
nodes = self.nodes
addr_before_encrypting = nodes[0].getnewaddress()
addr_before_encrypting_data = nodes[0].getaddressinfo(addr_before_encrypting)
wallet_info_old = nodes[0].getwalletinfo()
if not self.options.descriptors:
assert addr_before_encrypting_data['hdseedid'] == wallet_info_old['hdseedid']
# Encrypt wallet and wait to terminate
nodes[0].encryptwallet('test')
if self.options.descriptors:
# Import hardened derivation only descriptors
nodes[0].walletpassphrase('test', 10)
nodes[0].importdescriptors([
{
"desc": "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/*h)#y4dfsj7n",
"timestamp": "now",
"range": [0,0],
"active": True
},
{
"desc": "pkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1h/*h)#a0nyvl0k",
"timestamp": "now",
"range": [0,0],
"active": True
},
{
"desc": "sh(wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/2h/*h))#lmeu2axg",
"timestamp": "now",
"range": [0,0],
"active": True
},
{
"desc": "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/3h/*h)#jkl636gm",
"timestamp": "now",
"range": [0,0],
"active": True,
"internal": True
},
{
"desc": "pkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/4h/*h)#l3crwaus",
"timestamp": "now",
"range": [0,0],
"active": True,
"internal": True
},
{
"desc": "sh(wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/5h/*h))#qg8wa75f",
"timestamp": "now",
"range": [0,0],
"active": True,
"internal": True
}
])
nodes[0].walletlock()
# Keep creating keys
addr = nodes[0].getnewaddress()
addr_data = nodes[0].getaddressinfo(addr)
wallet_info = nodes[0].getwalletinfo()
assert addr_before_encrypting_data['hdmasterfingerprint'] != addr_data['hdmasterfingerprint']
if not self.options.descriptors:
assert addr_data['hdseedid'] == wallet_info['hdseedid']
assert_raises_rpc_error(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
# put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min)
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(6)
nodes[0].walletlock()
wi = nodes[0].getwalletinfo()
if self.options.descriptors:
assert_equal(wi['keypoolsize_hd_internal'], 18)
assert_equal(wi['keypoolsize'], 18)
else:
assert_equal(wi['keypoolsize_hd_internal'], 6)
assert_equal(wi['keypoolsize'], 6)
# drain the internal keys
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
addr = set()
# the next one should fail
assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getrawchangeaddress)
# drain the external keys
addr.add(nodes[0].getnewaddress(address_type="bech32"))
addr.add(nodes[0].getnewaddress(address_type="bech32"))
addr.add(nodes[0].getnewaddress(address_type="bech32"))
addr.add(nodes[0].getnewaddress(address_type="bech32"))
addr.add(nodes[0].getnewaddress(address_type="bech32"))
addr.add(nodes[0].getnewaddress(address_type="bech32"))
assert len(addr) == 6
# the next one should fail
assert_raises_rpc_error(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
# refill keypool with three new addresses
nodes[0].walletpassphrase('test', 1)
nodes[0].keypoolrefill(3)
# test walletpassphrase timeout
time.sleep(1.1)
assert_equal(nodes[0].getwalletinfo()["unlocked_until"], 0)
# drain the keypool
for _ in range(3):
nodes[0].getnewaddress()
assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getnewaddress)
nodes[0].walletpassphrase('test', 100)
nodes[0].keypoolrefill(100)
wi = nodes[0].getwalletinfo()
if self.options.descriptors:
assert_equal(wi['keypoolsize_hd_internal'], 300)
assert_equal(wi['keypoolsize'], 300)
else:
assert_equal(wi['keypoolsize_hd_internal'], 100)
assert_equal(wi['keypoolsize'], 100)
# create a blank wallet
nodes[0].createwallet(wallet_name='w2', blank=True, disable_private_keys=True)
w2 = nodes[0].get_wallet_rpc('w2')
# refer to initial wallet as w1
w1 = nodes[0].get_wallet_rpc('')
# import private key and fund it
address = addr.pop()
desc = w1.getaddressinfo(address)['desc']
if self.options.descriptors:
res = w2.importdescriptors([{'desc': desc, 'timestamp': 'now'}])
else:
res = w2.importmulti([{'desc': desc, 'timestamp': 'now'}])
assert_equal(res[0]['success'], True)
w1.walletpassphrase('test', 100)
res = w1.sendtoaddress(address=address, amount=0.00010000)
nodes[0].generate(1)
destination = addr.pop()
# Using a fee rate (10 sat / byte) well above the minimum relay rate
# creating a 5,000 sat transaction with change should not be possible
assert_raises_rpc_error(-4, "Transaction needs a change address, but we can't generate it. Please call keypoolrefill first.", w2.walletcreatefundedpsbt, inputs=[], outputs=[{addr.pop(): 0.00005000}], options={"subtractFeeFromOutputs": [0], "feeRate": 0.00010})
# creating a 10,000 sat transaction without change, with a manual input, should still be possible
res = w2.walletcreatefundedpsbt(inputs=w2.listunspent(), outputs=[{destination: 0.00010000}], options={"subtractFeeFromOutputs": [0], "feeRate": 0.00010})
assert_equal("psbt" in res, True)
# creating a 10,000 sat transaction without change should still be possible
res = w2.walletcreatefundedpsbt(inputs=[], outputs=[{destination: 0.00010000}], options={"subtractFeeFromOutputs": [0], "feeRate": 0.00010})
assert_equal("psbt" in res, True)
# should work without subtractFeeFromOutputs if the exact fee is subtracted from the amount
res = w2.walletcreatefundedpsbt(inputs=[], outputs=[{destination: 0.00008900}], options={"feeRate": 0.00010})
assert_equal("psbt" in res, True)
# dust change should be removed
res = w2.walletcreatefundedpsbt(inputs=[], outputs=[{destination: 0.00008800}], options={"feeRate": 0.00010})
assert_equal("psbt" in res, True)
# create a transaction without change at the maximum fee rate, such that the output is still spendable:
res = w2.walletcreatefundedpsbt(inputs=[], outputs=[{destination: 0.00010000}], options={"subtractFeeFromOutputs": [0], "feeRate": 0.0008824})
assert_equal("psbt" in res, True)
assert_equal(res["fee"], Decimal("0.00009706"))
# creating a 10,000 sat transaction with a manual change address should be possible
res = w2.walletcreatefundedpsbt(inputs=[], outputs=[{destination: 0.00010000}], options={"subtractFeeFromOutputs": [0], "feeRate": 0.00010, "changeAddress": addr.pop()})
assert_equal("psbt" in res, True)
if __name__ == '__main__':
KeyPoolTest().main()
| {
"content_hash": "687a404bbd57b02c9885ab876d04e373",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 268,
"avg_line_length": 47.67553191489362,
"alnum_prop": 0.6115140020082561,
"repo_name": "midnightmagic/bitcoin",
"id": "40a2b3ab6a1b2b72faa374c07f5a05e825895085",
"size": "9177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/functional/wallet_keypool.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "534165"
},
{
"name": "C++",
"bytes": "3705952"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Groff",
"bytes": "19797"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "Makefile",
"bytes": "65360"
},
{
"name": "Objective-C",
"bytes": "2022"
},
{
"name": "Objective-C++",
"bytes": "7238"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "447889"
},
{
"name": "QMake",
"bytes": "2019"
},
{
"name": "Shell",
"bytes": "40702"
}
],
"symlink_target": ""
} |
#include "mali_kernel_common.h"
#include "mali_memory.h"
#include "mali_memory_block_alloc.h"
#include "mali_osk.h"
#include <linux/mutex.h>
#define MALI_BLOCK_SIZE (256UL * 1024UL) /* 256 kB, remember to keep the ()s */
struct block_info {
struct block_info *next;
};
typedef struct block_info block_info;
typedef struct block_allocator {
struct mutex mutex;
block_info *all_blocks;
block_info *first_free;
u32 base;
u32 cpu_usage_adjust;
u32 num_blocks;
u32 free_blocks;
} block_allocator;
static block_allocator *mali_mem_block_gobal_allocator = NULL;
MALI_STATIC_INLINE u32 get_phys(block_allocator *info, block_info *block)
{
return info->base + ((block - info->all_blocks) * MALI_BLOCK_SIZE);
}
mali_mem_allocator *mali_mem_block_allocator_create(u32 base_address, u32 cpu_usage_adjust, u32 size)
{
block_allocator *info;
u32 usable_size;
u32 num_blocks;
usable_size = size & ~(MALI_BLOCK_SIZE - 1);
MALI_DEBUG_PRINT(3, ("Mali block allocator create for region starting at 0x%08X length 0x%08X\n", base_address, size));
MALI_DEBUG_PRINT(4, ("%d usable bytes\n", usable_size));
num_blocks = usable_size / MALI_BLOCK_SIZE;
MALI_DEBUG_PRINT(4, ("which becomes %d blocks\n", num_blocks));
if (usable_size == 0) {
MALI_DEBUG_PRINT(1, ("Memory block of size %d is unusable\n", size));
return NULL;
}
info = _mali_osk_malloc(sizeof(block_allocator));
if (NULL != info) {
mutex_init(&info->mutex);
info->all_blocks = _mali_osk_malloc(sizeof(block_info) * num_blocks);
if (NULL != info->all_blocks) {
u32 i;
info->first_free = NULL;
info->num_blocks = num_blocks;
info->free_blocks = num_blocks;
info->base = base_address;
info->cpu_usage_adjust = cpu_usage_adjust;
for ( i = 0; i < num_blocks; i++) {
info->all_blocks[i].next = info->first_free;
info->first_free = &info->all_blocks[i];
}
return (mali_mem_allocator *)info;
}
_mali_osk_free(info);
}
return NULL;
}
void mali_mem_block_allocator_destroy(mali_mem_allocator *allocator)
{
block_allocator *info = (block_allocator*)allocator;
info = mali_mem_block_gobal_allocator;
if (NULL == info) return;
MALI_DEBUG_ASSERT_POINTER(info);
_mali_osk_free(info->all_blocks);
_mali_osk_free(info);
}
static void mali_mem_block_mali_map(mali_mem_allocation *descriptor, u32 phys, u32 virt, u32 size)
{
struct mali_page_directory *pagedir = descriptor->session->page_directory;
u32 prop = descriptor->mali_mapping.properties;
u32 offset = 0;
while (size) {
mali_mmu_pagedir_update(pagedir, virt + offset, phys + offset, MALI_MMU_PAGE_SIZE, prop);
size -= MALI_MMU_PAGE_SIZE;
offset += MALI_MMU_PAGE_SIZE;
}
}
static int mali_mem_block_cpu_map(mali_mem_allocation *descriptor, struct vm_area_struct *vma, u32 mali_phys, u32 mapping_offset, u32 size, u32 cpu_usage_adjust)
{
u32 virt = vma->vm_start + mapping_offset;
u32 cpu_phys = mali_phys + cpu_usage_adjust;
u32 offset = 0;
int ret;
while (size) {
ret = vm_insert_pfn(vma, virt + offset, __phys_to_pfn(cpu_phys + offset));
if (unlikely(ret)) {
MALI_DEBUG_PRINT(1, ("Block allocator: Failed to insert pfn into vma\n"));
return 1;
}
size -= MALI_MMU_PAGE_SIZE;
offset += MALI_MMU_PAGE_SIZE;
}
return 0;
}
mali_mem_allocation *mali_mem_block_alloc(u32 mali_addr, u32 size, struct vm_area_struct *vma, struct mali_session_data *session)
{
_mali_osk_errcode_t err;
mali_mem_allocation *descriptor;
block_allocator *info;
u32 left;
block_info *last_allocated = NULL;
block_allocator_allocation *ret_allocation;
u32 offset = 0;
size = ALIGN(size, MALI_BLOCK_SIZE);
info = mali_mem_block_gobal_allocator;
if (NULL == info) return NULL;
left = size;
MALI_DEBUG_ASSERT(0 != left);
descriptor = mali_mem_descriptor_create(session, MALI_MEM_BLOCK);
if (NULL == descriptor) {
return NULL;
}
descriptor->mali_mapping.addr = mali_addr;
descriptor->size = size;
descriptor->cpu_mapping.addr = (void __user*)vma->vm_start;
descriptor->cpu_mapping.ref = 1;
if (VM_SHARED == (VM_SHARED & vma->vm_flags)) {
descriptor->mali_mapping.properties = MALI_MMU_FLAGS_DEFAULT;
} else {
/* Cached Mali memory mapping */
descriptor->mali_mapping.properties = MALI_MMU_FLAGS_FORCE_GP_READ_ALLOCATE;
vma->vm_flags |= VM_SHARED;
}
ret_allocation = &descriptor->block_mem.mem;
ret_allocation->mapping_length = 0;
_mali_osk_mutex_wait(session->memory_lock);
mutex_lock(&info->mutex);
if (left > (info->free_blocks * MALI_BLOCK_SIZE)) {
MALI_DEBUG_PRINT(2, ("Mali block allocator: not enough free blocks to service allocation (%u)\n", left));
mutex_unlock(&info->mutex);
_mali_osk_mutex_signal(session->memory_lock);
mali_mem_descriptor_destroy(descriptor);
return NULL;
}
err = mali_mem_mali_map_prepare(descriptor);
if (_MALI_OSK_ERR_OK != err) {
mutex_unlock(&info->mutex);
_mali_osk_mutex_signal(session->memory_lock);
mali_mem_descriptor_destroy(descriptor);
return NULL;
}
while ((left > 0) && (info->first_free)) {
block_info *block;
u32 phys_addr;
u32 current_mapping_size;
block = info->first_free;
info->first_free = info->first_free->next;
block->next = last_allocated;
last_allocated = block;
phys_addr = get_phys(info, block);
if (MALI_BLOCK_SIZE < left) {
current_mapping_size = MALI_BLOCK_SIZE;
} else {
current_mapping_size = left;
}
mali_mem_block_mali_map(descriptor, phys_addr, mali_addr + offset, current_mapping_size);
if (mali_mem_block_cpu_map(descriptor, vma, phys_addr, offset, current_mapping_size, info->cpu_usage_adjust)) {
/* release all memory back to the pool */
while (last_allocated) {
/* This relinks every block we've just allocated back into the free-list */
block = last_allocated->next;
last_allocated->next = info->first_free;
info->first_free = last_allocated;
last_allocated = block;
}
mutex_unlock(&info->mutex);
_mali_osk_mutex_signal(session->memory_lock);
mali_mem_mali_map_free(descriptor);
mali_mem_descriptor_destroy(descriptor);
return NULL;
}
left -= current_mapping_size;
offset += current_mapping_size;
ret_allocation->mapping_length += current_mapping_size;
--info->free_blocks;
}
mutex_unlock(&info->mutex);
_mali_osk_mutex_signal(session->memory_lock);
MALI_DEBUG_ASSERT(0 == left);
/* Record all the information about this allocation */
ret_allocation->last_allocated = last_allocated;
ret_allocation->info = info;
return descriptor;
}
void mali_mem_block_release(mali_mem_allocation *descriptor)
{
block_allocator *info = descriptor->block_mem.mem.info;
block_info *block, *next;
block_allocator_allocation *allocation = &descriptor->block_mem.mem;
MALI_DEBUG_ASSERT(MALI_MEM_BLOCK == descriptor->type);
block = allocation->last_allocated;
MALI_DEBUG_ASSERT_POINTER(block);
/* unmap */
mali_mem_mali_map_free(descriptor);
mutex_lock(&info->mutex);
while (block) {
MALI_DEBUG_ASSERT(!((block < info->all_blocks) || (block > (info->all_blocks + info->num_blocks))));
next = block->next;
/* relink into free-list */
block->next = info->first_free;
info->first_free = block;
/* advance the loop */
block = next;
++info->free_blocks;
}
mutex_unlock(&info->mutex);
}
u32 mali_mem_block_allocator_stat(void)
{
block_allocator *info = (block_allocator *)mali_mem_block_gobal_allocator;
if (NULL == info) return 0;
MALI_DEBUG_ASSERT_POINTER(info);
return (info->num_blocks - info->free_blocks) * MALI_BLOCK_SIZE;
}
_mali_osk_errcode_t mali_memory_core_resource_dedicated_memory(u32 start, u32 size)
{
mali_mem_allocator *allocator;
/* Do the low level linux operation first */
/* Request ownership of the memory */
if (_MALI_OSK_ERR_OK != _mali_osk_mem_reqregion(start, size, "Dedicated Mali GPU memory")) {
MALI_DEBUG_PRINT(1, ("Failed to request memory region for frame buffer (0x%08X - 0x%08X)\n", start, start + size - 1));
return _MALI_OSK_ERR_FAULT;
}
/* Create generic block allocator object to handle it */
allocator = mali_mem_block_allocator_create(start, 0 /* cpu_usage_adjust */, size);
if (NULL == allocator) {
MALI_DEBUG_PRINT(1, ("Memory bank registration failed\n"));
_mali_osk_mem_unreqregion(start, size);
MALI_ERROR(_MALI_OSK_ERR_FAULT);
}
mali_mem_block_gobal_allocator = (block_allocator*)allocator;
return _MALI_OSK_ERR_OK;
}
| {
"content_hash": "95d4ba371f2e69571e978490c6cc9796",
"timestamp": "",
"source": "github",
"line_count": 311,
"max_line_length": 161,
"avg_line_length": 26.84887459807074,
"alnum_prop": 0.687185628742515,
"repo_name": "indashnet/InDashNet.Open.UN2000",
"id": "2847893dcd2d40239f1fbb88d84544cd489c4a80",
"size": "8852",
"binary": false,
"copies": "103",
"ref": "refs/heads/master",
"path": "lichee/linux-3.4/modules/mali/DX910-SW-99002-r4p0-00rel0/driver/src/devicedrv/mali/linux/mali_memory_block_alloc.c",
"mode": "33261",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#region
using NUnit.Framework;
using RMIT.Counter.Libraries.Library.Common;
#endregion
namespace RMIT.Counter.Test.Unit.Libraries.Library.Common
{
[TestFixture]
public class StringExtensionsTest
{
[Test]
public void ToProperCase()
{
var expect = "Abc";
var result = "abc".ToProperCase();
Assert.AreEqual(expect, result);
expect = "The Project Is Ok";
result = "the project is ok".ToProperCase();
Assert.AreEqual(expect, result);
expect = "The Project Is Ok, But How To Prove It?";
result = "the project is ok, but how to prove it?".ToProperCase();
Assert.AreEqual(expect, result);
}
}
} | {
"content_hash": "0cad9e2b0e6478d34dc24284ccef82a3",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 78,
"avg_line_length": 24.161290322580644,
"alnum_prop": 0.5847797062750334,
"repo_name": "rmittraining/CounterCompliance",
"id": "313cb2de832a90407ea7506ea9790d4570155484",
"size": "2242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests/Unit/Libraries/Library/Common/StringExtensions.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "108"
},
{
"name": "C#",
"bytes": "486451"
},
{
"name": "CSS",
"bytes": "2626"
},
{
"name": "HTML",
"bytes": "2993"
},
{
"name": "JavaScript",
"bytes": "10714"
},
{
"name": "XSLT",
"bytes": "119907"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/C:/Users/assy/Documents/GitHub/PhotoGramApp/ParseStarterProject/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.0/res/values-w600dp/values-w600dp.xml -->
<eat-comment/>
<dimen name="abc_search_view_text_min_width">192dip</dimen>
<integer name="abc_max_action_buttons">5</integer>
</resources> | {
"content_hash": "07d90c3bd600a7f48dbf19fb52963f62",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 197,
"avg_line_length": 57,
"alnum_prop": 0.7268170426065163,
"repo_name": "asioh123/PhotoGramApp",
"id": "ee45660e070fa1139331611df28f2101de001cc4",
"size": "399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ParseStarterProject/build/intermediates/res/merged/debug/values-w600dp/values-w600dp.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "450600"
}
],
"symlink_target": ""
} |
package me.echeung.cdflabs.ui.fragments;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import me.echeung.cdflabs.R;
import me.echeung.cdflabs.ui.fragments.base.TabFragment;
public class LocationsFragment extends Fragment {
private static final String BAHEN_MAP_ADDRESS =
"https://www.google.com/maps/place/Bahen+Centre+for+Information+Technology/@43.659489,-79.397613,17z/data=!3m1!4b1!4m2!3m1!1s0x882b34c75165c957:0x6459384147b4b67b?hl=en";
private static final String NX_ADDRESS =
"http://www.cdf.utoronto.ca/using_cdf/remote_access_server.html";
public LocationsFragment() {
}
public static Fragment newInstance(int sectionNumber) {
return TabFragment.newInstance(sectionNumber, new LocationsFragment());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_locations, container, false);
// Google Maps for Bahen address
final TextView bahenAddress = (TextView) rootView.findViewById(R.id.bahen_address);
bahenAddress.setOnClickListener(view -> openLink(BAHEN_MAP_ADDRESS));
// Webpage for NX
final Button nxMore = (Button) rootView.findViewById(R.id.more_nx);
nxMore.setOnClickListener(view -> openLink(NX_ADDRESS));
return rootView;
}
/**
* Opens a web link.
*
* @param link The website URL.
*/
private void openLink(String link) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
startActivity(intent);
}
}
| {
"content_hash": "81a39fe9873c560ea2cb65b6888db4bd",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 182,
"avg_line_length": 33.578947368421055,
"alnum_prop": 0.7027168234064786,
"repo_name": "arkon/CDFLabs",
"id": "64a34a8ffb86180a74348d085d47993e038e1762",
"size": "1914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/me/echeung/cdflabs/ui/fragments/LocationsFragment.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "54548"
}
],
"symlink_target": ""
} |
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsLifecycle.Restart, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Vmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSOperationStatusResponse))]
public partial class RestartAzureRmVmss : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.VMScaleSetName, VerbsLifecycle.Restart))
{
string resourceGroupName = this.ResourceGroupName;
string vmScaleSetName = this.VMScaleSetName;
System.Collections.Generic.IList<string> instanceIds = this.InstanceId;
var result = VirtualMachineScaleSetsClient.RestartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceIds).GetAwaiter().GetResult();
PSOperationStatusResponse output = new PSOperationStatusResponse
{
StartTime = this.StartTime,
EndTime = DateTime.Now
};
if (result != null && result.Request != null && result.Request.RequestUri != null)
{
output.Name = GetOperationIdFromUrlString(result.Request.RequestUri.ToString());
}
WriteObject(output);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceNameCompleter("Microsoft.Compute/virtualMachineScaleSets", "ResourceGroupName")]
[Alias("Name")]
public string VMScaleSetName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 3,
ValueFromPipelineByPropertyName = true)]
public string [] InstanceId { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
}
}
| {
"content_hash": "b2b2a76017cfe518460e78bfe167e60e",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 176,
"avg_line_length": 40.67605633802817,
"alnum_prop": 0.6243074792243767,
"repo_name": "AzureAutomationTeam/azure-powershell",
"id": "915e1f9c38d3841a31adb6dabf922a196261db45",
"size": "3670",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/ResourceManager/Compute/Commands.Compute/Generated/VirtualMachineScaleSet/VirtualMachineScaleSetRestartMethod.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "14962309"
},
{
"name": "HTML",
"bytes": "209"
},
{
"name": "JavaScript",
"bytes": "4979"
},
{
"name": "PHP",
"bytes": "41"
},
{
"name": "PowerShell",
"bytes": "691666"
},
{
"name": "Python",
"bytes": "20483"
},
{
"name": "Shell",
"bytes": "15168"
}
],
"symlink_target": ""
} |
define([
'underscore',
'backbone',
'json!configPath/config.json',
'marionette',
'templates'
], function (_, Backbone, config) {
var RealNotificationDetailView = Backbone.Marionette.ItemView.extend({
template: 'real-notification-detail',
className: 'modal fade',
attributes: function() {
return {
id: this.model.get('id'),
tabindex: -1,
role: 'dialog',
'aria-labelledby': this.model.get('id'),
'aria-hidden': true
}
},
onBeforeRender: function() {
this.model.set('serverUrl', config.serverUrl);
}
});
return RealNotificationDetailView;
}); | {
"content_hash": "5484c6577fa1d19b340a1f5e63b7bfc2",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 74,
"avg_line_length": 20.694444444444443,
"alnum_prop": 0.5221476510067115,
"repo_name": "matthis-d/NotificationEngine-front",
"id": "7709bd1b23e6f1bb3e5e6112ae74620904b85ceb",
"size": "745",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/scripts/views/real-notification-detail-view.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3864"
},
{
"name": "JavaScript",
"bytes": "321456"
}
],
"symlink_target": ""
} |
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin({
filename: 'css/[name].css',
allChunks: true
});
module.exports = {
entry: {
index: './client/Content.js'
},
ssrWebpack: {
plugins: [
new webpack.BannerPlugin('This file is created by coren. Built time: ' + new Date()),
extractCSS
],
module: {
rules: [
{
test: /\.css$/,
use: extractCSS.extract(["css-loader?minimize"])
}
]
}
},
assetsHost: (env, absolutePath = '') => {
const rel = path.relative(`${__dirname}/public/dist/`, absolutePath);
switch (env) {
case 'production':
return `/dist/${rel}`;
case 'development':
return `http://localhost:5556/dist/${rel}`;
default:
return false;
}
}
};
| {
"content_hash": "2234437f0a8f6adefc9969198c11205d",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 91,
"avg_line_length": 23.53846153846154,
"alnum_prop": 0.5664488017429193,
"repo_name": "Canner/coren",
"id": "e2352d6265380483e38ff46475a51b7066c4eec1",
"size": "918",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/withCss/coren.config.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1847"
},
{
"name": "JavaScript",
"bytes": "44083"
}
],
"symlink_target": ""
} |
Repository for CSCI 4940
Austin Peay State University, Clarksville, TN
Fall 2016
David Pridemore (me@davidpridemore.com)
Austin Buchanan (abuchanan5@my.apsu.edu)
We completed this project for a local company and for a course credit internship.
This is a web scraper project that pulls data from allbreedpedigree.com. You
must have a working account with allbreedpedigree.com for the application to
return data.
See license.md for MIT licensing information.
## about the app
This app will generate horse inbreeding statistics for quarter horses based on user input.
This app uses PHP to scrape allbreedpedigree.com for information on each horse the user enters,
then outputs that information into a .csv file.
## getting started
Upon first accessing the app, you will be greeted with a login screen.
Enter your allbreedpedigree.com username and password to continue to the horse entry form.
If you enter the wrong password or username, you will still be able to access the app,
but you will not be able to generate a report upon querying the website.
## main page
The main page for the app contains a text area field where horse names can be entered,
and 4 drop down menus for additional constraints. These constraints include:
* the kind of report you want to generate (Cross Dups, Dups Only, All Horses, Males Only, Females Only)
* the number of generations you want to include (4-20)
* the number of crosses you want to do (2-10)
* the influence (All, >2x3, >3x3, >3x4, >4x4, >4x5, >5x5, >5x6)
When you are finished adding horse names, and you have selected your constraint values, click "Submit Query."
The app will then scrape allbreedpedigree.com to look for the information that you entered, and output that
information into a .csv file.
## the .csv file
The .csv file organizes information by horse in the order that you entered it in a table-style fashion.
These tables include the horse's name and an inbreeding coefficient at the top of each table, and varying rows
of data consisting of:
* the horse's relative's name
* the inbreeding stats
* the number of crosses
* the lines
* the blood %
* the influence
* the AGR
If there is no data in the table, it means that you have entered the wrong username and/or password.
If there is no data in 1 or more tables, but there are inbreeding coeffecients, it means that allbreedpedigree.com
does not have a record of that horse's relatives for the specified constraints.
| {
"content_hash": "0bc06a1c195e79900fab22214deb7271",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 115,
"avg_line_length": 48.72549019607843,
"alnum_prop": 0.7686116700201208,
"repo_name": "austinbuchanan/ricardoracing",
"id": "70ff07fc5cb274890b6f2da1f960c92f7e55e445",
"size": "2501",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "437"
},
{
"name": "PHP",
"bytes": "83172"
}
],
"symlink_target": ""
} |
programinit()
function main() {
var filename = COMMAND.f(2);//field(SENTENCE, " ", 2).lcase();
if (filename && not filename.starts("dict."))
filename = "dict." ^ filename;
//perform("list " ^ dictfilename ^ " by type \"F\" by FMC by PART");
//list the dictionary filenames if none provided
if (not filename) {
//copy of rules in mvdbpostgres.cpp
var dictdb = "";
//dictdb.osgetenv("EXO_DICT");
if (not dictdb.osgetenv("EXO_DICT")) {
//null
}
if (not dictdb) {
//dictdb = "exodus_dict";
dictdb = "exodus";
}
var conn;
if (not conn.connect(dictdb)) {
//connect to default db
//conn.connect();
if (not conn.connect()) {
abort(lasterror());
}
}
//GB version
// let dictdb = "";
// if (not dictdb.osgetenv("EXO_DICT")) {
// dictdb = "";
// //default is exodus i.e ""
// }
// let conn;
// if (not conn.connect(dictdb)) {
// abort();
var dictfilenames = "";
let filenames = conn.listfiles();
for (var filename : filenames) {
if (filename.starts("dict."))
dictfilenames ^= filename ^ FM;
}
dictfilenames.replacer(FM, "\n");
print(dictfilenames);
return 0;
}
var cmd = "list " ^ filename;
// Need to escape/add quotes for bash
//cmd ^= " " ^ COMMAND.field(FM, 3, 999999999).convert(FM, " ");
if (filename == "dict.all")
cmd ^= " ID-SUPP FILE_NAME FIELD_NAME @CRT BY FILE_NAME";
cmd ^= " by TYPE by FMC by PART by MASTER_FLAG";
//cmd ^= " by TYPE by-dsnd MASTER_FLAG by FMC by PART";
//cmd ^= " " ^ COMMAND.field(FM, 3, 999999999).convert(FM, " ");
cmd ^= " {" ^ OPTIONS ^ "}";
if (OPTIONS.contains("V"))
logputl(cmd);
osshell(cmd) or lasterror().errputl("listdict:");
return 0;
}
programexit()
| {
"content_hash": "74fd64ea13b29355590b5c4fda262923",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 69,
"avg_line_length": 21.833333333333332,
"alnum_prop": 0.5948326482677627,
"repo_name": "exodusdb/exodusdb",
"id": "540703d4f35d7743c9bc49d8597c721b2e52af33",
"size": "1731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cli/src/listdict.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "48844"
},
{
"name": "C++",
"bytes": "2692110"
},
{
"name": "CMake",
"bytes": "31492"
},
{
"name": "CSS",
"bytes": "27076"
},
{
"name": "Classic ASP",
"bytes": "51959"
},
{
"name": "HTML",
"bytes": "502802"
},
{
"name": "JavaScript",
"bytes": "852795"
},
{
"name": "Makefile",
"bytes": "32"
},
{
"name": "PHP",
"bytes": "69433"
},
{
"name": "Python",
"bytes": "4101"
},
{
"name": "Shell",
"bytes": "66668"
}
],
"symlink_target": ""
} |
<?php
$site_guid = elgg_get_site_entity()->getGUID();
$metadata_name = trim(get_input("metadata_name"));
$metadata_label = trim(get_input("metadata_label"));
$metadata_hint = trim(get_input("metadata_hint"));
$metadata_type = get_input("metadata_type");
$metadata_options = get_input("metadata_options");
$show_on_register = get_input("show_on_register");
$mandatory = get_input("mandatory");
$user_editable = get_input("user_editable");
$output_as_tags = get_input("output_as_tags");
$admin_only = get_input("admin_only");
$blank_available = get_input("blank_available");
$type = get_input("type", "profile");
$guid = get_input("guid");
$reserved_metadata_names = array(
"guid", "title", "access_id", "owner_guid", "container_guid", "type", "subtype", "name", "username", "email", "membership", "group_acl", "icon", "site_guid",
"time_created", "time_updated", "enabled", "tables_split", "tables_loaded", "password", "salt", "language", "code", "banned", "admin", "custom_profile_type",
"icontime", "x1", "x2", "y1", "y2"
);
if($guid){
$current_field = get_entity($guid);
}
if($current_field && ($current_field->getSubtype() != CUSTOM_PROFILE_FIELDS_PROFILE_SUBTYPE && $current_field->getSubtype() != CUSTOM_PROFILE_FIELDS_GROUP_SUBTYPE)){
// wrong custom field type
register_error(elgg_echo("profile_manager:action:new:error:type2"));
} elseif($type != "profile" && $type != "group"){
// wrong custom field type
register_error(elgg_echo("profile_manager:action:new:error:type"));
} elseif(empty($metadata_name)){
// no name
register_error(elgg_echo("profile_manager:actions:new:error:metadata_name_missing"));
} elseif(in_array(strtolower($metadata_name), $reserved_metadata_names) || !preg_match("/^[a-zA-Z0-9_]{1,}$/", $metadata_name)){
// invalid name
register_error(elgg_echo("profile_manager:actions:new:error:metadata_name_invalid"));
} elseif(($metadata_type == "dropdown" || $metadata_type == "radio" || $metadata_type == "multiselect") && empty($metadata_options)){
register_error(elgg_echo("profile_manager:actions:new:error:metadata_options"));
} else {
if(array_key_exists($metadata_name, elgg_get_config('profile_fields'))){
$existing = true;
}
if(empty($current_field) && $existing){
register_error(elgg_echo("profile_manager:actions:new:error:metadata_name_invalid"));
} else {
$new_options = array();
$options_error = false;
if($metadata_type == "dropdown" || $metadata_type == "radio" || $metadata_type == "multiselect"){
$temp_options = explode(",", $metadata_options);
foreach($temp_options as $key => $option) {
$trimmed_option = trim($option);
if(!empty($trimmed_option)){
$new_options[$key] = $trimmed_option;
}
}
if(count($new_options) > 0 ){
$new_options = implode(",", $new_options);
} else {
$options_error = true;
}
}
if(!$options_error){
$options = array(
"type" => "object",
"subtype" => "custom_" . $type . "_field",
"count" => true,
"owner_guid" => $site_guid
);
$max_fields = elgg_get_entities($options) + 1;
if($current_field){
$field = $current_field;
} else {
$field = new ElggObject();
$field->owner_guid = $site_guid;
$field->container_guid = $site_guid;
$field->access_id = ACCESS_PUBLIC;
$field->subtype = "custom_" . $type . "_field";
$field->save();
}
$field->metadata_name = $metadata_name;
if(!empty($metadata_label)){
$field->metadata_label = $metadata_label;
} elseif($current_field){
unset($field->metadata_label);
}
if(!empty($metadata_hint)){
$field->metadata_hint = $metadata_hint;
} elseif($current_field){
unset($field->metadata_hint);
}
$field->metadata_type = $metadata_type;
if($metadata_type == "dropdown" || $metadata_type == "radio" || $metadata_type == "multiselect"){
$field->metadata_options = $new_options;
} elseif($current_field) {
$field->clearMetaData("metadata_options");
}
if($type == "profile"){
$field->show_on_register = $show_on_register;
$field->mandatory = $mandatory;
$field->user_editable = $user_editable;
}
$field->admin_only = $admin_only;
$field->output_as_tags = $output_as_tags;
$field->blank_available = $blank_available;
if(empty($current_field)){
$field->order = $max_fields;
}
if($field->save()){
system_message(elgg_echo("profile_manager:actions:new:success"));
} else {
register_error(elgg_echo("profile_manager:actions:new:error:unknown"));
}
} else {
register_error(elgg_echo("profile_manager:actions:new:error:metadata_options"));
}
}
}
forward(REFERER); | {
"content_hash": "37dd1d0358ea1b9bd42ea62ba4ea62d2",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 166,
"avg_line_length": 34.76086956521739,
"alnum_prop": 0.619345424223473,
"repo_name": "mizerani/shareit",
"id": "c0647fff5babbe9d81eae0aae2c19e8e24e9ff07",
"size": "5009",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "elgg/mod/profile_manager/actions/new.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "5668"
},
{
"name": "CSS",
"bytes": "274319"
},
{
"name": "JavaScript",
"bytes": "2056815"
},
{
"name": "PHP",
"bytes": "5295797"
},
{
"name": "Perl",
"bytes": "6733"
},
{
"name": "Shell",
"bytes": "1527"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
<feature name="${project.artifactId}" version="${project.version}"
description="${project.description}">
<feature>onos-api</feature>
<bundle>mvn:${project.groupId}/onos-app-olt-api/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-app-olt/${project.version}</bundle>
</feature>
</features>
| {
"content_hash": "0372fa95eef04f12391e65b44003f184",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 112,
"avg_line_length": 48.041666666666664,
"alnum_prop": 0.6964440589765828,
"repo_name": "Phaneendra-Huawei/demo",
"id": "9556eddd4af54a7767e5fa92431175986e142cf4",
"size": "1153",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apps/olt/app/features.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "72448"
},
{
"name": "CSS",
"bytes": "179104"
},
{
"name": "Groff",
"bytes": "1090"
},
{
"name": "HTML",
"bytes": "504906"
},
{
"name": "Java",
"bytes": "25023287"
},
{
"name": "JavaScript",
"bytes": "3056920"
},
{
"name": "Protocol Buffer",
"bytes": "5812"
},
{
"name": "Python",
"bytes": "126150"
},
{
"name": "Shell",
"bytes": "3492"
}
],
"symlink_target": ""
} |
.class Landroid/media/AudioService$ForceControlStreamClient;
.super Ljava/lang/Object;
.source "AudioService.java"
# interfaces
.implements Landroid/os/IBinder$DeathRecipient;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/media/AudioService;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x2
name = "ForceControlStreamClient"
.end annotation
# instance fields
.field private mCb:Landroid/os/IBinder;
.field final synthetic this$0:Landroid/media/AudioService;
# direct methods
.method constructor <init>(Landroid/media/AudioService;Landroid/os/IBinder;)V
.locals 4
.param p2, "cb" # Landroid/os/IBinder;
.prologue
.line 1509
iput-object p1, p0, Landroid/media/AudioService$ForceControlStreamClient;->this$0:Landroid/media/AudioService;
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 1510
if-eqz p2, :cond_0
.line 1512
const/4 v1, 0x0
:try_start_0
invoke-interface {p2, p0, v1}, Landroid/os/IBinder;->linkToDeath(Landroid/os/IBinder$DeathRecipient;I)V
:try_end_0
.catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0
.line 1519
:cond_0
:goto_0
iput-object p2, p0, Landroid/media/AudioService$ForceControlStreamClient;->mCb:Landroid/os/IBinder;
.line 1520
return-void
.line 1513
:catch_0
move-exception v0
.line 1515
.local v0, "e":Landroid/os/RemoteException;
const-string v1, "AudioService"
new-instance v2, Ljava/lang/StringBuilder;
invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V
const-string v3, "ForceControlStreamClient() could not link to "
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v2
const-string v3, " binder death"
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v2
invoke-static {v1, v2}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I
.line 1516
const/4 p2, 0x0
goto :goto_0
.end method
# virtual methods
.method public binderDied()V
.locals 3
.prologue
.line 1523
iget-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->this$0:Landroid/media/AudioService;
# getter for: Landroid/media/AudioService;->mForceControlStreamLock:Ljava/lang/Object;
invoke-static {v0}, Landroid/media/AudioService;->access$900(Landroid/media/AudioService;)Ljava/lang/Object;
move-result-object v1
monitor-enter v1
.line 1524
:try_start_0
const-string v0, "AudioService"
const-string v2, "SCO client died"
invoke-static {v0, v2}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I
.line 1525
iget-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->this$0:Landroid/media/AudioService;
# getter for: Landroid/media/AudioService;->mForceControlStreamClient:Landroid/media/AudioService$ForceControlStreamClient;
invoke-static {v0}, Landroid/media/AudioService;->access$1000(Landroid/media/AudioService;)Landroid/media/AudioService$ForceControlStreamClient;
move-result-object v0
if-eq v0, p0, :cond_0
.line 1526
const-string v0, "AudioService"
const-string v2, "unregistered control stream client died"
invoke-static {v0, v2}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I
.line 1531
:goto_0
monitor-exit v1
.line 1532
return-void
.line 1528
:cond_0
iget-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->this$0:Landroid/media/AudioService;
const/4 v2, 0x0
# setter for: Landroid/media/AudioService;->mForceControlStreamClient:Landroid/media/AudioService$ForceControlStreamClient;
invoke-static {v0, v2}, Landroid/media/AudioService;->access$1002(Landroid/media/AudioService;Landroid/media/AudioService$ForceControlStreamClient;)Landroid/media/AudioService$ForceControlStreamClient;
.line 1529
iget-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->this$0:Landroid/media/AudioService;
const/4 v2, -0x1
# setter for: Landroid/media/AudioService;->mVolumeControlStream:I
invoke-static {v0, v2}, Landroid/media/AudioService;->access$1102(Landroid/media/AudioService;I)I
goto :goto_0
.line 1531
:catchall_0
move-exception v0
monitor-exit v1
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
throw v0
.end method
.method public release()V
.locals 2
.prologue
.line 1535
iget-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->mCb:Landroid/os/IBinder;
if-eqz v0, :cond_0
.line 1536
iget-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->mCb:Landroid/os/IBinder;
const/4 v1, 0x0
invoke-interface {v0, p0, v1}, Landroid/os/IBinder;->unlinkToDeath(Landroid/os/IBinder$DeathRecipient;I)Z
.line 1537
const/4 v0, 0x0
iput-object v0, p0, Landroid/media/AudioService$ForceControlStreamClient;->mCb:Landroid/os/IBinder;
.line 1539
:cond_0
return-void
.end method
| {
"content_hash": "718eb3164c789d243132c206ff1895f4",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 205,
"avg_line_length": 27.742424242424242,
"alnum_prop": 0.7218277808119424,
"repo_name": "shumxin/FlymeOS_A5DUG",
"id": "0addc6c58567a9773ed190ddc8b86f50e6981eb2",
"size": "5493",
"binary": false,
"copies": "1",
"ref": "refs/heads/lollipop-5.0",
"path": "framework.jar.out/smali_classes2/android/media/AudioService$ForceControlStreamClient.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "13678"
},
{
"name": "Shell",
"bytes": "103420"
},
{
"name": "Smali",
"bytes": "189389087"
}
],
"symlink_target": ""
} |
package org.cloudfoundry.operations.applications;
import org.immutables.value.Value;
/**
* The request options for the set environment variable of an application operation
*/
@Value.Immutable
abstract class _UnsetEnvironmentVariableApplicationRequest {
/**
* The application name
*/
abstract String getName();
/**
* The variable name
*/
abstract String getVariableName();
}
| {
"content_hash": "e9ba291fe6e138c13828e32b7a6b1f38",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 83,
"avg_line_length": 18.217391304347824,
"alnum_prop": 0.7016706443914081,
"repo_name": "alexander071/cf-java-client",
"id": "1e89babc4fdbdce181f3963da8045bb634bf4197",
"size": "1039",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cloudfoundry-operations/src/main/java/org/cloudfoundry/operations/applications/_UnsetEnvironmentVariableApplicationRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5043"
},
{
"name": "Java",
"bytes": "4410753"
},
{
"name": "Shell",
"bytes": "8834"
}
],
"symlink_target": ""
} |
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import timeutils
from oslo_utils import units
import taskflow.engines
from taskflow.patterns import linear_flow
from taskflow.types import failure as ft
from jacket.storage import exception
from jacket.storage import flow_utils
from jacket.storage.i18n import _, _LE, _LW
from jacket.objects import storage
from jacket.storage import policy
from jacket.storage import quota
from jacket.storage import utils
from jacket.storage.volume.flows import common
from jacket.storage.volume import utils as vol_utils
from jacket.storage.volume import volume_types
LOG = logging.getLogger(__name__)
ACTION = 'volume:create'
CONF = cfg.CONF
GB = units.Gi
QUOTAS = quota.QUOTAS
# Only in these 'sources' status can we attempt to create a volume from a
# source volume or a source snapshot, other status states we can not create
# from, 'error' being the common example.
SNAPSHOT_PROCEED_STATUS = ('available',)
SRC_VOL_PROCEED_STATUS = ('available', 'in-use',)
REPLICA_PROCEED_STATUS = ('active', 'active-stopped',)
CG_PROCEED_STATUS = ('available', 'creating',)
CGSNAPSHOT_PROCEED_STATUS = ('available',)
class ExtractVolumeRequestTask(flow_utils.CinderTask):
"""Processes an api request values into a validated set of values.
This tasks responsibility is to take in a set of inputs that will form
a potential volume request and validates those values against a set of
conditions and/or translates those values into a valid set and then returns
the validated/translated values for use by other tasks.
Reversion strategy: N/A
"""
# This task will produce the following outputs (said outputs can be
# saved to durable storage in the future so that the flow can be
# reconstructed elsewhere and continued).
default_provides = set(['availability_zone', 'size', 'snapshot_id',
'source_volid', 'volume_type', 'volume_type_id',
'encryption_key_id', 'source_replicaid',
'consistencygroup_id', 'cgsnapshot_id',
'qos_specs'])
def __init__(self, image_service, availability_zones, **kwargs):
super(ExtractVolumeRequestTask, self).__init__(addons=[ACTION],
**kwargs)
self.image_service = image_service
self.availability_zones = availability_zones
@staticmethod
def _extract_resource(resource, allowed_vals, exc, resource_name,
props=('status',)):
"""Extracts the resource id from the provided resource.
This method validates the input resource dict and checks that the
properties which names are passed in `props` argument match
corresponding lists in `allowed` argument. In case of mismatch
exception of type exc is raised.
:param resource: Resource dict.
:param allowed_vals: Tuple of allowed values lists.
:param exc: Exception type to raise.
:param resource_name: Name of resource - used to construct log message.
:param props: Tuple of resource properties names to validate.
:return: Id of a resource.
"""
resource_id = None
if resource:
for prop, allowed_states in zip(props, allowed_vals):
if resource[prop] not in allowed_states:
msg = _("Originating %(res)s %(prop)s must be one of "
"'%(vals)s' values")
msg = msg % {'res': resource_name,
'prop': prop,
'vals': ', '.join(allowed_states)}
# TODO(harlowja): what happens if the status changes after
# this initial resource status check occurs??? Seems like
# someone could delete the resource after this check passes
# but before the volume is officially created?
raise exc(reason=msg)
resource_id = resource['id']
return resource_id
def _extract_consistencygroup(self, consistencygroup):
return self._extract_resource(consistencygroup, (CG_PROCEED_STATUS,),
exception.InvalidConsistencyGroup,
'consistencygroup')
def _extract_cgsnapshot(self, cgsnapshot):
return self._extract_resource(cgsnapshot, (CGSNAPSHOT_PROCEED_STATUS,),
exception.InvalidCgSnapshot,
'CGSNAPSHOT')
def _extract_snapshot(self, snapshot):
return self._extract_resource(snapshot, (SNAPSHOT_PROCEED_STATUS,),
exception.InvalidSnapshot, 'snapshot')
def _extract_source_volume(self, source_volume):
return self._extract_resource(source_volume, (SRC_VOL_PROCEED_STATUS,),
exception.InvalidVolume, 'source volume')
def _extract_source_replica(self, source_replica):
return self._extract_resource(source_replica, (SRC_VOL_PROCEED_STATUS,
REPLICA_PROCEED_STATUS),
exception.InvalidVolume,
'replica', ('status',
'replication_status'))
@staticmethod
def _extract_size(size, source_volume, snapshot):
"""Extracts and validates the volume size.
This function will validate or when not provided fill in the provided
size variable from the source_volume or snapshot and then does
validation on the size that is found and returns said validated size.
"""
def validate_snap_size(size):
if snapshot and size < snapshot.volume_size:
msg = _("Volume size '%(size)s'GB cannot be smaller than"
" the snapshot size %(snap_size)sGB. "
"They must be >= original snapshot size.")
msg = msg % {'size': size,
'snap_size': snapshot.volume_size}
raise exception.InvalidInput(reason=msg)
def validate_source_size(size):
if source_volume and size < source_volume['size']:
msg = _("Volume size '%(size)s'GB cannot be smaller than "
"original volume size %(source_size)sGB. "
"They must be >= original volume size.")
msg = msg % {'size': size,
'source_size': source_volume['size']}
raise exception.InvalidInput(reason=msg)
def validate_int(size):
if not isinstance(size, int) or size <= 0:
msg = _("Volume size '%(size)s' must be an integer and"
" greater than 0") % {'size': size}
raise exception.InvalidInput(reason=msg)
# Figure out which validation functions we should be applying
# on the size value that we extract.
validator_functors = [validate_int]
if source_volume:
validator_functors.append(validate_source_size)
elif snapshot:
validator_functors.append(validate_snap_size)
# If the size is not provided then try to provide it.
if not size and source_volume:
size = source_volume['size']
elif not size and snapshot:
size = snapshot.volume_size
size = utils.as_int(size)
LOG.debug("Validating volume '%(size)s' using %(functors)s" %
{'size': size,
'functors': ", ".join([common.make_pretty_name(func)
for func in validator_functors])})
for func in validator_functors:
func(size)
return size
def _check_image_metadata(self, context, image_id, size):
"""Checks image existence and validates that the image metadata."""
# Check image existence
if image_id is None:
return
# NOTE(harlowja): this should raise an error if the image does not
# exist, this is expected as it signals that the image_id is missing.
image_meta = self.image_service.show(context, image_id)
# check whether image is active
if image_meta['status'] != 'active':
msg = _('Image %(image_id)s is not active.')\
% {'image_id': image_id}
raise exception.InvalidInput(reason=msg)
# Check image size is not larger than volume size.
image_size = utils.as_int(image_meta['size'], quiet=False)
image_size_in_gb = (image_size + GB - 1) // GB
if image_size_in_gb > size:
msg = _('Size of specified image %(image_size)sGB'
' is larger than volume size %(volume_size)sGB.')
msg = msg % {'image_size': image_size_in_gb, 'volume_size': size}
raise exception.InvalidInput(reason=msg)
# Check image min_disk requirement is met for the particular volume
min_disk = image_meta.get('min_disk', 0)
if size < min_disk:
msg = _('Volume size %(volume_size)sGB cannot be smaller'
' than the image minDisk size %(min_disk)sGB.')
msg = msg % {'volume_size': size, 'min_disk': min_disk}
raise exception.InvalidInput(reason=msg)
def _get_image_volume_type(self, context, image_id):
"""Get cinder_img_volume_type property from the image metadata."""
# Check image existence
if image_id is None:
return None
image_meta = self.image_service.show(context, image_id)
# check whether image is active
if image_meta['status'] != 'active':
msg = (_('Image %(image_id)s is not active.') %
{'image_id': image_id})
raise exception.InvalidInput(reason=msg)
# Retrieve 'cinder_img_volume_type' property from glance image
# metadata.
image_volume_type = "cinder_img_volume_type"
properties = image_meta.get('properties')
if properties:
try:
img_vol_type = properties.get(image_volume_type)
if img_vol_type is None:
return None
volume_type = volume_types.get_volume_type_by_name(
context,
img_vol_type)
except exception.VolumeTypeNotFoundByName:
LOG.warning(_LW("Failed to retrieve volume_type from image "
"metadata. '%(img_vol_type)s' doesn't match "
"any volume types."),
{'img_vol_type': img_vol_type})
return None
LOG.debug("Retrieved volume_type from glance image metadata. "
"image_id: %(image_id)s, "
"image property: %(image_volume_type)s, "
"volume_type: %(volume_type)s." %
{'image_id': image_id,
'image_volume_type': image_volume_type,
'volume_type': volume_type})
return volume_type
@staticmethod
def _check_metadata_properties(metadata=None):
"""Checks that the volume metadata properties are valid."""
if not metadata:
metadata = {}
for (k, v) in metadata.items():
if len(k) == 0:
msg = _("Metadata property key blank")
LOG.warning(msg)
raise exception.InvalidVolumeMetadata(reason=msg)
if len(k) > 255:
msg = _("Metadata property key %s greater than 255 "
"characters") % k
LOG.warning(msg)
raise exception.InvalidVolumeMetadataSize(reason=msg)
if len(v) > 255:
msg = _("Metadata property key %s value greater than"
" 255 characters") % k
LOG.warning(msg)
raise exception.InvalidVolumeMetadataSize(reason=msg)
def _extract_availability_zone(self, availability_zone, snapshot,
source_volume):
"""Extracts and returns a validated availability zone.
This function will extract the availability zone (if not provided) from
the snapshot or source_volume and then performs a set of validation
checks on the provided or extracted availability zone and then returns
the validated availability zone.
"""
# Try to extract the availability zone from the corresponding snapshot
# or source volume if either is valid so that we can be in the same
# availability zone as the source.
if availability_zone is None:
if snapshot:
try:
availability_zone = snapshot['volume']['availability_zone']
except (TypeError, KeyError):
pass
if source_volume and availability_zone is None:
try:
availability_zone = source_volume['availability_zone']
except (TypeError, KeyError):
pass
if availability_zone is None:
if CONF.default_availability_zone:
availability_zone = CONF.default_availability_zone
else:
# For backwards compatibility use the storage_availability_zone
availability_zone = CONF.storage_availability_zone
if availability_zone not in self.availability_zones:
if CONF.allow_availability_zone_fallback:
original_az = availability_zone
availability_zone = (
CONF.default_availability_zone or
CONF.storage_availability_zone)
LOG.warning(_LW("Availability zone '%(s_az)s' "
"not found, falling back to "
"'%(s_fallback_az)s'."),
{'s_az': original_az,
's_fallback_az': availability_zone})
else:
msg = _("Availability zone '%(s_az)s' is invalid.")
msg = msg % {'s_az': availability_zone}
raise exception.InvalidInput(reason=msg)
# If the configuration only allows cloning to the same availability
# zone then we need to enforce that.
if CONF.cloned_volume_same_az:
snap_az = None
try:
snap_az = snapshot['volume']['availability_zone']
except (TypeError, KeyError):
pass
if snap_az and snap_az != availability_zone:
msg = _("Volume must be in the same "
"availability zone as the snapshot")
raise exception.InvalidInput(reason=msg)
source_vol_az = None
try:
source_vol_az = source_volume['availability_zone']
except (TypeError, KeyError):
pass
if source_vol_az and source_vol_az != availability_zone:
msg = _("Volume must be in the same "
"availability zone as the source volume")
raise exception.InvalidInput(reason=msg)
return availability_zone
def _get_encryption_key_id(self, key_manager, context, volume_type_id,
snapshot, source_volume):
encryption_key_id = None
if volume_types.is_encrypted(context, volume_type_id):
if snapshot is not None: # creating from snapshot
encryption_key_id = snapshot['encryption_key_id']
elif source_volume is not None: # cloning volume
encryption_key_id = source_volume['encryption_key_id']
# NOTE(joel-coffman): References to the encryption key should *not*
# be copied because the key is deleted when the volume is deleted.
# Clone the existing key and associate a separate -- but
# identical -- key with each volume.
if encryption_key_id is not None:
encryption_key_id = key_manager.copy_key(context,
encryption_key_id)
else:
encryption_key_id = key_manager.create_key(context)
return encryption_key_id
def _get_volume_type_id(self, volume_type, source_volume, snapshot):
if not volume_type and source_volume:
return source_volume['volume_type_id']
elif snapshot is not None:
if volume_type:
current_volume_type_id = volume_type.get('id')
if current_volume_type_id != snapshot['volume_type_id']:
msg = _LW("Volume type will be changed to "
"be the same as the source volume.")
LOG.warning(msg)
return snapshot['volume_type_id']
else:
return volume_type.get('id')
def execute(self, context, size, snapshot, image_id, source_volume,
availability_zone, volume_type, metadata, key_manager,
source_replica, consistencygroup, cgsnapshot):
utils.check_exclusive_options(snapshot=snapshot,
imageRef=image_id,
source_volume=source_volume)
policy.enforce_action(context, ACTION)
# TODO(harlowja): what guarantee is there that the snapshot or source
# volume will remain available after we do this initial verification??
snapshot_id = self._extract_snapshot(snapshot)
source_volid = self._extract_source_volume(source_volume)
source_replicaid = self._extract_source_replica(source_replica)
size = self._extract_size(size, source_volume, snapshot)
consistencygroup_id = self._extract_consistencygroup(consistencygroup)
cgsnapshot_id = self._extract_cgsnapshot(cgsnapshot)
self._check_image_metadata(context, image_id, size)
availability_zone = self._extract_availability_zone(availability_zone,
snapshot,
source_volume)
# TODO(joel-coffman): This special handling of snapshots to ensure that
# their volume type matches the source volume is too convoluted. We
# should copy encryption metadata from the encrypted volume type to the
# volume upon creation and propagate that information to each snapshot.
# This strategy avoids any dependency upon the encrypted volume type.
def_vol_type = volume_types.get_default_volume_type()
if not volume_type and not source_volume and not snapshot:
image_volume_type = self._get_image_volume_type(context, image_id)
volume_type = (image_volume_type if image_volume_type else
def_vol_type)
# When creating a clone of a replica (replication test), we can't
# use the volume type of the replica, therefore, we use the default.
# NOTE(ronenkat): this assumes the default type is not replicated.
if source_replicaid:
volume_type = def_vol_type
volume_type_id = self._get_volume_type_id(volume_type,
source_volume, snapshot)
if image_id and volume_types.is_encrypted(context, volume_type_id):
msg = _('Create encrypted volumes with type %(type)s '
'from image %(image)s is not supported.')
msg = msg % {'type': volume_type_id,
'image': image_id, }
raise exception.InvalidInput(reason=msg)
encryption_key_id = self._get_encryption_key_id(key_manager,
context,
volume_type_id,
snapshot,
source_volume)
specs = {}
if volume_type_id:
qos_specs = volume_types.get_volume_type_qos_specs(volume_type_id)
if qos_specs['qos_specs']:
specs = qos_specs['qos_specs'].get('specs', {})
if not specs:
# to make sure we don't pass empty dict
specs = None
self._check_metadata_properties(metadata)
return {
'size': size,
'snapshot_id': snapshot_id,
'source_volid': source_volid,
'availability_zone': availability_zone,
'volume_type': volume_type,
'volume_type_id': volume_type_id,
'encryption_key_id': encryption_key_id,
'qos_specs': specs,
'source_replicaid': source_replicaid,
'consistencygroup_id': consistencygroup_id,
'cgsnapshot_id': cgsnapshot_id,
}
class EntryCreateTask(flow_utils.CinderTask):
"""Creates an entry for the given volume creation in the database.
Reversion strategy: remove the volume_id created from the database.
"""
default_provides = set(['volume_properties', 'volume_id', 'volume'])
def __init__(self, db):
requires = ['availability_zone', 'description', 'metadata',
'name', 'reservations', 'size', 'snapshot_id',
'source_volid', 'volume_type_id', 'encryption_key_id',
'source_replicaid', 'consistencygroup_id',
'cgsnapshot_id', 'multiattach', 'qos_specs']
super(EntryCreateTask, self).__init__(addons=[ACTION],
requires=requires)
self.db = db
def execute(self, context, optional_args, **kwargs):
"""Creates a database entry for the given inputs and returns details.
Accesses the database and creates a new entry for the to be created
volume using the given volume properties which are extracted from the
input kwargs (and associated requirements this task needs). These
requirements should be previously satisfied and validated by a
pre-cursor task.
"""
volume_properties = {
'size': kwargs.pop('size'),
'user_id': context.user_id,
'project_id': context.project_id,
'status': 'creating',
'attach_status': 'detached',
'encryption_key_id': kwargs.pop('encryption_key_id'),
# Rename these to the internal name.
'display_description': kwargs.pop('description'),
'display_name': kwargs.pop('name'),
'replication_status': 'disabled',
'multiattach': kwargs.pop('multiattach'),
}
# Merge in the other required arguments which should provide the rest
# of the volume property fields (if applicable).
volume_properties.update(kwargs)
volume = storage.Volume(context=context, **volume_properties)
volume.create()
return {
'volume_id': volume['id'],
'volume_properties': volume_properties,
# NOTE(harlowja): it appears like further usage of this volume
# result actually depend on it being a sqlalchemy object and not
# just a plain dictionary so that's why we are storing this here.
#
# In the future where this task results can be serialized and
# restored automatically for continued running we will need to
# resolve the serialization & recreation of this object since raw
# sqlalchemy storage can't be serialized.
'volume': volume,
}
def revert(self, context, result, optional_args, **kwargs):
if isinstance(result, ft.Failure):
# We never produced a result and therefore can't destroy anything.
return
if optional_args['is_quota_committed']:
# If quota got committed we shouldn't rollback as the volume has
# already been created and the quota has already been absorbed.
return
volume = result['volume']
try:
volume.destroy()
except exception.CinderException:
# We are already reverting, therefore we should silence this
# exception since a second exception being active will be bad.
#
# NOTE(harlowja): Being unable to destroy a volume is pretty
# bad though!!
LOG.exception(_LE("Failed destroying volume entry %s"), volume.id)
class QuotaReserveTask(flow_utils.CinderTask):
"""Reserves a single volume with the given size & the given volume type.
Reversion strategy: rollback the quota reservation.
Warning Warning: if the process that is running this reserve and commit
process fails (or is killed before the quota is rolled back or committed
it does appear like the quota will never be rolled back). This makes
software upgrades hard (inflight operations will need to be stopped or
allowed to complete before the upgrade can occur). *In the future* when
taskflow has persistence built-in this should be easier to correct via
an automated or manual process.
"""
default_provides = set(['reservations'])
def __init__(self):
super(QuotaReserveTask, self).__init__(addons=[ACTION])
def execute(self, context, size, volume_type_id, optional_args):
try:
values = {'per_volume_gigabytes': size}
QUOTAS.limit_check(context, project_id=context.project_id,
**values)
except exception.OverQuota as e:
quotas = e.kwargs['quotas']
raise exception.VolumeSizeExceedsLimit(
size=size, limit=quotas['per_volume_gigabytes'])
try:
reserve_opts = {'volumes': 1, 'gigabytes': size}
QUOTAS.add_volume_type_opts(context, reserve_opts, volume_type_id)
reservations = QUOTAS.reserve(context, **reserve_opts)
return {
'reservations': reservations,
}
except exception.OverQuota as e:
overs = e.kwargs['overs']
quotas = e.kwargs['quotas']
usages = e.kwargs['usages']
def _consumed(name):
usage = usages[name]
return usage['reserved'] + usage['in_use'] + usage.get(
'allocated', 0)
def _get_over(name):
for over in overs:
if name in over:
return over
return None
over_name = _get_over('gigabytes')
exceeded_vol_limit_name = _get_over('volumes')
if over_name:
# TODO(mc_nair): improve error message for child -1 limit
msg = _LW("Quota exceeded for %(s_pid)s, tried to create "
"%(s_size)sG volume (%(d_consumed)dG "
"of %(d_quota)dG already consumed)")
LOG.warning(msg, {'s_pid': context.project_id,
's_size': size,
'd_consumed': _consumed(over_name),
'd_quota': quotas[over_name]})
raise exception.VolumeSizeExceedsAvailableQuota(
name=over_name,
requested=size,
consumed=_consumed(over_name),
quota=quotas[over_name])
elif exceeded_vol_limit_name:
msg = _LW("Quota %(s_name)s exceeded for %(s_pid)s, tried "
"to create volume (%(d_consumed)d volume(s) "
"already consumed).")
LOG.warning(msg,
{'s_name': exceeded_vol_limit_name,
's_pid': context.project_id,
'd_consumed':
_consumed(exceeded_vol_limit_name)})
# TODO(mc_nair): improve error message for child -1 limit
raise exception.VolumeLimitExceeded(
allowed=quotas[exceeded_vol_limit_name],
name=exceeded_vol_limit_name)
else:
# If nothing was reraised, ensure we reraise the initial error
raise
def revert(self, context, result, optional_args, **kwargs):
# We never produced a result and therefore can't destroy anything.
if isinstance(result, ft.Failure):
return
if optional_args['is_quota_committed']:
# The reservations have already been committed and can not be
# rolled back at this point.
return
# We actually produced an output that we can revert so lets attempt
# to use said output to rollback the reservation.
reservations = result['reservations']
try:
QUOTAS.rollback(context, reservations)
except exception.CinderException:
# We are already reverting, therefore we should silence this
# exception since a second exception being active will be bad.
LOG.exception(_LE("Failed rolling back quota for"
" %s reservations"), reservations)
class QuotaCommitTask(flow_utils.CinderTask):
"""Commits the reservation.
Reversion strategy: N/A (the rollback will be handled by the task that did
the initial reservation (see: QuotaReserveTask).
Warning Warning: if the process that is running this reserve and commit
process fails (or is killed before the quota is rolled back or committed
it does appear like the quota will never be rolled back). This makes
software upgrades hard (inflight operations will need to be stopped or
allowed to complete before the upgrade can occur). *In the future* when
taskflow has persistence built-in this should be easier to correct via
an automated or manual process.
"""
def __init__(self):
super(QuotaCommitTask, self).__init__(addons=[ACTION])
def execute(self, context, reservations, volume_properties,
optional_args):
QUOTAS.commit(context, reservations)
# updating is_quota_committed attribute of optional_args dictionary
optional_args['is_quota_committed'] = True
return {'volume_properties': volume_properties}
def revert(self, context, result, **kwargs):
# We never produced a result and therefore can't destroy anything.
if isinstance(result, ft.Failure):
return
volume = result['volume_properties']
try:
reserve_opts = {'volumes': -1, 'gigabytes': -volume['size']}
QUOTAS.add_volume_type_opts(context,
reserve_opts,
volume['volume_type_id'])
reservations = QUOTAS.reserve(context,
project_id=context.project_id,
**reserve_opts)
if reservations:
QUOTAS.commit(context, reservations,
project_id=context.project_id)
except Exception:
LOG.exception(_LE("Failed to update quota for deleting "
"volume: %s"), volume['id'])
class VolumeCastTask(flow_utils.CinderTask):
"""Performs a volume create cast to the scheduler or to the volume manager.
This will signal a transition of the api workflow to another child and/or
related workflow on another component.
Reversion strategy: rollback source volume status and error out newly
created volume.
"""
def __init__(self, scheduler_rpcapi, jacket_rpcapi, db):
requires = ['image_id', 'scheduler_hints', 'snapshot_id',
'source_volid', 'volume_id', 'volume', 'volume_type',
'volume_properties', 'source_replicaid',
'consistencygroup_id', 'cgsnapshot_id', ]
super(VolumeCastTask, self).__init__(addons=[ACTION],
requires=requires)
self.jacket_rpcapi = jacket_rpcapi
self.scheduler_rpcapi = scheduler_rpcapi
self.db = db
def _cast_create_volume(self, context, request_spec, filter_properties):
source_volid = request_spec['source_volid']
source_replicaid = request_spec['source_replicaid']
volume_id = request_spec['volume_id']
volume = request_spec['volume']
snapshot_id = request_spec['snapshot_id']
image_id = request_spec['image_id']
cgroup_id = request_spec['consistencygroup_id']
host = None
cgsnapshot_id = request_spec['cgsnapshot_id']
if cgroup_id:
# If cgroup_id existed, we should cast volume to the scheduler
# to choose a proper pool whose backend is same as CG's backend.
cgroup = storage.ConsistencyGroup.get_by_id(context, cgroup_id)
# FIXME(wanghao): CG_backend got added before request_spec was
# converted to versioned storage. We should make sure that this
# will be handled by object version translations once we add
# RequestSpec object.
request_spec['CG_backend'] = vol_utils.extract_host(cgroup.host)
elif snapshot_id and CONF.snapshot_same_host:
# NOTE(Rongze Zhu): A simple solution for bug 1008866.
#
# If snapshot_id is set and CONF.snapshot_same_host is True, make
# the call create volume directly to the volume host where the
# snapshot resides instead of passing it through the scheduler, so
# snapshot can be copied to the new volume.
snapshot = storage.Snapshot.get_by_id(context, snapshot_id)
source_volume_ref = storage.Volume.get_by_id(context,
snapshot.volume_id)
host = source_volume_ref.host
elif source_volid:
source_volume_ref = storage.Volume.get_by_id(context,
source_volid)
host = source_volume_ref.host
elif source_replicaid:
source_volume_ref = storage.Volume.get_by_id(context,
source_replicaid)
host = source_volume_ref.host
# if not host:
# # Cast to the scheduler and let it handle whatever is needed
# # to select the target host for this volume.
# self.scheduler_rpcapi.create_volume(
# context,
# CONF.volume_topic,
# volume_id,
# snapshot_id=snapshot_id,
# image_id=image_id,
# request_spec=request_spec,
# filter_properties=filter_properties,
# volume=volume)
# else:
# # Bypass the scheduler and send the request directly to the volume
# # manager.
# volume.host = host
# volume.scheduled_at = timeutils.utcnow()
# volume.save()
# if not cgsnapshot_id:
# self.compute_rpcapi.create_volume(
# context,
# volume,
# volume.host,
# request_spec,
# filter_properties,
# allow_reschedule=False)
#by luorui : no scheduler,need host for rpcapi and others
host = None
volume.host = host
volume.scheduled_at = timeutils.utcnow()
volume.save()
if not cgsnapshot_id:
self.jacket_rpcapi.create_volume(
context,
volume,
volume.host,
request_spec,
filter_properties,
allow_reschedule=False)
def execute(self, context, **kwargs):
scheduler_hints = kwargs.pop('scheduler_hints', None)
request_spec = kwargs.copy()
filter_properties = {}
if scheduler_hints:
filter_properties['scheduler_hints'] = scheduler_hints
self._cast_create_volume(context, request_spec, filter_properties)
def revert(self, context, result, flow_failures, **kwargs):
if isinstance(result, ft.Failure):
return
# Restore the source volume status and set the volume to error status.
volume_id = kwargs['volume_id']
common.restore_source_status(context, self.db, kwargs)
common.error_out_volume(context, self.db, volume_id)
LOG.error(_LE("Volume %s: create failed"), volume_id)
exc_info = False
if all(flow_failures[-1].exc_info):
exc_info = flow_failures[-1].exc_info
LOG.error(_LE('Unexpected build error:'), exc_info=exc_info)
def get_flow(db_api, image_service_api, availability_zones, create_what,
scheduler_rpcapi=None, jacket_rpcapi=None):
"""Constructs and returns the api entrypoint flow.
This flow will do the following:
1. Inject keys & values for dependent tasks.
2. Extracts and validates the input keys & values.
3. Reserves the quota (reverts quota on any failures).
4. Creates the database entry.
5. Commits the quota.
6. Casts to volume manager or scheduler for further processing.
"""
flow_name = ACTION.replace(":", "_") + "_api"
api_flow = linear_flow.Flow(flow_name)
api_flow.add(ExtractVolumeRequestTask(
image_service_api,
availability_zones,
rebind={'size': 'raw_size',
'availability_zone': 'raw_availability_zone',
'volume_type': 'raw_volume_type'}))
api_flow.add(QuotaReserveTask(),
EntryCreateTask(db_api),
QuotaCommitTask())
if scheduler_rpcapi and jacket_rpcapi:
# This will cast it out to either the scheduler or volume manager via
# the rpc apis provided.
api_flow.add(VolumeCastTask(scheduler_rpcapi, jacket_rpcapi, db_api))
# Now load (but do not run) the flow using the provided initial data.
return taskflow.engines.load(api_flow, store=create_what)
| {
"content_hash": "ba5677a6eb00c96381fb5dc9c088c44f",
"timestamp": "",
"source": "github",
"line_count": 864,
"max_line_length": 80,
"avg_line_length": 44.8125,
"alnum_prop": 0.5706131515057596,
"repo_name": "HybridF5/jacket",
"id": "0e08b89f32d02fb98972f9c38fb44553a3eb56f6",
"size": "39292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jacket/storage/volume/flows/api/create_volume.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "26995056"
},
{
"name": "Shell",
"bytes": "28464"
},
{
"name": "Smarty",
"bytes": "291947"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.