text
stringlengths 2
1.04M
| meta
dict |
|---|---|
int initInput();
void quitInput();
void addEventWatch(SDL_EventFilter filter, void* userdata);
void deleteEventWatch(SDL_EventFilter filter, void* userdata);
void pumpEvents(void);
#endif // INPUT_H
|
{
"content_hash": "2a8f3b3b1ecd7acfa13fc83552f1d9a6",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 62,
"avg_line_length": 18.454545454545453,
"alnum_prop": 0.7635467980295566,
"repo_name": "GGist/RubyGL",
"id": "80f7d675797a14f0ba552ccf529b99e4a5253b36",
"size": "254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/rubygl/native/include/Input.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6375"
},
{
"name": "Ruby",
"bytes": "239532"
},
{
"name": "Shell",
"bytes": "766"
}
],
"symlink_target": ""
}
|
<?php
/**
* @link https://github.com/old-town/old-town-workflow
* @author Malofeykin Andrey <and-rey2@yandex.ru>
*/
namespace OldTown\Workflow\Loader;
use OldTown\Workflow\Exception\FactoryException;
use OldTown\Workflow\Exception\InvalidParsingWorkflowException;
use OldTown\Workflow\Loader\XMLWorkflowFactory\WorkflowConfig;
/**
* Class ArrayWorkflowFactory
*
* @package OldTown\Workflow\Loader
*/
class ArrayWorkflowFactory extends XmlWorkflowFactory
{
/**
*
* @var string
*/
const WORKFLOWS_PROPERTY = 'workflows';
/**
*
* @return void
* @throws FactoryException
* @throws InvalidParsingWorkflowException
* @throws \OldTown\Workflow\Exception\RemoteException
*/
public function initDone()
{
$this->reload = true === $this->getProperties()->getProperty(static::RELOAD_PROPERTY, false);
$workflows = $this->getProperties()->getProperty(static::WORKFLOWS_PROPERTY, false);
$basedir = null;
foreach ($workflows as $name => $workflowItem) {
$type = array_key_exists('type', $workflowItem) ? $workflowItem['type'] : WorkflowConfig::FILE_TYPE;
$location = array_key_exists('location', $workflowItem) ? $workflowItem['location'] : '';
$config = $this->buildWorkflowConfig($basedir, $type, $location);
$this->workflows[$name] = $config;
}
}
}
|
{
"content_hash": "55891c99f1129c6bc3207d8f60a6e1e8",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 113,
"avg_line_length": 30.76086956521739,
"alnum_prop": 0.6558303886925795,
"repo_name": "old-town/old-town-workflow",
"id": "04bec9d4ddf7829543dd8f4ac065a7a4bee4dfe1",
"size": "1415",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Loader/ArrayWorkflowFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Cucumber",
"bytes": "178367"
},
{
"name": "PHP",
"bytes": "575050"
}
],
"symlink_target": ""
}
|
// Copyright 2015 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package stringutil
import (
"bytes"
"fmt"
"strings"
"unicode/utf8"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/util/hack"
)
// ErrSyntax indicates that a value does not have the right syntax for the target type.
var ErrSyntax = errors.New("invalid syntax")
// UnquoteChar decodes the first character or byte in the escaped string
// or character literal represented by the string s.
// It returns four values:
//
//1) value, the decoded Unicode code point or byte value;
//2) multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
//3) tail, the remainder of the string after the character; and
//4) an error that will be nil if the character is syntactically valid.
//
// The second argument, quote, specifies the type of literal being parsed
// and therefore which escaped quote character is permitted.
// If set to a single quote, it permits the sequence \' and disallows unescaped '.
// If set to a double quote, it permits \" and disallows unescaped ".
// If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.
// Different with strconv.UnquoteChar, it permits unnecessary backslash.
func UnquoteChar(s string, quote byte) (value []byte, tail string, err error) {
// easy cases
switch c := s[0]; {
case c == quote:
err = errors.Trace(ErrSyntax)
return
case c >= utf8.RuneSelf:
r, size := utf8.DecodeRuneInString(s)
if r == utf8.RuneError {
value = append(value, c)
return value, s[1:], nil
}
value = append(value, string(r)...)
return value, s[size:], nil
case c != '\\':
value = append(value, c)
return value, s[1:], nil
}
// hard case: c is backslash
if len(s) <= 1 {
err = errors.Trace(ErrSyntax)
return
}
c := s[1]
s = s[2:]
switch c {
case 'b':
value = append(value, '\b')
case 'n':
value = append(value, '\n')
case 'r':
value = append(value, '\r')
case 't':
value = append(value, '\t')
case 'Z':
value = append(value, '\032')
case '0':
value = append(value, '\000')
case '_', '%':
value = append(value, '\\')
value = append(value, c)
case '\\':
value = append(value, '\\')
case '\'', '"':
value = append(value, c)
default:
value = append(value, c)
}
tail = s
return
}
// Unquote interprets s as a single-quoted, double-quoted,
// or backquoted Go string literal, returning the string value
// that s quotes. For example: test=`"\"\n"` (hex: 22 5c 22 5c 6e 22)
// should be converted to `"\n` (hex: 22 0a).
func Unquote(s string) (t string, err error) {
n := len(s)
if n < 2 {
return "", errors.Trace(ErrSyntax)
}
quote := s[0]
if quote != s[n-1] {
return "", errors.Trace(ErrSyntax)
}
s = s[1 : n-1]
if quote != '"' && quote != '\'' {
return "", errors.Trace(ErrSyntax)
}
// Avoid allocation. No need to convert if there is no '\'
if strings.IndexByte(s, '\\') == -1 && strings.IndexByte(s, quote) == -1 {
return s, nil
}
buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations.
for len(s) > 0 {
mb, ss, err := UnquoteChar(s, quote)
if err != nil {
return "", errors.Trace(err)
}
s = ss
buf = append(buf, mb...)
}
return string(buf), nil
}
const (
patMatch = iota + 1
patOne
patAny
)
// CompilePattern handles escapes and wild cards convert pattern characters and
// pattern types.
func CompilePattern(pattern string, escape byte) (patChars, patTypes []byte) {
var lastAny bool
patChars = make([]byte, len(pattern))
patTypes = make([]byte, len(pattern))
patLen := 0
for i := 0; i < len(pattern); i++ {
var tp byte
var c = pattern[i]
switch c {
case escape:
lastAny = false
tp = patMatch
if i < len(pattern)-1 {
i++
c = pattern[i]
if c == escape || c == '_' || c == '%' {
// Valid escape.
} else {
// Invalid escape, fall back to escape byte.
// mysql will treat escape character as the origin value even
// the escape sequence is invalid in Go or C.
// e.g., \m is invalid in Go, but in MySQL we will get "m" for select '\m'.
// Following case is correct just for escape \, not for others like +.
// TODO: Add more checks for other escapes.
i--
c = escape
}
}
case '_':
if lastAny {
continue
}
tp = patOne
case '%':
if lastAny {
continue
}
lastAny = true
tp = patAny
default:
lastAny = false
tp = patMatch
}
patChars[patLen] = c
patTypes[patLen] = tp
patLen++
}
patChars = patChars[:patLen]
patTypes = patTypes[:patLen]
return
}
// NOTE: Currently tikv's like function is case sensitive, so we keep its behavior here.
func matchByteCI(a, b byte) bool {
return a == b
// We may reuse below code block when like function go back to case insensitive.
/*
if a == b {
return true
}
if a >= 'a' && a <= 'z' && a-caseDiff == b {
return true
}
return a >= 'A' && a <= 'Z' && a+caseDiff == b
*/
}
// CompileLike2Regexp convert a like `lhs` to a regular expression
func CompileLike2Regexp(str string) string {
patChars, patTypes := CompilePattern(str, '\\')
var result []byte
for i := 0; i < len(patChars); i++ {
switch patTypes[i] {
case patMatch:
result = append(result, patChars[i])
case patOne:
// .*. == .*
if !bytes.HasSuffix(result, []byte{'.', '*'}) {
result = append(result, '.')
}
case patAny:
// ..* == .*
if bytes.HasSuffix(result, []byte{'.'}) {
result = append(result, '*')
continue
}
// .*.* == .*
if !bytes.HasSuffix(result, []byte{'.', '*'}) {
result = append(result, '.')
result = append(result, '*')
}
}
}
return string(result)
}
// DoMatch matches the string with patChars and patTypes.
// The algorithm has linear time complexity.
// https://research.swtch.com/glob
func DoMatch(str string, patChars, patTypes []byte) bool {
var sIdx, pIdx, nextSIdx, nextPIdx int
for pIdx < len(patChars) || sIdx < len(str) {
if pIdx < len(patChars) {
switch patTypes[pIdx] {
case patMatch:
if sIdx < len(str) && matchByteCI(str[sIdx], patChars[pIdx]) {
pIdx++
sIdx++
continue
}
case patOne:
if sIdx < len(str) {
pIdx++
sIdx++
continue
}
case patAny:
// Try to match at sIdx.
// If that doesn't work out,
// restart at sIdx+1 next.
nextPIdx = pIdx
nextSIdx = sIdx + 1
pIdx++
continue
}
}
// Mismatch. Maybe restart.
if 0 < nextSIdx && nextSIdx <= len(str) {
pIdx = nextPIdx
sIdx = nextSIdx
continue
}
return false
}
// Matched all of pattern to all of name. Success.
return true
}
// IsExactMatch return true if no wildcard character
func IsExactMatch(patTypes []byte) bool {
for _, pt := range patTypes {
if pt != patMatch {
return false
}
}
return true
}
// Copy deep copies a string.
func Copy(src string) string {
return string(hack.Slice(src))
}
// StringerFunc defines string func implement fmt.Stringer.
type StringerFunc func() string
// String implements fmt.Stringer
func (l StringerFunc) String() string {
return l()
}
// MemoizeStr returns memoized version of stringFunc.
func MemoizeStr(l func() string) fmt.Stringer {
return StringerFunc(func() string {
return l()
})
}
// StringerStr defines a alias to normal string.
// implement fmt.Stringer
type StringerStr string
// String implements fmt.Stringer
func (i StringerStr) String() string {
return string(i)
}
|
{
"content_hash": "d7822bad0fa0dbbf23c5e3727f96a208",
"timestamp": "",
"source": "github",
"line_count": 312,
"max_line_length": 109,
"avg_line_length": 25.362179487179485,
"alnum_prop": 0.6402123088588398,
"repo_name": "Cofyc/tidb",
"id": "065b7394356c0d0303baf17708575d4919275134",
"size": "7913",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "util/stringutil/string_util.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "1226037"
},
{
"name": "Lex",
"bytes": "15554"
},
{
"name": "Makefile",
"bytes": "1902"
},
{
"name": "Shell",
"bytes": "70"
},
{
"name": "Yacc",
"bytes": "66735"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="M:\installed\anstudio\gradle\gradle-2.4" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/library" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
|
{
"content_hash": "5e5671fe8b3d066e20534a90a589611e",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 84,
"avg_line_length": 36.8,
"alnum_prop": 0.5910326086956522,
"repo_name": "rameshvoltella/EZWebView",
"id": "8d26393c5752ce9195d8edb5fb903130f687d4e8",
"size": "736",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/gradle.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "77319"
}
],
"symlink_target": ""
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { st, classes } from './CheckToggle.st.css';
import { dataHooks } from './constants';
import Tooltip from '../Tooltip';
import { TooltipCommonProps } from '../common/PropTypes/TooltipCommon';
import { withFocusable } from 'wix-ui-core/dist/src/hocs/Focusable/FocusableHOC';
import ConfirmSmall from 'wix-ui-icons-common/ConfirmSmall';
import Confirm from 'wix-ui-icons-common/Confirm';
const icon = {
small: <ConfirmSmall />,
medium: <Confirm />,
};
/** CheckToggle */
class CheckToggle extends React.PureComponent {
state = {
checked: !!this.props.checked,
};
/**
* Checks if the component is controlled or uncontrolled.
* The component is controlled only if prop checked is provided.
*
* @returns boolean
* @private
*/
_isControlled = () => {
return this.props.hasOwnProperty('checked');
};
/**
* Toggles checked state and triggers the onChange callback.
* Except when disabled
*/
_handleChange = changeEvent => {
const { checked } = this.state;
const { onChange } = this.props;
this.setState({ checked: !checked }, () => {
if (onChange) onChange(changeEvent);
});
};
/**
* Renders the toggle itself
* @returns React.ReactNode
* @private
*/
_renderInput = () => {
const { checked } = this._isControlled() ? this.props : this.state;
const { size, disabled, onChange } = this.props;
return (
<>
<input
type="checkbox"
className={classes.input}
data-hook={dataHooks.toggle}
checked={checked}
disabled={disabled}
onChange={this._isControlled() ? onChange : this._handleChange}
/>
<span className={classes.toggle}>{icon[size]}</span>
</>
);
};
/**
* Renders a tooltip wrapper
* @returns React.ReactNode
* @private
*/
_renderTooltip = () => {
const { tooltipContent, tooltipProps } = this.props;
return (
<Tooltip
dataHook={dataHooks.tooltip}
content={tooltipContent}
{...tooltipProps}
>
{this._renderInput()}
</Tooltip>
);
};
render() {
const { checked } = this._isControlled() ? this.props : this.state;
const {
dataHook,
size,
skin,
disabled,
tooltipContent,
focusableOnFocus,
focusableOnBlur,
className,
} = this.props;
return (
<label
className={st(
classes.root,
{ checked, size, skin, disabled },
className,
)}
data-hook={dataHook}
onFocus={focusableOnFocus}
onBlur={focusableOnBlur}
>
{tooltipContent ? this._renderTooltip() : this._renderInput()}
</label>
);
}
}
CheckToggle.displayName = 'CheckToggle';
CheckToggle.propTypes = {
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** A css class to be applied to the component's root element */
className: PropTypes.string,
/** If true, the check is toggled */
checked: PropTypes.bool,
/** A callback function, called when the check value is changed */
onChange: PropTypes.func,
/** Applies disabled styles and prevent toggling the check */
disabled: PropTypes.bool,
/** The size of the component */
size: PropTypes.oneOf(['small', 'medium']),
/** The color of the component */
skin: PropTypes.oneOf(['standard', 'success']),
/** When provided, hover will display a tooltip */
tooltipContent: PropTypes.node,
/** Tooltip props, common for all tooltips */
tooltipProps: PropTypes.shape(TooltipCommonProps),
};
CheckToggle.defaultProps = {
disabled: false,
size: 'small',
skin: 'standard',
};
export default withFocusable(CheckToggle);
|
{
"content_hash": "238168530be3f2785de6c191cd0eb497",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 81,
"avg_line_length": 24.703225806451613,
"alnum_prop": 0.6202663880908853,
"repo_name": "wix/wix-style-react",
"id": "2a35745c03fdf094a5ebd4aaf54e6eddda9b8965",
"size": "3829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/wix-style-react/src/CheckToggle/CheckToggle.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "325595"
},
{
"name": "HTML",
"bytes": "20584"
},
{
"name": "JavaScript",
"bytes": "4465095"
},
{
"name": "Shell",
"bytes": "4264"
},
{
"name": "TypeScript",
"bytes": "219813"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>semantics: 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 / released</a></li>
<li class="active"><a href="">8.7.1+1 / semantics - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
semantics
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-20 02:00:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-20 02:00:26 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1+1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/semantics"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Semantics"]
depends: [
"ocaml"
"ocamlbuild" {build}
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: natural semantics" "keyword: denotational semantics" "keyword: axiomatic semantics" "keyword: Hoare logic" "keyword: Dijkstra weakest pre-condition calculus" "keyword: abstract interpretation" "keyword: intervals" "category: Computer Science/Semantics and Compilation/Semantics" "date: 2007-07-5" ]
authors: [ "Yves Bertot <Yves.Bertot@sophia.inria.fr> [http://www-sop.inria.fr/marelle/Yves.Bertot]" ]
bug-reports: "https://github.com/coq-contribs/semantics/issues"
dev-repo: "git+https://github.com/coq-contribs/semantics.git"
synopsis: "A survey of semantics styles, from natural semantics through structural operational, axiomatic, and denotational semantics, to abstract interpretation"
description: """
ftp://ftp-sop.inria.fr/marelle/Yves.Bertot/semantics_survey.tgz
This is a survey of programming language semantics styles
for a miniature example of a programming language, with their encoding
in Coq, the proofs of equivalence of different styles, and the proof
of soundess of tools obtained from axiomatic semantics or abstract
interpretation. The tools can be run inside Coq, thus making them
available for proof by reflection, and the code can also be extracted
and connected to a yacc-based parser, thanks to the use of a functor
parameterized by a module type of strings. A hand-written parser is
also provided in Coq, but there are no proofs associated."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/semantics/archive/v8.6.0.tar.gz"
checksum: "md5=b055739d0156b50e8bbcbfdfd4913254"
}
</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-semantics.8.6.0 coq.8.7.1+1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1).
The following dependencies couldn't be met:
- coq-semantics -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
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-semantics.8.6.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": "7f2b0e36efb7619dfd10fa5a4bd4afe8",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 406,
"avg_line_length": 45.46242774566474,
"alnum_prop": 0.5739351557533375,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "3055060c01a8db753488897690adc81158e53bc1",
"size": "7890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.7.1+1/semantics/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
package gnieh.sohva.test
import org.scalatest.Tag
object NoTravis extends Tag("org.gnieh.sohva.NoTravis")
|
{
"content_hash": "424f1ff40017b55ffafa8d001d94dab3",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 55,
"avg_line_length": 21.6,
"alnum_prop": 0.8055555555555556,
"repo_name": "gnieh/sohva",
"id": "426d1c9b31bd6779ad2791dc6f11efd6278b753f",
"size": "108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/gnieh/sohva/test/tags.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22959"
},
{
"name": "HTML",
"bytes": "5087"
},
{
"name": "JavaScript",
"bytes": "10164"
},
{
"name": "Ruby",
"bytes": "4423"
},
{
"name": "Scala",
"bytes": "216938"
}
],
"symlink_target": ""
}
|
package org.krysalis.barcode4j.impl.upcean;
import org.krysalis.barcode4j.BarGroup;
import org.krysalis.barcode4j.ChecksumMode;
import org.krysalis.barcode4j.ClassicBarcodeLogicHandler;
/**
* This is an abstract base class for UPC and EAN barcodes.
*
* @author Jeremias Maerki
* @version $Id$
*/
public abstract class UPCEANLogicImpl {
/** Left hand A character set */
protected static final byte LEFT_HAND_A = 0;
/** Left hand B character set */
protected static final byte LEFT_HAND_B = 1;
/** Right hand character set */
protected static final byte RIGHT_HAND = 2;
/** Odd parity character set */
protected static final byte ODD_PARITY = LEFT_HAND_A;
/** Even parity character set */
protected static final byte EVEN_PARITY = LEFT_HAND_B;
private static final byte[][] CHARSET = {{3, 2, 1, 1},
{2, 2, 2, 1},
{2, 1, 2, 2},
{1, 4, 1, 1},
{1, 1, 3, 2},
{1, 2, 3, 1},
{1, 1, 1, 4},
{1, 3, 1, 2},
{1, 2, 1, 3},
{3, 1, 1, 2}};
private static final byte O = ODD_PARITY;
private static final byte E = EVEN_PARITY;
private static final byte[][] SUPP2_PARITY =
{{O, O}, {O, E}, {E, O}, {E, E}};
private static final byte[][] SUPP5_PARITY =
{{E, E, O, O, O},
{E, O, E, O, O},
{E, O, O, E, O},
{E, O, O, O, E},
{O, E, E, O, O},
{O, O, E, E, O},
{O, O, O, E, E},
{O, E, O, E, O},
{O, E, O, O, E},
{O, O, E, O, E}};
private ChecksumMode checksumMode = ChecksumMode.CP_AUTO;
/**
* Main constructor
* @param mode the checksum mode
*/
public UPCEANLogicImpl(ChecksumMode mode) {
this.checksumMode = mode;
}
/**
* Returns the current checksum mode.
* @return the checksum mode
*/
public ChecksumMode getChecksumMode() {
return this.checksumMode;
}
/**
* Validates a UPC/EAN message. The method throws IllegalArgumentExceptions
* if an invalid message is passed.
* @param msg the message to validate
*/
public static void validateMessage(String msg) {
for (int i = 0; i < msg.length(); i++) {
final char c = msg.charAt(i);
if ((c < '0') || (c > '9')) {
throw new IllegalArgumentException("Invalid characters found. "
+ "Valid are 0-9 only. Message: " + msg);
}
}
}
/**
* Calculates the check character for a given message
* @param msg the message
* @return char the check character
*/
public static char calcChecksum(String msg) {
int oddsum = 0;
int evensum = 0;
for (int i = msg.length() - 1; i >= 0; i--) {
if ((msg.length() - i) % 2 == 0) {
evensum += Character.digit(msg.charAt(i), 10);
} else {
oddsum += Character.digit(msg.charAt(i), 10);
}
}
int check = 10 - ((evensum + 3 * oddsum) % 10);
if (check >= 10) check = 0;
return Character.forDigit(check, 10);
}
private int widthAt(char ch, int index) {
if (Character.isDigit(ch)) {
int digit = Character.digit(ch, 10);
int width = CHARSET[digit][index];
return width;
} else {
throw new IllegalArgumentException("Invalid character '" + ch + "'. Expected a digit.");
}
}
/**
* Encodes a character.
* @param logic the logic handler to receive generated events
* @param c the character to encode
* @param charset the character set to use
*/
protected void encodeChar(ClassicBarcodeLogicHandler logic, char c, int charset) {
logic.startBarGroup(BarGroup.MSG_CHARACTER, String.valueOf(c));
if (charset == LEFT_HAND_B) {
for (byte i = 0; i < 4; i++) {
final int width = widthAt(c, 3 - i);
final boolean black = (i % 2 != 0);
logic.addBar(black, width);
}
} else {
for (byte i = 0; i < 4; i++) {
final int width = widthAt(c, i);
final boolean black = ((i % 2 == 0 && charset == RIGHT_HAND)
|| (i % 2 != 0 && charset == LEFT_HAND_A));
logic.addBar(black, width);
}
}
logic.endBarGroup();
}
/**
* Generates a side guard.
* @param logic the logic handler to receive generated events
*/
protected void drawSideGuard(ClassicBarcodeLogicHandler logic) {
//draw guard bars 101
logic.startBarGroup(BarGroup.UPC_EAN_GUARD, null);
logic.addBar(true, 1);
logic.addBar(false, 1);
logic.addBar(true, 1);
logic.endBarGroup();
}
/**
* Generates a center guard.
* @param logic the logic handler to receive generated events
*/
protected void drawCenterGuard(ClassicBarcodeLogicHandler logic) {
//draw guard bars 01010
logic.startBarGroup(BarGroup.UPC_EAN_GUARD, null);
logic.addBar(false, 1);
logic.addBar(true, 1);
logic.addBar(false, 1);
logic.addBar(true, 1);
logic.addBar(false, 1);
logic.endBarGroup();
}
/**
* Generates a left guard for a supplemental.
* @param logic the logic handler to receive generated events
*/
private void drawSuppLeftGuard(ClassicBarcodeLogicHandler logic) {
//draw guard bars 1011
logic.startBarGroup(BarGroup.UPC_EAN_GUARD, null);
logic.addBar(true, 1);
logic.addBar(false, 1);
logic.addBar(true, 2);
logic.endBarGroup();
}
/**
* Generates a supplemental separator.
* @param logic the logic handler to receive generated events
*/
private void drawSuppSeparator(ClassicBarcodeLogicHandler logic) {
//draw inter-character separator 01
logic.startBarGroup(BarGroup.UPC_EAN_GUARD, null);
logic.addBar(false, 1);
logic.addBar(true, 1);
logic.endBarGroup();
}
/**
* Generates a 2-character supplemental.
* @param logic the logic handler to receive generated events
* @param supp the two characters
*/
private void drawSupplemental2(ClassicBarcodeLogicHandler logic, String supp) {
int suppValue = Integer.parseInt(supp);
int remainder = suppValue % 4;
logic.startBarGroup(BarGroup.UPC_EAN_SUPP, supp);
drawSuppLeftGuard(logic);
encodeChar(logic, supp.charAt(0), SUPP2_PARITY[remainder][0]);
drawSuppSeparator(logic);
encodeChar(logic, supp.charAt(1), SUPP2_PARITY[remainder][1]);
logic.endBarGroup();
}
/**
* Generates a 5-character supplemental.
* @param logic the logic handler to receive generated events
* @param supp the five characters
*/
private void drawSupplemental5(ClassicBarcodeLogicHandler logic, String supp) {
int suppValue = Integer.parseInt(supp);
int weightedSum =
3 * ((suppValue / 10000) % 10)
+ 9 * ((suppValue / 1000) % 10)
+ 3 * ((suppValue / 100) % 10)
+ 9 * ((suppValue / 10) % 10)
+ 3 * (suppValue % 10);
byte checksum = (byte)(weightedSum % 10);
logic.startBarGroup(BarGroup.UPC_EAN_SUPP, supp);
drawSuppLeftGuard(logic);
for (byte i = 0; i < 5; i++) {
if (i > 0) {
drawSuppSeparator(logic);
}
encodeChar(logic, supp.charAt(i), SUPP5_PARITY[checksum][i]);
}
logic.endBarGroup();
}
/**
* Generates events for a supplemental.
* @param logic the logic handler to receive generated events
* @param supp the supplemental
*/
protected void drawSupplemental(ClassicBarcodeLogicHandler logic, String supp) {
if (supp == null) {
throw new NullPointerException("Supplemental message must not be null");
}
if (supp.length() == 2) {
drawSupplemental2(logic, supp);
} else if (supp.length() == 5) {
drawSupplemental5(logic, supp);
} else {
throw new IllegalArgumentException(
"Only supplemental lengths 2 and 5 are allowed: " + supp.length());
}
}
/**
* Returns the length of the supplemental part of a UPC/EAN message.
* The method throws an IllegalArgumentException if the supplement is
* malformed.
* @param msg the UPC/EAN message
* @return 2 or 5 if there is a supplemental, 0 if there's none.
*/
protected static int getSupplementalLength(String msg) {
String supp = retrieveSupplemental(msg);
if (supp == null) {
return 0;
} else if (supp.length() == 2) {
return 2;
} else if (supp.length() == 5) {
return 5;
} else {
throw new IllegalArgumentException(
"Illegal supplemental length (valid: 2 or 5): " + supp);
}
}
/**
* Removes an optional supplemental (ex. "+20") from the message.
* @param msg a UPC/EAN message
* @return the message without the supplemental
*/
protected static String removeSupplemental(String msg) {
int pos = msg.indexOf('+');
if (pos >= 0) {
return msg.substring(0, pos);
} else {
return msg;
}
}
/**
* Returns the supplemental part of a UPC/EAN message if there is one.
* Supplementals are added in the form: "+[supplemental]" (ex. "+20").
* @param msg a UPC/EAN message
* @return the supplemental part, null if there is none
*/
protected static String retrieveSupplemental(String msg) {
int pos = msg.indexOf('+');
if (pos >= 0) {
return msg.substring(pos + 1);
} else {
return null;
}
}
/**
* Generates the barcode logic.
* @param logic the logic handler to receive generated events
* @param msg the message to encode
*/
public abstract void generateBarcodeLogic(ClassicBarcodeLogicHandler logic, String msg);
}
|
{
"content_hash": "23ea170e81996dd84c0fcc8a25e528c7",
"timestamp": "",
"source": "github",
"line_count": 315,
"max_line_length": 100,
"avg_line_length": 34.36825396825397,
"alnum_prop": 0.5326066876039165,
"repo_name": "mbhk/barcode4j-modified",
"id": "852199bd03f403d338e1bcf1da4621dc2e31346f",
"size": "11434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "barcode4j/src/main/java/org/krysalis/barcode4j/impl/upcean/UPCEANLogicImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1198"
},
{
"name": "Java",
"bytes": "1049894"
},
{
"name": "Shell",
"bytes": "291"
},
{
"name": "XSLT",
"bytes": "21639"
}
],
"symlink_target": ""
}
|
/*
*
* Changelog
* $Date: 2014-06-04 (Wed, 04 June 2014) $
* $version 1.6.6 - Merge of pull requests.
* - IE10 touch support
* - Only prevent default event handling on valid swipe
* - Separate license/changelog comment
* - Detect if the swipe is valid at the end of the touch event.
* - Pass fingerdata to event handlers.
* - Add 'hold' gesture
* - Be more tolerant about the tap distance
* - Typos and minor fixes
*/
/**
* See (http://jquery.com/).
* @name $
* @class
* See the jQuery Library (http://jquery.com/) for full details. This just
* documents the function and classes that are added to jQuery by this plug-in.
*/
/**
* See (http://jquery.com/)
* @name fn
* @class
* See the jQuery Library (http://jquery.com/) for full details. This just
* documents the function and classes that are added to jQuery by this plug-in.
* @memberOf $
*/
(function (factory) {
if (typeof define === 'function' && define.amd && define.amd.jQuery) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
"use strict";
//Constants
var LEFT = "left",
RIGHT = "right",
UP = "up",
DOWN = "down",
IN = "in",
OUT = "out",
NONE = "none",
AUTO = "auto",
SWIPE = "swipe",
PINCH = "pinch",
TAP = "tap",
DOUBLE_TAP = "doubletap",
LONG_TAP = "longtap",
HOLD = "hold",
HORIZONTAL = "horizontal",
VERTICAL = "vertical",
ALL_FINGERS = "all",
DOUBLE_TAP_THRESHOLD = 10,
PHASE_START = "start",
PHASE_MOVE = "move",
PHASE_END = "end",
PHASE_CANCEL = "cancel",
SUPPORTS_TOUCH = 'ontouchstart' in window,
SUPPORTS_POINTER_IE10 = window.navigator.msPointerEnabled && !window.navigator.pointerEnabled,
SUPPORTS_POINTER = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
PLUGIN_NS = 'TouchSwipe';
/**
* The default configuration, and available options to configure touch swipe with.
* You can set the default values by updating any of the properties prior to instantiation.
* @name $.fn.swipe.defaults
* @namespace
* @property {int} [fingers=1] The number of fingers to detect in a swipe. Any swipes that do not meet this requirement will NOT trigger swipe handlers.
* @property {int} [threshold=75] The number of pixels that the user must move their finger by before it is considered a swipe.
* @property {int} [cancelThreshold=null] The number of pixels that the user must move their finger back from the original swipe direction to cancel the gesture.
* @property {int} [pinchThreshold=20] The number of pixels that the user must pinch their finger by before it is considered a pinch.
* @property {int} [maxTimeThreshold=null] Time, in milliseconds, between touchStart and touchEnd must NOT exceed in order to be considered a swipe.
* @property {int} [fingerReleaseThreshold=250] Time in milliseconds between releasing multiple fingers. If 2 fingers are down, and are released one after the other, if they are within this threshold, it counts as a simultaneous release.
* @property {int} [longTapThreshold=500] Time in milliseconds between tap and release for a long tap
* @property {int} [doubleTapThreshold=200] Time in milliseconds between 2 taps to count as a double tap
* @property {function} [swipe=null] A handler to catch all swipes. See {@link $.fn.swipe#event:swipe}
* @property {function} [swipeLeft=null] A handler that is triggered for "left" swipes. See {@link $.fn.swipe#event:swipeLeft}
* @property {function} [swipeRight=null] A handler that is triggered for "right" swipes. See {@link $.fn.swipe#event:swipeRight}
* @property {function} [swipeUp=null] A handler that is triggered for "up" swipes. See {@link $.fn.swipe#event:swipeUp}
* @property {function} [swipeDown=null] A handler that is triggered for "down" swipes. See {@link $.fn.swipe#event:swipeDown}
* @property {function} [swipeStatus=null] A handler triggered for every phase of the swipe. See {@link $.fn.swipe#event:swipeStatus}
* @property {function} [pinchIn=null] A handler triggered for pinch in events. See {@link $.fn.swipe#event:pinchIn}
* @property {function} [pinchOut=null] A handler triggered for pinch out events. See {@link $.fn.swipe#event:pinchOut}
* @property {function} [pinchStatus=null] A handler triggered for every phase of a pinch. See {@link $.fn.swipe#event:pinchStatus}
* @property {function} [tap=null] A handler triggered when a user just taps on the item, rather than swipes it. If they do not move, tap is triggered, if they do move, it is not.
* @property {function} [doubleTap=null] A handler triggered when a user double taps on the item. The delay between taps can be set with the doubleTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold}
* @property {function} [longTap=null] A handler triggered when a user long taps on the item. The delay between start and end can be set with the longTapThreshold property. See {@link $.fn.swipe.defaults#longTapThreshold}
* @property (function) [hold=null] A handler triggered when a user reaches longTapThreshold on the item. See {@link $.fn.swipe.defaults#longTapThreshold}
* @property {boolean} [triggerOnTouchEnd=true] If true, the swipe events are triggered when the touch end event is received (user releases finger). If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
* @property {boolean} [triggerOnTouchLeave=false] If true, then when the user leaves the swipe object, the swipe will end and trigger appropriate handlers.
* @property {string|undefined} [allowPageScroll='auto'] How the browser handles page scrolls when the user is swiping on a touchSwipe object. See {@link $.fn.swipe.pageScroll}. <br/><br/>
<code>"auto"</code> : all undefined swipes will cause the page to scroll in that direction. <br/>
<code>"none"</code> : the page will not scroll when user swipes. <br/>
<code>"horizontal"</code> : will force page to scroll on horizontal swipes. <br/>
<code>"vertical"</code> : will force page to scroll on vertical swipes. <br/>
* @property {boolean} [fallbackToMouseEvents=true] If true mouse events are used when run on a non touch device, false will stop swipes being triggered by mouse events on non tocuh devices.
* @property {string} [excludedElements="button, input, select, textarea, a, .noSwipe"] A jquery selector that specifies child elements that do NOT trigger swipes. By default this excludes all form, input, select, button, anchor and .noSwipe elements.
*/
var defaults = {
fingers: 1,
threshold: 75,
cancelThreshold:null,
pinchThreshold:20,
maxTimeThreshold: null,
fingerReleaseThreshold:250,
longTapThreshold:500,
doubleTapThreshold:200,
swipe: null,
swipeLeft: null,
swipeRight: null,
swipeUp: null,
swipeDown: null,
swipeStatus: null,
pinchIn:null,
pinchOut:null,
pinchStatus:null,
click:null, //Deprecated since 1.6.2
tap:null,
doubleTap:null,
longTap:null,
hold:null,
triggerOnTouchEnd: true,
triggerOnTouchLeave:false,
allowPageScroll: "auto",
fallbackToMouseEvents: true,
excludedElements:"label, button, input, select, textarea, a, .noSwipe"
};
/**
* Applies TouchSwipe behaviour to one or more jQuery objects.
* The TouchSwipe plugin can be instantiated via this method, or methods within
* TouchSwipe can be executed via this method as per jQuery plugin architecture.
* @see TouchSwipe
* @class
* @param {Mixed} method If the current DOMNode is a TouchSwipe object, and <code>method</code> is a TouchSwipe method, then
* the <code>method</code> is executed, and any following arguments are passed to the TouchSwipe method.
* If <code>method</code> is an object, then the TouchSwipe class is instantiated on the current DOMNode, passing the
* configuration properties defined in the object. See TouchSwipe
*
*/
$.fn.swipe = function (method) {
var $this = $(this),
plugin = $this.data(PLUGIN_NS);
//Check if we are already instantiated and trying to execute a method
if (plugin && typeof method === 'string') {
if (plugin[method]) {
return plugin[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
$.error('Method ' + method + ' does not exist on jQuery.swipe');
}
}
//Else not instantiated and trying to pass init object (or nothing)
else if (!plugin && (typeof method === 'object' || !method)) {
return init.apply(this, arguments);
}
return $this;
};
//Expose our defaults so a user could override the plugin defaults
$.fn.swipe.defaults = defaults;
/**
* The phases that a touch event goes through. The <code>phase</code> is passed to the event handlers.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @property {string} PHASE_START Constant indicating the start phase of the touch event. Value is <code>"start"</code>.
* @property {string} PHASE_MOVE Constant indicating the move phase of the touch event. Value is <code>"move"</code>.
* @property {string} PHASE_END Constant indicating the end phase of the touch event. Value is <code>"end"</code>.
* @property {string} PHASE_CANCEL Constant indicating the cancel phase of the touch event. Value is <code>"cancel"</code>.
*/
$.fn.swipe.phases = {
PHASE_START: PHASE_START,
PHASE_MOVE: PHASE_MOVE,
PHASE_END: PHASE_END,
PHASE_CANCEL: PHASE_CANCEL
};
/**
* The direction constants that are passed to the event handlers.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @property {string} LEFT Constant indicating the left direction. Value is <code>"left"</code>.
* @property {string} RIGHT Constant indicating the right direction. Value is <code>"right"</code>.
* @property {string} UP Constant indicating the up direction. Value is <code>"up"</code>.
* @property {string} DOWN Constant indicating the down direction. Value is <code>"cancel"</code>.
* @property {string} IN Constant indicating the in direction. Value is <code>"in"</code>.
* @property {string} OUT Constant indicating the out direction. Value is <code>"out"</code>.
*/
$.fn.swipe.directions = {
LEFT: LEFT,
RIGHT: RIGHT,
UP: UP,
DOWN: DOWN,
IN : IN,
OUT: OUT
};
/**
* The page scroll constants that can be used to set the value of <code>allowPageScroll</code> option
* These properties are read only
* @namespace
* @readonly
* @see $.fn.swipe.defaults#allowPageScroll
* @property {string} NONE Constant indicating no page scrolling is allowed. Value is <code>"none"</code>.
* @property {string} HORIZONTAL Constant indicating horizontal page scrolling is allowed. Value is <code>"horizontal"</code>.
* @property {string} VERTICAL Constant indicating vertical page scrolling is allowed. Value is <code>"vertical"</code>.
* @property {string} AUTO Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers registered. Value is <code>"auto"</code>.
*/
$.fn.swipe.pageScroll = {
NONE: NONE,
HORIZONTAL: HORIZONTAL,
VERTICAL: VERTICAL,
AUTO: AUTO
};
/**
* Constants representing the number of fingers used in a swipe. These are used to set both the value of <code>fingers</code> in the
* options object, as well as the value of the <code>fingers</code> event property.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @see $.fn.swipe.defaults#fingers
* @property {string} ONE Constant indicating 1 finger is to be detected / was detected. Value is <code>1</code>.
* @property {string} TWO Constant indicating 2 fingers are to be detected / were detected. Value is <code>1</code>.
* @property {string} THREE Constant indicating 3 finger are to be detected / were detected. Value is <code>1</code>.
* @property {string} ALL Constant indicating any combination of finger are to be detected. Value is <code>"all"</code>.
*/
$.fn.swipe.fingers = {
ONE: 1,
TWO: 2,
THREE: 3,
ALL: ALL_FINGERS
};
/**
* Initialise the plugin for each DOM element matched
* This creates a new instance of the main TouchSwipe class for each DOM element, and then
* saves a reference to that instance in the elements data property.
* @internal
*/
function init(options) {
//Prep and extend the options
if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) {
options.allowPageScroll = NONE;
}
//Check for deprecated options
//Ensure that any old click handlers are assigned to the new tap, unless we have a tap
if(options.click!==undefined && options.tap===undefined) {
options.tap = options.click;
}
if (!options) {
options = {};
}
//pass empty object so we dont modify the defaults
options = $.extend({}, $.fn.swipe.defaults, options);
//For each element instantiate the plugin
return this.each(function () {
var $this = $(this);
//Check we havent already initialised the plugin
var plugin = $this.data(PLUGIN_NS);
if (!plugin) {
plugin = new TouchSwipe(this, options);
$this.data(PLUGIN_NS, plugin);
}
});
}
/**
* Main TouchSwipe Plugin Class.
* Do not use this to construct your TouchSwipe object, use the jQuery plugin method $.fn.swipe(); {@link $.fn.swipe}
* @private
* @name TouchSwipe
* @param {DOMNode} element The HTML DOM object to apply to plugin to
* @param {Object} options The options to configure the plugin with. @link {$.fn.swipe.defaults}
* @see $.fh.swipe.defaults
* @see $.fh.swipe
* @class
*/
function TouchSwipe(element, options) {
var useTouchEvents = (SUPPORTS_TOUCH || SUPPORTS_POINTER || !options.fallbackToMouseEvents),
START_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerDown' : 'pointerdown') : 'touchstart') : 'mousedown',
MOVE_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerMove' : 'pointermove') : 'touchmove') : 'mousemove',
END_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerUp' : 'pointerup') : 'touchend') : 'mouseup',
LEAVE_EV = useTouchEvents ? null : 'mouseleave', //we manually detect leave on touch devices, so null event here
CANCEL_EV = (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerCancel' : 'pointercancel') : 'touchcancel');
//touch properties
var distance = 0,
direction = null,
duration = 0,
startTouchesDistance = 0,
endTouchesDistance = 0,
pinchZoom = 1,
pinchDistance = 0,
pinchDirection = 0,
maximumsMap=null;
//jQuery wrapped element for this instance
var $element = $(element);
//Current phase of th touch cycle
var phase = "start";
// the current number of fingers being used.
var fingerCount = 0;
//track mouse points / delta
var fingerData=null;
//track times
var startTime = 0,
endTime = 0,
previousTouchEndTime=0,
previousTouchFingerCount=0,
doubleTapStartTime=0;
//Timeouts
var singleTapTimeout=null,
holdTimeout=null;
// Add gestures to all swipable areas if supported
try {
$element.bind(START_EV, touchStart);
$element.bind(CANCEL_EV, touchCancel);
}
catch (e) {
$.error('events not supported ' + START_EV + ',' + CANCEL_EV + ' on jQuery.swipe');
}
//
//Public methods
//
/**
* re-enables the swipe plugin with the previous configuration
* @function
* @name $.fn.swipe#enable
* @return {DOMNode} The Dom element that was registered with TouchSwipe
* @example $("#element").swipe("enable");
*/
this.enable = function () {
$element.bind(START_EV, touchStart);
$element.bind(CANCEL_EV, touchCancel);
return $element;
};
/**
* disables the swipe plugin
* @function
* @name $.fn.swipe#disable
* @return {DOMNode} The Dom element that is now registered with TouchSwipe
* @example $("#element").swipe("disable");
*/
this.disable = function () {
removeListeners();
return $element;
};
/**
* Destroy the swipe plugin completely. To use any swipe methods, you must re initialise the plugin.
* @function
* @name $.fn.swipe#destroy
* @return {DOMNode} The Dom element that was registered with TouchSwipe
* @example $("#element").swipe("destroy");
*/
this.destroy = function () {
removeListeners();
$element.data(PLUGIN_NS, null);
return $element;
};
/**
* Allows run time updating of the swipe configuration options.
* @function
* @name $.fn.swipe#option
* @param {String} property The option property to get or set
* @param {Object} [value] The value to set the property to
* @return {Object} If only a property name is passed, then that property value is returned.
* @example $("#element").swipe("option", "threshold"); // return the threshold
* @example $("#element").swipe("option", "threshold", 100); // set the threshold after init
* @see $.fn.swipe.defaults
*
*/
this.option = function (property, value) {
if(options[property]!==undefined) {
if(value===undefined) {
return options[property];
} else {
options[property] = value;
}
} else {
$.error('Option ' + property + ' does not exist on jQuery.swipe.options');
}
return null;
};
//
// Private methods
//
//
// EVENTS
//
/**
* Event handler for a touch start event.
* Stops the default click event from triggering and stores where we touched
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchStart(jqEvent) {
//If we already in a touch event (a finger already in use) then ignore subsequent ones..
if( getTouchInProgress() )
return;
//Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe
if( $(jqEvent.target).closest( options.excludedElements, $element ).length>0 )
return;
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
var ret,
evt = SUPPORTS_TOUCH ? event.touches[0] : event;
phase = PHASE_START;
//If we support touches, get the finger count
if (SUPPORTS_TOUCH) {
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
}
//Else this is the desktop, so stop the browser from dragging the image
else {
jqEvent.preventDefault(); //call this on jq event so we are cross browser
}
//clear vars..
distance = 0;
direction = null;
pinchDirection=null;
duration = 0;
startTouchesDistance=0;
endTouchesDistance=0;
pinchZoom = 1;
pinchDistance = 0;
fingerData=createAllFingerData();
maximumsMap=createMaximumsData();
cancelMultiFingerRelease();
// check the number of fingers is what we are looking for, or we are capturing pinches
if (!SUPPORTS_TOUCH || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) {
// get the coordinates of the touch
createFingerData( 0, evt );
startTime = getTimeStamp();
if(fingerCount==2) {
//Keep track of the initial pinch distance, so we can calculate the diff later
//Store second finger data as start
createFingerData( 1, event.touches[1] );
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
}
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
}
else {
//A touch with more or less than the fingers we are looking for, so cancel
ret = false;
}
//If we have a return value from the users handler, then return and cancel
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
return ret;
}
else {
if (options.hold) {
holdTimeout = setTimeout($.proxy(function() {
//Trigger the event
$element.trigger('hold', [event.target]);
//Fire the callback
if(options.hold) {
ret = options.hold.call($element, event, event.target);
}
}, this), options.longTapThreshold );
}
setTouchInProgress(true);
}
return null;
};
/**
* Event handler for a touch move event.
* If we change fingers during move, then cancel the event
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchMove(jqEvent) {
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything..
if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease())
return;
var ret,
evt = SUPPORTS_TOUCH ? event.touches[0] : event;
//Update the finger data
var currentFinger = updateFingerData(evt);
endTime = getTimeStamp();
if (SUPPORTS_TOUCH) {
fingerCount = event.touches.length;
}
if (options.hold)
clearTimeout(holdTimeout);
phase = PHASE_MOVE;
//If we have 2 fingers get Touches distance as well
if(fingerCount==2) {
//Keep track of the initial pinch distance, so we can calculate the diff later
//We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers
if(startTouchesDistance==0) {
//Create second finger if this is the first time...
createFingerData( 1, event.touches[1] );
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
} else {
//Else just update the second finger
updateFingerData(event.touches[1]);
endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end);
pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end);
}
pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance);
pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance);
}
if ( (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH || hasPinches() ) {
direction = calculateDirection(currentFinger.start, currentFinger.end);
//Check if we need to prevent default event (page scroll / pinch zoom) or not
validateDefaultEvent(jqEvent, direction);
//Distance and duration are all off the main finger
distance = calculateDistance(currentFinger.start, currentFinger.end);
duration = calculateDuration();
//Cache the maximum distance we made in this direction
setMaxDistance(direction, distance);
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
//If we trigger end events when threshold are met, or trigger events when touch leaves element
if(!options.triggerOnTouchEnd || options.triggerOnTouchLeave) {
var inBounds = true;
//If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit)
if(options.triggerOnTouchLeave) {
var bounds = getbounds( this );
inBounds = isInBounds( currentFinger.end, bounds );
}
//Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these..
if(!options.triggerOnTouchEnd && inBounds) {
phase = getNextPhase( PHASE_MOVE );
}
//We end if out of bounds here, so set current phase to END, and check if its modified
else if(options.triggerOnTouchLeave && !inBounds ) {
phase = getNextPhase( PHASE_END );
}
if(phase==PHASE_CANCEL || phase==PHASE_END) {
triggerHandler(event, phase);
}
}
}
else {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
}
/**
* Event handler for a touch end event.
* Calculate the direction and trigger events
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchEnd(jqEvent) {
//As we use Jquery bind for events, we need to target the original event object
var event = jqEvent.originalEvent;
//If we are still in a touch with another finger return
//This allows us to wait a fraction and see if the other finger comes up, if it does within the threshold, then we treat it as a multi release, not a single release.
if (SUPPORTS_TOUCH) {
if(event.touches.length>0) {
startMultiFingerRelease();
return true;
}
}
//If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release.
//This is used to allow 2 fingers to release fractionally after each other, whilst maintainig the event as containg 2 fingers, not 1
if(inMultiFingerRelease()) {
fingerCount=previousTouchFingerCount;
}
//Set end of swipe
endTime = getTimeStamp();
//Get duration incase move was never fired
duration = calculateDuration();
//If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase
if(didSwipeBackToCancel() || !validateSwipeDistance()) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
} else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd == false && phase === PHASE_MOVE)) {
//call this on jq event so we are cross browser
jqEvent.preventDefault();
phase = PHASE_END;
triggerHandler(event, phase);
}
//Special cases - A tap should always fire on touch end regardless,
//So here we manually trigger the tap end handler by itself
//We dont run trigger handler as it will re-trigger events that may have fired already
else if (!options.triggerOnTouchEnd && hasTap()) {
//Trigger the pinch events...
phase = PHASE_END;
triggerHandlerForGesture(event, phase, TAP);
}
else if (phase === PHASE_MOVE) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
setTouchInProgress(false);
return null;
}
/**
* Event handler for a touch cancel event.
* Clears current vars
* @inner
*/
function touchCancel() {
// reset the variables back to default values
fingerCount = 0;
endTime = 0;
startTime = 0;
startTouchesDistance=0;
endTouchesDistance=0;
pinchZoom=1;
//If we were in progress of tracking a possible multi touch end, then re set it.
cancelMultiFingerRelease();
setTouchInProgress(false);
}
/**
* Event handler for a touch leave event.
* This is only triggered on desktops, in touch we work this out manually
* as the touchleave event is not supported in webkit
* @inner
*/
function touchLeave(jqEvent) {
var event = jqEvent.originalEvent;
//If we have the trigger on leave property set....
if(options.triggerOnTouchLeave) {
phase = getNextPhase( PHASE_END );
triggerHandler(event, phase);
}
}
/**
* Removes all listeners that were associated with the plugin
* @inner
*/
function removeListeners() {
$element.unbind(START_EV, touchStart);
$element.unbind(CANCEL_EV, touchCancel);
$element.unbind(MOVE_EV, touchMove);
$element.unbind(END_EV, touchEnd);
//we only have leave events on desktop, we manually calculate leave on touch as its not supported in webkit
if(LEAVE_EV) {
$element.unbind(LEAVE_EV, touchLeave);
}
setTouchInProgress(false);
}
/**
* Checks if the time and distance thresholds have been met, and if so then the appropriate handlers are fired.
*/
function getNextPhase(currentPhase) {
var nextPhase = currentPhase;
// Ensure we have valid swipe (under time and over distance and check if we are out of bound...)
var validTime = validateSwipeTime();
var validDistance = validateSwipeDistance();
var didCancel = didSwipeBackToCancel();
//If we have exceeded our time, then cancel
if(!validTime || didCancel) {
nextPhase = PHASE_CANCEL;
}
//Else if we are moving, and have reached distance then end
else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) ) {
nextPhase = PHASE_END;
}
//Else if we have ended by leaving and didn't reach distance, then cancel
else if (!validDistance && currentPhase==PHASE_END && options.triggerOnTouchLeave) {
nextPhase = PHASE_CANCEL;
}
return nextPhase;
}
/**
* Trigger the relevant event handler
* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
* @param {object} event the original event object
* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
* @inner
*/
function triggerHandler(event, phase) {
var ret = undefined;
// SWIPE GESTURES
if(didSwipe() || hasSwipes()) { //hasSwipes as status needs to fire even if swipe is invalid
//Trigger the swipe events...
ret = triggerHandlerForGesture(event, phase, SWIPE);
}
// PINCH GESTURES (if the above didn't cancel)
else if((didPinch() || hasPinches()) && ret!==false) {
//Trigger the pinch events...
ret = triggerHandlerForGesture(event, phase, PINCH);
}
// CLICK / TAP (if the above didn't cancel)
if(didDoubleTap() && ret!==false) {
//Trigger the tap events...
ret = triggerHandlerForGesture(event, phase, DOUBLE_TAP);
}
// CLICK / TAP (if the above didn't cancel)
else if(didLongTap() && ret!==false) {
//Trigger the tap events...
ret = triggerHandlerForGesture(event, phase, LONG_TAP);
}
// CLICK / TAP (if the above didn't cancel)
else if(didTap() && ret!==false) {
//Trigger the tap event..
ret = triggerHandlerForGesture(event, phase, TAP);
}
// If we are cancelling the gesture, then manually trigger the reset handler
if (phase === PHASE_CANCEL) {
touchCancel(event);
}
// If we are ending the gesture, then manually trigger the reset handler IF all fingers are off
if(phase === PHASE_END) {
//If we support touch, then check that all fingers are off before we cancel
if (SUPPORTS_TOUCH) {
if(event.touches.length==0) {
touchCancel(event);
}
}
else {
touchCancel(event);
}
}
return ret;
}
/**
* Trigger the relevant event handler
* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
* @param {object} event the original event object
* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
* @param {string} gesture the gesture to trigger a handler for : PINCH or SWIPE {@link $.fn.swipe.gestures}
* @return Boolean False, to indicate that the event should stop propagation, or void.
* @inner
*/
function triggerHandlerForGesture(event, phase, gesture) {
var ret=undefined;
//SWIPES....
if(gesture==SWIPE) {
//Trigger status every time..
//Trigger the event...
$element.trigger('swipeStatus', [phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData]);
//Fire the callback
if (options.swipeStatus) {
ret = options.swipeStatus.call($element, event, phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if(ret===false) return false;
}
if (phase == PHASE_END && validateSwipe()) {
//Fire the catch all event
$element.trigger('swipe', [direction, distance, duration, fingerCount, fingerData]);
//Fire catch all callback
if (options.swipe) {
ret = options.swipe.call($element, event, direction, distance, duration, fingerCount, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if(ret===false) return false;
}
//trigger direction specific event handlers
switch (direction) {
case LEFT:
//Trigger the event
$element.trigger('swipeLeft', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeLeft) {
ret = options.swipeLeft.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
case RIGHT:
//Trigger the event
$element.trigger('swipeRight', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeRight) {
ret = options.swipeRight.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
case UP:
//Trigger the event
$element.trigger('swipeUp', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeUp) {
ret = options.swipeUp.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
case DOWN:
//Trigger the event
$element.trigger('swipeDown', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeDown) {
ret = options.swipeDown.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
}
}
}
//PINCHES....
if(gesture==PINCH) {
//Trigger the event
$element.trigger('pinchStatus', [phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
//Fire the callback
if (options.pinchStatus) {
ret = options.pinchStatus.call($element, event, phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if(ret===false) return false;
}
if(phase==PHASE_END && validatePinch()) {
switch (pinchDirection) {
case IN:
//Trigger the event
$element.trigger('pinchIn', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
//Fire the callback
if (options.pinchIn) {
ret = options.pinchIn.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
}
break;
case OUT:
//Trigger the event
$element.trigger('pinchOut', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
//Fire the callback
if (options.pinchOut) {
ret = options.pinchOut.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
}
break;
}
}
}
if(gesture==TAP) {
if(phase === PHASE_CANCEL || phase === PHASE_END) {
//Cancel any existing double tap
clearTimeout(singleTapTimeout);
//Cancel hold timeout
clearTimeout(holdTimeout);
//If we are also looking for doubelTaps, wait incase this is one...
if(hasDoubleTap() && !inDoubleTap()) {
//Cache the time of this tap
doubleTapStartTime = getTimeStamp();
//Now wait for the double tap timeout, and trigger this single tap
//if its not cancelled by a double tap
singleTapTimeout = setTimeout($.proxy(function() {
doubleTapStartTime=null;
//Trigger the event
$element.trigger('tap', [event.target]);
//Fire the callback
if(options.tap) {
ret = options.tap.call($element, event, event.target);
}
}, this), options.doubleTapThreshold );
} else {
doubleTapStartTime=null;
//Trigger the event
$element.trigger('tap', [event.target]);
//Fire the callback
if(options.tap) {
ret = options.tap.call($element, event, event.target);
}
}
}
}
else if (gesture==DOUBLE_TAP) {
if(phase === PHASE_CANCEL || phase === PHASE_END) {
//Cancel any pending singletap
clearTimeout(singleTapTimeout);
doubleTapStartTime=null;
//Trigger the event
$element.trigger('doubletap', [event.target]);
//Fire the callback
if(options.doubleTap) {
ret = options.doubleTap.call($element, event, event.target);
}
}
}
else if (gesture==LONG_TAP) {
if(phase === PHASE_CANCEL || phase === PHASE_END) {
//Cancel any pending singletap (shouldnt be one)
clearTimeout(singleTapTimeout);
doubleTapStartTime=null;
//Trigger the event
$element.trigger('longtap', [event.target]);
//Fire the callback
if(options.longTap) {
ret = options.longTap.call($element, event, event.target);
}
}
}
return ret;
}
//
// GESTURE VALIDATION
//
/**
* Checks the user has swipe far enough
* @return Boolean if <code>threshold</code> has been set, return true if the threshold was met, else false.
* If no threshold was set, then we return true.
* @inner
*/
function validateSwipeDistance() {
var valid = true;
//If we made it past the min swipe distance..
if (options.threshold !== null) {
valid = distance >= options.threshold;
}
return valid;
}
/**
* Checks the user has swiped back to cancel.
* @return Boolean if <code>cancelThreshold</code> has been set, return true if the cancelThreshold was met, else false.
* If no cancelThreshold was set, then we return true.
* @inner
*/
function didSwipeBackToCancel() {
var cancelled = false;
if(options.cancelThreshold !== null && direction !==null) {
cancelled = (getMaxDistance( direction ) - distance) >= options.cancelThreshold;
}
return cancelled;
}
/**
* Checks the user has pinched far enough
* @return Boolean if <code>pinchThreshold</code> has been set, return true if the threshold was met, else false.
* If no threshold was set, then we return true.
* @inner
*/
function validatePinchDistance() {
if (options.pinchThreshold !== null) {
return pinchDistance >= options.pinchThreshold;
}
return true;
}
/**
* Checks that the time taken to swipe meets the minimum / maximum requirements
* @return Boolean
* @inner
*/
function validateSwipeTime() {
var result;
//If no time set, then return true
if (options.maxTimeThreshold) {
if (duration >= options.maxTimeThreshold) {
result = false;
} else {
result = true;
}
}
else {
result = true;
}
return result;
}
/**
* Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
* This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
* @param {object} jqEvent The normalised jQuery representation of the event object.
* @param {string} direction The direction of the event. See {@link $.fn.swipe.directions}
* @see $.fn.swipe.directions
* @inner
*/
function validateDefaultEvent(jqEvent, direction) {
if (options.allowPageScroll === NONE || hasPinches()) {
jqEvent.preventDefault();
} else {
var auto = options.allowPageScroll === AUTO;
switch (direction) {
case LEFT:
if ((options.swipeLeft && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
jqEvent.preventDefault();
}
break;
case RIGHT:
if ((options.swipeRight && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
jqEvent.preventDefault();
}
break;
case UP:
if ((options.swipeUp && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
jqEvent.preventDefault();
}
break;
case DOWN:
if ((options.swipeDown && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
jqEvent.preventDefault();
}
break;
}
}
}
// PINCHES
/**
* Returns true of the current pinch meets the thresholds
* @return Boolean
* @inner
*/
function validatePinch() {
var hasCorrectFingerCount = validateFingers();
var hasEndPoint = validateEndPoint();
var hasCorrectDistance = validatePinchDistance();
return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance;
}
/**
* Returns true if any Pinch events have been registered
* @return Boolean
* @inner
*/
function hasPinches() {
//Enure we dont return 0 or null for false values
return !!(options.pinchStatus || options.pinchIn || options.pinchOut);
}
/**
* Returns true if we are detecting pinches, and have one
* @return Boolean
* @inner
*/
function didPinch() {
//Enure we dont return 0 or null for false values
return !!(validatePinch() && hasPinches());
}
// SWIPES
/**
* Returns true if the current swipe meets the thresholds
* @return Boolean
* @inner
*/
function validateSwipe() {
//Check validity of swipe
var hasValidTime = validateSwipeTime();
var hasValidDistance = validateSwipeDistance();
var hasCorrectFingerCount = validateFingers();
var hasEndPoint = validateEndPoint();
var didCancel = didSwipeBackToCancel();
// if the user swiped more than the minimum length, perform the appropriate action
// hasValidDistance is null when no distance is set
var valid = !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime;
return valid;
}
/**
* Returns true if any Swipe events have been registered
* @return Boolean
* @inner
*/
function hasSwipes() {
//Enure we dont return 0 or null for false values
return !!(options.swipe || options.swipeStatus || options.swipeLeft || options.swipeRight || options.swipeUp || options.swipeDown);
}
/**
* Returns true if we are detecting swipes and have one
* @return Boolean
* @inner
*/
function didSwipe() {
//Enure we dont return 0 or null for false values
return !!(validateSwipe() && hasSwipes());
}
/**
* Returns true if we have matched the number of fingers we are looking for
* @return Boolean
* @inner
*/
function validateFingers() {
//The number of fingers we want were matched, or on desktop we ignore
return ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH);
}
/**
* Returns true if we have an end point for the swipe
* @return Boolean
* @inner
*/
function validateEndPoint() {
//We have an end value for the finger
return fingerData[0].end.x !== 0;
}
// TAP / CLICK
/**
* Returns true if a click / tap events have been registered
* @return Boolean
* @inner
*/
function hasTap() {
//Enure we dont return 0 or null for false values
return !!(options.tap) ;
}
/**
* Returns true if a double tap events have been registered
* @return Boolean
* @inner
*/
function hasDoubleTap() {
//Enure we dont return 0 or null for false values
return !!(options.doubleTap) ;
}
/**
* Returns true if any long tap events have been registered
* @return Boolean
* @inner
*/
function hasLongTap() {
//Enure we dont return 0 or null for false values
return !!(options.longTap) ;
}
/**
* Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
* @return Boolean
* @inner
*/
function validateDoubleTap() {
if(doubleTapStartTime==null){
return false;
}
var now = getTimeStamp();
return (hasDoubleTap() && ((now-doubleTapStartTime) <= options.doubleTapThreshold));
}
/**
* Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
* @return Boolean
* @inner
*/
function inDoubleTap() {
return validateDoubleTap();
}
/**
* Returns true if we have a valid tap
* @return Boolean
* @inner
*/
function validateTap() {
return ((fingerCount === 1 || !SUPPORTS_TOUCH) && (isNaN(distance) || distance < options.threshold));
}
/**
* Returns true if we have a valid long tap
* @return Boolean
* @inner
*/
function validateLongTap() {
//slight threshold on moving finger
return ((duration > options.longTapThreshold) && (distance < DOUBLE_TAP_THRESHOLD));
}
/**
* Returns true if we are detecting taps and have one
* @return Boolean
* @inner
*/
function didTap() {
//Enure we dont return 0 or null for false values
return !!(validateTap() && hasTap());
}
/**
* Returns true if we are detecting double taps and have one
* @return Boolean
* @inner
*/
function didDoubleTap() {
//Enure we dont return 0 or null for false values
return !!(validateDoubleTap() && hasDoubleTap());
}
/**
* Returns true if we are detecting long taps and have one
* @return Boolean
* @inner
*/
function didLongTap() {
//Enure we dont return 0 or null for false values
return !!(validateLongTap() && hasLongTap());
}
// MULTI FINGER TOUCH
/**
* Starts tracking the time between 2 finger releases, and keeps track of how many fingers we initially had up
* @inner
*/
function startMultiFingerRelease() {
previousTouchEndTime = getTimeStamp();
previousTouchFingerCount = event.touches.length+1;
}
/**
* Cancels the tracking of time between 2 finger releases, and resets counters
* @inner
*/
function cancelMultiFingerRelease() {
previousTouchEndTime = 0;
previousTouchFingerCount = 0;
};
/**
* Checks if we are in the threshold between 2 fingers being released
* @return Boolean
* @inner
*/
function inMultiFingerRelease() {
var withinThreshold = false;
if(previousTouchEndTime) {
var diff = getTimeStamp() - previousTouchEndTime;
if( diff<=options.fingerReleaseThreshold ) {
withinThreshold = true;
};
};
return withinThreshold;
};
/**
* gets a data flag to indicate that a touch is in progress
* @return Boolean
* @inner
*/
function getTouchInProgress() {
//strict equality to ensure only true and false are returned
return !!($element.data(PLUGIN_NS+'_intouch') === true);
}
/**
* Sets a data flag to indicate that a touch is in progress
* @param {boolean} val The value to set the property to
* @inner
*/
function setTouchInProgress(val) {
//Add or remove event listeners depending on touch status
if(val===true) {
$element.bind(MOVE_EV, touchMove);
$element.bind(END_EV, touchEnd);
//we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
if(LEAVE_EV) {
$element.bind(LEAVE_EV, touchLeave);
}
} else {
$element.unbind(MOVE_EV, touchMove, false);
$element.unbind(END_EV, touchEnd, false);
//we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
if(LEAVE_EV) {
$element.unbind(LEAVE_EV, touchLeave, false);
}
}
//strict equality to ensure only true and false can update the value
$element.data(PLUGIN_NS+'_intouch', val === true);
}
/**
* Creates the finger data for the touch/finger in the event object.
* @param {int} index The index in the array to store the finger data (usually the order the fingers were pressed)
* @param {object} evt The event object containing finger data
* @return finger data object
* @inner
*/
function createFingerData( index, evt ) {
var id = evt.identifier!==undefined ? evt.identifier : 0;
fingerData[index].identifier = id;
fingerData[index].start.x = fingerData[index].end.x = evt.pageX||evt.clientX;
fingerData[index].start.y = fingerData[index].end.y = evt.pageY||evt.clientY;
return fingerData[index];
}
/**
* Updates the finger data for a particular event object
* @param {object} evt The event object containing the touch/finger data to upadte
* @return a finger data object.
* @inner
*/
function updateFingerData(evt) {
var id = evt.identifier!==undefined ? evt.identifier : 0;
var f = getFingerData( id );
f.end.x = evt.pageX||evt.clientX;
f.end.y = evt.pageY||evt.clientY;
return f;
}
/**
* Returns a finger data object by its event ID.
* Each touch event has an identifier property, which is used
* to track repeat touches
* @param {int} id The unique id of the finger in the sequence of touch events.
* @return a finger data object.
* @inner
*/
function getFingerData( id ) {
for(var i=0; i<fingerData.length; i++) {
if(fingerData[i].identifier == id) {
return fingerData[i];
}
}
}
/**
* Creats all the finger onjects and returns an array of finger data
* @return Array of finger objects
* @inner
*/
function createAllFingerData() {
var fingerData=[];
for (var i=0; i<=5; i++) {
fingerData.push({
start:{ x: 0, y: 0 },
end:{ x: 0, y: 0 },
identifier:0
});
}
return fingerData;
}
/**
* Sets the maximum distance swiped in the given direction.
* If the new value is lower than the current value, the max value is not changed.
* @param {string} direction The direction of the swipe
* @param {int} distance The distance of the swipe
* @inner
*/
function setMaxDistance(direction, distance) {
distance = Math.max(distance, getMaxDistance(direction) );
maximumsMap[direction].distance = distance;
}
/**
* gets the maximum distance swiped in the given direction.
* @param {string} direction The direction of the swipe
* @return int The distance of the swipe
* @inner
*/
function getMaxDistance(direction) {
if (maximumsMap[direction]) return maximumsMap[direction].distance;
return undefined;
}
/**
* Creats a map of directions to maximum swiped values.
* @return Object A dictionary of maximum values, indexed by direction.
* @inner
*/
function createMaximumsData() {
var maxData={};
maxData[LEFT]=createMaximumVO(LEFT);
maxData[RIGHT]=createMaximumVO(RIGHT);
maxData[UP]=createMaximumVO(UP);
maxData[DOWN]=createMaximumVO(DOWN);
return maxData;
}
/**
* Creates a map maximum swiped values for a given swipe direction
* @param {string} The direction that these values will be associated with
* @return Object Maximum values
* @inner
*/
function createMaximumVO(dir) {
return {
direction:dir,
distance:0
}
}
//
// MATHS / UTILS
//
/**
* Calculate the duration of the swipe
* @return int
* @inner
*/
function calculateDuration() {
return endTime - startTime;
}
/**
* Calculate the distance between 2 touches (pinch)
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int;
* @inner
*/
function calculateTouchesDistance(startPoint, endPoint) {
var diffX = Math.abs(startPoint.x - endPoint.x);
var diffY = Math.abs(startPoint.y - endPoint.y);
return Math.round(Math.sqrt(diffX*diffX+diffY*diffY));
}
/**
* Calculate the zoom factor between the start and end distances
* @param {int} startDistance Distance (between 2 fingers) the user started pinching at
* @param {int} endDistance Distance (between 2 fingers) the user ended pinching at
* @return float The zoom value from 0 to 1.
* @inner
*/
function calculatePinchZoom(startDistance, endDistance) {
var percent = (endDistance/startDistance) * 1;
return percent.toFixed(2);
}
/**
* Returns the pinch direction, either IN or OUT for the given points
* @return string Either {@link $.fn.swipe.directions.IN} or {@link $.fn.swipe.directions.OUT}
* @see $.fn.swipe.directions
* @inner
*/
function calculatePinchDirection() {
if(pinchZoom<1) {
return OUT;
}
else {
return IN;
}
}
/**
* Calculate the length / distance of the swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int
* @inner
*/
function calculateDistance(startPoint, endPoint) {
return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2)));
}
/**
* Calculate the angle of the swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int
* @inner
*/
function calculateAngle(startPoint, endPoint) {
var x = startPoint.x - endPoint.x;
var y = endPoint.y - startPoint.y;
var r = Math.atan2(y, x); //radians
var angle = Math.round(r * 180 / Math.PI); //degrees
//ensure value is positive
if (angle < 0) {
angle = 360 - Math.abs(angle);
}
return angle;
}
/**
* Calculate the direction of the swipe
* This will also call calculateAngle to get the latest angle of swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return string Either {@link $.fn.swipe.directions.LEFT} / {@link $.fn.swipe.directions.RIGHT} / {@link $.fn.swipe.directions.DOWN} / {@link $.fn.swipe.directions.UP}
* @see $.fn.swipe.directions
* @inner
*/
function calculateDirection(startPoint, endPoint ) {
var angle = calculateAngle(startPoint, endPoint);
if ((angle <= 45) && (angle >= 0)) {
return LEFT;
} else if ((angle <= 360) && (angle >= 315)) {
return LEFT;
} else if ((angle >= 135) && (angle <= 225)) {
return RIGHT;
} else if ((angle > 45) && (angle < 135)) {
return DOWN;
} else {
return UP;
}
}
/**
* Returns a MS time stamp of the current time
* @return int
* @inner
*/
function getTimeStamp() {
var now = new Date();
return now.getTime();
}
/**
* Returns a bounds object with left, right, top and bottom properties for the element specified.
* @param {DomNode} The DOM node to get the bounds for.
*/
function getbounds( el ) {
el = $(el);
var offset = el.offset();
var bounds = {
left:offset.left,
right:offset.left+el.outerWidth(),
top:offset.top,
bottom:offset.top+el.outerHeight()
};
return bounds;
}
/**
* Checks if the point object is in the bounds object.
* @param {object} point A point object.
* @param {int} point.x The x value of the point.
* @param {int} point.y The x value of the point.
* @param {object} bounds The bounds object to test
* @param {int} bounds.left The leftmost value
* @param {int} bounds.right The righttmost value
* @param {int} bounds.top The topmost value
* @param {int} bounds.bottom The bottommost value
*/
function isInBounds(point, bounds) {
return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom);
};
}
/**
* A catch all handler that is triggered for all swipe directions.
* @name $.fn.swipe#swipe
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "left" swipes.
* @name $.fn.swipe#swipeLeft
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "right" swipes.
* @name $.fn.swipe#swipeRight
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "up" swipes.
* @name $.fn.swipe#swipeUp
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "down" swipes.
* @name $.fn.swipe#swipeDown
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for every phase of the swipe. This handler is constantly fired for the duration of the pinch.
* This is triggered regardless of swipe thresholds.
* @name $.fn.swipe#swipeStatus
* @event
* @default null
* @param {EventObject} event The original event object
* @param {string} phase The phase of the swipe event. See {@link $.fn.swipe.phases}
* @param {string} direction The direction the user swiped in. This is null if the user has yet to move. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped. This is 0 if the user has yet to move.
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for pinch in events.
* @name $.fn.swipe#pinchIn
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for pinch out events.
* @name $.fn.swipe#pinchOut
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for all pinch events. This handler is constantly fired for the duration of the pinch. This is triggered regardless of thresholds.
* @name $.fn.swipe#pinchStatus
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A click handler triggered when a user simply clicks, rather than swipes on an element.
* This is deprecated since version 1.6.2, any assignment to click will be assigned to the tap handler.
* You cannot use <code>on</code> to bind to this event as the default jQ <code>click</code> event will be triggered.
* Use the <code>tap</code> event instead.
* @name $.fn.swipe#click
* @event
* @deprecated since version 1.6.2, please use {@link $.fn.swipe#tap} instead
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A click / tap handler triggered when a user simply clicks or taps, rather than swipes on an element.
* @name $.fn.swipe#tap
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A double tap handler triggered when a user double clicks or taps on an element.
* You can set the time delay for a double tap with the {@link $.fn.swipe.defaults#doubleTapThreshold} property.
* Note: If you set both <code>doubleTap</code> and <code>tap</code> handlers, the <code>tap</code> event will be delayed by the <code>doubleTapThreshold</code>
* as the script needs to check if its a double tap.
* @name $.fn.swipe#doubleTap
* @see $.fn.swipe.defaults#doubleTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A long tap handler triggered once a tap has been release if the tap was longer than the longTapThreshold.
* You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
* @name $.fn.swipe#longTap
* @see $.fn.swipe.defaults#longTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A hold tap handler triggered as soon as the longTapThreshold is reached
* You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
* @name $.fn.swipe#hold
* @see $.fn.swipe.defaults#longTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
}));
|
{
"content_hash": "b0fced137237fd0f7428295d158155f2",
"timestamp": "",
"source": "github",
"line_count": 1953,
"max_line_length": 254,
"avg_line_length": 33.19815668202765,
"alnum_prop": 0.665633290147449,
"repo_name": "kenorvick/kenorvick",
"id": "dcdca9cafdd501f391438bb87bdcdae3dce8cf32",
"size": "65210",
"binary": false,
"copies": "35",
"ref": "refs/heads/master",
"path": "clients/shfm/wp-content/themes/Avada/assets/js/jquery.touchSwipe.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "877"
},
{
"name": "CSS",
"bytes": "4341509"
},
{
"name": "HTML",
"bytes": "126162"
},
{
"name": "JavaScript",
"bytes": "6620032"
},
{
"name": "PHP",
"bytes": "17279155"
},
{
"name": "Ruby",
"bytes": "927"
},
{
"name": "Shell",
"bytes": "2684"
}
],
"symlink_target": ""
}
|
package level_10;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* --- Day 10: Balance Bots ---
* <p>
* You come upon a factory in which many robots are zooming around handing small microchips to each other.
* <p>
* Upon closer examination, you notice that each bot only proceeds when it has two microchips, and once it does, it gives each one to a different bot or puts it in a marked "output" bin. Sometimes, bots take microchips from "input" bins, too.
* <p>
* Inspecting one of the microchips, it seems like they each contain a single number; the bots must use some logic to decide what to do with each chip. You access the local control computer and download the bots' instructions (your puzzle input).
* <p>
* Some of the instructions specify that a specific-valued microchip should be given to a specific bot; the rest of the instructions indicate what a given bot should do with its lower-value or higher-value chip.
* <p>
* For example, consider the following instructions:
* <p>
* value 5 goes to bot 2
* bot 2 gives low to bot 1 and high to bot 0
* value 3 goes to bot 1
* bot 1 gives low to output 1 and high to bot 0
* bot 0 gives low to output 2 and high to output 0
* value 2 goes to bot 2
* <p>
* Initially, bot 1 starts with a value-3 chip, and bot 2 starts with a value-2 chip and a value-5 chip.
* Because bot 2 has two microchips, it gives its lower one (2) to bot 1 and its higher one (5) to bot 0.
* Then, bot 1 has two microchips; it puts the value-2 chip in output 1 and gives the value-3 chip to bot 0.
* Finally, bot 0 has two microchips; it puts the 3 in output 2 and the 5 in output 0.
* <p>
* In the end, output bin 0 contains a value-5 microchip, output bin 1 contains a value-2 microchip, and output bin 2 contains a value-3 microchip. In this configuration, bot number 2 is responsible for comparing value-5 microchips with value-2 microchips.
* <p>
* Based on your instructions, what is the number of the bot that is responsible for comparing value-61 microchips with value-17 microchips?
* <p>
* <p>
* --- Part Two ---
* <p>
* What do you get if you multiply together the values of one chip in each of outputs 0, 1, and 2?
*/
public class Level10 {
private static HashMap<Integer, ChipReceiver> receivers;
public static void main(String[] args) throws IOException {
List<String> content = Files.readAllLines(Paths.get("level_10/in1.txt"));
Pattern botToSomethingPattern = Pattern.compile("^bot ([0-9]+) gives low to (bot|output) ([0-9]+) and high to (bot|output) ([0-9]+)$");
Pattern inToBotPattern = Pattern.compile("^value ([0-9]+) goes to bot ([0-9]+)$");
receivers = new HashMap<>();
// process only bot connections first
for (String line : content) {
Matcher botToSomethingMatcher = botToSomethingPattern.matcher(line);
if (botToSomethingMatcher.matches()) {
Integer botId = Integer.parseInt(botToSomethingMatcher.group(1));
Integer lowId = Integer.parseInt(botToSomethingMatcher.group(3));
Integer hiId = Integer.parseInt(botToSomethingMatcher.group(5));
String lowEntity = botToSomethingMatcher.group(2);
String hiEntity = botToSomethingMatcher.group(4);
if ("output".equals(lowEntity)) {
lowId = (lowId * -1) - 1;
}
if ("output".equals(hiEntity))
hiId = (hiId * -1) - 1;
ChipReceiver currentBot = getOrCreateReceiver(botId);
currentBot.setLowReceiver(getOrCreateReceiver(lowId));
currentBot.setHiReceiver(getOrCreateReceiver(hiId));
}
}
// process only inputs
for (String line : content) {
Matcher inToBotMatcher = inToBotPattern.matcher(line);
if (inToBotMatcher.matches()) {
Integer chipId = Integer.parseInt(inToBotMatcher.group(1));
Integer botId = Integer.parseInt(inToBotMatcher.group(2));
getOrCreateReceiver(botId).take(chipId);
}
}
int result2 = getOrCreateReceiver(-1).data.get(0) * getOrCreateReceiver(-2).data.get(0) * getOrCreateReceiver(-3).data.get(0);
System.out.println("result 2: " + result2);
}
/**
* Thing that accepts chips - either bot or output.
* Outputs get negative indices minus 1 (output 0 = -1, -1 = -2 etc).
* Bots get links to two neighbours.
* After getting both inputs, bot sorts them and passes further.
* Output has both neighbours = null and only one value in data.
*/
private static ChipReceiver getOrCreateReceiver(Integer receiverId) {
ChipReceiver newborn = new ChipReceiver(receiverId);
if (receivers.containsKey(receiverId))
return receivers.get(receiverId);
receivers.put(receiverId, newborn);
return newborn;
}
private static class ChipReceiver {
private ChipReceiver low = null;
private ChipReceiver hi = null;
List<Integer> data;
Integer id = null;
ChipReceiver(Integer id) {
this.id = id;
data = new ArrayList<>();
}
void take(Integer chip) {
data.add(chip);
if (data.size() == 2) {
Collections.sort(data);
// part 1 condition
if (data.get(0).equals(17) && data.get(1).equals(61)) {
System.out.println("result 1: " + this.id);
}
if (low != null && hi != null) {
low.take(data.get(0));
hi.take(data.get(1));
} else {
System.out.println("bot " + this.id + " is stuck");
}
}
}
void setHiReceiver(ChipReceiver hi) {
this.hi = hi;
}
void setLowReceiver(ChipReceiver low) {
this.low = low;
}
}
}
|
{
"content_hash": "62342ffd651ab77f2ca95d2387173478",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 256,
"avg_line_length": 38.42758620689655,
"alnum_prop": 0.7011844938980617,
"repo_name": "hermes-jr/adventofcode2016-in-java",
"id": "39d371c255f8064e51cb5e2802084e5081ef6cd8",
"size": "5572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "level_10/Level10.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "153813"
}
],
"symlink_target": ""
}
|
/* This is a managed file. Do not delete this comment. */
#include <include/test.h>
void test_Attributes_tc_isDefaultPersistent(
test_Attributes this)
{
corto_int32__create_auto(NULL, i, 10);
test_assert(i != NULL);
test_assert(!corto_check_attr(i, CORTO_ATTR_PERSISTENT));
corto_delete(i);
}
void test_Attributes_tc_isDefaultScopedPersistent(
test_Attributes this)
{
corto_int32__create_auto(root_o, i, 10);
test_assert(i != NULL);
test_assert(corto_check_attr(i, CORTO_ATTR_PERSISTENT));
corto_delete(i);
}
void test_Attributes_tc_testDefaultSet(
test_Attributes this)
{
test_assertint(corto_get_attr(), CORTO_ATTR_DEFAULT);
}
void test_Attributes_tc_testTargetAttr(
test_Attributes this)
{
corto_object o = corto_create(root_o, "a", test_TargetActual_o);
test_assert(o != NULL);
test_assert(corto_typeof(o) == corto_type(test_TargetActual_o));
test_assert(corto_check_attr(o, CORTO_ATTR_PERSISTENT));
test_assert(corto_delete(o) == 0);
}
void test_Attributes_tc_testTargetOrphanAttr(
test_Attributes this)
{
test_TargetActualMember* o = corto_create(root_o, "a", test_TargetActualMember_o);
test_assert(o != NULL);
test_assert(corto_typeof(o) == corto_type(test_TargetActualMember_o));
test_assert(corto_check_attr(o, CORTO_ATTR_PERSISTENT));
test_assert(!corto_check_attr(o->m, CORTO_ATTR_PERSISTENT));
test_assert(corto_delete(o) == 0);
}
void test_Attributes_tc_typeOverridesAttributes(
test_Attributes this)
{
corto_object o = corto_create(NULL, NULL, test_TypeAttr_o);
test_assert(o != NULL);
test_assertint(corto_attrof(o), CORTO_ATTR_OBSERVABLE);
test_assert(corto_delete(o) == 0);
}
|
{
"content_hash": "c2835c020924072665f437055553d9e7",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 86,
"avg_line_length": 25.470588235294116,
"alnum_prop": 0.684757505773672,
"repo_name": "cortoproject/corto",
"id": "09f707ae2625fecc42e52f88507106b4c2a69cdc",
"size": "1732",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/store/src/Attributes.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3170894"
},
{
"name": "C++",
"bytes": "106700"
}
],
"symlink_target": ""
}
|
var fnToString = (fn) => Function.prototype.toString.call(fn);
var objStringValue = fnToString(Object);
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
export default function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function'
&& constructor instanceof constructor
&& fnToString(constructor) === objStringValue;
}
|
{
"content_hash": "7c16633245b088f7005cb8822130788c",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 100,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.6822289156626506,
"repo_name": "andreieftimie/redux",
"id": "4a37a2aa2c45e0c4ff157662e98ccd359d2af12d",
"size": "664",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/utils/isPlainObject.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "41390"
}
],
"symlink_target": ""
}
|
namespace ORM
{
class UpdateBase : public QueryBase
{
public:
UpdateBase(Queryable& db, const Table& table)
:QueryBase(db, "UPDATE " + table.GetTableName())
{
}
~UpdateBase()
{
}
UpdateBase* Set(const FieldBase& field, const Gtk::TreeIter& row)
{
m_Query += " SET " + field.GetSmallFieldName() + "=" + field.GetStrValue(row);
return this;
}
template<class T> UpdateBase* Set(const Field<T>& field, const T& value)
{
m_Query += " SET " + field.GetSmallFieldName() + "=" + Field<T>::ToString(value);
return this;
}
void Where(const WhereBase& where)
{
m_Query += " WHERE " + where.GetQuery();
}
private:
};
}
#endif
|
{
"content_hash": "1343af039782a549874c36d82828efcb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 84,
"avg_line_length": 19.735294117647058,
"alnum_prop": 0.6214605067064084,
"repo_name": "olegshtch/gtable",
"id": "fab39267562702670d85176cbb8395059873c6fc",
"size": "757",
"binary": false,
"copies": "1",
"ref": "refs/heads/orm-data",
"path": "src/orm/update.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7067"
},
{
"name": "C++",
"bytes": "517390"
},
{
"name": "Objective-C",
"bytes": "4456"
},
{
"name": "Shell",
"bytes": "1595"
}
],
"symlink_target": ""
}
|
import json
import sys
import cherrypy
import splunk
import splunk.appserver.mrsparkle.controllers as controllers
from splunk.appserver.mrsparkle.lib.decorators import expose_page
# JIRA: Must use private API (splunkweb controllers) for server-side
# endpoint due to lack of public API. (SPL-90798)
class SetupService(controllers.BaseController):
@expose_page(must_login=True, methods=['GET'])
def is_unix(self, **kwargs):
"""
Returns whether current OS is a recognized Unix.
"""
is_recognized_unix = not sys.platform.startswith('win')
cherrypy.response.headers['Content-Type'] = 'text/json'
return json.dumps(is_recognized_unix)
|
{
"content_hash": "9d93db4190e63a25d60de793ee7ffede",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 68,
"avg_line_length": 32.40909090909091,
"alnum_prop": 0.6956521739130435,
"repo_name": "excessivedemon/puppet-splunk",
"id": "1e25d55a4c5b217391741e41c300a2e65c099343",
"size": "713",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "files/ta/Splunk_TA_nix/appserver/controllers/setup.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "884"
},
{
"name": "HTML",
"bytes": "31033"
},
{
"name": "JavaScript",
"bytes": "9996"
},
{
"name": "Makefile",
"bytes": "464"
},
{
"name": "Nix",
"bytes": "502927"
},
{
"name": "Pascal",
"bytes": "24"
},
{
"name": "PostScript",
"bytes": "623"
},
{
"name": "Puppet",
"bytes": "34437"
},
{
"name": "Python",
"bytes": "7172"
},
{
"name": "Ruby",
"bytes": "13767"
},
{
"name": "Shell",
"bytes": "162270"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="BCKTheme" parent="@android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:background">@android:color/background_light</item>
<item name="android:logo">@android:color/transparent</item>
</style>
<!-- ActionBar styles -->
<style name="MyActionBar"
parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
<item name="android:background">@android:color/background_light</item>
<item name="android:titleTextStyle">@style/MyActionBarTitleText</item>
</style>
<!-- ActionBar title text -->
<style name="MyActionBarTitleText">
<item name="android:textColor">@android:color/background_light</item>
</style>
</resources>
|
{
"content_hash": "150ab85200f25b1482406cafcabc5a8e",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 78,
"avg_line_length": 39.17391304347826,
"alnum_prop": 0.6714761376248612,
"repo_name": "BarCodeKey/BarCodeKey",
"id": "95ca37d65ba0764dcc81c5851fa8a3e917e18317",
"size": "901",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/themes.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "115341"
}
],
"symlink_target": ""
}
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Public Class SymbolDescriptionServiceTests
Private Async Function TestAsync(languageServiceProvider As HostLanguageServices, workspace As TestWorkspace, expectedDescription As String) As Task
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorPosition = cursorDocument.CursorPosition.Value
Dim cursorBuffer = cursorDocument.TextBuffer
Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)
' using GetTouchingWord instead of FindToken allows us to test scenarios where cursor is at the end of token (E.g: Foo$$)
Dim commonSyntaxToken = (Await document.GetSyntaxTreeAsync()).GetTouchingWord(cursorPosition, languageServiceProvider.GetService(Of ISyntaxFactsService), Nothing)
' For String Literals GetTouchingWord returns Nothing, we still need this for Quick Info. Quick Info code does exactly the following.
' caveat: The comment above the previous line of code. Do not put the cursor at the end of the token.
If commonSyntaxToken = Nothing Then
commonSyntaxToken = (Await document.GetSyntaxRootAsync()).FindToken(cursorPosition)
End If
Dim semanticModel = Await document.GetSemanticModelAsync()
Dim symbol = semanticModel.GetSymbols(commonSyntaxToken, document.Project.Solution.Workspace, bindLiteralsToUnderlyingType:=True, cancellationToken:=CancellationToken.None).AsImmutable()
Dim symbolDescriptionService = languageServiceProvider.GetService(Of ISymbolDisplayService)()
Dim actualDescription = Await symbolDescriptionService.ToDescriptionStringAsync(workspace, semanticModel, cursorPosition, symbol)
Assert.Equal(expectedDescription, actualDescription)
End Function
Private Function StringFromLines(ParamArray lines As String()) As String
Return String.Join(Environment.NewLine, lines)
End Function
Private Async Function TestCSharpAsync(workspaceDefinition As XElement, expectedDescription As String) As Tasks.Task
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceDefinition)
Await TestAsync(GetLanguageServiceProvider(workspace, LanguageNames.CSharp), workspace, expectedDescription)
End Using
End Function
Private Async Function TestBasicAsync(workspaceDefinition As XElement, expectedDescription As String) As Tasks.Task
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceDefinition)
Await TestAsync(GetLanguageServiceProvider(workspace, LanguageNames.VisualBasic), workspace, expectedDescription)
End Using
End Function
Private Function GetLanguageServiceProvider(workspace As TestWorkspace, language As String) As HostLanguageServices
Return workspace.Services.GetLanguageServices(language)
End Function
Private Function WrapCodeInWorkspace(ParamArray lines As String()) As XElement
Dim part1 = "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document>"
Dim part2 = "</Document></Project></Workspace>"
Dim code = StringFromLines(lines)
Dim workspace = String.Concat(part1, code, part2)
WrapCodeInWorkspace = XElement.Parse(workspace)
End Function
#Region "CSharp SymbolDescription Tests"
<Fact>
Public Async Function TestCSharpDynamic() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo { void M() { dyn$$amic d; } }
</Document>
</Project>
</Workspace>
Await TestCSharpAsync(workspace,
StringFromLines("dynamic",
FeaturesResources.RepresentsAnObjectWhoseOperations))
End Function
<WorkItem(543912)>
<Fact>
Public Async Function TestCSharpLocalConstant() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
void Method()
{
const int $$x = 2
}
}
</Document>
</Project>
</Workspace>
Await TestCSharpAsync(workspace, $"({FeaturesResources.LocalConstant}) int x = 2")
End Function
#End Region
#Region "Basic SymbolDescription Tests"
<Fact>
Public Async Function TestNamedTypeKindClass() As Task
Dim workspace = WrapCodeInWorkspace("class Program",
"Dim p as Prog$$ram",
"End class")
Await TestBasicAsync(workspace, "Class Program")
End Function
''' <summary>
''' Design Change from Dev10. Notice that we now show the type information for T
''' C# / VB Quick Info consistency
''' </summary>
''' <remarks></remarks>
<Fact>
Public Async Function TestGenericClass() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class Program
Dim p as New System.Collections.Generic.Lis$$t(Of String)
End class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace,
StringFromLines("Sub List(Of String).New()"))
End Function
<Fact>
Public Async Function TestGenericClassFromSource() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace TestNamespace
Public Class Outer(Of T)
End Class
Module Test
Dim x As New O$$uter(Of Integer)
End Module
End Namespace
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace,
StringFromLines("Sub Outer(Of Integer).New()"))
End Function
<Fact>
Public Async Function TestClassNestedWithinAGenericClass() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Outer(Of T)
Public Class Inner
Public Sub F(x As T)
End Sub
End Class
End Class
Module Test
Sub Main()
Dim x As New Outer(Of Integer).In$$ner()
x.F(4)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace,
StringFromLines("Sub Outer(Of Integer).Inner.New()"))
End Function
<Fact>
Public Async Function TestTypeParameter() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Foo(Of T)
Dim x as T$$
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"T {FeaturesResources.In} Foo(Of T)")
End Function
<Fact>
Public Async Function TestTypeParameterFromNestedClass() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Outer(Of T)
Public Class Inner
Public Sub F(x As T$$)
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"T {FeaturesResources.In} Outer(Of T)")
End Function
<Fact>
Public Async Function TestShadowedTypeParameter() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Outer(Of T)
Public Class Inner
Public Sub F(x As T$$)
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"T {FeaturesResources.In} Outer(Of T)")
End Function
<Fact>
Public Async Function TestNullableOfInt() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Public Class Foo
Dim x as Nullab$$le(Of Integer)
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace,
StringFromLines("Structure System.Nullable(Of T As Structure)",
String.Empty,
$"T {FeaturesResources.Is} Integer"))
End Function
<Fact>
Public Async Function TestDictionaryOfIntAndString() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Collections.Generic
class Program
Dim p as New Dictio$$nary(Of Integer, String)
End class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace,
StringFromLines("Sub Dictionary(Of Integer, String).New()"))
End Function
<Fact>
Public Async Function TestNamedTypeKindStructure() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Structure Program
Dim p as Prog$$ram
End Structure
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Structure Program")
End Function
<Fact>
Public Async Function TestNamedTypeKindStructureBuiltIn() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class Program
Dim p as Int$$eger
End class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Structure System.Int32")
End Function
<Fact>
Public Async Function TestNamedTypeKindEnum() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Enum Program
End Enum
Module M1
Sub Main(args As String())
Dim p as Prog$$ram
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Enum Program")
End Function
<Fact>
Public Async Function TestNamedTypeKindDelegate() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Delegate Sub DelegateType()
Module M1
Event AnEvent As Delega$$teType
Sub Main(args As String())
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Delegate Sub DelegateType()")
End Function
<Fact>
Public Async Function TestNamedTypeKindInterface() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface Foo
End Interface
Module M1
Sub Main(args As String())
Dim p as Foo$$
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Interface Foo")
End Function
<Fact>
Public Async Function TestNamedTypeKindModule() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
sub Method()
$$M1.M()
End sub
End Class
Module M1
public sub M()
End sub
End Module
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Module M1")
End Function
<Fact>
Public Async Function TestNamespace() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
sub Method()
Sys$$tem.Console.Write(5)
End sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Namespace System")
End Function
<Fact>
Public Async Function TestNamespace2() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Collections.Gene$$ric
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Namespace System.Collections.Generic")
End Function
<Fact>
Public Async Function TestField() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
private field as Integer
sub Method()
fie$$ld = 5
End sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"({FeaturesResources.Field}) Foo.field As Integer")
End Function
<Fact>
Public Async Function TestLocal() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
sub Method()
Dim x as String
x$$ = "Hello"
End sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"({FeaturesResources.LocalVariable}) x As String")
End Function
<Fact>
Public Async Function TestStringLiteral() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
Dim x As String = "Hel$$lo"
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Class System.String")
End Function
<Fact>
Public Async Function TestIntegerLiteral() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
Dim x = 4$$2
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Structure System.Int32")
End Function
<Fact>
Public Async Function TestDateLiteral() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
Dim d As Date
d = #8/23/1970 $$3:45:39 AM#
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Structure System.DateTime")
End Function
''' Design change from Dev10
<Fact>
Public Async Function TestNothingLiteral() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
Dim x = Nothin$$g
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "")
End Function
<Fact>
Public Async Function TestTrueKeyword() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
Dim x = Tr$$ue
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Structure System.Boolean")
End Function
<WorkItem(538732)>
<Fact>
Public Async Function TestMethod() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
Fu$$n()
End Sub
Function Fun() As Integer
Return 1
End Function
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Function Foo.Fun() As Integer")
End Function
''' <summary>
''' This is a design change from Dev10. Notice that modifiers "public shared sub" are absent.
''' VB / C# Quick Info Consistency
''' </summary>
''' <remarks></remarks>
<WorkItem(538732)>
<Fact>
Public Async Function TestPEMethod() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
System.Console.Writ$$e(5)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub Console.Write(value As Integer)")
End Function
''' <summary>
''' This is a design change from Dev10. Showing what we already know is kinda useless.
''' This is what C# does. We are modifying VB to follow this model.
''' </summary>
''' <remarks></remarks>
<Fact>
Public Async Function TestFormalParameter() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method()
End Sub
Function Fun(x$$ As String) As Integer
Return 1
End Function
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"({FeaturesResources.Parameter}) x As String")
End Function
<Fact>
Public Async Function TestOptionalParameter() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Method(x As Short, Optional y As Integer = 10)
End Sub
Sub Test
Met$$hod(1, 2)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub Foo.Method(x As Short, [y As Integer = 10])")
End Function
<Fact>
Public Async Function TestOverloadedMethod() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Overloads Sub Method(x As Integer)
End Sub
Overloads Sub Method(x As String)
End Sub
Sub Test()
Meth$$od("str")
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub Foo.Method(x As String)")
End Function
<Fact>
Public Async Function TestOverloadedMethods() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Overloads Sub Method(x As Integer)
End Sub
Overloads Sub Method(x As String)
End Sub
Overloads Sub Method(x As Double)
End Sub
Sub Test()
Meth$$od("str")
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub Foo.Method(x As String)")
End Function
<WorkItem(527639)>
<Fact>
Public Async Function TestInterfaceConstraintOnClass() As Task
Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic",
"Class CC(Of T$$ As IEnumerable(Of Integer))",
"End Class")
Dim expectedDescription = $"T {FeaturesResources.In} CC(Of T As IEnumerable(Of Integer))"
Await TestBasicAsync(workspace, expectedDescription)
End Function
<WorkItem(527639)>
<Fact>
Public Async Function TestInterfaceConstraintOnInterface() As Task
Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic",
"Interface IMyInterface(Of T$$ As IEnumerable(Of Integer))",
"End Interface")
Dim expectedDescription = $"T {FeaturesResources.In} IMyInterface(Of T As IEnumerable(Of Integer))"
Await TestBasicAsync(workspace, expectedDescription)
End Function
<WorkItem(527639)>
<Fact>
Public Async Function TestReferenceTypeConstraintOnClass() As Task
Dim workspace = WrapCodeInWorkspace("Class CC(Of T$$ As Class)",
"End Class")
Dim expectedDescription = $"T {FeaturesResources.In} CC(Of T As Class)"
Await TestBasicAsync(workspace, expectedDescription)
End Function
<WorkItem(527639)>
<Fact>
Public Async Function TestValueTypeConstraintOnClass() As Task
Dim workspace = WrapCodeInWorkspace("Class CC(Of T$$ As Structure)",
"End Class")
Dim expectedDescription = $"T {FeaturesResources.In} CC(Of T As Structure)"
Await TestBasicAsync(workspace, expectedDescription)
End Function
<WorkItem(527639)>
<Fact>
Public Async Function TestValueTypeConstraintOnStructure() As Task
Dim workspace = WrapCodeInWorkspace("Structure S(Of T$$ As Class)",
"End Structure")
Dim expectedDescription = $"T {FeaturesResources.In} S(Of T As Class)"
Await TestBasicAsync(workspace, expectedDescription)
End Function
<WorkItem(527639)>
<Fact>
Public Async Function TestMultipleConstraintsOnClass() As Task
Dim workspace = WrapCodeInWorkspace("Public Class CC(Of T$$ As {IComparable, IDisposable, Class, New})",
"End Class")
Dim expectedDescription = $"T {FeaturesResources.In} CC(Of T As {{Class, IComparable, IDisposable, New}})"
Await TestBasicAsync(workspace, expectedDescription)
End Function
''' TO DO: Add test for Ref Arg
<Fact>
Public Async Function TestOutArguments() As Task
Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic",
"Class CC(Of T As IEnum$$erable(Of Integer))",
"End Class")
Dim expectedDescription = StringFromLines("Interface System.Collections.Generic.IEnumerable(Of Out T)",
String.Empty,
$"T {FeaturesResources.Is} Integer")
Await TestBasicAsync(workspace, expectedDescription)
End Function
<WorkItem(527655)>
<Fact>
Public Async Function TestMinimalDisplayName() As Task
Dim workspace = WrapCodeInWorkspace("Imports System",
"Imports System.Collections.Generic",
"Class CC(Of T As IEnu$$merable(Of IEnumerable(of Int32)))",
"End Class")
Dim expectedDescription = StringFromLines("Interface System.Collections.Generic.IEnumerable(Of Out T)",
String.Empty,
$"T {FeaturesResources.Is} IEnumerable(Of Integer)")
Await TestBasicAsync(workspace, expectedDescription)
End Function
<Fact>
Public Async Function TestOverridableMethod() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public Overridable Sub G()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub G()
End Sub
End Class
Class C
Sub Test()
Dim x As A
x = new A()
x.G$$()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub A.G()")
End Function
<Fact>
Public Async Function TestOverriddenMethod2() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public Overridable Sub G()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub G()
End Sub
End Class
Class C
Sub Test()
Dim x As A
x = new B()
x.G$$()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub A.G()")
End Function
<Fact>
Public Async Function TestGenericMethod() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Outer(Of T)
Public Class Inner
Public Sub F(x As T)
End Sub
End Class
End Class
Module Test
Sub Main()
Dim x As New Outer(Of Integer).Inner()
x.F$$(4)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Sub Outer(Of Integer).Inner.F(x As Integer)")
End Function
<Fact>
Public Async Function TestAutoImplementedProperty() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Collections.Generic
Class Foo
Public Property It$$ems As New List(Of String) From {"M", "T", "W"}
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, "Property Foo.Items As List(Of String)")
End Function
<WorkItem(538806)>
<Fact>
Public Async Function TestField1() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Dim x As Integer
Sub Method()
Dim y As Integer
$$x = y
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"({FeaturesResources.Field}) C.x As Integer")
End Function
<WorkItem(538806)>
<Fact>
Public Async Function TestProperty1() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Dim x As Integer
Sub Method()
Dim y As Integer
x = $$y
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"({FeaturesResources.LocalVariable}) y As Integer")
End Function
<WorkItem(543911)>
<Fact>
Public Async Function TestVBLocalConstant() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
sub Method()
Const $$b = 2
End sub
End Class
</Document>
</Project>
</Workspace>
Await TestBasicAsync(workspace, $"({FeaturesResources.LocalConstant}) b As Integer = 2")
End Function
#End Region
End Class
End Namespace
|
{
"content_hash": "a9d80ddd689171d36e776896d72216c4",
"timestamp": "",
"source": "github",
"line_count": 926,
"max_line_length": 198,
"avg_line_length": 33.12419006479482,
"alnum_prop": 0.5501255175561569,
"repo_name": "HellBrick/roslyn",
"id": "68e27dbded4bc4e9ccdc92b5ff29c324bfa68eb3",
"size": "30673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/EditorFeatures/Test2/Workspaces/SymbolDescriptionServiceTests.vb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "18635"
},
{
"name": "C#",
"bytes": "74423805"
},
{
"name": "C++",
"bytes": "6311"
},
{
"name": "F#",
"bytes": "421"
},
{
"name": "Groovy",
"bytes": "6673"
},
{
"name": "Makefile",
"bytes": "2958"
},
{
"name": "PowerShell",
"bytes": "29636"
},
{
"name": "Shell",
"bytes": "5659"
},
{
"name": "Visual Basic",
"bytes": "59843519"
}
],
"symlink_target": ""
}
|
package com.brightgenerous.csv.delegate;
//@formatter:off
/*
* origin file
* groupId: net.sf.opencsv
* artifactId: opencsv
* version: 2.3
* au.com.bytecode.opencsv.CSVReader
*
* edit
* - package au.com.bytecode.opencsv;
* + //package au.com.bytecode.opencsv;
*
* - public class CSVReader implements Closeable {
* + //public class CSVReader implements Closeable {
* + class CSVReader implements Closeable {
*/
/*
* 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.
*/
//package au.com.bytecode.opencsv;
/**
Copyright 2005 Bytecode Pty Ltd.
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.
*/
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* A very simple CSV reader released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
//public class CSVReader implements Closeable {
class CSVReader implements Closeable {
private BufferedReader br;
private boolean hasNext = true;
private CSVParser parser;
private int skipLines;
private boolean linesSkiped;
/**
* The default line to start reading.
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Constructs CSVReader using a comma for the separator.
*
* @param reader
* the reader to an underlying CSV source.
*/
public CSVReader(Reader reader) {
this(reader, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVReader(Reader reader, char separator) {
this(reader, separator, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVReader(Reader reader, char separator, char quotechar) {
this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator, quote char and quote handling
* behavior.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param strictQuotes
* sets if characters outside the quotes are ignored
*/
public CSVReader(Reader reader, char separator, char quotechar, boolean strictQuotes) {
this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES, strictQuotes);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
*/
public CSVReader(Reader reader, char separator,
char quotechar, char escape) {
this(reader, separator, quotechar, escape, DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, line, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line) {
this(reader, separator, quotechar, escape, line, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
* @param strictQuotes
* sets if characters outside the quotes are ignored
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes) {
this(reader, separator, quotechar, escape, line, strictQuotes, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
* @param strictQuotes
* sets if characters outside the quotes are ignored
* @param ignoreLeadingWhiteSpace
* it true, parser should ignore white space before a quote in a field
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes, boolean ignoreLeadingWhiteSpace) {
br = new BufferedReader(reader);
parser = new CSVParser(separator, quotechar, escape, strictQuotes, ignoreLeadingWhiteSpace);
skipLines = line;
}
/**
* Reads the entire file into a List with each element being a String[] of
* tokens.
*
* @return a List of String[], with each String[] representing a line of the
* file.
*
* @throws IOException
* if bad things happen during the read
*/
public List<String[]> readAll() throws IOException {
List<String[]> allElements = new ArrayList<String[]>();
while (hasNext) {
String[] nextLineAsTokens = readNext();
if (nextLineAsTokens != null) {
allElements.add(nextLineAsTokens);
}
}
return allElements;
}
/**
* Reads the next line from the buffer and converts to a string array.
*
* @return a string array with each comma-separated element as a separate
* entry.
*
* @throws IOException
* if bad things happen during the read
*/
public String[] readNext() throws IOException {
String[] result = null;
do {
String nextLine = getNextLine();
if (!hasNext) {
return result; // should throw if still pending?
}
String[] r = parser.parseLineMulti(nextLine);
if (r.length > 0) {
if (result == null) {
result = r;
} else {
String[] t = new String[result.length+r.length];
System.arraycopy(result, 0, t, 0, result.length);
System.arraycopy(r, 0, t, result.length, r.length);
result = t;
}
}
} while (parser.isPending());
return result;
}
/**
* Reads the next line from the file.
*
* @return the next line from the file without trailing newline
* @throws IOException
* if bad things happen during the read
*/
private String getNextLine() throws IOException {
if (!linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
/**
* Closes the underlying reader.
*
* @throws IOException if the close fails
*/
@Override
public void close() throws IOException{
br.close();
}
}
|
{
"content_hash": "5c7e5cc8d0b4a17395a9fcd8fbf0a30d",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 147,
"avg_line_length": 34.809968847352025,
"alnum_prop": 0.6039914086271703,
"repo_name": "brightgenerous/brigen-base",
"id": "637afda5265529e7e78031514a025a98c831da8e",
"size": "11174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/brightgenerous/csv/delegate/au$com$bytecode$opencsv$CSVReader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1634863"
},
{
"name": "Ruby",
"bytes": "958"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>jbatch</artifactId>
<groupId>javax.batch</groupId>
<version>1.0-b25.topicus1</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.ibm.jbatch</groupId>
<artifactId>com.ibm.jbatch-runtime-all</artifactId>
<version>1.0-b25.topicus1</version>
<build>
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createSourcesJar>true</createSourcesJar>
<artifactSet>
<excludes>
<exclude>javax.batch:javax.batch-api</exclude>
<exclude>javax.batch:javax.batch-annotation</exclude>
<exclude>com.ibm.jbatch:com.ibm.jbatch-ri-spi</exclude>
</excludes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.2</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<forceCreation>true</forceCreation>
<archive>
<manifestFile>META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>java.net-Public</id>
<name>Maven Java Net Snapshots and Releases</name>
<url>https://maven.java.net/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.ibm.jbatch</groupId>
<artifactId>com.ibm.jbatch-ri-spi</artifactId>
<version>1.0-b25.topicus1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.1-20121030</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>el-api</artifactId>
<groupId>javax.el</groupId>
</exclusion>
<exclusion>
<artifactId>jboss-interceptors-api_1.1_spec</artifactId>
<groupId>org.jboss.spec.javax.interceptor</groupId>
</exclusion>
<exclusion>
<artifactId>jsr250-api</artifactId>
<groupId>javax.annotation</groupId>
</exclusion>
<exclusion>
<artifactId>javax.inject</artifactId>
<groupId>javax.inject</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.0.0.Alpha3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.fabric3.api</groupId>
<artifactId>commonj</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
|
{
"content_hash": "8f9ae13db5f244f566a718a662fab140",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 201,
"avg_line_length": 33.15079365079365,
"alnum_prop": 0.5750538664113,
"repo_name": "papegaaij/jsr-352",
"id": "1910ac0ce032ade6b7b6fd9416c5166141fc7202",
"size": "4177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JSR352.Aggregation/runtime/dependency-reduced-pom.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1938555"
},
{
"name": "Perl",
"bytes": "6130"
},
{
"name": "Ruby",
"bytes": "722"
},
{
"name": "Shell",
"bytes": "641"
},
{
"name": "Standard ML",
"bytes": "53525"
}
],
"symlink_target": ""
}
|
package com.sequenceiq.cloudbreak.orchestrator.salt.domain;
public class Fingerprint {
private String fingerprint;
private String errorText;
private String address;
private int statusCode;
public String getFingerprint() {
return fingerprint;
}
public void setFingerprint(String fingerprint) {
this.fingerprint = fingerprint;
}
public String getErrorText() {
return errorText;
}
public void setErrorText(String errorText) {
this.errorText = errorText;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
}
|
{
"content_hash": "ed83b52dbc1cfe12b365478588489305",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 59,
"avg_line_length": 19.363636363636363,
"alnum_prop": 0.647887323943662,
"repo_name": "hortonworks/cloudbreak",
"id": "6d25a9f6174f0fcd75ec128b56a8db91e78b3429",
"size": "852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "orchestrator-salt/src/main/java/com/sequenceiq/cloudbreak/orchestrator/salt/domain/Fingerprint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7535"
},
{
"name": "Dockerfile",
"bytes": "9586"
},
{
"name": "Fluent",
"bytes": "10"
},
{
"name": "FreeMarker",
"bytes": "395982"
},
{
"name": "Groovy",
"bytes": "523"
},
{
"name": "HTML",
"bytes": "9917"
},
{
"name": "Java",
"bytes": "55250904"
},
{
"name": "JavaScript",
"bytes": "47923"
},
{
"name": "Jinja",
"bytes": "190660"
},
{
"name": "Makefile",
"bytes": "8537"
},
{
"name": "PLpgSQL",
"bytes": "1830"
},
{
"name": "Perl",
"bytes": "17726"
},
{
"name": "Python",
"bytes": "29898"
},
{
"name": "SaltStack",
"bytes": "222692"
},
{
"name": "Scala",
"bytes": "11168"
},
{
"name": "Shell",
"bytes": "416225"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.fhg.igd</groupId>
<artifactId>equinox-test</artifactId>
<version>1.2.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>de.fhg.igd</groupId>
<artifactId>de.fhg.igd.equinox.test.site</artifactId>
<version>1.2.0-SNAPSHOT</version>
<packaging>eclipse-repository</packaging>
</project>
|
{
"content_hash": "a2e876f93cc31ac838e1a82ba832d5d8",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 149,
"avg_line_length": 43,
"alnum_prop": 0.7023255813953488,
"repo_name": "igd-geo/equinox-test",
"id": "a98a7a02818cfadfc240d4069dd6d503378bf0f0",
"size": "645",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "de.fhg.igd.equinox.test.site/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "35276"
},
{
"name": "Shell",
"bytes": "76"
}
],
"symlink_target": ""
}
|
template <typename T> class C { virtual void f() { } };
//- @f defines/binding DF
//- DF overrides TAppCF
//- DF overrides/root TAppCF
//- TAppCF.node/kind tapp
//- TAppCF param.0 CF
class D : public C<int> { void f() override { } };
//- @f defines/binding EF
//- EF overrides DF
//- EF overrides/root TAppCF
class E : public D { void f() override { } };
|
{
"content_hash": "3bb3c431d5396ade43b4c0c813e9f51a",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 55,
"avg_line_length": 32.27272727272727,
"alnum_prop": 0.6422535211267606,
"repo_name": "kythe/kythe",
"id": "405939db4b756bd6564e21023bcea5b0e25fe9f4",
"size": "531",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "kythe/cxx/indexer/cxx/testdata/tvar_template/template_rec_override_root_aliasing.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4169"
},
{
"name": "C++",
"bytes": "1874842"
},
{
"name": "Dockerfile",
"bytes": "20694"
},
{
"name": "Go",
"bytes": "1876965"
},
{
"name": "HTML",
"bytes": "5148"
},
{
"name": "Java",
"bytes": "844590"
},
{
"name": "JavaScript",
"bytes": "3513"
},
{
"name": "Lex",
"bytes": "5192"
},
{
"name": "Makefile",
"bytes": "222"
},
{
"name": "OCaml",
"bytes": "12652"
},
{
"name": "Python",
"bytes": "10918"
},
{
"name": "Ruby",
"bytes": "2543"
},
{
"name": "Rust",
"bytes": "581728"
},
{
"name": "SCSS",
"bytes": "10113"
},
{
"name": "Shell",
"bytes": "89032"
},
{
"name": "Starlark",
"bytes": "540157"
},
{
"name": "TeX",
"bytes": "2455"
},
{
"name": "TypeScript",
"bytes": "124204"
},
{
"name": "Yacc",
"bytes": "5018"
}
],
"symlink_target": ""
}
|
namespace media {
// A codec allocator that provides a configurable fake implementation
// and lets you set expecations on the "Mock*" methods.
class FakeCodecAllocator : public testing::NiceMock<CodecAllocator> {
public:
explicit FakeCodecAllocator(
scoped_refptr<base::SequencedTaskRunner> task_runner);
~FakeCodecAllocator() override;
// These are called with some parameters of the codec config by our
// implementation of their respective functions. This allows tests to set
// expectations on them.
MOCK_METHOD0(MockCreateMediaCodecAsync, void());
// Note that this doesn't exactly match the signature, since unique_ptr
// doesn't work.
MOCK_METHOD1(MockReleaseMediaCodec, void(MediaCodecBridge*));
void CreateMediaCodecAsync(CodecCreatedCB codec_created_cb,
std::unique_ptr<VideoCodecConfig> config) override;
void ReleaseMediaCodec(std::unique_ptr<MediaCodecBridge> media_codec,
base::OnceClosure codec_released_cb) override;
// Satisfies the pending codec creation with |codec| if given, or a new
// MockMediaCodecBridge if not. Returns a raw pointer to the codec, or nullptr
// if the client WeakPtr was invalidated.
MockMediaCodecBridge* ProvideMockCodecAsync(
std::unique_ptr<MockMediaCodecBridge> codec = nullptr);
// Satisfies the pending codec creation with a null codec.
void ProvideNullCodecAsync();
// Most recent codec that we've created via CreateMockCodec, since we have
// to assign ownership. It may be freed already.
MockMediaCodecBridge* most_recent_codec = nullptr;
// The DestructionObserver for |most_recent_codec|.
std::unique_ptr<DestructionObserver> most_recent_codec_destruction_observer;
// Copy of most of the fields in the most recent config, except for the ptrs.
std::unique_ptr<VideoCodecConfig> most_recent_config;
private:
CodecCreatedCB pending_codec_created_cb_;
DISALLOW_COPY_AND_ASSIGN(FakeCodecAllocator);
};
} // namespace media
#endif // MEDIA_GPU_ANDROID_FAKE_CODEC_ALLOCATOR_H_
|
{
"content_hash": "5abe43c3f014fc0b02fbd3a3faf0f341",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 80,
"avg_line_length": 39.67307692307692,
"alnum_prop": 0.7445467765390208,
"repo_name": "endlessm/chromium-browser",
"id": "6816c0a75eab80913034ca303e58564d39e944c2",
"size": "2630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "media/gpu/android/fake_codec_allocator.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
package com.amazonservices.mws.jaxb;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>CycleLengthUnitOfMeasure的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
* <p>
* <pre>
* <simpleType name="CycleLengthUnitOfMeasure">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CM"/>
* <enumeration value="IN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CycleLengthUnitOfMeasure")
@XmlEnum
public enum CycleLengthUnitOfMeasure {
CM,
IN;
public String value() {
return name();
}
public static CycleLengthUnitOfMeasure fromValue(String v) {
return valueOf(v);
}
}
|
{
"content_hash": "d4fcc4be89b051815c00b2988add2a9c",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 69,
"avg_line_length": 19.44736842105263,
"alnum_prop": 0.6562922868741543,
"repo_name": "kenyonduan/amazon-mws",
"id": "c610c0267f7829e0109492ad57420f27ab7a9b38",
"size": "785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/amazonservices/mws/jaxb/CycleLengthUnitOfMeasure.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "8584668"
}
],
"symlink_target": ""
}
|
#ifndef __Scanner_Handler_hpp__
#define __Scanner_Handler_hpp__ 1
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2004 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
#include "Trivial_Handler.hpp"
// =================================================================================================
/// \file Scanner_Handler.hpp
/// \brief File format handler for packet scanning.
///
/// This header ...
///
// =================================================================================================
extern XMPFileHandler * Scanner_MetaHandlerCTor ( XMPFiles * parent );
static const XMP_OptionBits kScanner_HandlerFlags = kTrivial_HandlerFlags;
class Scanner_MetaHandler : public Trivial_MetaHandler
{
public:
Scanner_MetaHandler () {};
Scanner_MetaHandler ( XMPFiles * parent );
~Scanner_MetaHandler();
void CacheFileData();
}; // Scanner_MetaHandler
// =================================================================================================
#endif /* __Scanner_Handler_hpp__ */
|
{
"content_hash": "65bdbf94db6059eee148a5e1af1ccc84",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 100,
"avg_line_length": 32.595238095238095,
"alnum_prop": 0.4631117604090577,
"repo_name": "vb0067/XMPToolkitSDK",
"id": "e3ea8013d76b2ff1d4aaea70f3af1dd9289c5238",
"size": "1369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XMPFilesStatic/source/FileHandlers/Scanner_Handler.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "26831"
},
{
"name": "C++",
"bytes": "3582672"
}
],
"symlink_target": ""
}
|
#import "BackRow-Structs.h"
#import "BRControl.h"
@class NSArray;
__attribute__((visibility("hidden")))
@interface BRMetadataLinesLayer : BRControl {
@private
NSArray *_lineLayers; // 40 = 0x28
float _lineHeight; // 44 = 0x2c
}
- (id)init; // 0x315b5cfd
- (void)_buildLineLayersForValues:(id)values andLabels:(id)labels usingIndexes:(id)indexes; // 0x315b70d1
- (void)_layoutLines; // 0x315b73bd
- (void)_setLineHeightUsingValues:(id)values andLabels:(id)labels; // 0x315b6de9
- (id)_visibleMetadataIndexesForHeight:(float)height andValues:(id)values; // 0x315b6f51
- (float)_widthOfWidestLabel; // 0x315b74b9
- (void)dealloc; // 0x315b7729
- (void)setMetadataValues:(id)values withLabels:(id)labels frameWidth:(float)width maxHeight:(float)height; // 0x315b6d01
@end
|
{
"content_hash": "a53851ab6ec206d72c27a5a6f2a3e81a",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 121,
"avg_line_length": 33.69565217391305,
"alnum_prop": 0.743225806451613,
"repo_name": "tandrup/eyetv4atv",
"id": "8e60329a922552841e7b670a5085a5036f9f7ec7",
"size": "979",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "eyetv4atv/include/BackRow/BRMetadataLinesLayer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1157"
},
{
"name": "C++",
"bytes": "1195"
},
{
"name": "Objective-C",
"bytes": "741647"
}
],
"symlink_target": ""
}
|
package com.google.gwt.modernizr.client.utils;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.StyleElement;
/**
* Implement StyleSheet object
*
* @author Julien Dramaix (julien.dramaix@gmail.com, @jdramaix)
*
*/
public class StyleSheet extends JavaScriptObject {
public static class CssRule extends JavaScriptObject {
protected CssRule() {
}
public final native String getCssText()/*-{
return this.cssText;
}-*/;
}
public static class CssRuleList extends JavaScriptObject {
protected CssRuleList() {
}
public final native int getLenght()/*-{
return this.length;
}-*/;
public final native CssRule item(int index)/*-{
return this[index];
}-*/;
}
public native static StyleSheet get(StyleElement style)/*-{
return style.sheet || style.styleSheet;
}-*/;
protected StyleSheet() {
}
public final native void deleteRule(int index)/*-{
this.deleteRule(index);
}-*/;
public final native CssRuleList getCssRules()/*-{
return this.cssRules;
}-*/;
public final native String getCssText()/*-{
return this.cssText;
}-*/;
public final native void insertRule(String rule, int index)/*-{
this.insertRule(rule,index);
}-*/;
public final native void setCssText(String css)/*-{
this.cssText=css;
}-*/;
}
|
{
"content_hash": "a2fe51ce7b9720056fe92a9328ba7e79",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 65,
"avg_line_length": 20.388059701492537,
"alnum_prop": 0.664714494875549,
"repo_name": "jDramaix/gwtmodernizr",
"id": "e8e7fa14d1a421fea1cadbff6f5f12dddfe0f42b",
"size": "2734",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/com/google/gwt/modernizr/client/utils/StyleSheet.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "119173"
}
],
"symlink_target": ""
}
|
<?php
namespace CedricBlondeau\Moneris\Transaction\Basic;
use CedricBlondeau\Moneris\Config;
use CedricBlondeau\Moneris\Transaction\AbstractTransaction;
final class Purchase extends AbstractTransaction
{
/**
* @param Config $config
* @param array $params
*/
public function __construct(Config $config, array $params)
{
parent::__construct('purchase', $config, $params);
$this->requiredParams = array('order_id', 'pan', 'amount', 'expdate');
}
}
|
{
"content_hash": "e7d67e3e57eafc7fa7dd1c1c4087ed8e",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 78,
"avg_line_length": 27.38888888888889,
"alnum_prop": 0.6835699797160243,
"repo_name": "cedricblondeau/php-moneris-eselectplus",
"id": "7afb3e8e41af8d67124a3ab0ccdb5fa6da16bf09",
"size": "493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Transaction/Basic/Purchase.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "23991"
}
],
"symlink_target": ""
}
|
[](https://travis-ci.org/geerlingguy/ansible-role-nginx)
Installs Nginx on RedHat/CentOS or Debian/Ubuntu linux servers.
This role installs and configures the latest version of Nginx from the Nginx yum repository (on RedHat-based systems) or via apt (on Debian-based systems). You will likely need to do extra setup work after this role has installed Nginx, like adding your own [virtualhost].conf file inside `/etc/nginx/conf.d/`, describing the location and options to use for your particular website.
## Requirements
None.
## Role Variables
Available variables are listed below, along with default values (see `defaults/main.yml`):
nginx_vhosts: []
A list of vhost definitions (server blocks) for Nginx virtual hosts. If left empty, you will need to supply your own virtual host configuration. See the commented example in `defaults/main.yml` for available server options. If you have a large number of customizations required for your server definition(s), you're likely better off managing the vhost configuration file yourself, leaving this variable set to `[]`.
nginx_vhosts:
- listen: "80 default_server"
server_name: "example.com"
root: "/var/www/example.com"
index: "index.php index.html index.htm"
error_page: ""
access_log: ""
extra_parameters: |
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
An example of a fully-populated nginx_vhosts entry, using a `|` to declare a block of syntax for the `extra_parameters`.
nginx_remove_default_vhost: false
Whether to remove the 'default' virtualhost configuration supplied by Nginx. Useful if you want the base `/` URL to be directed at one of your own virtual hosts configured in a separate .conf file.
nginx_upstreams: []
If you are configuring Nginx as a load balancer, you can define one or more upstream sets using this variable. In addition to defining at least one upstream, you would need to configure one of your server blocks to proxy requests through the defined upstream (e.g. `proxy_pass http://myapp1;`). See the commented example in `defaults/main.yml` for more information.
nginx_user: "nginx"
The user under which Nginx will run. Defaults to `nginx` for RedHat, and `www-data` for Debian.
nginx_worker_processes: "1"
nginx_worker_connections: "1024"
`nginx_worker_processes` should be set to the number of cores present on your machine. Connections (find this number with `grep processor /proc/cpuinfo | wc -l`). `nginx_worker_connections` is the number of connections per process. Set this higher to handle more simultaneous connections (and remember that a connection will be used for as long as the keepalive timeout duration for every client!).
nginx_error_log: "/var/log/nginx/error.log warn"
nginx_access_log: "/var/log/nginx/access.log main buffer=16k"
Configuration of the default error and access logs. Set to `off` to disable a log entirely.
nginx_sendfile: "on"
nginx_tcp_nopush: "on"
nginx_tcp_nodelay: "on"
TCP connection options. See [this blog post](https://t37.net/nginx-optimization-understanding-sendfile-tcp_nodelay-and-tcp_nopush.html) for more information on these directives.
nginx_keepalive_timeout: "65"
nginx_keepalive_requests: "100"
Nginx keepalive settings. Timeout should be set higher (10s+) if you have more polling-style traffic (AJAX-powered sites especially), or lower (<10s) if you have a site where most users visit a few pages and don't send any further requests.
nginx_client_max_body_size: "64m"
This value determines the largest file upload possible, as uploads are passed through Nginx before hitting a backend like `php-fpm`. If you get an error like `client intended to send too large body`, it means this value is set too low.
nginx_proxy_cache_path: ""
Set as the `proxy_cache_path` directive in the `nginx.conf` file. By default, this will not be configured (if left as an empty string), but if you wish to use Nginx as a reverse proxy, you can set this to a valid value (e.g. `"/var/cache/nginx keys_zone=cache:32m"`) to use Nginx's cache (further proxy configuration can be done in individual server configurations).
nginx_default_release: ""
(For Debian/Ubuntu only) Allows you to set a different repository for the installation of Nginx. As an example, if you are running Debian's wheezy release, and want to get a newer version of Nginx, you can install the `wheezy-backports` repository and set that value here, and Ansible will use that as the `-t` option while installing Nginx.
## Dependencies
None.
## Example Playbook
- hosts: server
roles:
- { role: geerlingguy.nginx }
## License
MIT / BSD
## Author Information
This role was created in 2014 by [Jeff Geerling](http://jeffgeerling.com/), author of [Ansible for DevOps](http://ansiblefordevops.com/).
|
{
"content_hash": "e1660beee3301c0feab06c2b79f3a10e",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 416,
"avg_line_length": 53.06122448979592,
"alnum_prop": 0.735,
"repo_name": "FlorianLB/lumberjack",
"id": "6e92a26dc74b58fd4b3d9be1c547c541b1096260",
"size": "5223",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ansible/roles/galaxy/geerlingguy.nginx/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22997"
},
{
"name": "Shell",
"bytes": "6127"
}
],
"symlink_target": ""
}
|
package org.gearvrf.x3d;
import org.gearvrf.GVRCameraRig;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRCursorController;
import org.gearvrf.GVRDrawFrameListener;
import org.gearvrf.GVRExternalScene;
import org.gearvrf.GVRPhongShader;
import org.gearvrf.GVRRenderData;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.ISensorEvents;
import org.gearvrf.SensorEvent;
import org.gearvrf.io.GVRControllerType;
import org.gearvrf.io.GVRInputManager;
import org.gearvrf.scene_objects.GVRCubeSceneObject;
import org.gearvrf.scene_objects.GVRSphereSceneObject;
import org.gearvrf.scene_objects.GVRTextViewSceneObject;
import org.gearvrf.scene_objects.GVRViewSceneObject;
import org.gearvrf.scene_objects.view.GVRWebView;
import org.gearvrf.GVRScene;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.Threads;
import org.joml.Vector3f;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Color;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
import android.content.Context;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* @author m1.williams
* AnchorImplementation handles the functions specific to X3D's Anchor node.
* An Anchor is a subclass of the TouchSensor (though only 'isActive' is
* implemented, there is no 'isOver').
* The Anchor can either:
* Animate to a new Viewpoint if the url begins with a # followed by the Viewpoint's DEF name
* Go to a new X3D scene if the url ends with ".x3d"
* Or open up a new web page.
*/
public class AnchorImplementation {
private static final String TAG = AnchorImplementation.class.getSimpleName();
private static final String IS_OVER = "isOver";
private static final String Is_ACTIVE = "isActive";
private GVRContext gvrContext = null;
private GVRSceneObject root = null;
private Vector<Viewpoint> viewpoints = new Vector<Viewpoint>();
private PerFrameWebViewControl perFrameWebViewControl = new PerFrameWebViewControl();
private GVRSphereSceneObject gvrScaleObject = null;
private final float[] scaleControlInitPosition = {-2, 1.5f, 0};
private Vector3f translationObjectTranslationLocal = new Vector3f();
private Vector3f translationObjectTranslationGlobal = new Vector3f();
// when the tranlsation icon is clicked on, saves the initial value for the camera's look at
private float[] initialCameralookAt = new float[3];
private final float[] webViewDimensions = {8.0f, 6.0f}; //web view is width x height
private final Vector3f cubeUISize = new Vector3f(webViewDimensions[0], .5f, .2f);
private final float[] cubeUIPosition = {0, (webViewDimensions[1] + cubeUISize.y)/2.0f, -cubeUISize.z/2.0f}; // center, above the web page
private GVRTextViewSceneObject gvrTextExitObject = null;
private GVRTextViewSceneObject gvrTextTranslationObject = null;
private GVRTextViewSceneObject gvrTextScaleObject = null;
private GVRTextViewSceneObject gvrTextRotateObject = null;
private final float[] textExitPosition = {1.5f, 0, .125f};
private final float[] textScalePosition = {-1.5f, 0, .125f};
private final float[] textTranslatePosition = {-.5f, 0, .125f};
private final float[] textRotatePosition = {.5f, 0, .125f};
private float[] webPagePlusUIPosition = {1.0f, -1.0f, -5.0f};
private float[] webPagePlusUIScale = {1, 1}; // retains current Web page Scale. z is always 1
private float[] beginWebPagePlusUIScale = {1, 1}; // retains the beginning Web page Scale when first clicked
private float[] beginUIClickPos = {0, 0, 0}; // where we clicked on UI to control the web page U.I.
private float[] diffWebPageUIClick = {0, 0, 0}; // difference between beginUIClickPos and webPagePlusUIPosition
private float[] initialHitPoint = new float[3];
private GVRSceneObject webPagePlusUISceneObject = null;
private final int textColorDefault = Color.BLACK;
private final int textColorIsOver = Color.LTGRAY;
private final int textColorIsActive = Color.WHITE;
private final int textColorBackground = Color.CYAN;
private final String TEXT_EXIT_NAME = "exit";
private final String TEXT_TRANSLATE_NAME = "translate";
private final String TEXT_ROTATE_NAME = "rotate";
private final String TEXT_SCALE_NAME = "scale";
private GVRDrawFrameListener mOnDrawFrame = null;
private boolean webViewTranslation = false;
private boolean webViewScale = false;
private GVRWebView gvrWebView = null;
private String webPageContent = "";
// temporary boolean to switch between just the web page display with
// UI controls or just click on the web page to close it all.
private final boolean useWebPageTranformControls = false;
private boolean webPageActive = false;
private boolean webPageClosed = false;
public AnchorImplementation(GVRContext gvrContext, GVRSceneObject root, Vector<Viewpoint> viewpoints ) {
this.gvrContext = gvrContext;
this.root = root;
this.viewpoints = viewpoints;
}
/**
* AnchorInteractivity() called when an object associated with an Anchor tag
* is clicked. There are 3 possible outcomes:
* A web page is opened, we go to a new .x3d scene, or we go to a new Camera (Viewpoint)
*/
public void AnchorInteractivity(InteractiveObject interactiveObject) {
// The interactiveObject contains an Anchor tag.
// Could be a link to another x3d page, <Viewpoint> (camera) or web page
final InteractiveObject interactiveObjectFinal = interactiveObject;
interactiveObject.getSensor().addISensorEvents(new ISensorEvents() {
boolean isActiveDone = false;
boolean newSceneLoaded = false;
@Override
public void onSensorEvent(SensorEvent event) {
// Getting event group stuff.
if (event.isActive()) {
//Log.e("X3D-a", "event.isActive " + interactiveObjectFinal.getDefinedItem().getName() );
Log.e("X3D-a", "event.isActive " + interactiveObjectFinal.getSensor().getAnchorURL() );
if (!isActiveDone) {
isActiveDone = true;
String url = interactiveObjectFinal.getSensor().getAnchorURL();
if (url.toLowerCase().endsWith(".x3d")) {
if ( !newSceneLoaded ) {
// Go to another X3D scene
GVRExternalScene gvrExternalScene = new GVRExternalScene(gvrContext, url, true);
GVRSceneObject gvrSceneObjectAnchor = new GVRSceneObject(gvrContext);
gvrSceneObjectAnchor.attachComponent( gvrExternalScene );
boolean load = gvrExternalScene.load(gvrContext.getMainScene());
newSceneLoaded = true;
if (!load) Log.e(TAG, "Error loading new X3D scene " + url);
else Log.e(TAG, "New X3D scene " + url + " loaded.");
}
} // end if .x3d file
else if (url.startsWith("#")) {
// go to another Viewpoint
SetNewViewpoint(url);
} // end if new Viewpoint selected
else if ((url.endsWith(".xml")) || (url.endsWith(".rss"))) {
// Web page with XML, RSS data
if (!webPageActive && !webPageClosed) {
webPageActive = true;
webPageContent = "<HTML><BODY><FONT SIZE=7>Issue pressenting RSS / XML page</FONT></BODY></HTML>";
final String urlFinal = url;
Threads.spawn(new Runnable() {
public void run() {
File file = null;
FileInputStream fileInputStream = null;
try {
Context context = gvrContext.getContext();
file = gvrContext.getAssetLoader().downloadFile(context, urlFinal);
fileInputStream = new FileInputStream(file);
// Parse the XML/RSS file
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
UserHandler userhandler = new UserHandler();
// CSS definitions will make XML/RSS data look nice
webPageContent = "<html><body>";
String css = "<style>" +
"#title { font-size: 60px; font-family: Arial; }" +
"#desc { font-size: 50px; font-family: Arial; }" +
"#link { font-size: 60px; font-family: Arial; }" +
"</style>";
webPageContent += css;
saxParser.parse(fileInputStream, userhandler);
webPageContent += "</body></html>";
LaunchWebPage(interactiveObjectFinal, urlFinal);
} catch (FileNotFoundException e) {
Log.e(TAG, "File " + urlFinal + " not found: " + e);
} catch (IOException e) {
Log.e(TAG, "File " + urlFinal + " IOException: " + e);
} catch (Exception e) {
Log.e(TAG, "File " + urlFinal + " exception: " + e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
if (file != null) {
file.delete();
}
}
}
});
} // end if !webPageActive
} // end if rss or xml data
else {
if ( !webPageActive && !webPageClosed) {
// Launch a web page window
LaunchWebPage(interactiveObjectFinal, url);
webPageActive = true;
}
} // end launching a Web Page
} // end if isActiveDone = false
else {
isActiveDone = false;
}
}
else if (!event.isActive() ) {
//Prevents closing the web page from invoking a new page on the item behind it.
webPageClosed = false;
}
else if (event.isOver()) {
GVRSceneObject sensorObj = interactiveObjectFinal.getSensor().getGVRSceneObject();
if (sensorObj != null) {
GVRSceneObject sensorObj2 = sensorObj.getChildByIndex(0);
if (sensorObj2 != null) {
GVRCameraRig mainCameraRig = gvrContext.getMainScene().getMainCameraRig();
float[] cameraPosition = new float[3];
cameraPosition[0] = mainCameraRig.getTransform().getPositionX();
cameraPosition[1] = mainCameraRig.getTransform().getPositionY();
cameraPosition[2] = mainCameraRig.getTransform().getPositionZ();
}
}
} else {
GVRSceneObject sensorObj = interactiveObjectFinal.getSensor().getGVRSceneObject();
if (sensorObj != null) {
GVRSceneObject sensorObj2 = sensorObj.getChildByIndex(0);
if (sensorObj2 != null) {
GVRCameraRig mainCameraRig = gvrContext.getMainScene().getMainCameraRig();
float[] cameraPosition = new float[3];
cameraPosition[0] = mainCameraRig.getTransform().getPositionX();
cameraPosition[1] = mainCameraRig.getTransform().getPositionY();
cameraPosition[2] = mainCameraRig.getTransform().getPositionZ();
}
}
}
} // end of onSensorEvent
}); // end of AddISensorEvent
} // end AnchorImplementation class
private void SetNewViewpoint(String url) {
Viewpoint vp = null;
// get the name without the '#' sign
String vpURL = url.substring(1, url.length());
for (Viewpoint viewpoint : viewpoints) {
if ( viewpoint.getName().equalsIgnoreCase(vpURL) ) {
vp = viewpoint;
}
}
if ( vp != null ) {
// found the Viewpoint matching the url
GVRCameraRig mainCameraRig = gvrContext.getMainScene().getMainCameraRig();
float[] cameraPosition = vp.getPosition();
mainCameraRig.getTransform().setPosition( cameraPosition[0], cameraPosition[1], cameraPosition[2] );
// Set the Gaze controller position which is where the pick ray
// begins in the direction of camera.lookt()
GVRCursorController gazeController = null;
GVRInputManager inputManager = gvrContext.getInputManager();
List<GVRCursorController> controllerList = inputManager.getCursorControllers();
for(GVRCursorController controller: controllerList){
if(controller.getControllerType() == GVRControllerType.GAZE);
{
gazeController = controller;
break;
}
}
if ( gazeController != null) {
gazeController.setOrigin(cameraPosition[0], cameraPosition[1], cameraPosition[2]);
}
}
else {
Log.e(TAG, "Viewpoint named " + vpURL + " not found (defined).");
}
} // end SetNewViewpoint
private void LaunchWebPage(InteractiveObject interactiveObjectFinal, String url) {
if (webPagePlusUISceneObject == null) {
final String urlFinal = url;
final GVRSceneObject gvrSceneObjectAnchor = interactiveObjectFinal.getSensor().getGVRSceneObject();
gvrContext.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Launch a new WebView window and place the web page there.
gvrWebView = new GVRWebView(gvrContext.getActivity());
gvrWebView.setInitialScale(100);
gvrWebView.measure(1600, 1200);
gvrWebView.layout(0, 0, 1600, 1200);
WebSettings webSettings = gvrWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
if ((urlFinal.endsWith(".xml")) || (urlFinal.endsWith(".rss"))) {
if (gvrWebView != null) gvrWebView.loadData(webPageContent, "text/html", null);
} // end if rss or xml data
else {
// Open a Web page
gvrWebView.setWebViewClient(new WebViewClient() {
//TODO: replace for depricated code with:
// onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, " setWebViewClient Error ");
Log.e(TAG, " errorCode " + errorCode + "; description " + description + "; url " + failingUrl);
}
});
if (gvrWebView != null) gvrWebView.loadUrl(urlFinal);
} // end if url data - a web address
if (gvrWebView != null) {
GVRViewSceneObject gvrWebViewSceneObject = new GVRViewSceneObject(gvrContext,
gvrWebView, webViewDimensions[0], webViewDimensions[1]);
gvrWebViewSceneObject.setName("Web View");
gvrWebViewSceneObject.getRenderData().getMaterial().setOpacity(1.0f);
gvrWebViewSceneObject.getRenderData().setShaderTemplate(GVRPhongShader.class);
gvrWebViewSceneObject.getTransform().setPosition(0.0f, 0.0f, 0.0f);
gvrWebViewSceneObject.getRenderData().setRenderMask(0);
gvrWebViewSceneObject.getRenderData().setRenderMask(
GVRRenderData.GVRRenderMaskBit.Left
| GVRRenderData.GVRRenderMaskBit.Right);
if (useWebPageTranformControls) WebPageTranformControls( gvrWebViewSceneObject, gvrSceneObjectAnchor, urlFinal);
else WebPageCloseOnClick( gvrWebViewSceneObject, gvrSceneObjectAnchor, urlFinal);
}
} // end run
});
} // end if webPagePlusUISceneObject == null
} // end LaunchWebPage
// Display web page, but no user interface - close
private void WebPageCloseOnClick(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {
final String urlFinal = url;
webPagePlusUISceneObject = new GVRSceneObject(gvrContext);
webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], webPagePlusUIPosition[1], webPagePlusUIPosition[2]);
GVRScene mainScene = gvrContext.getMainScene();
mainScene.bindShaders(webPagePlusUISceneObject);
Sensor webPageSensor = new Sensor(urlFinal, Sensor.Type.TOUCH, gvrWebViewSceneObject);
final GVRSceneObject gvrSceneObjectAnchorFinal = gvrSceneObjectAnchor;
final GVRSceneObject gvrWebViewSceneObjectFinal = gvrWebViewSceneObject;
final GVRSceneObject webPagePlusUISceneObjectFinal = webPagePlusUISceneObject;
webPagePlusUISceneObjectFinal.addChildObject(gvrWebViewSceneObjectFinal);
gvrSceneObjectAnchorFinal.addChildObject(webPagePlusUISceneObjectFinal);
webPageSensor.addISensorEvents(new ISensorEvents() {
boolean uiObjectIsActive = false;
boolean clickDown = true;
@Override
public void onSensorEvent(SensorEvent event) {
if (event.isActive()) {
clickDown = !clickDown;
if (clickDown) {
// Delete the WebView page
gvrSceneObjectAnchorFinal.removeChildObject(webPagePlusUISceneObjectFinal);
webPageActive = false;
webPagePlusUISceneObject = null;
webPageClosed = true; // Make sure click up doesn't open web page behind it
}
}
}
});
} // end WebPageCloseOnClick
// When we implement controls for dragging, scaling, closing, etc. a WebView
private void WebPageTranformControls(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {
final String urlFinal = url;
GVRCubeSceneObject gvrUICubeSceneObject = new GVRCubeSceneObject(gvrContext, true, cubeUISize);
gvrUICubeSceneObject.getTransform().setPosition(cubeUIPosition[0], cubeUIPosition[1], cubeUIPosition[2]);
gvrUICubeSceneObject.getRenderData().getMaterial().setDiffuseColor(.3f, .5f, .7f, 1);
gvrUICubeSceneObject.getRenderData().setShaderTemplate(GVRPhongShader.class);
// Add the icons to close, scale, translate and rotate
gvrTextExitObject = new GVRTextViewSceneObject(gvrContext, 0.5f, 0.45f, " x ");
gvrTextExitObject.setName(TEXT_EXIT_NAME);
gvrTextExitObject.setTextColor(textColorDefault);
gvrTextExitObject.setBackgroundColor(textColorBackground);
gvrTextExitObject.getTransform().setPosition(textExitPosition[0], textExitPosition[1], textExitPosition[2]);
gvrUICubeSceneObject.addChildObject(gvrTextExitObject);
gvrTextTranslationObject = new GVRTextViewSceneObject(gvrContext, 0.5f, 0.45f, " t ");
gvrTextTranslationObject.setName(TEXT_TRANSLATE_NAME);
gvrTextTranslationObject.setTextColor(textColorDefault);
gvrTextTranslationObject.setBackgroundColor(textColorBackground);
gvrTextTranslationObject.getTransform().setPosition(textTranslatePosition[0], textTranslatePosition[1], textTranslatePosition[2]);
gvrUICubeSceneObject.addChildObject(gvrTextTranslationObject);
gvrTextRotateObject = new GVRTextViewSceneObject(gvrContext, 0.5f, 0.45f, " r ");
gvrTextRotateObject.setName(TEXT_ROTATE_NAME);
gvrTextRotateObject.setTextColor(textColorDefault);
gvrTextRotateObject.setBackgroundColor(textColorBackground);
gvrTextRotateObject.getTransform().setPosition(textRotatePosition[0], textRotatePosition[1], textRotatePosition[2]);
gvrUICubeSceneObject.addChildObject(gvrTextRotateObject);
gvrTextScaleObject = new GVRTextViewSceneObject(gvrContext, 0.5f, 0.45f, " s ");
gvrTextScaleObject.setName(TEXT_SCALE_NAME);
gvrTextScaleObject.setTextColor(textColorDefault);
gvrTextScaleObject.setBackgroundColor(textColorBackground);
gvrTextScaleObject.getTransform().setPosition(textScalePosition[0], textScalePosition[1], textScalePosition[2]);
gvrUICubeSceneObject.addChildObject(gvrTextScaleObject);
// Currently req to show an object dynamically added
GVRScene mainScene = gvrContext.getMainScene();
mainScene.bindShaders(gvrUICubeSceneObject);
mainScene.bindShaders(gvrTextExitObject);
mainScene.bindShaders(gvrTextTranslationObject);
mainScene.bindShaders(gvrTextRotateObject);
mainScene.bindShaders(gvrTextScaleObject);
webPagePlusUISceneObject = new GVRSceneObject(gvrContext);
webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], webPagePlusUIPosition[1], webPagePlusUIPosition[2]);
// Set up sensor for the U.I.
Sensor uibObjectSensor = new Sensor(urlFinal, Sensor.Type.TOUCH, gvrUICubeSceneObject);
final GVRSceneObject gvrWebViewSceneObjectFinal = gvrWebViewSceneObject;
final GVRSceneObject gvrUICubeSceneObjectFinal = gvrUICubeSceneObject;
final GVRSceneObject webPagePlusUISceneObjectFinal = webPagePlusUISceneObject;
final GVRSceneObject gvrSceneObjectAnchorFinal = gvrSceneObjectAnchor;
webPagePlusUISceneObjectFinal.addChildObject(gvrWebViewSceneObjectFinal);
webPagePlusUISceneObjectFinal.addChildObject(gvrUICubeSceneObjectFinal);
gvrSceneObjectAnchorFinal.addChildObject(webPagePlusUISceneObjectFinal);
uibObjectSensor.addISensorEvents(new ISensorEvents() {
boolean uiObjectIsActive = false;
boolean clickDown = false;
@Override
public void onSensorEvent(SensorEvent event) {
float[] hitLocation = event.getPickedObject().getHitLocation();
float hitX = hitLocation[0];
if (event.isActive()) {
clickDown = !clickDown;
if (clickDown) {
// only go through once even if object is clicked a long time
uiObjectIsActive = !uiObjectIsActive;
if (uiObjectIsActive) {
if (hitX > cubeUISize.x / 4.0f) {
// Delete the WebView page, control currently far right of web page
gvrContext.unregisterDrawFrameListener(mOnDrawFrame);
if (gvrTextScaleObject != null) {
gvrWebViewSceneObjectFinal.removeChildObject(gvrTextScaleObject);
}
if (gvrTextRotateObject != null) {
gvrWebViewSceneObjectFinal.removeChildObject(gvrTextRotateObject);
}
if (gvrTextTranslationObject != null) {
gvrWebViewSceneObjectFinal.removeChildObject(gvrTextTranslationObject);
}
gvrTextExitObject = null;
gvrTextScaleObject = null;
gvrTextRotateObject = null;
gvrTextTranslationObject = null;
gvrSceneObjectAnchorFinal.removeChildObject(webPagePlusUISceneObjectFinal);
webViewTranslation = false;
webViewScale = false;
gvrWebView = null;
webPagePlusUISceneObject = null;
webPageActive = false;
} else if (hitX > 0) {
// TODO: Rotate the web view, control currently right side of control bar
webViewTranslation = false;
} else if (hitX > -cubeUISize.x / 4.0f) {
// Translate the web view, control currently left side of control bar
TranslationControl(gvrWebViewSceneObjectFinal);
} // end transltion web window, hit between 0 and .25,
else {
// Scale the web view, control currently in upper right corner
webViewTranslation = false;
ScaleControl(gvrWebViewSceneObjectFinal, gvrSceneObjectAnchorFinal, urlFinal);
} // end scaling web window, hit between -2 and -1,
} else { // uiObjectIsActive is false
if (mOnDrawFrame != null)
// wrap up any lose ends closing the web page.
gvrContext.unregisterDrawFrameListener(mOnDrawFrame);
if (hitX > 0) {
// TODO: Stop Rotating the web page
} else if (hitX > -cubeUISize.x / 4.0f) {
// Stop translating the web page
if (gvrTextTranslationObject != null) {
gvrTextTranslationObject.setTextColor(textColorIsOver);
}
webViewTranslation = false;
} // end transltion web window, hit between 0 and .25,
else if (hitX < -cubeUISize.x / 4.0f) {
// Stop scaling the web page
if (gvrTextScaleObject != null) {
gvrTextScaleObject.setTextColor(textColorIsOver);
}
webViewScale = false;
} // end scaling web window, hit between -2 and -1,
}
}
} else if (event.isOver() && !uiObjectIsActive) {
// highlight the icons to give visual cue to users
if (hitX > cubeUISize.x / 4.0f) {
if (gvrTextExitObject != null)
gvrTextExitObject.setTextColor(textColorIsOver);
if (gvrTextRotateObject != null)
gvrTextRotateObject.setTextColor(textColorDefault);
if (gvrTextTranslationObject != null)
gvrTextTranslationObject.setTextColor(textColorDefault);
if (gvrTextScaleObject != null)
gvrTextScaleObject.setTextColor(textColorDefault);
webViewTranslation = false;
webViewScale = false;
} else if (hitX > 0) {
if (gvrTextExitObject != null) gvrTextExitObject.setTextColor(textColorDefault);
if (gvrTextRotateObject != null) gvrTextRotateObject.setTextColor(textColorIsOver);
if (gvrTextTranslationObject != null) gvrTextTranslationObject.setTextColor(textColorDefault);
if (gvrTextScaleObject != null) gvrTextScaleObject.setTextColor(textColorDefault);
webViewTranslation = false;
webViewScale = false;
} // end scaling web window, hit between 0 and .25,
else if (hitX > -cubeUISize.x / 4.0f) {
if (gvrTextExitObject != null) gvrTextExitObject.setTextColor(textColorDefault);
if (gvrTextRotateObject != null) gvrTextRotateObject.setTextColor(textColorDefault);
if (gvrTextTranslationObject != null) gvrTextTranslationObject.setTextColor(textColorIsOver);
if (gvrTextScaleObject != null) gvrTextScaleObject.setTextColor(textColorDefault);
webViewTranslation = false;
webViewScale = false;
} else {
if (gvrTextExitObject != null) gvrTextExitObject.setTextColor(textColorDefault);
if (gvrTextRotateObject != null) gvrTextRotateObject.setTextColor(textColorDefault);
if (gvrTextTranslationObject != null) gvrTextTranslationObject.setTextColor(textColorDefault);
if (gvrTextScaleObject != null) gvrTextScaleObject.setTextColor(textColorIsOver);
webViewTranslation = false;
webViewScale = false;
}
} else if (!event.isOver() && !uiObjectIsActive) {
if (gvrTextExitObject != null) gvrTextExitObject.setTextColor(textColorDefault);
if (gvrTextRotateObject != null)
gvrTextRotateObject.setTextColor(textColorDefault);
if (gvrTextTranslationObject != null)
gvrTextTranslationObject.setTextColor(textColorDefault);
if (gvrTextScaleObject != null) gvrTextScaleObject.setTextColor(textColorDefault);
webViewTranslation = false;
webViewScale = false;
}
}
});
} // end WebPageTranformControls
private void TranslationControl(GVRSceneObject gvrWebViewSceneObjectFinal) {
GVRScene mainScene = gvrContext.getMainScene();
GVRCameraRig gvrCameraRig = mainScene.getMainCameraRig();
initialCameralookAt = gvrCameraRig.getLookAt();
gvrWebViewSceneObjectFinal.getTransform().getModelMatrix4f().getTranslation(translationObjectTranslationGlobal);
gvrWebViewSceneObjectFinal.getTransform().getLocalModelMatrix4f().getTranslation(translationObjectTranslationLocal);
if (gvrTextTranslationObject != null) {
gvrTextTranslationObject.setTextColor(textColorIsActive);
}
webViewTranslation = true;
for ( int i = 0; i < 3; i++ ) {
if (i == 2) beginUIClickPos[i] = webPagePlusUIPosition[i] - cubeUIPosition[i];
else beginUIClickPos[i] = webPagePlusUIPosition[i] + cubeUIPosition[i] + textTranslatePosition[i];
diffWebPageUIClick[i] = beginUIClickPos[i] - webPagePlusUIPosition[i];
}
mOnDrawFrame = new DrawFrame();
gvrContext.registerDrawFrameListener(mOnDrawFrame);
} // end TranslationControl
private void ScaleControl(GVRSceneObject gvrWebViewSceneObjectFinal, GVRSceneObject gvrSceneObjectAnchorFinal, String urlFinal) {
GVRScene mainScene = gvrContext.getMainScene();
GVRCameraRig gvrCameraRig = mainScene.getMainCameraRig();
initialCameralookAt = gvrCameraRig.getLookAt();
gvrWebViewSceneObjectFinal.getTransform().getModelMatrix4f().getTranslation(translationObjectTranslationGlobal);
gvrWebViewSceneObjectFinal.getTransform().getLocalModelMatrix4f().getTranslation(translationObjectTranslationLocal);
if (gvrTextScaleObject != null) {
gvrTextScaleObject.setTextColor(textColorIsActive);
}
webViewScale = true;
for (int i = 0; i < 3; i++ ) {
initialHitPoint[i] = (initialCameralookAt[i] * translationObjectTranslationGlobal.z) / initialCameralookAt[2];
}
beginWebPagePlusUIScale[0] = webPagePlusUIScale[0];
beginWebPagePlusUIScale[1] = webPagePlusUIScale[1];
mOnDrawFrame = new DrawFrame();
gvrContext.registerDrawFrameListener(mOnDrawFrame);
} // end ScaleControl
private class PerFrameWebViewControl {
final void onDrawFrame(float frameTime) {
GVRScene mainScene = gvrContext.getMainScene();
GVRCameraRig gvrCameraRig = mainScene.getMainCameraRig();
float[] currentCameraLookAt = gvrCameraRig.getLookAt();
if ( webViewScale ) {
float zFactor = initialCameralookAt[2] / currentCameraLookAt[2];
webPagePlusUIScale[0] = (currentCameraLookAt[0] / initialCameralookAt[0]) * zFactor * beginWebPagePlusUIScale[0];
webPagePlusUIScale[1] = (currentCameraLookAt[1] / initialCameralookAt[1]) * zFactor * beginWebPagePlusUIScale[1];
float[] currentHitPoint = new float[3];
for (int i = 0; i < 3; i++ ) {
currentHitPoint[i] = (currentCameraLookAt[i] * translationObjectTranslationGlobal.z) / currentCameraLookAt[2];
}
if (webPagePlusUIScale[0] < 1 ) webPagePlusUIScale[0] = 1;
else {
webPagePlusUIScale[0] = ((webPagePlusUIScale[0] - 1) / 2.0f) + 1;
}
if (webPagePlusUISceneObject != null) webPagePlusUISceneObject.getTransform().setScale(webPagePlusUIScale[0], webPagePlusUIScale[0], 1);
} // end if scale
else if ( webViewTranslation ) {
float[] transitionClickPt = {0, 0, translationObjectTranslationGlobal.z};
transitionClickPt[0] = currentCameraLookAt[0] * translationObjectTranslationGlobal.z/currentCameraLookAt[2];
transitionClickPt[1] = currentCameraLookAt[1] * translationObjectTranslationGlobal.z/currentCameraLookAt[2];
for (int i = 0; i < 3; i++) {
transitionClickPt[i] -= diffWebPageUIClick[i];
}
if (webPagePlusUISceneObject != null) webPagePlusUISceneObject.getTransform().setPosition( transitionClickPt[0], transitionClickPt[1], transitionClickPt[2]);
}
} // end onDrawFrame
} // end private class PerFrameScripting
private final class DrawFrame implements GVRDrawFrameListener {
@Override
public void onDrawFrame(float frameTime) {
perFrameWebViewControl.onDrawFrame(frameTime);
}
}
/**
* Prases RSS - XML data that is part of a web page
* Inserts CSS DIV tags.
*/
class UserHandler extends DefaultHandler {
boolean title = false;
boolean description = false;
boolean link = false;
String attributeValue;
String titleString = "";
String xmlElement;
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("title")) {
title = true;
}
else if (qName.equalsIgnoreCase("description")) {
description = true;
}
else if (qName.equalsIgnoreCase("link")) {
link = true;
}
else if (qName.equalsIgnoreCase("media:content")) {
String url = "";
int height = 96;
int width = 128;
String type = "";
attributeValue = attributes.getValue("url");
if (attributeValue != null) {
attributeValue = attributeValue.replace("\"", ""); // remove double and
// single quotes
attributeValue = attributeValue.replace("\'", "");
url = attributeValue;
}
attributeValue = attributes.getValue("height");
if (attributeValue != null) {
try {
height = Integer.parseInt(attributeValue);
}
catch (Exception e) {};
}
attributeValue = attributes.getValue("width");
if (attributeValue != null) {
try {
width = Integer.parseInt(attributeValue);
}
catch (Exception e) {};
}
attributeValue = attributes.getValue("type");
if (attributeValue != null) {
try {
type = attributeValue;
}
catch (Exception e) {};
}
webPageContent += "<img src=\"" + url + "\"><P>";
}
} // end startElement
public void endElement(String uri, String localName, String qName)
throws SAXException {
} // end endElement
public void characters(char ch[], int start, int length) throws SAXException {
if (title) {
titleString = new String(ch, start, length);
//webPageContent += "<DIV id=\"title\">" + titleString + "</DIV>";
title = false;
}
else if (description) {
xmlElement = new String(ch, start, length);
webPageContent += "<DIV id=\"desc\">" + xmlElement + "</DIV>";
description = false;
}
else if (link) {
xmlElement = new String(ch, start, length);
webPageContent += "<DIV id=\"link\"><A HREF=\"" + xmlElement + "\">" + titleString + "</A></DIV>";
link = false;
}
} // end characters prsing
} // end UserHandler (XML parsing)
} // end AnchorInteractivity
|
{
"content_hash": "ce01d23c67326227c3efca880a266441",
"timestamp": "",
"source": "github",
"line_count": 779,
"max_line_length": 173,
"avg_line_length": 51.80872913992298,
"alnum_prop": 0.5666641889045814,
"repo_name": "roshanch/GearVRf",
"id": "fccf33f262d87a4ed48944f2263ef5622d1520b1",
"size": "40967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GVRf/Framework/framework/src/main/java/org/gearvrf/x3d/AnchorImplementation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "463832"
},
{
"name": "C++",
"bytes": "5581263"
},
{
"name": "CMake",
"bytes": "4903"
},
{
"name": "CSS",
"bytes": "1394"
},
{
"name": "GLSL",
"bytes": "50769"
},
{
"name": "HTML",
"bytes": "4555"
},
{
"name": "Java",
"bytes": "3628596"
},
{
"name": "JavaScript",
"bytes": "868539"
},
{
"name": "Makefile",
"bytes": "22841"
},
{
"name": "Objective-C",
"bytes": "51656"
}
],
"symlink_target": ""
}
|
project_path: /web/tools/_project.yaml
book_path: /web/tools/_book.yaml
description: Reference documentation for the "Document uses plugins" Lighthouse audit.
{# wf_updated_on: 2018-07-23 #}
{# wf_published_on: 2018-03-26 #}
{# wf_blink_components: Platform>DevTools #}
# Document uses plugins {: .page-title }
## Overview {: #overview }
Plugins harm SEO in two ways:
1. Search engines can't index plugin content. Plugin content won't show up in search results.
2. Many mobile devices don't support plugins, which creates frustrating experiences for
mobile users This is likely to increase your bounce rate and other signals that indicate to
search engines that the page is not helpful for mobile users.
Source:
* [Unplayable content](/search/mobile-sites/mobile-seo/common-mistakes#unplayable-content)
## Recommendations {: #recommendations }
Remove the plugins and convert your content to HTML.
See [Video](/web/fundamentals/media/video) to learn the best practices for displaying video on
the web.
## More information {: #more-info }
Lighthouse checks the page for tags that commonly represent plugins:
* `embed`
* `object`
* `applet`
And then flags each tag as a plugin if its MIME type matches any of the following:
* `application/x-java-applet`
* `application/x-java-bean`
* `application/x-shockwave-flash`
* `application/x-silverlight`
* `application/x-silverlight-2`
Or if the tag points to a URL with a file format that is known to represent plugin content:
* `swf`
* `flv`
* `class`
* `xap`
[Audit source][src]{:.external}
[src]: https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/audits/seo/plugins.js
## Feedback {: #feedback }
{% include "web/_shared/helpful.html" %}
|
{
"content_hash": "77cca56901170363e3681e33566baadc",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 99,
"avg_line_length": 28.816666666666666,
"alnum_prop": 0.7432041642567958,
"repo_name": "samdutton/WebFundamentals",
"id": "72eff1dd694b638533874d09401610d3dc5a7fb7",
"size": "1729",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/content/en/tools/lighthouse/audits/plugins.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "34512"
},
{
"name": "HTML",
"bytes": "3375500"
},
{
"name": "JavaScript",
"bytes": "274741"
},
{
"name": "Python",
"bytes": "256072"
},
{
"name": "Shell",
"bytes": "5080"
},
{
"name": "Smarty",
"bytes": "3872"
}
],
"symlink_target": ""
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
Editor, EditorState, ContentState, RichUtils,
getDefaultKeyBinding, KeyBindingUtil,
Entity, convertToRaw, CompositeDecorator
} from 'draft-js';
import {stateToHTML} from 'draft-js-export-html';
/**
* Setup hot keybinding
* Cmd + S
* @param e
* @returns {*}
*/
function myKeyBindingFn(e:SyntheticKeyboardEvent):string {
if (e.keyCode == 83 && KeyBindingUtil.hasCommandModifier(e)) {
return 'save';
}
return getDefaultKeyBinding(e);
}
const findLinkEntities = (contentBlock, callback) => {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
Entity.get(entityKey).getType() === 'LINK'
)
},
callback
)
}
const Link = (props) => {
const {url} = Entity.get(props.entityKey).getData();
return (
<a href={url}>
{props.children}
</a>
)
}
const findUnderlineEntities = (contentBlock,callback) => {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
Entity.get(entityKey).getType() === 'UNDERLINE'
)
},
callback
)
}
const Underline = (props) => {
return (
<u>{props.children}</u>
)
}
export default class EditorLink extends React.Component {
constructor(props) {
super(props);
const decorator = new CompositeDecorator([
{
strategy: findLinkEntities,
component: Link
},
{
strategy: findUnderlineEntities,
component: Underline
}
]);
this.state = {
editorState: EditorState.createEmpty(decorator)
};
this.onChange = (editorState) => this.setState({editorState});
this.focus = () => this.refs.editor.focus();
this.logState = () => {
console.log(this.state.editorState.getCurrentContent());
console.log(ContentState.createFromText('ok i i love it'));
}
}
handleKeyCommand(command) {
const newState = RichUtils.handleKeyCommand(this.state.editorState, command);
console.log(command);
if (newState) {
this.onChange(newState);
return true;
}
return false;
}
_onBoldClick() {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD'));
}
_confirmLink(e) {
e.preventDefault();
const {editorState} = this.state;
const entityKey = Entity.create('LINK', 'SEGMENTED', {url: 'http://gamestudio.vn/public/img/logo.png'});
console.log(editorState.getSelection());
this.setState({
editorState: RichUtils.toggleLink(
editorState,
editorState.getSelection(),
entityKey
)
}, ()=> {
console.log('focus');
setTimeout(()=> this.refs.editor.focus(), 0);
});
}
_confirmUnderline(e){
e.preventDefault();
const entityKey =Entity.create('UNDERLINE','MUTABLE');
this.setState({
editorState: RichUtils.toggleLink(
this.state.editorState,
this.state.editorState.getSelection(),
entityKey
)
});
}
/*<div>
{stateToHTML(this.state.editorState.getCurrentContent())}
</div>
<button onClick={this._confirmUnderline().bind(this)}>Underline</button>
<div onClick={this.focus.bind(this)} style={styles.editor}>
<Editor editorState={editorState}
onChange={this.onChange}
handleKeyCommand={this.handleKeyCommand.bind(this)}
placeholder="Enter some text ..."
keyBindingFn={myKeyBindingFn}
ref="editor"/>
</div>
<button bStyle="primary" onClick={this.logState.bind(this)}>Log state</button>*/
render() {
const {editorState} = this.state;
return (
<div>
<button type="button" onClick={this._confirmUnderline.bind(this)}>Underline</button>
<button onClick={this._onBoldClick.bind(this)}>Bold</button>
<button type="button" onClick={this._confirmLink.bind(this)}>Add l dsink</button>
<div style={styles.editor}>
<Editor editorState={editorState}
onChange={this.onChange}
handleKeyCommand={this.handleKeyCommand.bind(this)}
placeholder="Enter some text ..."
keyBindingFn={myKeyBindingFn}
ref="editor"
contentEditable={true}
disableContentEditableWarning
suppressContentEditableWarning
>
Heleo
</Editor>
</div>
Hello
</div>
)
}
//render(){
// return (
// <div>
// Hello
// <Editor editorState={this.state.editorState}
// placeholder="Enter some text ..."
// ref="editor"/>
// </div>
// )
//}
}
const styles = {
editor: {
border: '1px solid #ccc',
cursor: 'text',
minHeight: 80,
padding: 10
}
}
|
{
"content_hash": "782f2214cdc744b8a85c550c6a9b58c6",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 112,
"avg_line_length": 29.364583333333332,
"alnum_prop": 0.5262504434196523,
"repo_name": "amrit92/educron-ssr",
"id": "e655bfab38d9e9118890f04805a968c10b8fb2ca",
"size": "5638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/form/Editors/EditorLink.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "20553"
},
{
"name": "JavaScript",
"bytes": "160159"
}
],
"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 (version 1.7.0_80) on Sun Oct 23 18:18:18 UTC 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class me.hyperperform.listener.CalendarListener (hyperperform-system 1.0-SNAPSHOT API)</title>
<meta name="date" content="2016-10-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class me.hyperperform.listener.CalendarListener (hyperperform-system 1.0-SNAPSHOT API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../me/hyperperform/listener/CalendarListener.html" title="class in me.hyperperform.listener">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?me/hyperperform/listener/class-use/CalendarListener.html" target="_top">Frames</a></li>
<li><a href="CalendarListener.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class me.hyperperform.listener.CalendarListener" class="title">Uses of Class<br>me.hyperperform.listener.CalendarListener</h2>
</div>
<div class="classUseContainer">No usage of me.hyperperform.listener.CalendarListener</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../me/hyperperform/listener/CalendarListener.html" title="class in me.hyperperform.listener">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?me/hyperperform/listener/class-use/CalendarListener.html" target="_top">Frames</a></li>
<li><a href="CalendarListener.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016. All rights reserved.</small></p>
</body>
</html>
|
{
"content_hash": "a8d2d14b7e4ad6adf0cba30b5c6adacb",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 145,
"avg_line_length": 37.27350427350427,
"alnum_prop": 0.631506535198349,
"repo_name": "HyperPerform/hyperperform.github.io",
"id": "2f0b3abbe95393af349f0f85240be3ef7c23cd70",
"size": "4361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadoc/me/hyperperform/listener/class-use/CalendarListener.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "128889"
},
{
"name": "HTML",
"bytes": "40013"
},
{
"name": "Java",
"bytes": "281859"
},
{
"name": "JavaScript",
"bytes": "1409159"
}
],
"symlink_target": ""
}
|
package com.dremio.exec.physical.config;
import java.util.List;
import com.dremio.common.logical.data.Order.Ordering;
import com.dremio.exec.physical.base.AbstractSingle;
import com.dremio.exec.physical.base.OpProps;
import com.dremio.exec.physical.base.PhysicalOperator;
import com.dremio.exec.physical.base.PhysicalVisitor;
public abstract class AbstractSort extends AbstractSingle{
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractSort.class);
protected final List<Ordering> orderings;
protected final boolean reverse;
public AbstractSort(OpProps props, PhysicalOperator child, List<Ordering> orderings, boolean reverse) {
super(props, child);
this.orderings = orderings;
this.reverse = reverse;
}
public List<Ordering> getOrderings() {
return orderings;
}
public boolean getReverse() {
return reverse;
}
@Override
public <T, X, E extends Throwable> T accept(PhysicalVisitor<T, X, E> physicalVisitor, X value) throws E{
return physicalVisitor.visitSort(this, value);
}
}
|
{
"content_hash": "31b7259a501e3a8f7e0aba6c82ecdf52",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 106,
"avg_line_length": 29.52777777777778,
"alnum_prop": 0.7648165569143932,
"repo_name": "dremio/dremio-oss",
"id": "5be338fe15446c17d50de19a0a09ab548b8cf5ee",
"size": "1673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sabot/kernel/src/main/java/com/dremio/exec/physical/config/AbstractSort.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "47376"
},
{
"name": "Dockerfile",
"bytes": "1668"
},
{
"name": "FreeMarker",
"bytes": "132156"
},
{
"name": "GAP",
"bytes": "15936"
},
{
"name": "HTML",
"bytes": "6544"
},
{
"name": "Java",
"bytes": "39679012"
},
{
"name": "JavaScript",
"bytes": "5439822"
},
{
"name": "Less",
"bytes": "547002"
},
{
"name": "SCSS",
"bytes": "95688"
},
{
"name": "Shell",
"bytes": "16063"
},
{
"name": "TypeScript",
"bytes": "887739"
}
],
"symlink_target": ""
}
|
<?php
namespace Drupal\Tests\node\Kernel;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
/**
* Tests that conditions, provided by the node module, are working properly.
*
* @group node
* @group legacy
*/
class NodeConditionTest extends EntityKernelTestBase {
protected static $modules = ['node'];
protected function setUp(): void {
parent::setUp();
// Create the node bundles required for testing.
$type = NodeType::create(['type' => 'page', 'name' => 'page']);
$type->save();
$type = NodeType::create(['type' => 'article', 'name' => 'article']);
$type->save();
$type = NodeType::create(['type' => 'test', 'name' => 'test']);
$type->save();
}
/**
* Tests conditions.
*/
public function testConditions() {
$this->expectDeprecation('\Drupal\node\Plugin\Condition\NodeType is deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. Use \Drupal\Core\Entity\Plugin\Condition\EntityBundle instead. See https://www.drupal.org/node/2983299');
$manager = $this->container->get('plugin.manager.condition');
$this->createUser();
// Get some nodes of various types to check against.
$page = Node::create(['type' => 'page', 'title' => $this->randomMachineName(), 'uid' => 1]);
$page->save();
$article = Node::create(['type' => 'article', 'title' => $this->randomMachineName(), 'uid' => 1]);
$article->save();
$test = Node::create(['type' => 'test', 'title' => $this->randomMachineName(), 'uid' => 1]);
$test->save();
// Grab the node type condition and configure it to check against node type
// of 'article' and set the context to the page type node.
$condition = $manager->createInstance('node_type')
->setConfig('bundles', ['article' => 'article'])
->setContextValue('node', $page);
$this->assertFalse($condition->execute(), 'Page type nodes fail node type checks for articles.');
// Check for the proper summary.
$this->assertEquals('The node bundle is article', $condition->summary());
// Set the node type check to page.
$condition->setConfig('bundles', ['page' => 'page']);
$this->assertTrue($condition->execute(), 'Page type nodes pass node type checks for pages');
// Check for the proper summary.
$this->assertEquals('The node bundle is page', $condition->summary());
// Set the node type check to page or article.
$condition->setConfig('bundles', ['page' => 'page', 'article' => 'article']);
$this->assertTrue($condition->execute(), 'Page type nodes pass node type checks for pages or articles');
// Check for the proper summary.
$this->assertEquals('The node bundle is page or article', $condition->summary());
// Set the context to the article node.
$condition->setContextValue('node', $article);
$this->assertTrue($condition->execute(), 'Article type nodes pass node type checks for pages or articles');
// Set the context to the test node.
$condition->setContextValue('node', $test);
$this->assertFalse($condition->execute(), 'Test type nodes pass node type checks for pages or articles');
// Check a greater than 2 bundles summary scenario.
$condition->setConfig('bundles', ['page' => 'page', 'article' => 'article', 'test' => 'test']);
$this->assertEquals('The node bundle is page, article or test', $condition->summary());
}
/**
* @group legacy
*/
public function testLegacy() {
$this->expectDeprecation('Passing context values to plugins via configuration is deprecated in drupal:9.1.0 and will be removed before drupal:10.0.0. Instead, call ::setContextValue() on the plugin itself. See https://www.drupal.org/node/3120980');
$manager = $this->container->get('plugin.manager.condition');
$article = Node::create(['type' => 'article', 'title' => $this->randomMachineName(), 'uid' => 1]);
$article->save();
// Test Constructor injection.
$condition = $manager->createInstance('node_type', ['bundles' => ['article' => 'article'], 'context' => ['node' => $article]]);
$this->assertTrue($condition->execute(), 'Constructor injection of context and configuration working as anticipated.');
}
}
|
{
"content_hash": "845f0866c1a9eec408c537ddcca79754",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 252,
"avg_line_length": 44.6,
"alnum_prop": 0.6575407127684683,
"repo_name": "electric-eloquence/fepper-drupal",
"id": "2aa4f0dfb2d7c49988de8d548a1288f4aa34197d",
"size": "4237",
"binary": false,
"copies": "9",
"ref": "refs/heads/dev",
"path": "backend/drupal/core/modules/node/tests/src/Kernel/NodeConditionTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2300765"
},
{
"name": "HTML",
"bytes": "68444"
},
{
"name": "JavaScript",
"bytes": "2453602"
},
{
"name": "Mustache",
"bytes": "40698"
},
{
"name": "PHP",
"bytes": "41684915"
},
{
"name": "PowerShell",
"bytes": "755"
},
{
"name": "Shell",
"bytes": "72896"
},
{
"name": "Stylus",
"bytes": "32803"
},
{
"name": "Twig",
"bytes": "1820730"
},
{
"name": "VBScript",
"bytes": "466"
}
],
"symlink_target": ""
}
|
using AeccApp.Core.Resources;
using System;
using System.Globalization;
using Xamarin.Forms;
namespace AeccApp.Core.Converters
{
public class GenderToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value?.ToString().StartsWith("h", StringComparison.CurrentCultureIgnoreCase) ?? true) ?
ResourcesReference.MAN_ICON : ResourcesReference.GIRL_ICON;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
{
"content_hash": "f3c0d30dcdeab8dbf001f154cda56e93",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 107,
"avg_line_length": 32.38095238095238,
"alnum_prop": 0.6897058823529412,
"repo_name": "BraventIT/AeccApp",
"id": "f6e6acf911d9b7bb8aba1a2ceb3aaacb9f36a07b",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Mobile/AeccApp/AeccApp.Core/Converters/GenderToImageConverter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "101"
},
{
"name": "Batchfile",
"bytes": "591"
},
{
"name": "C#",
"bytes": "729625"
},
{
"name": "CSS",
"bytes": "1304"
},
{
"name": "HTML",
"bytes": "646"
},
{
"name": "JavaScript",
"bytes": "68"
}
],
"symlink_target": ""
}
|
@implementation UINavigationController (animatedNavController)
- (void) pushWithAnim:(UIViewController*)viewController inView:(UIView*)view
{
viewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64.0);
[viewController.view setTransform:CGAffineTransformMakeScale(0.01, 0.01)];
[view addSubview:viewController.view];
[UIView beginAnimations:@"animationExpand" context:viewController];
[UIView setAnimationDuration:0.5];
viewController.view.transform=CGAffineTransformMakeScale(1, 1);
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
}
- (void) pushWithAnim:(UIViewController*)viewController inView:(UIView*)view withAnchor:(CGPoint)anchor
{
viewController.view.layer.anchorPoint = anchor;
viewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64.0);
[viewController.view setTransform:CGAffineTransformMakeScale(0.01, 0.01)];
[view addSubview:viewController.view];
[UIView beginAnimations:@"animationExpand" context:viewController];
[UIView setAnimationDuration:0.5];
viewController.view.transform=CGAffineTransformMakeScale(1, 1);
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
}
- (void) shrinkLastViewController
{
int beforeint = ([[self viewControllers] count]-2);
if(beforeint < 0)
{
return;
}
UIViewController *vc = [[self viewControllers] lastObject];
UIViewController *before = [[self viewControllers] objectAtIndex:beforeint];
[before.view addSubview:vc.view];
[self popViewControllerAnimated:NO];
[UIView beginAnimations:@"animationShrink" context:[vc view]];
[UIView setAnimationDuration:0.5];
[[vc view] setTransform:CGAffineTransformMakeScale(0.01, 0.01)];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
}
- (void) animationDidStop:(NSString *)animationID finished:(BOOL)finished context:(id)context
{
if([animationID isEqualToString:@"animationExpand"])
{
[self pushViewController:context animated:NO];
[context release]; context = nil;
}
else
{
[context removeFromSuperview];
}
}
@end
|
{
"content_hash": "bdd40c617f6289650bb012348488d50d",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 111,
"avg_line_length": 35.083333333333336,
"alnum_prop": 0.7288202692003167,
"repo_name": "CraigMerchant/Expanding-Navigation-Controller",
"id": "1b2417bc1d8d0316908b93c9361431841fe07828",
"size": "2761",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UINavigationController+animatedNavController.m",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
package com.wizzardo.epoll.readable;
import com.wizzardo.tools.misc.Unchecked;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author: wizzardo
* Date: 8/5/14
*/
public class ReadableFile extends ReadableData {
private long offset;
private long length;
private long position;
private RandomAccessFile randomAccessFile;
private FileChannel channel;
public ReadableFile(File file, long offset, long length) throws IOException {
if (offset < 0)
throw new IllegalArgumentException("negative offset: " + offset);
if (length < 0)
throw new IllegalArgumentException("negative length: " + length);
if (offset + length > file.length())
throw new IllegalArgumentException("offset + length > file.length()");
this.offset = offset;
this.length = length;
position = offset;
randomAccessFile = new RandomAccessFile(file, "r");
if (offset > 0)
randomAccessFile.seek(offset);
channel = randomAccessFile.getChannel();
}
@Override
public void close() throws IOException {
randomAccessFile.close();
}
@Override
public int read(ByteBuffer byteBuffer) {
try {
long length = offset + this.length - position;
if (length <= 0)
return 0;
int oldLimit = byteBuffer.limit();
if (length <= byteBuffer.remaining())
byteBuffer.limit((int) (length + byteBuffer.position()));
int read = channel.read(byteBuffer);
byteBuffer.limit(oldLimit);
if (read > 0)
position += read;
return Math.max(0, read);
} catch (IOException e) {
throw Unchecked.rethrow(e);
}
}
@Override
public void unread(int i) {
if (i < 0)
throw new IllegalArgumentException("can't unread negative value: " + i);
if (position - i < offset)
throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
position -= i;
try {
randomAccessFile.seek(position);
} catch (IOException e) {
throw Unchecked.rethrow(e);
}
}
@Override
public boolean isComplete() {
return position == offset + length;
}
@Override
public long complete() {
return position - offset;
}
@Override
public long length() {
return length;
}
@Override
public long remains() {
return length + offset - position;
}
}
|
{
"content_hash": "4e2f662f27abee548baa70358c4f9a62",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 111,
"avg_line_length": 26.980198019801982,
"alnum_prop": 0.5897247706422019,
"repo_name": "wizzardo/epoll",
"id": "cca286a3c6c501ef5c118d0c9fbd2a1d309b27e8",
"size": "2725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/wizzardo/epoll/readable/ReadableFile.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "24810"
},
{
"name": "Java",
"bytes": "118911"
},
{
"name": "Shell",
"bytes": "801"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html>
<head>
<title>Quicksort Proficiency Exercise</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../../JSAV/css/JSAV.css" type="text/css" />
<link rel="stylesheet" href="../../lib/odsaAV-min.css" type="text/css" />
<link rel="stylesheet" href="quicksortPRO.css" type="text/css" />
</head>
<body>
<div id="container">
<table class="proHeaderTable">
<tr>
<td class="headerLeft">
<input type="button" id="help" name="help" value="Help" />
</td>
<td class="headerCenter">
<p class="jsavexercisecontrols"></p>
</td>
<td class="headerRight">
<input type="button" id="about" name="about" value="About" />
<a id="settings" class="jsavsettings" href="#">Settings</a>
</td>
</tr>
</table>
<form class="avcontainer">
<p class="instructLabel">Instructions:</p>
<p class="instructions">
This exercise has you perform all of the steps taken by
Quicksort, except that the details of the partion step are done
for you. Perform your steps according to the highlighted lines in
the code until the array has been sorted. The message above the
array gives more information about how the steps should be done.
<br /><br />
When partitioning, always select the left and right endpoints,
even if they are the same element. When processing a sublist of
length 1, simply mark the element as sorted. When determining
the pivot's final location, treat any elements that match the
pivot as if they were larger than the pivot.
</p>
<p>
<input type="button" id="partition" name="partition" value="Partition" />
<input type="button" id="markSorted" name="markSorted" value="Mark Selected as Sorted" />
<span class="jsavscore"></span>
</p>
<p class="jsavoutput jsavline"></p>
<div id="array" class="jsavcanvas">
</div>
</form>
</div> <!-- container -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="../../JSAV/lib/jquery.transit.js"></script>
<script src="../../JSAV/build/JSAV-min.js"></script>
<script src="../../lib/odsaUtils-min.js"></script>
<script src="../../lib/odsaAV-min.js"></script>
<script src="quicksortCODE.js"></script>
<script src="quicksortAltPRO.js"></script>
</body>
</html>
|
{
"content_hash": "395fdcb61ab6dcf0eae65a3e2f230959",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 95,
"avg_line_length": 37.276923076923076,
"alnum_prop": 0.6413536937680562,
"repo_name": "OpenDSA/OpenDSA-stable",
"id": "730156efe8d0ea932eb25db4d9aca63698d626e8",
"size": "2423",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "AV/Development/quicksortAltPRO.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1946"
},
{
"name": "C++",
"bytes": "47021"
},
{
"name": "CSS",
"bytes": "272288"
},
{
"name": "Groff",
"bytes": "3834"
},
{
"name": "HTML",
"bytes": "3057933"
},
{
"name": "Java",
"bytes": "169267"
},
{
"name": "JavaScript",
"bytes": "6835210"
},
{
"name": "Makefile",
"bytes": "66643"
},
{
"name": "Processing",
"bytes": "158771"
},
{
"name": "Python",
"bytes": "88576"
},
{
"name": "Shell",
"bytes": "2405"
},
{
"name": "TeX",
"bytes": "80510"
}
],
"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_112) on Fri Jun 16 09:55:16 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.wildfly.swarm.messaging (Public javadocs 2017.6.1 API)</title>
<meta name="date" content="2017-06-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.wildfly.swarm.messaging (Public javadocs 2017.6.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.6.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/messaging/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.wildfly.swarm.messaging" class="title">Uses of Package<br>org.wildfly.swarm.messaging</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.messaging">org.wildfly.swarm.messaging</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.messaging">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a> used by <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/EnhancedServer.html#org.wildfly.swarm.messaging">EnhancedServer</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/EnhancedServerConsumer.html#org.wildfly.swarm.messaging">EnhancedServerConsumer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/MessagingFraction.html#org.wildfly.swarm.messaging">MessagingFraction</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/MessagingServer.html#org.wildfly.swarm.messaging">MessagingServer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.html#org.wildfly.swarm.messaging">RemoteConnection</a>
<div class="block">Details for a remote message-queue connection.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.Consumer.html#org.wildfly.swarm.messaging">RemoteConnection.Consumer</a>
<div class="block">Configuration functional interface for container-supplied objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.Supplier.html#org.wildfly.swarm.messaging">RemoteConnection.Supplier</a>
<div class="block">Supplier functional interface for user-supplied object.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.6.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/messaging/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
{
"content_hash": "750820479e8287ecfdf4b1d94858edb9",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 290,
"avg_line_length": 39.08108108108108,
"alnum_prop": 0.6542185338865837,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "8adcec5948ed10abfae639f270bb002db34bbacd",
"size": "7230",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2017.6.1/apidocs/org/wildfly/swarm/messaging/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
package com.wrapper.spotify.exceptions.detailed;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
/**
* The server was acting as a gateway or proxy and received an invalid response from the upstream server.
*/
public class BadGatewayException extends SpotifyWebApiException {
public BadGatewayException() {
super();
}
public BadGatewayException(String message) {
super(message);
}
public BadGatewayException(String message, Throwable cause) {
super(message, cause);
}
}
|
{
"content_hash": "89103194ddc663ebaa16282acc927137",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 105,
"avg_line_length": 23.40909090909091,
"alnum_prop": 0.7553398058252427,
"repo_name": "thelinmichael/spotify-web-api-java",
"id": "31a3e1ab27eeeb3a5bdda43c93eac151fb13cbfa",
"size": "515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/wrapper/spotify/exceptions/detailed/BadGatewayException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "960819"
},
{
"name": "Shell",
"bytes": "213"
}
],
"symlink_target": ""
}
|
package org.jbpm.services.task.audit.service;
import static org.kie.internal.query.QueryParameterIdentifiers.TASK_EVENT_DATE_ID_LIST;
import java.util.Date;
import org.jbpm.process.audit.JPAAuditLogService;
import org.jbpm.process.audit.query.AbstractAuditDeleteBuilderImpl;
import org.jbpm.services.task.audit.impl.model.TaskEventImpl;
import org.kie.api.runtime.CommandExecutor;
import org.kie.internal.task.query.TaskEventDeleteBuilder;
public class TaskEventDeleteBuilderImpl extends AbstractAuditDeleteBuilderImpl<TaskEventDeleteBuilder> implements TaskEventDeleteBuilder {
private static String TASK_EVENT_IMPL_DELETE =
"DELETE\n"
+ "FROM TaskEventImpl l\n";
public TaskEventDeleteBuilderImpl(CommandExecutor cmdExecutor ) {
super(cmdExecutor);
intersect();
}
public TaskEventDeleteBuilderImpl(JPAAuditLogService jpaAuditService) {
super(jpaAuditService);
intersect();
}
@Override
public TaskEventDeleteBuilder date(Date... date) {
if (checkIfNull(date)) {
return this;
}
addObjectParameter(TASK_EVENT_DATE_ID_LIST, "created on date", ensureDateNotTimestamp(date));
return this;
}
@Override
public TaskEventDeleteBuilder dateRangeStart(Date rangeStart) {
if (checkIfNull(rangeStart)) {
return this;
}
addRangeParameter(TASK_EVENT_DATE_ID_LIST, "created on date range end", ensureDateNotTimestamp(rangeStart)[0], true);
return this;
}
@Override
public TaskEventDeleteBuilder dateRangeEnd(Date rangeStart) {
if (checkIfNull(rangeStart)) {
return this;
}
addRangeParameter(TASK_EVENT_DATE_ID_LIST, "created on date range end", ensureDateNotTimestamp(rangeStart)[0], false);
return this;
}
@Override
protected Class getQueryType() {
return TaskEventImpl.class;
}
@Override
protected String getQueryBase() {
return TASK_EVENT_IMPL_DELETE;
}
@Override
protected String getSubQuery() {
return ONLY_COMPLETED_PROCESS_INSTANCES;
}
}
|
{
"content_hash": "43e03a70bd88418cb38d35f564e7d195",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 138,
"avg_line_length": 28.26388888888889,
"alnum_prop": 0.7331695331695331,
"repo_name": "DuncanDoyle/jbpm",
"id": "2a86c2239d8f19872cd265cd96f749fe002d7442",
"size": "2654",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "jbpm-human-task/jbpm-human-task-audit/src/main/java/org/jbpm/services/task/audit/service/TaskEventDeleteBuilderImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "24447"
},
{
"name": "HTML",
"bytes": "271"
},
{
"name": "Java",
"bytes": "14490302"
},
{
"name": "PLSQL",
"bytes": "34719"
},
{
"name": "PLpgSQL",
"bytes": "11997"
},
{
"name": "Shell",
"bytes": "98"
},
{
"name": "Visual Basic",
"bytes": "2545"
}
],
"symlink_target": ""
}
|
Systemd-journald is a system service that collects and stores logging data.
It creates and maintains structured, indexed journals based on logging information from a variety of sources.
## Setup
### Installation
The journald check is included in the [Datadog Agent][1] package.
No additional installation is needed on your server.
### Configuration
Journal files, by default, are owned and readable by the systemd-journal system group. To start collecting your journal logs, you need to:
1. [Install the Agent][2] on the instance running the journal.
2. Add the `dd-agent` user to the `systemd-journal` group by running:
```text
usermod -a -G systemd-journal dd-agent
```
<!-- xxx tabs xxx -->
<!-- xxx tab "Host" xxx -->
To configure this check for an Agent running on a host:
Edit the `journald.d/conf.yaml` file, in the `conf.d/` folder at the root of your [Agent's configuration directory][3] to start collecting logs.
#### Log collection
Collecting logs is disabled by default in the Datadog Agent, you need to enable it in the `datadog.yaml` with:
```yaml
logs_enabled: true
```
Then add this configuration block to your `journald.d/conf.yaml` file to start collecting your Logs:
```yaml
logs:
- type: journald
container_mode: true
```
To fill `source` and `service` attributes, the Agent collects `SYSLOG_IDENTIFIER` , `_SYSTEMD_UNIT` and `_COMM`and set them to the first non empty value. To take advantage of the integration pipelines, Datadog recommends setting the `SyslogIdentifier` parameter in the `systemd` service file directly, or in a `systemd` service override file. Their location depends on your distribution, but you can find the location of the `systemd` service file by using the command `systemctl show -p FragmentPath <unit_name>`.
**Note**: With Agent 7.17+, if `container_mode` is set to `true`, the default behavior changes for logs coming from Docker containers. The `source` attribute of your logs is automatically set to the corresponding short image name of the container instead of simply `docker`.
[Restart the Agent][1].
<!-- xxz tab xxx -->
<!-- xxx tab "Containerized" xxx -->
For containerized environments, see the [Autodiscovery Integration Templates][4] for guidance on applying the parameters below.
#### Log collection
Collecting logs is disabled by default in the Datadog Agent. To enable it, see [Kubernetes Log Collection][5].
| Parameter | Value |
| -------------- | ------------------------------------------------------ |
| `<LOG_CONFIG>` | `{"source": "journald", "service": "<YOUR_APP_NAME>"}` |
<!-- xxz tab xxx -->
<!-- xxz tabs xxx -->
#### Advanced features
##### Change journal location
By default the Agent looks for the journal at the following locations:
- `/var/log/journal`
- `/run/log/journal`
If your journal is located elsewhere, add a `path` parameter with the corresponding journal path.
##### Filter journal units
It's possible to filter in and out specific units by using these parameters:
- `include_units`: Includes all units specified.
- `exclude_units`: Excludes all units specified.
Example:
```yaml
logs:
- type: journald
path: /var/log/journal/
include_units:
- docker.service
- sshd.service
```
##### Collect container tags
Tags are critical for finding information in highly dynamic containerized environments, which is why the Agent can collect container tags in journald logs.
This works automatically when the Agent is running from the host. If you are using the containerized version of the Datadog Agent, mount your journal path and the following file:
- `/etc/machine-id`: this ensures that the Agent can query the journal that is stored on the host.
### Validation
Run the Agent's [status subcommand][6] and look for `journald` under the Logs Agent section.
## Data Collected
### Metrics
journald does not include any metrics.
### Service Checks
journald does not include any service checks.
### Events
journald does not include any events.
## Troubleshooting
Need help? Contact [Datadog support][7].
[1]: https://docs.datadoghq.com/agent/guide/agent-commands/#start-stop-and-restart-the-agent
[2]: https://app.datadoghq.com/account/settings#agent
[3]: https://docs.datadoghq.com/agent/guide/agent-configuration-files/#agent-configuration-directory
[4]: https://docs.datadoghq.com/agent/kubernetes/integrations/
[5]: https://docs.datadoghq.com/agent/kubernetes/log/?tab=containerinstallation#setup
[6]: https://docs.datadoghq.com/agent/guide/agent-commands/#agent-status-and-information
[7]: https://docs.datadoghq.com/help/
|
{
"content_hash": "3f673442fcda37aea120c88d5b888a25",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 514,
"avg_line_length": 34.88805970149254,
"alnum_prop": 0.7191443850267379,
"repo_name": "DataDog/integrations-core",
"id": "14b34c6cc09720ed5d047c015cf6669cd4ae0aa1",
"size": "4719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "journald/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "578"
},
{
"name": "COBOL",
"bytes": "12312"
},
{
"name": "Dockerfile",
"bytes": "22998"
},
{
"name": "Erlang",
"bytes": "15518"
},
{
"name": "Go",
"bytes": "6988"
},
{
"name": "HCL",
"bytes": "4080"
},
{
"name": "HTML",
"bytes": "1318"
},
{
"name": "JavaScript",
"bytes": "1817"
},
{
"name": "Kotlin",
"bytes": "430"
},
{
"name": "Lua",
"bytes": "3489"
},
{
"name": "PHP",
"bytes": "20"
},
{
"name": "PowerShell",
"bytes": "2398"
},
{
"name": "Python",
"bytes": "13020828"
},
{
"name": "Roff",
"bytes": "359"
},
{
"name": "Ruby",
"bytes": "241"
},
{
"name": "Scala",
"bytes": "7000"
},
{
"name": "Shell",
"bytes": "83227"
},
{
"name": "Swift",
"bytes": "203"
},
{
"name": "TSQL",
"bytes": "29972"
},
{
"name": "TypeScript",
"bytes": "1019"
}
],
"symlink_target": ""
}
|
namespace leveldb_proto {
extern const COMPONENT_EXPORT(LEVELDB_PROTO) base::Feature
kProtoDBSharedMigration;
} // namespace leveldb_proto
#endif // COMPONENTS_LEVELDB_PROTO_FEATURE_LIST_H_
|
{
"content_hash": "656a42f2af45555f110fbeba09b7d5cd",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 58,
"avg_line_length": 24.75,
"alnum_prop": 0.7727272727272727,
"repo_name": "endlessm/chromium-browser",
"id": "a4711650e83333c31a3ca2e3e676b4055155da17",
"size": "576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/leveldb_proto/internal/leveldb_proto_feature_list.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
#include "UsbMouse.h"
EFI_DRIVER_BINDING_PROTOCOL gUsbMouseDriverBinding = {
USBMouseDriverBindingSupported,
USBMouseDriverBindingStart,
USBMouseDriverBindingStop,
0xa,
NULL,
NULL
};
/**
Entrypoint of USB Mouse Driver.
This function is the entrypoint of USB Mouse Driver. It installs Driver Binding
Protocols together with Component Name Protocols.
@param ImageHandle The firmware allocated handle for the EFI image.
@param SystemTable A pointer to the EFI System Table.
@retval EFI_SUCCESS The entry point is executed successfully.
**/
EFI_STATUS
EFIAPI
USBMouseDriverBindingEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
Status = EfiLibInstallDriverBindingComponentName2 (
ImageHandle,
SystemTable,
&gUsbMouseDriverBinding,
ImageHandle,
&gUsbMouseComponentName,
&gUsbMouseComponentName2
);
ASSERT_EFI_ERROR (Status);
return EFI_SUCCESS;
}
/**
Check whether USB mouse driver supports this device.
@param This The USB mouse driver binding protocol.
@param Controller The controller handle to check.
@param RemainingDevicePath The remaining device path.
@retval EFI_SUCCESS The driver supports this controller.
@retval other This device isn't supported.
**/
EFI_STATUS
EFIAPI
USBMouseDriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
{
EFI_STATUS Status;
EFI_USB_IO_PROTOCOL *UsbIo;
Status = gBS->OpenProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
(VOID **) &UsbIo,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Use the USB I/O Protocol interface to check whether Controller is
// a mouse device that can be managed by this driver.
//
Status = EFI_SUCCESS;
if (!IsUsbMouse (UsbIo)) {
Status = EFI_UNSUPPORTED;
}
gBS->CloseProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
This->DriverBindingHandle,
Controller
);
return Status;
}
/**
Starts the mouse device with this driver.
This function consumes USB I/O Portocol, intializes USB mouse device,
installs Simple Pointer Protocol, and submits Asynchronous Interrupt
Transfer to manage the USB mouse device.
@param This The USB mouse driver binding instance.
@param Controller Handle of device to bind driver to.
@param RemainingDevicePath Optional parameter use to pick a specific child
device to start.
@retval EFI_SUCCESS This driver supports this device.
@retval EFI_UNSUPPORTED This driver does not support this device.
@retval EFI_DEVICE_ERROR This driver cannot be started due to device Error.
@retval EFI_OUT_OF_RESOURCES Can't allocate memory resources.
@retval EFI_ALREADY_STARTED This driver has been started.
**/
EFI_STATUS
EFIAPI
USBMouseDriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
{
EFI_STATUS Status;
EFI_USB_IO_PROTOCOL *UsbIo;
USB_MOUSE_DEV *UsbMouseDevice;
UINT8 EndpointNumber;
EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor;
UINT8 Index;
UINT8 EndpointAddr;
UINT8 PollingInterval;
UINT8 PacketSize;
BOOLEAN Found;
EFI_TPL OldTpl;
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
//
// Open USB I/O Protocol
//
Status = gBS->OpenProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
(VOID **) &UsbIo,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (Status)) {
goto ErrorExit1;
}
UsbMouseDevice = AllocateZeroPool (sizeof (USB_MOUSE_DEV));
ASSERT (UsbMouseDevice != NULL);
UsbMouseDevice->UsbIo = UsbIo;
UsbMouseDevice->Signature = USB_MOUSE_DEV_SIGNATURE;
//
// Get the Device Path Protocol on Controller's handle
//
Status = gBS->OpenProtocol (
Controller,
&gEfiDevicePathProtocolGuid,
(VOID **) &UsbMouseDevice->DevicePath,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
goto ErrorExit;
}
//
// Get interface & endpoint descriptor
//
UsbIo->UsbGetInterfaceDescriptor (
UsbIo,
&UsbMouseDevice->InterfaceDescriptor
);
EndpointNumber = UsbMouseDevice->InterfaceDescriptor.NumEndpoints;
//
// Traverse endpoints to find interrupt endpoint
//
Found = FALSE;
for (Index = 0; Index < EndpointNumber; Index++) {
UsbIo->UsbGetEndpointDescriptor (
UsbIo,
Index,
&EndpointDescriptor
);
if ((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) {
//
// We only care interrupt endpoint here
//
CopyMem(&UsbMouseDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof(EndpointDescriptor));
Found = TRUE;
break;
}
}
if (!Found) {
//
// No interrupt endpoint found, then return unsupported.
//
Status = EFI_UNSUPPORTED;
goto ErrorExit;
}
Status = InitializeUsbMouseDevice (UsbMouseDevice);
if (EFI_ERROR (Status)) {
//
// Fail to initialize USB mouse device.
//
REPORT_STATUS_CODE_WITH_DEVICE_PATH (
EFI_ERROR_CODE | EFI_ERROR_MINOR,
(EFI_PERIPHERAL_MOUSE | EFI_P_EC_INTERFACE_ERROR),
UsbMouseDevice->DevicePath
);
goto ErrorExit;
}
//
// Initialize and install EFI Simple Pointer Protocol.
//
UsbMouseDevice->SimplePointerProtocol.GetState = GetMouseState;
UsbMouseDevice->SimplePointerProtocol.Reset = UsbMouseReset;
UsbMouseDevice->SimplePointerProtocol.Mode = &UsbMouseDevice->Mode;
Status = gBS->CreateEvent (
EVT_NOTIFY_WAIT,
TPL_NOTIFY,
UsbMouseWaitForInput,
UsbMouseDevice,
&((UsbMouseDevice->SimplePointerProtocol).WaitForInput)
);
if (EFI_ERROR (Status)) {
goto ErrorExit;
}
Status = gBS->InstallProtocolInterface (
&Controller,
&gEfiSimplePointerProtocolGuid,
EFI_NATIVE_INTERFACE,
&UsbMouseDevice->SimplePointerProtocol
);
if (EFI_ERROR (Status)) {
goto ErrorExit;
}
//
// The next step would be submitting Asynchronous Interrupt Transfer on this mouse device.
// After that we will be able to get key data from it. Thus this is deemed as
// the enable action of the mouse, so report status code accordingly.
//
REPORT_STATUS_CODE_WITH_DEVICE_PATH (
EFI_PROGRESS_CODE,
(EFI_PERIPHERAL_MOUSE | EFI_P_PC_ENABLE),
UsbMouseDevice->DevicePath
);
//
// Submit Asynchronous Interrupt Transfer to manage this device.
//
EndpointAddr = UsbMouseDevice->IntEndpointDescriptor.EndpointAddress;
PollingInterval = UsbMouseDevice->IntEndpointDescriptor.Interval;
PacketSize = (UINT8) (UsbMouseDevice->IntEndpointDescriptor.MaxPacketSize);
Status = UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
EndpointAddr,
TRUE,
PollingInterval,
PacketSize,
OnMouseInterruptComplete,
UsbMouseDevice
);
if (EFI_ERROR (Status)) {
//
// If submit error, uninstall that interface
//
gBS->UninstallProtocolInterface (
Controller,
&gEfiSimplePointerProtocolGuid,
&UsbMouseDevice->SimplePointerProtocol
);
goto ErrorExit;
}
UsbMouseDevice->ControllerNameTable = NULL;
AddUnicodeString2 (
"eng",
gUsbMouseComponentName.SupportedLanguages,
&UsbMouseDevice->ControllerNameTable,
L"Generic Usb Mouse",
TRUE
);
AddUnicodeString2 (
"en",
gUsbMouseComponentName2.SupportedLanguages,
&UsbMouseDevice->ControllerNameTable,
L"Generic Usb Mouse",
FALSE
);
gBS->RestoreTPL (OldTpl);
return EFI_SUCCESS;
//
// Error handler
//
ErrorExit:
if (EFI_ERROR (Status)) {
gBS->CloseProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
This->DriverBindingHandle,
Controller
);
if (UsbMouseDevice != NULL) {
if ((UsbMouseDevice->SimplePointerProtocol).WaitForInput != NULL) {
gBS->CloseEvent ((UsbMouseDevice->SimplePointerProtocol).WaitForInput);
}
FreePool (UsbMouseDevice);
UsbMouseDevice = NULL;
}
}
ErrorExit1:
gBS->RestoreTPL (OldTpl);
return Status;
}
/**
Stop the USB mouse device handled by this driver.
@param This The USB mouse driver binding protocol.
@param Controller The controller to release.
@param NumberOfChildren The number of handles in ChildHandleBuffer.
@param ChildHandleBuffer The array of child handle.
@retval EFI_SUCCESS The device was stopped.
@retval EFI_UNSUPPORTED Simple Pointer Protocol is not installed on Controller.
@retval Others Fail to uninstall protocols attached on the device.
**/
EFI_STATUS
EFIAPI
USBMouseDriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
)
{
EFI_STATUS Status;
USB_MOUSE_DEV *UsbMouseDevice;
EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol;
EFI_USB_IO_PROTOCOL *UsbIo;
Status = gBS->OpenProtocol (
Controller,
&gEfiSimplePointerProtocolGuid,
(VOID **) &SimplePointerProtocol,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}
UsbMouseDevice = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (SimplePointerProtocol);
UsbIo = UsbMouseDevice->UsbIo;
//
// The key data input from this device will be disabled.
//
REPORT_STATUS_CODE_WITH_DEVICE_PATH (
EFI_PROGRESS_CODE,
(EFI_PERIPHERAL_MOUSE | EFI_P_PC_DISABLE),
UsbMouseDevice->DevicePath
);
//
// Delete the Asynchronous Interrupt Transfer from this device
//
UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
UsbMouseDevice->IntEndpointDescriptor.EndpointAddress,
FALSE,
UsbMouseDevice->IntEndpointDescriptor.Interval,
0,
NULL,
NULL
);
Status = gBS->UninstallProtocolInterface (
Controller,
&gEfiSimplePointerProtocolGuid,
&UsbMouseDevice->SimplePointerProtocol
);
if (EFI_ERROR (Status)) {
return Status;
}
gBS->CloseProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
This->DriverBindingHandle,
Controller
);
//
// Free all resources.
//
gBS->CloseEvent (UsbMouseDevice->SimplePointerProtocol.WaitForInput);
if (UsbMouseDevice->DelayedRecoveryEvent != NULL) {
gBS->CloseEvent (UsbMouseDevice->DelayedRecoveryEvent);
UsbMouseDevice->DelayedRecoveryEvent = NULL;
}
if (UsbMouseDevice->ControllerNameTable != NULL) {
FreeUnicodeStringTable (UsbMouseDevice->ControllerNameTable);
}
FreePool (UsbMouseDevice);
return EFI_SUCCESS;
}
/**
Uses USB I/O to check whether the device is a USB mouse device.
@param UsbIo Pointer to a USB I/O protocol instance.
@retval TRUE Device is a USB mouse device.
@retval FALSE Device is a not USB mouse device.
**/
BOOLEAN
IsUsbMouse (
IN EFI_USB_IO_PROTOCOL *UsbIo
)
{
EFI_STATUS Status;
EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor;
//
// Get the default interface descriptor
//
Status = UsbIo->UsbGetInterfaceDescriptor (
UsbIo,
&InterfaceDescriptor
);
if (EFI_ERROR (Status)) {
return FALSE;
}
if ((InterfaceDescriptor.InterfaceClass == CLASS_HID) &&
(InterfaceDescriptor.InterfaceSubClass == SUBCLASS_BOOT) &&
(InterfaceDescriptor.InterfaceProtocol == PROTOCOL_MOUSE)
) {
return TRUE;
}
return FALSE;
}
/**
Initialize the USB mouse device.
This function retrieves and parses HID report descriptor, and
initializes state of USB_MOUSE_DEV. Then it sets indefinite idle
rate for the device. Finally it creates event for delayed recovery,
which deals with device error.
@param UsbMouseDev Device instance to be initialized.
@retval EFI_SUCCESS USB mouse device successfully initialized..
@retval EFI_UNSUPPORTED HID descriptor type is not report descriptor.
@retval Other USB mouse device was not initialized successfully.
**/
EFI_STATUS
InitializeUsbMouseDevice (
IN OUT USB_MOUSE_DEV *UsbMouseDev
)
{
EFI_USB_IO_PROTOCOL *UsbIo;
UINT8 Protocol;
EFI_STATUS Status;
EFI_USB_HID_DESCRIPTOR MouseHidDesc;
UINT8 *ReportDesc;
UINT8 ReportId;
UINT8 Duration;
UsbIo = UsbMouseDev->UsbIo;
//
// Get HID descriptor
//
Status = UsbGetHidDescriptor (
UsbIo,
UsbMouseDev->InterfaceDescriptor.InterfaceNumber,
&MouseHidDesc
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Get report descriptor
//
if (MouseHidDesc.HidClassDesc[0].DescriptorType != USB_DESC_TYPE_REPORT) {
return EFI_UNSUPPORTED;
}
ReportDesc = AllocateZeroPool (MouseHidDesc.HidClassDesc[0].DescriptorLength);
ASSERT (ReportDesc != NULL);
Status = UsbGetReportDescriptor (
UsbIo,
UsbMouseDev->InterfaceDescriptor.InterfaceNumber,
MouseHidDesc.HidClassDesc[0].DescriptorLength,
ReportDesc
);
if (EFI_ERROR (Status)) {
FreePool (ReportDesc);
return Status;
}
//
// Parse report descriptor
//
Status = ParseMouseReportDescriptor (
UsbMouseDev,
ReportDesc,
MouseHidDesc.HidClassDesc[0].DescriptorLength
);
if (EFI_ERROR (Status)) {
FreePool (ReportDesc);
return Status;
}
//
// Check the presence of left and right buttons,
// and initialize fields of EFI_SIMPLE_POINTER_MODE.
//
if (UsbMouseDev->NumberOfButtons >= 1) {
UsbMouseDev->Mode.LeftButton = TRUE;
}
if (UsbMouseDev->NumberOfButtons > 1) {
UsbMouseDev->Mode.RightButton = TRUE;
}
UsbMouseDev->Mode.ResolutionX = 8;
UsbMouseDev->Mode.ResolutionY = 8;
UsbMouseDev->Mode.ResolutionZ = 0;
//
// Set boot protocol for the USB mouse.
// This driver only supports boot protocol.
//
UsbGetProtocolRequest (
UsbIo,
UsbMouseDev->InterfaceDescriptor.InterfaceNumber,
&Protocol
);
if (Protocol != BOOT_PROTOCOL) {
Status = UsbSetProtocolRequest (
UsbIo,
UsbMouseDev->InterfaceDescriptor.InterfaceNumber,
BOOT_PROTOCOL
);
if (EFI_ERROR (Status)) {
FreePool (ReportDesc);
return Status;
}
}
//
// ReportId is zero, which means the idle rate applies to all input reports.
//
ReportId = 0;
//
// Duration is zero, which means the duration is infinite.
// so the endpoint will inhibit reporting forever,
// and only reporting when a change is detected in the report data.
//
Duration = 0;
UsbSetIdleRequest (
UsbIo,
UsbMouseDev->InterfaceDescriptor.InterfaceNumber,
ReportId,
Duration
);
FreePool (ReportDesc);
//
// Create event for delayed recovery, which deals with device error.
//
if (UsbMouseDev->DelayedRecoveryEvent != NULL) {
gBS->CloseEvent (UsbMouseDev->DelayedRecoveryEvent);
UsbMouseDev->DelayedRecoveryEvent = 0;
}
gBS->CreateEvent (
EVT_TIMER | EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
USBMouseRecoveryHandler,
UsbMouseDev,
&UsbMouseDev->DelayedRecoveryEvent
);
return EFI_SUCCESS;
}
/**
Handler function for USB mouse's asynchronous interrupt transfer.
This function is the handler function for USB mouse's asynchronous interrupt transfer
to manage the mouse. It parses data returned from asynchronous interrupt transfer, and
get button and movement state.
@param Data A pointer to a buffer that is filled with key data which is
retrieved via asynchronous interrupt transfer.
@param DataLength Indicates the size of the data buffer.
@param Context Pointing to USB_KB_DEV instance.
@param Result Indicates the result of the asynchronous interrupt transfer.
@retval EFI_SUCCESS Asynchronous interrupt transfer is handled successfully.
@retval EFI_DEVICE_ERROR Hardware error occurs.
**/
EFI_STATUS
EFIAPI
OnMouseInterruptComplete (
IN VOID *Data,
IN UINTN DataLength,
IN VOID *Context,
IN UINT32 Result
)
{
USB_MOUSE_DEV *UsbMouseDevice;
EFI_USB_IO_PROTOCOL *UsbIo;
UINT8 EndpointAddr;
UINT32 UsbResult;
UsbMouseDevice = (USB_MOUSE_DEV *) Context;
UsbIo = UsbMouseDevice->UsbIo;
if (Result != EFI_USB_NOERROR) {
//
// Some errors happen during the process
//
REPORT_STATUS_CODE_WITH_DEVICE_PATH (
EFI_ERROR_CODE | EFI_ERROR_MINOR,
(EFI_PERIPHERAL_MOUSE | EFI_P_EC_INPUT_ERROR),
UsbMouseDevice->DevicePath
);
if ((Result & EFI_USB_ERR_STALL) == EFI_USB_ERR_STALL) {
EndpointAddr = UsbMouseDevice->IntEndpointDescriptor.EndpointAddress;
UsbClearEndpointHalt (
UsbIo,
EndpointAddr,
&UsbResult
);
}
//
// Delete & Submit this interrupt again
// Handler of DelayedRecoveryEvent triggered by timer will re-submit the interrupt.
//
UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
UsbMouseDevice->IntEndpointDescriptor.EndpointAddress,
FALSE,
0,
0,
NULL,
NULL
);
//
// EFI_USB_INTERRUPT_DELAY is defined in USB standard for error handling.
//
gBS->SetTimer (
UsbMouseDevice->DelayedRecoveryEvent,
TimerRelative,
EFI_USB_INTERRUPT_DELAY
);
return EFI_DEVICE_ERROR;
}
//
// If no error and no data, just return EFI_SUCCESS.
//
if (DataLength == 0 || Data == NULL) {
return EFI_SUCCESS;
}
UsbMouseDevice->StateChanged = TRUE;
//
// Check mouse Data
// USB HID Specification specifies following data format:
// Byte Bits Description
// 0 0 Button 1
// 1 Button 2
// 2 Button 3
// 4 to 7 Device-specific
// 1 0 to 7 X displacement
// 2 0 to 7 Y displacement
// 3 to n 0 to 7 Device specific (optional)
//
UsbMouseDevice->State.LeftButton = (BOOLEAN) ((*(UINT8 *) Data & BIT0) != 0);
UsbMouseDevice->State.RightButton = (BOOLEAN) ((*(UINT8 *) Data & BIT1) != 0);
UsbMouseDevice->State.RelativeMovementX += *((INT8 *) Data + 1);
UsbMouseDevice->State.RelativeMovementY += *((INT8 *) Data + 2);
if (DataLength > 3) {
UsbMouseDevice->State.RelativeMovementZ += *((INT8 *) Data + 3);
}
return EFI_SUCCESS;
}
/**
Retrieves the current state of a pointer device.
@param This A pointer to the EFI_SIMPLE_POINTER_PROTOCOL instance.
@param MouseState A pointer to the state information on the pointer device.
@retval EFI_SUCCESS The state of the pointer device was returned in State.
@retval EFI_NOT_READY The state of the pointer device has not changed since the last call to
GetState().
@retval EFI_DEVICE_ERROR A device error occurred while attempting to retrieve the pointer device's
current state.
@retval EFI_INVALID_PARAMETER MouseState is NULL.
**/
EFI_STATUS
EFIAPI
GetMouseState (
IN EFI_SIMPLE_POINTER_PROTOCOL *This,
OUT EFI_SIMPLE_POINTER_STATE *MouseState
)
{
USB_MOUSE_DEV *MouseDev;
if (MouseState == NULL) {
return EFI_INVALID_PARAMETER;
}
MouseDev = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (This);
if (!MouseDev->StateChanged) {
return EFI_NOT_READY;
}
//
// Retrieve mouse state from USB_MOUSE_DEV, which was filled by OnMouseInterruptComplete()
//
CopyMem (
MouseState,
&MouseDev->State,
sizeof (EFI_SIMPLE_POINTER_STATE)
);
//
// Clear previous move state
//
MouseDev->State.RelativeMovementX = 0;
MouseDev->State.RelativeMovementY = 0;
MouseDev->State.RelativeMovementZ = 0;
MouseDev->StateChanged = FALSE;
return EFI_SUCCESS;
}
/**
Resets the pointer device hardware.
@param This A pointer to the EFI_SIMPLE_POINTER_PROTOCOL instance.
@param ExtendedVerification Indicates that the driver may perform a more exhaustive
verification operation of the device during reset.
@retval EFI_SUCCESS The device was reset.
@retval EFI_DEVICE_ERROR The device is not functioning correctly and could not be reset.
**/
EFI_STATUS
EFIAPI
UsbMouseReset (
IN EFI_SIMPLE_POINTER_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
)
{
USB_MOUSE_DEV *UsbMouseDevice;
UsbMouseDevice = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (This);
REPORT_STATUS_CODE_WITH_DEVICE_PATH (
EFI_PROGRESS_CODE,
(EFI_PERIPHERAL_MOUSE | EFI_P_PC_RESET),
UsbMouseDevice->DevicePath
);
//
// Clear mouse state.
//
ZeroMem (
&UsbMouseDevice->State,
sizeof (EFI_SIMPLE_POINTER_STATE)
);
UsbMouseDevice->StateChanged = FALSE;
return EFI_SUCCESS;
}
/**
Event notification function for EFI_SIMPLE_POINTER_PROTOCOL.WaitForInput event.
@param Event Event to be signaled when there's input from mouse.
@param Context Points to USB_MOUSE_DEV instance.
**/
VOID
EFIAPI
UsbMouseWaitForInput (
IN EFI_EVENT Event,
IN VOID *Context
)
{
USB_MOUSE_DEV *UsbMouseDev;
UsbMouseDev = (USB_MOUSE_DEV *) Context;
//
// If there's input from mouse, signal the event.
//
if (UsbMouseDev->StateChanged) {
gBS->SignalEvent (Event);
}
}
/**
Handler for Delayed Recovery event.
This function is the handler for Delayed Recovery event triggered
by timer.
After a device error occurs, the event would be triggered
with interval of EFI_USB_INTERRUPT_DELAY. EFI_USB_INTERRUPT_DELAY
is defined in USB standard for error handling.
@param Event The Delayed Recovery event.
@param Context Points to the USB_MOUSE_DEV instance.
**/
VOID
EFIAPI
USBMouseRecoveryHandler (
IN EFI_EVENT Event,
IN VOID *Context
)
{
USB_MOUSE_DEV *UsbMouseDev;
EFI_USB_IO_PROTOCOL *UsbIo;
UsbMouseDev = (USB_MOUSE_DEV *) Context;
UsbIo = UsbMouseDev->UsbIo;
//
// Re-submit Asynchronous Interrupt Transfer for recovery.
//
UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
UsbMouseDev->IntEndpointDescriptor.EndpointAddress,
TRUE,
UsbMouseDev->IntEndpointDescriptor.Interval,
UsbMouseDev->IntEndpointDescriptor.MaxPacketSize,
OnMouseInterruptComplete,
UsbMouseDev
);
}
|
{
"content_hash": "50a4662ba4a6b77c660c6173dcd9794f",
"timestamp": "",
"source": "github",
"line_count": 916,
"max_line_length": 121,
"avg_line_length": 27.189956331877728,
"alnum_prop": 0.6128242190636795,
"repo_name": "egraba/vbox_openbsd",
"id": "13b07d944d8773c109ef72141fa50116768dccf6",
"size": "25477",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "VirtualBox-5.0.0/src/VBox/Devices/EFI/Firmware/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "88714"
},
{
"name": "Assembly",
"bytes": "4303680"
},
{
"name": "AutoIt",
"bytes": "2187"
},
{
"name": "Batchfile",
"bytes": "95534"
},
{
"name": "C",
"bytes": "192632221"
},
{
"name": "C#",
"bytes": "64255"
},
{
"name": "C++",
"bytes": "83842667"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "6041"
},
{
"name": "CSS",
"bytes": "26756"
},
{
"name": "D",
"bytes": "41844"
},
{
"name": "DIGITAL Command Language",
"bytes": "56579"
},
{
"name": "DTrace",
"bytes": "1466646"
},
{
"name": "GAP",
"bytes": "350327"
},
{
"name": "Groff",
"bytes": "298540"
},
{
"name": "HTML",
"bytes": "467691"
},
{
"name": "IDL",
"bytes": "106734"
},
{
"name": "Java",
"bytes": "261605"
},
{
"name": "JavaScript",
"bytes": "80927"
},
{
"name": "Lex",
"bytes": "25122"
},
{
"name": "Logos",
"bytes": "4941"
},
{
"name": "Makefile",
"bytes": "426902"
},
{
"name": "Module Management System",
"bytes": "2707"
},
{
"name": "NSIS",
"bytes": "177212"
},
{
"name": "Objective-C",
"bytes": "5619792"
},
{
"name": "Objective-C++",
"bytes": "81554"
},
{
"name": "PHP",
"bytes": "58585"
},
{
"name": "Pascal",
"bytes": "69941"
},
{
"name": "Perl",
"bytes": "240063"
},
{
"name": "PowerShell",
"bytes": "10664"
},
{
"name": "Python",
"bytes": "9094160"
},
{
"name": "QMake",
"bytes": "3055"
},
{
"name": "R",
"bytes": "21094"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "1460572"
},
{
"name": "SourcePawn",
"bytes": "4139"
},
{
"name": "TypeScript",
"bytes": "142342"
},
{
"name": "Visual Basic",
"bytes": "7161"
},
{
"name": "XSLT",
"bytes": "1034475"
},
{
"name": "Yacc",
"bytes": "22312"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using JetBrains.Annotations;
namespace libsup
{
/// <summary>
/// A single color in a palette.
/// </summary>
[PublicAPI]
public sealed class PaletteEntry
{
/// <summary>
/// Entry number of the palette.
/// </summary>
public byte PaletteEntryId { get; }
/// <summary>
/// Luminance (Y value).
/// </summary>
public byte Luminance { get; }
/// <summary>
/// Color Difference Red (Cr value).
/// </summary>
public byte ColorDifferenceRed { get; }
/// <summary>
/// Color Difference Blue (Cb value).
/// </summary>
public byte ColorDifferenceBlue { get; }
/// <summary>
/// Transparency (Alpha value).
/// </summary>
public byte Transparency { get; }
/// <summary>
/// Converts the color format of the palette entry into a <see cref="System.Drawing.Color"/> structure.
/// </summary>
/// <returns>The <see cref="System.Drawing.Color"/> structure representing the color of this palette
/// entry.</returns>
public Color GetColor()
{
// Convert HDTV YCbCr to RGB.
var y = Luminance - 16;
var cr = ColorDifferenceRed - 128;
var cb = ColorDifferenceBlue - 128;
var r = (byte) Math.Min(Math.Max(Math.Round(1.1644 * y + 1.596 * cr), 0), 255);
var g = (byte) Math.Min(Math.Max(Math.Round(1.1644 * y - 0.813 * cr - 0.391 * cb), 0), 255);
var b = (byte) Math.Min(Math.Max(Math.Round(1.1644 * y + 2.018 * cb), 0), 255);
return Color.FromArgb(Transparency, r, g, b);
}
/// <summary>
/// Create a new palette entry from an array of bytes.
/// </summary>
/// <param name="bytes">The byte collection that should be parsed.</param>
/// <exception cref="InvalidDataException">The given byte array has an invalid amount of data.</exception>
internal PaletteEntry(IReadOnlyList<byte> bytes)
{
// Check for invalid amount of bytes in the given byte collection.
if (bytes.Count != 5)
{
throw new InvalidDataException(
"The given byte array has an invalid amount of data and cannot be parsed as a palette entry!");
}
// Map the byte values in the given collection to their corresponding properties.
PaletteEntryId = bytes[0];
Luminance = bytes[1];
ColorDifferenceRed = bytes[2];
ColorDifferenceBlue = bytes[3];
Transparency = bytes[4];
}
}
}
|
{
"content_hash": "51e845ab3f7cd1ecb4aad195bf5c2123",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 115,
"avg_line_length": 34.8,
"alnum_prop": 0.5531609195402298,
"repo_name": "maki-chan/libsup",
"id": "44dc2c8b77bff362daca065f039055070a36b173",
"size": "2786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libsup/PaletteEntry.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "55112"
}
],
"symlink_target": ""
}
|
/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
#ifdef __cplusplus
extern "C" {
#endif
extern struct SN_env * indonesian_UTF_8_create_env(void);
extern void indonesian_UTF_8_close_env(struct SN_env * z);
extern int indonesian_UTF_8_stem(struct SN_env * z);
#ifdef __cplusplus
}
#endif
|
{
"content_hash": "ffd71498985568d10198de62eb9be780",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 20.266666666666666,
"alnum_prop": 0.7039473684210527,
"repo_name": "tebeka/snowball",
"id": "9f51324ca92708a22d141d561fb2a30734d95dce",
"size": "304",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "stem_UTF_8_indonesian.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1764902"
},
{
"name": "Go",
"bytes": "5073"
},
{
"name": "Shell",
"bytes": "415"
}
],
"symlink_target": ""
}
|
require 'date'
require_relative 'index_page_by_year'
require_relative 'issues'
#
# Matt Parker
# July 27, 2012
#
# Generate indexes by decade.
#
if __FILE__ == $0
xmlFile = "corpus-201208062245.xml"
puts "Building HMTL indexes..."
issues = Issues.new
html = IndexPageByYear.new
issues.index( xmlFile, 1969, 1979 )
html.write( "C:/Projects/communicator/index1970.html", issues )
issues.index( xmlFile, 1980, 1989 )
html.write( "C:/Projects/communicator/index1980.html", issues )
issues.index( xmlFile, 1990, 1999 )
html.write( "C:/Projects/communicator/index1990.html", issues )
issues.index( xmlFile, 2000, 2010 )
html.write( "C:/Projects/communicator/index2000.html", issues )
issues.index( xmlFile, 1969, 2010 )
html.write( "C:/Projects/communicator/indexall.html", issues )
puts "Found #{issues.size} issues"
end
|
{
"content_hash": "fbd40ad8d23b9a0dbd515a08c473a4a0",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 64,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.7124260355029586,
"repo_name": "parker20121/communicator",
"id": "7e39475219307ce71ecf38ef5cb00bf70325f589",
"size": "845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "indexgen.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6081"
}
],
"symlink_target": ""
}
|
class NewoneController < ApplicationController
end
|
{
"content_hash": "4a5b33b151e2a09a554aca93b330df12",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 46,
"avg_line_length": 25.5,
"alnum_prop": 0.8823529411764706,
"repo_name": "alexandernajafi/nifty_stuff",
"id": "620a0e474faec0f067b7ba0596add09038260403",
"size": "51",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "patrik/emacs.d/plugins/rinari/test/rails-app/app/controllers/newone_controller.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3031"
},
{
"name": "CSS",
"bytes": "42977"
},
{
"name": "Emacs Lisp",
"bytes": "8822092"
},
{
"name": "HTML",
"bytes": "763358"
},
{
"name": "Hack",
"bytes": "911"
},
{
"name": "Java",
"bytes": "3175034"
},
{
"name": "JavaScript",
"bytes": "181527"
},
{
"name": "Makefile",
"bytes": "30592"
},
{
"name": "Mako",
"bytes": "457"
},
{
"name": "PHP",
"bytes": "168589"
},
{
"name": "Perl",
"bytes": "318209"
},
{
"name": "Python",
"bytes": "8035"
},
{
"name": "Roff",
"bytes": "3109"
},
{
"name": "Ruby",
"bytes": "55301"
},
{
"name": "Shell",
"bytes": "108289"
},
{
"name": "TeX",
"bytes": "12467"
},
{
"name": "Vim script",
"bytes": "19686"
},
{
"name": "YASnippet",
"bytes": "140157"
}
],
"symlink_target": ""
}
|
```cpp
template<int N=1, typename F>
num::function<double(double)> derivative(F f);
template<int N=1>
vec derivative(vec v);
```
|
{
"content_hash": "3fff8f6b0ebd1553b0de6a78e54183b9",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 46,
"avg_line_length": 14.555555555555555,
"alnum_prop": 0.6870229007633588,
"repo_name": "wenyuzhao/num",
"id": "2757b384eca68408832c75d58d956eb70e42c6bc",
"size": "157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/linalg/derivative.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "75"
},
{
"name": "C",
"bytes": "1399"
},
{
"name": "C++",
"bytes": "122923"
},
{
"name": "Python",
"bytes": "874"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.me.deviceinfo">
<application
android:label="@string/app_name"
android:icon="@drawable/icon">
<activity android:label="@string/app_name" android:name="org.me.deviceinfo.InfoActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="4" />
</manifest>
|
{
"content_hash": "9e7d9b86b5d34702e3ffb859453e3d94",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 93,
"avg_line_length": 40.333333333333336,
"alnum_prop": 0.656198347107438,
"repo_name": "remobjects/ElementsSamples",
"id": "b70dca3b1a5474ddb0dc99a47aa326e3d52073b4",
"size": "605",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Oxygene/Cooper/Android/DeviceInfo/Properties/AndroidManifest.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "8446"
},
{
"name": "C",
"bytes": "1844"
},
{
"name": "C#",
"bytes": "123653"
},
{
"name": "CSS",
"bytes": "435"
},
{
"name": "GLSL",
"bytes": "1486"
},
{
"name": "Go",
"bytes": "513138"
},
{
"name": "HTML",
"bytes": "22290"
},
{
"name": "Java",
"bytes": "51837"
},
{
"name": "Metal",
"bytes": "12625"
},
{
"name": "Objective-C",
"bytes": "4470"
},
{
"name": "Pascal",
"bytes": "1497534"
},
{
"name": "Swift",
"bytes": "76044"
},
{
"name": "Visual Basic .NET",
"bytes": "11935"
}
],
"symlink_target": ""
}
|
package com.intellij.openapi.vfs.impl.jar;
import com.intellij.concurrency.ConcurrentCollectionFactory;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.IntegrityCheckCapableFileSystem;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.impl.ArchiveHandler;
import com.intellij.openapi.vfs.impl.ZipHandler;
import com.intellij.openapi.vfs.impl.ZipHandlerBase;
import com.intellij.openapi.vfs.newvfs.VfsImplUtil;
import com.intellij.util.containers.HashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class JarFileSystemImpl extends JarFileSystem implements IntegrityCheckCapableFileSystem {
private final Set<String> myNoCopyJarPaths;
private final Path myNoCopyJarDir;
public JarFileSystemImpl() {
if (!SystemInfoRt.isWindows) {
myNoCopyJarPaths = null;
}
else if (SystemInfoRt.isFileSystemCaseSensitive) {
//noinspection SSBasedInspection
myNoCopyJarPaths = Collections.newSetFromMap(new ConcurrentHashMap<>());
}
else {
myNoCopyJarPaths = ConcurrentCollectionFactory.createConcurrentSet(HashingStrategy.caseInsensitive());
}
// to prevent platform .jar files from copying
myNoCopyJarDir = Path.of(PathManager.getHomePath());
}
@Override
public void setNoCopyJarForPath(@NotNull String pathInJar) {
if (myNoCopyJarPaths == null) return;
int index = pathInJar.indexOf(JAR_SEPARATOR);
if (index > 0) pathInJar = pathInJar.substring(0, index);
myNoCopyJarPaths.add(new File(pathInJar).getPath());
}
public @Nullable File getMirroredFile(@NotNull VirtualFile file) {
return new File(file.getPath());
}
public boolean isMakeCopyOfJar(@NotNull File originalJar) {
return !(myNoCopyJarPaths == null ||
myNoCopyJarPaths.contains(originalJar.getPath()) ||
originalJar.toPath().startsWith(myNoCopyJarDir));
}
@Override
public @NotNull String getProtocol() {
return PROTOCOL;
}
@Override
public @NotNull String extractPresentableUrl(@NotNull String path) {
return super.extractPresentableUrl(StringUtil.trimEnd(path, JAR_SEPARATOR));
}
@Override
protected @Nullable String normalize(@NotNull String path) {
int separatorIndex = path.indexOf(JAR_SEPARATOR);
return separatorIndex > 0 ? FileUtil.normalize(path.substring(0, separatorIndex)) + path.substring(separatorIndex) : null;
}
@Override
protected @NotNull String extractRootPath(@NotNull String normalizedPath) {
int separatorIndex = normalizedPath.indexOf(JAR_SEPARATOR);
return separatorIndex > 0 ? normalizedPath.substring(0, separatorIndex + JAR_SEPARATOR.length()) : "";
}
@Override
protected @NotNull String extractLocalPath(@NotNull String rootPath) {
return StringUtil.trimEnd(rootPath, JAR_SEPARATOR);
}
@Override
protected @NotNull String composeRootPath(@NotNull String localPath) {
return localPath + JAR_SEPARATOR;
}
@Override
protected @NotNull ArchiveHandler getHandler(@NotNull VirtualFile entryFile) {
return VfsImplUtil.getHandler(this, entryFile, myNoCopyJarPaths == null ? ZipHandler::new : TimedZipHandler::new);
}
@TestOnly
public void markDirtyAndRefreshVirtualFileDeepInsideJarForTest(@NotNull VirtualFile file) {
// clear caches in ArchiveHandler so that refresh will actually refresh something
getHandler(file).clearCaches();
VfsUtil.markDirtyAndRefresh(false, true, true, file);
}
@Override
public VirtualFile findFileByPath(@NotNull String path) {
return isValid(path) ? VfsImplUtil.findFileByPath(this, path) : null;
}
@Override
public VirtualFile findFileByPathIfCached(@NotNull String path) {
return isValid(path) ? VfsImplUtil.findFileByPathIfCached(this, path) : null;
}
@Override
public VirtualFile refreshAndFindFileByPath(@NotNull String path) {
return isValid(path) ? VfsImplUtil.refreshAndFindFileByPath(this, path) : null;
}
private static boolean isValid(String path) {
return path.contains(JAR_SEPARATOR);
}
@Override
public void refresh(boolean asynchronous) {
VfsImplUtil.refresh(this, asynchronous);
}
@TestOnly
public static void cleanupForNextTest() {
TimedZipHandler.closeOpenZipReferences();
}
@Override
public @NotNull Map<String, Long> getArchiveCrcHashes(@NotNull VirtualFile file) throws IOException {
ArchiveHandler handler = getHandler(file);
return ((ZipHandlerBase)handler).getArchiveCrcHashes();
}
}
|
{
"content_hash": "dfbae9a9ddbab714998362e6b1788200",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 126,
"avg_line_length": 34.56551724137931,
"alnum_prop": 0.7627693535514765,
"repo_name": "JetBrains/intellij-community",
"id": "846e07326680d932019839a353054b4fffdc41fb",
"size": "5133",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
<?php
class login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('user');
}
public function index()
{
// get form input
$name = $this->input->post("name");
$password = $this->input->post("password");
// form validation
$this->form_validation->set_rules("name", "Username", "trim|required");
$this->form_validation->set_rules("password", "Password", "trim|required");
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login');
}
else
{
// check for user credentials
$uresult = $this->user->get_user($name, $password);
if (count($uresult) > 0)
{
// set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->name,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
redirect("admin");
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Wrong Email-ID or Password!</div>');
redirect('login/index');
}
}
}
}
|
{
"content_hash": "70bbab3ed3c79c3a6b8a467bffccfff2",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 122,
"avg_line_length": 25.041666666666668,
"alnum_prop": 0.5873544093178037,
"repo_name": "amit15110003/thehippogriff",
"id": "57b944c28cb1760cf948de16985e9904f1be508a",
"size": "1202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "admin/application/controllers/Login.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "399408"
},
{
"name": "HTML",
"bytes": "1976756"
},
{
"name": "JavaScript",
"bytes": "2915653"
},
{
"name": "PHP",
"bytes": "18043350"
}
],
"symlink_target": ""
}
|
ActionMailer::Base.smtp_settings = {
:address => "smtp.psu.edu"
}
|
{
"content_hash": "7e2b2c6c0db128e84ca1c200ef761be2",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 45,
"avg_line_length": 28.333333333333332,
"alnum_prop": 0.5294117647058824,
"repo_name": "neversion/comment_sufia",
"id": "4558e3f427b8789b53bfe21302c9071b9b5e32ba",
"size": "85",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sufia-models/lib/generators/sufia/models/templates/config/setup_mail.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "38769"
},
{
"name": "JavaScript",
"bytes": "30778"
},
{
"name": "Ruby",
"bytes": "426500"
}
],
"symlink_target": ""
}
|
#ifndef __terminal_IF_H
#define __terminal_IF_H 1
#include <flounder/flounder.h>
/*
* Concrete type definitions
*/
typedef uint64_t terminal_genpaddr_t;
typedef uint64_t terminal_genvaddr_t;
typedef uint32_t terminal_rsrcid_t;
typedef uint64_t terminal_errval_t;
typedef uint64_t terminal_cycles_t;
typedef uint32_t terminal_iref_t;
typedef uint8_t terminal_coreid_t;
typedef uint32_t terminal_domainid_t;
/*
* Forward declaration of binding type
*/
struct terminal_binding;
/*
* Contination (callback) and control function types
*/
typedef void terminal_bind_continuation_fn(void *st, errval_t err, struct terminal_binding *_binding);
typedef bool terminal_can_send_fn(struct terminal_binding *_binding);
typedef errval_t terminal_register_send_fn(struct terminal_binding *_binding, struct waitset *ws, struct event_closure _continuation);
typedef errval_t terminal_change_waitset_fn(struct terminal_binding *_binding, struct waitset *ws);
typedef errval_t terminal_control_fn(struct terminal_binding *_binding, idc_control_t control);
typedef void terminal_error_handler_fn(struct terminal_binding *_binding, errval_t err);
/*
* Enumeration for message numbers
*/
typedef enum terminal_msg_enum {
terminal___dummy__msgnum = 0,
terminal_characters__msgnum = 1
} terminal_msg_enum;
/*
* Message type signatures (transmit)
*/
typedef errval_t terminal_characters__tx_method_fn(struct terminal_binding *_binding, struct event_closure _continuation, const char *buffer, size_t length);
/*
* Message type signatures (receive)
*/
typedef void terminal_characters__rx_method_fn(struct terminal_binding *_binding, char *buffer, size_t length);
/*
* Struct type for holding the args for each msg
*/
struct terminal_characters__args {
char *buffer;
size_t length;
};
/*
* Union type for all message arguments
*/
union terminal_arg_union {
struct terminal_characters__args characters;
};
/*
* VTable struct definition for the interface (transmit)
*/
struct terminal_tx_vtbl {
terminal_characters__tx_method_fn *characters;
};
/*
* VTable struct definition for the interface (receive)
*/
struct terminal_rx_vtbl {
terminal_characters__rx_method_fn *characters;
};
/*
* Incoming connect callback type
*/
typedef errval_t terminal_connect_fn(void *st, struct terminal_binding *binding);
/*
* Export state struct
*/
struct terminal_export {
struct idc_export common;
terminal_connect_fn *connect_cb;
struct waitset *waitset;
void *st;
};
/*
* Export function
*/
extern errval_t terminal_export(void *st, idc_export_callback_fn *export_cb, terminal_connect_fn *connect_cb, struct waitset *ws, idc_export_flags_t flags);
/*
* The Binding structure
*/
struct terminal_binding {
/* Arbitrary user state pointer */
void *st;
/* Waitset used for receive handlers and send continuations */
struct waitset *waitset;
/* Mutex for the use of user code. */
/* Must be held before any operation where there is a possibility of */
/* concurrent access to the same binding (eg. multiple threads, or */
/* asynchronous event handlers that use the same binding object). */
struct event_mutex mutex;
/* returns true iff a message could currently be accepted by the binding */
terminal_can_send_fn *can_send;
/* register an event for when a message is likely to be able to be sent */
terminal_register_send_fn *register_send;
/* change the waitset used by a binding */
terminal_change_waitset_fn *change_waitset;
/* perform control operations */
terminal_control_fn *control;
/* error handler for any async errors associated with this binding */
/* must be filled-in by user */
terminal_error_handler_fn *error_handler;
/* Message send functions (filled in by binding) */
struct terminal_tx_vtbl tx_vtbl;
/* Incoming message handlers (filled in by user) */
struct terminal_rx_vtbl rx_vtbl;
/* Private state belonging to the binding implementation */
union terminal_arg_union tx_union;
union terminal_arg_union rx_union;
struct waitset_chanstate register_chanstate;
struct waitset_chanstate tx_cont_chanstate;
enum terminal_msg_enum tx_msgnum;
enum terminal_msg_enum rx_msgnum;
int tx_msg_fragment;
int rx_msg_fragment;
size_t tx_str_pos;
size_t rx_str_pos;
size_t tx_str_len;
size_t rx_str_len;
struct event_queue_node event_qnode;
terminal_bind_continuation_fn *bind_cont;
};
/*
* Generic bind function
*/
extern errval_t terminal_bind(iref_t i, terminal_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags);
/*
* Send wrappers
*/
static inline errval_t terminal_characters__tx(struct terminal_binding *_binding, struct event_closure _continuation, const char *buffer, size_t length) __attribute__ ((always_inline));
static inline errval_t terminal_characters__tx(struct terminal_binding *_binding, struct event_closure _continuation, const char *buffer, size_t length)
{
return(((_binding->tx_vtbl).characters)(_binding, _continuation, buffer, length));
}
/*
* Backend-specific includes
*/
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
#include <if/terminal_lmp_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_LMP
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
#include <if/terminal_ump_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_UMP
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
#include <if/terminal_ump_ipi_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
#include <if/terminal_multihop_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
/*
* And we're done
*/
#endif // __terminal_IF_H
|
{
"content_hash": "b7d4d2cbd8b5350db34b4bc280ede6ee",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 185,
"avg_line_length": 30.306878306878307,
"alnum_prop": 0.7168296089385475,
"repo_name": "daleooo/barrelfish",
"id": "812599b665c5a14bb4367d665fdfb87158b573ea",
"size": "6220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/x86_64/include/if/terminal_defs.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1131283"
},
{
"name": "Awk",
"bytes": "8608"
},
{
"name": "C",
"bytes": "110151643"
},
{
"name": "C++",
"bytes": "2000568"
},
{
"name": "Clojure",
"bytes": "7003"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "Gnuplot",
"bytes": "3830"
},
{
"name": "Haskell",
"bytes": "898395"
},
{
"name": "Objective-C",
"bytes": "117094"
},
{
"name": "Perl",
"bytes": "2717951"
},
{
"name": "Prolog",
"bytes": "2743673"
},
{
"name": "Python",
"bytes": "5352"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Scilab",
"bytes": "5315"
},
{
"name": "Shell",
"bytes": "298866"
},
{
"name": "Tcl",
"bytes": "18591"
},
{
"name": "TeX",
"bytes": "786785"
},
{
"name": "eC",
"bytes": "5079"
}
],
"symlink_target": ""
}
|
#include "squid.h"
#if USE_AUTH
#include "auth/State.h"
CBDATA_NAMESPACED_CLASS_INIT(Auth, StateData);
#endif /* USE_AUTH */
|
{
"content_hash": "dbd19e74820cbf92f958b60c4c27d9a9",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 46,
"avg_line_length": 18.142857142857142,
"alnum_prop": 0.7007874015748031,
"repo_name": "spaceify/spaceify",
"id": "187a83c543b1562b1ebb0ab216167ec7e6582ebc",
"size": "127",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "squid/squid3-3.3.8.spaceify/src/auth/State.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "5027"
},
{
"name": "C",
"bytes": "6727964"
},
{
"name": "C++",
"bytes": "7435855"
},
{
"name": "CSS",
"bytes": "9138"
},
{
"name": "CoffeeScript",
"bytes": "10353"
},
{
"name": "Groff",
"bytes": "253204"
},
{
"name": "HTML",
"bytes": "67045"
},
{
"name": "JavaScript",
"bytes": "559321"
},
{
"name": "M4",
"bytes": "241674"
},
{
"name": "Makefile",
"bytes": "5753890"
},
{
"name": "Objective-C",
"bytes": "1898"
},
{
"name": "Perl",
"bytes": "152532"
},
{
"name": "Python",
"bytes": "60106"
},
{
"name": "Shell",
"bytes": "3088278"
}
],
"symlink_target": ""
}
|
var static = require('node-static');
var file = new static.Server();
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
}).resume();
}).listen(8080);
|
{
"content_hash": "400a811d031d1a2c7dccf18290dc7cfb",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 59,
"avg_line_length": 35.42857142857143,
"alnum_prop": 0.657258064516129,
"repo_name": "angeal185/js-canvas-animations",
"id": "bc92ebd77a15c2cf2cd071a808295fe18eed2f40",
"size": "250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "144"
},
{
"name": "CoffeeScript",
"bytes": "24153"
},
{
"name": "HTML",
"bytes": "17978"
},
{
"name": "JavaScript",
"bytes": "251124"
}
],
"symlink_target": ""
}
|
package security
/**
* Created by gilad on 9/18/14.
*/
// todo: delete. no longer in use
trait AuthorizationService {
// def authorize(path:String, token:Option[String]): Boolean
}
|
{
"content_hash": "0cc1df4631d4da65e009fa1980ace190",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 61,
"avg_line_length": 17.181818181818183,
"alnum_prop": 0.6878306878306878,
"repo_name": "hochgi/CM-Well",
"id": "fc7ef730504621d54be8e5976a0923644f5ee6e1",
"size": "804",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "server/cmwell-ws/app/security/AuthorizationService.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "53"
},
{
"name": "CSS",
"bytes": "165222"
},
{
"name": "Groovy",
"bytes": "5710"
},
{
"name": "HTML",
"bytes": "125489"
},
{
"name": "Java",
"bytes": "3557"
},
{
"name": "JavaScript",
"bytes": "524779"
},
{
"name": "Scala",
"bytes": "3535492"
},
{
"name": "Shell",
"bytes": "15333"
},
{
"name": "XSLT",
"bytes": "2451"
}
],
"symlink_target": ""
}
|
namespace NFleet.Data
{
public class ImportRequest
{
public VehicleSetImportRequest Vehicles { get; set; }
public TaskSetImportRequest Tasks { get; set; }
public ImportDepotSetRequest Depots { get; set; }
}
}
|
{
"content_hash": "43482d109a5a430eac6d89de00d675ff",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 61,
"avg_line_length": 24.7,
"alnum_prop": 0.6558704453441295,
"repo_name": "nfleet/.net-sdk",
"id": "8d4aafbf5cf538591809adfce9c115cf3006eade",
"size": "249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NFleetSDK/Data/ImportRequest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "168364"
}
],
"symlink_target": ""
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.customtabs;
import org.chromium.chrome.browser.metrics.PageLoadMetrics;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.content_public.browser.WebContents;
/**
* Notifies the provided {@link CustomTabObserver} when first meaningful paint occurs.
*/
public class FirstMeaningfulPaintObserver implements PageLoadMetrics.Observer {
private final Tab mTab;
private final CustomTabObserver mCustomTabObserver;
public FirstMeaningfulPaintObserver(CustomTabObserver tabObserver, Tab tab) {
mCustomTabObserver = tabObserver;
mTab = tab;
}
@Override
public void onFirstMeaningfulPaint(WebContents webContents, long navigationId,
long navigationStartTick, long firstContentfulPaintMs) {
if (webContents != mTab.getWebContents()) return;
mCustomTabObserver.onFirstMeaningfulPaint(mTab);
}
}
|
{
"content_hash": "70f5c0430f7c3ae98606643242eb1e80",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 86,
"avg_line_length": 35.9,
"alnum_prop": 0.7632311977715878,
"repo_name": "endlessm/chromium-browser",
"id": "7731ba1abdd422595aab8b46fb063835e23db3a2",
"size": "1077",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chrome/android/java/src/org/chromium/chrome/browser/customtabs/FirstMeaningfulPaintObserver.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
ALTER TABLE playing ADD COLUMN 'activityType' varchar(16) NOT NULL DEFAULT "PLAYING";
INSERT INTO playing (playingString, activityType) VALUES ("the Vytal Festival Tournament", "COMPETING"), ("RWBY", "WATCHING"), ("the RWBY Soundtrack", "LISTENING");
-- Down
BEGIN TRANSACTION;
DELETE FROM playing WHERE activityType != "PLAYING";
CREATE TABLE IF NOT EXISTS `new_playing` (
`playingID` integer NOT NULL PRIMARY KEY AUTOINCREMENT
, `playingString` varchar(64) NOT NULL
);
INSERT INTO new_playing(playingString) SELECT playingString FROM playing;
DROP TABLE playing;
ALTER TABLE new_playing RENAME to playing;
COMMIT;
|
{
"content_hash": "084bcc8453ad24ceaeee3dc23f80b8a9",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 164,
"avg_line_length": 44.214285714285715,
"alnum_prop": 0.7705977382875606,
"repo_name": "Deixel/DeixBot",
"id": "7a61c32abe4aaa9a5cc67316dbdb8d2ab1d57d34",
"size": "625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/migrations/004-new-play-types.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "8488"
},
{
"name": "TypeScript",
"bytes": "23919"
}
],
"symlink_target": ""
}
|
/**
* plugin demo
*/
function demo(state, silent){
console.log(state);
console.log(silent);
}
module.exports = function demo_plugin(md){
md.inline.ruler.before('emphasis', 'demo', demo);
}
|
{
"content_hash": "713b7035975e3d118649b12a255da147",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 51,
"avg_line_length": 15.384615384615385,
"alnum_prop": 0.66,
"repo_name": "demohi/markdown-it-plugin",
"id": "c662484090efaa7b06aba56ebc24951f7d7f8557",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugin-demo.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "650"
}
],
"symlink_target": ""
}
|
import path from 'path'
import fs from 'mz/fs'
import db from '../db'
import { ROOT } from '../config'
const { redis } = db
export default class Resume {
static get() {
return redis.get('resume')
}
static async init() {
redis.del('resume')
const filePath = path.join(ROOT, 'view/resume.md')
const resume = await fs.readFile(filePath)
redis.set('resume', resume.toString())
}
}
Resume.init().catch(error => console.error(error.stack)) // eslint-disable-line no-console
|
{
"content_hash": "f535c2143b6af52720ab8062395fa80c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 90,
"avg_line_length": 23.142857142857142,
"alnum_prop": 0.676954732510288,
"repo_name": "ustccjw/tech-blog",
"id": "d4c9909b21fc98ebb61ff2df4581789b32da91b6",
"size": "486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/model/resume.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2050"
},
{
"name": "HTML",
"bytes": "458"
},
{
"name": "JavaScript",
"bytes": "31736"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Maven artifact details -->
<artifactId>dao-lib</artifactId>
<parent>
<groupId>edu.mit.ll.nics.common</groupId>
<artifactId>master-pom</artifactId>
<version>6.3</version>
<relativePath>..</relativePath>
</parent>
<!-- Project information -->
<name>DAO</name>
<description>Library for building queries and accessing the database</description>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
|
{
"content_hash": "970157308de2565fb2d14dbe10032ca9",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 104,
"avg_line_length": 35.32673267326733,
"alnum_prop": 0.67152466367713,
"repo_name": "hadrsystems/nics-common",
"id": "4c4b4cdbf545ac181a4c41ab70d834c54c788ea0",
"size": "3568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dao/pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "1386041"
},
{
"name": "Scheme",
"bytes": "20331"
}
],
"symlink_target": ""
}
|
class Layou2Generator < Rails::Generator::Base
def manifest
record do |m|
m.template 'initializer.rb', File.join(*%w[config initializers layou2.rb])
end
end
end
|
{
"content_hash": "7a6f1130963bb8ee2a36f3f7328811cf",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 80,
"avg_line_length": 20,
"alnum_prop": 0.6888888888888889,
"repo_name": "grimen/layou2",
"id": "8a830c48aa01839e6725c4ba47a1902e41e51975",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "generators/layou2/layou2_generator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "19263"
}
],
"symlink_target": ""
}
|
///////////////////////////////////////////////////////////////////////////
// __ _ _ ________ //
// / / ____ ____ _(_)____/ | / / ____/ //
// / / / __ \/ __ `/ / ___/ |/ / / __ //
// / /___/ /_/ / /_/ / / /__/ /| / /_/ / //
// /_____/\____/\__, /_/\___/_/ |_/\____/ //
// /____/ //
// //
// The Next Generation Logic Library //
// //
///////////////////////////////////////////////////////////////////////////
// //
// Copyright 2015-20xx Christoph Zengler //
// //
// 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.logicng.knowledgecompilation.bdds.orderings;
import java.util.function.Supplier;
/**
* An enumeration for the different BDD variable orderings. A variable ordering is associated
* with its own provider which can generate orderings for this ordering.
* @version 1.4.0
* @since 1.4.0
*/
public enum VariableOrdering {
DFS(DFSOrdering::new),
BFS(BFSOrdering::new),
MIN2MAX(MinToMaxOrdering::new),
MAX2MIN(MaxToMinOrdering::new),
FORCE(ForceOrdering::new);
private final Supplier<? extends VariableOrderingProvider> provider;
/**
* Constructs a new variable ordering with a given provider.
* @param provider the provider
*/
VariableOrdering(final Supplier<? extends VariableOrderingProvider> provider) {
this.provider = provider;
}
/**
* Returns the provider for this variable ordering.
* @return the provider for this variable ordering
*/
public VariableOrderingProvider provider() {
return this.provider.get();
}
}
|
{
"content_hash": "0907057626ca222e7fe23fa1c4a989a7",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 94,
"avg_line_length": 48.1875,
"alnum_prop": 0.39007782101167315,
"repo_name": "logic-ng/LogicNG",
"id": "4f434ddd371d14e632953543f28091d6dbd11f33",
"size": "3084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/logicng/knowledgecompilation/bdds/orderings/VariableOrdering.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "9714"
},
{
"name": "Java",
"bytes": "3949377"
}
],
"symlink_target": ""
}
|
module Twilio
module REST
class Preview < Domain
class DeployedDevices < Version
class FleetContext < InstanceContext
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
class KeyList < ListResource
##
# Initialize the KeyList
# @param [Version] version Version that contains the resource
# @param [String] fleet_sid Specifies the unique string identifier of the Fleet
# that the given Key credential belongs to.
# @return [KeyList] KeyList
def initialize(version, fleet_sid: nil)
super(version)
# Path Solution
@solution = {fleet_sid: fleet_sid}
@uri = "/Fleets/#{@solution[:fleet_sid]}/Keys"
end
##
# Retrieve a single page of KeyInstance records from the API.
# Request is executed immediately.
# @param [String] friendly_name Provides a human readable descriptive text for
# this Key credential, up to 256 characters long.
# @param [String] device_sid Provides the unique string identifier of an existing
# Device to become authenticated with this Key credential.
# @return [KeyInstance] Newly created KeyInstance
def create(friendly_name: :unset, device_sid: :unset)
data = Twilio::Values.of({'FriendlyName' => friendly_name, 'DeviceSid' => device_sid,})
payload = @version.create(
'POST',
@uri,
data: data
)
KeyInstance.new(@version, payload, fleet_sid: @solution[:fleet_sid],)
end
##
# Lists KeyInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [String] device_sid Filters the resulting list of Keys by a unique string
# identifier of an authenticated Device.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(device_sid: :unset, limit: nil, page_size: nil)
self.stream(device_sid: device_sid, limit: limit, page_size: page_size).entries
end
##
# Streams KeyInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [String] device_sid Filters the resulting list of Keys by a unique string
# identifier of an authenticated Device.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(device_sid: :unset, limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(device_sid: device_sid, page_size: limits[:page_size],)
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields KeyInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size],)
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of KeyInstance records from the API.
# Request is executed immediately.
# @param [String] device_sid Filters the resulting list of Keys by a unique string
# identifier of an authenticated Device.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of KeyInstance
def page(device_sid: :unset, page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'DeviceSid' => device_sid,
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page(
'GET',
@uri,
params
)
KeyPage.new(@version, response, @solution)
end
##
# Retrieve a single page of KeyInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of KeyInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
KeyPage.new(@version, response, @solution)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Preview.DeployedDevices.KeyList>'
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
class KeyPage < Page
##
# Initialize the KeyPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [KeyPage] KeyPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of KeyInstance
# @param [Hash] payload Payload response from the API
# @return [KeyInstance] KeyInstance
def get_instance(payload)
KeyInstance.new(@version, payload, fleet_sid: @solution[:fleet_sid],)
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Preview.DeployedDevices.KeyPage>'
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
class KeyContext < InstanceContext
##
# Initialize the KeyContext
# @param [Version] version Version that contains the resource
# @param [String] fleet_sid The fleet_sid
# @param [String] sid Provides a 34 character string that uniquely identifies the
# requested Key credential resource.
# @return [KeyContext] KeyContext
def initialize(version, fleet_sid, sid)
super(version)
# Path Solution
@solution = {fleet_sid: fleet_sid, sid: sid,}
@uri = "/Fleets/#{@solution[:fleet_sid]}/Keys/#{@solution[:sid]}"
end
##
# Fetch a KeyInstance
# @return [KeyInstance] Fetched KeyInstance
def fetch
params = Twilio::Values.of({})
payload = @version.fetch(
'GET',
@uri,
params,
)
KeyInstance.new(@version, payload, fleet_sid: @solution[:fleet_sid], sid: @solution[:sid],)
end
##
# Deletes the KeyInstance
# @return [Boolean] true if delete succeeds, true otherwise
def delete
@version.delete('delete', @uri)
end
##
# Update the KeyInstance
# @param [String] friendly_name Provides a human readable descriptive text for
# this Key credential, up to 256 characters long.
# @param [String] device_sid Provides the unique string identifier of an existing
# Device to become authenticated with this Key credential.
# @return [KeyInstance] Updated KeyInstance
def update(friendly_name: :unset, device_sid: :unset)
data = Twilio::Values.of({'FriendlyName' => friendly_name, 'DeviceSid' => device_sid,})
payload = @version.update(
'POST',
@uri,
data: data,
)
KeyInstance.new(@version, payload, fleet_sid: @solution[:fleet_sid], sid: @solution[:sid],)
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Preview.DeployedDevices.KeyContext #{context}>"
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
class KeyInstance < InstanceResource
##
# Initialize the KeyInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] fleet_sid Specifies the unique string identifier of the Fleet
# that the given Key credential belongs to.
# @param [String] sid Provides a 34 character string that uniquely identifies the
# requested Key credential resource.
# @return [KeyInstance] KeyInstance
def initialize(version, payload, fleet_sid: nil, sid: nil)
super(version)
# Marshaled Properties
@properties = {
'sid' => payload['sid'],
'url' => payload['url'],
'friendly_name' => payload['friendly_name'],
'fleet_sid' => payload['fleet_sid'],
'account_sid' => payload['account_sid'],
'device_sid' => payload['device_sid'],
'secret' => payload['secret'],
'date_created' => Twilio.deserialize_iso8601_datetime(payload['date_created']),
'date_updated' => Twilio.deserialize_iso8601_datetime(payload['date_updated']),
}
# Context
@instance_context = nil
@params = {'fleet_sid' => fleet_sid, 'sid' => sid || @properties['sid'],}
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [KeyContext] KeyContext for this KeyInstance
def context
unless @instance_context
@instance_context = KeyContext.new(@version, @params['fleet_sid'], @params['sid'],)
end
@instance_context
end
##
# @return [String] A string that uniquely identifies this Key.
def sid
@properties['sid']
end
##
# @return [String] URL of this Key.
def url
@properties['url']
end
##
# @return [String] A human readable description for this Key.
def friendly_name
@properties['friendly_name']
end
##
# @return [String] The unique identifier of the Fleet.
def fleet_sid
@properties['fleet_sid']
end
##
# @return [String] The unique SID that identifies this Account.
def account_sid
@properties['account_sid']
end
##
# @return [String] The unique identifier of a mapped Device.
def device_sid
@properties['device_sid']
end
##
# @return [String] The key secret.
def secret
@properties['secret']
end
##
# @return [Time] The date this Key credential was created.
def date_created
@properties['date_created']
end
##
# @return [Time] The date this Key credential was updated.
def date_updated
@properties['date_updated']
end
##
# Fetch a KeyInstance
# @return [KeyInstance] Fetched KeyInstance
def fetch
context.fetch
end
##
# Deletes the KeyInstance
# @return [Boolean] true if delete succeeds, true otherwise
def delete
context.delete
end
##
# Update the KeyInstance
# @param [String] friendly_name Provides a human readable descriptive text for
# this Key credential, up to 256 characters long.
# @param [String] device_sid Provides the unique string identifier of an existing
# Device to become authenticated with this Key credential.
# @return [KeyInstance] Updated KeyInstance
def update(friendly_name: :unset, device_sid: :unset)
context.update(friendly_name: friendly_name, device_sid: device_sid,)
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Preview.DeployedDevices.KeyInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Preview.DeployedDevices.KeyInstance #{values}>"
end
end
end
end
end
end
end
|
{
"content_hash": "8ff376a4d4adbdf4d054539917ea9acd",
"timestamp": "",
"source": "github",
"line_count": 378,
"max_line_length": 203,
"avg_line_length": 41.526455026455025,
"alnum_prop": 0.5430974071478627,
"repo_name": "Yasu31/TK_1720",
"id": "fa4e99fe803703fa76a82907818a1fe06fa5b37a",
"size": "15805",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/loverduck_app/vendor/bundle/ruby/2.4.0/gems/twilio-ruby-5.4.3/lib/twilio-ruby/rest/preview/deployed_devices/fleet/key.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "7824"
},
{
"name": "CSS",
"bytes": "2779"
},
{
"name": "CoffeeScript",
"bytes": "633"
},
{
"name": "HTML",
"bytes": "16742"
},
{
"name": "JavaScript",
"bytes": "69585"
},
{
"name": "Jupyter Notebook",
"bytes": "256601"
},
{
"name": "Python",
"bytes": "5979"
},
{
"name": "Ruby",
"bytes": "60792"
},
{
"name": "Vue",
"bytes": "34136"
}
],
"symlink_target": ""
}
|
<!--
Copyright (c) 2015-2016 PointSource, LLC.
MIT Licensed
-->
<!--Date out of Bounds warning-->
<div class="reveal large text-center dialog" id="dateWarning" overlay="true" overlay-close="true">
<h4 >Date should be <em>at most</em> 1 month from now and not before today.</h4>
<div data-close class="secondary button">Got it</div>
</div>
<!--Scanner failed in some way-->
<div class="reveal large text-center dialog" id="scannerError" overlay="true" overlay-close="true" >
<h1 class="error-message">Scanner error</h1>
<div data-close class="secondary button">Return</div>
</div>
<!-- Modal to warn users not to update the os version -->
<div class="reveal large dialog" id="doNotUpgradeModal">
<h3>Please do not upgrade this device's OS</h3>
<div data-close style="float: right;">Ok</div>
</div>
<!-- A user has supplied an incorrect asset title when deleting -->
<div id="deleteFailedModal" class="reveal large dialog">
<h2 class="error-message">Incorrect asset title</h2>
<div data-close style="float: right;">Okay</div>
</div>
|
{
"content_hash": "71eecaaa54487a36e6d1a155ed3d23dd",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 100,
"avg_line_length": 38.214285714285715,
"alnum_prop": 0.688785046728972,
"repo_name": "PointSource/checkit-blueoak",
"id": "0fa233eb1676299ec6af8ccc5bf780ddc528880f",
"size": "1070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/app/modals/modals.template.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "69691"
},
{
"name": "HTML",
"bytes": "33716"
},
{
"name": "JavaScript",
"bytes": "253828"
},
{
"name": "Shell",
"bytes": "10710"
}
],
"symlink_target": ""
}
|
package model;
/**
* Represents a turtle or multiple turtles that can receive commands. For
* multiple turtles, commands give the return value for the last active one.
*
* @author Aaron Paskin
* @author Ian Eldridge-Allegra
*/
public interface Turtle {
/**
* @return The id of the turtle
*/
public int getID();
/**
* @return the x coordinate of the turtle
*/
public double getX();
/**
* @return the y coordinate of the turtle
*/
public double getY();
/**
* @return the heading of the turtle
*/
public double getHeading();
/**
* @return whether the pen is done (ie should lines be drawn)
*/
public boolean getPenDown();
/**
* @return whether the turtle is visible
*/
public boolean isVisible();
/**
* @return the index of the pen color being used
*/
public int getPenColorIndex();
/**
* @return the pen size in pixels
*/
public double getPenSize();
/**
* @return the index of the shape
*/
public int getShapeIndex();
/**
* @param par The distance to move, as a command
* @param commands The available commands
* @param variables The available variables
* @return The distance moved
*/
public double forward(Command par, CommandManager commands, VariableManager variables);
/**
* @param input The angle to turn, as a command
* @param commands The available commands
* @param variables The available variables
* @return The angle change
*/
public double left(Command input, CommandManager commands, VariableManager variables);
/**
* @param input The target heading, as a command
* @param commands The available commands
* @param variables The available variables
* @return The angle change
*/
public double setHeading(Command input, CommandManager commands, VariableManager variables);
/**
* @param xCor The target x coordinate, as a command
* @param yCor The target y coordinate, as a command
* @param commands The available commands
* @param variables The available variables
* @return The distance moved
*/
public double setXY(Command xCor, Command yCor, CommandManager commands, VariableManager variables);
/**
* @param xCor The x to point to, as a command
* @param yCor The y to point to, as a command
* @param commands The available commands
* @param variables The available variables
* @return The angle change
*/
public double setTowards(Command xCor, Command yCor, CommandManager commands, VariableManager variables);
/**
* @param b whether the pen should be down
*/
public void setPenDown(boolean b);
/**
* @param index the index of the color to change to
*/
public void setPenColor(int index);
/**
* @param pixels the new pen thickness, in pixels
*/
public void setPenSize(double pixels);
/**
* @param index the index of the background color to change to
*/
public void setBackgroundColor(int index);
/**
* @param b whether the turtle should be visible
*/
public void setVisible(boolean b);
/**
* @param index The index of the shape to use
*/
public void setShapeIndex(int index);
/**
* @return clears the lines from the screen
*/
public double clearScreen();
/**
* @return the number total number of turtles in the model
*/
public int getNumTurtles();
/**
* @param indexVal The index of the color to replace
* @param rVal
* @param gVal
* @param bVal
*/
public void setPalette(int indexVal, int rVal, int gVal, int bVal);
}
|
{
"content_hash": "8306fe3c9f8a188684a655e69fc1aa1d",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 106,
"avg_line_length": 23.58219178082192,
"alnum_prop": 0.6944525123438862,
"repo_name": "tran-d/SLogo",
"id": "11ba317cbba32774064f7cd3228ff05c305a242e",
"size": "3443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/model/Turtle.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2522"
},
{
"name": "Java",
"bytes": "181634"
}
],
"symlink_target": ""
}
|
set -e
function cleanup {
plan_dir="$1"
old_dir="$2"
cd "$plan_dir"
echo "Writing solution to: $output"
cat $(ls "$solution"* | tail -n 1) > "$output"
rm "$solution"*
rm "output" "output.sas" "all.groups" "variables.groups"
cd "$old_dir"
rm -rf "$plan_dir"
exit "$EXIT_STATUS"
}
function plan {
tfd_dir="$1"
domain="$2"
problem="$3"
solution="$4"
config="y+Y+a+e+r+O+1+C+1+b"
if [ $# != 4 ]; then
echo "Usage: plan <tfdDir> <domainFile> <problemFile> <solutionFile>"
else
python "$tfd_dir"/translate/translate.py "$domain" "$problem"
"$tfd_dir"/preprocess/preprocess < "output.sas"
"$tfd_dir"/search/search `echo -n $config | tr '+' ' '` "p" "$solution" < "output"
fi
}
old_dir="`pwd`"
plan_dir="`mktemp`"
rm "$plan_dir"
mkdir -p "$plan_dir"
solution="`mktemp`"
solution="`realpath $solution`"
tfd_dir="$HOME/dev/planners/tfd/tfd-src-0.4/downward"
domain="`realpath $1`"
problem="`realpath $2`"
output="`realpath $3`"
EXIT_STATUS="0"
trap 'pkill -TERM -P $PID; cleanup $plan_dir $old_dir' SIGINT SIGTERM SIGHUP
cd "$plan_dir" && plan "$tfd_dir" "$domain" "$problem" "$solution" &
PID=$!
wait $PID
trap - SIGINT SIGTERM
wait $PID
EXIT_STATUS=$?
cleanup
|
{
"content_hash": "2252a72471c94450b3a90237f3739c96",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 82,
"avg_line_length": 21.181818181818183,
"alnum_prop": 0.648068669527897,
"repo_name": "oskopek/TransportEditor",
"id": "8bc1b38ddf2ba28e264e1204177882b0f707e9b9",
"size": "1177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "transport-planners/src/main/resources/com/oskopek/transport/planners/tfd-plan.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "10460"
},
{
"name": "CSS",
"bytes": "814"
},
{
"name": "FreeMarker",
"bytes": "11453"
},
{
"name": "HTML",
"bytes": "115896"
},
{
"name": "Java",
"bytes": "962140"
},
{
"name": "Makefile",
"bytes": "801"
},
{
"name": "Prolog",
"bytes": "14778"
},
{
"name": "Python",
"bytes": "29590"
},
{
"name": "Shell",
"bytes": "43125"
},
{
"name": "TeX",
"bytes": "532024"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "9b1711a596cf6e1b40bcf37ecae809e6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "8dddcb66d43af0dfa6b9ca8c62d48bdba5dc0d51",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Oreogenia/Oreogenia arassanica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
package com.choudoufu.algorithm.entity;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
/**
* 分页对象
*
* @author xuhaowen
* @create 2017-09-下午 8:35
**/
public class Page<T extends Serializable> {
public static final String ASC = "asc";
public static final String DESC = "desc";
protected int pageNo = 1;
protected int pageSize = 1;
protected String orderBy = null;
protected String order = null;
protected boolean autoCount = true;
protected List<T> result = Collections.emptyList();
protected long totalCount = 0;
public Page() {
}
public Page(int pageSize) {
this.pageSize = pageSize;
}
public Page(int pageSize,int pageNo) {
this.pageSize = pageSize;
this.pageNo = pageNo;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(final int pageNo) {
this.pageNo = pageNo;
if (pageNo < 1) {
this.pageNo = 1;
}
}
public Page<T> pageNo(final int thePageNo) {
setPageNo(thePageNo);
return this;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
if (pageSize < 1) {
this.pageSize = 1;
}
}
public Page<T> pageSize(final int thePageSize) {
setPageSize(thePageSize);
return this;
}
public int getFirstResult() {
return (pageNo - 1) * pageSize;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(final String orderBy) {
this.orderBy = orderBy;
}
public Page<T> orderBy(final String theOrderBy) {
setOrderBy(theOrderBy);
return this;
}
public String getOrder() {
return order;
}
public void setOrder(final String order) {
String[] orders = order.toLowerCase().split(",");
for (String orderStr : orders) {
if (!DESC.equals(orderStr) || !ASC.equals(orderStr))
throw new IllegalArgumentException("order " + orderStr + " illegal");
}
this.order = order.toLowerCase();
}
public Page<T> order(final String theOrder) {
setOrder(theOrder);
return this;
}
public boolean isOrderBySetted() {
return (orderBy!=null && !orderBy.trim().isEmpty()) && (order!=null && !order.trim().isEmpty());
}
public boolean isAutoCount() {
return autoCount;
}
public void setAutoCount(final boolean autoCount) {
this.autoCount = autoCount;
}
public Page<T> autoCount(final boolean theAutoCount) {
setAutoCount(theAutoCount);
return this;
}
public List<T> getResult() {
return result;
}
public void setResult(final List<T> result) {
this.result = result;
}
public long getTotalCount() {
return totalCount;
}
public void setTotalCount(final long totalCount) {
this.totalCount = totalCount;
}
public long getTotalPages() {
if (totalCount <= 0)
return 0;
long count = totalCount / pageSize;
if (totalCount % pageSize > 0) {
count++;
}
return count;
}
public boolean isHasNext() {
return (pageNo + 1 <= getTotalPages());
}
public int getNextPage() {
if (isHasNext())
return pageNo + 1;
else
return pageNo;
}
public boolean isHasPre() {
return (pageNo - 1 >= 1);
}
public int getPrePage() {
if (isHasPre())
return pageNo - 1;
else
return pageNo;
}
}
|
{
"content_hash": "2866833c399db9289603d5661b10552c",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 104,
"avg_line_length": 20.988826815642458,
"alnum_prop": 0.5704019164226777,
"repo_name": "choudou5/algorithm-demo",
"id": "401567f12f1d7fc1c1e3291326243f02b1d8814d",
"size": "3769",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/choudoufu/algorithm/entity/Page.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "171610"
}
],
"symlink_target": ""
}
|
export default class ExecutableCollection extends Array {
populate () {
let promises = this.map(p => p.populate())
return Promise.all(promises)
.then(executables => new ExecutableCollection(...this))
}
executeMerge () {
let tmp = {}
/* Go through every executable... */
for (let e of this) {
let mergeField = e.mergeField
if (!mergeField) {
mergeField = 'error'
}
/* Haven't seen the realpath before? Add as new! */
if (!tmp[mergeField]) {
tmp[mergeField] = e
continue
}
/* Seen it already? Add the path as another 'known' path */
tmp[mergeField].addPath(e.path)
if (e.isDefault && e.defaultCommands.length > 0) {
tmp[mergeField].addCommand(e.defaultCommands[0])
}
}
/* Grab each unique key. Object.values doesn't work */
let uniques = Object.keys(tmp).map(function (key) {
return tmp[key]
})
return new ExecutableCollection(...uniques)
}
merge () {
return new Promise((resolve, reject) => {
let promises = this.map(e => e.assureMergeable())
Promise.all(promises)
.then(() => {
let merged = this.executeMerge()
resolve(merged)
})
.catch()
})
}
}
|
{
"content_hash": "173824efb766256f7c772be209d32feb",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 65,
"avg_line_length": 24.07547169811321,
"alnum_prop": 0.5713166144200627,
"repo_name": "jsoma/mcpyver",
"id": "266e6b465f64daf36767d9eda7301e2f29322a3b",
"size": "1276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/executables/executable_collection.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "57735"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Caliburn.Micro;
using EventAggregatorDemo.Events;
namespace EventAggregatorDemo.ViewModels
{
public class Screen1ViewModel : Screen, IHandle<MainPageButtonPressedEvent>
{
private readonly IEventAggregator _eventAggregator;
private string _eventText;
public string EventText
{
get { return _eventText; }
set
{
_eventText = value;
NotifyOfPropertyChange(() => EventText);
}
}
public Screen1ViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
protected override void OnActivate()
{
base.OnActivate();
_eventAggregator.Subscribe(this);
}
protected override void OnDeactivate(bool close)
{
base.OnDeactivate(close);
_eventAggregator.Unsubscribe(this);
}
public void Handle(MainPageButtonPressedEvent message)
{
EventText = "The button in the appbar has been clicked";
}
}
}
|
{
"content_hash": "1abb99be940a0d419b84378d981e28c5",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 79,
"avg_line_length": 26.244444444444444,
"alnum_prop": 0.5952582557154953,
"repo_name": "delahermosa/EventAggregatorDemo",
"id": "91bc10bd5fbc7e1d10ac3f6a3fc318f85e72e412",
"size": "1183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EventAggregatorDemo/EventAggregatorDemo.Shared/ViewModels/Screen1ViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "18175"
}
],
"symlink_target": ""
}
|
#include <algorithm>
#include <map>
#include <vector>
#include "talk/media/base/testutils.h"
#include "talk/media/base/videoengine_unittest.h"
#include "talk/media/webrtc/fakewebrtcvideoengine.h"
#include "talk/media/webrtc/simulcast.h"
#include "talk/media/webrtc/webrtcvideochannelfactory.h"
#include "talk/media/webrtc/webrtcvideoengine2.h"
#include "talk/media/webrtc/webrtcvideoengine2_unittest.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
#include "webrtc/base/arraysize.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/stringutils.h"
#include "webrtc/video_encoder.h"
namespace {
static const int kDefaultQpMax = 56;
static const int kDefaultFramerate = 30;
static const cricket::VideoCodec kVp8Codec720p(100, "VP8", 1280, 720, 30, 0);
static const cricket::VideoCodec kVp8Codec360p(100, "VP8", 640, 360, 30, 0);
static const cricket::VideoCodec kVp8Codec270p(100, "VP8", 480, 270, 30, 0);
static const cricket::VideoCodec kVp8Codec(100, "VP8", 640, 400, 30, 0);
static const cricket::VideoCodec kVp9Codec(101, "VP9", 640, 400, 30, 0);
static const cricket::VideoCodec kH264Codec(102, "H264", 640, 400, 30, 0);
static const cricket::VideoCodec kRedCodec(116, "red", 0, 0, 0, 0);
static const cricket::VideoCodec kUlpfecCodec(117, "ulpfec", 0, 0, 0, 0);
static const uint32 kSsrcs1[] = {1};
static const uint32 kSsrcs3[] = {1, 2, 3};
static const uint32 kRtxSsrcs1[] = {4};
static const char kUnsupportedExtensionName[] =
"urn:ietf:params:rtp-hdrext:unsupported";
void VerifyCodecHasDefaultFeedbackParams(const cricket::VideoCodec& codec) {
EXPECT_TRUE(codec.HasFeedbackParam(cricket::FeedbackParam(
cricket::kRtcpFbParamNack, cricket::kParamValueEmpty)));
EXPECT_TRUE(codec.HasFeedbackParam(cricket::FeedbackParam(
cricket::kRtcpFbParamNack, cricket::kRtcpFbNackParamPli)));
EXPECT_TRUE(codec.HasFeedbackParam(cricket::FeedbackParam(
cricket::kRtcpFbParamRemb, cricket::kParamValueEmpty)));
EXPECT_TRUE(codec.HasFeedbackParam(cricket::FeedbackParam(
cricket::kRtcpFbParamCcm, cricket::kRtcpFbCcmParamFir)));
}
static void CreateBlackFrame(webrtc::I420VideoFrame* video_frame,
int width,
int height) {
video_frame->CreateEmptyFrame(
width, height, width, (width + 1) / 2, (width + 1) / 2);
memset(video_frame->buffer(webrtc::kYPlane), 16,
video_frame->allocated_size(webrtc::kYPlane));
memset(video_frame->buffer(webrtc::kUPlane), 128,
video_frame->allocated_size(webrtc::kUPlane));
memset(video_frame->buffer(webrtc::kVPlane), 128,
video_frame->allocated_size(webrtc::kVPlane));
}
} // namespace
namespace cricket {
FakeVideoSendStream::FakeVideoSendStream(
const webrtc::VideoSendStream::Config& config,
const webrtc::VideoEncoderConfig& encoder_config)
: sending_(false),
config_(config),
codec_settings_set_(false),
num_swapped_frames_(0) {
assert(config.encoder_settings.encoder != NULL);
ReconfigureVideoEncoder(encoder_config);
}
webrtc::VideoSendStream::Config FakeVideoSendStream::GetConfig() const {
return config_;
}
webrtc::VideoEncoderConfig FakeVideoSendStream::GetEncoderConfig() const {
return encoder_config_;
}
std::vector<webrtc::VideoStream> FakeVideoSendStream::GetVideoStreams() {
return encoder_config_.streams;
}
bool FakeVideoSendStream::IsSending() const {
return sending_;
}
bool FakeVideoSendStream::GetVp8Settings(
webrtc::VideoCodecVP8* settings) const {
if (!codec_settings_set_) {
return false;
}
*settings = vp8_settings_;
return true;
}
int FakeVideoSendStream::GetNumberOfSwappedFrames() const {
return num_swapped_frames_;
}
int FakeVideoSendStream::GetLastWidth() const {
return last_frame_.width();
}
int FakeVideoSendStream::GetLastHeight() const {
return last_frame_.height();
}
void FakeVideoSendStream::SwapFrame(webrtc::I420VideoFrame* frame) {
++num_swapped_frames_;
last_frame_.SwapFrame(frame);
}
void FakeVideoSendStream::SetStats(
const webrtc::VideoSendStream::Stats& stats) {
stats_ = stats;
}
webrtc::VideoSendStream::Stats FakeVideoSendStream::GetStats() {
return stats_;
}
bool FakeVideoSendStream::ReconfigureVideoEncoder(
const webrtc::VideoEncoderConfig& config) {
encoder_config_ = config;
if (config.encoder_specific_settings != NULL) {
assert(config_.encoder_settings.payload_name == "VP8");
vp8_settings_ = *reinterpret_cast<const webrtc::VideoCodecVP8*>(
config.encoder_specific_settings);
}
codec_settings_set_ = config.encoder_specific_settings != NULL;
return true;
}
webrtc::VideoSendStreamInput* FakeVideoSendStream::Input() {
return this;
}
void FakeVideoSendStream::Start() {
sending_ = true;
}
void FakeVideoSendStream::Stop() {
sending_ = false;
}
FakeVideoReceiveStream::FakeVideoReceiveStream(
const webrtc::VideoReceiveStream::Config& config)
: config_(config), receiving_(false) {
}
webrtc::VideoReceiveStream::Config FakeVideoReceiveStream::GetConfig() {
return config_;
}
bool FakeVideoReceiveStream::IsReceiving() const {
return receiving_;
}
void FakeVideoReceiveStream::InjectFrame(const webrtc::I420VideoFrame& frame,
int time_to_render_ms) {
config_.renderer->RenderFrame(frame, time_to_render_ms);
}
webrtc::VideoReceiveStream::Stats FakeVideoReceiveStream::GetStats() const {
return stats_;
}
void FakeVideoReceiveStream::Start() {
receiving_ = true;
}
void FakeVideoReceiveStream::Stop() {
receiving_ = false;
}
void FakeVideoReceiveStream::SetStats(
const webrtc::VideoReceiveStream::Stats& stats) {
stats_ = stats;
}
FakeCall::FakeCall(const webrtc::Call::Config& config)
: config_(config),
network_state_(kNetworkUp),
num_created_send_streams_(0),
num_created_receive_streams_(0) {
SetVideoCodecs(GetDefaultVideoCodecs());
}
FakeCall::~FakeCall() {
EXPECT_EQ(0u, video_send_streams_.size());
EXPECT_EQ(0u, video_receive_streams_.size());
}
void FakeCall::SetVideoCodecs(const std::vector<webrtc::VideoCodec> codecs) {
codecs_ = codecs;
}
webrtc::Call::Config FakeCall::GetConfig() const {
return config_;
}
std::vector<FakeVideoSendStream*> FakeCall::GetVideoSendStreams() {
return video_send_streams_;
}
std::vector<FakeVideoReceiveStream*> FakeCall::GetVideoReceiveStreams() {
return video_receive_streams_;
}
webrtc::VideoCodec FakeCall::GetEmptyVideoCodec() {
webrtc::VideoCodec codec;
codec.minBitrate = 300;
codec.startBitrate = 800;
codec.maxBitrate = 1500;
codec.maxFramerate = 10;
codec.width = 640;
codec.height = 480;
codec.qpMax = 56;
return codec;
}
webrtc::VideoCodec FakeCall::GetVideoCodecVp8() {
webrtc::VideoCodec vp8_codec = GetEmptyVideoCodec();
vp8_codec.codecType = webrtc::kVideoCodecVP8;
rtc::strcpyn(
vp8_codec.plName, ARRAY_SIZE(vp8_codec.plName), kVp8Codec.name.c_str());
vp8_codec.plType = kVp8Codec.id;
return vp8_codec;
}
webrtc::VideoCodec FakeCall::GetVideoCodecVp9() {
webrtc::VideoCodec vp9_codec = GetEmptyVideoCodec();
// TODO(pbos): Add a correct codecType when webrtc has one.
vp9_codec.codecType = webrtc::kVideoCodecVP8;
rtc::strcpyn(
vp9_codec.plName, ARRAY_SIZE(vp9_codec.plName), kVp9Codec.name.c_str());
vp9_codec.plType = kVp9Codec.id;
return vp9_codec;
}
std::vector<webrtc::VideoCodec> FakeCall::GetDefaultVideoCodecs() {
std::vector<webrtc::VideoCodec> codecs;
codecs.push_back(GetVideoCodecVp8());
// codecs.push_back(GetVideoCodecVp9());
return codecs;
}
webrtc::Call::NetworkState FakeCall::GetNetworkState() const {
return network_state_;
}
webrtc::VideoSendStream* FakeCall::CreateVideoSendStream(
const webrtc::VideoSendStream::Config& config,
const webrtc::VideoEncoderConfig& encoder_config) {
FakeVideoSendStream* fake_stream =
new FakeVideoSendStream(config, encoder_config);
video_send_streams_.push_back(fake_stream);
++num_created_send_streams_;
return fake_stream;
}
void FakeCall::DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) {
FakeVideoSendStream* fake_stream =
static_cast<FakeVideoSendStream*>(send_stream);
for (size_t i = 0; i < video_send_streams_.size(); ++i) {
if (video_send_streams_[i] == fake_stream) {
delete video_send_streams_[i];
video_send_streams_.erase(video_send_streams_.begin() + i);
return;
}
}
ADD_FAILURE() << "DestroyVideoSendStream called with unknown paramter.";
}
webrtc::VideoReceiveStream* FakeCall::CreateVideoReceiveStream(
const webrtc::VideoReceiveStream::Config& config) {
video_receive_streams_.push_back(new FakeVideoReceiveStream(config));
++num_created_receive_streams_;
return video_receive_streams_[video_receive_streams_.size() - 1];
}
void FakeCall::DestroyVideoReceiveStream(
webrtc::VideoReceiveStream* receive_stream) {
FakeVideoReceiveStream* fake_stream =
static_cast<FakeVideoReceiveStream*>(receive_stream);
for (size_t i = 0; i < video_receive_streams_.size(); ++i) {
if (video_receive_streams_[i] == fake_stream) {
delete video_receive_streams_[i];
video_receive_streams_.erase(video_receive_streams_.begin() + i);
return;
}
}
ADD_FAILURE() << "DestroyVideoReceiveStream called with unknown paramter.";
}
webrtc::PacketReceiver* FakeCall::Receiver() {
// TODO(pbos): Fix this.
return NULL;
}
void FakeCall::SetStats(const webrtc::Call::Stats& stats) {
stats_ = stats;
}
int FakeCall::GetNumCreatedSendStreams() const {
return num_created_send_streams_;
}
int FakeCall::GetNumCreatedReceiveStreams() const {
return num_created_receive_streams_;
}
webrtc::Call::Stats FakeCall::GetStats() const {
return stats_;
}
void FakeCall::SetBitrateConfig(
const webrtc::Call::Config::BitrateConfig& bitrate_config) {
config_.stream_bitrates = bitrate_config;
}
void FakeCall::SignalNetworkState(webrtc::Call::NetworkState state) {
network_state_ = state;
}
class WebRtcVideoEngine2Test : public ::testing::Test {
public:
WebRtcVideoEngine2Test() {
std::vector<VideoCodec> engine_codecs = engine_.codecs();
assert(!engine_codecs.empty());
bool codec_set = false;
for (size_t i = 0; i < engine_codecs.size(); ++i) {
if (engine_codecs[i].name == "red") {
default_red_codec_ = engine_codecs[i];
} else if (engine_codecs[i].name == "ulpfec") {
default_ulpfec_codec_ = engine_codecs[i];
} else if (engine_codecs[i].name == "rtx") {
default_rtx_codec_ = engine_codecs[i];
} else if (!codec_set) {
default_codec_ = engine_codecs[i];
codec_set = true;
}
}
assert(codec_set);
}
protected:
class FakeCallFactory : public WebRtcCallFactory {
public:
FakeCallFactory() : fake_call_(NULL) {}
FakeCall* GetCall() { return fake_call_; }
private:
virtual webrtc::Call* CreateCall(
const webrtc::Call::Config& config) OVERRIDE {
assert(fake_call_ == NULL);
fake_call_ = new FakeCall(config);
return fake_call_;
}
FakeCall* fake_call_;
};
VideoMediaChannel* SetUpForExternalEncoderFactory(
cricket::WebRtcVideoEncoderFactory* encoder_factory,
const std::vector<VideoCodec>& codecs);
VideoMediaChannel* SetUpForExternalDecoderFactory(
cricket::WebRtcVideoDecoderFactory* decoder_factory,
const std::vector<VideoCodec>& codecs);
WebRtcVideoEngine2 engine_;
VideoCodec default_codec_;
VideoCodec default_red_codec_;
VideoCodec default_ulpfec_codec_;
VideoCodec default_rtx_codec_;
};
TEST_F(WebRtcVideoEngine2Test, ConfiguresAvSyncForFirstReceiveChannel) {
FakeCallFactory call_factory;
engine_.SetCallFactory(&call_factory);
WebRtcVoiceEngine voice_engine;
engine_.SetVoiceEngine(&voice_engine);
voice_engine.Init(rtc::Thread::Current());
engine_.Init(rtc::Thread::Current());
rtc::scoped_ptr<VoiceMediaChannel> voice_channel(
voice_engine.CreateChannel());
ASSERT_TRUE(voice_channel.get() != NULL);
WebRtcVoiceMediaChannel* webrtc_voice_channel =
static_cast<WebRtcVoiceMediaChannel*>(voice_channel.get());
ASSERT_NE(webrtc_voice_channel->voe_channel(), -1);
rtc::scoped_ptr<VideoMediaChannel> channel(
engine_.CreateChannel(cricket::VideoOptions(), voice_channel.get()));
FakeCall* fake_call = call_factory.GetCall();
ASSERT_TRUE(fake_call != NULL);
webrtc::Call::Config call_config = fake_call->GetConfig();
ASSERT_TRUE(voice_engine.voe()->engine() != NULL);
ASSERT_EQ(voice_engine.voe()->engine(), call_config.voice_engine);
EXPECT_TRUE(channel->AddRecvStream(StreamParams::CreateLegacy(kSsrc)));
EXPECT_TRUE(channel->AddRecvStream(StreamParams::CreateLegacy(kSsrc + 1)));
std::vector<FakeVideoReceiveStream*> receive_streams =
fake_call->GetVideoReceiveStreams();
ASSERT_EQ(2u, receive_streams.size());
EXPECT_EQ(webrtc_voice_channel->voe_channel(),
receive_streams[0]->GetConfig().audio_channel_id);
EXPECT_EQ(-1, receive_streams[1]->GetConfig().audio_channel_id)
<< "AV sync should only be set up for the first receive channel.";
}
TEST_F(WebRtcVideoEngine2Test, FindCodec) {
const std::vector<cricket::VideoCodec>& c = engine_.codecs();
EXPECT_EQ(4U, c.size());
cricket::VideoCodec vp8(104, "VP8", 320, 200, 30, 0);
EXPECT_TRUE(engine_.FindCodec(vp8));
cricket::VideoCodec vp8_ci(104, "vp8", 320, 200, 30, 0);
EXPECT_TRUE(engine_.FindCodec(vp8));
cricket::VideoCodec vp8_diff_fr_diff_pref(104, "VP8", 320, 200, 50, 50);
EXPECT_TRUE(engine_.FindCodec(vp8_diff_fr_diff_pref));
cricket::VideoCodec vp8_diff_id(95, "VP8", 320, 200, 30, 0);
EXPECT_FALSE(engine_.FindCodec(vp8_diff_id));
vp8_diff_id.id = 97;
EXPECT_TRUE(engine_.FindCodec(vp8_diff_id));
// FindCodec ignores the codec size.
// Test that FindCodec can accept uncommon codec size.
cricket::VideoCodec vp8_diff_res(104, "VP8", 320, 111, 30, 0);
EXPECT_TRUE(engine_.FindCodec(vp8_diff_res));
// PeerConnection doesn't negotiate the resolution at this point.
// Test that FindCodec can handle the case when width/height is 0.
cricket::VideoCodec vp8_zero_res(104, "VP8", 0, 0, 30, 0);
EXPECT_TRUE(engine_.FindCodec(vp8_zero_res));
cricket::VideoCodec red(101, "RED", 0, 0, 30, 0);
EXPECT_TRUE(engine_.FindCodec(red));
cricket::VideoCodec red_ci(101, "red", 0, 0, 30, 0);
EXPECT_TRUE(engine_.FindCodec(red));
cricket::VideoCodec fec(102, "ULPFEC", 0, 0, 30, 0);
EXPECT_TRUE(engine_.FindCodec(fec));
cricket::VideoCodec fec_ci(102, "ulpfec", 0, 0, 30, 0);
EXPECT_TRUE(engine_.FindCodec(fec));
cricket::VideoCodec rtx(96, "rtx", 0, 0, 30, 0);
EXPECT_TRUE(engine_.FindCodec(rtx));
}
TEST_F(WebRtcVideoEngine2Test, DefaultRtxCodecHasAssociatedPayloadTypeSet) {
std::vector<VideoCodec> engine_codecs = engine_.codecs();
for (size_t i = 0; i < engine_codecs.size(); ++i) {
if (engine_codecs[i].name != kRtxCodecName)
continue;
int associated_payload_type;
EXPECT_TRUE(engine_codecs[i].GetParam(kCodecParamAssociatedPayloadType,
&associated_payload_type));
EXPECT_EQ(default_codec_.id, associated_payload_type);
return;
}
FAIL() << "No RTX codec found among default codecs.";
}
TEST_F(WebRtcVideoEngine2Test, SupportsTimestampOffsetHeaderExtension) {
std::vector<RtpHeaderExtension> extensions = engine_.rtp_header_extensions();
ASSERT_FALSE(extensions.empty());
for (size_t i = 0; i < extensions.size(); ++i) {
if (extensions[i].uri == kRtpTimestampOffsetHeaderExtension) {
EXPECT_EQ(kRtpTimestampOffsetHeaderExtensionDefaultId, extensions[i].id);
return;
}
}
FAIL() << "Timestamp offset extension not in header-extension list.";
}
TEST_F(WebRtcVideoEngine2Test, SupportsAbsoluteSenderTimeHeaderExtension) {
std::vector<RtpHeaderExtension> extensions = engine_.rtp_header_extensions();
ASSERT_FALSE(extensions.empty());
for (size_t i = 0; i < extensions.size(); ++i) {
if (extensions[i].uri == kRtpAbsoluteSenderTimeHeaderExtension) {
EXPECT_EQ(kRtpAbsoluteSenderTimeHeaderExtensionDefaultId,
extensions[i].id);
return;
}
}
FAIL() << "Absolute Sender Time extension not in header-extension list.";
}
TEST_F(WebRtcVideoEngine2Test, SetSendFailsBeforeSettingCodecs) {
engine_.Init(rtc::Thread::Current());
rtc::scoped_ptr<VideoMediaChannel> channel(
engine_.CreateChannel(cricket::VideoOptions(), NULL));
EXPECT_TRUE(channel->AddSendStream(StreamParams::CreateLegacy(123)));
EXPECT_FALSE(channel->SetSend(true))
<< "Channel should not start without codecs.";
EXPECT_TRUE(channel->SetSend(false))
<< "Channel should be stoppable even without set codecs.";
}
TEST_F(WebRtcVideoEngine2Test, GetStatsWithoutSendCodecsSetDoesNotCrash) {
engine_.Init(rtc::Thread::Current());
rtc::scoped_ptr<VideoMediaChannel> channel(
engine_.CreateChannel(cricket::VideoOptions(), NULL));
EXPECT_TRUE(channel->AddSendStream(StreamParams::CreateLegacy(123)));
VideoMediaInfo info;
channel->GetStats(&info);
}
TEST_F(WebRtcVideoEngine2Test, UseExternalFactoryForVp8WhenSupported) {
cricket::FakeWebRtcVideoEncoderFactory encoder_factory;
encoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecVP8, "VP8");
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
rtc::scoped_ptr<VideoMediaChannel> channel(
SetUpForExternalEncoderFactory(&encoder_factory, codecs));
EXPECT_TRUE(
channel->AddSendStream(cricket::StreamParams::CreateLegacy(kSsrc)));
ASSERT_EQ(1u, encoder_factory.encoders().size());
EXPECT_TRUE(channel->SetSend(true));
cricket::FakeVideoCapturer capturer;
EXPECT_TRUE(channel->SetCapturer(kSsrc, &capturer));
EXPECT_EQ(cricket::CS_RUNNING,
capturer.Start(capturer.GetSupportedFormats()->front()));
EXPECT_TRUE(capturer.CaptureFrame());
EXPECT_TRUE_WAIT(encoder_factory.encoders()[0]->GetNumEncodedFrames() > 0,
kTimeout);
// Sending one frame will have reallocated the encoder since input size
// changes from a small default to the actual frame width/height.
int num_created_encoders = encoder_factory.GetNumCreatedEncoders();
EXPECT_EQ(num_created_encoders, 2);
// Setting codecs of the same type should not reallocate any encoders
// (expecting a no-op).
EXPECT_TRUE(channel->SetSendCodecs(codecs));
EXPECT_EQ(num_created_encoders, encoder_factory.GetNumCreatedEncoders());
// Remove stream previously added to free the external encoder instance.
EXPECT_TRUE(channel->RemoveSendStream(kSsrc));
EXPECT_EQ(0u, encoder_factory.encoders().size());
}
VideoMediaChannel* WebRtcVideoEngine2Test::SetUpForExternalEncoderFactory(
cricket::WebRtcVideoEncoderFactory* encoder_factory,
const std::vector<VideoCodec>& codecs) {
engine_.SetExternalEncoderFactory(encoder_factory);
engine_.Init(rtc::Thread::Current());
VideoMediaChannel* channel =
engine_.CreateChannel(cricket::VideoOptions(), NULL);
EXPECT_TRUE(channel->SetSendCodecs(codecs));
return channel;
}
VideoMediaChannel* WebRtcVideoEngine2Test::SetUpForExternalDecoderFactory(
cricket::WebRtcVideoDecoderFactory* decoder_factory,
const std::vector<VideoCodec>& codecs) {
engine_.SetExternalDecoderFactory(decoder_factory);
engine_.Init(rtc::Thread::Current());
VideoMediaChannel* channel =
engine_.CreateChannel(cricket::VideoOptions(), NULL);
EXPECT_TRUE(channel->SetRecvCodecs(codecs));
return channel;
}
TEST_F(WebRtcVideoEngine2Test, UsesSimulcastAdapterForVp8Factories) {
cricket::FakeWebRtcVideoEncoderFactory encoder_factory;
encoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecVP8, "VP8");
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
rtc::scoped_ptr<VideoMediaChannel> channel(
SetUpForExternalEncoderFactory(&encoder_factory, codecs));
std::vector<uint32> ssrcs = MAKE_VECTOR(kSsrcs3);
EXPECT_TRUE(
channel->AddSendStream(CreateSimStreamParams("cname", ssrcs)));
EXPECT_TRUE(channel->SetSend(true));
cricket::FakeVideoCapturer capturer;
EXPECT_TRUE(channel->SetCapturer(ssrcs.front(), &capturer));
EXPECT_EQ(cricket::CS_RUNNING,
capturer.Start(capturer.GetSupportedFormats()->front()));
EXPECT_TRUE(capturer.CaptureFrame());
EXPECT_GT(encoder_factory.encoders().size(), 1u);
// Verify that encoders are configured for simulcast through adapter
// (increasing resolution and only configured to send one stream each).
int prev_width = -1;
for (size_t i = 0; i < encoder_factory.encoders().size(); ++i) {
webrtc::VideoCodec codec_settings =
encoder_factory.encoders()[i]->GetCodecSettings();
EXPECT_EQ(0, codec_settings.numberOfSimulcastStreams);
EXPECT_GT(codec_settings.width, prev_width);
prev_width = codec_settings.width;
}
EXPECT_TRUE(channel->SetCapturer(ssrcs.front(), NULL));
}
TEST_F(WebRtcVideoEngine2Test, ChannelWithExternalH264CanChangeToInternalVp8) {
cricket::FakeWebRtcVideoEncoderFactory encoder_factory;
encoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kH264Codec);
rtc::scoped_ptr<VideoMediaChannel> channel(
SetUpForExternalEncoderFactory(&encoder_factory, codecs));
EXPECT_TRUE(
channel->AddSendStream(cricket::StreamParams::CreateLegacy(kSsrc)));
ASSERT_EQ(1u, encoder_factory.encoders().size());
codecs.clear();
codecs.push_back(kVp8Codec);
EXPECT_TRUE(channel->SetSendCodecs(codecs));
ASSERT_EQ(0u, encoder_factory.encoders().size());
}
TEST_F(WebRtcVideoEngine2Test,
DontUseExternalEncoderFactoryForUnsupportedCodecs) {
cricket::FakeWebRtcVideoEncoderFactory encoder_factory;
encoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
rtc::scoped_ptr<VideoMediaChannel> channel(
SetUpForExternalEncoderFactory(&encoder_factory, codecs));
EXPECT_TRUE(
channel->AddSendStream(cricket::StreamParams::CreateLegacy(kSsrc)));
ASSERT_EQ(0u, encoder_factory.encoders().size());
}
// Test external codec with be added to the end of the supported codec list.
TEST_F(WebRtcVideoEngine2Test, ReportSupportedExternalCodecs) {
cricket::FakeWebRtcVideoEncoderFactory encoder_factory;
encoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
engine_.SetExternalEncoderFactory(&encoder_factory);
engine_.Init(rtc::Thread::Current());
std::vector<cricket::VideoCodec> codecs(engine_.codecs());
ASSERT_GE(codecs.size(), 2u);
cricket::VideoCodec internal_codec = codecs.front();
cricket::VideoCodec external_codec = codecs.back();
// The external codec will appear at last.
EXPECT_EQ("VP8", internal_codec.name);
EXPECT_EQ("H264", external_codec.name);
}
TEST_F(WebRtcVideoEngine2Test, RegisterExternalDecodersIfSupported) {
cricket::FakeWebRtcVideoDecoderFactory decoder_factory;
decoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecVP8);
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
rtc::scoped_ptr<VideoMediaChannel> channel(
SetUpForExternalDecoderFactory(&decoder_factory, codecs));
EXPECT_TRUE(
channel->AddRecvStream(cricket::StreamParams::CreateLegacy(kSsrc)));
ASSERT_EQ(1u, decoder_factory.decoders().size());
// Setting codecs of the same type should not reallocate the decoder.
EXPECT_TRUE(channel->SetRecvCodecs(codecs));
EXPECT_EQ(1, decoder_factory.GetNumCreatedDecoders());
// Remove stream previously added to free the external decoder instance.
EXPECT_TRUE(channel->RemoveRecvStream(kSsrc));
EXPECT_EQ(0u, decoder_factory.decoders().size());
}
// Verifies that we can set up decoders that are not internally supported.
TEST_F(WebRtcVideoEngine2Test, RegisterExternalH264DecoderIfSupported) {
// TODO(pbos): Do not assume that encoder/decoder support is symmetric. We
// can't even query the WebRtcVideoDecoderFactory for supported codecs.
// For now we add a FakeWebRtcVideoEncoderFactory to add H264 to supported
// codecs.
cricket::FakeWebRtcVideoEncoderFactory encoder_factory;
encoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
engine_.SetExternalEncoderFactory(&encoder_factory);
cricket::FakeWebRtcVideoDecoderFactory decoder_factory;
decoder_factory.AddSupportedVideoCodecType(webrtc::kVideoCodecH264);
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kH264Codec);
rtc::scoped_ptr<VideoMediaChannel> channel(
SetUpForExternalDecoderFactory(&decoder_factory, codecs));
EXPECT_TRUE(
channel->AddRecvStream(cricket::StreamParams::CreateLegacy(kSsrc)));
ASSERT_EQ(1u, decoder_factory.decoders().size());
}
class WebRtcVideoEngine2BaseTest
: public VideoEngineTest<cricket::WebRtcVideoEngine2> {
protected:
typedef VideoEngineTest<cricket::WebRtcVideoEngine2> Base;
};
#define WEBRTC_ENGINE_BASE_TEST(test) \
TEST_F(WebRtcVideoEngine2BaseTest, test) { Base::test##Body(); }
WEBRTC_ENGINE_BASE_TEST(ConstrainNewCodec2);
class WebRtcVideoChannel2BaseTest
: public VideoMediaChannelTest<WebRtcVideoEngine2, WebRtcVideoChannel2> {
protected:
typedef VideoMediaChannelTest<WebRtcVideoEngine2, WebRtcVideoChannel2> Base;
virtual cricket::VideoCodec DefaultCodec() OVERRIDE { return kVp8Codec; }
};
#define WEBRTC_BASE_TEST(test) \
TEST_F(WebRtcVideoChannel2BaseTest, test) { Base::test(); }
#define WEBRTC_DISABLED_BASE_TEST(test) \
TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_##test) { Base::test(); }
// TODO(pbos): Fix WebRtcVideoEngine2BaseTest, where we want CheckCoInitialize.
#if 0
// TODO(juberti): Figure out why ViE is munging the COM refcount.
#ifdef WIN32
WEBRTC_DISABLED_BASE_TEST(CheckCoInitialize) {
Base::CheckCoInitialize();
}
#endif
#endif
WEBRTC_BASE_TEST(SetSend);
WEBRTC_BASE_TEST(SetSendWithoutCodecs);
WEBRTC_BASE_TEST(SetSendSetsTransportBufferSizes);
WEBRTC_BASE_TEST(GetStats);
WEBRTC_BASE_TEST(GetStatsMultipleRecvStreams);
WEBRTC_BASE_TEST(GetStatsMultipleSendStreams);
WEBRTC_BASE_TEST(SetSendBandwidth);
WEBRTC_BASE_TEST(SetSendSsrc);
WEBRTC_BASE_TEST(SetSendSsrcAfterSetCodecs);
WEBRTC_BASE_TEST(SetRenderer);
WEBRTC_BASE_TEST(AddRemoveRecvStreams);
WEBRTC_DISABLED_BASE_TEST(AddRemoveRecvStreamAndRender);
WEBRTC_BASE_TEST(AddRemoveRecvStreamsNoConference);
WEBRTC_BASE_TEST(AddRemoveSendStreams);
WEBRTC_BASE_TEST(SimulateConference);
WEBRTC_BASE_TEST(AddRemoveCapturer);
WEBRTC_BASE_TEST(RemoveCapturerWithoutAdd);
WEBRTC_BASE_TEST(AddRemoveCapturerMultipleSources);
// TODO(pbos): Figure out why this fails so often.
WEBRTC_DISABLED_BASE_TEST(HighAspectHighHeightCapturer);
WEBRTC_BASE_TEST(RejectEmptyStreamParams);
WEBRTC_BASE_TEST(AdaptResolution16x10);
WEBRTC_BASE_TEST(AdaptResolution4x3);
// TODO(juberti): Restore this test once we support sending 0 fps.
WEBRTC_DISABLED_BASE_TEST(AdaptDropAllFrames);
// TODO(juberti): Understand why we get decode errors on this test.
WEBRTC_DISABLED_BASE_TEST(AdaptFramerate);
WEBRTC_BASE_TEST(SendsLowerResolutionOnSmallerFrames);
WEBRTC_BASE_TEST(MuteStream);
WEBRTC_BASE_TEST(MultipleSendStreams);
WEBRTC_BASE_TEST(SetSendStreamFormat0x0);
// TODO(zhurunz): Fix the flakey test.
WEBRTC_DISABLED_BASE_TEST(SetSendStreamFormat);
TEST_F(WebRtcVideoChannel2BaseTest, SendAndReceiveVp8Vga) {
SendAndReceive(cricket::VideoCodec(100, "VP8", 640, 400, 30, 0));
}
TEST_F(WebRtcVideoChannel2BaseTest, SendAndReceiveVp8Qvga) {
SendAndReceive(cricket::VideoCodec(100, "VP8", 320, 200, 30, 0));
}
TEST_F(WebRtcVideoChannel2BaseTest, SendAndReceiveVp8SvcQqvga) {
SendAndReceive(cricket::VideoCodec(100, "VP8", 160, 100, 30, 0));
}
TEST_F(WebRtcVideoChannel2BaseTest, TwoStreamsSendAndReceive) {
Base::TwoStreamsSendAndReceive(kVp8Codec);
}
TEST_F(WebRtcVideoChannel2BaseTest, TwoStreamsReUseFirstStream) {
Base::TwoStreamsReUseFirstStream(kVp8Codec);
}
WEBRTC_BASE_TEST(SendManyResizeOnce);
// TODO(pbos): Enable and figure out why this fails (or should work).
TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_SendVp8HdAndReceiveAdaptedVp8Vga) {
EXPECT_TRUE(channel_->SetCapturer(kSsrc, NULL));
EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
channel_->UpdateAspectRatio(1280, 720);
video_capturer_.reset(new cricket::FakeVideoCapturer);
const std::vector<cricket::VideoFormat>* formats =
video_capturer_->GetSupportedFormats();
cricket::VideoFormat capture_format_hd = (*formats)[0];
EXPECT_EQ(cricket::CS_RUNNING, video_capturer_->Start(capture_format_hd));
EXPECT_TRUE(channel_->SetCapturer(kSsrc, video_capturer_.get()));
// Capture format HD -> adapt (OnOutputFormatRequest VGA) -> VGA.
cricket::VideoCodec codec = kVp8Codec720p;
EXPECT_TRUE(SetOneCodec(codec));
codec.width /= 2;
codec.height /= 2;
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
EXPECT_EQ(0, renderer_.num_rendered_frames());
EXPECT_TRUE(SendFrame());
EXPECT_FRAME_WAIT(1, codec.width, codec.height, kTimeout);
}
class WebRtcVideoChannel2Test : public WebRtcVideoEngine2Test,
public WebRtcCallFactory {
public:
WebRtcVideoChannel2Test() : fake_call_(NULL) {}
virtual void SetUp() OVERRIDE {
engine_.SetCallFactory(this);
engine_.Init(rtc::Thread::Current());
channel_.reset(engine_.CreateChannel(cricket::VideoOptions(), NULL));
ASSERT_TRUE(fake_call_ != NULL) << "Call not created through factory.";
last_ssrc_ = 123;
ASSERT_TRUE(channel_->SetSendCodecs(engine_.codecs()));
}
protected:
virtual webrtc::Call* CreateCall(
const webrtc::Call::Config& config) OVERRIDE {
assert(fake_call_ == NULL);
fake_call_ = new FakeCall(config);
return fake_call_;
}
FakeVideoSendStream* AddSendStream() {
return AddSendStream(StreamParams::CreateLegacy(++last_ssrc_));
}
FakeVideoSendStream* AddSendStream(const StreamParams& sp) {
size_t num_streams = fake_call_->GetVideoSendStreams().size();
EXPECT_TRUE(channel_->AddSendStream(sp));
std::vector<FakeVideoSendStream*> streams =
fake_call_->GetVideoSendStreams();
EXPECT_EQ(num_streams + 1, streams.size());
return streams[streams.size() - 1];
}
std::vector<FakeVideoSendStream*> GetFakeSendStreams() {
return fake_call_->GetVideoSendStreams();
}
FakeVideoReceiveStream* AddRecvStream() {
return AddRecvStream(StreamParams::CreateLegacy(++last_ssrc_));
}
FakeVideoReceiveStream* AddRecvStream(const StreamParams& sp) {
size_t num_streams = fake_call_->GetVideoReceiveStreams().size();
EXPECT_TRUE(channel_->AddRecvStream(sp));
std::vector<FakeVideoReceiveStream*> streams =
fake_call_->GetVideoReceiveStreams();
EXPECT_EQ(num_streams + 1, streams.size());
return streams[streams.size() - 1];
}
void SetSendCodecsShouldWorkForBitrates(const char* min_bitrate_kbps,
int expected_min_bitrate_bps,
const char* start_bitrate_kbps,
int expected_start_bitrate_bps,
const char* max_bitrate_kbps,
int expected_max_bitrate_bps) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs[0].params[kCodecParamMinBitrate] = min_bitrate_kbps;
codecs[0].params[kCodecParamStartBitrate] = start_bitrate_kbps;
codecs[0].params[kCodecParamMaxBitrate] = max_bitrate_kbps;
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
EXPECT_EQ(expected_min_bitrate_bps,
fake_call_->GetConfig().stream_bitrates.min_bitrate_bps);
EXPECT_EQ(expected_start_bitrate_bps,
fake_call_->GetConfig().stream_bitrates.start_bitrate_bps);
EXPECT_EQ(expected_max_bitrate_bps,
fake_call_->GetConfig().stream_bitrates.max_bitrate_bps);
}
void TestSetSendRtpHeaderExtensions(const std::string& cricket_ext,
const std::string& webrtc_ext) {
FakeCall* call = fake_call_;
// Enable extension.
const int id = 1;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(cricket::RtpHeaderExtension(cricket_ext, id));
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
FakeVideoSendStream* send_stream =
AddSendStream(cricket::StreamParams::CreateLegacy(123));
// Verify the send extension id.
ASSERT_EQ(1u, send_stream->GetConfig().rtp.extensions.size());
EXPECT_EQ(id, send_stream->GetConfig().rtp.extensions[0].id);
EXPECT_EQ(webrtc_ext, send_stream->GetConfig().rtp.extensions[0].name);
// Verify call with same set of extensions returns true.
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
// Verify that SetSendRtpHeaderExtensions doesn't implicitly add them for
// receivers.
EXPECT_TRUE(AddRecvStream(cricket::StreamParams::CreateLegacy(123))
->GetConfig()
.rtp.extensions.empty());
// Verify that existing RTP header extensions can be removed.
std::vector<cricket::RtpHeaderExtension> empty_extensions;
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(empty_extensions));
ASSERT_EQ(1u, call->GetVideoSendStreams().size());
send_stream = call->GetVideoSendStreams()[0];
EXPECT_TRUE(send_stream->GetConfig().rtp.extensions.empty());
// Verify that adding receive RTP header extensions adds them for existing
// streams.
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
send_stream = call->GetVideoSendStreams()[0];
ASSERT_EQ(1u, send_stream->GetConfig().rtp.extensions.size());
EXPECT_EQ(id, send_stream->GetConfig().rtp.extensions[0].id);
EXPECT_EQ(webrtc_ext, send_stream->GetConfig().rtp.extensions[0].name);
}
void TestSetRecvRtpHeaderExtensions(const std::string& cricket_ext,
const std::string& webrtc_ext) {
FakeCall* call = fake_call_;
// Enable extension.
const int id = 1;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(cricket::RtpHeaderExtension(cricket_ext, id));
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
FakeVideoReceiveStream* recv_stream =
AddRecvStream(cricket::StreamParams::CreateLegacy(123));
// Verify the recv extension id.
ASSERT_EQ(1u, recv_stream->GetConfig().rtp.extensions.size());
EXPECT_EQ(id, recv_stream->GetConfig().rtp.extensions[0].id);
EXPECT_EQ(webrtc_ext, recv_stream->GetConfig().rtp.extensions[0].name);
// Verify call with same set of extensions returns true.
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
// Verify that SetRecvRtpHeaderExtensions doesn't implicitly add them for
// senders.
EXPECT_TRUE(AddSendStream(cricket::StreamParams::CreateLegacy(123))
->GetConfig()
.rtp.extensions.empty());
// Verify that existing RTP header extensions can be removed.
std::vector<cricket::RtpHeaderExtension> empty_extensions;
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(empty_extensions));
ASSERT_EQ(1u, call->GetVideoReceiveStreams().size());
recv_stream = call->GetVideoReceiveStreams()[0];
EXPECT_TRUE(recv_stream->GetConfig().rtp.extensions.empty());
// Verify that adding receive RTP header extensions adds them for existing
// streams.
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
recv_stream = call->GetVideoReceiveStreams()[0];
ASSERT_EQ(1u, recv_stream->GetConfig().rtp.extensions.size());
EXPECT_EQ(id, recv_stream->GetConfig().rtp.extensions[0].id);
EXPECT_EQ(webrtc_ext, recv_stream->GetConfig().rtp.extensions[0].name);
}
void TestCpuAdaptation(bool enable_overuse);
FakeCall* fake_call_;
rtc::scoped_ptr<VideoMediaChannel> channel_;
uint32 last_ssrc_;
};
TEST_F(WebRtcVideoChannel2Test, RecvStreamWithSimAndRtx) {
EXPECT_TRUE(channel_->SetSendCodecs(engine_.codecs()));
EXPECT_TRUE(channel_->SetSend(true));
cricket::VideoOptions options;
options.conference_mode.Set(true);
EXPECT_TRUE(channel_->SetOptions(options));
// Send side.
const std::vector<uint32> ssrcs = MAKE_VECTOR(kSsrcs1);
const std::vector<uint32> rtx_ssrcs = MAKE_VECTOR(kRtxSsrcs1);
FakeVideoSendStream* send_stream = AddSendStream(
cricket::CreateSimWithRtxStreamParams("cname", ssrcs, rtx_ssrcs));
ASSERT_EQ(rtx_ssrcs.size(), send_stream->GetConfig().rtp.rtx.ssrcs.size());
for (size_t i = 0; i < rtx_ssrcs.size(); ++i)
EXPECT_EQ(rtx_ssrcs[i], send_stream->GetConfig().rtp.rtx.ssrcs[i]);
// Receiver side.
FakeVideoReceiveStream* recv_stream = AddRecvStream(
cricket::CreateSimWithRtxStreamParams("cname", ssrcs, rtx_ssrcs));
ASSERT_GT(recv_stream->GetConfig().rtp.rtx.size(), 0u)
<< "No SSRCs for RTX configured by AddRecvStream.";
ASSERT_EQ(1u, recv_stream->GetConfig().rtp.rtx.size())
<< "This test only works with one receive codec. Please update the test.";
EXPECT_EQ(rtx_ssrcs[0],
recv_stream->GetConfig().rtp.rtx.begin()->second.ssrc);
// TODO(pbos): Make sure we set the RTX for correct payloads etc.
}
TEST_F(WebRtcVideoChannel2Test, RecvStreamWithRtx) {
// Setup one channel with an associated RTX stream.
cricket::StreamParams params =
cricket::StreamParams::CreateLegacy(kSsrcs1[0]);
params.AddFidSsrc(kSsrcs1[0], kRtxSsrcs1[0]);
FakeVideoReceiveStream* recv_stream = AddRecvStream(params);
ASSERT_EQ(1u, recv_stream->GetConfig().rtp.rtx.size());
EXPECT_EQ(kRtxSsrcs1[0],
recv_stream->GetConfig().rtp.rtx.begin()->second.ssrc);
}
TEST_F(WebRtcVideoChannel2Test, RecvStreamNoRtx) {
// Setup one channel without an associated RTX stream.
cricket::StreamParams params =
cricket::StreamParams::CreateLegacy(kSsrcs1[0]);
FakeVideoReceiveStream* recv_stream = AddRecvStream(params);
ASSERT_TRUE(recv_stream->GetConfig().rtp.rtx.empty());
}
TEST_F(WebRtcVideoChannel2Test, NoHeaderExtesionsByDefault) {
FakeVideoSendStream* send_stream =
AddSendStream(cricket::StreamParams::CreateLegacy(kSsrcs1[0]));
ASSERT_TRUE(send_stream->GetConfig().rtp.extensions.empty());
FakeVideoReceiveStream* recv_stream =
AddRecvStream(cricket::StreamParams::CreateLegacy(kSsrcs1[0]));
ASSERT_TRUE(recv_stream->GetConfig().rtp.extensions.empty());
}
// Test support for RTP timestamp offset header extension.
TEST_F(WebRtcVideoChannel2Test, SendRtpTimestampOffsetHeaderExtensions) {
TestSetSendRtpHeaderExtensions(kRtpTimestampOffsetHeaderExtension,
webrtc::RtpExtension::kTOffset);
}
TEST_F(WebRtcVideoChannel2Test, RecvRtpTimestampOffsetHeaderExtensions) {
TestSetRecvRtpHeaderExtensions(kRtpTimestampOffsetHeaderExtension,
webrtc::RtpExtension::kTOffset);
}
// Test support for absolute send time header extension.
TEST_F(WebRtcVideoChannel2Test, SendAbsoluteSendTimeHeaderExtensions) {
TestSetSendRtpHeaderExtensions(kRtpAbsoluteSenderTimeHeaderExtension,
webrtc::RtpExtension::kAbsSendTime);
}
TEST_F(WebRtcVideoChannel2Test, RecvAbsoluteSendTimeHeaderExtensions) {
TestSetRecvRtpHeaderExtensions(kRtpAbsoluteSenderTimeHeaderExtension,
webrtc::RtpExtension::kAbsSendTime);
}
TEST_F(WebRtcVideoChannel2Test, IdenticalSendExtensionsDoesntRecreateStream) {
const int kTOffsetId = 1;
const int kAbsSendTimeId = 2;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(cricket::RtpHeaderExtension(
kRtpAbsoluteSenderTimeHeaderExtension, kAbsSendTimeId));
extensions.push_back(cricket::RtpHeaderExtension(
kRtpTimestampOffsetHeaderExtension, kTOffsetId));
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
FakeVideoSendStream* send_stream =
AddSendStream(cricket::StreamParams::CreateLegacy(123));
EXPECT_EQ(1, fake_call_->GetNumCreatedSendStreams());
ASSERT_EQ(2u, send_stream->GetConfig().rtp.extensions.size());
// Setting the same extensions (even if in different order) shouldn't
// reallocate the stream.
std::reverse(extensions.begin(), extensions.end());
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
EXPECT_EQ(1, fake_call_->GetNumCreatedSendStreams());
// Setting different extensions should recreate the stream.
extensions.resize(1);
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
EXPECT_EQ(2, fake_call_->GetNumCreatedSendStreams());
}
TEST_F(WebRtcVideoChannel2Test, IdenticalRecvExtensionsDoesntRecreateStream) {
const int kTOffsetId = 1;
const int kAbsSendTimeId = 2;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(cricket::RtpHeaderExtension(
kRtpAbsoluteSenderTimeHeaderExtension, kAbsSendTimeId));
extensions.push_back(cricket::RtpHeaderExtension(
kRtpTimestampOffsetHeaderExtension, kTOffsetId));
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
FakeVideoReceiveStream* send_stream =
AddRecvStream(cricket::StreamParams::CreateLegacy(123));
EXPECT_EQ(1, fake_call_->GetNumCreatedReceiveStreams());
ASSERT_EQ(2u, send_stream->GetConfig().rtp.extensions.size());
// Setting the same extensions (even if in different order) shouldn't
// reallocate the stream.
std::reverse(extensions.begin(), extensions.end());
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
EXPECT_EQ(1, fake_call_->GetNumCreatedReceiveStreams());
// Setting different extensions should recreate the stream.
extensions.resize(1);
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
EXPECT_EQ(2, fake_call_->GetNumCreatedReceiveStreams());
}
TEST_F(WebRtcVideoChannel2Test,
SetSendRtpHeaderExtensionsExcludeUnsupportedExtensions) {
const int kUnsupportedId = 1;
const int kTOffsetId = 2;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(
cricket::RtpHeaderExtension(kUnsupportedExtensionName, kUnsupportedId));
extensions.push_back(
cricket::RtpHeaderExtension(webrtc::RtpExtension::kTOffset, kTOffsetId));
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
FakeVideoSendStream* send_stream =
AddSendStream(cricket::StreamParams::CreateLegacy(123));
// Only timestamp offset extension is set to send stream,
// unsupported rtp extension is ignored.
ASSERT_EQ(1u, send_stream->GetConfig().rtp.extensions.size());
EXPECT_STREQ(webrtc::RtpExtension::kTOffset,
send_stream->GetConfig().rtp.extensions[0].name.c_str());
}
TEST_F(WebRtcVideoChannel2Test,
SetRecvRtpHeaderExtensionsExcludeUnsupportedExtensions) {
const int kUnsupportedId = 1;
const int kTOffsetId = 2;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(
cricket::RtpHeaderExtension(kUnsupportedExtensionName, kUnsupportedId));
extensions.push_back(
cricket::RtpHeaderExtension(webrtc::RtpExtension::kTOffset, kTOffsetId));
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
FakeVideoReceiveStream* recv_stream =
AddRecvStream(cricket::StreamParams::CreateLegacy(123));
// Only timestamp offset extension is set to receive stream,
// unsupported rtp extension is ignored.
ASSERT_EQ(1u, recv_stream->GetConfig().rtp.extensions.size());
EXPECT_STREQ(webrtc::RtpExtension::kTOffset,
recv_stream->GetConfig().rtp.extensions[0].name.c_str());
}
TEST_F(WebRtcVideoChannel2Test, SetSendRtpHeaderExtensionsRejectsIncorrectIds) {
const int kIncorrectIds[] = {-2, -1, 15, 16};
for (size_t i = 0; i < arraysize(kIncorrectIds); ++i) {
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(cricket::RtpHeaderExtension(
webrtc::RtpExtension::kTOffset, kIncorrectIds[i]));
EXPECT_FALSE(channel_->SetSendRtpHeaderExtensions(extensions))
<< "Bad extension id '" << kIncorrectIds[i] << "' accepted.";
}
}
TEST_F(WebRtcVideoChannel2Test, SetRecvRtpHeaderExtensionsRejectsIncorrectIds) {
const int kIncorrectIds[] = {-2, -1, 15, 16};
for (size_t i = 0; i < arraysize(kIncorrectIds); ++i) {
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(cricket::RtpHeaderExtension(
webrtc::RtpExtension::kTOffset, kIncorrectIds[i]));
EXPECT_FALSE(channel_->SetRecvRtpHeaderExtensions(extensions))
<< "Bad extension id '" << kIncorrectIds[i] << "' accepted.";
}
}
TEST_F(WebRtcVideoChannel2Test, SetSendRtpHeaderExtensionsRejectsDuplicateIds) {
const int id = 1;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(
cricket::RtpHeaderExtension(webrtc::RtpExtension::kTOffset, id));
extensions.push_back(
cricket::RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension, id));
EXPECT_FALSE(channel_->SetSendRtpHeaderExtensions(extensions));
// Duplicate entries are also not supported.
extensions.clear();
extensions.push_back(
cricket::RtpHeaderExtension(webrtc::RtpExtension::kTOffset, id));
extensions.push_back(extensions.back());
EXPECT_FALSE(channel_->SetSendRtpHeaderExtensions(extensions));
}
TEST_F(WebRtcVideoChannel2Test, SetRecvRtpHeaderExtensionsRejectsDuplicateIds) {
const int id = 1;
std::vector<cricket::RtpHeaderExtension> extensions;
extensions.push_back(
cricket::RtpHeaderExtension(webrtc::RtpExtension::kTOffset, id));
extensions.push_back(
cricket::RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension, id));
EXPECT_FALSE(channel_->SetRecvRtpHeaderExtensions(extensions));
// Duplicate entries are also not supported.
extensions.clear();
extensions.push_back(
cricket::RtpHeaderExtension(webrtc::RtpExtension::kTOffset, id));
extensions.push_back(extensions.back());
EXPECT_FALSE(channel_->SetRecvRtpHeaderExtensions(extensions));
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_LeakyBucketTest) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_BufferedModeLatency) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_AdditiveVideoOptions) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, AddRecvStreamOnlyUsesOneReceiveStream) {
EXPECT_TRUE(channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(1)));
EXPECT_EQ(1u, fake_call_->GetVideoReceiveStreams().size());
}
TEST_F(WebRtcVideoChannel2Test, RembIsEnabledByDefault) {
FakeVideoReceiveStream* stream = AddRecvStream();
EXPECT_TRUE(stream->GetConfig().rtp.remb);
}
TEST_F(WebRtcVideoChannel2Test, RembCanBeEnabledAndDisabled) {
FakeVideoReceiveStream* stream = AddRecvStream();
EXPECT_TRUE(stream->GetConfig().rtp.remb);
// Verify that REMB is turned off when codecs without REMB are set.
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
EXPECT_TRUE(codecs[0].feedback_params.params().empty());
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
stream = fake_call_->GetVideoReceiveStreams()[0];
EXPECT_FALSE(stream->GetConfig().rtp.remb);
// Verify that REMB is turned on when setting default codecs since the
// default codecs have REMB enabled.
EXPECT_TRUE(channel_->SetRecvCodecs(engine_.codecs()));
stream = fake_call_->GetVideoReceiveStreams()[0];
EXPECT_TRUE(stream->GetConfig().rtp.remb);
}
TEST_F(WebRtcVideoChannel2Test, NackIsEnabledByDefault) {
VerifyCodecHasDefaultFeedbackParams(default_codec_);
EXPECT_TRUE(channel_->SetSendCodecs(engine_.codecs()));
EXPECT_TRUE(channel_->SetSend(true));
// Send side.
FakeVideoSendStream* send_stream =
AddSendStream(cricket::StreamParams::CreateLegacy(1));
EXPECT_GT(send_stream->GetConfig().rtp.nack.rtp_history_ms, 0);
// Receiver side.
FakeVideoReceiveStream* recv_stream =
AddRecvStream(cricket::StreamParams::CreateLegacy(1));
EXPECT_GT(recv_stream->GetConfig().rtp.nack.rtp_history_ms, 0);
// Nack history size should match between sender and receiver.
EXPECT_EQ(send_stream->GetConfig().rtp.nack.rtp_history_ms,
recv_stream->GetConfig().rtp.nack.rtp_history_ms);
}
TEST_F(WebRtcVideoChannel2Test, NackCanBeDisabled) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
// Send side.
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
FakeVideoSendStream* send_stream =
AddSendStream(cricket::StreamParams::CreateLegacy(1));
EXPECT_EQ(0, send_stream->GetConfig().rtp.nack.rtp_history_ms);
// Receiver side.
ASSERT_TRUE(channel_->SetRecvCodecs(codecs));
FakeVideoReceiveStream* recv_stream =
AddRecvStream(cricket::StreamParams::CreateLegacy(1));
EXPECT_EQ(0, recv_stream->GetConfig().rtp.nack.rtp_history_ms);
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_VideoProtectionInterop) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_VideoProtectionInteropReversed) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_HybridNackFecConference) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_AddRemoveRecvStreamConference) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SetRender) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SetBandwidthAuto) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SetBandwidthAutoCapped) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SetBandwidthFixed) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SetBandwidthInConference) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, UsesCorrectSettingsForScreencast) {
static const int kScreenshareMinBitrateKbps = 800;
cricket::VideoCodec codec = kVp8Codec360p;
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(codec);
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
VideoOptions options;
options.screencast_min_bitrate.Set(kScreenshareMinBitrateKbps);
channel_->SetOptions(options);
AddSendStream();
cricket::FakeVideoCapturer capturer;
capturer.SetScreencast(false);
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, &capturer));
cricket::VideoFormat capture_format_hd =
capturer.GetSupportedFormats()->front();
EXPECT_EQ(1280, capture_format_hd.width);
EXPECT_EQ(720, capture_format_hd.height);
EXPECT_EQ(cricket::CS_RUNNING, capturer.Start(capture_format_hd));
EXPECT_TRUE(channel_->SetSend(true));
EXPECT_TRUE(capturer.CaptureFrame());
ASSERT_EQ(1u, fake_call_->GetVideoSendStreams().size());
FakeVideoSendStream* send_stream = fake_call_->GetVideoSendStreams().front();
EXPECT_EQ(1, send_stream->GetNumberOfSwappedFrames());
// Verify non-screencast settings.
webrtc::VideoEncoderConfig encoder_config = send_stream->GetEncoderConfig();
EXPECT_EQ(webrtc::VideoEncoderConfig::kRealtimeVideo,
encoder_config.content_type);
EXPECT_EQ(codec.width, encoder_config.streams.front().width);
EXPECT_EQ(codec.height, encoder_config.streams.front().height);
EXPECT_EQ(0, encoder_config.min_transmit_bitrate_bps)
<< "Non-screenshare shouldn't use min-transmit bitrate.";
capturer.SetScreencast(true);
EXPECT_TRUE(capturer.CaptureFrame());
EXPECT_EQ(2, send_stream->GetNumberOfSwappedFrames());
// Verify screencast settings.
encoder_config = send_stream->GetEncoderConfig();
EXPECT_EQ(webrtc::VideoEncoderConfig::kScreenshare,
encoder_config.content_type);
EXPECT_EQ(kScreenshareMinBitrateKbps * 1000,
encoder_config.min_transmit_bitrate_bps);
EXPECT_EQ(capture_format_hd.width, encoder_config.streams.front().width);
EXPECT_EQ(capture_format_hd.height, encoder_config.streams.front().height);
EXPECT_TRUE(encoder_config.streams[0].temporal_layer_thresholds_bps.empty());
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, NULL));
}
TEST_F(WebRtcVideoChannel2Test,
ConferenceModeScreencastConfiguresTemporalLayer) {
static const int kConferenceScreencastTemporalBitrateBps = 100000;
VideoOptions options;
options.conference_mode.Set(true);
channel_->SetOptions(options);
AddSendStream();
cricket::FakeVideoCapturer capturer;
capturer.SetScreencast(true);
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, &capturer));
cricket::VideoFormat capture_format_hd =
capturer.GetSupportedFormats()->front();
EXPECT_EQ(cricket::CS_RUNNING, capturer.Start(capture_format_hd));
EXPECT_TRUE(channel_->SetSend(true));
EXPECT_TRUE(capturer.CaptureFrame());
ASSERT_EQ(1u, fake_call_->GetVideoSendStreams().size());
FakeVideoSendStream* send_stream = fake_call_->GetVideoSendStreams().front();
webrtc::VideoEncoderConfig encoder_config = send_stream->GetEncoderConfig();
// Verify screencast settings.
encoder_config = send_stream->GetEncoderConfig();
EXPECT_EQ(webrtc::VideoEncoderConfig::kScreenshare,
encoder_config.content_type);
ASSERT_EQ(1u, encoder_config.streams.size());
ASSERT_EQ(1u, encoder_config.streams[0].temporal_layer_thresholds_bps.size());
EXPECT_EQ(kConferenceScreencastTemporalBitrateBps,
encoder_config.streams[0].temporal_layer_thresholds_bps[0]);
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, NULL));
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SetSendSsrcAndCname) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test,
DISABLED_SetSendSsrcAfterCreatingReceiveChannel) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, SuspendBelowMinBitrateDisabledByDefault) {
FakeVideoSendStream* stream = AddSendStream();
EXPECT_FALSE(stream->GetConfig().suspend_below_min_bitrate);
}
TEST_F(WebRtcVideoChannel2Test, SetOptionsWithSuspendBelowMinBitrate) {
VideoOptions options;
options.suspend_below_min_bitrate.Set(true);
channel_->SetOptions(options);
FakeVideoSendStream* stream = AddSendStream();
EXPECT_TRUE(stream->GetConfig().suspend_below_min_bitrate);
options.suspend_below_min_bitrate.Set(false);
channel_->SetOptions(options);
stream = fake_call_->GetVideoSendStreams()[0];
EXPECT_FALSE(stream->GetConfig().suspend_below_min_bitrate);
}
TEST_F(WebRtcVideoChannel2Test, Vp8DenoisingEnabledByDefault) {
FakeVideoSendStream* stream = AddSendStream();
webrtc::VideoCodecVP8 vp8_settings;
ASSERT_TRUE(stream->GetVp8Settings(&vp8_settings)) << "No VP8 config set.";
EXPECT_TRUE(vp8_settings.denoisingOn);
}
TEST_F(WebRtcVideoChannel2Test, SetOptionsWithDenoising) {
VideoOptions options;
options.video_noise_reduction.Set(false);
channel_->SetOptions(options);
FakeVideoSendStream* stream = AddSendStream();
webrtc::VideoCodecVP8 vp8_settings;
ASSERT_TRUE(stream->GetVp8Settings(&vp8_settings)) << "No VP8 config set.";
EXPECT_FALSE(vp8_settings.denoisingOn);
options.video_noise_reduction.Set(true);
channel_->SetOptions(options);
stream = fake_call_->GetVideoSendStreams()[0];
ASSERT_TRUE(stream->GetVp8Settings(&vp8_settings)) << "No VP8 config set.";
EXPECT_TRUE(vp8_settings.denoisingOn);
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_MultipleSendStreamsWithOneCapturer) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_SendReceiveBitratesStats) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
TEST_F(WebRtcVideoChannel2Test, AdaptsOnOveruse) {
TestCpuAdaptation(true);
}
TEST_F(WebRtcVideoChannel2Test, DoesNotAdaptOnOveruseWhenDisabled) {
TestCpuAdaptation(false);
}
void WebRtcVideoChannel2Test::TestCpuAdaptation(bool enable_overuse) {
cricket::VideoCodec codec = kVp8Codec720p;
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(codec);
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
if (enable_overuse) {
VideoOptions options;
options.cpu_overuse_detection.Set(true);
channel_->SetOptions(options);
}
AddSendStream();
cricket::FakeVideoCapturer capturer;
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, &capturer));
EXPECT_EQ(cricket::CS_RUNNING,
capturer.Start(capturer.GetSupportedFormats()->front()));
EXPECT_TRUE(channel_->SetSend(true));
// Trigger overuse.
webrtc::LoadObserver* overuse_callback =
fake_call_->GetConfig().overuse_callback;
ASSERT_TRUE(overuse_callback != NULL);
overuse_callback->OnLoadUpdate(webrtc::LoadObserver::kOveruse);
EXPECT_TRUE(capturer.CaptureFrame());
ASSERT_EQ(1u, fake_call_->GetVideoSendStreams().size());
FakeVideoSendStream* send_stream = fake_call_->GetVideoSendStreams().front();
EXPECT_EQ(1, send_stream->GetNumberOfSwappedFrames());
if (enable_overuse) {
EXPECT_LT(send_stream->GetLastWidth(), codec.width);
EXPECT_LT(send_stream->GetLastHeight(), codec.height);
} else {
EXPECT_EQ(codec.width, send_stream->GetLastWidth());
EXPECT_EQ(codec.height, send_stream->GetLastHeight());
}
// Trigger underuse which should go back to normal resolution.
overuse_callback->OnLoadUpdate(webrtc::LoadObserver::kUnderuse);
EXPECT_TRUE(capturer.CaptureFrame());
EXPECT_EQ(2, send_stream->GetNumberOfSwappedFrames());
EXPECT_EQ(codec.width, send_stream->GetLastWidth());
EXPECT_EQ(codec.height, send_stream->GetLastHeight());
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, NULL));
}
TEST_F(WebRtcVideoChannel2Test, EstimatesNtpStartTimeAndElapsedTimeCorrectly) {
// Start at last timestamp to verify that wraparounds are estimated correctly.
static const uint32_t kInitialTimestamp = 0xFFFFFFFFu;
static const int64_t kInitialNtpTimeMs = 1247891230;
static const int kFrameOffsetMs = 20;
EXPECT_TRUE(channel_->SetRecvCodecs(engine_.codecs()));
FakeVideoReceiveStream* stream = AddRecvStream();
cricket::FakeVideoRenderer renderer;
EXPECT_TRUE(channel_->SetRenderer(last_ssrc_, &renderer));
EXPECT_TRUE(channel_->SetRender(true));
webrtc::I420VideoFrame video_frame;
CreateBlackFrame(&video_frame, 4, 4);
video_frame.set_timestamp(kInitialTimestamp);
// Initial NTP time is not available on the first frame, but should still be
// able to be estimated.
stream->InjectFrame(video_frame, 0);
EXPECT_EQ(1, renderer.num_rendered_frames());
EXPECT_EQ(0, renderer.last_frame_elapsed_time_ns());
// This timestamp is kInitialTimestamp (-1) + kFrameOffsetMs * 90, which
// triggers a constant-overflow warning, hence we're calculating it explicitly
// here.
video_frame.set_timestamp(kFrameOffsetMs * 90 - 1);
video_frame.set_ntp_time_ms(kInitialNtpTimeMs + kFrameOffsetMs);
stream->InjectFrame(video_frame, 0);
EXPECT_EQ(2, renderer.num_rendered_frames());
EXPECT_EQ(kFrameOffsetMs * rtc::kNumNanosecsPerMillisec,
renderer.last_frame_elapsed_time_ns());
// Verify that NTP time has been correctly deduced.
cricket::VideoMediaInfo info;
ASSERT_TRUE(channel_->GetStats(cricket::StatsOptions(), &info));
ASSERT_EQ(1u, info.receivers.size());
EXPECT_EQ(kInitialNtpTimeMs, info.receivers[0].capture_start_ntp_time_ms);
}
TEST_F(WebRtcVideoChannel2Test, SetDefaultSendCodecs) {
ASSERT_TRUE(channel_->SetSendCodecs(engine_.codecs()));
VideoCodec codec;
EXPECT_TRUE(channel_->GetSendCodec(&codec));
EXPECT_TRUE(codec.Matches(engine_.codecs()[0]));
// Using a RTX setup to verify that the default RTX payload type is good.
const std::vector<uint32> ssrcs = MAKE_VECTOR(kSsrcs1);
const std::vector<uint32> rtx_ssrcs = MAKE_VECTOR(kRtxSsrcs1);
FakeVideoSendStream* stream = AddSendStream(
cricket::CreateSimWithRtxStreamParams("cname", ssrcs, rtx_ssrcs));
webrtc::VideoSendStream::Config config = stream->GetConfig();
// Make sure NACK and FEC are enabled on the correct payload types.
EXPECT_EQ(1000, config.rtp.nack.rtp_history_ms);
EXPECT_EQ(default_ulpfec_codec_.id, config.rtp.fec.ulpfec_payload_type);
EXPECT_EQ(default_red_codec_.id, config.rtp.fec.red_payload_type);
EXPECT_EQ(1u, config.rtp.rtx.ssrcs.size());
EXPECT_EQ(kRtxSsrcs1[0], config.rtp.rtx.ssrcs[0]);
EXPECT_EQ(static_cast<int>(default_rtx_codec_.id),
config.rtp.rtx.payload_type);
// TODO(juberti): Check RTCP, PLI, TMMBR.
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsWithoutFec) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
FakeVideoSendStream* stream = AddSendStream();
webrtc::VideoSendStream::Config config = stream->GetConfig();
EXPECT_EQ(-1, config.rtp.fec.ulpfec_payload_type);
EXPECT_EQ(-1, config.rtp.fec.red_payload_type);
}
TEST_F(WebRtcVideoChannel2Test,
SetSendCodecRejectsRtxWithoutAssociatedPayloadType) {
std::vector<VideoCodec> codecs;
cricket::VideoCodec rtx_codec(96, "rtx", 0, 0, 0, 0);
codecs.push_back(rtx_codec);
EXPECT_FALSE(channel_->SetSendCodecs(codecs))
<< "RTX codec without associated payload type should be rejected.";
}
TEST_F(WebRtcVideoChannel2Test,
SetSendCodecRejectsRtxWithoutMatchingVideoCodec) {
std::vector<VideoCodec> codecs;
cricket::VideoCodec rtx_codec =
cricket::VideoCodec::CreateRtxCodec(96, kVp8Codec.id);
codecs.push_back(kVp8Codec);
codecs.push_back(rtx_codec);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
cricket::VideoCodec rtx_codec2 =
cricket::VideoCodec::CreateRtxCodec(96, kVp8Codec.id + 1);
codecs.pop_back();
codecs.push_back(rtx_codec2);
EXPECT_FALSE(channel_->SetSendCodecs(codecs))
<< "RTX without matching video codec should be rejected.";
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsWithoutFecDisablesFec) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kUlpfecCodec);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
FakeVideoSendStream* stream = AddSendStream();
webrtc::VideoSendStream::Config config = stream->GetConfig();
EXPECT_EQ(kUlpfecCodec.id, config.rtp.fec.ulpfec_payload_type);
codecs.pop_back();
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
stream = fake_call_->GetVideoSendStreams()[0];
ASSERT_TRUE(stream != NULL);
config = stream->GetConfig();
EXPECT_EQ(-1, config.rtp.fec.ulpfec_payload_type)
<< "SetSendCodec without FEC should disable current FEC.";
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsChangesExistingStreams) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec720p);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
channel_->SetSend(true);
FakeVideoSendStream* stream = AddSendStream();
cricket::FakeVideoCapturer capturer;
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, &capturer));
EXPECT_EQ(cricket::CS_RUNNING,
capturer.Start(capturer.GetSupportedFormats()->front()));
EXPECT_TRUE(capturer.CaptureFrame());
std::vector<webrtc::VideoStream> streams = stream->GetVideoStreams();
EXPECT_EQ(kVp8Codec720p.width, streams[0].width);
EXPECT_EQ(kVp8Codec720p.height, streams[0].height);
codecs.clear();
codecs.push_back(kVp8Codec360p);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
streams = fake_call_->GetVideoSendStreams()[0]->GetVideoStreams();
EXPECT_EQ(kVp8Codec360p.width, streams[0].width);
EXPECT_EQ(kVp8Codec360p.height, streams[0].height);
EXPECT_TRUE(channel_->SetCapturer(last_ssrc_, NULL));
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsWithBitrates) {
SetSendCodecsShouldWorkForBitrates("100", 100000, "150", 150000, "200",
200000);
}
TEST_F(WebRtcVideoChannel2Test,
SetSendCodecsWithoutBitratesUsesCorrectDefaults) {
SetSendCodecsShouldWorkForBitrates(
"", 0, "", -1, "", -1);
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsCapsMinAndStartBitrate) {
SetSendCodecsShouldWorkForBitrates("-1", 0, "-100", -1, "", -1);
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsRejectsMaxLessThanMinBitrate) {
std::vector<VideoCodec> video_codecs = engine_.codecs();
video_codecs[0].params[kCodecParamMinBitrate] = "300";
video_codecs[0].params[kCodecParamMaxBitrate] = "200";
EXPECT_FALSE(channel_->SetSendCodecs(video_codecs));
}
TEST_F(WebRtcVideoChannel2Test,
SetMaxSendBandwidthShouldPreserveOtherBitrates) {
SetSendCodecsShouldWorkForBitrates("100", 100000, "150", 150000, "200",
200000);
channel_->SetMaxSendBandwidth(300000);
EXPECT_EQ(100000, fake_call_->GetConfig().stream_bitrates.min_bitrate_bps)
<< "Setting max bitrate should keep previous min bitrate.";
EXPECT_EQ(-1, fake_call_->GetConfig().stream_bitrates.start_bitrate_bps)
<< "Setting max bitrate should not reset start bitrate.";
EXPECT_EQ(300000, fake_call_->GetConfig().stream_bitrates.max_bitrate_bps);
}
TEST_F(WebRtcVideoChannel2Test, SetMaxSendBandwidthShouldBeRemovable) {
channel_->SetMaxSendBandwidth(300000);
EXPECT_EQ(300000, fake_call_->GetConfig().stream_bitrates.max_bitrate_bps);
// <= 0 means disable (infinite) max bitrate.
channel_->SetMaxSendBandwidth(0);
EXPECT_EQ(-1, fake_call_->GetConfig().stream_bitrates.max_bitrate_bps)
<< "Setting zero max bitrate did not reset start bitrate.";
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsWithMaxQuantization) {
static const char* kMaxQuantization = "21";
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs[0].params[kCodecParamMaxQuantization] = kMaxQuantization;
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
EXPECT_EQ(static_cast<unsigned int>(atoi(kMaxQuantization)),
AddSendStream()->GetVideoStreams().back().max_qp);
VideoCodec codec;
EXPECT_TRUE(channel_->GetSendCodec(&codec));
EXPECT_EQ(kMaxQuantization, codec.params[kCodecParamMaxQuantization]);
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsRejectBadDimensions) {
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs[0].width = 0;
EXPECT_FALSE(channel_->SetSendCodecs(codecs))
<< "Codec set though codec width is zero.";
codecs[0].width = kVp8Codec.width;
codecs[0].height = 0;
EXPECT_FALSE(channel_->SetSendCodecs(codecs))
<< "Codec set though codec height is zero.";
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsRejectBadPayloadTypes) {
// TODO(pbos): Should we only allow the dynamic range?
static const int kIncorrectPayloads[] = {-2, -1, 128, 129};
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
for (size_t i = 0; i < arraysize(kIncorrectPayloads); ++i) {
int payload_type = kIncorrectPayloads[i];
codecs[0].id = payload_type;
EXPECT_FALSE(channel_->SetSendCodecs(codecs))
<< "Bad payload type '" << payload_type << "' accepted.";
}
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsAcceptAllValidPayloadTypes) {
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
for (int payload_type = 0; payload_type <= 127; ++payload_type) {
codecs[0].id = payload_type;
EXPECT_TRUE(channel_->SetSendCodecs(codecs))
<< "Payload type '" << payload_type << "' rejected.";
}
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsWithOnlyVp8) {
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
}
// Test that we set our inbound RTX codecs properly.
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsWithRtx) {
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
cricket::VideoCodec rtx_codec(96, "rtx", 0, 0, 0, 0);
codecs.push_back(rtx_codec);
EXPECT_FALSE(channel_->SetRecvCodecs(codecs))
<< "RTX codec without associated payload should be rejected.";
codecs[1].SetParam("apt", kVp8Codec.id + 1);
EXPECT_FALSE(channel_->SetRecvCodecs(codecs))
<< "RTX codec with invalid associated payload type should be rejected.";
codecs[1].SetParam("apt", kVp8Codec.id);
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
cricket::VideoCodec rtx_codec2(97, "rtx", 0, 0, 0, 0);
rtx_codec2.SetParam("apt", rtx_codec.id);
codecs.push_back(rtx_codec2);
EXPECT_FALSE(channel_->SetRecvCodecs(codecs)) << "RTX codec with another RTX "
"as associated payload type "
"should be rejected.";
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsDifferentPayloadType) {
std::vector<cricket::VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs[0].id = 99;
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsAcceptDefaultCodecs) {
EXPECT_TRUE(channel_->SetRecvCodecs(engine_.codecs()));
FakeVideoReceiveStream* stream = AddRecvStream();
webrtc::VideoReceiveStream::Config config = stream->GetConfig();
EXPECT_EQ(engine_.codecs()[0].name, config.decoders[0].payload_name);
EXPECT_EQ(engine_.codecs()[0].id, config.decoders[0].payload_type);
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsRejectUnsupportedCodec) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(VideoCodec(101, "WTF3", 640, 400, 30, 0));
EXPECT_FALSE(channel_->SetRecvCodecs(codecs));
}
// TODO(pbos): Enable VP9 through external codec support
TEST_F(WebRtcVideoChannel2Test,
DISABLED_SetRecvCodecsAcceptsMultipleVideoCodecs) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kVp9Codec);
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
}
TEST_F(WebRtcVideoChannel2Test,
DISABLED_SetRecvCodecsSetsFecForAllVideoCodecs) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kVp9Codec);
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
FAIL(); // TODO(pbos): Verify that the FEC parameters are set for all codecs.
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsWithoutFecDisablesFec) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kUlpfecCodec);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
FakeVideoReceiveStream* stream = AddRecvStream();
webrtc::VideoReceiveStream::Config config = stream->GetConfig();
EXPECT_EQ(kUlpfecCodec.id, config.rtp.fec.ulpfec_payload_type);
codecs.pop_back();
ASSERT_TRUE(channel_->SetRecvCodecs(codecs));
stream = fake_call_->GetVideoReceiveStreams()[0];
ASSERT_TRUE(stream != NULL);
config = stream->GetConfig();
EXPECT_EQ(-1, config.rtp.fec.ulpfec_payload_type)
<< "SetSendCodec without FEC should disable current FEC.";
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsRejectDuplicateFecPayloads) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kRedCodec);
codecs[1].id = codecs[0].id;
EXPECT_FALSE(channel_->SetRecvCodecs(codecs));
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsRejectDuplicateCodecPayloads) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kVp9Codec);
codecs[1].id = codecs[0].id;
EXPECT_FALSE(channel_->SetRecvCodecs(codecs));
}
TEST_F(WebRtcVideoChannel2Test,
SetRecvCodecsAcceptSameCodecOnMultiplePayloadTypes) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
codecs.push_back(kVp8Codec);
codecs[1].id += 1;
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
}
TEST_F(WebRtcVideoChannel2Test, SendStreamNotSendingByDefault) {
EXPECT_FALSE(AddSendStream()->IsSending());
}
TEST_F(WebRtcVideoChannel2Test, ReceiveStreamReceivingByDefault) {
EXPECT_TRUE(AddRecvStream()->IsReceiving());
}
TEST_F(WebRtcVideoChannel2Test, SetSend) {
FakeVideoSendStream* stream = AddSendStream();
EXPECT_FALSE(stream->IsSending());
// false->true
EXPECT_TRUE(channel_->SetSend(true));
EXPECT_TRUE(stream->IsSending());
// true->true
EXPECT_TRUE(channel_->SetSend(true));
EXPECT_TRUE(stream->IsSending());
// true->false
EXPECT_TRUE(channel_->SetSend(false));
EXPECT_FALSE(stream->IsSending());
// false->false
EXPECT_TRUE(channel_->SetSend(false));
EXPECT_FALSE(stream->IsSending());
EXPECT_TRUE(channel_->SetSend(true));
FakeVideoSendStream* new_stream = AddSendStream();
EXPECT_TRUE(new_stream->IsSending())
<< "Send stream created after SetSend(true) not sending initially.";
}
// This test verifies DSCP settings are properly applied on video media channel.
TEST_F(WebRtcVideoChannel2Test, TestSetDscpOptions) {
rtc::scoped_ptr<cricket::FakeNetworkInterface> network_interface(
new cricket::FakeNetworkInterface);
channel_->SetInterface(network_interface.get());
cricket::VideoOptions options;
options.dscp.Set(true);
EXPECT_TRUE(channel_->SetOptions(options));
EXPECT_EQ(rtc::DSCP_AF41, network_interface->dscp());
// Verify previous value is not modified if dscp option is not set.
cricket::VideoOptions options1;
EXPECT_TRUE(channel_->SetOptions(options1));
EXPECT_EQ(rtc::DSCP_AF41, network_interface->dscp());
options.dscp.Set(false);
EXPECT_TRUE(channel_->SetOptions(options));
EXPECT_EQ(rtc::DSCP_DEFAULT, network_interface->dscp());
channel_->SetInterface(NULL);
}
TEST_F(WebRtcVideoChannel2Test, OnReadyToSendSignalsNetworkState) {
EXPECT_EQ(webrtc::Call::kNetworkUp, fake_call_->GetNetworkState());
channel_->OnReadyToSend(false);
EXPECT_EQ(webrtc::Call::kNetworkDown, fake_call_->GetNetworkState());
channel_->OnReadyToSend(true);
EXPECT_EQ(webrtc::Call::kNetworkUp, fake_call_->GetNetworkState());
}
TEST_F(WebRtcVideoChannel2Test, GetStatsReportsUpperResolution) {
FakeVideoSendStream* stream = AddSendStream();
webrtc::VideoSendStream::Stats stats;
stats.substreams[17].sent_width = 123;
stats.substreams[17].sent_height = 40;
stats.substreams[42].sent_width = 80;
stats.substreams[42].sent_height = 31;
stats.substreams[11].sent_width = 20;
stats.substreams[11].sent_height = 90;
stream->SetStats(stats);
cricket::VideoMediaInfo info;
ASSERT_TRUE(channel_->GetStats(cricket::StatsOptions(), &info));
ASSERT_EQ(1u, info.senders.size());
EXPECT_EQ(123, info.senders[0].send_frame_width);
EXPECT_EQ(90, info.senders[0].send_frame_height);
}
TEST_F(WebRtcVideoChannel2Test,
GetStatsTranslatesSendRtcpPacketTypesCorrectly) {
FakeVideoSendStream* stream = AddSendStream();
webrtc::VideoSendStream::Stats stats;
stats.substreams[17].rtcp_packet_type_counts.fir_packets = 2;
stats.substreams[17].rtcp_packet_type_counts.nack_packets = 3;
stats.substreams[17].rtcp_packet_type_counts.pli_packets = 4;
stats.substreams[42].rtcp_packet_type_counts.fir_packets = 5;
stats.substreams[42].rtcp_packet_type_counts.nack_packets = 7;
stats.substreams[42].rtcp_packet_type_counts.pli_packets = 9;
stream->SetStats(stats);
cricket::VideoMediaInfo info;
ASSERT_TRUE(channel_->GetStats(cricket::StatsOptions(), &info));
EXPECT_EQ(7, info.senders[0].firs_rcvd);
EXPECT_EQ(10, info.senders[0].nacks_rcvd);
EXPECT_EQ(13, info.senders[0].plis_rcvd);
}
TEST_F(WebRtcVideoChannel2Test,
GetStatsTranslatesReceiveRtcpPacketTypesCorrectly) {
FakeVideoReceiveStream* stream = AddRecvStream();
webrtc::VideoReceiveStream::Stats stats;
stats.rtcp_packet_type_counts.fir_packets = 2;
stats.rtcp_packet_type_counts.nack_packets = 3;
stats.rtcp_packet_type_counts.pli_packets = 4;
stream->SetStats(stats);
cricket::VideoMediaInfo info;
ASSERT_TRUE(channel_->GetStats(cricket::StatsOptions(), &info));
EXPECT_EQ(stats.rtcp_packet_type_counts.fir_packets,
info.receivers[0].firs_sent);
EXPECT_EQ(stats.rtcp_packet_type_counts.nack_packets,
info.receivers[0].nacks_sent);
EXPECT_EQ(stats.rtcp_packet_type_counts.pli_packets,
info.receivers[0].plis_sent);
}
TEST_F(WebRtcVideoChannel2Test, TranslatesCallStatsCorrectly) {
AddSendStream();
AddSendStream();
webrtc::Call::Stats stats;
stats.rtt_ms = 123;
fake_call_->SetStats(stats);
cricket::VideoMediaInfo info;
ASSERT_TRUE(channel_->GetStats(cricket::StatsOptions(), &info));
ASSERT_EQ(2u, info.senders.size());
EXPECT_EQ(stats.rtt_ms, info.senders[0].rtt_ms);
EXPECT_EQ(stats.rtt_ms, info.senders[1].rtt_ms);
}
class WebRtcVideoEngine2SimulcastTest : public testing::Test {
public:
WebRtcVideoEngine2SimulcastTest()
: engine_codecs_(engine_.codecs()) {
assert(!engine_codecs_.empty());
bool codec_set = false;
for (size_t i = 0; i < engine_codecs_.size(); ++i) {
if (engine_codecs_[i].name == "red") {
default_red_codec_ = engine_codecs_[i];
} else if (engine_codecs_[i].name == "ulpfec") {
default_ulpfec_codec_ = engine_codecs_[i];
} else if (engine_codecs_[i].name == "rtx") {
default_rtx_codec_ = engine_codecs_[i];
} else if (!codec_set) {
default_codec_ = engine_codecs_[i];
codec_set = true;
}
}
assert(codec_set);
}
protected:
WebRtcVideoEngine2 engine_;
VideoCodec default_codec_;
VideoCodec default_red_codec_;
VideoCodec default_ulpfec_codec_;
VideoCodec default_rtx_codec_;
// TODO(pbos): Remove engine_codecs_ unless used a lot.
std::vector<VideoCodec> engine_codecs_;
};
class WebRtcVideoChannel2SimulcastTest : public WebRtcVideoEngine2SimulcastTest,
public WebRtcCallFactory {
public:
WebRtcVideoChannel2SimulcastTest() : fake_call_(NULL) {}
virtual void SetUp() OVERRIDE {
engine_.SetCallFactory(this);
engine_.Init(rtc::Thread::Current());
channel_.reset(engine_.CreateChannel(VideoOptions(), NULL));
ASSERT_TRUE(fake_call_ != NULL) << "Call not created through factory.";
last_ssrc_ = 123;
}
protected:
virtual webrtc::Call* CreateCall(
const webrtc::Call::Config& config) OVERRIDE {
assert(fake_call_ == NULL);
fake_call_ = new FakeCall(config);
return fake_call_;
}
void VerifySimulcastSettings(const VideoCodec& codec,
VideoOptions::HighestBitrate bitrate_mode,
size_t num_configured_streams,
size_t expected_num_streams,
SimulcastBitrateMode simulcast_bitrate_mode) {
cricket::VideoOptions options;
options.video_highest_bitrate.Set(bitrate_mode);
EXPECT_TRUE(channel_->SetOptions(options));
std::vector<VideoCodec> codecs;
codecs.push_back(codec);
ASSERT_TRUE(channel_->SetSendCodecs(codecs));
std::vector<uint32> ssrcs = MAKE_VECTOR(kSsrcs3);
assert(num_configured_streams <= ssrcs.size());
ssrcs.resize(num_configured_streams);
FakeVideoSendStream* stream =
AddSendStream(CreateSimStreamParams("cname", ssrcs));
// Send a full-size frame to trigger a stream reconfiguration to use all
// expected simulcast layers.
cricket::FakeVideoCapturer capturer;
EXPECT_TRUE(channel_->SetCapturer(ssrcs.front(), &capturer));
EXPECT_EQ(cricket::CS_RUNNING, capturer.Start(cricket::VideoFormat(
codec.width, codec.height,
cricket::VideoFormat::FpsToInterval(30),
cricket::FOURCC_I420)));
channel_->SetSend(true);
EXPECT_TRUE(capturer.CaptureFrame());
std::vector<webrtc::VideoStream> video_streams = stream->GetVideoStreams();
ASSERT_EQ(expected_num_streams, video_streams.size());
std::vector<webrtc::VideoStream> expected_streams = GetSimulcastConfig(
num_configured_streams,
simulcast_bitrate_mode,
codec.width,
codec.height,
0,
kDefaultQpMax,
codec.framerate != 0 ? codec.framerate : kDefaultFramerate);
ASSERT_EQ(expected_streams.size(), video_streams.size());
size_t num_streams = video_streams.size();
for (size_t i = 0; i < num_streams; ++i) {
EXPECT_EQ(expected_streams[i].width, video_streams[i].width);
EXPECT_EQ(expected_streams[i].height, video_streams[i].height);
EXPECT_GT(video_streams[i].max_framerate, 0);
EXPECT_EQ(expected_streams[i].max_framerate,
video_streams[i].max_framerate);
EXPECT_GT(video_streams[i].min_bitrate_bps, 0);
EXPECT_EQ(expected_streams[i].min_bitrate_bps,
video_streams[i].min_bitrate_bps);
EXPECT_GT(video_streams[i].target_bitrate_bps, 0);
EXPECT_EQ(expected_streams[i].target_bitrate_bps,
video_streams[i].target_bitrate_bps);
EXPECT_GT(video_streams[i].max_bitrate_bps, 0);
EXPECT_EQ(expected_streams[i].max_bitrate_bps,
video_streams[i].max_bitrate_bps);
EXPECT_GT(video_streams[i].max_qp, 0);
EXPECT_EQ(expected_streams[i].max_qp, video_streams[i].max_qp);
EXPECT_FALSE(expected_streams[i].temporal_layer_thresholds_bps.empty());
EXPECT_EQ(expected_streams[i].temporal_layer_thresholds_bps,
video_streams[i].temporal_layer_thresholds_bps);
}
EXPECT_TRUE(channel_->SetCapturer(ssrcs.front(), NULL));
}
FakeVideoSendStream* AddSendStream() {
return AddSendStream(StreamParams::CreateLegacy(last_ssrc_++));
}
FakeVideoSendStream* AddSendStream(const StreamParams& sp) {
size_t num_streams =
fake_call_->GetVideoSendStreams().size();
EXPECT_TRUE(channel_->AddSendStream(sp));
std::vector<FakeVideoSendStream*> streams =
fake_call_->GetVideoSendStreams();
EXPECT_EQ(num_streams + 1, streams.size());
return streams[streams.size() - 1];
}
std::vector<FakeVideoSendStream*> GetFakeSendStreams() {
return fake_call_->GetVideoSendStreams();
}
FakeVideoReceiveStream* AddRecvStream() {
return AddRecvStream(StreamParams::CreateLegacy(last_ssrc_++));
}
FakeVideoReceiveStream* AddRecvStream(const StreamParams& sp) {
size_t num_streams =
fake_call_->GetVideoReceiveStreams().size();
EXPECT_TRUE(channel_->AddRecvStream(sp));
std::vector<FakeVideoReceiveStream*> streams =
fake_call_->GetVideoReceiveStreams();
EXPECT_EQ(num_streams + 1, streams.size());
return streams[streams.size() - 1];
}
FakeCall* fake_call_;
rtc::scoped_ptr<VideoMediaChannel> channel_;
uint32 last_ssrc_;
};
TEST_F(WebRtcVideoChannel2SimulcastTest, SetSendCodecsWith2SimulcastStreams) {
VerifySimulcastSettings(kVp8Codec, VideoOptions::NORMAL, 2, 2, SBM_NORMAL);
}
TEST_F(WebRtcVideoChannel2SimulcastTest, SetSendCodecsWith3SimulcastStreams) {
VerifySimulcastSettings(
kVp8Codec720p, VideoOptions::NORMAL, 3, 3, SBM_NORMAL);
}
TEST_F(WebRtcVideoChannel2SimulcastTest,
SetSendCodecsWith2SimulcastStreamsHighBitrateMode) {
VerifySimulcastSettings(kVp8Codec, VideoOptions::HIGH, 2, 2, SBM_HIGH);
}
TEST_F(WebRtcVideoChannel2SimulcastTest,
SetSendCodecsWith3SimulcastStreamsHighBitrateMode) {
VerifySimulcastSettings(kVp8Codec720p, VideoOptions::HIGH, 3, 3, SBM_HIGH);
}
TEST_F(WebRtcVideoChannel2SimulcastTest,
SetSendCodecsWith2SimulcastStreamsVeryHighBitrateMode) {
VerifySimulcastSettings(
kVp8Codec, VideoOptions::VERY_HIGH, 2, 2, SBM_VERY_HIGH);
}
TEST_F(WebRtcVideoChannel2SimulcastTest,
SetSendCodecsWith3SimulcastStreamsVeryHighBitrateMode) {
VerifySimulcastSettings(
kVp8Codec720p, VideoOptions::VERY_HIGH, 3, 3, SBM_VERY_HIGH);
}
// Test that we normalize send codec format size in simulcast.
TEST_F(WebRtcVideoChannel2SimulcastTest, SetSendCodecsWithOddSizeInSimulcast) {
cricket::VideoCodec codec(kVp8Codec270p);
codec.width += 1;
codec.height += 1;
VerifySimulcastSettings(codec, VideoOptions::NORMAL, 2, 2, SBM_NORMAL);
}
// Test that if we add a stream with RTX SSRC's, SSRC's get set correctly.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_TestStreamWithRtx) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that if we get too few ssrcs are given in AddSendStream(),
// only supported sub-streams will be added.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_TooFewSimulcastSsrcs) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that even more than enough ssrcs are given in AddSendStream(),
// only supported sub-streams will be added.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_MoreThanEnoughSimulcastSscrs) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that SetSendStreamFormat works well with simulcast.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_SetSendStreamFormatWithSimulcast) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that simulcast send codec is reset on new video frame size.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_ResetSimulcastSendCodecOnNewFrameSize) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that simulcast send codec is reset on new portait mode video frame.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_ResetSimulcastSendCodecOnNewPortaitFrame) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_SetBandwidthInConferenceWithSimulcast) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that sending screencast frames in conference mode changes
// bitrate.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_SetBandwidthScreencastInConference) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test AddSendStream with simulcast rejects bad StreamParams.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_AddSendStreamWithBadStreamParams) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test AddSendStream with simulcast sets ssrc and cname correctly.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_AddSendStreamWithSimulcast) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test RemoveSendStream with simulcast.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_RemoveSendStreamWithSimulcast) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test AddSendStream after send codec has already been set will reset
// send codec with simulcast settings.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_AddSimulcastStreamAfterSetSendCodec) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_GetStatsWithMultipleSsrcs) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test receiving channel(s) local ssrc is set to the same as the first
// simulcast sending ssrc.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_AddSimulcastStreamAfterCreatingRecvChannels) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test 1:1 call never turn on simulcast.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_NoSimulcastWith1on1) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test SetOptions with OPT_CONFERENCE flag.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_SetOptionsWithConferenceMode) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that two different streams can have different formats.
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_MultipleSendStreamsDifferentFormats) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_TestAdaptToOutputFormat) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_TestAdaptToCpuLoad) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_TestAdaptToCpuLoadDisabled) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_TestAdaptWithCpuOveruseObserver) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test that codec is not reset for every frame sent in non-conference and
// non-screencast mode.
TEST_F(WebRtcVideoEngine2SimulcastTest, DISABLED_DontResetCodecOnSendFrame) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_UseSimulcastAdapterOnVp8OnlyFactory) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_DontUseSimulcastAdapterOnNoneVp8Factory) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoEngine2SimulcastTest,
DISABLED_DontUseSimulcastAdapterOnMultipleCodecsFactory) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_1280x800) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_1280x720) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_960x540) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_960x600) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_640x400) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_640x360) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_480x300) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest,
DISABLED_DISABLED_SimulcastSend_480x270) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_320x200) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastSend_320x180) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test reset send codec with simulcast.
// Disabled per b/6773425
TEST_F(WebRtcVideoChannel2SimulcastTest,
DISABLED_DISABLED_SimulcastResetSendCodec) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Test simulcast streams are decodeable with expected sizes.
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_SimulcastStreams) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Simulcast and resolution resizing should be turned off when screencasting
// but not otherwise.
TEST_F(WebRtcVideoChannel2SimulcastTest, DISABLED_ScreencastRendering) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Ensures that the correct settings are applied to the codec when single
// temporal layer screencasting is enabled, and that the correct simulcast
// settings are reapplied when disabling screencasting.
TEST_F(WebRtcVideoChannel2SimulcastTest,
DISABLED_OneTemporalLayerScreencastSettings) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
// Ensures that the correct settings are applied to the codec when two temporal
// layer screencasting is enabled, and that the correct simulcast settings are
// reapplied when disabling screencasting.
TEST_F(WebRtcVideoChannel2SimulcastTest,
DISABLED_TwoTemporalLayerScreencastSettings) {
// TODO(pbos): Implement.
FAIL() << "Not implemented.";
}
} // namespace cricket
|
{
"content_hash": "5ca6074a0b58b23735e0184e43432113",
"timestamp": "",
"source": "github",
"line_count": 2546,
"max_line_length": 80,
"avg_line_length": 36.00785545954438,
"alnum_prop": 0.725402504472272,
"repo_name": "CTSRD-SOAAP/chromium-42.0.2311.135",
"id": "7dc7693508ea0b577162b62c95909fd2d7d85475",
"size": "93134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third_party/libjingle/source/talk/media/webrtc/webrtcvideoengine2_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "8402"
},
{
"name": "Assembly",
"bytes": "241154"
},
{
"name": "C",
"bytes": "12370053"
},
{
"name": "C++",
"bytes": "266788423"
},
{
"name": "CMake",
"bytes": "27829"
},
{
"name": "CSS",
"bytes": "813488"
},
{
"name": "Emacs Lisp",
"bytes": "2360"
},
{
"name": "Go",
"bytes": "13628"
},
{
"name": "Groff",
"bytes": "5283"
},
{
"name": "HTML",
"bytes": "20131029"
},
{
"name": "Java",
"bytes": "8495790"
},
{
"name": "JavaScript",
"bytes": "12980966"
},
{
"name": "LLVM",
"bytes": "1169"
},
{
"name": "Logos",
"bytes": "6893"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "Makefile",
"bytes": "208709"
},
{
"name": "Objective-C",
"bytes": "1509363"
},
{
"name": "Objective-C++",
"bytes": "7960581"
},
{
"name": "PLpgSQL",
"bytes": "215882"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "432373"
},
{
"name": "Python",
"bytes": "11147426"
},
{
"name": "Ragel in Ruby Host",
"bytes": "104923"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "1207731"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "VimL",
"bytes": "4075"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
}
|
'use strict';
angular.module('badgerApp')
.controller('EditCtrl', function ($scope) {
$scope.message = 'Hello';
});
|
{
"content_hash": "90788b42f6e1ae01488c0c0672c8dd0b",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 45,
"avg_line_length": 20.833333333333332,
"alnum_prop": 0.632,
"repo_name": "FatalBadgers/FatalBadgers",
"id": "576ff8685a516231154f0451df4da4d2bccb7e81",
"size": "125",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "client/app/job/edit/edit.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5889"
},
{
"name": "JavaScript",
"bytes": "112722"
}
],
"symlink_target": ""
}
|
//
// Source.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Query;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Configuration;
using Banshee.ServiceStack;
namespace Banshee.Sources
{
public abstract class Source : ISource
{
private Source parent;
private PropertyStore properties = new PropertyStore ();
protected SourceMessage status_message;
private List<SourceMessage> messages = new List<SourceMessage> ();
private List<Source> child_sources = new List<Source> ();
private ReadOnlyCollection<Source> read_only_children;
private SourceSortType child_sort;
private bool sort_children = true;
private SchemaEntry<string> child_sort_schema;
private SchemaEntry<bool> separate_by_type_schema;
public event EventHandler Updated;
public event EventHandler UserNotifyUpdated;
public event EventHandler MessageNotify;
public event SourceEventHandler ChildSourceAdded;
public event SourceEventHandler ChildSourceRemoved;
public delegate void OpenPropertiesDelegate ();
protected Source (string generic_name, string name, int order) : this (generic_name, name, order, null)
{
}
protected Source (string generic_name, string name, int order, string type_unique_id) : this ()
{
GenericName = generic_name;
Name = name;
Order = order;
TypeUniqueId = type_unique_id;
SourceInitialize ();
}
protected Source ()
{
child_sort = DefaultChildSort;
}
// This method is chained to subclasses intialize methods,
// allowing at any state for delayed intialization by using the empty ctor.
protected virtual void Initialize ()
{
SourceInitialize ();
}
private void SourceInitialize ()
{
// If this source is not defined in Banshee.Services, set its
// ResourceAssembly to the assembly where it is defined.
Assembly asm = Assembly.GetAssembly (this.GetType ());//Assembly.GetCallingAssembly ();
if (asm != Assembly.GetExecutingAssembly ()) {
Properties.Set<Assembly> ("ResourceAssembly", asm);
}
properties.PropertyChanged += OnPropertyChanged;
read_only_children = new ReadOnlyCollection<Source> (child_sources);
if (ApplicationContext.Debugging && ApplicationContext.CommandLine.Contains ("test-source-messages")) {
TestMessages ();
}
LoadSortSchema ();
}
protected void OnSetupComplete ()
{
/*ITrackModelSource tm_source = this as ITrackModelSource;
if (tm_source != null) {
tm_source.TrackModel.Parent = this;
ServiceManager.DBusServiceManager.RegisterObject (tm_source.TrackModel);
// TODO if/when browsable models can be added/removed on the fly, this would need to change to reflect that
foreach (IListModel model in tm_source.FilterModels) {
Banshee.Collection.ExportableModel exportable = model as Banshee.Collection.ExportableModel;
if (exportable != null) {
exportable.Parent = this;
ServiceManager.DBusServiceManager.RegisterObject (exportable);
}
}
}*/
}
protected void Remove ()
{
if (prefs_page != null) {
prefs_page.Dispose ();
}
if (ServiceManager.SourceManager.ContainsSource (this)) {
if (this.Parent != null) {
this.Parent.RemoveChildSource (this);
} else {
ServiceManager.SourceManager.RemoveSource (this);
}
}
}
protected void PauseSorting ()
{
sort_children = false;
}
protected void ResumeSorting ()
{
sort_children = true;
}
#region Public Methods
public virtual void Activate ()
{
}
public virtual void Deactivate ()
{
}
public virtual void Rename (string newName)
{
properties.SetString ("Name", newName);
}
public virtual bool AcceptsInputFromSource (Source source)
{
return false;
}
public virtual bool AcceptsUserInputFromSource (Source source)
{
return AcceptsInputFromSource (source);
}
public virtual void MergeSourceInput (Source source, SourceMergeType mergeType)
{
Log.ErrorFormat ("MergeSourceInput not implemented by {0}", this);
}
public virtual SourceMergeType SupportedMergeTypes {
get { return SourceMergeType.None; }
}
public virtual void SetParentSource (Source parent)
{
this.parent = parent;
}
public virtual bool ContainsChildSource (Source child)
{
lock (Children) {
return child_sources.Contains (child);
}
}
public virtual void AddChildSource (Source child)
{
lock (Children) {
if (!child_sources.Contains (child)) {
child.SetParentSource (this);
child_sources.Add (child);
OnChildSourceAdded (child);
}
}
}
public virtual void RemoveChildSource (Source child)
{
lock (Children) {
if (child.Children.Count > 0) {
child.ClearChildSources ();
}
child_sources.Remove (child);
if (ServiceManager.SourceManager.ActiveSource == child) {
if (CanActivate) {
ServiceManager.SourceManager.SetActiveSource (this);
}
}
OnChildSourceRemoved (child);
}
}
public virtual void ClearChildSources ()
{
lock (Children) {
while (child_sources.Count > 0) {
RemoveChildSource (child_sources[child_sources.Count - 1]);
}
}
}
private class SizeComparer : IComparer<Source>
{
public int Compare (Source a, Source b)
{
return a.Count.CompareTo (b.Count);
}
}
public virtual void SortChildSources (SourceSortType sort_type)
{
child_sort = sort_type;
child_sort_schema.Set (child_sort.Id);
SortChildSources ();
}
public virtual void SortChildSources ()
{
lock (this) {
if (!sort_children) {
return;
}
sort_children = false;
}
if (child_sort != null && child_sort.SortType != SortType.None) {
lock (Children) {
child_sort.Sort (child_sources, SeparateChildrenByType);
int i = 0;
foreach (Source child in child_sources) {
// Leave children with negative orders alone, so they can be manually
// placed at the top
if (child.Order >= 0) {
child.Order = i++;
}
}
}
}
sort_children = true;
}
private void LoadSortSchema ()
{
if (ChildSortTypes.Length == 0) {
return;
}
if (unique_id == null && type_unique_id == null) {
Hyena.Log.WarningFormat ("Trying to LoadSortSchema, but source's id not set! {0}", UniqueId);
return;
}
child_sort_schema = CreateSchema<string> ("child_sort_id", DefaultChildSort.Id, "", "");
string child_sort_id = child_sort_schema.Get ();
foreach (SourceSortType sort_type in ChildSortTypes) {
if (sort_type.Id == child_sort_id) {
child_sort = sort_type;
break;
}
}
separate_by_type_schema = CreateSchema<bool> ("separate_by_type", false, "", "");
SortChildSources ();
}
public T GetProperty<T> (string name, bool inherited)
{
return inherited ? GetInheritedProperty<T> (name) : Properties.Get<T> (name);
}
public T GetInheritedProperty<T> (string name)
{
return Properties.Contains (name)
? Properties.Get<T> (name)
: Parent != null
? Parent.GetInheritedProperty<T> (name)
: default (T);
}
#endregion
#region Protected Methods
public virtual void SetStatus (string message, bool error)
{
SetStatus (message, !error, !error, error ? "dialog-error" : null);
}
public virtual void SetStatus (string message, bool can_close, bool is_spinning, string icon_name)
{
lock (this) {
if (status_message == null) {
status_message = new SourceMessage (this);
PushMessage (status_message);
}
string status_name = String.Format ("<i>{0}</i>", GLib.Markup.EscapeText (Name));
status_message.FreezeNotify ();
status_message.Text = String.Format (GLib.Markup.EscapeText (message), status_name);
status_message.CanClose = can_close;
status_message.IsSpinning = is_spinning;
status_message.SetIconName (icon_name);
status_message.IsHidden = false;
status_message.ClearActions ();
}
status_message.ThawNotify ();
}
public virtual void HideStatus ()
{
lock (this) {
if (status_message != null) {
RemoveMessage (status_message);
status_message = null;
}
}
}
public void PushMessage (SourceMessage message)
{
lock (this) {
messages.Insert (0, message);
message.Updated += HandleMessageUpdated;
}
OnMessageNotify ();
}
protected SourceMessage PopMessage ()
{
try {
lock (this) {
if (messages.Count > 0) {
SourceMessage message = messages[0];
message.Updated -= HandleMessageUpdated;
messages.RemoveAt (0);
return message;
}
return null;
}
} finally {
OnMessageNotify ();
}
}
protected void ClearMessages ()
{
lock (this) {
if (messages.Count > 0) {
foreach (SourceMessage message in messages) {
message.Updated -= HandleMessageUpdated;
}
messages.Clear ();
OnMessageNotify ();
}
status_message = null;
}
}
private void TestMessages ()
{
int count = 0;
SourceMessage message_3 = null;
Application.RunTimeout (5000, delegate {
if (count++ > 5) {
if (count == 7) {
RemoveMessage (message_3);
}
PopMessage ();
return true;
} else if (count > 10) {
return false;
}
SourceMessage message = new SourceMessage (this);
message.FreezeNotify ();
message.Text = String.Format ("Testing message {0}", count);
message.IsSpinning = count % 2 == 0;
message.CanClose = count % 2 == 1;
if (count % 3 == 0) {
for (int i = 2; i < count; i++) {
message.AddAction (new MessageAction (String.Format ("Button {0}", i)));
}
}
message.ThawNotify ();
PushMessage (message);
if (count == 3) {
message_3 = message;
}
return true;
});
}
public void RemoveMessage (SourceMessage message)
{
lock (this) {
if (messages.Remove (message)) {
message.Updated -= HandleMessageUpdated;
OnMessageNotify ();
}
}
}
private void HandleMessageUpdated (object o, EventArgs args)
{
if (CurrentMessage == o && CurrentMessage.IsHidden) {
PopMessage ();
}
OnMessageNotify ();
}
protected virtual void OnMessageNotify ()
{
EventHandler handler = MessageNotify;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnChildSourceAdded (Source source)
{
SortChildSources ();
source.Updated += OnChildSourceUpdated;
ThreadAssist.ProxyToMain (delegate {
SourceEventHandler handler = ChildSourceAdded;
if (handler != null) {
SourceEventArgs args = new SourceEventArgs ();
args.Source = source;
handler (args);
}
});
}
protected virtual void OnChildSourceRemoved (Source source)
{
source.Updated -= OnChildSourceUpdated;
ThreadAssist.ProxyToMain (delegate {
SourceEventHandler handler = ChildSourceRemoved;
if (handler != null) {
SourceEventArgs args = new SourceEventArgs ();
args.Source = source;
handler (args);
}
});
}
protected virtual void OnUpdated ()
{
EventHandler handler = Updated;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnChildSourceUpdated (object o, EventArgs args)
{
SortChildSources ();
}
public void NotifyUser ()
{
OnUserNotifyUpdated ();
}
protected void OnUserNotifyUpdated ()
{
if (this != ServiceManager.SourceManager.ActiveSource) {
EventHandler handler = UserNotifyUpdated;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
}
#endregion
#region Private Methods
private void OnPropertyChanged (object o, PropertyChangeEventArgs args)
{
OnUpdated ();
}
#endregion
#region Public Properties
public ReadOnlyCollection<Source> Children {
get { return read_only_children; }
}
string [] ISource.Children {
get { return null; }
}
public Source Parent {
get { return parent; }
}
public virtual string TypeName {
get { return GetType ().Name; }
}
private string unique_id;
public string UniqueId {
get {
if (unique_id == null && type_unique_id == null) {
Log.ErrorFormat ("Creating Source.UniqueId for {0} (type {1}), but TypeUniqueId is null; trace is {2}", this.Name, GetType ().Name, System.Environment.StackTrace);
}
return unique_id ?? (unique_id = String.Format ("{0}-{1}", this.GetType ().Name, TypeUniqueId));
}
}
private string type_unique_id;
protected string TypeUniqueId {
get { return type_unique_id; }
set { type_unique_id = value; }
}
public virtual bool CanRename {
get { return false; }
}
public virtual bool HasProperties {
get { return false; }
}
public virtual bool HasViewableTrackProperties {
get { return false; }
}
public virtual bool HasEditableTrackProperties {
get { return false; }
}
public virtual string Name {
get { return properties.Get<string> ("Name"); }
set { properties.SetString ("Name", value); }
}
public virtual string GenericName {
get { return properties.Get<string> ("GenericName"); }
set { properties.SetString ("GenericName", value); }
}
public int Order {
get { return properties.GetInteger ("Order"); }
set { properties.SetInteger ("Order", value); }
}
public SourceMessage CurrentMessage {
get { lock (this) { return messages.Count > 0 ? messages[0] : null; } }
}
public virtual bool ImplementsCustomSearch {
get { return false; }
}
public virtual bool CanSearch {
get { return false; }
}
public virtual string FilterQuery {
get { return properties.Get<string> ("FilterQuery"); }
set { properties.SetString ("FilterQuery", value); }
}
public TrackFilterType FilterType {
get { return (TrackFilterType)properties.GetInteger ("FilterType"); }
set { properties.SetInteger ("FilterType", (int)value); }
}
public virtual bool Expanded {
get { return properties.GetBoolean ("Expanded"); }
set { properties.SetBoolean ("Expanded", value); }
}
public virtual bool? AutoExpand {
get { return true; }
}
public virtual PropertyStore Properties {
get { return properties; }
}
public virtual bool CanActivate {
get { return true; }
}
public virtual int Count {
get { return 0; }
}
public virtual int EnabledCount {
get { return Count; }
}
private string parent_conf_id;
public string ParentConfigurationId {
get {
if (parent_conf_id == null) {
parent_conf_id = (Parent ?? this).UniqueId.Replace ('.', '_');
}
return parent_conf_id;
}
}
private string conf_id;
public string ConfigurationId {
get { return conf_id ?? (conf_id = UniqueId.Replace ('.', '_')); }
}
public virtual int FilteredCount { get { return Count; } }
public virtual string TrackModelPath {
get { return null; }
}
public static readonly SourceSortType SortNameAscending = new SourceSortType (
"NameAsc",
Catalog.GetString ("Name"),
SortType.Ascending, null); // null comparer b/c we already fall back to sorting by name
public static readonly SourceSortType SortSizeAscending = new SourceSortType (
"SizeAsc",
Catalog.GetString ("Size Ascending"),
SortType.Ascending, new SizeComparer ());
public static readonly SourceSortType SortSizeDescending = new SourceSortType (
"SizeDesc",
Catalog.GetString ("Size Descending"),
SortType.Descending, new SizeComparer ());
private static SourceSortType[] sort_types = new SourceSortType[] {};
public virtual SourceSortType[] ChildSortTypes {
get { return sort_types; }
}
public SourceSortType ActiveChildSort {
get { return child_sort; }
}
public virtual SourceSortType DefaultChildSort {
get { return null; }
}
public bool SeparateChildrenByType {
get { return separate_by_type_schema.Get (); }
set {
separate_by_type_schema.Set (value);
SortChildSources ();
}
}
#endregion
#region Status Message Stuff
private static DurationStatusFormatters duration_status_formatters = new DurationStatusFormatters ();
public static DurationStatusFormatters DurationStatusFormatters {
get { return duration_status_formatters; }
}
protected virtual int StatusFormatsCount {
get { return duration_status_formatters.Count; }
}
public virtual int CurrentStatusFormat {
get { return ConfigurationClient.Get<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", 0); }
set { ConfigurationClient.Set<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", value); }
}
public SchemaEntry<T> CreateSchema<T> (string name)
{
return CreateSchema<T> (name, default(T), null, null);
}
public SchemaEntry<T> CreateSchema<T> (string name, T defaultValue, string shortDescription, string longDescription)
{
return new SchemaEntry<T> (String.Format ("sources.{0}", ParentConfigurationId), name, defaultValue, shortDescription, longDescription);
}
public SchemaEntry<T> CreateSchema<T> (string ns, string name, T defaultValue, string shortDescription, string longDescription)
{
return new SchemaEntry<T> (String.Format ("sources.{0}.{1}", ParentConfigurationId, ns), name, defaultValue, shortDescription, longDescription);
}
public virtual string PreferencesPageId {
get { return null; }
}
private Banshee.Preferences.SourcePage prefs_page;
public Banshee.Preferences.Page PreferencesPage {
get {
return prefs_page ?? (prefs_page = new Banshee.Preferences.SourcePage (this));
}
}
public void CycleStatusFormat ()
{
int new_status_format = CurrentStatusFormat + 1;
if (new_status_format >= StatusFormatsCount) {
new_status_format = 0;
}
CurrentStatusFormat = new_status_format;
}
private const string STATUS_BAR_SEPARATOR = " \u2013 ";
public virtual string GetStatusText ()
{
StringBuilder builder = new StringBuilder ();
int count = FilteredCount;
if (count == 0) {
return String.Empty;
}
var count_str = String.Format ("{0:N0}", count);
builder.AppendFormat (GetPluralItemCountString (count), count_str);
if (this is IDurationAggregator && StatusFormatsCount > 0) {
var duration = ((IDurationAggregator)this).Duration;
if (duration > TimeSpan.Zero) {
builder.Append (STATUS_BAR_SEPARATOR);
duration_status_formatters[CurrentStatusFormat] (builder, ((IDurationAggregator)this).Duration);
}
}
if (this is IFileSizeAggregator) {
long bytes = (this as IFileSizeAggregator).FileSize;
if (bytes > 0) {
builder.Append (STATUS_BAR_SEPARATOR);
builder.AppendFormat (new FileSizeQueryValue (bytes).ToUserQuery ());
}
}
return builder.ToString ();
}
public virtual string GetPluralItemCountString (int count)
{
return Catalog.GetPluralString ("{0} item", "{0} items", count);
}
#endregion
public override string ToString ()
{
return Name;
}
/*string IService.ServiceName {
get { return String.Format ("{0}{1}", DBusServiceManager.MakeDBusSafeString (Name), "Source"); }
}*/
// FIXME: Replace ISource with IDBusExportable when it's enabled again
ISource ISource.Parent {
get {
if (Parent != null) {
return ((Source)this).Parent;
} else {
return null /*ServiceManager.SourceManager*/;
}
}
}
}
}
|
{
"content_hash": "cbbb5e297410dfd0f32dded2cf417f18",
"timestamp": "",
"source": "github",
"line_count": 821,
"max_line_length": 183,
"avg_line_length": 31.982947624847746,
"alnum_prop": 0.5312666615888492,
"repo_name": "directhex/banshee-hacks",
"id": "a9cbee4e7986f0072641f0c0ef29d0c63383e53b",
"size": "26258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Core/Banshee.Services/Banshee.Sources/Source.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Boo",
"bytes": "3305"
},
{
"name": "C",
"bytes": "261313"
},
{
"name": "C#",
"bytes": "5376996"
},
{
"name": "JavaScript",
"bytes": "497"
},
{
"name": "Python",
"bytes": "964"
},
{
"name": "R",
"bytes": "3362"
},
{
"name": "Shell",
"bytes": "3482"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of Degree in UD_Gothic</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/got_proiel/got-feat-Degree.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_gothic-features-degree">Treebank Statistics: UD_Gothic: Features: <code class="language-plaintext highlighter-rouge">Degree</code></h2>
<p>This feature is universal.
It occurs with 3 different values: <code class="language-plaintext highlighter-rouge">Cmp</code>, <code class="language-plaintext highlighter-rouge">Pos</code>, <code class="language-plaintext highlighter-rouge">Sup</code>.</p>
<p>2455 tokens (4%) have a non-empty value of <code class="language-plaintext highlighter-rouge">Degree</code>.
988 types (11%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Degree</code>.
369 lemmas (11%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Degree</code>.
The feature is used with 2 part-of-speech tags: <tt><a href="got-pos-ADJ.html">ADJ</a></tt> (2306; 4% instances), <tt><a href="got-pos-ADV.html">ADV</a></tt> (149; 0% instances).</p>
<h3 id="adj"><code class="language-plaintext highlighter-rouge">ADJ</code></h3>
<p>2306 <tt><a href="got-pos-ADJ.html">ADJ</a></tt> tokens (48% of all <code class="language-plaintext highlighter-rouge">ADJ</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Degree</code>.</p>
<p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">ADJ</code> and <code class="language-plaintext highlighter-rouge">Degree</code> co-occurred: <tt><a href="got-feat-Person.html">Person</a></tt><tt>=EMPTY</tt> (2306; 100%), <tt><a href="got-feat-Poss.html">Poss</a></tt><tt>=EMPTY</tt> (2306; 100%), <tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt> (1580; 69%), <tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt> (1415; 61%), <tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt> (1316; 57%).</p>
<p><code class="language-plaintext highlighter-rouge">ADJ</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Degree</code>:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">Cmp</code> (113; 5% of non-empty <code class="language-plaintext highlighter-rouge">Degree</code>): <em>managizo, maiza, fruma, sutizo, azetizo, iftumin, batizo, frumin, hleidumein, maizo</em></li>
<li><code class="language-plaintext highlighter-rouge">Pos</code> (2077; 90% of non-empty <code class="language-plaintext highlighter-rouge">Degree</code>): <em>managai, anþar, silba, dauþaim, silban, anþara, silbans, leitil, goþ, managans</em></li>
<li><code class="language-plaintext highlighter-rouge">Sup</code> (116; 5% of non-empty <code class="language-plaintext highlighter-rouge">Degree</code>): <em>auhumistans, frumista, spedistin, sinistam, hauhistins, sinistans, auhumista, auhumistins, auhumistam, frumistin</em></li>
<li><code class="language-plaintext highlighter-rouge">EMPTY</code> (2471): <em>þata, sa, þo, ƕas, all, seinamma, sumai, meina, izwara, meinamma</em></li>
</ul>
<table>
<tr><th>Paradigm <i>manags</i></th><th><tt>Pos</tt></th><th><tt>Cmp</tt></th><th><tt>Sup</tt></th></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managans</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td><em>managans</em></td><td><em>managizans</em></td><td><em>managistans</em></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managa</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managos</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td></td><td><em>managizeins</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>manag</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td></td><td><em>managizo</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Acc</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managa</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc,Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managamma</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaim</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td><em>managam</em></td><td><em>managizam</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managai</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td></td><td><em>managizein</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaim</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td></td><td><em>managizeim</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managamma</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaim</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Dat</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaim</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaize</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaizos</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td><em>managons</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Gen</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managaize</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managai</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Masc</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td><em>managans</em></td><td></td><td><em>managistans</em></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managa</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td></td><td><em>managizo</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managos</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Fem</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td><em>managons</em></td><td></td><td><em>managistons</em></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>manag</em></td><td></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Weak</tt></tt></td><td></td><td><em>managizo</em></td><td></td></tr>
<tr><td><tt><tt><a href="got-feat-Case.html">Case</a></tt><tt>=Nom</tt>|<tt><a href="got-feat-Gender.html">Gender</a></tt><tt>=Neut</tt>|<tt><a href="got-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="got-feat-Strength.html">Strength</a></tt><tt>=Strong</tt></tt></td><td><em>managa</em></td><td></td><td></td></tr>
</table>
<p><code class="language-plaintext highlighter-rouge">Degree</code> seems to be <strong>lexical feature</strong> of <code class="language-plaintext highlighter-rouge">ADJ</code>. 94% lemmas (335) occur only with one value of <code class="language-plaintext highlighter-rouge">Degree</code>.</p>
<h3 id="adv"><code class="language-plaintext highlighter-rouge">ADV</code></h3>
<p>149 <tt><a href="got-pos-ADV.html">ADV</a></tt> tokens (3% of all <code class="language-plaintext highlighter-rouge">ADV</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Degree</code>.</p>
<p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">ADV</code> and <code class="language-plaintext highlighter-rouge">Degree</code> co-occurred: <tt><a href="got-feat-Polarity.html">Polarity</a></tt><tt>=EMPTY</tt> (149; 100%), <tt><a href="got-feat-PronType.html">PronType</a></tt><tt>=EMPTY</tt> (149; 100%).</p>
<p><code class="language-plaintext highlighter-rouge">ADV</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Degree</code>:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">Cmp</code> (58; 39% of non-empty <code class="language-plaintext highlighter-rouge">Degree</code>): <em>mais, aljaleikos, mins, airis, framis, hauhis, sniumundos, wairs</em></li>
<li><code class="language-plaintext highlighter-rouge">Pos</code> (78; 52% of non-empty <code class="language-plaintext highlighter-rouge">Degree</code>): <em>filu, sniumundo, fram, uhteigo, usdaudo</em></li>
<li><code class="language-plaintext highlighter-rouge">Sup</code> (13; 9% of non-empty <code class="language-plaintext highlighter-rouge">Degree</code>): <em>frumist</em></li>
<li><code class="language-plaintext highlighter-rouge">EMPTY</code> (4986): <em>ni, þan, jah, auk, nu, unte, swe, swaswe, swa, aftra</em></li>
</ul>
<table>
<tr><th>Paradigm <i>sniumundo</i></th><th><tt>Pos</tt></th><th><tt>Cmp</tt></th></tr>
<tr><td><tt></tt></td><td><em>sniumundo</em></td><td><em>sniumundos</em></td></tr>
</table>
<h2 id="relations-with-agreement-in-degree">Relations with Agreement in <code class="language-plaintext highlighter-rouge">Degree</code></h2>
<p>The 10 most frequent relations where parent and child node agree in <code class="language-plaintext highlighter-rouge">Degree</code>:
<tt>ADJ –[<tt><a href="got-dep-conj.html">conj</a></tt>]–> ADJ</tt> (84; 94%),
<tt>ADJ –[<tt><a href="got-dep-amod.html">amod</a></tt>]–> ADJ</tt> (20; 77%),
<tt>ADJ –[<tt><a href="got-dep-advmod.html">advmod</a></tt>]–> ADJ</tt> (10; 91%),
<tt>ADJ –[<tt><a href="got-dep-advcl.html">advcl</a></tt>]–> ADJ</tt> (2; 100%),
<tt>ADJ –[<tt><a href="got-dep-flat.html">flat</a></tt>]–> ADJ</tt> (1; 100%).</p>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<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-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
|
{
"content_hash": "fde99202b17fc6c968c7b1230d6a45e5",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 596,
"avg_line_length": 91.84016393442623,
"alnum_prop": 0.6288991030389576,
"repo_name": "UniversalDependencies/universaldependencies.github.io",
"id": "ea8666966e0d38f6d4eb2f85e8c2a4e6f0b31974",
"size": "22439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "treebanks/got_proiel/got-feat-Degree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "64420"
},
{
"name": "HTML",
"bytes": "383191916"
},
{
"name": "JavaScript",
"bytes": "687350"
},
{
"name": "Perl",
"bytes": "7788"
},
{
"name": "Python",
"bytes": "21203"
},
{
"name": "Shell",
"bytes": "7253"
}
],
"symlink_target": ""
}
|
typedef enum {
SENDER,
RECEIVER
} Reporter_t;
typedef struct {
char *address;
int port;
int sock;
int packet_size;
float bitrate;
pthread_t thread;
pthread_mutex_t lock;
float **results;
int nresults;
int nreporters;
int rsize;
} Reporter;
typedef struct {
int sock;
pthread_t thread_id;
Reporter *reporter;
} listener_thread_data;
Reporter* createReporter(char *address, int port, float bandwidth, int packet_size);
int reportResults(Reporter *r, McastResult **results, int n_tests, int json);
void* listen_for_results(void *args);
void crunchReports(Reporter *r, FILE *out);
void reporterListen(Reporter* r);
void freeReporter(Reporter *r);
void* handle_reporter(void *arg);
#endif
|
{
"content_hash": "fba7bbf1313f4d8e5821c3cea28234e9",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 84,
"avg_line_length": 18.657894736842106,
"alnum_prop": 0.7320169252468265,
"repo_name": "tldr193/multiperf",
"id": "0a604e9f1387922073fc304a9e2d5fb6fec46350",
"size": "918",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reporter.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "40685"
},
{
"name": "Makefile",
"bytes": "430"
}
],
"symlink_target": ""
}
|
import {PolymerElement} from '../deps/@polymer/polymer/polymer-element.js';
import '../deps/@polymer/iron-autogrow-textarea/iron-autogrow-textarea.js';
import '../deps/@vaadin/vaadin-split-layout/vaadin-split-layout.js';
import {MessengerMixin, recipeHtmlify} from './arcs-shared.js';
import {html} from '../deps/@polymer/polymer/lib/utils/html-tag.js';
class ArcsRecipeEditor extends MessengerMixin(PolymerElement) {
static get template() {
return html`
<style include="shared-styles">
:host {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
}
header {
flex-grow: 0;
}
vaadin-split-layout {
flex-grow: 1;
}
[mode] {
padding: 0 8px;
cursor: pointer;
}
.triangle {
margin-left: 12px;
}
iron-dropdown {
padding: 8px 0;
min-width: 200px;
}
header [section][status] {
margin-right: 8px;
}
[list] {
/* Overrides attributes set by the iron-dropdown */
max-width: 50vw !important;
max-height: 70vh !important;
}
[entry] {
line-height: 20px;
}
[entry][header] {
color: var(--dark-gray);
padding: 4px 12px;
}
[entry][selection] {
cursor: pointer;
padding: 4px 20px;
}
[entry][selection]:hover {
color: #fff;
background-color: var(--highlight-blue);
}
[editor] {
position: relative;
overflow: auto;
}
#underline {
position: absolute;
margin-top: -3px;
margin-left: 4px;
border-bottom: 3px dotted red;
pointer-events: none;
z-index: 1;
font-family: Menlo, monospace;
}
iron-autogrow-textarea {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
border: 0;
padding: 0;
margin: 0;
box-sizing: border-box;
--iron-autogrow-textarea: {
box-sizing: border-box;
resize: none;
border: 0;
padding: 0 4px;
font-family: Menlo, monospace;
font-size: 12px;
line-height: 18px;
white-space: nowrap;
background-image: linear-gradient(#fff 50%, #fafafa 50%);
background-size: 100% 36px;
outline: 0;
}
}
[none] {
font-style: italic;
color: var(--dark-gray);
}
[none][padding] {
padding: 8px;
}
[result] {
margin: 8px;
margin-left: 4px;
border: 1px solid var(--mid-gray);
box-shadow: var(--drop-shadow);
}
[derivation] {
padding: 4px;
font-family: Menlo, monospace;
border-bottom: 1px solid var(--mid-gray);
}
[derivation] > div {
margin: 8px 8px;
}
[result] pre {
box-sizing: border-box;
border: 0;
padding: 0 4px;
margin: 0;
font-family: Menlo, monospace;
font-size: 12px;
line-height: 18px;
background-image: linear-gradient(#ececec 50%, #f3f3f3 50%);
background-size: 100% 36px;
word-break: break-all;
white-space: pre-wrap;
}
[result] pre [unresolved] {
color: red;
}
[result] pre [comment] {
color: blue;
}
[result] [error] {
background: #fff0f0;
overflow: auto;
}
[result] [error] pre {
padding: 4px;
color: red;
background: transparent;
}
[result] [dataflow] {
border-top: 1px solid var(--mid-gray);
}
[result] [dataflow]:not([error]) {
background: #f0fff0;
}
[result] [dataflow]:not([error]) pre {
padding: 4px;
color: green;
background: transparent;
}
[suggestion] {
background-color: white;
border: 1px solid var(--mid-gray);
margin: 8px;
padding: 12px 12px 4px 36px;
position: relative;
}
[suggestion] > iron-icon {
position: absolute;
color: var(--focus-blue);
left: 8px;
top: 8px;
}
[suggestion] [message] {
margin-bottom: 8px;
}
[suggestionactionitem] {
border: 1px solid var(--focus-blue);
padding: 8px 12px;
margin-bottom: 8px;
border-radius: 9px;
cursor: pointer;
width: fit-content;
}
[suggestionactionitem]:not(:first-child) {
border-color: var(--mid-gray);
color: var(--mid-gray);
}
[suggestionactionitem]:hover {
background-color: var(--light-focus-blue);
border-color: var(--focus-blue);
color: black;
}
</style>
<header class="header">
<div section>
<div mode on-click="openResolutionDropdown">[[method.displayName]]<span class="triangle devtools-small-icon" expanded></span></div>
<iron-dropdown class="dropdown" id="dropdown" horizontal-align="left" vertical-align="top" vertical-offset="25">
<div slot="dropdown-content" list on-click="resolutionDropdownClicked">
<div entry header>Multi-Strategy:</div>
<template is="dom-repeat" items="[[multiMethods]]">
<div entry selection resolution$="[[item.name]]">[[item.displayName]]</div>
</template>
<div entry header>Single Strategy:</div>
<template is="dom-repeat" items="[[strategies]]">
<div entry selection resolution$="[[item]]">[[item]]</div>
</template>
</div>
</iron-dropdown>
<div divider></div>
<iron-icon title="Run" icon="av:play-arrow" on-click="runPlanner"></iron-icon>
<iron-icon title="Run on change" icon="av:loop" on-click="runOnChange" active$="[[autoRun]]"></iron-icon>
<div divider></div>
<label title="Show strategy derivation of produced recipes" on-click="derivationSettingClicked">
<input type="checkbox" id="derivation-checkbox">
<label for="derivation-checkbox">Show derivation</label>
</label>
<label title="Show dataflow results" on-click="dataflowSettingClicked">
<input type="checkbox" id="dataflow-checkbox">
<label for="dataflow-checkbox">Show dataflow</label>
</label>
</div>
<div section status>[[responseStatus(results)]]</div>
</header>
<vaadin-split-layout>
<div style="flex: .5" editor>
<div id="underline"></div>
<iron-autogrow-textarea value="{{manifest}}" spellcheck="false"></iron-autogrow-textarea>
</div>
<aside style="flex: .5">
<template is="dom-if" if="[[!results.length]]">
<div none padding>No results</div>
</template>
<template is="dom-repeat" items="[[results]]">
<div result>
<template is="dom-if" if="[[and(item.derivation, showDerivation)]]">
<div derivation>
Derivation:
<template is="dom-repeat" items="[[item.derivation]]">
<div>[[item]]</div>
</template>
<template is="dom-if" if="[[!item.derivation.length]]">
<div none>Empty</div>
</template>
</div>
</template>
<pre inner-h-t-m-l="[[item.content]]"></pre>
<template is="dom-if" if="[[and(item.dataflow, showDataflow)]]">
<div dataflow error$=[[!item.dataflow.success]]>
<pre>Dataflow: [[item.dataflow.message]]</pre>
</div>
</template>
<template is="dom-repeat" items="[[item.errors]]">
<div error>
<pre>[[item.error]]</pre>
<template is="dom-if" if="[[item.suggestion]]">
<div suggestion>
<iron-icon title="Suggestion" icon="image:assistant"></iron-icon>
<div message inner-h-t-m-l="[[item.suggestion.message]]"></div>
<div>
<template is="dom-repeat" items="[[item.suggestion.actionItems]]">
<div suggestionactionitem on-click="applySuggestion">[[item.text]]</div>
</template>
</div>
</div>
</template>
</div>
</template>
</div>
</template>
</aside>
</vaadin-split-layout>`;
}
static get is() { return 'arcs-recipe-editor'; }
static get properties() {
return {
manifest: {
type: String,
observer: 'manifestChanged',
value: ''
}
};
}
constructor() {
super();
this.version = 0;
this.autoRun = true;
this.multiMethods = [{
name: 'arc',
displayName: 'Arc Resolution'
}, {
name: 'arc_coalesce',
displayName: 'Arc Resolution + Coalescing'
}];
this.method = this.multiMethods[0];
}
onMessage(msg) {
switch (msg.messageType) {
case 'arc-selected':
this.arcId = msg.messageBody.arcId;
this.runPlanner();
if (!this.strategies) {
this.send({
messageType: 'fetch-strategies',
arcId: this.arcId
});
}
break;
case 'page-refresh':
this.arcId = null;
this.strategies = null;
break;
case 'fetch-strategies-result': {
this.set('strategies', msg.messageBody.slice().sort());
break;
}
case 'invoke-planner-result':
if (this.version === msg.requestId) this.processResponse(msg.messageBody);
break;
}
}
manifestChanged() {
this.$.underline.style.top = null;
this.version++;
if (this.autoRun) {
if (this.autoRunTimeoutId) {
clearTimeout(this.autoRunTimeoutId);
}
this.autoRunTimeoutId = setTimeout(() => this.runPlanner(), 100);
}
}
runPlanner() {
if (!this.arcId) return;
this.send({
messageType: 'invoke-planner',
messageBody: {
manifest: this.manifest,
method: this.method.name
},
arcId: this.arcId,
requestId: this.version
});
}
processResponse(message) {
if (message.error) {
this.processError(message);
} else {
this.processSuccess(message);
}
}
processSuccess({results}) {
this.positionErrorUnderline(null);
this.results = results.map(({recipe, derivation, errors, dataflow}) => ({
content: recipeHtmlify(recipe),
derivation: derivation.sort(),
errors,
dataflow,
unresolvedCount: recipe.split('// unresolved ').length - 1 // Don't judge me.
})).sort((a, b) => a.unresolvedCount - b.unresolvedCount);
}
processError({error, suggestion}) {
this.positionErrorUnderline(error.location);
this.results = [{
content: '',
errors: [{
error: error.message,
suggestion: this.processSuggestion(suggestion)
}],
}];
}
processSuggestion(suggestion) {
if (!suggestion) return null;
switch (suggestion.action) {
case 'import': return {
message: 'Import one of the manifests below:',
actionItems: suggestion.fileNames.map(fileName => ({
text: fileName,
action: {
type: 'import',
path: fileName
}
}))
};
default:
console.warn(`Unrecognized suggestion action: '${suggestion.action}'`);
return;
}
}
positionErrorUnderline(location) {
if (!location) {
this.$.underline.style.top = null;
return;
}
const start = location.start;
const end = location.end.line === start.line ? location.end
: {line: start.line, column: this.manifest.split('\n')[start.line - 1].length + 1};
this.$.underline.style.top = `${start.line * 18}px`;
this.$.underline.style.left = `${start.column - 1}ch`;
this.$.underline.style.width = `${Math.max(1, end.column - start.column)}ch`;
}
runOnChange() {
if (this.autoRun = !this.autoRun) {
this.runPlanner();
}
}
openResolutionDropdown() {
this.$.dropdown.open();
}
applySuggestion(e) {
const action = e.model.item.action;
switch (action.type) {
case 'import': {
const extraLineBreak = !this.manifest.startsWith('import ') && !this.manifest.startsWith('\n');
this.manifest = `import '${action.path}'\n${extraLineBreak ? '\n' : ''}${this.manifest}`;
break;
}
}
}
derivationSettingClicked(e) {
this.showDerivation = this.shadowRoot.querySelector('#derivation-checkbox').checked;
}
dataflowSettingClicked(e) {
this.showDataflow = this.shadowRoot.querySelector('#dataflow-checkbox').checked;
}
resolutionDropdownClicked(e) {
const resolutionAttr = e.path[0].getAttribute('resolution');
if (resolutionAttr) {
this.method = {
name: resolutionAttr,
displayName: e.path[0].innerText
};
this.$.dropdown.close();
this.runPlanner();
}
}
responseStatus(results) {
if (!results || !results.length || results.every(r => !r.content)) return '';
return `${results.length} result${results.length > 1 ? 's' : ''}`;
}
and(one, two) {
return !!one && !!two;
}
}
window.customElements.define(ArcsRecipeEditor.is, ArcsRecipeEditor);
|
{
"content_hash": "192691c8d83121094343e9f88ad2b7cf",
"timestamp": "",
"source": "github",
"line_count": 466,
"max_line_length": 139,
"avg_line_length": 29.141630901287552,
"alnum_prop": 0.5424889543446244,
"repo_name": "PolymerLabs/arcs-live",
"id": "2b53f5a607b43709c1a768a6521121aab2abdff3",
"size": "13891",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "devtools/src/arcs-recipe-editor.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "42"
},
{
"name": "C++",
"bytes": "2523"
},
{
"name": "CSS",
"bytes": "91310"
},
{
"name": "CoffeeScript",
"bytes": "3272"
},
{
"name": "HTML",
"bytes": "1280188"
},
{
"name": "JavaScript",
"bytes": "6704824"
},
{
"name": "Kotlin",
"bytes": "55841"
},
{
"name": "Makefile",
"bytes": "89"
},
{
"name": "PHP",
"bytes": "3338"
},
{
"name": "Shell",
"bytes": "2391"
},
{
"name": "Starlark",
"bytes": "7650"
},
{
"name": "TypeScript",
"bytes": "178144"
}
],
"symlink_target": ""
}
|
<?php defined('BASEPATH') OR exit('No direct script access allowed');
// General Email Language
$lang['email_greeting'] = 'Terve %s,';
$lang['email_signature'] = 'Kiitos,';
/* End of file email_lang.php */
/* Location: ./system/pyrocms/language/finnish/email_lang.php */
|
{
"content_hash": "1b04472445969779e07656bf60959535",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 69,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.684981684981685,
"repo_name": "wret36/marinersTraining",
"id": "39688cdd279959d24e19e2bdad4f99edfeba1999",
"size": "273",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "system/pyrocms/language/finnish/email_lang.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "442648"
},
{
"name": "PHP",
"bytes": "4078339"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mycotaxon 13(1): 18 (1981)
#### Original name
Ulocladium chlamydosporum Mouch., 1971
### Remarks
null
|
{
"content_hash": "b165e1c06d177ef8bf627eced877ecda",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 14.615384615384615,
"alnum_prop": 0.7157894736842105,
"repo_name": "mdoering/backbone",
"id": "775fd2e6ae45a7782239cda2ba9926b2b25cac32",
"size": "254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Pleosporaceae/Alternaria/Alternaria mouchaccae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
package com.googlecode.qualitas.internal.installation.instrumentation;
import java.lang.annotation.Annotation;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import com.googlecode.qualitas.engines.api.core.Bundle;
import com.googlecode.qualitas.engines.api.instrumentation.Instrumentor;
import com.googlecode.qualitas.internal.installation.core.AbstractProcessor;
import com.googlecode.qualitas.internal.installation.core.QualitasHeadersNames;
/**
* The Class BaseInstrumentorProcessor.
*/
public class BaseInstrumentorProcessor extends AbstractProcessor {
/*
* (non-Javadoc)
*
* @see org.apache.camel.Processor#process(org.apache.camel.Exchange)
*/
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
@SuppressWarnings("unchecked")
Class<Annotation> annotationType = (Class<Annotation>) in
.getHeader(QualitasHeadersNames.QUALITAS_INSTRUMENTATION_PHASE);
Bundle bundle = exchange.getIn().getBody(Bundle.class);
Instrumentor instrumentor = findQualitasComponent(Instrumentor.class,
bundle.getProcessType(), annotationType);
instrumentor.instrument(bundle);
Message out = exchange.getOut();
out.setBody(bundle);
}
}
|
{
"content_hash": "44b180366abcebc48a3e86c7dfcd6850",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 80,
"avg_line_length": 33.36585365853659,
"alnum_prop": 0.7112573099415205,
"repo_name": "lukaszbudnik/qualitas",
"id": "796ab9534c24133889fd987897d3a9d08a22a802",
"size": "1368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "qualitas-internal-installation-camel/src/main/java/com/googlecode/qualitas/internal/installation/instrumentation/BaseInstrumentorProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2798"
},
{
"name": "Java",
"bytes": "244055"
},
{
"name": "JavaScript",
"bytes": "7927"
},
{
"name": "Shell",
"bytes": "3235"
},
{
"name": "XSLT",
"bytes": "17067"
}
],
"symlink_target": ""
}
|
plato -r -d Reports -t "Cache Clear" ../../App/JavaScript/Src/ & START %~dps0\Reports\index.html
|
{
"content_hash": "49c6c23ecb15cf84552b0932648c1582",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 96,
"avg_line_length": 96,
"alnum_prop": 0.6875,
"repo_name": "splintercode/selector-reporter",
"id": "3bfdaa917b830495d4df9b1138351fff26f9375c",
"size": "96",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Specs/SpecRunners/plato-reporter.bat",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "55635"
},
{
"name": "JavaScript",
"bytes": "89570"
},
{
"name": "Shell",
"bytes": "96"
}
],
"symlink_target": ""
}
|
var Program = require('commander');
var FetchCli = require('./cli/fetch');
var pkg = require('./package.json');
Program
.version(pkg.version)
.option('-n, --number [number of events]', 'number of events to show [250]', 250)
.option('-d, --date <date>', 'date for query [today]', 'today')
.option('-c, --calendar [cal_id]', 'use calendar as a source, if not specified the primary calendar will be used')
.option('-m, --mail', 'use mail as source')
.option('-s, --slack', 'use slack as source')
.option('-l, --logbot', 'use logbot as source')
.option('-j, --jira', 'use jira as source')
.option('-z, --zebra', 'use zebra as source')
.option('-g, --git [path]', 'use git as a source')
.option('-G, --github', 'use github as a source')
.option('-L, --gitlab', 'use gitlab as a source')
.option('-p, --pie', 'print pie chart instead of text')
.option('-H, --hours', 'prefer output as number of hours instead of time ranges [false]', false)
.option('-v, --verbose', 'more verbose output [false]', false)
.option('-C, --config <path>', 'path to config file (defaults to ~/.cabdriver/cabdriver.yml)', false)
.option('-T, --test', 'for internal use only [false]', false)
.parse(process.argv);
var fetch = new FetchCli(Program.opts());
fetch.run();
|
{
"content_hash": "6c31fa5aeece8d955e71238450b631fa",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 118,
"avg_line_length": 48.666666666666664,
"alnum_prop": 0.6149162861491628,
"repo_name": "metaodi/cabdriver",
"id": "aade76f20611ead5373195aaab5498c699820b06",
"size": "1335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cabdriver-fetch.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "168729"
},
{
"name": "Procfile",
"bytes": "17"
}
],
"symlink_target": ""
}
|
LHModelDescription
=============

# Version 1.0:
override BaseModel's description to make NSLog more helpful
通过覆写BaseModel的description方法,为所有继承BaseModel的类实现了NSLog打印对象内的变量
More infomation in [My Blog(我的博客)](http://idatadev.com/2015/05/04/tong-guo-descriptionshi-xian-nslogda-yin-dui-xiang-nei-de-bian-liang/)
# License
LHModelDescription is available under the MIT license. See the LICENSE file for more info.
|
{
"content_hash": "22143b7af35f3ad86d550c5c3eda8f2a",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 136,
"avg_line_length": 30.6875,
"alnum_prop": 0.780040733197556,
"repo_name": "leostc/LHModelDescription",
"id": "9d69b8ab27e35b58b405e6f842f733a20c75e99c",
"size": "551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "9410"
}
],
"symlink_target": ""
}
|
WoUSO is an evaluation platform that uses gamification to keep it's users engaged. It can be personalized with specific content and custom game modes.
This new WoUSO is an upgrade on the existing python [wouso](https://github.com/rosedu/wouso).
## What it brings new to the table ?
* modular design, which ensures easy extensibility
* user interactivity, with live notifications
* mobile friendly interface
* integration with social networks
* i18n support
* API
## Setup
* Install **node** and **mongod**.
* Install requirements
```
npm install
```
* Configure settings under **config.json** file.
* Link preffered modules
```
npm link modules/qotd
```
* Start mongod databse
* Run **app.js** file
```
npm start
```
## License
This platform is licensed under the MIT license.
|
{
"content_hash": "ad64d07dc79fa13ce66e8ac1d205146d",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 150,
"avg_line_length": 24.4375,
"alnum_prop": 0.7416879795396419,
"repo_name": "mariuscoto/wouso-new",
"id": "68a2414952da3b710188402931bb6e07582c21fe",
"size": "800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6060"
},
{
"name": "HTML",
"bytes": "7969"
},
{
"name": "JavaScript",
"bytes": "2475078"
}
],
"symlink_target": ""
}
|
/*
* Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the StorageAccountCheckNameAvailabilityParameters class.
* @constructor
* @member {string} name
*
* @member {string} [type] Default value: 'Microsoft.Storage/storageAccounts' .
*
*/
class StorageAccountCheckNameAvailabilityParameters {
constructor() {
}
/**
* Defines the metadata of StorageAccountCheckNameAvailabilityParameters
*
* @returns {object} metadata of StorageAccountCheckNameAvailabilityParameters
*
*/
mapper() {
return {
required: false,
serializedName: 'StorageAccountCheckNameAvailabilityParameters',
type: {
name: 'Composite',
className: 'StorageAccountCheckNameAvailabilityParameters',
modelProperties: {
name: {
required: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
serializedName: 'type',
defaultValue: 'Microsoft.Storage/storageAccounts',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = StorageAccountCheckNameAvailabilityParameters;
|
{
"content_hash": "939a5c6a8f2965f84133ebabacf31c4c",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 89,
"avg_line_length": 24.54385964912281,
"alnum_prop": 0.6125804145818442,
"repo_name": "dsgouda/autorest",
"id": "c08dd6c67b162cfa1a460d057f414308d61e0a01",
"size": "1399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Samples/2a-validation/NodeJS/models/storageAccountCheckNameAvailabilityParameters.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "36"
},
{
"name": "C#",
"bytes": "15113885"
},
{
"name": "CSS",
"bytes": "110"
},
{
"name": "CoffeeScript",
"bytes": "63791"
},
{
"name": "Go",
"bytes": "149918"
},
{
"name": "HTML",
"bytes": "274"
},
{
"name": "Java",
"bytes": "7894733"
},
{
"name": "JavaScript",
"bytes": "6967281"
},
{
"name": "PowerShell",
"bytes": "41183"
},
{
"name": "Python",
"bytes": "2081886"
},
{
"name": "Ruby",
"bytes": "182108"
},
{
"name": "Shell",
"bytes": "196"
},
{
"name": "TypeScript",
"bytes": "460658"
}
],
"symlink_target": ""
}
|
const http = require('http')
const path = require('path')
const port = process.env.PORT || 8080
const restify = require('restify');
const transform = (request, response, next) => {
var s = request.params.s;
// Step 1: Measure existing complexity.
// For a first pass, let's just use string length.
const initialComplexity = s.length;
// Step 2: Do stuff.
// Some ideas:
// 1. Use a thesaurus
// 2. Translate to and back from another language
// 3. Map of common words and phrases to more complex phrases.
// 4. negated opposite (eg change "has" to "doesn't not have")
// For a first pass, let's map using maps/phrases.json
const phraseMap = require('./maps/phrases.json');
for (var phrase in phraseMap) {
s = s.replace(phrase, phraseMap[phrase]);
}
// Step 3: Ensure complexity has been increased and return value.
const finalComplexity = s.length;
response.send((initialComplexity < finalComplexity) ? s : request.params.s);
next()
}
const server = restify.createServer();
server.get('/transform/:s', transform);
// serve compiled js/css/etc
server.get(/\/js\/.*/, restify.serveStatic({
directory: path.resolve(__dirname, '../app-compiled')
}));
// root static files
server.get(/\//, restify.serveStatic({
directory: path.resolve(__dirname, '../static'),
default: 'index.html'
}));
server.listen(port, (err) => {
if (err) {
return console.log(`Unable to start server on port ${port}`, err)
}
console.log(`server is listening on ${port}`)
})
|
{
"content_hash": "444d75965b897834dda1d4b19f6ad371",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 78,
"avg_line_length": 29.54901960784314,
"alnum_prop": 0.6721964167219642,
"repo_name": "zbirkenbuel/complexifier",
"id": "ee61c14be6f947e63d1a005c2b5c3b6c449237fb",
"size": "1507",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "492"
},
{
"name": "JavaScript",
"bytes": "1736"
}
],
"symlink_target": ""
}
|
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
/*
* 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.
*/
/**
*
* @author root
*/
public class Create_a_New_Account_Page extends javax.swing.JFrame {
String url="jdbc:mysql://localhost:3306/"; //sizde 3306 olabilir
String veritabaniadi="passbox_db"; // ulaşmak istediğiniz veri tabanı ismi
String surucu="com.mysql.jdbc.Driver";
String kullaniciAdi="root"; // workbench deki kullanıcı adınız ne ise o "root" olabilir
String kullaniciParolası=""; //workbench deki şifreniz ne ise o
java.sql.Connection baglanti=null;
java.sql.Statement komut=null;
ResultSet gelenveri=null;
PreparedStatement pst=null;
/**
* Creates new form Create_a_New_Account_Page
*/
public Create_a_New_Account_Page() {
initComponents();
setIcon();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
try {
Class.forName(surucu);
//baglantı veri tabanı seçimi kullanıcı adı ve parola ile sağlanı
baglanti= DriverManager.getConnection(url+veritabaniadi, kullaniciAdi,kullaniciParolası);
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("HATA 1: Surucu ve Baglantı Hatsı !"+ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPasswordField2 = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
password_txt = new javax.swing.JPasswordField();
username_txt = new javax.swing.JTextField();
email_address_txt = new javax.swing.JTextField();
mobile_number_txt = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jCheckBox1 = new javax.swing.JCheckBox();
jLabel6 = new javax.swing.JLabel();
jCheckBox2 = new javax.swing.JCheckBox();
jButton_Create_a_New_Account_Page_TurnBack_Button = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
fullname_txt = new javax.swing.JTextField();
jPasswordField2.setText("jPasswordField2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("PassBox | Create a New Account");
setResizable(false);
jLabel1.setText("Username : ");
jLabel2.setText("Password : ");
jLabel3.setText("E-Mail Address :");
jLabel4.setText("Mobile Number :");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ico/register_ico.png"))); // NOI18N
jButton1.setText("Register");
jButton1.setEnabled(false);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jButton2.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jButton2.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jButton2.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jButton2.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jButton2.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jButton2.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/logo/PassBox.png"))); // NOI18N
jLabel5.setText("Confidentiality Agreement : ");
jCheckBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBox1ItemStateChanged(evt);
}
});
jLabel6.setText("Contract : ");
jCheckBox2.setEnabled(false);
jCheckBox2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBox2ItemStateChanged(evt);
}
});
jButton_Create_a_New_Account_Page_TurnBack_Button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ico/turnback_ico.png"))); // NOI18N
jButton_Create_a_New_Account_Page_TurnBack_Button.setText("Turn Back");
jButton_Create_a_New_Account_Page_TurnBack_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_Create_a_New_Account_Page_TurnBack_ButtonActionPerformed(evt);
}
});
jLabel7.setText("Full Name : ");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(email_address_txt, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(password_txt, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(username_txt, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(mobile_number_txt)
.addComponent(fullname_txt)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(jCheckBox1)
.addGap(24, 24, 24)
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(jCheckBox2)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton_Create_a_New_Account_Page_TurnBack_Button, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(fullname_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(username_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(password_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(email_address_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(mobile_number_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jCheckBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Create_a_New_Account_Page_TurnBack_Button))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_Create_a_New_Account_Page_TurnBack_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Create_a_New_Account_Page_TurnBack_ButtonActionPerformed
// TODO add your handling code here:
this.setVisible(false);
Login_Page frame = new Login_Page();
frame.setVisible(true);
}//GEN-LAST:event_jButton_Create_a_New_Account_Page_TurnBack_ButtonActionPerformed
private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBox1ItemStateChanged
// TODO add your handling code here:
int secili=evt.getStateChange();
int secili_degil = evt.getStateChange();
if(secili == ItemEvent.SELECTED)
jCheckBox2.setEnabled(true);
else
jCheckBox2.setEnabled(false);
}//GEN-LAST:event_jCheckBox1ItemStateChanged
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String sorgu = "INSERT INTO `passbox_db`.`users_tb`(`fullname`,`username`,`password`,`email_address`,`mobile_number`)VALUES(?,?,?,?,?);";
try {
pst=baglanti.prepareStatement(sorgu);
pst.setString(1, fullname_txt.getText());
pst.setString(2, username_txt.getText());
pst.setString(3, password_txt.getText());
pst.setString(4, email_address_txt.getText());
pst.setString(5, mobile_number_txt.getText());
int x= pst.executeUpdate();
if(x==1)
JOptionPane.showMessageDialog(null,"Başarılı Kayıt");
else
JOptionPane.showMessageDialog(null,"Başarısız Kayıt");
} catch (SQLException ex) {
JOptionPane.showConfirmDialog(null, "Sorgu da hata var !"+ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jCheckBox2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBox2ItemStateChanged
int secili=evt.getStateChange();
int secili_degil = evt.getStateChange();
if(secili == ItemEvent.SELECTED)
jButton1.setEnabled(true);
else
jButton1.setEnabled(false);
}//GEN-LAST:event_jCheckBox2ItemStateChanged
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Create_a_New_Account_Page.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Create_a_New_Account_Page.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Create_a_New_Account_Page.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Create_a_New_Account_Page.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Create_a_New_Account_Page().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField email_address_txt;
private javax.swing.JTextField fullname_txt;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton_Create_a_New_Account_Page_TurnBack_Button;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPasswordField jPasswordField2;
private javax.swing.JTextField mobile_number_txt;
private javax.swing.JPasswordField password_txt;
private javax.swing.JTextField username_txt;
// End of variables declaration//GEN-END:variables
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("passbox_ico.png")));
}
}
|
{
"content_hash": "244c5fb46d992c67a07c6acd751561bf",
"timestamp": "",
"source": "github",
"line_count": 325,
"max_line_length": 197,
"avg_line_length": 53.81230769230769,
"alnum_prop": 0.6620733032191664,
"repo_name": "ismailtasdelen/PassBox",
"id": "2a45216d35c533d1694dfaab544b0279e2c9f450",
"size": "17517",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Create_a_New_Account_Page.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "188023"
}
],
"symlink_target": ""
}
|
/*
* Connection.cpp
*
* Created on: Jun 5, 2017
* Author: kurt
*/
#include "Connection.h"
#include <stdexcept>
#include <cassert>
#include <string>
#include <iomanip>
#include <cstring>
#include <algorithm>
#include <locale>
#include <regex>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
namespace kcmsg {
Connection::Connection(sa_family_t fam, int t, int p, int maxthreads, std::string loginstance)
{
// assert a supported protocol
assert( ( fam == AF_INET ) || ( fam == AF_INET6 ) );
assert( ( t == SOCK_STREAM ) || ( t == SOCK_DGRAM ) || ( t == SOCK_SEQPACKET ) || ( t == SOCK_RAW ) );
assert( ( p == IPPROTO_TCP ) || ( p == IPPROTO_UDP ) || ( p == IPPROTO_SCTP ) );
// initialize member variables
// setting all bytes in 'conn' member to 0 makes the default for a
// connect() or a bind() to be to default addresses
// Host IP Service
// ==========================
// IP version 4 | INADDR_ANY | 0 |
// IP version 6 | in6addr_any | 0 |
// (i.e. the kernel will choose IP address and port number)
conn = {0};
listen_max = maxthreads;
// logger_ = log4cplus::Logger::getInstance( LOG4CPLUS_TEXT(loginstance) );
//set connection definition
family = fam;
protocol_type = t;
protocol = p;
//handle rest of initialization as a switch to support future protocols
switch ( fam )
{
case AF_INET :
conn.addr.length = 16;
break;
case AF_INET6 :
conn.addr.length = 28;
break;
default:
conn.addr.length = sizeof(uint8_t) + MAXADDRLEN;
}
// create the socket
conn.fd = socket(family, protocol_type, protocol);
}
Connection::~Connection() {
// TODO Auto-generated destructor stub
}
int Connection::resolveHost(std::string host, std::string service)
{
int res;
addrinfo hints, *result;
hints = {0};
// return hostname in cannonical form and only addresses meeting "hints"
hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
hints.ai_family = family;
hints.ai_socktype = protocol_type;
hints.ai_protocol = protocol;
if( (res = getaddrinfo(host.c_str(), service.c_str(), &hints, &result) ) != 0)
{
throw std::ios_base::failure("Unable to resolve host/service address");
return(res);
}
switch (family)
{
case AF_INET :
conn.addr.length = sizeof(sockaddr_in);
std::memcpy( conn.addr.addr, result->ai_addr, sizeof(sockaddr_in) );
break;
case AF_INET6 :
conn.addr.length = sizeof(sockaddr_in6);
std::memcpy( conn.addr.addr, result->ai_addr, sizeof(sockaddr_in6) );
break;
default:
// LOG4CPLUS_ERROR( logger_, LOG4CPLUS_TEXT( "Connection class instantiated with unsupported protocol family: \"" )
// << family << "\"" );
// throw std::invalid_argument("Unsupported protocol family");
break;
}
// LOG4CPLUS_DEBUG( logger_, LOG4CPLUS_TEXT( "Resolved host: \"" ) << LOG4CPLUS_TEXT( host) << "\" and service: \""
// << LOG4CPLUS_TEXT( service) << "\" to " << formatAddress() );
freeaddrinfo(result);
return (res);
}
int Connection::resolveHost(std::wstring host, std::wstring service)
{
/*
int res;
addrinfo hints, *result;
hints = {0};
// return hostname in cannonical form and only addresses meeting "hints"
hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
hints.ai_family = family;
hints.ai_socktype = protocol_type;
hints.ai_protocol = protocol;
*/
// convert to punycode
/*
if( (res = getaddrinfo(host.c_str(), service.c_str(), &hints, &result) ) != 0)
throw("Unable to resolve host/service address");
switch (family)
{
case AF_INET :
conn.addr.length = sizeof(sockaddr_in);
std::memcpy( conn.addr.addr, result->ai_addr, sizeof(sockaddr_in) );
break;
case AF_INET6 :
conn.addr.length = sizeof(sockaddr_in6);
std::memcpy( conn.addr.addr, result->ai_addr, sizeof(sockaddr_in6) );
break;
default:
throw("Unsupported protocol family");
break;
}
freeaddrinfo(result);
*/
return 0;
}
void Connection::setAddress(std::string a)
{
/*
hostent h;
std::regex re4("\d+\.\d+\.\d+\.\d+");
std::string addr6Cast = "(?: \\
(?: (?:[0-9a-f]{1,4}:){6} \\
| :: (?:[0-9a-f]{1,4}:){5} \\
| (?: [0-9a-f]{1,4})? :: (?:[0-9a-f]{1,4}:){4} \\
| (?: (?:[0-9a-f]{1,4}:){0,1} [0-9a-f]{1,4})? :: (?:[0-9a-f]{1,4}:){3} \\
| (?: (?:[0-9a-f]{1,4}:){0,2} [0-9a-f]{1,4})? :: (?:[0-9a-f]{1,4}:){2} \\
| (?: (?:[0-9a-f]{1,4}:){0,3} [0-9a-f]{1,4})? :: (?:[0-9a-f]{1,4}:) \\
| (?: (?:[0-9a-f]{1,4}:){0,4} [0-9a-f]{1,4})? :: \\
) \\
(?: [0-9a-f]{1,4} : [0-9a-f]{1,4} \\
| (?: (?: 25[0-5] | 2[0-4][0-9] | [01]?[0-9]?[0-9])\\.){3} \\
(?: (?: 25[0-5] | 2[0-4][0-9] | [01]?[0-9]?[0-9])) \\
) \\
| (?: (?:[0-9a-f]{1,4}:){0,5} [0-9a-f]{1,4})? :: [0-9a-f]{1,4} \\
| (?: (?:[0-9a-f]{1,4}:){0,6} [0-9a-f]{1,4})? :: \\
)";
std::remove_if(addr6Cast.begin(), addr6Cast.end(), ::isspace), addr6Cast.end();
std::regex re6(addr6Cast.c_str());
//force hex address string to be lower case
std::locale loc;
for (std::string::size_type i=0; i<a.length(); ++i)
std::tolower(a[i],loc);
//test if the string is a number address
//i.e. not requiring a hostname translation
if ( family == AF_INET ) //IPv4
{
if (!std::regex_match( a, re4 ) )
throw("Invalid IPv4 Address");
}
*/
}
void Connection::setAddress(uint32_t a)
{
}
void Connection::setService(std::string p)
{
}
void Connection::setService(uint16_t p)
{
}
void Connection::setListenerQueueSize(uint32_t s)
{
listen_max = s;
}
bool Connection::isValidateAddress(std::string a)
{
return ( true );
}
bool Connection::isValidatePort(std::string p)
{
return ( true );
}
bool Connection::isValidatePort(int p)
{
return ( true );
}
int Connection::getDescriptor(void)
{
return this->conn.fd;
}
bool Connection::Accept(void)
{
connection_storage cliaddr = {0};
switch ( family )
{
case AF_INET :
cliaddr.addr.length = 16;
break;
case AF_INET6 :
cliaddr.addr.length = 28;
break;
default:
cliaddr.addr.length = sizeof(uint8_t) + MAXADDRLEN;
}
// LOG4CPLUS_DEBUG( logger_, LOG4CPLUS_TEXT( "accepting client ... ") );
if ( ( cliaddr.fd = accept( conn.fd, ( sockaddr * ) &cliaddr.addr.addr, (unsigned int *) &cliaddr.addr.length ) ) < 0 )
{
return (errno);
}
// LOG4CPLUS_DEBUG( logger_, LOG4CPLUS_TEXT( "Client accepted on the descriptor (" ) << std::to_string( cliaddr.fd ) << ").");
return (true);
}
void Connection::Bind(void)
{
// int err;
if ( ( bind(conn.fd, (const struct sockaddr *) &conn.addr.addr, (socklen_t) conn.addr.length) ) < 0 )
// {
// err = errno;
// LOG4CPLUS_ERROR( logger_, LOG4CPLUS_TEXT( "Connection bind failure. ") << LOG4CPLUS_TEXT( formatErrno( err ) ) );
throw std::ios_base::failure( "Unable to Bind()" );
// }
// else
// {
// LOG4CPLUS_DEBUG( logger_, LOG4CPLUS_TEXT( "Bound socket (") << LOG4CPLUS_TEXT( std::to_string( conn.fd ) )
// << LOG4CPLUS_TEXT( ") to " ) << LOG4CPLUS_TEXT( formatAddress() ) );
// }
}
void Connection::Close(int sockfd)
{
close(sockfd);
}
void Connection::Connect(void)
{
// int err;
if ( ( conn.fd = connect(conn.fd, (const struct sockaddr *) &conn.addr.addr, (socklen_t) conn.addr.length) ) < 0 )
// {
// err = errno;
// LOG4CPLUS_ERROR( logger_, LOG4CPLUS_TEXT( "Connection connect failure. ") << LOG4CPLUS_TEXT( formatErrno( err ) ) );
throw std::ios_base::failure( "Unable to Connect()" );
// }
// else
// {
// LOG4CPLUS_DEBUG( logger_, LOG4CPLUS_TEXT( "Connected socket (") << LOG4CPLUS_TEXT( std::to_string( conn.fd ) )
// << LOG4CPLUS_TEXT( ") to " ) << LOG4CPLUS_TEXT( formatAddress() ) );
// }
}
void Connection::Listen(void)
{
// int err;
if ( ( listen(conn.fd, listen_max) < 0 ) )
// {
// err = errno;
// LOG4CPLUS_ERROR( logger_, LOG4CPLUS_TEXT( "Connection listen failure. ") << LOG4CPLUS_TEXT( formatErrno( err ) ) );
throw std::ios_base::failure( "Unable to Listen()" );
// }
// else
// {
// LOG4CPLUS_DEBUG( logger_, LOG4CPLUS_TEXT( "Listening on socket descriptor(") << LOG4CPLUS_TEXT( std::to_string( conn.fd ) )
// << LOG4CPLUS_TEXT( ") at address " ) << LOG4CPLUS_TEXT( formatAddress() ) );
// }
}
void Connection::Shutdown(int sockfd, int howto)
{
shutdown(sockfd, howto);
}
size_t Connection::Readn(char *msg, size_t nbytes)
{
size_t nleft;
ssize_t nread;
char *ptr;
ptr = msg;
nleft = nbytes;
while( nleft > 0 )
{
if( ( nread = read( conn.fd, ptr, nleft ) ) < 0 )
{
if( errno == EINTR )
{
nread = 0;
} else
{
return (-1);
}
} else if( nread == 0 )
{
break;
}
nleft -= nread;
ptr += nread;
}
return ( nbytes - nleft );
}
size_t Connection::ReadMessage(kcmsg::Message *msg, size_t nbytes)
{
// nbytes is the size of the buffer needed to read the message
// msgsize is the actual size of the message which is not known
// until we read its length
size_t nleft, msgsize;
ssize_t nread;
char *ptr;
ptr = (char *) msg;
nleft = nbytes; // Max size of buffer (msg)
msgsize = 0; // We do not know actual message size yet...
while( nleft > 0 )
{
if( ( nread = read( conn.fd, ptr, nleft ) ) < 0 )
{
if( errno == EINTR )
{
nread = 0;
} else
{
return (-1);
}
} else if( nread == 0 )
{
break;
}
nleft -= nread;
ptr += nread;
// set the actual length of the message
// if we do not know it yet and have read in enough bytes to obtain it
if ( ( msgsize == 0) && ( ( nbytes - nleft ) >= (sizeof(kcmsg::MessageHeader) + 2) ) )
{
msg->readMessageLength();
msg->getMessageLength();
nleft -= ( nbytes - msgsize );
}
}
return ( nleft );
}
size_t Connection::Writen(char *msg, size_t nbytes)
{
size_t nleft;
ssize_t nwritten;
const char *ptr;
ptr = msg;
nleft = nbytes;
while( nleft > 0 )
{
if( ( nwritten = write( conn.fd, ptr, nleft ) ) <= 0 )
{
if( nwritten < 0 && errno == EINTR )
{
nwritten = 0;
} else
{
return (-1);
}
}
nleft -= nwritten;
ptr += nwritten;
}
return ( nbytes );
}
size_t Connection::WriteMessage(kcmsg::Message *msg)
{
size_t nleft, retval;
ssize_t nwritten;
const char *ptr;
ptr = (const char *) msg;
nleft = retval = msg->getMessageLength();
while( nleft > 0 )
{
if( ( nwritten = write( conn.fd, ptr, nleft ) ) <= 0 )
{
if( nwritten < 0 && errno == EINTR )
{
nwritten = 0;
} else
{
return (-1);
}
}
nleft -= nwritten;
ptr += nwritten;
}
return ( retval );
}
/* private methods */
std::string Connection::formatAddress(void)
{
/*
*
*/
std::string ret;
uint p = 0; // holder for the port number in host order
switch ( family )
{
case AF_INET :
sockaddr_in *addr;
char host_addr[INET_ADDRSTRLEN];
ret = "AF_INET: HOST(";
addr = (sockaddr_in *) &conn.addr.addr;
ret += inet_ntop(AF_INET, &(addr->sin_addr), host_addr, INET_ADDRSTRLEN);
ret += ") PORT(";
p = ntohs(addr->sin_port);
ret += std::to_string( p );
ret += ")";
break;
case AF_INET6 :
sockaddr_in6 *addr6;
char host6_addr[INET6_ADDRSTRLEN];
ret = "AF_INET6: HOST(";
addr6 = (sockaddr_in6 *) &conn.addr.addr;
ret += inet_ntop(AF_INET6, &(addr6->sin6_addr), host6_addr, INET6_ADDRSTRLEN);
ret += ") PORT(";
p = ntohs(addr6->sin6_port);
ret += std::to_string( p );
ret += ")";
break;
default :
ret = "Unsupported protocol family";
break;
}
return (ret);
}
std::string Connection::formatErrno(int err)
{
std::string ret = "ERRNO: (";
ret += std::to_string(err);
ret += ") \"";
switch (err)
{
case EPERM :
ret += "EPERM - Operation not permitted\"";
break;
case ENOENT :
ret += "ENOENT - No such file or directory\"";
break;
case ESRCH :
ret += "ESRCH - No such process\"";
break;
case EINTR :
ret += "EINTR - Interrupted system call\"";
break;
case EIO :
ret += "EIO - I/O error\"";
break;
case ENXIO :
ret += "ENXIO - No such device or address\"";
break;
case E2BIG :
ret += "E2BIG - Argument list too long\"";
break;
case ENOEXEC :
ret += "ENOEXEC - Exec format error\"";
break;
case EBADF :
ret += "EBADF - Bad file number\"";
break;
case ECHILD :
ret += "ECHILD - No child processes\"";
break;
case EAGAIN :
ret += "EAGAIN - Try again\"";
break;
case ENOMEM :
ret += "ENOMEM - Out of memory\"";
break;
case EACCES :
ret += "EACCES - Permission denied\"";
break;
case EFAULT :
ret += "EFAULT - Bad address\"";
break;
case ENOTBLK :
ret += "ENOTBLK - Block device required\"";
break;
case EBUSY :
ret += "EBUSY - Device or resource busy\"";
break;
case EEXIST :
ret += "EEXIST - File exists\"";
break;
case EXDEV :
ret += "EXDEV - Cross-device link\"";
break;
case ENODEV :
ret += "ENODEV - No such device\"";
break;
case ENOTDIR :
ret += "ENOTDIR - Not a directory\"";
break;
case EISDIR :
ret += "EISDIR - Is a directory\"";
break;
case EINVAL :
ret += "EINVAL - Invalid argument\"";
break;
case ENFILE :
ret += "ENFILE - File table overflow\"";
break;
case EMFILE :
ret += "EMFILE - Too many open files\"";
break;
case ENOTTY :
ret += "ENOTTY - Not a typewriter\"";
break;
case ETXTBSY :
ret += "ETXTBSY - Text file busy\"";
break;
case EFBIG :
ret += "EFBIG - File too large\"";
break;
case ENOSPC :
ret += "ENOSPC - No space left on device\"";
break;
case ESPIPE :
ret += "ESPIPE - Illegal seek\"";
break;
case EROFS :
ret += "EROFS - Read-only file system\"";
break;
case EMLINK :
ret += "EMLINK - Too many links\"";
break;
case EPIPE :
ret += "EPIPE - Broken pipe\"";
break;
case EDEADLK :
ret += "EDEADLK - Resource deadlock would occur\"";
break;
case ENAMETOOLONG :
ret += "ENAMETOOLONG - File name too long\"";
break;
case ENOLCK :
ret += "ENOLCK - No record locks available\"";
break;
case ENOSYS :
ret += "ENOSYS - Invalid system call number\"";
break;
case ENOTEMPTY :
ret += "ENOTEMPTY - Directory not empty\"";
break;
case ELOOP :
ret += "ELOOP - Too many symbolic links encountered\"";
break;
case ENOMSG :
ret += "ENOMSG - No message of desired type\"";
break;
case EIDRM :
ret += "EIDRM - Identifier removed\"";
break;
case ENOSTR :
ret += "ENOSTR - Device not a stream\"";
break;
case ENODATA :
ret += "ENODATA - No data available\"";
break;
case ETIME :
ret += "ETIME - Timer expired\"";
break;
case ENOSR :
ret += "ENOSR - Out of streams resources\"";
break;
case EREMOTE :
ret += "EREMOTE - Object is remote\"";
break;
case ENOLINK :
ret += "ENOLINK - Link has been severed\"";
break;
case EPROTO :
ret += "EPROTO - Protocol error\"";
break;
case EMULTIHOP :
ret += "EMULTIHOP - Multihop attempted\"";
break;
case EBADMSG :
ret += "EBADMSG - Not a data message\"";
break;
case EOVERFLOW :
ret += "EOVERFLOW - Value too large for defined data type\"";
break;
case EUSERS :
ret += "EUSERS - Too many users\"";
break;
case ENOTSOCK :
ret += "ENOTSOCK - Socket operation on non-socket\"";
break;
case EDESTADDRREQ :
ret += "EDESTADDRREQ - Destination address required\"";
break;
case EMSGSIZE :
ret += "EMSGSIZE - Message too long\"";
break;
case EPROTOTYPE :
ret += "EPROTOTYPE - Protocol wrong type for socket\"";
break;
case ENOPROTOOPT :
ret += "ENOPROTOOPT - Protocol not available\"";
break;
case EPROTONOSUPPORT :
ret += "EPROTONOSUPPORT - Protocol not supported\"";
break;
case ESOCKTNOSUPPORT :
ret += "ESOCKTNOSUPPORT - Socket type not supported\"";
break;
case EOPNOTSUPP :
ret += "EOPNOTSUPP - Operation not supported on transport endpoint\"";
break;
case EPFNOSUPPORT :
ret += "EPFNOSUPPORT - Protocol family not supported\"";
break;
case EAFNOSUPPORT :
ret += "EAFNOSUPPORT - Address family not supported by protocol\"";
break;
case EADDRINUSE :
ret += "EADDRINUSE - Address already in use\"";
break;
case EADDRNOTAVAIL :
ret += "EADDRNOTAVAIL - Cannot assign requested address\"";
break;
case ENETDOWN :
ret += "ENETDOWN - Network is down\"";
break;
case ENETUNREACH :
ret += "ENETUNREACH - Network is unreachable\"";
break;
case ENETRESET :
ret += "ENETRESET - Network dropped connection because of reset\"";
break;
case ECONNABORTED :
ret += "ECONNABORTED - Software caused connection abort\"";
break;
case ECONNRESET :
ret += "ECONNRESET - Connection reset by peer\"";
break;
case ENOBUFS :
ret += "ENOBUFS - No buffer space available\"";
break;
case EISCONN :
ret += "EISCONN - Transport endpoint is already connected\"";
break;
case ENOTCONN :
ret += "ENOTCONN - Transport endpoint is not connected\"";
break;
case ESHUTDOWN :
ret += "ESHUTDOWN - Cannot send after transport endpoint shutdown\"";
break;
case ETOOMANYREFS :
ret += "ETOOMANYREFS - Too many references: cannot splice\"";
break;
case ETIMEDOUT :
ret += "ETIMEDOUT - Connection timed out\"";
break;
case ECONNREFUSED :
ret += "ECONNREFUSED - Connection refused\"";
break;
case EHOSTDOWN :
ret += "EHOSTDOWN - Host is down\"";
break;
case EHOSTUNREACH :
ret += "EHOSTUNREACH - No route to host\"";
break;
case EALREADY :
ret += "EALREADY - Operation already in progress\"";
break;
case EINPROGRESS :
ret += "EINPROGRESS - Operation now in progress\"";
break;
case ESTALE :
ret += "ESTALE - Stale file handle\"";
break;
case EDQUOT :
ret += "EDQUOT - Quota exceeded\"";
break;
case ECANCELED :
ret += "ECANCELED - Operation Canceled\"";
break;
case EOWNERDEAD :
ret += "EOWNERDEAD - Owner died\"";
break;
case ENOTRECOVERABLE :
ret += "ENOTRECOVERABLE - State not recoverable\"";
break;
default :
ret += "UNKNOWN - UNKNOWN errno value\"";
break;
}
return (ret);
}
} /* namespace kcmsg */
|
{
"content_hash": "bd51671d42319fd2451032d6e3902941",
"timestamp": "",
"source": "github",
"line_count": 773,
"max_line_length": 127,
"avg_line_length": 23.85640362225097,
"alnum_prop": 0.5845669974513312,
"repo_name": "kchristofferson/kcmsg",
"id": "ce7160a9a80f8d8cc7a3ecf6ef2e396c6a8736a7",
"size": "18441",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Connection.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "287"
},
{
"name": "C++",
"bytes": "78704"
}
],
"symlink_target": ""
}
|
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
|
{
"content_hash": "39cdee64ad0fa9e9dbfb3ce22c9c97d2",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 90,
"avg_line_length": 26.333333333333332,
"alnum_prop": 0.6582278481012658,
"repo_name": "akramhussein/ForwardBackward",
"id": "db5d0c42330acffee1d7f3a6e15eb920d9bf9a4a",
"size": "352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ForwardBackward/ForwardBackward/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "47468"
}
],
"symlink_target": ""
}
|
package azurequeuestorage
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/storage"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
fv1 "github.com/fission/fission/pkg/apis/core/v1"
"github.com/fission/fission/pkg/mqtrigger/messageQueue"
)
const (
DummyRouterURL = "http://localhost"
)
func panicIf(err error) {
if err != nil {
log.Panicf("Error: %v", err)
}
}
type azureQueueServiceMock struct {
mock.Mock
}
func (m *azureQueueServiceMock) GetQueue(name string) AzureQueue {
args := m.Called(name)
return args.Get(0).(AzureQueue)
}
type azureQueueMock struct {
mock.Mock
}
func (m *azureQueueMock) Create(options *storage.QueueServiceOptions) error {
args := m.Called(options)
return args.Error(0)
}
func (m *azureQueueMock) NewMessage(text string) AzureMessage {
args := m.Called(text)
return args.Get(0).(AzureMessage)
}
func (m *azureQueueMock) GetMessages(options *storage.GetMessagesOptions) ([]AzureMessage, error) {
args := m.Called(options)
return args.Get(0).([]AzureMessage), args.Error(1)
}
type azureMessageMock struct {
mock.Mock
}
func (m *azureMessageMock) Bytes() []byte {
args := m.Called()
return args.Get(0).([]byte)
}
func (m *azureMessageMock) Put(options *storage.PutMessageOptions) error {
args := m.Called(options)
return args.Error(0)
}
func (m *azureMessageMock) Delete(options *storage.QueueServiceOptions) error {
args := m.Called(options)
return args.Error(0)
}
type azureHTTPClientMock struct {
mock.Mock
bodyHandler func(res *http.Response)
}
func (m *azureHTTPClientMock) Do(req *http.Request) (*http.Response, error) {
args := m.Called(req)
res := args.Get(0).(*http.Response)
err := args.Error(1)
if res != nil && m.bodyHandler != nil {
m.bodyHandler(res)
}
return res, err
}
func TestNewStorageConnectionMissingAccountName(t *testing.T) {
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, err := config.Build()
panicIf(err)
connection, err := New(logger, messageQueue.Config{
MQType: fv1.MessageQueueTypeASQ,
Url: "",
}, DummyRouterURL)
require.Nil(t, connection)
require.Error(t, err, "Required environment variable 'AZURE_STORAGE_ACCOUNT_NAME' is not set")
}
func TestNewStorageConnectionMissingAccessKey(t *testing.T) {
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, err := config.Build()
panicIf(err)
_ = os.Setenv("AZURE_STORAGE_ACCOUNT_NAME", "accountname")
connection, err := New(logger, messageQueue.Config{
MQType: fv1.MessageQueueTypeASQ,
Url: "",
}, DummyRouterURL)
_ = os.Unsetenv("AZURE_STORAGE_ACCOUNT_NAME")
require.Nil(t, connection)
require.Error(t, err, "Required environment variable 'AZURE_STORAGE_ACCOUNT_KEY' is not set")
}
func TestNewStorageConnection(t *testing.T) {
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, err := config.Build()
panicIf(err)
_ = os.Setenv("AZURE_STORAGE_ACCOUNT_NAME", "accountname")
_ = os.Setenv("AZURE_STORAGE_ACCOUNT_KEY", "bm90IGEga2V5")
connection, err := New(logger, messageQueue.Config{
MQType: "azure-storage-queue",
Url: "",
}, DummyRouterURL)
_ = os.Unsetenv("AZURE_STORAGE_ACCOUNT_NAME")
_ = os.Unsetenv("AZURE_STORAGE_ACCOUNT_KEY")
require.NoError(t, err)
require.IsType(t, &AzureStorageConnection{}, connection)
p := connection.(*AzureStorageConnection)
require.Equal(t, DummyRouterURL, p.routerURL)
require.NotNil(t, p.service)
}
func TestAzureStorageQueueSingleMessage(t *testing.T) {
runAzureStorageQueueTest(t, 1, false)
}
// TODO: Enable after fixing race condition
// func TestAzureStorageQueueMultipleMessages(t *testing.T) {
// runAzureStorageQueueTest(t, 10, false)
// }
func TestAzureStorageQueueSingleOutputMessage(t *testing.T) {
runAzureStorageQueueTest(t, 1, true)
}
// TODO: Enable after fixing race condition
// func TestAzureStorageQueueMultipleOutputMessages(t *testing.T) {
// runAzureStorageQueueTest(t, 10, true)
// }
func TestAzureStorageQueuePoisonMessage(t *testing.T) {
const (
TriggerName = "queuetrigger"
QueueName = "inputqueue"
MessageBody = "input"
FunctionName = "badfunc"
ContentType = "text/plain"
)
// Mock a HTTP client that returns different failures
httpClient := new(azureHTTPClientMock)
httpClient.On(
"Do",
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "", ContentType, FunctionName, MessageBody)),
).Return(
&http.Response{
StatusCode: http.StatusInternalServerError,
Body: ioutil.NopCloser(strings.NewReader("server error")),
},
nil,
).Once()
httpClient.On(
"Do",
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "1", ContentType, FunctionName, MessageBody)),
).Return(
&http.Response{
StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(strings.NewReader("not found")),
},
nil,
).Once()
httpClient.On(
"Do",
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "2", ContentType, FunctionName, MessageBody)),
).Return(
&http.Response{
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader("bad request")),
},
nil,
).Once()
httpClient.On(
"Do",
mock.MatchedBy(httpRequestMatcher(t, QueueName, "", "3", ContentType, FunctionName, MessageBody)),
).Return(
&http.Response{
StatusCode: http.StatusForbidden,
Body: ioutil.NopCloser(strings.NewReader("not authorized")),
},
nil,
).Once()
// Mock a queue message with "input" as the message body
message := new(azureMessageMock)
message.On("Bytes").Return([]byte(MessageBody))
message.On(
"Delete",
mock.MatchedBy(
func(options *storage.QueueServiceOptions) bool {
return options == nil
},
),
).Return(nil)
// Mock a queue that performs a no-op create, returns a "poison" message, and then returns no more messages
queue := new(azureQueueMock)
queue.On(
"Create",
mock.MatchedBy(
func(options *storage.QueueServiceOptions) bool {
return options == nil
},
),
).Return(nil)
queue.On(
"GetMessages",
mock.MatchedBy(
func(options *storage.GetMessagesOptions) bool {
return options.NumOfMessages == AzureMessageFetchCount &&
options.VisibilityTimeout == int(AzureMessageVisibilityTimeout/time.Second)
},
),
).Return([]AzureMessage{message}, nil).Once()
queue.On(
"GetMessages",
mock.MatchedBy(
func(options *storage.GetMessagesOptions) bool {
return options.NumOfMessages == AzureMessageFetchCount &&
options.VisibilityTimeout == int(AzureMessageVisibilityTimeout/time.Second)
},
),
).Return([]AzureMessage{}, nil)
// Mock a poison queue message that performs a no-op Put
poisonMessage := new(azureMessageMock)
poisonMessage.On(
"Put",
mock.MatchedBy(
func(options *storage.PutMessageOptions) bool {
return options == nil
},
),
).Return(nil)
// Mock a poison queue that performs a no-op create and creates a new message
poisonQueue := new(azureQueueMock)
poisonQueue.On(
"Create",
mock.MatchedBy(
func(options *storage.QueueServiceOptions) bool {
return options == nil
},
),
).Return(nil)
poisonQueue.On("NewMessage", MessageBody).Return(poisonMessage).Once()
// Mock the queue service to return the input queue
service := new(azureQueueServiceMock)
service.On("GetQueue", QueueName).Return(queue).Once()
service.On("GetQueue", QueueName+AzurePoisonQueueSuffix).Return(poisonQueue).Once()
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, err := config.Build()
panicIf(err)
// Create the storage connection and subscribe to the trigger
connection := AzureStorageConnection{
logger: logger,
routerURL: DummyRouterURL,
service: service,
httpClient: httpClient,
}
subscription, err := connection.Subscribe(&fv1.MessageQueueTrigger{
ObjectMeta: metav1.ObjectMeta{
Name: TriggerName,
Namespace: metav1.NamespaceDefault,
},
Spec: fv1.MessageQueueTriggerSpec{
FunctionReference: fv1.FunctionReference{
Type: fv1.FunctionReferenceTypeFunctionName,
Name: FunctionName,
},
MessageQueueType: fv1.MessageQueueTypeASQ,
Topic: QueueName,
ContentType: ContentType,
},
})
require.NoError(t, err)
require.NotNil(t, subscription)
panicIf(connection.Unsubscribe(subscription))
mock.AssertExpectationsForObjects(t, httpClient, message, poisonMessage, queue, poisonQueue, service)
}
func httpRequestMatcher(t *testing.T, queue string, responseQueue string, retry string, contentType string, functionName string, body string) func(*http.Request) bool {
expectedURL := fmt.Sprintf("%s/fission-function/%s", DummyRouterURL, functionName)
return func(req *http.Request) bool {
requestBody, err := ioutil.ReadAll(req.Body)
require.NoError(t, err)
req.Body = ioutil.NopCloser(strings.NewReader(string(requestBody)))
return queue == req.Header.Get("X-Fission-MQTrigger-Topic") &&
responseQueue == req.Header.Get("X-Fission-MQTrigger-RespTopic") &&
retry == req.Header.Get("X-Fission-MQTrigger-RetryCount") &&
contentType == req.Header.Get("Content-Type") &&
req.URL.String() == expectedURL &&
string(requestBody) == body
}
}
func runAzureStorageQueueTest(t *testing.T, count int, output bool) {
const (
TriggerName = "queuetrigger"
QueueName = "inputqueue"
OutputQueueName = "outputqueue"
MessageBody = "input"
FunctionName = "testfunc"
FunctionResponse = "output"
ContentType = "text/plain"
)
responseTopic := ""
if output {
responseTopic = OutputQueueName
}
// Mock a HTTP client that returns http.StatusOK with "output" for the body
httpClient := new(azureHTTPClientMock)
httpClient.bodyHandler = func(res *http.Response) {
res.Body = ioutil.NopCloser(strings.NewReader(FunctionResponse))
}
httpClient.On(
"Do",
mock.MatchedBy(httpRequestMatcher(t, QueueName, responseTopic, "", ContentType, FunctionName, MessageBody)),
).Return(&http.Response{StatusCode: http.StatusOK}, nil).Times(count)
// Mock a queue message with "input" as the message body
message := new(azureMessageMock)
message.On("Bytes").Return([]byte(MessageBody)).Times(count)
message.On(
"Delete",
mock.MatchedBy(
func(options *storage.QueueServiceOptions) bool {
return options == nil
},
),
).Return(nil).Times(count)
// Mock a queue that performs a no-op create, returns a message the specified number of times, and then returns no more messages
queue := new(azureQueueMock)
queue.On(
"Create",
mock.MatchedBy(
func(options *storage.QueueServiceOptions) bool {
return options == nil
},
),
).Return(nil)
queue.On(
"GetMessages",
mock.MatchedBy(
func(options *storage.GetMessagesOptions) bool {
return options.NumOfMessages == AzureMessageFetchCount &&
options.VisibilityTimeout == int(AzureMessageVisibilityTimeout/time.Second)
},
),
).Return([]AzureMessage{message}, nil).Times(count)
queue.On(
"GetMessages",
mock.MatchedBy(
func(options *storage.GetMessagesOptions) bool {
return options.NumOfMessages == AzureMessageFetchCount &&
options.VisibilityTimeout == int(AzureMessageVisibilityTimeout/time.Second)
},
),
).Return([]AzureMessage{}, nil)
// Mock the output queue if needed
outputMessage := new(azureMessageMock)
outputQueue := new(azureQueueMock)
if output {
outputMessage.On(
"Put",
mock.MatchedBy(
func(options *storage.PutMessageOptions) bool {
return options == nil
},
),
).Return(nil).Times(count)
outputQueue.On(
"Create",
mock.MatchedBy(
func(options *storage.QueueServiceOptions) bool {
return options == nil
},
),
).Return(nil).Times(count)
outputQueue.On("NewMessage", FunctionResponse).Return(outputMessage).Times(count)
}
// Mock the queue service to return the input queue
service := new(azureQueueServiceMock)
service.On("GetQueue", QueueName).Return(queue).Once()
if output {
service.On("GetQueue", OutputQueueName).Return(outputQueue).Times(count)
}
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, err := config.Build()
panicIf(err)
// Create the storage connection and subscribe to the trigger
connection := AzureStorageConnection{
logger: logger,
routerURL: DummyRouterURL,
service: service,
httpClient: httpClient,
}
subscription, err := connection.Subscribe(&fv1.MessageQueueTrigger{
ObjectMeta: metav1.ObjectMeta{
Name: TriggerName,
Namespace: metav1.NamespaceDefault,
},
Spec: fv1.MessageQueueTriggerSpec{
FunctionReference: fv1.FunctionReference{
Type: fv1.FunctionReferenceTypeFunctionName,
Name: FunctionName,
},
MessageQueueType: fv1.MessageQueueTypeASQ,
Topic: QueueName,
ResponseTopic: responseTopic,
ContentType: ContentType,
},
})
require.NoError(t, err)
require.NotNil(t, subscription)
panicIf(connection.Unsubscribe(subscription))
mock.AssertExpectationsForObjects(t, httpClient, message, outputMessage, queue, outputQueue, service)
}
|
{
"content_hash": "ff099ed48bb40431437bee816d91d3f5",
"timestamp": "",
"source": "github",
"line_count": 474,
"max_line_length": 168,
"avg_line_length": 28.122362869198312,
"alnum_prop": 0.7200300075018755,
"repo_name": "platform9/fission",
"id": "e985c329a6d9c146dc21cf291babb7dfbde42ad6",
"size": "13896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/mqtrigger/messageQueue/azurequeuestorage/asq_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "161278"
},
{
"name": "JavaScript",
"bytes": "2743"
},
{
"name": "Python",
"bytes": "1235"
},
{
"name": "Shell",
"bytes": "1331"
}
],
"symlink_target": ""
}
|
<?php
use Helpers\Assets;
use Helpers\Url;
use Helpers\Hooks;
use Helpers\Session;
use Models\Page;
//initialise hooks
$hooks = Hooks::get();
?>
<!DOCTYPE html>
<html lang="en" class="app">
<head>
<meta charset="utf-8" />
<meta name="description" content="app, web app, responsive, admin dashboard, admin, flat, flat ui, ui kit, off screen nav" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<title><?php echo $title.' | '.SITETITLE; ?></title>
<?php
Assets::css(array(
Url::templatePath() . 'js/jPlayer/jplayer.flat.css',
Url::templatePath() . 'css/bootstrap.css',
Url::templatePath() . 'css/animate.css',
Url::templatePath() . 'css/font-awesome.min.css',
Url::templatePath() . 'css/simple-line-icons.css',
Url::templatePath() . 'css/font.css',
Url::templatePath() . 'css/app.css'
));
//hook for plugging in css
$hooks->run('css');
?>
<!--[if lt IE 9]>
<?php
Assets::js(array(
Url::templatePath() . 'js/ie/html5shiv.js',
Url::templatePath() . 'js/ie/respond.min.js',
Url::templatePath() . 'js/ie/excanvas.js'
));
?>
<![endif]-->
<!--
<script type="text/javascript" src="http://hosted.musesradioplayer.com/mrp.js"></script>
<script type="text/javascript">
MRP.insert({
'url':'http://icestream.coolwazobiainfo.com:8000/coolfm-lagos',
'codec':'mp3',
'volume':100,
'autoplay':true,
'buffering':5,
'title':'Cool FM',
'bgcolor':'#FFFFFF',
'skin':'mcclean',
'width':180,
'height':60
});
</script>
-->
</head>
<?php Session::notification(); ?>
|
{
"content_hash": "5e263496f802d8f52a78904e580215ca",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 127,
"avg_line_length": 23.597014925373134,
"alnum_prop": 0.6280834914611005,
"repo_name": "Oluwafemikorede/gbedu",
"id": "26d81ad8c4d001667fc12358015ba764a2305f34",
"size": "1581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/default/header.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1088"
},
{
"name": "CSS",
"bytes": "425201"
},
{
"name": "HTML",
"bytes": "477685"
},
{
"name": "JavaScript",
"bytes": "488980"
},
{
"name": "PHP",
"bytes": "1379408"
}
],
"symlink_target": ""
}
|
layout: post
title: Kiara Mia & John E Depth
titleinfo: pornvd
desc: Watch Kiara Mia & John E Depth. Pornhub is the ultimate xxx porn and sex site.
---
<iframe src="http://www.pornhub.com/embed/1341023325" frameborder="0" width="630" height="338" scrolling="no"></iframe>
<h2>Kiara Mia & John E Depth</h2>
<h3>Watch Kiara Mia & John E Depth. Pornhub is the ultimate xxx porn and sex site.</h3>
|
{
"content_hash": "42aa83cce56e333e74206c2ba334bc72",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 119,
"avg_line_length": 42.7,
"alnum_prop": 0.6955503512880562,
"repo_name": "pornvd/pornvd.github.io",
"id": "da888ebaa69ae24f2f1738b0453ddb4ca0c9c3c1",
"size": "431",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-01-26-Kiara-Mia-&-John-E-Depth.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18073"
},
{
"name": "HTML",
"bytes": "10043"
},
{
"name": "JavaScript",
"bytes": "1581"
},
{
"name": "Python",
"bytes": "2932"
},
{
"name": "Ruby",
"bytes": "3287"
},
{
"name": "Shell",
"bytes": "310"
}
],
"symlink_target": ""
}
|
import React from "react";
import Method from "../../method.js";
import Parameter from "../../parameter.js";
import Example from "../../example.js";
import ResourceMissingResult from "../../resourceMissingResult.js";
export default class CreateResetTokenMethod extends Method {
uri() { return "/api/v1/users/reset"; }
version() { return 1; }
httpMethod() { return "POST"; }
group() { return "user"; }
description() {
return (
<div>
<p>
This is the "lost password" functionality. Hitting this endpoint
will cause a password reset request to be sent to the user via their email.
</p>
<p>
That email contains a code which they can use to complete their
reset request.
</p>
</div>
)
}
parameters() { return [ new EmailParameter() ]; }
examples() { return [ new SuccesfulExample(), new ResourceMissingResult("User"),
new RateLimitExample() ]; }
}
class EmailParameter extends Parameter {
name() { return "email"; }
description() { return "Users's email address."; }
}
class SuccesfulExample extends Example {
httpCode() { return 200; }
data() { return "Succesfully sent password reset email"; }
}
class RateLimitExample extends Example {
httpCode() { return 429; }
data() { return "Too many reset requests. Please wait a few minutes, or check your spambox"; }
}
|
{
"content_hash": "4da0d5a38da1dab5cd0551adb9b99bb3",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 96,
"avg_line_length": 29.95744680851064,
"alnum_prop": 0.6377840909090909,
"repo_name": "MrAdder/developers",
"id": "d88aff7c856df08deab71c29ac60cb00c98313f9",
"size": "1408",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/api/docs/user/sendResetToken.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33358"
},
{
"name": "HTML",
"bytes": "2140221"
},
{
"name": "JavaScript",
"bytes": "153038"
},
{
"name": "Shell",
"bytes": "285"
}
],
"symlink_target": ""
}
|
package ru.otus.web;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.security.Credential;
import ru.otus.datasets.LoginDataSet;
import ru.otus.db.dbservices.DBServiceNamed;
import ru.otus.jpa.JPAException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by Artem Gabbasov on 25.07.2017.
* <p>
*/
@SuppressWarnings("FieldCanBeLocal")
public class LoginServlet extends HttpServlet {
private final String LOGIN_PAGE_TEMPLATE = "login.html";
private final String UNDEFINED_MESSAGE = "DBService is undefined";
private final String PARAMETER_USERNAME = "username";
private final String PARAMETER_PASSWORD = "password";
private final DBServiceNamed dbService;
/**
* Флаг, указывающий, что попытка авторизации не удалась (для вывода красивого сообщения на странице авторизации)
*/
private boolean isLastLoginIncorrect;
public LoginServlet(DBServiceNamed dbService) {
this.dbService = dbService;
isLastLoginIncorrect = false;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String, Object> pageVariables = new HashMap<>();
pageVariables.put("isLastLoginIncorrect", isLastLoginIncorrect);
resp.getWriter().println(TemplateProcessor.instance().getPage(LOGIN_PAGE_TEMPLATE, pageVariables));
isLastLoginIncorrect = false;
resp.setContentType("text/html;charset=utf-8");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (dbService == null) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, UNDEFINED_MESSAGE);
} else {
try {
processRequest(req.getParameter(PARAMETER_USERNAME), req.getParameter(PARAMETER_PASSWORD), req.getSession(), resp);
} catch (SQLException | JPAException e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
}
}
}
/**
* Обрабатывает http-запрос на авторизацию
* @param username имя пользователя из http-запроса
* @param password пароль из http-запроса
* @param session сессия для авторизации
* @param resp http-ответ для реакции на запрос
* @throws SQLException
* @throws JPAException
* @throws IOException
* @throws ServletException
*/
private void processRequest(String username, String password, HttpSession session, HttpServletResponse resp) throws SQLException, JPAException, IOException, ServletException {
String passwordMD5 = Credential.MD5.digest(password);
passwordMD5 = passwordMD5.startsWith("MD5:")?passwordMD5.substring("MD5:".length()):passwordMD5;
processLoginData(username, passwordMD5, session, resp);
}
/**
* Обрабатывает учётные данные, пришедшие в запросе
* @param username имя пользователя
* @param passwordMD5 MD5-хеш пароля
* @param session сессия для авторизации
* @param resp http-ответ для реакции на запрос
* @throws JPAException
* @throws SQLException
* @throws IOException
* @throws ServletException
*/
private void processLoginData(String username, String passwordMD5, HttpSession session, HttpServletResponse resp) throws JPAException, SQLException, IOException, ServletException {
LoginDataSet loginDataSet = dbService.loadByName(username, LoginDataSet.class);
if (loginDataSet != null && loginDataSet.getPasswordMD5().equals(passwordMD5)) {
Object authorizedSessions = ContextHandler.getCurrentContext().getAttribute(ServerManager.AUTHORIZED_SESSIONS);
Set<HttpSession> authorizedSessionsSet;
if (authorizedSessions == null) {
authorizedSessionsSet = new HashSet<>();
} else {
authorizedSessionsSet = (Set<HttpSession>) authorizedSessions;
}
authorizedSessionsSet.add(session);
ContextHandler.getCurrentContext().setAttribute(ServerManager.AUTHORIZED_SESSIONS, authorizedSessionsSet);
String redirectPage;
Object redirectPageObj = ContextHandler.getCurrentContext().getAttribute(ServerManager.REDIRECT_PAGE);
if (redirectPageObj != null) {
redirectPage = redirectPageObj.toString();
} else {
redirectPage = ServerManager.INDEX_PAGE;
}
resp.sendRedirect(redirectPage);
} else {
isLastLoginIncorrect = true;
doGet(null, resp);
}
}
}
|
{
"content_hash": "52778e7c0a06231982ace1d985cde6f0",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 184,
"avg_line_length": 40.85826771653543,
"alnum_prop": 0.6824050876854886,
"repo_name": "artem-gabbasov/otus_java_2017_04_L1",
"id": "6c3d37c58aadbf28df4938b05c60475816a0c337",
"size": "5504",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "L12.1/src/main/java/ru/otus/web/LoginServlet.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "214"
},
{
"name": "CSS",
"bytes": "192"
},
{
"name": "HTML",
"bytes": "5392"
},
{
"name": "Java",
"bytes": "730238"
},
{
"name": "JavaScript",
"bytes": "3221"
},
{
"name": "Shell",
"bytes": "852"
}
],
"symlink_target": ""
}
|
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20120607091940 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("ALTER TABLE inscripcion CHANGE sede sede INT NOT NULL");
$this->addSql("ALTER TABLE inscripcion ADD CONSTRAINT FK_935E99F02C395692 FOREIGN KEY (sexo) REFERENCES opcion_sexo(id)");
}
public function down(Schema $schema)
{
// this down() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("ALTER TABLE inscripcion DROP FOREIGN KEY FK_935E99F02C395692");
$this->addSql("ALTER TABLE inscripcion CHANGE sede sede TINYINT(1) DEFAULT NULL");
}
}
|
{
"content_hash": "d17aa8118e20977b902abc6da9b4f40d",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 130,
"avg_line_length": 36.56666666666667,
"alnum_prop": 0.6882406563354604,
"repo_name": "rodrigomiranda/upv-form-inscripcion",
"id": "f6ca4b3254660cddf818e9be3a2451ab0eb5c807",
"size": "1097",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/DoctrineMigrations/Version20120607091940.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "53133"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>matrices: 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 / released</a></li>
<li class="active"><a href="">8.9.1 / matrices - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
matrices
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-18 10:02:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-18 10:02:02 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/matrices"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Matrices"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [ "keyword: matrices" "keyword: vectors" "keyword: linear algebra" "keyword: Coq modules" "category: Mathematics/Algebra" "date: 2003-03" ]
authors: [ "Nicolas Magaud" ]
bug-reports: "https://github.com/coq-contribs/matrices/issues"
dev-repo: "git+https://github.com/coq-contribs/matrices.git"
synopsis: "Ring properties for square matrices"
description: """
This contribution contains an operational formalization of square matrices.
(m,n)-Matrices are represented as vectors of length n. Each vector
(a row) is itself a vector whose length is m.
Vectors are actually implemented as dependent lists.
We define basic operations for this datatype (addition, product, neutral
elements O_n and I_n). We then prove the ring properties for these
operations. The development uses Coq modules to specify the interface
(the ring structure properties) as a signature.
This development deals with dependent types and partial functions.
Most of the functions are defined by dependent case analysis
and some functions such as getting a column require
the use of preconditions (to check whether we are within the
bounds of the matrix)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/matrices/archive/v8.8.0.tar.gz"
checksum: "md5=e1966ab1027086001a3f4b27f37978dc"
}
</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-matrices.8.8.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1).
The following dependencies couldn't be met:
- coq-matrices -> coq < 8.9~ -> 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-matrices.8.8.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": "906a54133614b2d1ada1177553ba742f",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 205,
"avg_line_length": 43.067796610169495,
"alnum_prop": 0.5657877476059294,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e31ae2c685d771289d9604761d18b90a0a7567b0",
"size": "7648",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.9.1/matrices/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
(function ($) {
"use strict";
var defaults = {
animateTime: 300
};
var StickyChimp = function(el, options) {
this.options = $.extend(defaults, options);
this.el = el;
this.elementHeight = el.height();
this.elementTop = parseInt(el.css('top'), 10);
this.documentHeight = $(document).height();
this.windowHeight = $(window).height();
this.lastFromTop = 0;
this.sclUp = 0;
this.sclDown = 0;
this.upperHit = false;
this.lowerHit = false;
this.lastScroll = 0;
var that = this;
$(window).resize(function() {
that.onResize();
});
$(window).scroll(function() {
that.onScroll();
});
};
StickyChimp.prototype.hideMenu = function() {
$(this.el).stop().animate({
opacity: 0,
top: '-=' + this.elementHeight
}, this.options.animateTime, function() {
$(this).css('top');
});
};
StickyChimp.prototype.showMenu = function(fromTop) {
$(this.el).stop().animate({
opacity: 1,
top: this.elementTop > 0 && fromTop < this.elementTop ? this.elementTop : 0
}, this.options.animateTime);
};
StickyChimp.prototype.onResize = function() {
this.documentHeight = $(document).height();
this.windowHeight = $(window).height();
};
StickyChimp.prototype.onScroll = function() {
var now = +new Date(),
fromTop = $(window).scrollTop(),
atBottom = fromTop >= (this.documentHeight - this.windowHeight - 5);
if(this.elementTop === 0) {
// If element top is 0 we can defer the scroll events and reduce methods fired.
if((now - this.lastScroll < 250)) {
return;
}
} else {
// However due to continue change in the menu position when scrolling we need to fire
// each of the scroll events when the menu top is > 0 ensuring smooth animation.
var adjustedTop = fromTop < 0 ? 0 : fromTop;
$(this.el).css('top', fromTop > this.elementTop ? 0 : this.elementTop - adjustedTop);
}
// Clear animation queue and set to visible if user hits the top of the page suddenly.
if(fromTop <= 0) {
$(this.el).stop(true);
$(this.el).show().fadeTo(0, 1).css('top', this.elementTop);
}
if (!atBottom && fromTop > this.lastFromTop) {
this.sclUp = 0;
this.lowerHit = false;
this.sclDown += (fromTop - this.lastFromTop);
if (!this.upperHit && (this.sclDown > this.elementHeight)) {
this.upperHit = true;
this.hideMenu();
}
} else {
this.sclDown = 0;
this.upperHit = false;
this.sclUp += (this.lastFromTop - fromTop);
if (!this.lowerHit && (this.sclUp > this.elementHeight || fromTop >= this.windowHeight)) {
this.lowerHit = true;
this.showMenu(fromTop);
}
}
this.lastFromTop = fromTop;
this.lastScroll = now;
};
$.fn.stickychimp = function (options) {
new StickyChimp(this, options);
};
$(window).on('load', function () {
$('[data-toggle="stickychimp"]').each(function () {
var el = $(this);
new StickyChimp(el, el.data());
});
});
}(jQuery));
|
{
"content_hash": "5f24919ed8ab236b87013a8d9f94318e",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 93,
"avg_line_length": 25.31304347826087,
"alnum_prop": 0.631054620405359,
"repo_name": "nathanbrock/StickyChimp",
"id": "0b8e30580d6dbbc0e5326766b1163c46155e4cb5",
"size": "2911",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/jquery.stickychimp.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2013"
},
{
"name": "JavaScript",
"bytes": "10445"
}
],
"symlink_target": ""
}
|
module Azure::ApiManagement::Mgmt::V2016_07_07
module Models
#
# API OAuth2 Authentication settings details.
#
class OAuth2AuthenticationSettingsContract
include MsRestAzure
# @return [String] OAuth authorization server identifier.
attr_accessor :authorization_server_id
# @return [String] operations scope.
attr_accessor :scope
#
# Mapper for OAuth2AuthenticationSettingsContract class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'OAuth2AuthenticationSettingsContract',
type: {
name: 'Composite',
class_name: 'OAuth2AuthenticationSettingsContract',
model_properties: {
authorization_server_id: {
client_side_validation: true,
required: false,
serialized_name: 'authorizationServerId',
type: {
name: 'String'
}
},
scope: {
client_side_validation: true,
required: false,
serialized_name: 'scope',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
{
"content_hash": "15243545fb418eb27c37ccec4f4f3d69",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 75,
"avg_line_length": 27.25,
"alnum_prop": 0.5257586450247,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "ad0554b5c5ed362a15417831b03e25f28e82738e",
"size": "1581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_api_management/lib/2016-07-07/generated/azure_mgmt_api_management/models/oauth2authentication_settings_contract.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.