text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class TextAttributeTypeController extends Concrete5_Controller_AttributeType_Text {}
| {'content_hash': 'd40dce9b0c3197a0e2d2d58c5fa3dc52', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 85, 'avg_line_length': 35.5, 'alnum_prop': 0.7816901408450704, 'repo_name': 'Skyvod/integration', 'id': '6c0d482dc07ab958cf77ce071d54c5c27c1e557e', 'size': '142', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'concrete/models/attribute/types/text/controller.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1683'}, {'name': 'PHP', 'bytes': '6454'}]} |
#pragma once
#include <aws/codecommit/CodeCommit_EXPORTS.h>
#include <aws/codecommit/CodeCommitRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace CodeCommit
{
namespace Model
{
/**
* <p>Represents the input of a get commit operation.</p>
*/
class AWS_CODECOMMIT_API GetCommitRequest : public CodeCommitRequest
{
public:
GetCommitRequest();
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline const Aws::String& GetRepositoryName() const{ return m_repositoryName; }
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline void SetRepositoryName(const Aws::String& value) { m_repositoryNameHasBeenSet = true; m_repositoryName = value; }
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline void SetRepositoryName(Aws::String&& value) { m_repositoryNameHasBeenSet = true; m_repositoryName = value; }
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline void SetRepositoryName(const char* value) { m_repositoryNameHasBeenSet = true; m_repositoryName.assign(value); }
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline GetCommitRequest& WithRepositoryName(const Aws::String& value) { SetRepositoryName(value); return *this;}
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline GetCommitRequest& WithRepositoryName(Aws::String&& value) { SetRepositoryName(value); return *this;}
/**
* <p>The name of the repository to which the commit was made.</p>
*/
inline GetCommitRequest& WithRepositoryName(const char* value) { SetRepositoryName(value); return *this;}
/**
* <p>The commit ID.</p>
*/
inline const Aws::String& GetCommitId() const{ return m_commitId; }
/**
* <p>The commit ID.</p>
*/
inline void SetCommitId(const Aws::String& value) { m_commitIdHasBeenSet = true; m_commitId = value; }
/**
* <p>The commit ID.</p>
*/
inline void SetCommitId(Aws::String&& value) { m_commitIdHasBeenSet = true; m_commitId = value; }
/**
* <p>The commit ID.</p>
*/
inline void SetCommitId(const char* value) { m_commitIdHasBeenSet = true; m_commitId.assign(value); }
/**
* <p>The commit ID.</p>
*/
inline GetCommitRequest& WithCommitId(const Aws::String& value) { SetCommitId(value); return *this;}
/**
* <p>The commit ID.</p>
*/
inline GetCommitRequest& WithCommitId(Aws::String&& value) { SetCommitId(value); return *this;}
/**
* <p>The commit ID.</p>
*/
inline GetCommitRequest& WithCommitId(const char* value) { SetCommitId(value); return *this;}
private:
Aws::String m_repositoryName;
bool m_repositoryNameHasBeenSet;
Aws::String m_commitId;
bool m_commitIdHasBeenSet;
};
} // namespace Model
} // namespace CodeCommit
} // namespace Aws
| {'content_hash': '6d368fb79c3fbb84d94f3571e670de75', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 124, 'avg_line_length': 30.423076923076923, 'alnum_prop': 0.6554993678887484, 'repo_name': 'ambasta/aws-sdk-cpp', 'id': '4004542a07034ef654f01252479e50923d35c1e9', 'size': '3737', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-codecommit/include/aws/codecommit/model/GetCommitRequest.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2305'}, {'name': 'C++', 'bytes': '74273816'}, {'name': 'CMake', 'bytes': '412257'}, {'name': 'Java', 'bytes': '229873'}, {'name': 'Python', 'bytes': '62933'}]} |
package gw.internal.gosu.ir.transform.statement;
import gw.config.CommonServices;
import gw.internal.gosu.parser.TypeLoaderAccess;
import gw.internal.gosu.parser.expressions.ArrayAccess;
import gw.internal.gosu.parser.statements.ArrayAssignmentStatement;
import gw.internal.gosu.ir.transform.ExpressionTransformer;
import gw.internal.gosu.ir.transform.TopLevelTransformationContext;
import gw.internal.gosu.runtime.GosuRuntimeMethods;
import gw.lang.ir.IRStatement;
import gw.lang.ir.IRExpression;
import gw.lang.ir.IRSymbol;
import gw.lang.ir.statement.IRStatementList;
import gw.lang.parser.EvaluationException;
import gw.lang.reflect.IPlaceholder;
import gw.lang.reflect.IType;
import gw.lang.reflect.java.JavaTypes;
import gw.util.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
*/
public class ArrayAssignmentStatementTransformer extends AbstractStatementTransformer<ArrayAssignmentStatement>
{
public static IRStatement compile( TopLevelTransformationContext cc, ArrayAssignmentStatement stmt )
{
ArrayAssignmentStatementTransformer gen = new ArrayAssignmentStatementTransformer( cc, stmt );
return gen.compile();
}
private ArrayAssignmentStatementTransformer( TopLevelTransformationContext cc, ArrayAssignmentStatement stmt )
{
super( cc, stmt );
}
@Override
protected IRStatement compile_impl()
{
ArrayAccess arrayAccess = _stmt().getArrayAccessExpression();
IRExpression originalRoot = ExpressionTransformer.compile( arrayAccess.getRootExpression(), _cc() );
IRSymbol tempRoot = null;
IRExpression root;
boolean needsAutoinsert = needsAutoinsert( arrayAccess );
if( needsAutoinsert || _stmt().isCompoundStatement() )
{
tempRoot = _cc().makeAndIndexTempSymbol( originalRoot.getType() );
root = identifier( tempRoot );
if(_stmt().isCompoundStatement())
{
ExpressionTransformer.addTempSymbolForCompoundAssignment(arrayAccess.getRootExpression(), tempRoot );
}
} else {
root = originalRoot;
}
IRExpression originalIndex = ExpressionTransformer.compile( arrayAccess.getMemberExpression(), _cc() );
IRSymbol tempIndex = null;
IRExpression index;
if( needsAutoinsert || _stmt().isCompoundStatement() )
{
tempIndex = _cc().makeAndIndexTempSymbol( originalIndex.getType() );
index = identifier( tempIndex );
if( _stmt().isCompoundStatement() )
{
ExpressionTransformer.addTempSymbolForCompoundAssignment( arrayAccess.getMemberExpression(), tempIndex );
}
}
else
{
index = originalIndex;
}
IRExpression value = ExpressionTransformer.compile( _stmt().getExpression(), _cc() );
IType rootType = arrayAccess.getRootExpression().getType();
if( rootType.isArray() && isBytecodeType( rootType ) )
{
// Normal array access
IRStatement ret = buildArrayStore( root, index, value, getDescriptor( rootType.getComponentType() ) );
if( _stmt().isCompoundStatement() )
{
ExpressionTransformer.clearTempSymbolForCompoundAssignment();
return new IRStatementList( false, buildAssignment( tempRoot, originalRoot ), buildAssignment( tempIndex, originalIndex ), ret );
}
return ret;
}
else
{
IRStatement ret;
if( needsAutoinsert )
{
return new IRStatementList( false, buildAssignment( tempRoot, originalRoot ),
buildAssignment( tempIndex, originalIndex ),
buildMethodCall( callStaticMethod( ArrayAssignmentStatementTransformer.class, "setOrAddElement", new Class[]{Object.class, int.class, Object.class},
exprList( root, index, value ) ) ) );
}
else if( JavaTypes.LIST().isAssignableFrom( rootType ) )
{
ret = buildMethodCall( buildMethodCall( List.class, "set", Object.class, new Class[]{int.class, Object.class},
buildCast( getDescriptor( List.class ), root ), Arrays.asList( index, value ) ) );
}
else if( JavaTypes.STRING_BUILDER().isAssignableFrom( rootType ) )
{
ret = buildMethodCall( buildMethodCall( StringBuilder.class, "setCharAt", void.class, new Class[]{int.class, char.class},
buildCast( getDescriptor( StringBuilder.class ), root ), Arrays.asList( index, value ) ) );
}
else if( rootType instanceof IPlaceholder )
{
ret = buildMethodCall(
callStaticMethod( ArrayAssignmentStatementTransformer.class, "setPropertyOrElementOnDynamicType", new Class[]{Object.class, Object.class, Object.class},
exprList( root, index, value ) ) );
}
else
{
ret = buildMethodCall(
callStaticMethod( ArrayAssignmentStatementTransformer.class, "setArrayElement", new Class[]{Object.class, int.class, Object.class},
exprList( root, index, value ) ) );
}
if( _stmt().isCompoundStatement() )
{
ExpressionTransformer.clearTempSymbolForCompoundAssignment();
return new IRStatementList( false, buildAssignment( tempRoot, originalRoot ), buildAssignment( tempIndex, originalIndex ), ret );
}
return ret;
}
}
private static boolean needsAutoinsert( ArrayAccess arrayAccess ) {
if (ArrayAccess.needsAutoinsert( arrayAccess ) ) {
return true;
} else if ( arrayAccess.getRootExpression() instanceof ArrayAccess ) {
return ArrayAccess.needsAutoinsert((ArrayAccess) arrayAccess.getRootExpression());
} else {
return false;
}
}
public static void setPropertyOrElementOnDynamicType( Object obj, Object index, Object value )
{
if( obj == null )
{
throw new NullPointerException();
}
if( index instanceof Number )
{
if( obj instanceof Map )
{
((Map)obj).put( index, value );
}
else if( obj.getClass().isArray() )
{
Array.set( obj, ((Number)index).intValue(), value );
}
else if( obj instanceof List )
{
((List)obj).set( ((Number)index).intValue(), value );
}
else if( obj instanceof StringBuilder )
{
if( value instanceof Character )
{
((StringBuilder)obj).setCharAt( ((Number)index).intValue(), (Character)value );
}
else if( value instanceof Number )
{
((StringBuilder)obj).setCharAt( ((Number)index).intValue(), (char)((Number)value).intValue() );
}
else
{
replaceAt( (StringBuilder)obj, (Number)index, value );
}
}
else
{
IType classObj = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( obj );
if( classObj.isArray() )
{
value = CommonServices.getCoercionManager().convertValue( value, classObj.getComponentType() );
classObj.setArrayComponent( obj, ((Number)index).intValue(), value );
}
else
{
throw new UnsupportedOperationException( "Don't know how to assign [" + value + "] to [" + obj + "] at index [" + index + "]" );
}
}
}
else if( obj instanceof Map )
{
((Map)obj).put( index, value );
}
else
{
GosuRuntimeMethods.setPropertyDynamically( obj, index.toString(), value );
}
}
private static void replaceAt( StringBuilder obj, Number index, Object value )
{
int start = index.intValue();
int end = start + ((CharSequence)value).length();
if( end <= obj.length() )
{
obj.replace( start, end, value.toString() );
}
else
{
obj.delete( start, obj.length() );
String s = value.toString();
obj.append( s );
}
}
public static void setArrayElement( Object obj, int iIndex, Object value )
{
if( obj instanceof List )
{
//noinspection unchecked
((List)obj).set( iIndex, value );
return;
}
IType classObj = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( obj );
if( classObj.isArray() )
{
value = CommonServices.getCoercionManager().convertValue( value, classObj.getComponentType() );
classObj.setArrayComponent( obj, iIndex, value );
return;
}
if( obj instanceof StringBuffer )
{
((StringBuffer)obj).setCharAt( iIndex, ((Character)CommonServices.getCoercionManager().convertValue( value, JavaTypes.CHARACTER() )).charValue() );
}
throw new EvaluationException( "The type, " + classObj.getName() + ", is not coercible to an indexed-writable array." );
}
public static void setOrAddElement( Object obj, int iIndex, Object value )
{
List l = (List)obj;
if( l.size() == iIndex )
{
l.add( value );
}
else
{
l.set( iIndex, value );
}
}
}
| {'content_hash': '01bd4ef3f6d5ad67a9efee317617cb3d', 'timestamp': '', 'source': 'github', 'line_count': 258, 'max_line_length': 184, 'avg_line_length': 34.64341085271318, 'alnum_prop': 0.6424255985679123, 'repo_name': 'gosu-lang/gosu-lang', 'id': 'ceb4a8cab12b0f44c67c90ed34d6f7c650f44444', 'size': '8987', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gosu-core/src/main/java/gw/internal/gosu/ir/transform/statement/ArrayAssignmentStatementTransformer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '10236'}, {'name': 'GAP', 'bytes': '51837'}, {'name': 'Gosu', 'bytes': '16976739'}, {'name': 'Groovy', 'bytes': '22653'}, {'name': 'Java', 'bytes': '12112134'}, {'name': 'JavaScript', 'bytes': '921060'}, {'name': 'Makefile', 'bytes': '6850'}, {'name': 'Python', 'bytes': '8450'}, {'name': 'Roff', 'bytes': '345'}, {'name': 'Shell', 'bytes': '3417'}]} |
<!--
Author: Sam Ruby (http://intertwingly.net/) and Mark Pilgrim (http://diveintomark.org/)
Copyright: Copyright (c) 2002 Sam Ruby and Mark Pilgrim
-->
<!--
Description: lastBuildDate must be RFC 2822 date format
Expect: ValidRFC2822Date{parent:channel,element:lastBuildDate}
-->
<rss version="2.0">
<channel>
<title>Invalid date format</title>
<link>http://purl.org/rss/2.0/</link>
<description>lastBuildDate must be RFC 2822 date format</description>
<lastBuildDate>Tue, 31 Dec 2002 14:20:20 GMT</lastBuildDate>
</channel>
</rss>
| {'content_hash': '4e20d6b8e8633aba33f2eed8762b4414', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 95, 'avg_line_length': 31.055555555555557, 'alnum_prop': 0.7084078711985689, 'repo_name': 'youprofit/NewsBlur', 'id': 'e942d49d6e052a45230b8e386331c3e2bb26d6d6', 'size': '559', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'vendor/feedvalidator/demo/testcases/rss20/element-channel-lastbuilddate/valid_lastBuildDate.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '678536'}, {'name': 'CoffeeScript', 'bytes': '6451'}, {'name': 'HTML', 'bytes': '269852'}, {'name': 'Java', 'bytes': '710373'}, {'name': 'JavaScript', 'bytes': '1577082'}, {'name': 'Nginx', 'bytes': '897'}, {'name': 'Objective-C', 'bytes': '2667108'}, {'name': 'Perl', 'bytes': '55598'}, {'name': 'Python', 'bytes': '2407231'}, {'name': 'R', 'bytes': '527'}, {'name': 'Ruby', 'bytes': '870'}, {'name': 'Shell', 'bytes': '40018'}]} |
package org.apache.flink.api.common.io;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.fs.FileInputSplit;
import org.apache.flink.core.fs.Path;
import org.apache.flink.types.parser.FieldParser;
import org.apache.flink.types.parser.StringParser;
import org.apache.flink.types.parser.StringValueParser;
import org.apache.flink.util.InstantiationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
@Internal
public abstract class GenericCsvInputFormat<OT> extends DelimitedInputFormat<OT> {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(GenericCsvInputFormat.class);
private static final Class<?>[] EMPTY_TYPES = new Class<?>[0];
private static final boolean[] EMPTY_INCLUDED = new boolean[0];
private static final byte[] DEFAULT_FIELD_DELIMITER = new byte[] {','};
private static final byte BACKSLASH = 92;
// --------------------------------------------------------------------------------------------
// Variables for internal operation.
// They are all transient, because we do not want them so be serialized
// --------------------------------------------------------------------------------------------
private transient FieldParser<?>[] fieldParsers;
// To speed up readRecord processing. Used to find windows line endings.
// It is set when open so that readRecord does not have to evaluate it
protected boolean lineDelimiterIsLinebreak = false;
protected transient int commentCount;
protected transient int invalidLineCount;
// --------------------------------------------------------------------------------------------
// The configuration parameters. Configured on the instance and serialized to be shipped.
// --------------------------------------------------------------------------------------------
private Class<?>[] fieldTypes = EMPTY_TYPES;
protected boolean[] fieldIncluded = EMPTY_INCLUDED;
// The byte representation of the delimiter is updated consistent with
// current charset.
private byte[] fieldDelim = DEFAULT_FIELD_DELIMITER;
private String fieldDelimString = null;
private boolean lenient;
private boolean skipFirstLineAsHeader;
private boolean quotedStringParsing = false;
private byte quoteCharacter;
// The byte representation of the comment prefix is updated consistent with
// current charset.
protected byte[] commentPrefix = null;
private String commentPrefixString = null;
// --------------------------------------------------------------------------------------------
// Constructors and getters/setters for the configurable parameters
// --------------------------------------------------------------------------------------------
protected GenericCsvInputFormat() {
super();
}
protected GenericCsvInputFormat(Path filePath) {
super(filePath, null);
}
// --------------------------------------------------------------------------------------------
public int getNumberOfFieldsTotal() {
return this.fieldIncluded.length;
}
public int getNumberOfNonNullFields() {
return this.fieldTypes.length;
}
@Override
public void setCharset(String charset) {
super.setCharset(charset);
if (this.fieldDelimString != null) {
this.fieldDelim = fieldDelimString.getBytes(getCharset());
}
if (this.commentPrefixString != null) {
this.commentPrefix = commentPrefixString.getBytes(getCharset());
}
}
public byte[] getCommentPrefix() {
return commentPrefix;
}
public void setCommentPrefix(String commentPrefix) {
if (commentPrefix != null) {
this.commentPrefix = commentPrefix.getBytes(getCharset());
} else {
this.commentPrefix = null;
}
this.commentPrefixString = commentPrefix;
}
public byte[] getFieldDelimiter() {
return fieldDelim;
}
public void setFieldDelimiter(String delimiter) {
if (delimiter == null) {
throw new IllegalArgumentException("Delimiter must not be null");
}
this.fieldDelim = delimiter.getBytes(getCharset());
this.fieldDelimString = delimiter;
}
public boolean isLenient() {
return lenient;
}
public void setLenient(boolean lenient) {
this.lenient = lenient;
}
public boolean isSkippingFirstLineAsHeader() {
return skipFirstLineAsHeader;
}
public void setSkipFirstLineAsHeader(boolean skipFirstLine) {
this.skipFirstLineAsHeader = skipFirstLine;
}
public void enableQuotedStringParsing(char quoteCharacter) {
quotedStringParsing = true;
this.quoteCharacter = (byte)quoteCharacter;
}
// --------------------------------------------------------------------------------------------
protected FieldParser<?>[] getFieldParsers() {
return this.fieldParsers;
}
protected Class<?>[] getGenericFieldTypes() {
// check if we are dense, i.e., we read all fields
if (this.fieldIncluded.length == this.fieldTypes.length) {
return this.fieldTypes;
}
else {
// sparse type array which we made dense for internal book keeping.
// create a sparse copy to return
Class<?>[] types = new Class<?>[this.fieldIncluded.length];
for (int i = 0, k = 0; i < this.fieldIncluded.length; i++) {
if (this.fieldIncluded[i]) {
types[i] = this.fieldTypes[k++];
}
}
return types;
}
}
protected void setFieldTypesGeneric(Class<?> ... fieldTypes) {
if (fieldTypes == null) {
throw new IllegalArgumentException("Field types must not be null.");
}
this.fieldIncluded = new boolean[fieldTypes.length];
ArrayList<Class<?>> types = new ArrayList<Class<?>>();
// check if we support parsers for these types
for (int i = 0; i < fieldTypes.length; i++) {
Class<?> type = fieldTypes[i];
if (type != null) {
if (FieldParser.getParserForType(type) == null) {
throw new IllegalArgumentException("The type '" + type.getName() + "' is not supported for the CSV input format.");
}
types.add(type);
fieldIncluded[i] = true;
}
}
this.fieldTypes = types.toArray(new Class<?>[types.size()]);
}
protected void setFieldsGeneric(int[] sourceFieldIndices, Class<?>[] fieldTypes) {
checkNotNull(sourceFieldIndices);
checkNotNull(fieldTypes);
checkArgument(sourceFieldIndices.length == fieldTypes.length,
"Number of field indices and field types must match.");
for (int i : sourceFieldIndices) {
if (i < 0) {
throw new IllegalArgumentException("Field indices must not be smaller than zero.");
}
}
int largestFieldIndex = max(sourceFieldIndices);
this.fieldIncluded = new boolean[largestFieldIndex + 1];
ArrayList<Class<?>> types = new ArrayList<Class<?>>();
// check if we support parsers for these types
for (int i = 0; i < fieldTypes.length; i++) {
Class<?> type = fieldTypes[i];
if (type != null) {
if (FieldParser.getParserForType(type) == null) {
throw new IllegalArgumentException("The type '" + type.getName()
+ "' is not supported for the CSV input format.");
}
types.add(type);
fieldIncluded[sourceFieldIndices[i]] = true;
}
}
this.fieldTypes = types.toArray(new Class<?>[types.size()]);
}
protected void setFieldsGeneric(boolean[] includedMask, Class<?>[] fieldTypes) {
checkNotNull(includedMask);
checkNotNull(fieldTypes);
ArrayList<Class<?>> types = new ArrayList<Class<?>>();
// check if types are valid for included fields
int typeIndex = 0;
for (int i = 0; i < includedMask.length; i++) {
if (includedMask[i]) {
if (typeIndex > fieldTypes.length - 1) {
throw new IllegalArgumentException("Missing type for included field " + i + ".");
}
Class<?> type = fieldTypes[typeIndex++];
if (type == null) {
throw new IllegalArgumentException("Type for included field " + i + " should not be null.");
} else {
// check if we support parsers for this type
if (FieldParser.getParserForType(type) == null) {
throw new IllegalArgumentException("The type '" + type.getName() + "' is not supported for the CSV input format.");
}
types.add(type);
}
}
}
this.fieldTypes = types.toArray(new Class<?>[types.size()]);
this.fieldIncluded = includedMask;
}
// --------------------------------------------------------------------------------------------
// Runtime methods
// --------------------------------------------------------------------------------------------
@Override
public void open(FileInputSplit split) throws IOException {
super.open(split);
// instantiate the parsers
FieldParser<?>[] parsers = new FieldParser<?>[fieldTypes.length];
for (int i = 0; i < fieldTypes.length; i++) {
if (fieldTypes[i] != null) {
Class<? extends FieldParser<?>> parserType = FieldParser.getParserForType(fieldTypes[i]);
if (parserType == null) {
throw new RuntimeException("No parser available for type '" + fieldTypes[i].getName() + "'.");
}
FieldParser<?> p = InstantiationUtil.instantiate(parserType, FieldParser.class);
p.setCharset(getCharset());
if (this.quotedStringParsing) {
if (p instanceof StringParser) {
((StringParser)p).enableQuotedStringParsing(this.quoteCharacter);
} else if (p instanceof StringValueParser) {
((StringValueParser)p).enableQuotedStringParsing(this.quoteCharacter);
}
}
parsers[i] = p;
}
}
this.fieldParsers = parsers;
// skip the first line, if we are at the beginning of a file and have the option set
if (this.skipFirstLineAsHeader && this.splitStart == 0) {
readLine(); // read and ignore
}
}
@Override
public void close() throws IOException {
if (this.invalidLineCount > 0) {
if (LOG.isWarnEnabled()) {
LOG.warn("In file \""+ this.filePath + "\" (split start: " + this.splitStart + ") " + this.invalidLineCount +" invalid line(s) were skipped.");
}
}
if (this.commentCount > 0) {
if (LOG.isInfoEnabled()) {
LOG.info("In file \""+ this.filePath + "\" (split start: " + this.splitStart + ") " + this.commentCount +" comment line(s) were skipped.");
}
}
super.close();
}
protected boolean parseRecord(Object[] holders, byte[] bytes, int offset, int numBytes) throws ParseException {
boolean[] fieldIncluded = this.fieldIncluded;
int startPos = offset;
final int limit = offset + numBytes;
for (int field = 0, output = 0; field < fieldIncluded.length; field++) {
// check valid start position
if (startPos > limit || (startPos == limit && field != fieldIncluded.length - 1)) {
if (lenient) {
return false;
} else {
throw new ParseException("Row too short: " + new String(bytes, offset, numBytes, getCharset()));
}
}
if (fieldIncluded[field]) {
// parse field
@SuppressWarnings("unchecked")
FieldParser<Object> parser = (FieldParser<Object>) this.fieldParsers[output];
Object reuse = holders[output];
startPos = parser.resetErrorStateAndParse(bytes, startPos, limit, this.fieldDelim, reuse);
holders[output] = parser.getLastResult();
// check parse result
if (startPos < 0) {
// no good
if (lenient) {
return false;
} else {
String lineAsString = new String(bytes, offset, numBytes, getCharset());
throw new ParseException("Line could not be parsed: '" + lineAsString + "'\n"
+ "ParserError " + parser.getErrorState() + " \n"
+ "Expect field types: "+fieldTypesToString() + " \n"
+ "in file: " + filePath);
}
}
else if (startPos == limit
&& field != fieldIncluded.length - 1
&& !FieldParser.endsWithDelimiter(bytes, startPos - 1, fieldDelim)) {
// We are at the end of the record, but not all fields have been read
// and the end is not a field delimiter indicating an empty last field.
if (lenient) {
return false;
} else {
throw new ParseException("Row too short: " + new String(bytes, offset, numBytes));
}
}
output++;
}
else {
// skip field
startPos = skipFields(bytes, startPos, limit, this.fieldDelim);
if (startPos < 0) {
if (!lenient) {
String lineAsString = new String(bytes, offset, numBytes, getCharset());
throw new ParseException("Line could not be parsed: '" + lineAsString+"'\n"
+ "Expect field types: "+fieldTypesToString()+" \n"
+ "in file: "+filePath);
} else {
return false;
}
}
else if (startPos == limit
&& field != fieldIncluded.length - 1
&& !FieldParser.endsWithDelimiter(bytes, startPos - 1, fieldDelim)) {
// We are at the end of the record, but not all fields have been read
// and the end is not a field delimiter indicating an empty last field.
if (lenient) {
return false;
} else {
throw new ParseException("Row too short: " + new String(bytes, offset, numBytes));
}
}
}
}
return true;
}
private String fieldTypesToString() {
StringBuilder string = new StringBuilder();
string.append(this.fieldTypes[0].toString());
for (int i = 1; i < this.fieldTypes.length; i++) {
string.append(", ").append(this.fieldTypes[i]);
}
return string.toString();
}
protected int skipFields(byte[] bytes, int startPos, int limit, byte[] delim) {
int i = startPos;
final int delimLimit = limit - delim.length + 1;
if (quotedStringParsing && bytes[i] == quoteCharacter) {
// quoted string parsing enabled and field is quoted
// search for ending quote character, continue when it is escaped
i++;
while (i < limit && (bytes[i] != quoteCharacter || bytes[i-1] == BACKSLASH)) {
i++;
}
i++;
if (i == limit) {
// we are at the end of the record
return limit;
} else if ( i < delimLimit && FieldParser.delimiterNext(bytes, i, delim)) {
// we are not at the end, check if delimiter comes next
return i + delim.length;
} else {
// delimiter did not follow end quote. Error...
return -1;
}
} else {
// field is not quoted
while(i < delimLimit && !FieldParser.delimiterNext(bytes, i, delim)) {
i++;
}
if (i >= delimLimit) {
// no delimiter found. We are at the end of the record
return limit;
} else {
// delimiter found.
return i + delim.length;
}
}
}
@SuppressWarnings("unused")
protected static void checkAndCoSort(int[] positions, Class<?>[] types) {
if (positions.length != types.length) {
throw new IllegalArgumentException("The positions and types must be of the same length");
}
TreeMap<Integer, Class<?>> map = new TreeMap<Integer, Class<?>>();
for (int i = 0; i < positions.length; i++) {
if (positions[i] < 0) {
throw new IllegalArgumentException("The field " + " (" + positions[i] + ") is invalid.");
}
if (types[i] == null) {
throw new IllegalArgumentException("The type " + i + " is invalid (null)");
}
if (map.containsKey(positions[i])) {
throw new IllegalArgumentException("The position " + positions[i] + " occurs multiple times.");
}
map.put(positions[i], types[i]);
}
int i = 0;
for (Map.Entry<Integer, Class<?>> entry : map.entrySet()) {
positions[i] = entry.getKey();
types[i] = entry.getValue();
i++;
}
}
protected static void checkForMonotonousOrder(int[] positions, Class<?>[] types) {
if (positions.length != types.length) {
throw new IllegalArgumentException("The positions and types must be of the same length");
}
int lastPos = -1;
for (int i = 0; i < positions.length; i++) {
if (positions[i] < 0) {
throw new IllegalArgumentException("The field " + " (" + positions[i] + ") is invalid.");
}
if (types[i] == null) {
throw new IllegalArgumentException("The type " + i + " is invalid (null)");
}
if (positions[i] <= lastPos) {
throw new IllegalArgumentException("The positions must be strictly increasing (no permutations are supported).");
}
lastPos = positions[i];
}
}
private static int max(int[] ints) {
checkArgument(ints.length > 0);
int max = ints[0];
for (int i = 1 ; i < ints.length; i++) {
max = Math.max(max, ints[i]);
}
return max;
}
}
| {'content_hash': 'e6a7d57f463e59f701f9905fcf5af5ab', 'timestamp': '', 'source': 'github', 'line_count': 533, 'max_line_length': 147, 'avg_line_length': 30.557223264540337, 'alnum_prop': 0.6299502670841776, 'repo_name': 'Xpray/flink', 'id': 'bddaec96491c0ba0b4cee3563951b01b9b565abc', 'size': '17092', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'flink-core/src/main/java/org/apache/flink/api/common/io/GenericCsvInputFormat.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4792'}, {'name': 'CSS', 'bytes': '18100'}, {'name': 'CoffeeScript', 'bytes': '89458'}, {'name': 'HTML', 'bytes': '88253'}, {'name': 'Java', 'bytes': '31057958'}, {'name': 'JavaScript', 'bytes': '8267'}, {'name': 'Python', 'bytes': '166860'}, {'name': 'Scala', 'bytes': '5494479'}, {'name': 'Shell', 'bytes': '76520'}]} |
from django import forms
from django.forms.models import inlineformset_factory
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.widgets import AdminPageChooser
from wagtail.wagtailsearch import models
class QueryForm(forms.Form):
query_string = forms.CharField(label=_("Search term(s)/phrase"),
help_text=_("Enter the full search string to match. An "
"exact match is required for your Editors Picks to be "
"displayed, wildcards are NOT allowed."),
required=True)
class EditorsPickForm(forms.ModelForm):
sort_order = forms.IntegerField(required=False)
def __init__(self, *args, **kwargs):
super(EditorsPickForm, self).__init__(*args, **kwargs)
self.fields['page'].widget = AdminPageChooser()
class Meta:
model = models.EditorsPick
fields = ('query', 'page', 'description')
widgets = {
'description': forms.Textarea(attrs=dict(rows=3)),
}
EditorsPickFormSetBase = inlineformset_factory(models.Query, models.EditorsPick, form=EditorsPickForm, can_order=True, can_delete=True, extra=0)
class EditorsPickFormSet(EditorsPickFormSetBase):
minimum_forms = 1
minimum_forms_message = _("Please specify at least one recommendation for this search term.")
def add_fields(self, form, *args, **kwargs):
super(EditorsPickFormSet, self).add_fields(form, *args, **kwargs)
# Hide delete and order fields
form.fields['DELETE'].widget = forms.HiddenInput()
form.fields['ORDER'].widget = forms.HiddenInput()
# Remove query field
del form.fields['query']
def clean(self):
# Editors pick must have at least one recommended page to be valid
# Check there is at least one non-deleted form.
non_deleted_forms = self.total_form_count()
non_empty_forms = 0
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete and self._should_delete_form(form):
non_deleted_forms -= 1
if not (form.instance.id is None and not form.has_changed()):
non_empty_forms += 1
if (
non_deleted_forms < self.minimum_forms
or non_empty_forms < self.minimum_forms
):
raise forms.ValidationError(self.minimum_forms_message)
| {'content_hash': '403f36f23e8a16510c528f86a4dd7d88', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 144, 'avg_line_length': 36.63076923076923, 'alnum_prop': 0.6526669466610667, 'repo_name': 'darith27/wagtail', 'id': '6f067497faf1ec468f96a34eb789dd94adfffc2e', 'size': '2381', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'wagtail/wagtailsearch/forms.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '149904'}, {'name': 'HTML', 'bytes': '239138'}, {'name': 'JavaScript', 'bytes': '87166'}, {'name': 'Makefile', 'bytes': '548'}, {'name': 'Python', 'bytes': '1432674'}, {'name': 'Shell', 'bytes': '6954'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.17"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>JWTXX: File List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">JWTXX
</div>
<div id="projectbrief">C++ library for JWT</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.17 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">File List</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock">Here is a list of all documented files with brief descriptions:</div><div class="directory">
<div class="levels">[detail level <span onclick="javascript:toggleLevel(1);">1</span><span onclick="javascript:toggleLevel(2);">2</span><span onclick="javascript:toggleLevel(3);">3</span>]</div><table class="directory">
<tr id="row_0_" class="even"><td class="entry"><span style="width:0px;display:inline-block;"> </span><span id="arr_0_" class="arrow" onclick="toggleFolder('0_')">▼</span><span id="img_0_" class="iconfopen" onclick="toggleFolder('0_')"> </span><a class="el" href="dir_d44c64559bbebec7f509842c48db8b23.html" target="_self">include</a></td><td class="desc"></td></tr>
<tr id="row_0_0_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span id="arr_0_0_" class="arrow" onclick="toggleFolder('0_0_')">▼</span><span id="img_0_0_" class="iconfopen" onclick="toggleFolder('0_0_')"> </span><a class="el" href="dir_cbd0c1630137b12302b80799dec40aec.html" target="_self">jwtxx</a></td><td class="desc"></td></tr>
<tr id="row_0_0_0_" class="even"><td class="entry"><span style="width:48px;display:inline-block;"> </span><a href="ios_8h_source.html"><span class="icondoc"></span></a><a class="el" href="ios_8h.html" target="_self">ios.h</a></td><td class="desc">Stream input/output functions </td></tr>
<tr id="row_0_0_1_"><td class="entry"><span style="width:48px;display:inline-block;"> </span><a href="jwt_8h_source.html"><span class="icondoc"></span></a><a class="el" href="jwt_8h.html" target="_self">jwt.h</a></td><td class="desc">Classes, constants and functions to work with JWT </td></tr>
</table>
</div><!-- directory -->
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.17
</small></address>
</body>
</html>
| {'content_hash': '9ad6a2077ab9beb525e08a6e8347d699', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 380, 'avg_line_length': 53.90588235294118, 'alnum_prop': 0.6809253601047578, 'repo_name': 'madf/jwtxx', 'id': 'a95c6d9aa9c218898b2529d9bc11a35b10bea721', 'size': '4582', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/files.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '113'}, {'name': 'C++', 'bytes': '123994'}, {'name': 'CMake', 'bytes': '6570'}]} |
@interface PodsDummy_Pods_TXDragAndDrop_Example : NSObject
@end
@implementation PodsDummy_Pods_TXDragAndDrop_Example
@end
| {'content_hash': '4e03d07f08436be50ac6219b61b487f8', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 58, 'avg_line_length': 30.5, 'alnum_prop': 0.8442622950819673, 'repo_name': 'rtoshiro/TXDragAndDrop', 'id': '03f2a4b8414d2094b5cacd5e0d57a31230f0ef01', 'size': '156', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Example/Pods/Target Support Files/Pods-TXDragAndDrop_Example/Pods-TXDragAndDrop_Example-dummy.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '187877'}, {'name': 'Ruby', 'bytes': '3945'}, {'name': 'Shell', 'bytes': '24787'}, {'name': 'Swift', 'bytes': '2696'}]} |
import ActionDispatcher from '../dispatcher/action-dispatcher';
import ContextMenuConstants from '../constants/contextmenu-constants';
import clipboard from 'clipboard-js';
export default class ClipboardAction {
constructor() {
ActionDispatcher.register((action) => {
switch(action.actionType) {
case ContextMenuConstants.COPY_TEXT:
clipboard.copy(action.text);
break;
default:
break;
}
});
}
}
| {'content_hash': '7e5ab95e759ba8a850adb9db85145f63', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 70, 'avg_line_length': 31.529411764705884, 'alnum_prop': 0.5764925373134329, 'repo_name': 'sabazusi/tsukikaze', 'id': '053335e664464d4a9b0e7206f666e63b5b53f8b7', 'size': '536', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/renderer/actions/clipboard-action.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '119594'}, {'name': 'HTML', 'bytes': '3560'}, {'name': 'JavaScript', 'bytes': '65432'}]} |
package com.example.mobilesafe.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class AppLockOpenHelper extends SQLiteOpenHelper {
public AppLockOpenHelper(Context context) {
super(context, "applock.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info (_id integer primary key autoincrement,packagename varchar(20)) ");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
| {'content_hash': 'ca46c5266167624ccde89caf9758b689', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 99, 'avg_line_length': 26.56, 'alnum_prop': 0.786144578313253, 'repo_name': 'yuSniper/mobilesafe', 'id': 'cb3138efc3507e1ef41c158bbef2600d442baf09', 'size': '664', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/com/example/mobilesafe/db/AppLockOpenHelper.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '193820'}]} |
'use strict';
var _ = require('lodash');
var vg = {};
// Utility functions
vg.bezier = require('./util/bezier');
vg.color = require('./util/color');
vg.geo = require('./util/geo');
vg.math = require('./util/math');
vg.random = require('./util/random');
vg.svg = require('./util/svg');
// Objects
vg.Color = require('./objects/color');
vg.Group = require('./objects/group');
vg.Matrix4 = require('./objects/matrix4');
vg.Path = require('./objects/path');
vg.Point = vg.Vec2 = require('./objects/point');
vg.Rect = require('./objects/rect');
vg.Text = require('./objects/text');
vg.Transform = vg.Matrix3 = require('./objects/transform');
vg.Vec3 = require('./objects/vec3');
// Commands
function importCommands(module) {
for (var k in module) {
vg[k] = module[k];
}
}
var Transformable = require('./objects/transformable');
_.extend(vg.Point.prototype, Transformable);
_.extend(vg.Path.prototype, Transformable);
_.extend(vg.Group.prototype, Transformable);
_.extend(vg.Text.prototype, Transformable);
importCommands(require('./commands/draw'));
importCommands(require('./commands/filters'));
importCommands(require('./commands/shapes'));
module.exports = vg; | {'content_hash': '9af8704bea827b8c3286a4b31053c6c2', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 59, 'avg_line_length': 27.488372093023255, 'alnum_prop': 0.6759729272419628, 'repo_name': 'nodebox/vg.js', 'id': '33e96f1ffcbd3599d5bf524b6c4dbb56cb9bab77', 'size': '1534', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/vg.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '9373'}, {'name': 'JavaScript', 'bytes': '1008370'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 20827 -->
<!-- Reviewed: no -->
<sect1 id="zend.progressbar.introduction" xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Zend_ProgressBar</title>
<sect2 id="zend.progressbar.whatisit">
<title>Wprowadzenie</title>
<para>
<classname>Zend_ProgressBar</classname> to komponent służący do tworzenia i
aktualizacji pasków postępu (progressbar) w różnych środowiskach. Składa się na niego
pojedynczy element backendu, który sygnalizuje postęp poprzez jeden z wielu
dostępnych adapterów. Podczas każdej aktualizacji brana jest wartość absolutna i
opcjonalna wiadomość o stanie postępu a następnie skonfigurowany adapter
jest wywoływany z obliczonymi danymi takimi jak procent postępu
oraz czas, jaki został do końca wykonywanej akcji.
</para>
</sect2>
<sect2 id="zend.progressbar.basic">
<title>Podstawowe użycie Zend_Progressbar</title>
<para>
<classname>Zend_ProgressBar</classname> jest komponentem łatwym w użyciu. Należy,
po prostu, utworzyć nową instancję klasy <classname>Zend_Progressbar</classname>,
definiując wartość minimalną i maksymalną oraz wybrać adapter służący prezentacji
danych o postępie działań. W przypadku operacji na pliku, użycie może wyglądać
następująco:
</para>
<programlisting language="php"><![CDATA[
$progressBar = new Zend_ProgressBar($adapter, 0, $fileSize);
while (!feof($fp)) {
// Wykonanie operacji
$progressBar->update($currentByteCount);
}
$progressBar->finish();
]]></programlisting>
<para>
W pierwszym kroku tworzona jest instancja <classname>Zend_ProgressBar</classname>
ze zdefiniowanym adapterem, wartością minimalną: 0, oraz maksymalną równą
rozmiarowi pliku. Po tym następuje seria operacji na pliku w pętli.
Podczas każdej iteracji pętli, pasek postępu jest aktualizowany danymi o
ilości "przerobionych" bajtów pliku.
</para>
<para>
Metodę <methodname>update()</methodname> klasy <classname>Zend_ProgressBar</classname>
można również wywoływać bez argumentów. Powoduje to przeliczenie czasu do końca
wykonywanej akcji i wysłanie go do adaptera. Ten sposób może być przydatny gdy nie
ma konkretnych danych do wysłania adapterowi ale niezbędna jest aktualizacja
paska postępu.
</para>
</sect2>
<sect2 id="zend.progressbar.persistent">
<title>Postęp utrwalony (persistent progress)</title>
<para>
Jeśli zajdzie potrzeba utrzymania paska postępu przez wiele żądań, można w tym celu
podać łańcuch znaków z przestrzenią nazw sesji
jako czwarty argument konstruktora. W tym przypadku
pasek postępu nie uaktualni adaptera w momencie konstruowania - niezbędne będzie
wywołanie metody <methodname>update()</methodname>
lub <methodname>finish()</methodname>.
Obecna wartość, tekst stanu postępu oraz czas rozpoczęcia działania
(wymagany przy obliczaniu czasu pozostałego do końca) będą pobrane podczas następnego
żądania i uruchomienia skryptu.
</para>
</sect2>
<sect2 id="zend.progressbar.adapters">
<title>Standardowe adaptery</title>
<para>
Standardowo <classname>Zend_ProgressBar</classname> ma do dyspozycji następujące
adaptery:
<itemizedlist mark="opencircle">
<listitem>
<para><xref linkend="zend.progressbar.adapter.console" /></para>
</listitem>
<listitem><para><xref linkend="zend.progressbar.adapter.jspush" /></para></listitem>
<listitem><para><xref linkend="zend.progressbar.adapter.jspull" /></para></listitem>
</itemizedlist>
</para>
<xi:include href="Zend_ProgressBar_Adapter_Console.xml" />
<xi:include href="Zend_ProgressBar_Adapter_JsPush.xml" />
<xi:include href="Zend_ProgressBar_Adapter_JsPull.xml" />
</sect2>
</sect1>
<!--
vim:se ts=4 sw=4 et:
-->
| {'content_hash': '4b744b5dc19b4571a3def2f3d117ee18', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 100, 'avg_line_length': 43.292929292929294, 'alnum_prop': 0.6556229584694354, 'repo_name': 'whitefire/zf2', 'id': '5807c9e49364c547d456136c0f1a2db75d58c2dd', 'size': '4394', 'binary': False, 'copies': '48', 'ref': 'refs/heads/master', 'path': 'documentation/manual/pl/module_specs/Zend_ProgressBar.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '30072'}, {'name': 'PHP', 'bytes': '27001014'}, {'name': 'Shell', 'bytes': '5201'}]} |
<?php
/** Zend_Mobile_Push_Message_Interface **/
//require_once 'Zend/Mobile/Push/Message/Interface.php';
/** Zend_Mobile_Push_Message_Exception **/
//require_once 'Zend/Mobile/Push/Message/Exception.php';
/**
* Message Abstract
*
* @category Zend
* @package Zend_Mobile
* @subpackage Zend_Mobile_Push_Message
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
abstract class Zend_Mobile_Push_Message_Abstract implements Zend_Mobile_Push_Message_Interface
{
/**
* Token
*
* @var string
*/
protected $_token;
/**
* Id
*
* @var scalar
*/
protected $_id;
/**
* Get Token
*
* @return string
*/
public function getToken()
{
return $this->_token;
}
/**
* Set Token
*
* @param string $token
* @return Zend_Mobile_Push_Message_Abstract
*/
public function setToken($token)
{
if (!is_string($token)) {
throw new Zend_Mobile_Push_Message_Exception('$token must be a string');
}
$this->_token = $token;
return $this;
}
/**
* Get Message ID
*
* @return scalar
*/
public function getId()
{
return $this->_id;
}
/**
* Set Message ID
*
* @param scalar $id
* @return Zend_Mobile_Push_Message_Abstract
* @throws Exception
*/
public function setId($id)
{
if (!is_scalar($id)) {
throw new Zend_Mobile_Push_Message_Exception('$id must be a scalar');
}
$this->_id = $id;
return $this;
}
/**
* Set Options
*
* @param array $options
* @return Zend_Mobile_Push_Message_Abstract
* @throws Zend_Mobile_Push_Message_Exception
*/
public function setOptions(array $options)
{
foreach ($options as $k => $v) {
$method = 'set' . ucwords($k);
if (!method_exists($this, $method)) {
throw new Zend_Mobile_Push_Message_Exception('The method "' . $method . "' does not exist.");
}
$this->$method($v);
}
return $this;
}
/**
* Validate Message format
*
* @return boolean
*/
public function validate()
{
return true;
}
}
| {'content_hash': '551d90ccf5c93a1edb2632aa4645da70', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 109, 'avg_line_length': 21.03448275862069, 'alnum_prop': 0.5327868852459017, 'repo_name': 'zhy1stgg/highcharts.me', 'id': '951a9a43922a829703a2409345985d0229d3f509', 'size': '3164', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'system/Zend/Mobile/Push/Message/Abstract.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '189570'}, {'name': 'HTML', 'bytes': '1352212'}, {'name': 'JavaScript', 'bytes': '503310'}, {'name': 'PHP', 'bytes': '5289932'}]} |
package LeetcodeTemplate;
public class _0188BestTimeToBuyAndSellStockIV {
public static void main(String[] args) {
System.out.println(maxProfit(2, new int[] { 2, 4, 1 }));
System.out.println(maxProfit(2, new int[] { 3, 2, 6, 5, 0, 3 }));
}
public static int maxProfit(int k, int[] prices) {
}
}
| {'content_hash': 'fea9e5881e2db1fbf79a1f4d64f7372a', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 67, 'avg_line_length': 22.0, 'alnum_prop': 0.6655844155844156, 'repo_name': 'darshanhs90/Java-InterviewPrep', 'id': '029847f7956302e6fec960a15e850cf34dcf94ee', 'size': '308', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/LeetcodeTemplate/_0188BestTimeToBuyAndSellStockIV.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1870066'}]} |
'use strict'
const {resolve} = require('path')
, chalk = require('chalk')
, pkg = require('./package.json')
, debug = require('debug')(`${pkg.name}:boot`)
, nameError =
`*******************************************************************
You need to give your app a proper name.
The package name
${pkg.name}
isn't valid. If you don't change it, things won't work right.
Please change it in ${__dirname}/package.json
~ xoxo, bones
********************************************************************`
const reasonableName = /^[a-z0-9\-_]+$/
// RegExp.test docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
if (!reasonableName.test(pkg.name)) {
console.error(chalk.red(nameError))
}
// This will load a secrets file from
//
// ~/.your_app_name.env.js
// or ~/.your_app_name.env.json
//
// and add it to the environment.
// Note that this needs to be in your home directory, not the project's root directory
const env = process.env
, secretsFile = resolve(require('homedir')(), `.${pkg.name}.env`)
console.log(chalk.bold.green("secretsFile:"));
console.log(secretsFile);
try {
Object.assign(env, require(secretsFile))
console.log(chalk.bold.green("secretsFile:"));
console.log(require(secretsFile));
//console.log(chalk.bold.green("loaded the following env parameters from secretsFile:"));
//console.log(env);
} catch (error) {
debug('%s: %s', secretsFile, error.message)
debug('%s: env file not found or invalid, moving on', secretsFile)
}
module.exports = {
get name() { return pkg.name },
get isTesting() { return !!global.it },
get isProduction() {
return env.NODE_ENV === 'production'
},
get isDevelopment() {
return env.NODE_ENV === 'development'
},
get baseUrl() {
return env.BASE_URL || `http://localhost:${module.exports.port}`
},
get port() {
return env.PORT || 1337
},
get root() {
return __dirname
},
package: pkg,
env,
}
| {'content_hash': '4dd57986422873f0ec99be7e87a55013', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 113, 'avg_line_length': 27.63888888888889, 'alnum_prop': 0.6105527638190955, 'repo_name': 'tryandbry/grace-shopper', 'id': '1dbfa1a5b52397e5398c4154805564713644b66c', 'size': '1990', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '187792'}, {'name': 'HTML', 'bytes': '21197'}, {'name': 'JavaScript', 'bytes': '138123'}, {'name': 'Shell', 'bytes': '1794'}]} |
<div class="container">
<form name="editPersonForm" class="form-horizontal well" novalidate>
<fieldset>
<legend>Edit Person</legend>
<div class="form-group">
<label for="firstName" class="col-md-2 control-label">First Name</label>
<div class="col-md-10">
<input id="firstName" type="text" pattern=".{2,}" required title="2 characters minimum" placeholder="2 characters minimum" ng-model="currentPerson.FirstName" required="required" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="middleName" class="col-md-2 control-label">Middle Name</label>
<div class="col-md-10">
<input id="middleName" type="text" ng-model="currentPerson.MiddleName" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-md-2 control-label">Last Name</label>
<div class="col-md-10">
<input id="lastName" type="text" pattern=".{2,}" required title="2 characters minimum" placeholder="2 characters minimum" ng-model="currentPerson.LastName" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="gender" class="col-md-2 control-label">Gender</label>
<div class="col-md-10">
<select id="gender" class="form-control" ng-model="currentPerson.IsMale">
<option ng-repeat="g in genders" value="{{g.value}}" ng-selected="currentPerson.IsMale==={{g.value}}">{{g.name}}</option>
</select>
</div>
</div>
<div class="form-group">
<label for="birthday" class="col-md-2 control-label">Date of birth</label>
<div class="col-md-10">
<input id="birthday" type="datetime" ng-model="currentPerson.BirthDay" date-picker placeholder="yyyy-MM-dd" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="city" class="col-md-2 control-label">City</label>
<div class="col-md-10">
<input id="city" type="text" ng-model="currentPerson.City" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="phone" class="col-md-2 control-label">Phone number</label>
<div class="col-md-10">
<input id="phone" type="text" ng-model="currentPerson.PhoneNumber" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="egn" class="col-md-2 control-label">EGN/Personal number</label>
<div class="col-md-10">
<input id="egn" type="text" ng-model="currentPerson.EGN" class="form-control" />
</div>
</div>
<div class="pull-right">
<button ng-click="deletePerson(currentPerson.egn)" class="btn btn-danger">
Delete
</button>
<button name="deleteButton" ng-click="editPerson(currentPerson)" ng-disabled="editPersonForm.$invalid" class="btn btn-primary">
Edit
</button>
<a href="#/" class="btn btn-primary">Cancel</a>
</div>
</fieldset>
</form>
</div>
| {'content_hash': '45a441f9446475e06de17300246d66fd', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 221, 'avg_line_length': 54.21212121212121, 'alnum_prop': 0.5181665735047513, 'repo_name': 'TsvetanKT/BgPersonGeneratorClient', 'id': '89743617ebfc479b19b42bc6971e63b66a9b89fb', 'size': '3578', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'views/partials/edit.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '18'}, {'name': 'CSS', 'bytes': '7590'}, {'name': 'HTML', 'bytes': '18978'}, {'name': 'JavaScript', 'bytes': '21126'}]} |
import argparse
import typing
import random
import sys
def reducer() -> None:
running_sum = 0
running_total = 0
for line in sys.stdin:
pieces = line.split(",")
piece_sum = int(pieces[0])
piece_num = int(pieces[1])
running_sum += piece_sum
running_total += piece_num
print("{}".format(running_sum / running_total))
if __name__ == "__main__":
reducer()
| {'content_hash': '96c55a4097d53a2cb511d6e8d14a70a7', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 51, 'avg_line_length': 19.80952380952381, 'alnum_prop': 0.5793269230769231, 'repo_name': 'holycrap872/til', 'id': '9a7b80801f9b0172b347de8741b8643a25605eb1', 'size': '436', 'binary': False, 'copies': '1', 'ref': 'refs/heads/mainline', 'path': 'hadoop/average/reducer.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '9016'}, {'name': 'C', 'bytes': '2205'}, {'name': 'C++', 'bytes': '3545'}, {'name': 'E', 'bytes': '902619'}, {'name': 'Python', 'bytes': '16628'}, {'name': 'Ruby', 'bytes': '3150'}, {'name': 'Shell', 'bytes': '4093'}, {'name': 'Vim script', 'bytes': '1369'}]} |
using Provisioning.Common.Authentication;
using Provisioning.Common.Configuration;
using Provisioning.Common.Configuration.Application;
using Provisioning.Common.Utilities;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.Online.SharePoint.TenantManagement;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Provisioning.Common.Data.Templates;
using System.Diagnostics;
namespace Provisioning.Common
{
/// <summary>
/// Abstract Site Provisioning Service
/// </summary>
public abstract class AbstractSiteProvisioningService : ISiteProvisioning, ISharePointClientService
{
#region Properties
/// <summary>
/// Gets or Sets the services Authentication.
/// </summary>
public IAuthentication Authentication
{
get;
set;
}
#endregion
#region ISiteProvisioning Members
public abstract void CreateSiteCollection(SiteInformation siteRequest, Template template);
public abstract Web CreateSubSite(SiteInformation siteRequest, Template template);
public virtual bool IsTenantExternalSharingEnabled(string tenantUrl)
{
Log.Info("AbstractSiteProvisioningService.IsTenantExternalSharingEnabled", "Entering IsTenantExternalSharingEnabled Url {0}", tenantUrl);
var _returnResult = false;
UsingContext(ctx =>
{
Stopwatch _timespan = Stopwatch.StartNew();
Tenant _tenant = new Tenant(ctx);
ctx.Load(_tenant);
try
{
//IF CALLING SP ONPREM THIS WILL FAIL
ctx.ExecuteQuery();
//check sharing capabilities
if(_tenant.SharingCapability == SharingCapabilities.Disabled)
{
_returnResult = false;
}
else
{
_returnResult = true;
}
_timespan.Stop();
Log.TraceApi("SharePoint", "AbstractSiteProvisioningService.IsTenantExternalSharingEnabled", _timespan.Elapsed);
}
catch(Exception ex)
{
Log.Error("Provisioning.Common.AbstractSiteProvisioningService.IsTenantExternalSharingEnabled",
PCResources.ExternalSharing_Enabled_Error_Message,
tenantUrl,
ex);
}
});
return _returnResult;
}
/// <summary>
///
/// </summary>
/// <param name="siteUrl"></param>
public virtual bool isSiteExternalSharingEnabled(string siteUrl)
{
ConfigManager _manager = new ConfigManager();
var _tenantAdminUrl = _manager.GetAppSettingsKey("TenantAdminUrl");
var _returnResult = false;
AbstractSiteProvisioningService _siteService = new Office365SiteProvisioningService();
_siteService.Authentication = new AppOnlyAuthenticationTenant();
_siteService.Authentication.TenantAdminUrl = _tenantAdminUrl;
_siteService.UsingContext(ctx =>
{
try
{
Tenant _tenant = new Tenant(ctx);
SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteUrl, false);
ctx.Load(_tenant);
ctx.Load(_siteProps);
ctx.ExecuteQuery();
var _tenantSharingCapability = _tenant.SharingCapability;
var _siteSharingCapability = _siteProps.SharingCapability;
if (_tenantSharingCapability != SharingCapabilities.Disabled)
{
if (_siteSharingCapability != SharingCapabilities.Disabled)
{
// Enabled
_returnResult = true;
}
else
{
// Disabled
_returnResult = false;
}
}
else
{
// Disabled
_returnResult = false;
}
}
catch (Exception _ex)
{
Log.Warning("AbstractSiteProvisioningService.IsSiteExternalSharingEnabled",
PCResources.SiteExternalSharing_Enabled_Error_Message,
siteUrl,
_ex);
}
});
return _returnResult;
}
public abstract void SetExternalSharing(SiteInformation siteInfo);
public virtual SitePolicyEntity GetAppliedSitePolicy()
{
Log.Info("AbstractSiteProvisioningService.GetAppliedSitePolicy", "Entering GetAppliedSitePolicy");
SitePolicyEntity _appliedSitePolicy = null;
UsingContext(ctx =>
{
Stopwatch _timespan = Stopwatch.StartNew();
var _web = ctx.Web;
_appliedSitePolicy = _web.GetAppliedSitePolicy();
_timespan.Stop();
Log.TraceApi("SharePoint", "AbstractSiteProvisioningService.IsTenantExternalSharingEnabled", _timespan.Elapsed);
});
return _appliedSitePolicy;
}
public virtual void SetSitePolicy(string policyName)
{
Log.Info("AbstractSiteProvisioningService.SetSitePolicy", "Entering SetSitePolicy Policy Name {0}", policyName);
UsingContext(ctx =>
{
Stopwatch _timespan = Stopwatch.StartNew();
var _web = ctx.Web;
bool _policyApplied = _web.ApplySitePolicy(policyName);
_timespan.Stop();
Log.TraceApi("SharePoint", "AbstractSiteProvisioningService.SetSitePolicy", _timespan.Elapsed);
});
}
public virtual List<SitePolicyEntity> GetAvailablePolicies()
{
List<SitePolicyEntity> _results = new List<SitePolicyEntity>();
UsingContext(ctx =>
{
var _web = ctx.Web;
_results = _web.GetSitePolicies();
});
return _results;
}
public Web GetWebByUrl(string url)
{
Log.Info("AbstractSiteProvisioningService.GetWebByUrl", "Entering GetWebByUrl Url {0}", url);
Web _web = null;
UsingContext(ctx =>
{
_web = ctx.Site.RootWeb;
ctx.Load(_web);
ctx.ExecuteQuery();
});
return _web;
}
/// <summary>
/// Returns the Site Collection ID
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public Guid? GetSiteGuidByUrl(string url)
{
Log.Info("AbstractSiteProvisioningService.GetSiteGuidByUrl", "Entering GetSiteGuidByUrl Url {0}", url);
Guid? _siteID = Guid.Empty;
UsingContext(ctx =>
{
Tenant _tenant = new Tenant(ctx);
_siteID = _tenant.GetSiteGuidByUrl(url);
});
return _siteID;
}
#endregion
/// <summary>
/// Checks to see if a site already exists.
/// </summary>
/// <param name="siteUrl"></param>
/// <returns></returns>
public bool SiteExists(string siteUrl)
{
bool _doesSiteExist = false;
UsingContext(ctx =>
{
var tenant = new Tenant(ctx);
_doesSiteExist = tenant.SiteExists(siteUrl);
});
return _doesSiteExist;
}
/// <summary>
/// Checks to see if a sub site already exists.
/// </summary>
/// <param name="siteUrl"></param>
/// <returns></returns>
public bool SubSiteExists(string siteUrl)
{
bool _doesSiteExist = false;
UsingContext(ctx =>
{
var tenant = new Tenant(ctx);
_doesSiteExist = tenant.SubSiteExists(siteUrl);
});
return _doesSiteExist;
}
#region ISharePointService Members
/// <summary>
/// Delegate that is used to handle creation of ClientContext that is authenticated
/// </summary>
/// <param name="action"></param>
public void UsingContext(Action<ClientContext> action)
{
UsingContext(action, Timeout.Infinite);
}
/// <summary>
/// Delegate that is used to handle creation of ClientContext that is authenticated
/// </summary>
/// <param name="action"></param>
public void UsingContext(Action<ClientContext> action, int csomTimeout)
{
using (ClientContext _ctx = Authentication.GetAuthenticatedContext())
{
_ctx.RequestTimeout = csomTimeout;
action(_ctx);
}
}
#endregion
}
}
| {'content_hash': 'd946bed67de5b7340d8e2e559dd2c89c', 'timestamp': '', 'source': 'github', 'line_count': 275, 'max_line_length': 149, 'avg_line_length': 34.832727272727276, 'alnum_prop': 0.5291784111076313, 'repo_name': 'IvanTheBearable/PnP', 'id': 'a5acfdd6c9619b32366acf8c34c55d804cdbba8c', 'size': '9581', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'Solutions/Provisioning.UX.App/Provisioning.Common/AbstractSiteProvisioningService.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '284049'}, {'name': 'Batchfile', 'bytes': '565'}, {'name': 'C#', 'bytes': '7540217'}, {'name': 'CSS', 'bytes': '179178'}, {'name': 'Cucumber', 'bytes': '13062'}, {'name': 'HTML', 'bytes': '102893'}, {'name': 'JavaScript', 'bytes': '1688711'}, {'name': 'PowerShell', 'bytes': '8226'}, {'name': 'XSLT', 'bytes': '9717'}]} |
/*!
* Module dependencies.
*/
var EmbeddedDocument = require('./embedded');
var Document = require('../document');
var ObjectId = require('./objectid');
var utils = require('../utils');
var isMongooseObject = utils.isMongooseObject;
/**
* Mongoose Array constructor.
*
* ####NOTE:
*
* _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._
*
* @param {Array} values
* @param {String} path
* @param {Document} doc parent document
* @api private
* @inherits Array
* @see http://bit.ly/f6CnZU
*/
function MongooseArray (values, path, doc) {
var arr = [];
arr.push.apply(arr, values);
arr.__proto__ = MongooseArray.prototype;
arr._atomics = {};
arr.validators = [];
arr._path = path;
if (doc) {
arr._parent = doc;
arr._schema = doc.schema.path(path);
}
return arr;
};
/*!
* Inherit from Array
*/
MongooseArray.prototype = new Array;
/**
* Stores a queue of atomic operations to perform
*
* @property _atomics
* @api private
*/
MongooseArray.prototype._atomics;
/**
* Parent owner document
*
* @property _parent
* @api private
*/
MongooseArray.prototype._parent;
/**
* Casts a member based on this arrays schema.
*
* @param {any} value
* @return value the casted value
* @api private
*/
MongooseArray.prototype._cast = function (value) {
var owner = this._owner;
var populated = false;
var Model;
if (this._parent) {
// if a populated array, we must cast to the same model
// instance as specified in the original query.
if (!owner) {
owner = this._owner = this._parent.ownerDocument
? this._parent.ownerDocument()
: this._parent;
}
populated = owner.populated(this._path, true);
}
if (populated && null != value) {
// cast to the populated Models schema
var Model = populated.options.model;
// only objects are permitted so we can safely assume that
// non-objects are to be interpreted as _id
if (Buffer.isBuffer(value) ||
value instanceof ObjectId || !utils.isObject(value)) {
value = { _id: value };
}
value = new Model(value);
return this._schema.caster.cast(value, this._parent, true)
}
return this._schema.caster.cast(value, this._parent, false)
}
/**
* Marks this array as modified.
*
* If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
*
* @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array
* @param {String} embeddedPath the path which changed in the embeddedDoc
* @api private
*/
MongooseArray.prototype._markModified = function (elem, embeddedPath) {
var parent = this._parent
, dirtyPath;
if (parent) {
dirtyPath = this._path;
if (arguments.length) {
if (null != embeddedPath) {
// an embedded doc bubbled up the change
dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath;
} else {
// directly set an index
dirtyPath = dirtyPath + '.' + elem;
}
}
parent.markModified(dirtyPath);
}
return this;
};
/**
* Register an atomic operation with the parent.
*
* @param {Array} op operation
* @param {any} val
* @api private
*/
MongooseArray.prototype._registerAtomic = function (op, val) {
if ('$set' == op) {
// $set takes precedence over all other ops.
// mark entire array modified.
this._atomics = { $set: val };
return this;
}
var atomics = this._atomics;
// reset pop/shift after save
if ('$pop' == op && !('$pop' in atomics)) {
var self = this;
this._parent.once('save', function () {
self._popped = self._shifted = null;
});
}
// check for impossible $atomic combos (Mongo denies more than one
// $atomic op on a single path
if (this._atomics.$set ||
Object.keys(atomics).length && !(op in atomics)) {
// a different op was previously registered.
// save the entire thing.
this._atomics = { $set: this };
return this;
}
if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') {
atomics[op] || (atomics[op] = []);
atomics[op] = atomics[op].concat(val);
} else if (op === '$pullDocs') {
var pullOp = atomics['$pull'] || (atomics['$pull'] = {})
, selector = pullOp['_id'] || (pullOp['_id'] = {'$in' : [] });
selector['$in'] = selector['$in'].concat(val);
} else {
atomics[op] = val;
}
return this;
};
/**
* Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.
*
* If no atomics exist, we return all array values after conversion.
*
* @return {Array}
* @method $__getAtomics
* @memberOf MongooseArray
* @api private
*/
MongooseArray.prototype.$__getAtomics = function () {
var ret = [];
var keys = Object.keys(this._atomics);
var i = keys.length;
if (0 === i) {
ret[0] = ['$set', this.toObject({ depopulate: 1 })];
return ret;
}
while (i--) {
var op = keys[i];
var val = this._atomics[op];
// the atomic values which are arrays are not MongooseArrays. we
// need to convert their elements as if they were MongooseArrays
// to handle populated arrays versus DocumentArrays properly.
if (isMongooseObject(val)) {
val = val.toObject({ depopulate: 1 });
} else if (Array.isArray(val)) {
val = this.toObject.call(val, { depopulate: 1 });
} else if (val.valueOf) {
val = val.valueOf();
}
if ('$addToSet' == op) {
val = { $each: val }
}
ret.push([op, val]);
}
return ret;
}
/**
* Returns the number of pending atomic operations to send to the db for this array.
*
* @api private
* @return {Number}
*/
MongooseArray.prototype.hasAtomics = function hasAtomics () {
if (!(this._atomics && 'Object' === this._atomics.constructor.name)) {
return 0;
}
return Object.keys(this._atomics).length;
}
/**
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
*
* @param {Object} [args...]
* @api public
*/
MongooseArray.prototype.push = function () {
var values = [].map.call(arguments, this._cast, this)
, ret = [].push.apply(this, values);
// $pushAll might be fibbed (could be $push). But it makes it easier to
// handle what could have been $push, $pushAll combos
this._registerAtomic('$pushAll', values);
this._markModified();
return ret;
};
/**
* Pushes items to the array non-atomically.
*
* ####NOTE:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @param {any} [args...]
* @api public
*/
MongooseArray.prototype.nonAtomicPush = function () {
var values = [].map.call(arguments, this._cast, this)
, ret = [].push.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
return ret;
};
/**
* Pops the array atomically at most one time per document `save()`.
*
* #### NOTE:
*
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
*
* doc.array = [1,2,3];
*
* var popped = doc.array.$pop();
* console.log(popped); // 3
* console.log(doc.array); // [1,2]
*
* // no affect
* popped = doc.array.$pop();
* console.log(doc.array); // [1,2]
*
* doc.save(function (err) {
* if (err) return handleError(err);
*
* // we saved, now $pop works again
* popped = doc.array.$pop();
* console.log(popped); // 2
* console.log(doc.array); // [1]
* })
*
* @api public
* @method $pop
* @memberOf MongooseArray
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
*/
MongooseArray.prototype.$pop = function () {
this._registerAtomic('$pop', 1);
this._markModified();
// only allow popping once
if (this._popped) return;
this._popped = true;
return [].pop.call(this);
};
/**
* Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
*
* ####Note:
*
* _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @see MongooseArray#$pop #types_array_MongooseArray-%24pop
* @api public
*/
MongooseArray.prototype.pop = function () {
var ret = [].pop.call(this);
this._registerAtomic('$set', this);
this._markModified();
return ret;
};
/**
* Atomically shifts the array at most one time per document `save()`.
*
* ####NOTE:
*
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
*
* doc.array = [1,2,3];
*
* var shifted = doc.array.$shift();
* console.log(shifted); // 1
* console.log(doc.array); // [2,3]
*
* // no affect
* shifted = doc.array.$shift();
* console.log(doc.array); // [2,3]
*
* doc.save(function (err) {
* if (err) return handleError(err);
*
* // we saved, now $shift works again
* shifted = doc.array.$shift();
* console.log(shifted ); // 2
* console.log(doc.array); // [3]
* })
*
* @api public
* @memberOf MongooseArray
* @method $shift
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
*/
MongooseArray.prototype.$shift = function $shift () {
this._registerAtomic('$pop', -1);
this._markModified();
// only allow shifting once
if (this._shifted) return;
this._shifted = true;
return [].shift.call(this);
};
/**
* Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
*
* ####Example:
*
* doc.array = [2,3];
* var res = doc.array.shift();
* console.log(res) // 2
* console.log(doc.array) // [3]
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
*/
MongooseArray.prototype.shift = function () {
var ret = [].shift.call(this);
this._registerAtomic('$set', this);
this._markModified();
return ret;
};
/**
* Pulls items from the array atomically.
*
* ####Examples:
*
* doc.array.pull(ObjectId)
* doc.array.pull({ _id: 'someId' })
* doc.array.pull(36)
* doc.array.pull('tag 1', 'tag 2')
*
* To remove a document from a subdocument array we may pass an object with a matching `_id`.
*
* doc.subdocs.push({ _id: 4815162342 })
* doc.subdocs.pull({ _id: 4815162342 }) // removed
*
* Or we may passing the _id directly and let mongoose take care of it.
*
* doc.subdocs.push({ _id: 4815162342 })
* doc.subdocs.pull(4815162342); // works
*
* @param {any} [args...]
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
* @api public
*/
MongooseArray.prototype.pull = function () {
var values = [].map.call(arguments, this._cast, this)
, cur = this._parent.get(this._path)
, i = cur.length
, mem;
while (i--) {
mem = cur[i];
if (mem instanceof EmbeddedDocument) {
if (values.some(function (v) { return v.equals(mem); } )) {
[].splice.call(cur, i, 1);
}
} else if (~cur.indexOf.call(values, mem)) {
[].splice.call(cur, i, 1);
}
}
if (values[0] instanceof EmbeddedDocument) {
this._registerAtomic('$pullDocs', values.map( function (v) { return v._id; } ));
} else {
this._registerAtomic('$pullAll', values);
}
this._markModified();
return this;
};
/**
* Alias of [pull](#types_array_MongooseArray-pull)
*
* @see MongooseArray#pull #types_array_MongooseArray-pull
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
* @api public
* @memberOf MongooseArray
* @method remove
*/
MongooseArray.prototype.remove = MongooseArray.prototype.pull;
/**
* Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
*/
MongooseArray.prototype.splice = function splice () {
var ret, vals, i;
if (arguments.length) {
vals = [];
for (i = 0; i < arguments.length; ++i) {
vals[i] = i < 2
? arguments[i]
: this._cast(arguments[i]);
}
ret = [].splice.apply(this, vals);
this._registerAtomic('$set', this);
this._markModified();
}
return ret;
}
/**
* Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
*/
MongooseArray.prototype.unshift = function () {
var values = [].map.call(arguments, this._cast, this);
[].unshift.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
return this.length;
};
/**
* Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
*
* ####NOTE:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
*/
MongooseArray.prototype.sort = function () {
var ret = [].sort.apply(this, arguments);
this._registerAtomic('$set', this);
this._markModified();
return ret;
}
/**
* Adds values to the array if not already present.
*
* ####Example:
*
* console.log(doc.array) // [2,3,4]
* var added = doc.array.addToSet(4,5);
* console.log(doc.array) // [2,3,4,5]
* console.log(added) // [5]
*
* @param {any} [args...]
* @return {Array} the values that were added
* @api public
*/
MongooseArray.prototype.addToSet = function addToSet () {
var values = [].map.call(arguments, this._cast, this)
, added = []
, type = values[0] instanceof EmbeddedDocument ? 'doc' :
values[0] instanceof Date ? 'date' :
'';
values.forEach(function (v) {
var found;
switch (type) {
case 'doc':
found = this.some(function(doc){ return doc.equals(v) });
break;
case 'date':
var val = +v;
found = this.some(function(d){ return +d === val });
break;
default:
found = ~this.indexOf(v);
}
if (!found) {
[].push.call(this, v);
this._registerAtomic('$addToSet', v);
this._markModified();
[].push.call(added, v);
}
}, this);
return added;
};
/**
* Sets the casted `val` at index `i` and marks the array modified.
*
* ####Example:
*
* // given documents based on the following
* var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
*
* var doc = new Doc({ array: [2,3,4] })
*
* console.log(doc.array) // [2,3,4]
*
* doc.array.set(1,"5");
* console.log(doc.array); // [2,5,4] // properly cast to number
* doc.save() // the change is saved
*
* // VS not using array#set
* doc.array[1] = "5";
* console.log(doc.array); // [2,"5",4] // no casting
* doc.save() // change is not saved
*
* @return {Array} this
* @api public
*/
MongooseArray.prototype.set = function set (i, val) {
this[i] = this._cast(val);
this._markModified(i);
return this;
}
/**
* Returns a native js Array.
*
* @param {Object} options
* @return {Array}
* @api public
*/
MongooseArray.prototype.toObject = function (options) {
if (options && options.depopulate) {
return this.map(function (doc) {
return doc instanceof Document
? doc.toObject(options)
: doc
});
}
return this.slice();
}
/**
* Helper for console.log
*
* @api public
*/
MongooseArray.prototype.inspect = function () {
return '[' + this.map(function (doc) {
return ' ' + doc;
}) + ' ]';
};
/**
* Return the index of `obj` or `-1` if not found.
*
* @param {Object} obj the item to look for
* @return {Number}
* @api public
*/
MongooseArray.prototype.indexOf = function indexOf (obj) {
if (obj instanceof ObjectId) obj = obj.toString();
for (var i = 0, len = this.length; i < len; ++i) {
if (obj == this[i])
return i;
}
return -1;
};
/*!
* Module exports.
*/
module.exports = exports = MongooseArray;
| {'content_hash': '4ecf786f13b852d822bc0598253b1806', 'timestamp': '', 'source': 'github', 'line_count': 679, 'max_line_length': 202, 'avg_line_length': 26.583210603829162, 'alnum_prop': 0.598393351800554, 'repo_name': 'jclinn/myCloset2', 'id': 'deebc82cb64cc8b3f7bc7104ed225bfdc7a71367', 'size': '18050', 'binary': False, 'copies': '35', 'ref': 'refs/heads/master', 'path': 'node_modules/mongoose/lib/types/array.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '694'}, {'name': 'JavaScript', 'bytes': '3522'}, {'name': 'Shell', 'bytes': '3008'}]} |
function c = appendevent(a, b)
% APPENDEVENT
% Copyright (C) 2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: appendevent.m 2885 2011-02-16 09:41:58Z roboos $
if isempty(a)
c = b(:);
elseif isempty(b)
c = a(:);
else
c = a(:);
for i=1:numel(b)
c(end+1).type = b(i).type;
c(end ).value = b(i).value;
c(end ).sample = b(i).sample;
if isfield(b, 'timestamp')
c(end ).timestamp = b(i).timestamp; % optional
end
if isfield(b, 'offset')
c(end ).offset = b(i).offset; % optional
end
if isfield(b, 'duration')
c(end ).duration = b(i).duration; % optional
end
end
end
| {'content_hash': '5d23e6bc8db24693041ef785efa91249', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 77, 'avg_line_length': 31.2, 'alnum_prop': 0.655982905982906, 'repo_name': 'jimmyshen007/NeMo', 'id': 'e6c7c43b7e2d83b49592e1b51977d5d2cfbbe096', 'size': '1404', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mymfiles/spm8/external/fieldtrip/fileio/private/appendevent.m', 'mode': '33261', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '1151672'}, {'name': 'C++', 'bytes': '3310'}, {'name': 'M', 'bytes': '995814'}, {'name': 'Mathematica', 'bytes': '122494'}, {'name': 'Matlab', 'bytes': '5692710'}, {'name': 'Mercury', 'bytes': '2633349'}, {'name': 'Objective-C', 'bytes': '245514'}, {'name': 'Perl', 'bytes': '7850'}, {'name': 'R', 'bytes': '12651'}, {'name': 'Ruby', 'bytes': '15824'}, {'name': 'TeX', 'bytes': '1035980'}]} |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
module Web.Serverless.Internal.Handler where
--------------------------------------------------------------------------------
import Control.Exception.Safe
import Data.Void
import Data.Aeson hiding (Success)
import Data.Aeson.Internal (IResult (..), ifromJSON)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Functor
import GHC.Generics
import Network.HTTP.Types
--------------------------------------------------------------------------------
import Web.Serverless.Internal.SocketApp
import Web.Serverless.Internal.Types
--------------------------------------------------------------------------------
data FailType err
= Fail err
| GotException String
deriving Generic
instance ToJSON err => ToJSON (FailType err) where
toJSON = genericToJSON aesonSettings
data Answer err ret
= Success ret
| Failure (FailType err)
deriving Generic
instance (ToJSON err, ToJSON ret) => ToJSON (Answer err ret) where
toJSON = genericToJSON aesonSettings
--------------------------------------------------------------------------------
data In payload
= InEvent payload
deriving Generic
instance FromJSON a => FromJSON (In a) where
parseJSON = genericParseJSON aesonSettings
data Out err ret
= OutAnswer (Answer err ret)
deriving Generic
instance (ToJSON err, ToJSON ret) => ToJSON (Out err ret) where
toJSON = genericToJSON aesonSettings
--------------------------------------------------------------------------------
run :: Int -> LambdaFunction payload err ret -> IO Void
run port (LambdaFunction fun) = runSocketApp port $ \val ->
try (fun $ Event val (Context ())) >>= \case
Left ex -> return . Failure . GotException $ show (ex :: SomeException)
Right (Left err) -> return . Failure $ Fail err
Right (Right ret) -> return $ Success ret
--------------------------------------------------------------------------------
decodeJSON :: BS.ByteString -> Either String Value
decodeJSON = eitherDecodeStrict
decodeValue :: FromJSON a => Value -> Either String a
decodeValue = resToStr . ifromJSON
where
resToStr :: IResult a -> Either String a
resToStr (ISuccess a) = Right $ a
resToStr err = Left $ show (err $> ())
encodeJSON :: ToJSON a => a -> Value
encodeJSON = toJSON
encodeValue :: Value -> BS.ByteString
encodeValue = BL.toStrict . encode
| {'content_hash': 'a2bbc9ea52cf1c836f77039f70184303', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 80, 'avg_line_length': 32.8375, 'alnum_prop': 0.5550057099352874, 'repo_name': 'utdemir/serverless-hs', 'id': '16bb07cf6b8f42a87aa0c51c95c28f10ddf1d9e4', 'size': '2627', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Web/Serverless/Internal/Handler.hs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Haskell', 'bytes': '31852'}, {'name': 'JavaScript', 'bytes': '4043'}, {'name': 'Makefile', 'bytes': '260'}]} |
<?php
/**
* Created by PhpStorm.
* User: aasiimwe
* Date: 9/25/2015
* Time: 11:55 AM
*/
if (!defined('BASEPATH')) exit('No direct script access allowed');
class SgUserProfile extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
$this->load->library('form_validation');
$this->load->library('email');
$this->load->library('pagination');
}
public function index()
{
$pageName = array('page_name' => 'User Area');
$this->session->set_userdata($pageName);
$data = '';
$this->load->view('header');
$this->load->view('left_nav_menu', $data);
$this->load->view('SgUserProfile/home_view', $data);
$this->load->view('footer');
$this->load->view('footer_close_tags');
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/SgMain.php */ | {'content_hash': '939b9b9926776bc9acd45c4cce58863c', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 66, 'avg_line_length': 22.97826086956522, 'alnum_prop': 0.5600756859035004, 'repo_name': 'aasiimweDataCare/sugarGirls', 'id': 'dc502d191b89b37488787f1a2fa54b80c3c87f38', 'size': '1057', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/controllers/SgUserProfile.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '613'}, {'name': 'CSS', 'bytes': '331402'}, {'name': 'HTML', 'bytes': '511727'}, {'name': 'Java', 'bytes': '99318'}, {'name': 'JavaScript', 'bytes': '1577601'}, {'name': 'PHP', 'bytes': '2453858'}, {'name': 'PLpgSQL', 'bytes': '875'}]} |
package org.jetbrains.git4idea.http;
import org.apache.xmlrpc.XmlRpcClientLite;
import org.apache.xmlrpc.XmlRpcException;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Vector;
/**
* Calls {@link GitAskPassXmlRpcHandler} methods via XML RPC.
*
* @author Kirill Likhodedov
*/
class GitAskPassXmlRpcClient {
@NotNull private final XmlRpcClientLite myClient;
GitAskPassXmlRpcClient(int port) throws MalformedURLException {
myClient = new XmlRpcClientLite("127.0.0.1", port);
}
// Obsolete collection usage because of the XmlRpcClientLite API
@SuppressWarnings({"UseOfObsoleteCollectionType", "unchecked"})
String askUsername(String token, @NotNull String url) {
Vector parameters = new Vector();
parameters.add(token);
parameters.add(url);
try {
return (String)myClient.execute(methodName("askUsername"), parameters);
}
catch (XmlRpcException | IOException e) {
throw new RuntimeException("Invocation failed " + e.getMessage(), e);
}
}
// Obsolete collection usage because of the XmlRpcClientLite API
@SuppressWarnings({"UseOfObsoleteCollectionType", "unchecked"})
String askPassword(String token, @NotNull String url) {
Vector parameters = new Vector();
parameters.add(token);
parameters.add(url);
try {
return (String)myClient.execute(methodName("askPassword"), parameters);
}
catch (XmlRpcException | IOException e) {
throw new RuntimeException("Invocation failed " + e.getMessage(), e);
}
}
@NotNull
private static String methodName(@NotNull String method) {
return GitAskPassXmlRpcHandler.HANDLER_NAME + "." + method;
}
}
| {'content_hash': '7a92773fdae2761f9dc7e1707dbcf79a', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 77, 'avg_line_length': 28.916666666666668, 'alnum_prop': 0.7256484149855907, 'repo_name': 'apixandru/intellij-community', 'id': '79935041361a8782c237a3018027221e4abe096c', 'size': '2335', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'plugins/git4idea/rt/src/org/jetbrains/git4idea/http/GitAskPassXmlRpcClient.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60827'}, {'name': 'C', 'bytes': '213044'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '181491'}, {'name': 'CMake', 'bytes': '1675'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'DTrace', 'bytes': '578'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '3329190'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1906377'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '168701434'}, {'name': 'JavaScript', 'bytes': '570147'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '5190572'}, {'name': 'Lex', 'bytes': '147513'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '51691'}, {'name': 'Objective-C', 'bytes': '27309'}, {'name': 'PHP', 'bytes': '1549'}, {'name': 'Perl', 'bytes': '936'}, {'name': 'Perl 6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6680'}, {'name': 'Python', 'bytes': '25896118'}, {'name': 'Roff', 'bytes': '37534'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Shell', 'bytes': '64132'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]} |
void wasm_##type##_delete(void *native_object); \
void wasm_##type##_finalizer(void *unused, void *native_object) { \
wasm_##type##_delete(native_object); \
} \
DART_EXPORT void set_finalizer_for_##type(Dart_Handle dart_object, \
void *native_object) { \
Dart_NewFinalizableHandle_DL(dart_object, native_object, 0, \
wasm_##type##_finalizer); \
}
FINALIZER(engine);
FINALIZER(store);
FINALIZER(module);
FINALIZER(instance);
FINALIZER(trap);
FINALIZER(memorytype);
FINALIZER(memory);
FINALIZER(func);
FINALIZER(global);
| {'content_hash': 'dfd5ab372c5604057a87568b550395d3', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 80, 'avg_line_length': 43.421052631578945, 'alnum_prop': 0.4581818181818182, 'repo_name': 'dart-lang/wasm', 'id': 'e7c702a6bb86181f10f5763b06a8ea29a067db62', 'size': '1171', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'wasm/bin/finalizers.c', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '1171'}, {'name': 'Dart', 'bytes': '170487'}, {'name': 'Kotlin', 'bytes': '958'}, {'name': 'Perl', 'bytes': '949'}, {'name': 'Python', 'bytes': '14519'}, {'name': 'Raku', 'bytes': '215'}, {'name': 'Rust', 'bytes': '25'}]} |
package com.microsoft.windowsazure.serviceruntime;
import java.math.BigInteger;
import java.util.Calendar;
/**
*
*/
class GoalState {
private final BigInteger incarnation;
private final ExpectedState expectedState;
private final String environmentPath;
private final Calendar deadline;
private final String currentStateEndpoint;
public GoalState(BigInteger incarnation, ExpectedState expectedState,
String environmentPath, Calendar deadline,
String currentStateEndpoint) {
this.incarnation = incarnation;
this.expectedState = expectedState;
this.environmentPath = environmentPath;
this.deadline = deadline;
this.currentStateEndpoint = currentStateEndpoint;
}
public BigInteger getIncarnation() {
return incarnation;
}
public ExpectedState getExpectedState() {
return expectedState;
}
public String getEnvironmentPath() {
return environmentPath;
}
public Calendar getDeadline() {
return deadline;
}
public String getCurrentStateEndpoint() {
return currentStateEndpoint;
}
}
| {'content_hash': 'ef1a9591296c9abfdbf3316bb72a748f', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 73, 'avg_line_length': 25.152173913043477, 'alnum_prop': 0.6966292134831461, 'repo_name': 'jingleheimerschmidt/azure-sdk-for-java', 'id': '813a51b6ff0ded0f1209517bc1c1e02f4c975ef0', 'size': '1798', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'services/azure-serviceruntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '10369'}, {'name': 'Java', 'bytes': '24078302'}]} |
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
items = client.sync \
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.sync_lists("MyCollection") \
.sync_list_items \
.list()
for item in items:
print(item.data)
| {'content_hash': 'ac7c5e94e997e7f8142aff3986b4d143', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 62, 'avg_line_length': 27.0, 'alnum_prop': 0.7283950617283951, 'repo_name': 'teoreteetik/api-snippets', 'id': 'e75e84b92f723ad5c7fe0de9f8039d223506c5da', 'size': '478', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sync/rest/lists/query-list/query-list.6.x.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '643369'}, {'name': 'HTML', 'bytes': '335'}, {'name': 'Java', 'bytes': '943336'}, {'name': 'JavaScript', 'bytes': '539577'}, {'name': 'M', 'bytes': '117'}, {'name': 'Mathematica', 'bytes': '93'}, {'name': 'Objective-C', 'bytes': '46198'}, {'name': 'PHP', 'bytes': '538312'}, {'name': 'Python', 'bytes': '467248'}, {'name': 'Ruby', 'bytes': '470316'}, {'name': 'Shell', 'bytes': '1564'}, {'name': 'Swift', 'bytes': '36563'}]} |
"use strict";
define([
"jquery",
"QUnit",
"pagination.component"
], function($, QUnit, Pagination){
var run = function(){
var pagination;
var $selectedLi;
QUnit.module( "pagination initialization", {
beforeEach: function() {
pagination = new Pagination(".pagination");
$selectedLi = pagination.selectedLi;
}
});
QUnit.test("_addSelectedToCurrentIndex() : 선택한 페이지 인덱스에 selected 클래스 추가", function(assert) {
//Given : 현재 1페이지
var $targetLi = pagination.pagination.children("li").eq(2);
//When
pagination._addSelectedToCurrentIndex({
target : $targetLi.children("a").eq(0)
});
//Then
assert.ok($targetLi.hasClass("selected"));
});
QUnit.test("_checkIfArrowShouldBeDisabled() : 1페이지에서 < disable", function(assert) {
//Given
var selectedIndex = 1;
var $prevArrow = pagination.prevArrow;
//When
pagination._checkIfArrowShouldBeDisabled(selectedIndex);
//Then
assert.ok($prevArrow.hasClass("disabled"));
});
QUnit.test("_checkIfArrowShouldBeDisabled() : 5페이지에서 > disable", function(assert) {
//Given
var selectedIndex = 5;
var $nextArrow = pagination.nextArrow;
//When
pagination._checkIfArrowShouldBeDisabled(selectedIndex);
//Then
assert.ok($nextArrow.hasClass("disabled"));
});
};
return {
run : run
}
});
| {'content_hash': '26a2135e50adbc367ea67301e1727e20', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 96, 'avg_line_length': 28.46, 'alnum_prop': 0.6191145467322557, 'repo_name': 'fairesy/pagination-component', 'id': 'f69e007dda29112d0b91fbdf7f9b436a7681aaa5', 'size': '1483', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/pagination.test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2453'}, {'name': 'HTML', 'bytes': '1404'}, {'name': 'JavaScript', 'bytes': '11149'}]} |
'use strict';
const cleanBaseURL = require('clean-base-url');
const existsSync = require('exists-sync');
const path = require('path');
const fs = require('fs');
const logger = require('heimdalljs-logger')('ember-cli:test-server');
class TestsServerAddon {
/**
* This addon is used to serve the QUnit or Mocha test runner
* at `baseURL + '/tests'`.
*
* @class TestsServerAddon
* @constructor
*/
constructor(project) {
this.project = project;
this.name = 'tests-server-middleware';
}
serverMiddleware(config) {
let app = config.app;
let options = config.options;
let watcher = options.watcher;
let baseURL = options.rootURL === '' ? '/' : cleanBaseURL(options.rootURL || options.baseURL);
let testsPath = `${baseURL}tests`;
app.use((req, res, next) => {
watcher.then(results => {
let acceptHeaders = req.headers.accept || [];
let hasHTMLHeader = acceptHeaders.indexOf('text/html') !== -1;
let hasWildcardHeader = acceptHeaders.indexOf('*/*') !== -1;
let isForTests = req.path.indexOf(testsPath) === 0;
logger.info('isForTests: %o', isForTests);
if (isForTests && (hasHTMLHeader || hasWildcardHeader) && req.method === 'GET') {
let assetPath = req.path.slice(baseURL.length);
let filePath = path.join(results.directory, assetPath);
if (!existsSync(filePath) || !fs.statSync(filePath).isFile()) {
// N.B., `baseURL` will end with a slash as it went through `cleanBaseURL`
let newURL = `${baseURL}tests/index.html`;
logger.info('url: %s resolved to path: %s which is not a file. Assuming %s instead', req.path, filePath, newURL);
req.url = newURL;
}
}
}).finally(next).finally(() => {
if (config.finally) {
config.finally();
}
});
});
}
}
module.exports = TestsServerAddon;
| {'content_hash': '2f997dc2d576066aaebe219d5b3aa8ce', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 125, 'avg_line_length': 31.177419354838708, 'alnum_prop': 0.6032074495602691, 'repo_name': 'sivakumar-kailasam/ember-cli', 'id': '785a4234dea2831999dba618354703909ca4c0bc', 'size': '1933', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'lib/tasks/server/middleware/tests-server/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '3959'}, {'name': 'JavaScript', 'bytes': '1166583'}, {'name': 'PowerShell', 'bytes': '604'}, {'name': 'Ruby', 'bytes': '358'}, {'name': 'Shell', 'bytes': '2442'}]} |
package org.andengine.opengl.vbo;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.andengine.opengl.shader.ShaderProgram;
import org.andengine.opengl.util.BufferUtils;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes;
import org.andengine.util.adt.DataConstants;
import android.opengl.GLES20;
/**
* Compared to a {@link HighPerformanceVertexBufferObject} or a {@link LowMemoryVertexBufferObject}, the {@link ZeroMemoryVertexBufferObject} uses <b><u>no</u> permanent heap memory</b>,
* at the cost of expensive data buffering (<b>up to <u>5x</u> slower!</b>) whenever the bufferdata needs to be updated and higher GC activity, due to the temporary {@link ByteBuffer} allocations.
* <p/>
* Usually a {@link ZeroMemoryVertexBufferObject} is preferred to a {@link HighPerformanceVertexBufferObject} or a {@link LowMemoryVertexBufferObject} when the following conditions are met:
* <ol>
* <li>The application is close to run out of memory.</li>
* <li>You have very big {@link HighPerformanceVertexBufferObject}/{@link LowMemoryVertexBufferObject} or an extreme number of small {@link HighPerformanceVertexBufferObject}/{@link LowMemoryVertexBufferObject}s, where you can't afford to have any of the bufferdata to be kept in heap memory.</li>
* <li>The content (color, vertices, texturecoordinates) of the {@link ZeroMemoryVertexBufferObject} is changed not often, or even better: never.</li>
* </ol>
* <p/>
* (c) Zynga 2011
*
* @author Nicolas Gramlich <[email protected]>
* @author Greg Haynes
* @since 19:03:32 - 10.02.2012
*/
public abstract class ZeroMemoryVertexBufferObject implements IVertexBufferObject {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final int mCapacity;
protected final boolean mAutoDispose;
protected final int mUsage;
protected int mHardwareBufferID = IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID;
protected boolean mDirtyOnHardware = true;
protected boolean mDisposed;
protected final VertexBufferObjectManager mVertexBufferObjectManager;
protected final VertexBufferObjectAttributes mVertexBufferObjectAttributes;
// ===========================================================
// Constructors
// ===========================================================
public ZeroMemoryVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) {
this.mVertexBufferObjectManager = pVertexBufferObjectManager;
this.mCapacity = pCapacity;
this.mUsage = pDrawType.getUsage();
this.mAutoDispose = pAutoDispose;
this.mVertexBufferObjectAttributes = pVertexBufferObjectAttributes;
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public VertexBufferObjectManager getVertexBufferObjectManager() {
return this.mVertexBufferObjectManager;
}
@Override
public boolean isDisposed() {
return this.mDisposed;
}
@Override
public boolean isAutoDispose() {
return this.mAutoDispose;
}
@Override
public int getHardwareBufferID() {
return this.mHardwareBufferID;
}
@Override
public boolean isLoadedToHardware() {
return this.mHardwareBufferID != IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID;
}
@Override
public void setNotLoadedToHardware() {
this.mHardwareBufferID = IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID;
this.mDirtyOnHardware = true;
}
@Override
public boolean isDirtyOnHardware() {
return this.mDirtyOnHardware;
}
@Override
public void setDirtyOnHardware() {
this.mDirtyOnHardware = true;
}
@Override
public int getCapacity() {
return this.mCapacity;
}
@Override
public int getByteCapacity() {
return this.mCapacity * DataConstants.BYTES_PER_FLOAT;
}
@Override
public int getHeapMemoryByteSize() {
return 0;
}
@Override
public int getNativeHeapMemoryByteSize() {
return 0;
}
@Override
public int getGPUMemoryByteSize() {
if(this.isLoadedToHardware()) {
return this.getByteCapacity();
} else {
return 0;
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onPopulateBufferData(final ByteBuffer byteBuffer);
@Override
public void bind(final GLState pGLState) {
if(this.mHardwareBufferID == IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID) {
this.loadToHardware(pGLState);
this.mVertexBufferObjectManager.onVertexBufferObjectLoaded(this);
}
pGLState.bindArrayBuffer(this.mHardwareBufferID);
if(this.mDirtyOnHardware) {
ByteBuffer byteBuffer = null;
try {
byteBuffer = this.aquireByteBuffer();
this.onPopulateBufferData(byteBuffer);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, byteBuffer.limit(), byteBuffer, this.mUsage);
} finally {
if(byteBuffer != null) {
this.releaseByteBuffer(byteBuffer);
}
}
this.mDirtyOnHardware = false;
}
}
@Override
public void bind(final GLState pGLState, final ShaderProgram pShaderProgram) {
this.bind(pGLState);
pShaderProgram.bind(pGLState, this.mVertexBufferObjectAttributes);
}
@Override
public void unbind(final GLState pGLState, final ShaderProgram pShaderProgram) {
pShaderProgram.unbind(pGLState);
// pGLState.bindBuffer(0); // TODO Does this have an positive/negative impact on performance?
}
@Override
public void unloadFromHardware(final GLState pGLState) {
pGLState.deleteArrayBuffer(this.mHardwareBufferID);
this.mHardwareBufferID = IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID;
}
@Override
public void draw(final int pPrimitiveType, final int pCount) {
GLES20.glDrawArrays(pPrimitiveType, 0, pCount);
}
@Override
public void draw(final int pPrimitiveType, final int pOffset, final int pCount) {
GLES20.glDrawArrays(pPrimitiveType, pOffset, pCount);
}
@Override
public void dispose() {
if(!this.mDisposed) {
this.mDisposed = true;
this.mVertexBufferObjectManager.onUnloadVertexBufferObject(this);
} else {
throw new AlreadyDisposedException();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if(!this.mDisposed) {
this.dispose();
}
}
// ===========================================================
// Methods
// ===========================================================
private void loadToHardware(final GLState pGLState) {
this.mHardwareBufferID = pGLState.generateBuffer();
this.mDirtyOnHardware = true;
}
/**
* When a non <code>null</code> {@link ByteBuffer} is returned by this function, it is guaranteed that {@link ZeroMemoryVertexBufferObject#releaseByteBuffer(ByteBuffer)} is called.
* @return a {@link ByteBuffer} to be passed to {@link ZeroMemoryVertexBufferObject#onPopulateBufferData(ByteBuffer)}.
*/
protected ByteBuffer aquireByteBuffer() {
final ByteBuffer byteBuffer = BufferUtils.allocateDirectByteBuffer(this.getByteCapacity());
byteBuffer.order(ByteOrder.nativeOrder());
return byteBuffer;
}
protected void releaseByteBuffer(final ByteBuffer byteBuffer) {
BufferUtils.freeDirectByteBuffer(byteBuffer);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| {'content_hash': '932567850ea934a0e67868589f9f960e', 'timestamp': '', 'source': 'github', 'line_count': 248, 'max_line_length': 297, 'avg_line_length': 31.169354838709676, 'alnum_prop': 0.680595084087969, 'repo_name': 'yudhir/AndEngine', 'id': '3617267c71041a12adbaf00c7c5777b39bc28966', 'size': '7730', 'binary': False, 'copies': '38', 'ref': 'refs/heads/GLES2', 'path': 'src/org/andengine/opengl/vbo/ZeroMemoryVertexBufferObject.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1189'}, {'name': 'C++', 'bytes': '1159'}, {'name': 'Java', 'bytes': '2296149'}, {'name': 'Makefile', 'bytes': '499'}, {'name': 'Shell', 'bytes': '3493'}]} |
// ADTF header
#include <adtf_platform_inc.h>
#include <adtf_plugin_sdk.h>
using namespace adtf;
#include <adtf_graphics.h>
using namespace adtf_graphics;
// opencv header
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
#endif // __STD_INCLUDES_HEADER
| {'content_hash': '488764370558f5d0c1564521cd25e06b', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 38, 'avg_line_length': 20.41176470588235, 'alnum_prop': 0.7089337175792507, 'repo_name': 'AADC-Fruit/AADC_2015_FRUIT', 'id': '2f2251301fac42ac38f710787656d2aa61d35847', 'size': '409', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'AADC/src/adtfUser/dev/src/objectMergeFilter/stdafx.h', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Apex', 'bytes': '5619'}, {'name': 'Batchfile', 'bytes': '4242'}, {'name': 'C', 'bytes': '34545'}, {'name': 'C++', 'bytes': '3324319'}, {'name': 'CMake', 'bytes': '187891'}, {'name': 'CSS', 'bytes': '33023'}, {'name': 'Gnuplot', 'bytes': '423'}, {'name': 'HTML', 'bytes': '25123155'}, {'name': 'JavaScript', 'bytes': '520130'}, {'name': 'Makefile', 'bytes': '207'}, {'name': 'R', 'bytes': '553'}, {'name': 'Shell', 'bytes': '10599'}, {'name': 'TeX', 'bytes': '58099'}]} |
namespace Iyzipay.Request.V2.Subscription
{
public class RetrieveProductRequest : BaseRequestV2
{
public string ProductReferenceCode { get; set; }
}
} | {'content_hash': 'bb70406ef1950db84e4d5aa18d5276fc', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 56, 'avg_line_length': 24.285714285714285, 'alnum_prop': 0.711764705882353, 'repo_name': 'iyzico/iyzipay-dotnet', 'id': '2c664ac62fc86b8f9a6826ab74ca1bef1e2fa1fa', 'size': '170', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Iyzipay/Request/V2/Subscription/RetrieveProductRequest.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '470'}, {'name': 'C#', 'bytes': '455820'}, {'name': 'Shell', 'bytes': '838'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_11) on Mon Jul 12 21:36:38 CEST 2010 -->
<TITLE>
Uses of Class org.apache.fop.render.mif.RefElement (Apache FOP 1.0 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.apache.fop.render.mif.RefElement (Apache FOP 1.0 API)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/mif/RefElement.html" title="class in org.apache.fop.render.mif"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.0</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="RefElement.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.fop.render.mif.RefElement</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/fop/render/mif/RefElement.html" title="class in org.apache.fop.render.mif">RefElement</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.mif"><B>org.apache.fop.render.mif</B></A></TD>
<TD>MIF Output Support </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.mif"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/render/mif/RefElement.html" title="class in org.apache.fop.render.mif">RefElement</A> in <A HREF="../../../../../../org/apache/fop/render/mif/package-summary.html">org.apache.fop.render.mif</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Subclasses of <A HREF="../../../../../../org/apache/fop/render/mif/RefElement.html" title="class in org.apache.fop.render.mif">RefElement</A> in <A HREF="../../../../../../org/apache/fop/render/mif/package-summary.html">org.apache.fop.render.mif</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/mif/PGFElement.html" title="class in org.apache.fop.render.mif">PGFElement</A></B></CODE>
<BR>
Font Catalog element.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/mif/RulingElement.html" title="class in org.apache.fop.render.mif">RulingElement</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/render/mif/RefElement.html" title="class in org.apache.fop.render.mif"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.0</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="RefElement.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| {'content_hash': 'd83dfed7b15d976f4ad641a5870ce5fb', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 275, 'avg_line_length': 44.227777777777774, 'alnum_prop': 0.6170079135786961, 'repo_name': 'kezhong/XML', 'id': '348114657049a90911b0948eaa433fb8a70f5f26', 'size': '7961', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'javadocs/org/apache/fop/render/mif/class-use/RefElement.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '28133'}, {'name': 'PHP', 'bytes': '1069'}, {'name': 'Shell', 'bytes': '7531'}]} |
const { toBeEqualWithTolerance } = require('./matchers/toBeEqualWithTolerance');
const { toEqualArray } = require('./matchers/toEqualArray');
expect.extend({
toBeEqualWithTolerance,
toEqualArray
});
| {'content_hash': '9488894fbb7d03449665be33ce320196', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 80, 'avg_line_length': 29.714285714285715, 'alnum_prop': 0.7403846153846154, 'repo_name': 'ColinEberhardt/d3fc', 'id': 'aaa4c429217e9dfa35ce289fc5d807f5c3deb560', 'size': '208', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'scripts/jest/setup.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '39980'}, {'name': 'JavaScript', 'bytes': '6536'}, {'name': 'Shell', 'bytes': '877'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template icase</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../xpressive/reference.html#header.boost.xpressive.regex_primitives_hpp" title="Header <boost/xpressive/regex_primitives.hpp>">
<link rel="prev" href="a9.html" title="Global a9">
<link rel="next" href="as_xpr.html" title="Function template as_xpr">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="a9.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../xpressive/reference.html#header.boost.xpressive.regex_primitives_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="as_xpr.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.xpressive.icase"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template icase</span></h2>
<p>boost::xpressive::icase — Makes a sub-expression case-insensitive. </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../xpressive/reference.html#header.boost.xpressive.regex_primitives_hpp" title="Header <boost/xpressive/regex_primitives.hpp>">boost/xpressive/regex_primitives.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> <a class="link" href="../../Expr.html" title="Concept Expr">Expr</a><span class="special">></span> <span class="emphasis"><em><span class="identifier">unspecified</span></em></span> <span class="identifier">icase</span><span class="special">(</span><span class="identifier">Expr</span> <span class="keyword">const</span> <span class="special">&</span> expr<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idm45555017080192"></a><h2>Description</h2>
<p>Use icase() to make a sub-expression case-insensitive. For instance, "foo" >> icase(set['b'] >> "ar") will match "foo" exactly followed by "bar" irrespective of case. </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="a9.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../xpressive/reference.html#header.boost.xpressive.regex_primitives_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="as_xpr.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {'content_hash': '1801c7662c147291019f46a374ff8ea1', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 543, 'avg_line_length': 80.41818181818182, 'alnum_prop': 0.6656115758534931, 'repo_name': 'zjutjsj1004/third', 'id': '0e182cb54b0f7262527559b797fc1522a508a751', 'size': '4423', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'boost/doc/html/boost/xpressive/icase.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '224158'}, {'name': 'Batchfile', 'bytes': '33175'}, {'name': 'C', 'bytes': '5576593'}, {'name': 'C#', 'bytes': '41850'}, {'name': 'C++', 'bytes': '179595990'}, {'name': 'CMake', 'bytes': '28348'}, {'name': 'CSS', 'bytes': '331303'}, {'name': 'Cuda', 'bytes': '26521'}, {'name': 'FORTRAN', 'bytes': '1856'}, {'name': 'Groff', 'bytes': '1305458'}, {'name': 'HTML', 'bytes': '159660377'}, {'name': 'IDL', 'bytes': '15'}, {'name': 'JavaScript', 'bytes': '285786'}, {'name': 'Lex', 'bytes': '1290'}, {'name': 'Makefile', 'bytes': '1202020'}, {'name': 'Max', 'bytes': '37424'}, {'name': 'Objective-C', 'bytes': '3674'}, {'name': 'Objective-C++', 'bytes': '651'}, {'name': 'PHP', 'bytes': '60249'}, {'name': 'Perl', 'bytes': '37297'}, {'name': 'Perl6', 'bytes': '2130'}, {'name': 'Python', 'bytes': '1833677'}, {'name': 'QML', 'bytes': '613'}, {'name': 'QMake', 'bytes': '17385'}, {'name': 'Rebol', 'bytes': '372'}, {'name': 'Shell', 'bytes': '1144162'}, {'name': 'Tcl', 'bytes': '1205'}, {'name': 'TeX', 'bytes': '38313'}, {'name': 'XSLT', 'bytes': '564356'}, {'name': 'Yacc', 'bytes': '20341'}]} |
package com.cezarykluczynski.stapi.etl.template.episode.dto;
import com.cezarykluczynski.stapi.etl.template.common.dto.ImageTemplate;
import com.cezarykluczynski.stapi.model.episode.entity.Episode;
import com.cezarykluczynski.stapi.model.page.entity.Page;
import com.cezarykluczynski.stapi.model.season.entity.Season;
import com.cezarykluczynski.stapi.model.series.entity.Series;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
@Data
@EqualsAndHashCode(callSuper = true)
public class EpisodeTemplate extends ImageTemplate {
private Page page;
private Series series;
private Season season;
private Episode episodeStub;
private String title;
private String titleGerman;
private String titleItalian;
private String titleJapanese;
private Integer seasonNumber;
private Integer episodeNumber;
private String productionSerialNumber;
private Boolean featureLength;
private LocalDate usAirDate;
private LocalDate finalScriptDate;
}
| {'content_hash': '9281bdd0c95d53fc6ec43b3e52b42bb9', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 72, 'avg_line_length': 21.977777777777778, 'alnum_prop': 0.8240647118301314, 'repo_name': 'cezarykluczynski/stapi', 'id': '7a39c3deceee3a2650b09501a34fc2832b415d9b', 'size': '989', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'etl/src/main/java/com/cezarykluczynski/stapi/etl/template/episode/dto/EpisodeTemplate.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Groovy', 'bytes': '4357719'}, {'name': 'HTML', 'bytes': '31512'}, {'name': 'Java', 'bytes': '3370461'}, {'name': 'JavaScript', 'bytes': '5771'}, {'name': 'Sass', 'bytes': '3577'}, {'name': 'TypeScript', 'bytes': '138102'}]} |
cask 'font-noto-sans-bengali' do
version :latest
sha256 :no_check
# noto-website-2.storage.googleapis.com was verified as official when first introduced to the cask
url 'https://noto-website-2.storage.googleapis.com/pkgs/NotoSansBengali-unhinted.zip'
name 'Noto Sans Bengali'
homepage 'https://www.google.com/get/noto/#sans-beng'
font 'NotoSansBengali-Black.ttf'
font 'NotoSansBengali-Bold.ttf'
font 'NotoSansBengali-ExtraBold.ttf'
font 'NotoSansBengali-ExtraLight.ttf'
font 'NotoSansBengali-Light.ttf'
font 'NotoSansBengali-Medium.ttf'
font 'NotoSansBengali-Regular.ttf'
font 'NotoSansBengali-SemiBold.ttf'
font 'NotoSansBengali-Thin.ttf'
font 'NotoSansBengaliUI-Black.ttf'
font 'NotoSansBengaliUI-Bold.ttf'
font 'NotoSansBengaliUI-ExtraBold.ttf'
font 'NotoSansBengaliUI-ExtraLight.ttf'
font 'NotoSansBengaliUI-Light.ttf'
font 'NotoSansBengaliUI-Medium.ttf'
font 'NotoSansBengaliUI-Regular.ttf'
font 'NotoSansBengaliUI-SemiBold.ttf'
font 'NotoSansBengaliUI-Thin.ttf'
end
| {'content_hash': 'f0395a9716e55c16a641f0dedd553feb', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 100, 'avg_line_length': 36.5, 'alnum_prop': 0.776908023483366, 'repo_name': 'unasuke/homebrew-fonts', 'id': '60d8b2eeabcbd93daef80257a93f1d0cd32bdb40', 'size': '1022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Casks/font-noto-sans-bengali.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Ruby', 'bytes': '644287'}]} |
<card [verticalMode]="hasChild" [title]="'Document List'" (reset)="onReset()" (close)="close()" (closeChild)="closeChild()" [(showAll)]="isShowAll">
<form>
<sml-abstract-metadata-list [model]="model" [config]="config" [isShowAll]="isShowAll"></sml-abstract-metadata-list>
<div class="form-group" *ngIf="isShowAll || config.isFieldVisible('sml:document')">
<label for="documents">{{getDisplayName('documents')}}</label>
<list [list]="model.documents" (select)="openNewOnlineResourceItem($event)" (remove)="onRemove($event)" (add)="onAdd()"></list>
</div>
</form>
</card>
| {'content_hash': '38409cd241e1acfd03b3aa46fe002548', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 148, 'avg_line_length': 66.44444444444444, 'alnum_prop': 0.6605351170568562, 'repo_name': 'janschulte/smle', 'id': 'b475ba889e26670e1cedf811c9f846cd2083c430', 'size': '598', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/editor/components/sml/DocumentListComponent.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '6887'}, {'name': 'HTML', 'bytes': '85751'}, {'name': 'JavaScript', 'bytes': '44122'}, {'name': 'Shell', 'bytes': '989'}, {'name': 'TypeScript', 'bytes': '538029'}]} |
#include "subStructFileGet.h"
#include "miscServerFunct.hpp"
#include "dataObjOpr.hpp"
// =-=-=-=-=-=-=-
#include "irods_structured_object.hpp"
#include "irods_error.hpp"
#include "irods_stacktrace.hpp"
int
rsSubStructFileGet( rsComm_t *rsComm, subFile_t *subFile,
bytesBuf_t *subFileGetOutBBuf ) {
rodsServerHost_t *rodsServerHost;
int remoteFlag;
int status;
remoteFlag = resolveHost( &subFile->addr, &rodsServerHost );
if ( remoteFlag == LOCAL_HOST ) {
status = _rsSubStructFileGet( rsComm, subFile, subFileGetOutBBuf );
}
else if ( remoteFlag == REMOTE_HOST ) {
status = remoteSubStructFileGet( rsComm, subFile, subFileGetOutBBuf,
rodsServerHost );
}
else {
if ( remoteFlag < 0 ) {
return remoteFlag;
}
else {
rodsLog( LOG_NOTICE,
"rsSubStructFileGet: resolveHost returned unrecognized value %d",
remoteFlag );
return SYS_UNRECOGNIZED_REMOTE_FLAG;
}
}
return status;
}
int
remoteSubStructFileGet( rsComm_t *rsComm, subFile_t *subFile,
bytesBuf_t *subFileGetOutBBuf, rodsServerHost_t *rodsServerHost ) {
int status;
if ( rodsServerHost == NULL ) {
rodsLog( LOG_NOTICE,
"remoteSubStructFileGet: Invalid rodsServerHost" );
return SYS_INVALID_SERVER_HOST;
}
if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) {
return status;
}
status = rcSubStructFileGet( rodsServerHost->conn, subFile,
subFileGetOutBBuf );
if ( status < 0 ) {
rodsLog( LOG_NOTICE,
"remoteSubStructFileGet: rcSubStructFileGet failed for %s, status = %d",
subFile->subFilePath, status );
}
return status;
}
int _rsSubStructFileGet( rsComm_t* _comm,
subFile_t* _sub_file,
bytesBuf_t* _out_buf ) {
// =-=-=-=-=-=-=-
// convert subfile to a first class object
irods::structured_object_ptr struct_obj(
new irods::structured_object(
*_sub_file ) );
struct_obj->comm( _comm );
struct_obj->resc_hier( _sub_file->specColl->rescHier );
if ( _sub_file->offset <= 0 ) {
irods::log( ERROR( SYS_INVALID_INPUT_PARAM, "invalid length" ) );
return -1;
}
// =-=-=-=-=-=-=-
// open the structured object
irods::error open_err = fileOpen( _comm, struct_obj );
if ( !open_err.ok() ) {
std::stringstream msg;
msg << "fileOpen error for [";
msg << struct_obj->sub_file_path();
msg << "], status = ";
msg << open_err.code();
irods::log( PASSMSG( msg.str(), open_err ) );
return open_err.code();
}
// =-=-=-=-=-=-=-
// allocte outgoing buffer if necessary
if ( _out_buf->buf == NULL ) {
_out_buf->buf = new unsigned char[ _sub_file->offset ];
}
// =-=-=-=-=-=-=-
// read structured file
irods::error read_err = fileRead( _comm, struct_obj, _out_buf->buf, _sub_file->offset );
int status = read_err.code();
if ( !read_err.ok() ) {
if ( status >= 0 ) {
std::stringstream msg;
msg << "failed in fileRead for [";
msg << struct_obj->sub_file_path();
msg << ", toread ";
msg << _sub_file->offset;
msg << ", read ";
msg << read_err.code();
irods::log( PASSMSG( msg.str(), read_err ) );
status = SYS_COPY_LEN_ERR;
}
else {
std::stringstream msg;
msg << "failed in fileRead for [";
msg << struct_obj->sub_file_path();
msg << ", status = ";
msg << read_err.code();
irods::log( PASSMSG( msg.str(), read_err ) );
status = read_err.code();
}
}
else {
_out_buf->len = read_err.code();
}
// =-=-=-=-=-=-=-
// ok, done with that. close the file.
irods::error close_err = fileClose( _comm, struct_obj );
if ( !close_err.ok() ) {
std::stringstream msg;
msg << "failed in fileClose for [";
msg << struct_obj->sub_file_path();
msg << ", status = ";
msg << close_err.code();
irods::log( PASSMSG( msg.str(), read_err ) );
}
return status;
}
| {'content_hash': 'e0cbaf62ec496b01b30a926609bf1b7b', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 92, 'avg_line_length': 28.98701298701299, 'alnum_prop': 0.5199372759856631, 'repo_name': 'PaulVanSchayck/irods', 'id': '8be9b1464106624584f075f33ff6f7c3a2c298fa', 'size': '4631', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'iRODS/server/api/src/rsSubStructFileGet.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '438371'}, {'name': 'C++', 'bytes': '8158805'}, {'name': 'CMake', 'bytes': '854'}, {'name': 'CSS', 'bytes': '3246'}, {'name': 'FORTRAN', 'bytes': '6804'}, {'name': 'HTML', 'bytes': '27675'}, {'name': 'JavaScript', 'bytes': '5231'}, {'name': 'Lex', 'bytes': '3088'}, {'name': 'Makefile', 'bytes': '75587'}, {'name': 'Objective-C', 'bytes': '1160'}, {'name': 'PLSQL', 'bytes': '3241'}, {'name': 'Pascal', 'bytes': '20991'}, {'name': 'Perl', 'bytes': '281394'}, {'name': 'Python', 'bytes': '779176'}, {'name': 'R', 'bytes': '10664'}, {'name': 'Rebol', 'bytes': '159165'}, {'name': 'Ruby', 'bytes': '5914'}, {'name': 'Shell', 'bytes': '205324'}, {'name': 'Yacc', 'bytes': '17441'}]} |
#pragma once
#include <string>
#include <map>
#include "Manager.h"
#include "Notification.h"
#include "Options.h"
#include "Driver.h"
#include "Node.h"
#include "Group.h"
#include "platform/Log.h"
namespace upm {
/**
* @brief UPM OpenZWave library
* @defgroup ozw libupm-ozw
* @ingroup uart wifi
*/
/**
* @library ozw
* @sensor ozw
* @comname Wrapper for the OpenZWave Library
* @type wifi
* @man other
* @con uart
* @web http://www.openzwave.com/
*
* @brief UPM API for the OpenZWave library
*
* This module implements a singleton wrapper around the OpenZWave
* library. OpenZWave must be compiled and installed on your
* machine in order to use this library.
*
* This module was developed with OpenZWave 1.3/1.4, and an Aeon
* Z-Stick Gen5 configured as a Primary Controller. It provides the
* ability to query and set various values that can be used to
* control ZWave devices. It does not concern itself with
* configuration of devices. It is assumed that you have already
* setup your ZWave network using a tool like the OpenZWave control
* panel, and have already configured your devices as appropriate.
*
* To avoid exposing some of the internals of OpenZWave, devices
* (nodes) and their values, are accessed via a nodeId and a value
* index number. The ozwdump example will run dumpNodes() which
* will list the currently connected devices and the values that are
* available to them, along with an index number for that value. It
* is through these values (nodeId and index) that you can query and
* set device values at a low level.
*
* In addition to querying values from a device (such as state
* (on/off), or temperature, etc), methods are provided to allow you
* to control these devices to the extent they allow, for example,
* using a ZWave connected switch to turn on a lamp.
*
* Access to this class by OZW drivers is handled by the
* ozwInterface class. It is that class that drivers use for access
* to ozw, and therefore the Z-Wave network.
*
* This class is not intended to be used directly by end users.
* When writing an OZW driver, the ozwInterface class should be used
* (inherited) by your driver, and your driver should wrap and
* expose only those methods needed by the user. Take a look at
* some of the drivers (like aeotecss6) to see how this works.
*/
// forward declaration of private zwNode data
class zwNode;
class OZW {
public:
typedef std::map<uint8_t, zwNode *> zwNodeMap_t;
/**
* Get our singleton instance, initializing it if neccessary. All
* requests to this class should be done through this instance
* accessor.
*
* @return static pointer to our class instance
*/
static OZW* instance();
/**
* Start configuration with basic options. This must be called
* prior to init(), after the OZW() constructor is called.
*
* @param configPath Set the location of the OpenZWave config
* directory, default is /etc/openzwave
* @param userConfigDir Set the path to the user configuration
* directory. This is the location of the zwcfg*.xml and
* option.xml files for the user (probably created by the
* OpenZWave Control Panel example application). The default is
* the current directory ("").
* @param cmdLine Specify command line formatted options to
* OpenZWave. The default is "".
*/
void optionsCreate(std::string configPath="/etc/openzwave",
std::string userConfigDir="",
std::string cmdLine="");
/**
* Add an integer Option. See the OpenZWave documentation for
* valid values.
*
* @param name The name of the configuration option
* @param val The value to set it to
*/
void optionAddInt(std::string name, int val);
/**
* Add a boolean Option. See the OpenZWave documentation for
* valid values.
*
* @param name The name of the configuration option
* @param val The value to set it to
*/
void optionAddBool(std::string name, bool val);
/**
* Add a string Option. See the OpenZWave documentation for valid
* values.
*
* @param name The name of the configuration option
* @param val The value to set it to
* @append true to append to the option, false to override
*/
void optionAddString(std::string name, std::string val, bool append);
/**
* Lock the Options. This must be called after all options have
* been set, and before init() is called. If init() is called
* without locking the Options, init() will lock them itself.
* After the options have been locked, no further options can be
* specified.
*/
void optionsLock();
/**
* Initialize the ZWave network. This method will start a probe
* of all defined devices on the ZWave network and query essential
* information about them. This function will not return until
* either initialization has failed, or has succeeded far enough
* along for the following methods to work. Depending on the size
* an complexity of the ZWave network, this may take anywhere from
* seconds to several minutes to complete.
*
* All Options (via option*()) must have been specified before
* this function is called. If the Options have not been locked
* via optionsLock() prior to calling init(), this method will
* lock them for you before proceeding.
*
* @param devicePath The device path for the ZWave controller,
* typically something like /dev/ttyACM0, or similiar
* @param isHID true if this is a HID device, false otherwise (ie:
* a serial port like /dev/ttyACM0, /dev/ttyUSB0, etc). Default
* is false.
* @return true if init succeeded, false otherwise
*/
bool init(std::string devicePath, bool isHID=false);
/**
* Dump information about all configured nodes (devices) and their
* available values to stdout. This is useful to determine what
* nodes are available, and the index (used for querying and
* seting values for them). In addition, it includes information
* about each value (type, current value, etc).
*
* @param all set to true to dump information about all values
* available for each node. If false, only information about
* 'user' values (ignoring 'system' and 'configuration') are
* output. The default is false ('user' values only).
*/
void dumpNodes(bool all=false);
/**
* Return a string (which may be empty) indicating the Units of
* measure for a given value. For example, querying a temperature
* value may return "F" to indicate Fahrenheit.
*
* @param nodeId The node ID to query
* @param index The value index (see dumpNodes()) of the value to query.
* @return A string containing the Unit of measure for the value
*/
std::string getValueUnits(int nodeId, int index);
/**
* Set the text for the Units of measure for a value.
*
* @param nodeId The node ID to query
* @param index The value index (see dumpNodes()) of the value to query.
* @param text The text to set
*/
void setValueUnits(int nodeId, int index, std::string text);
/**
* Return a string (which may be empty) containing the
* user-freindly Label for a value.
*
* @param nodeId The node ID to query
* @param index The value index (see dumpNodes()) of the value to query.
* @return A string containing the Value's label
*/
std::string getValueLabel(int nodeId, int index);
/**
* Set the text for a Value's label.
*
* @param nodeId The node ID to query
* @param index The value index (see dumpNodes()) of the value to query.
* @param text The text to set
*/
void setValueLabel(int nodeId, int index, std::string text);
/**
* Return a string (which may be empty) indicating the Help text
* of a value, if available.
*
* @param nodeId The node ID to query
* @param index The value index (see dumpNodes()) of the value to query.
* @return A string containing the Help text, if available
*/
std::string getValueHelp(int nodeId, int index);
/**
* Set the text for a Value's help text.
*
* @param nodeId The node ID to query
* @param index The value index (see dumpNodes()) of the value to query.
* @param text The text to set
*/
void setValueHelp(int nodeId, int index, std::string text);
/**
* Set the contents of a Value to a string. This should always
* succeed if the supplied content makes sense for a given value,
* regardless of the value's actual type.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the content to assign to the value referenced by
* nodeId, and index.
*/
void setValueAsString(int nodeId, int index, std::string val);
/**
* Set the contents of a Value, to a bool. This will fail, and an
* error message printed if the value type is not a boolean value.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the boolean content to assign to the value referenced
* by nodeId, and index.
*/
void setValueAsBool(int nodeId, int index, bool val);
/**
* Set the contents of a Value, to a byte. This will fail, and an
* error message printed if the value type is not a byte value.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the byte content to assign to the value referenced
* by nodeId, and index.
*/
void setValueAsByte(int nodeId, int index, uint8_t val);
/**
* Set the contents of a Value, to a float. This will fail, and an
* error message printed if the value type is not a float value.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the float content to assign to the value referenced
* by nodeId, and index.
*/
void setValueAsFloat(int nodeId, int index, float val);
/**
* Set the contents of a Value, to a 32 bit integer (int32). This
* will fail, and an error message printed if the value type is
* not an int32.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the int32 content to assign to the value referenced
* by nodeId, and index.
*/
void setValueAsInt32(int nodeId, int index, int32_t val);
/**
* Set the contents of a Value, to a 16 bit integer (int16). This
* will fail, and an error message printed if the value type is
* not an int16.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the int16 content to assign to the value referenced
* by nodeId, and index.
*/
void setValueAsInt16(int nodeId, int index, int16_t val);
/**
* Set the contents of a Value, to an array of bytes. This will
* fail, and an error message printed if the value type is not
* settable as an array of bytes.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param val the byte array content to assign to the value referenced
* by nodeId, and index.
* @param len The length of the byte array
*/
void setValueAsBytes(int nodeId, int index, uint8_t *val, uint8_t len);
/**
* Get the minimum allowed value for a node's Value.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return The minumum allowed value
*/
int getValueMin(int nodeId, int index);
/**
* Get the maximum allowed value for a node's Value.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return The maximum allowed value
*/
int getValueMax(int nodeId, int index);
/**
* Test whether a value is read-only.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return true if the value is read-only, false otherwise
*/
bool isValueReadOnly(int nodeId, int index);
/**
* Test whether a value is write only.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return true if the value is write-only, false otherwise
*/
bool isValueWriteOnly(int nodeId, int index);
/**
* Test whether a value is really set on a node, and not a default
* value chosen by the OpenZWave library.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return true if the value is really set, false if a default value is
* being reported
*/
bool isValueSet(int nodeId, int index);
/**
* Test whether a value is being manually polled by the OpenZWave
* library. Most modern devices are never polled, rather they are
* configured to report changing values to the controller on their
* own at device specific intervals or when appropriate events
* (depending the device) have occurred.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return true if the value is being maually polled, false otherwise
* being reported
*/
bool isValuePolled(int nodeId, int index);
/**
* Return the content of a value as a string. This should always
* succeed, regardless of the actual value type.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return A string representing the current contents of a value.
*/
std::string getValueAsString(int nodeId, int index);
/**
* Return the content of a value as a booleang. This will fail,
* and an error message printed if the value type is not boolean.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return A boolean representing the current contents of a value.
*/
bool getValueAsBool(int nodeId, int index);
/**
* Return the content of a value as a byte. This will fail, and
* an error message printed if the value type is not a byte.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return A byte representing the current contents of a value.
*/
uint8_t getValueAsByte(int nodeId, int index);
/**
* Return the content of a value as a float. This will fail, and
* an error message printed if the value type is not a floating
* point value.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return A float representing the current contents of a value.
*/
float getValueAsFloat(int nodeId, int index);
/**
* Return the content of a value as an int32. This will fail, and
* an error message printed if the value type is not an int32.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return An int32 representing the current contents of a value.
*/
int getValueAsInt32(int nodeId, int index);
/**
* Return the content of a value as an int16. This will fail, and
* an error message printed if the value type is not an int16.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @return An int16 representing the current contents of a value.
*/
int getValueAsInt16(int nodeId, int index);
/**
* Issue a refresh request for a value on a node. OpenZWave will
* query the value and update it's internal state when the device
* responds. Note, this happens asynchronously - it may take some
* time before the current value is reported to OpenZWave by the
* node. If the node is asleep, you may not get a current value
* for some time (or at all, depending on the device). This
* method will return immediately after the request has been
* queued.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
*/
void refreshValue(int nodeId, int index);
/**
* Enable or disable some debugging output. Note, this will not
* affect OpenZWave's own debugging, which is usually set in the
* option.xml file.
*
* @param enable true to enable debugging, false otherwise
*/
void setDebug(bool enable);
/**
* Determine if a node is a listening device -- in other words, the
* node never sleeps.
*
* @param nodeId The node ID
* @return true if the node never sleeps, false otherwise
*/
bool isNodeListeningDevice(int nodeId);
/**
* Determine if a node is a frequent listening device -- in other
* words, if the node is asleep, can it be woken by a beam.
*
* @param nodeId The node ID
* @return true if the node is a frequent listening device, false
* otherwise
*/
bool isNodeFrequentListeningDevice(int nodeId);
/**
* Determine if a node is awake.
*
* @param nodeId The node ID
* @return true if the node is awake, false otherwise
*/
bool isNodeAwake(int nodeId);
/**
* Determine whether a Node's information has been received. For
* sleeping nodes, this may take a while (until the node wakes).
*
* @param nodeId The node ID
* @return true if the node information is known, false otherwise
*/
bool isNodeInfoReceived(int nodeId);
/**
* Determine if the Z-Wave network has been initialized yet.
*
* @return true if the network is initialized, false otherwise
*/
bool isInitialized()
{
return m_initialized;
}
protected:
/**
* OZW constructor
*/
OZW();
/**
* OZW Destructor
*/
~OZW();
/**
* Based on a nodeId and a value index, lookup the corresponding
* OpenZWave ValueID.
*
* @param nodeId The node ID
* @param index The value index (see dumpNodes()) of the value to query.
* @param A pointer to a ValueID that will be returned if successful
* @return true of the nodeId and index was found, false otherwise
*/
bool getValueID(int nodeId, int index, OpenZWave::ValueID *vid);
/**
* Return the Home ID of the network.
*
* @return The Home ID.
*/
uint32_t getHomeID()
{
return m_homeId;
}
/**
* Lock the m_zwNodeMap mutex to protect against changes made to
* the the the map by the OpenZWave notification handler. Always
* lock this mutex when acessing anything in the zwNodeMap map.
*/
void lockNodes() { pthread_mutex_lock(&m_nodeLock); };
/**
* Unlock the m_zwNodeMap mutex after lockNodes() has been called.
*/
void unlockNodes() { pthread_mutex_unlock(&m_nodeLock); };
private:
// prevent copying and assignment
OZW(OZW const &) = delete;
OZW& operator=(OZW const&) = delete;
// our class instance
static OZW* m_instance;
uint32_t m_homeId;
bool m_mgrCreated;
bool m_driverFailed;
bool m_debugging;
bool m_initialized;
bool m_driverIsHID;
std::string m_devicePath;
// our notification handler, called by OpenZWave for events on the
// network.
static void notificationHandler(OpenZWave::Notification
const* notification,
void *ctx);
// a map of added nodes
zwNodeMap_t m_zwNodeMap;
// for coordinating access to the node list
pthread_mutex_t m_nodeLock;
// We use these to determine init failure or success (if OpenZWave
// has successfully queried essential data about the network).
pthread_mutex_t m_initLock;
pthread_cond_t m_initCond;
};
}
| {'content_hash': '6e5bf82caec3ed070a0d678734c191a8', 'timestamp': '', 'source': 'github', 'line_count': 591, 'max_line_length': 76, 'avg_line_length': 35.135363790186126, 'alnum_prop': 0.6474837466891403, 'repo_name': 'sasmita/upm', 'id': '53b3ab81df9df1ad06131cbcf34fa0be4f13c964', 'size': '21937', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'src/ozw/ozw.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3003252'}, {'name': 'C++', 'bytes': '3364615'}, {'name': 'CMake', 'bytes': '136360'}, {'name': 'CSS', 'bytes': '18714'}, {'name': 'HTML', 'bytes': '33016'}, {'name': 'JavaScript', 'bytes': '47971'}, {'name': 'Objective-C', 'bytes': '5854'}, {'name': 'Python', 'bytes': '39405'}]} |
import MainController from './controller'
export const mainConfig = (modulo) => {
return ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) => {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
template: require('@views/main/component.html'),
controller: MainController,
controllerAs: 'vm',
url: '/'
});
}];
}; | {'content_hash': '11f0717c3fd8a197ac6f4ab123b52e89', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 91, 'avg_line_length': 29.428571428571427, 'alnum_prop': 0.6140776699029126, 'repo_name': 'JosiasMattiole/CursoJavaAvancado', 'id': '8a48f3047a3ac204b6a4f6fb7c9229159702e312', 'size': '412', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'webschool/app/src/webschool/main/config.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13341'}, {'name': 'HTML', 'bytes': '20220'}, {'name': 'Java', 'bytes': '45071'}, {'name': 'JavaScript', 'bytes': '15873'}]} |
layout: lab
key: leipzig
# metadata is in: _labs/leipzig.yml
# english text is in en/leipzig/index.html
---
Das OK Lab Leipzig trifft sich jeden Montag um 19:00 Uhr im [BIC](http://www.bic-leipzig.de/kontakt-wegbeschreibung.html), um gemeinsam an Open Data Apps für Leipzig zu arbeiten. Neueinsteigerinnen und Leute, die nicht programmieren, sind immer herzlich willkommen!
Am zweiten Montag im Monat findet eine Input-Session statt. Hier laden wir externe Referentinnen ein, stellen selbst Technologien und Konzepte vor oder arbeiten Projekt-übergreifend zusammen.
<img class="h4c-teaser" src="/img/h4c_logo_big.svg" alt="Hack your City">
Das OK Lab Leipzig ist Teil des Projekts <a href="http://www.hackyourcity.de">Hack your City</a> und arbeitet in 2015 schwerpunktmäßig an Citizen Science Projekten. Hack your City ist ein Projekt im Rahmen des <a href="https://www.wissenschaftsjahr-zukunftsstadt.de">Wissenschaftsjahr 2015 - Zukunftsstadt</a>. Mehr Informationen findet ihr hier: <a href="http://www.hackyourcity.de/berlin/">hackyourcity.de</a>
| {'content_hash': '338d8b4de5e6c98f0961acf2c4614332', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 411, 'avg_line_length': 81.23076923076923, 'alnum_prop': 0.7840909090909091, 'repo_name': 'webwurst/codefor.de', 'id': 'fd332a6aecaa20155f36c16aed5e6ce7dd66c50a', 'size': '1064', 'binary': False, 'copies': '4', 'ref': 'refs/heads/gh-pages', 'path': 'leipzig/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23976'}, {'name': 'HTML', 'bytes': '272415'}, {'name': 'JavaScript', 'bytes': '18073'}, {'name': 'Python', 'bytes': '2259'}, {'name': 'Ruby', 'bytes': '3165'}, {'name': 'Shell', 'bytes': '154'}]} |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>lxml.etree.XInclude</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="lxml-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="/">lxml API</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="lxml-module.html">Package lxml</a> ::
<a href="lxml.etree-module.html">Module etree</a> ::
Class XInclude
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="lxml.etree.XInclude-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class XInclude</h1><p class="nomargin-top"></p>
<pre class="base-tree">
object --+
|
<strong class="uidshort">XInclude</strong>
</pre>
<hr />
<p>XInclude(self)
XInclude processor.</p>
<p>Create an instance and call it on an Element to run XInclude
processing.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__call__"></a><span class="summary-sig-name">__call__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">node</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.XInclude-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>)</span><br />
x.__init__(...) initializes x; see help(type(x)) for signature</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type">a new object with type S, a subtype of T</span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.XInclude-class.html#__new__" class="summary-sig-name">__new__</a>(<span class="summary-sig-arg">T</span>,
<span class="summary-sig-arg">S</span>,
<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__str__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="error_log"></a><span class="summary-name">error_log</span>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
x.__init__(...) initializes x; see help(type(x)) for signature
<dl class="fields">
<dt>Overrides:
object.__init__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__new__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__new__</span>(<span class="sig-arg">T</span>,
<span class="sig-arg">S</span>,
<span class="sig-arg">...</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<dl class="fields">
<dt>Returns: a new object with type S, a subtype of T</dt>
<dt>Overrides:
object.__new__
</dt>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="lxml-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="/">lxml API</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sat May 11 23:36:56 2013
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| {'content_hash': 'd1649a9204ca792aef61f4560e09fea0', 'timestamp': '', 'source': 'github', 'line_count': 313, 'max_line_length': 183, 'avg_line_length': 33.87539936102237, 'alnum_prop': 0.5495614448740922, 'repo_name': 'ioram7/keystone-federado-pgid2013', 'id': '407c4f5122320171f90a6a23d64312b42db4c807', 'size': '10603', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'build/lxml/doc/html/api/lxml.etree.XInclude-class.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1841'}, {'name': 'C', 'bytes': '10584735'}, {'name': 'C++', 'bytes': '19231'}, {'name': 'CSS', 'bytes': '172341'}, {'name': 'JavaScript', 'bytes': '530938'}, {'name': 'Python', 'bytes': '26306359'}, {'name': 'Shell', 'bytes': '38138'}, {'name': 'XSLT', 'bytes': '306125'}]} |
package org.elasticsearch.index.search.nested;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.FixedBitSet;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
/**
* A special query that accepts a top level parent matching query, and returns the nested docs of the matching parent
* doc as well. This is handy when deleting by query, don't use it for other purposes.
*
* @elasticsearch.internal
*/
public class IncludeNestedDocsQuery extends Query {
private final Filter parentFilter;
private final Query parentQuery;
// If we are rewritten, this is the original childQuery we
// were passed; we use this for .equals() and
// .hashCode(). This makes rewritten query equal the
// original, so that user does not have to .rewrite() their
// query before searching:
private final Query origParentQuery;
public IncludeNestedDocsQuery(Query parentQuery, Filter parentFilter) {
this.origParentQuery = parentQuery;
this.parentQuery = parentQuery;
this.parentFilter = parentFilter;
}
// For rewritting
IncludeNestedDocsQuery(Query rewrite, Query originalQuery, IncludeNestedDocsQuery previousInstance) {
this.origParentQuery = originalQuery;
this.parentQuery = rewrite;
this.parentFilter = previousInstance.parentFilter;
setBoost(previousInstance.getBoost());
}
// For cloning
IncludeNestedDocsQuery(Query originalQuery, IncludeNestedDocsQuery previousInstance) {
this.origParentQuery = originalQuery;
this.parentQuery = originalQuery;
this.parentFilter = previousInstance.parentFilter;
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
return new IncludeNestedDocsWeight(parentQuery, parentQuery.createWeight(searcher), parentFilter);
}
static class IncludeNestedDocsWeight extends Weight {
private final Query parentQuery;
private final Weight parentWeight;
private final Filter parentsFilter;
IncludeNestedDocsWeight(Query parentQuery, Weight parentWeight, Filter parentsFilter) {
this.parentQuery = parentQuery;
this.parentWeight = parentWeight;
this.parentsFilter = parentsFilter;
}
@Override
public Query getQuery() {
return parentQuery;
}
@Override
public void normalize(float norm, float topLevelBoost) {
parentWeight.normalize(norm, topLevelBoost);
}
@Override
public float getValueForNormalization() throws IOException {
return parentWeight.getValueForNormalization(); // this query is never boosted so just delegate...
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException {
final Scorer parentScorer = parentWeight.scorer(context, true, false, acceptDocs);
// no matches
if (parentScorer == null) {
return null;
}
DocIdSet parents = parentsFilter.getDocIdSet(context, acceptDocs);
if (parents == null) {
// No matches
return null;
}
if (!(parents instanceof FixedBitSet)) {
throw new IllegalStateException("parentFilter must return FixedBitSet; got " + parents);
}
int firstParentDoc = parentScorer.nextDoc();
if (firstParentDoc == DocIdSetIterator.NO_MORE_DOCS) {
// No matches
return null;
}
return new IncludeNestedDocsScorer(this, parentScorer, (FixedBitSet) parents, firstParentDoc);
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
return null; //Query is used internally and not by users, so explain can be empty
}
@Override
public boolean scoresDocsOutOfOrder() {
return false;
}
}
static class IncludeNestedDocsScorer extends Scorer {
final Scorer parentScorer;
final FixedBitSet parentBits;
int currentChildPointer = -1;
int currentParentPointer = -1;
int currentDoc = -1;
IncludeNestedDocsScorer(Weight weight, Scorer parentScorer, FixedBitSet parentBits, int currentParentPointer) {
super(weight);
this.parentScorer = parentScorer;
this.parentBits = parentBits;
this.currentParentPointer = currentParentPointer;
if (currentParentPointer == 0) {
currentChildPointer = 0;
} else {
this.currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, we delete from doc 0
currentChildPointer = 0;
} else {
currentChildPointer++; // we only care about children
}
}
currentDoc = currentChildPointer;
}
@Override
public Collection<ChildScorer> getChildren() {
return parentScorer.getChildren();
}
public int nextDoc() throws IOException {
if (currentParentPointer == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (currentChildPointer == currentParentPointer) {
// we need to return the current parent as well, but prepare to return
// the next set of children
currentDoc = currentParentPointer;
currentParentPointer = parentScorer.nextDoc();
if (currentParentPointer != NO_MORE_DOCS) {
currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, just set the child to the current parent
currentChildPointer = currentParentPointer;
} else {
currentChildPointer++; // we only care about children
}
}
} else {
currentDoc = currentChildPointer++;
}
assert currentDoc != -1;
return currentDoc;
}
public int advance(int target) throws IOException {
if (target == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (target == 0) {
return nextDoc();
}
if (target < currentParentPointer) {
currentDoc = currentParentPointer = parentScorer.advance(target);
if (currentParentPointer == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (currentParentPointer == 0) {
currentChildPointer = 0;
} else {
currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, just set the child to 0 to delete all up to the parent
currentChildPointer = 0;
} else {
currentChildPointer++; // we only care about children
}
}
} else {
currentDoc = currentChildPointer++;
}
return currentDoc;
}
public float score() throws IOException {
return parentScorer.score();
}
public int freq() throws IOException {
return parentScorer.freq();
}
public int docID() {
return currentDoc;
}
@Override
public long cost() {
return parentScorer.cost();
}
}
@Override
public void extractTerms(Set<Term> terms) {
parentQuery.extractTerms(terms);
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
final Query parentRewrite = parentQuery.rewrite(reader);
if (parentRewrite != parentQuery) {
return new IncludeNestedDocsQuery(parentRewrite, parentQuery, this);
} else {
return this;
}
}
@Override
public String toString(String field) {
return "IncludeNestedDocsQuery (" + parentQuery.toString() + ")";
}
@Override
public boolean equals(Object _other) {
if (_other instanceof IncludeNestedDocsQuery) {
final IncludeNestedDocsQuery other = (IncludeNestedDocsQuery) _other;
return origParentQuery.equals(other.origParentQuery) && parentFilter.equals(other.parentFilter);
} else {
return false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int hash = 1;
hash = prime * hash + origParentQuery.hashCode();
hash = prime * hash + parentFilter.hashCode();
return hash;
}
@Override
public Query clone() {
Query clonedQuery = origParentQuery.clone();
return new IncludeNestedDocsQuery(clonedQuery, this);
}
}
| {'content_hash': 'dddacd37375542a5fd9ba8e2f351833e', 'timestamp': '', 'source': 'github', 'line_count': 280, 'max_line_length': 140, 'avg_line_length': 34.339285714285715, 'alnum_prop': 0.597191887675507, 'repo_name': 'uboness/elasticsearch', 'id': 'ee1f76c48a4c6122417078d19817577072233b6c', 'size': '10403', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/elasticsearch/index/search/nested/IncludeNestedDocsQuery.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '22454040'}, {'name': 'Python', 'bytes': '25956'}, {'name': 'Ruby', 'bytes': '20739'}, {'name': 'Shell', 'bytes': '27703'}]} |
import argparse
import contextlib
import distutils.spawn
import errno
import itertools
import os
import pkg_resources
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from grpc.framework.alpha import exceptions
from grpc.framework.foundation import future
# Identifiers of entities we expect to find in the generated module.
SERVICER_IDENTIFIER = 'EarlyAdopterTestServiceServicer'
SERVER_IDENTIFIER = 'EarlyAdopterTestServiceServer'
STUB_IDENTIFIER = 'EarlyAdopterTestServiceStub'
SERVER_FACTORY_IDENTIFIER = 'early_adopter_create_TestService_server'
STUB_FACTORY_IDENTIFIER = 'early_adopter_create_TestService_stub'
# The timeout used in tests of RPCs that are supposed to expire.
SHORT_TIMEOUT = 2
# The timeout used in tests of RPCs that are not supposed to expire. The
# absurdly large value doesn't matter since no passing execution of this test
# module will ever wait the duration.
LONG_TIMEOUT = 600
NO_DELAY = 0
class _ServicerMethods(object):
def __init__(self, test_pb2, delay):
self._condition = threading.Condition()
self._delay = delay
self._paused = False
self._fail = False
self._test_pb2 = test_pb2
@contextlib.contextmanager
def pause(self): # pylint: disable=invalid-name
with self._condition:
self._paused = True
yield
with self._condition:
self._paused = False
self._condition.notify_all()
@contextlib.contextmanager
def fail(self): # pylint: disable=invalid-name
with self._condition:
self._fail = True
yield
with self._condition:
self._fail = False
def _control(self): # pylint: disable=invalid-name
with self._condition:
if self._fail:
raise ValueError()
while self._paused:
self._condition.wait()
time.sleep(self._delay)
def UnaryCall(self, request, unused_rpc_context):
response = self._test_pb2.SimpleResponse()
response.payload.payload_type = self._test_pb2.COMPRESSABLE
response.payload.payload_compressable = 'a' * request.response_size
self._control()
return response
def StreamingOutputCall(self, request, unused_rpc_context):
for parameter in request.response_parameters:
response = self._test_pb2.StreamingOutputCallResponse()
response.payload.payload_type = self._test_pb2.COMPRESSABLE
response.payload.payload_compressable = 'a' * parameter.size
self._control()
yield response
def StreamingInputCall(self, request_iter, unused_rpc_context):
response = self._test_pb2.StreamingInputCallResponse()
aggregated_payload_size = 0
for request in request_iter:
aggregated_payload_size += len(request.payload.payload_compressable)
response.aggregated_payload_size = aggregated_payload_size
self._control()
return response
def FullDuplexCall(self, request_iter, unused_rpc_context):
for request in request_iter:
for parameter in request.response_parameters:
response = self._test_pb2.StreamingOutputCallResponse()
response.payload.payload_type = self._test_pb2.COMPRESSABLE
response.payload.payload_compressable = 'a' * parameter.size
self._control()
yield response
def HalfDuplexCall(self, request_iter, unused_rpc_context):
responses = []
for request in request_iter:
for parameter in request.response_parameters:
response = self._test_pb2.StreamingOutputCallResponse()
response.payload.payload_type = self._test_pb2.COMPRESSABLE
response.payload.payload_compressable = 'a' * parameter.size
self._control()
responses.append(response)
for response in responses:
yield response
@contextlib.contextmanager
def _CreateService(test_pb2, delay):
"""Provides a servicer backend and a stub.
The servicer is just the implementation
of the actual servicer passed to the face player of the python RPC
implementation; the two are detached.
Non-zero delay puts a delay on each call to the servicer, representative of
communication latency. Timeout is the default timeout for the stub while
waiting for the service.
Args:
test_pb2: The test_pb2 module generated by this test.
delay: Delay in seconds per response from the servicer.
Yields:
A (servicer_methods, servicer, stub) three-tuple where servicer_methods is
the back-end of the service bound to the stub and the server and stub
are both activated and ready for use.
"""
servicer_methods = _ServicerMethods(test_pb2, delay)
class Servicer(getattr(test_pb2, SERVICER_IDENTIFIER)):
def UnaryCall(self, request, context):
return servicer_methods.UnaryCall(request, context)
def StreamingOutputCall(self, request, context):
return servicer_methods.StreamingOutputCall(request, context)
def StreamingInputCall(self, request_iter, context):
return servicer_methods.StreamingInputCall(request_iter, context)
def FullDuplexCall(self, request_iter, context):
return servicer_methods.FullDuplexCall(request_iter, context)
def HalfDuplexCall(self, request_iter, context):
return servicer_methods.HalfDuplexCall(request_iter, context)
servicer = Servicer()
server = getattr(
test_pb2, SERVER_FACTORY_IDENTIFIER)(servicer, 0)
with server:
port = server.port()
stub = getattr(test_pb2, STUB_FACTORY_IDENTIFIER)('localhost', port)
with stub:
yield servicer_methods, stub, server
def _streaming_input_request_iterator(test_pb2):
for _ in range(3):
request = test_pb2.StreamingInputCallRequest()
request.payload.payload_type = test_pb2.COMPRESSABLE
request.payload.payload_compressable = 'a'
yield request
def _streaming_output_request(test_pb2):
request = test_pb2.StreamingOutputCallRequest()
sizes = [1, 2, 3]
request.response_parameters.add(size=sizes[0], interval_us=0)
request.response_parameters.add(size=sizes[1], interval_us=0)
request.response_parameters.add(size=sizes[2], interval_us=0)
return request
def _full_duplex_request_iterator(test_pb2):
request = test_pb2.StreamingOutputCallRequest()
request.response_parameters.add(size=1, interval_us=0)
yield request
request = test_pb2.StreamingOutputCallRequest()
request.response_parameters.add(size=2, interval_us=0)
request.response_parameters.add(size=3, interval_us=0)
yield request
class PythonPluginTest(unittest.TestCase):
"""Test case for the gRPC Python protoc-plugin.
While reading these tests, remember that the futures API
(`stub.method.async()`) only gives futures for the *non-streaming* responses,
else it behaves like its blocking cousin.
"""
def setUp(self):
# Assume that the appropriate protoc and grpc_python_plugins are on the
# path.
protoc_command = 'protoc'
protoc_plugin_filename = distutils.spawn.find_executable(
'grpc_python_plugin')
test_proto_filename = pkg_resources.resource_filename(
'grpc_protoc_plugin', 'test.proto')
if not os.path.isfile(protoc_command):
# Assume that if we haven't built protoc that it's on the system.
protoc_command = 'protoc'
# Ensure that the output directory exists.
self.outdir = tempfile.mkdtemp()
# Invoke protoc with the plugin.
cmd = [
protoc_command,
'--plugin=protoc-gen-python-grpc=%s' % protoc_plugin_filename,
'-I .',
'--python_out=%s' % self.outdir,
'--python-grpc_out=%s' % self.outdir,
os.path.basename(test_proto_filename),
]
subprocess.check_call(' '.join(cmd), shell=True, env=os.environ,
cwd=os.path.dirname(test_proto_filename))
sys.path.append(self.outdir)
def tearDown(self):
try:
shutil.rmtree(self.outdir)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
# TODO(atash): Figure out which of these tests is hanging flakily with small
# probability.
def testImportAttributes(self):
# check that we can access the generated module and its members.
import test_pb2 # pylint: disable=g-import-not-at-top
self.assertIsNotNone(getattr(test_pb2, SERVICER_IDENTIFIER, None))
self.assertIsNotNone(getattr(test_pb2, SERVER_IDENTIFIER, None))
self.assertIsNotNone(getattr(test_pb2, STUB_IDENTIFIER, None))
self.assertIsNotNone(getattr(test_pb2, SERVER_FACTORY_IDENTIFIER, None))
self.assertIsNotNone(getattr(test_pb2, STUB_FACTORY_IDENTIFIER, None))
def testUpDown(self):
import test_pb2
with _CreateService(
test_pb2, NO_DELAY) as (servicer, stub, unused_server):
request = test_pb2.SimpleRequest(response_size=13)
def testUnaryCall(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (methods, stub, unused_server):
timeout = 6 # TODO(issue 2039): LONG_TIMEOUT like the other methods.
request = test_pb2.SimpleRequest(response_size=13)
response = stub.UnaryCall(request, timeout)
expected_response = methods.UnaryCall(request, 'not a real RpcContext!')
self.assertEqual(expected_response, response)
def testUnaryCallAsync(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = test_pb2.SimpleRequest(response_size=13)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
# Check that the call does not block waiting for the server to respond.
with methods.pause():
response_future = stub.UnaryCall.async(request, LONG_TIMEOUT)
response = response_future.result()
expected_response = methods.UnaryCall(request, 'not a real RpcContext!')
self.assertEqual(expected_response, response)
def testUnaryCallAsyncExpired(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
request = test_pb2.SimpleRequest(response_size=13)
with methods.pause():
response_future = stub.UnaryCall.async(request, SHORT_TIMEOUT)
with self.assertRaises(exceptions.ExpirationError):
response_future.result()
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testUnaryCallAsyncCancelled(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = test_pb2.SimpleRequest(response_size=13)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.pause():
response_future = stub.UnaryCall.async(request, 1)
response_future.cancel()
self.assertTrue(response_future.cancelled())
def testUnaryCallAsyncFailed(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = test_pb2.SimpleRequest(response_size=13)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.fail():
response_future = stub.UnaryCall.async(request, LONG_TIMEOUT)
self.assertIsNotNone(response_future.exception())
def testStreamingOutputCall(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = _streaming_output_request(test_pb2)
with _CreateService(test_pb2, NO_DELAY) as (methods, stub, unused_server):
responses = stub.StreamingOutputCall(request, LONG_TIMEOUT)
expected_responses = methods.StreamingOutputCall(
request, 'not a real RpcContext!')
for expected_response, response in itertools.izip_longest(
expected_responses, responses):
self.assertEqual(expected_response, response)
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testStreamingOutputCallExpired(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = _streaming_output_request(test_pb2)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.pause():
responses = stub.StreamingOutputCall(request, SHORT_TIMEOUT)
with self.assertRaises(exceptions.ExpirationError):
list(responses)
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testStreamingOutputCallCancelled(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = _streaming_output_request(test_pb2)
with _CreateService(test_pb2, NO_DELAY) as (
unused_methods, stub, unused_server):
responses = stub.StreamingOutputCall(request, SHORT_TIMEOUT)
next(responses)
responses.cancel()
with self.assertRaises(future.CancelledError):
next(responses)
@unittest.skip('TODO(atash,nathaniel): figure out why this times out '
'instead of raising the proper error.')
def testStreamingOutputCallFailed(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request = _streaming_output_request(test_pb2)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.fail():
responses = stub.StreamingOutputCall(request, 1)
self.assertIsNotNone(responses)
with self.assertRaises(exceptions.ServicerError):
next(responses)
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testStreamingInputCall(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (methods, stub, unused_server):
response = stub.StreamingInputCall(
_streaming_input_request_iterator(test_pb2), LONG_TIMEOUT)
expected_response = methods.StreamingInputCall(
_streaming_input_request_iterator(test_pb2), 'not a real RpcContext!')
self.assertEqual(expected_response, response)
def testStreamingInputCallAsync(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.pause():
response_future = stub.StreamingInputCall.async(
_streaming_input_request_iterator(test_pb2), LONG_TIMEOUT)
response = response_future.result()
expected_response = methods.StreamingInputCall(
_streaming_input_request_iterator(test_pb2), 'not a real RpcContext!')
self.assertEqual(expected_response, response)
def testStreamingInputCallAsyncExpired(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.pause():
response_future = stub.StreamingInputCall.async(
_streaming_input_request_iterator(test_pb2), SHORT_TIMEOUT)
with self.assertRaises(exceptions.ExpirationError):
response_future.result()
self.assertIsInstance(
response_future.exception(), exceptions.ExpirationError)
def testStreamingInputCallAsyncCancelled(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.pause():
timeout = 6 # TODO(issue 2039): LONG_TIMEOUT like the other methods.
response_future = stub.StreamingInputCall.async(
_streaming_input_request_iterator(test_pb2), timeout)
response_future.cancel()
self.assertTrue(response_future.cancelled())
with self.assertRaises(future.CancelledError):
response_future.result()
def testStreamingInputCallAsyncFailed(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.fail():
response_future = stub.StreamingInputCall.async(
_streaming_input_request_iterator(test_pb2), SHORT_TIMEOUT)
self.assertIsNotNone(response_future.exception())
def testFullDuplexCall(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (methods, stub, unused_server):
responses = stub.FullDuplexCall(
_full_duplex_request_iterator(test_pb2), LONG_TIMEOUT)
expected_responses = methods.FullDuplexCall(
_full_duplex_request_iterator(test_pb2), 'not a real RpcContext!')
for expected_response, response in itertools.izip_longest(
expected_responses, responses):
self.assertEqual(expected_response, response)
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testFullDuplexCallExpired(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request_iterator = _full_duplex_request_iterator(test_pb2)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.pause():
responses = stub.FullDuplexCall(request_iterator, SHORT_TIMEOUT)
with self.assertRaises(exceptions.ExpirationError):
list(responses)
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testFullDuplexCallCancelled(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (methods, stub, unused_server):
request_iterator = _full_duplex_request_iterator(test_pb2)
responses = stub.FullDuplexCall(request_iterator, LONG_TIMEOUT)
next(responses)
responses.cancel()
with self.assertRaises(future.CancelledError):
next(responses)
@unittest.skip('TODO(atash,nathaniel): figure out why this hangs forever '
'and fix.')
def testFullDuplexCallFailed(self):
import test_pb2 # pylint: disable=g-import-not-at-top
request_iterator = _full_duplex_request_iterator(test_pb2)
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
with methods.fail():
responses = stub.FullDuplexCall(request_iterator, LONG_TIMEOUT)
self.assertIsNotNone(responses)
with self.assertRaises(exceptions.ServicerError):
next(responses)
@unittest.skip('TODO(atash,nathaniel): figure out why this flakily hangs '
'forever and fix.')
def testHalfDuplexCall(self):
import test_pb2 # pylint: disable=g-import-not-at-top
with _CreateService(test_pb2, NO_DELAY) as (
methods, stub, unused_server):
def half_duplex_request_iterator():
request = test_pb2.StreamingOutputCallRequest()
request.response_parameters.add(size=1, interval_us=0)
yield request
request = test_pb2.StreamingOutputCallRequest()
request.response_parameters.add(size=2, interval_us=0)
request.response_parameters.add(size=3, interval_us=0)
yield request
responses = stub.HalfDuplexCall(
half_duplex_request_iterator(), LONG_TIMEOUT)
expected_responses = methods.HalfDuplexCall(
half_duplex_request_iterator(), 'not a real RpcContext!')
for check in itertools.izip_longest(expected_responses, responses):
expected_response, response = check
self.assertEqual(expected_response, response)
def testHalfDuplexCallWedged(self):
import test_pb2 # pylint: disable=g-import-not-at-top
condition = threading.Condition()
wait_cell = [False]
@contextlib.contextmanager
def wait(): # pylint: disable=invalid-name
# Where's Python 3's 'nonlocal' statement when you need it?
with condition:
wait_cell[0] = True
yield
with condition:
wait_cell[0] = False
condition.notify_all()
def half_duplex_request_iterator():
request = test_pb2.StreamingOutputCallRequest()
request.response_parameters.add(size=1, interval_us=0)
yield request
with condition:
while wait_cell[0]:
condition.wait()
with _CreateService(test_pb2, NO_DELAY) as (methods, stub, unused_server):
with wait():
responses = stub.HalfDuplexCall(
half_duplex_request_iterator(), SHORT_TIMEOUT)
# half-duplex waits for the client to send all info
with self.assertRaises(exceptions.ExpirationError):
next(responses)
if __name__ == '__main__':
os.chdir(os.path.dirname(sys.argv[0]))
unittest.main(verbosity=2)
| {'content_hash': '5f5aa96b4218720ec364f99fb8e652bb', 'timestamp': '', 'source': 'github', 'line_count': 512, 'max_line_length': 79, 'avg_line_length': 39.99609375, 'alnum_prop': 0.6991405410684637, 'repo_name': 'fichter/grpc', 'id': 'b200d129a9c8f28ef9039674aa5b51c6a88fbfbd', 'size': '22007', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'src/python/grpcio_test/grpc_protoc_plugin/python_plugin_test.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '3220'}, {'name': 'C', 'bytes': '3674346'}, {'name': 'C#', 'bytes': '784596'}, {'name': 'C++', 'bytes': '988770'}, {'name': 'DTrace', 'bytes': '147'}, {'name': 'JavaScript', 'bytes': '196335'}, {'name': 'Makefile', 'bytes': '2042006'}, {'name': 'Objective-C', 'bytes': '243336'}, {'name': 'PHP', 'bytes': '66550'}, {'name': 'Protocol Buffer', 'bytes': '105002'}, {'name': 'Python', 'bytes': '1286466'}, {'name': 'Ruby', 'bytes': '348704'}, {'name': 'Shell', 'bytes': '25777'}]} |
__version__=''' $Id$ '''
__doc__="""A Sequencer class counts things. It aids numbering and formatting lists."""
__all__='''Sequencer getSequencer setSequencer'''.split()
#
# roman numbers conversion thanks to
#
# fredrik lundh, november 1996 (based on a C hack from 1984)
#
# [email protected]
# http://www.pythonware.com
_RN_TEMPLATES = [ 0, 0o1, 0o11, 0o111, 0o12, 0o2, 0o21, 0o211, 0o2111, 0o13 ]
_RN_LETTERS = "IVXLCDM"
from reportlab import isPy3
def _format_I(value):
if value < 0 or value > 3999:
raise ValueError("illegal value")
str = ""
base = -1
while value:
value, index = divmod(value, 10)
tmp = _RN_TEMPLATES[index]
while tmp:
tmp, index = divmod(tmp, 8)
str = _RN_LETTERS[index+base] + str
base += 2
return str
def _format_i(num):
return _format_I(num).lower()
def _format_123(num):
"""The simplest formatter"""
return str(num)
def _format_ABC(num):
"""Uppercase. Wraps around at 26."""
n = (num -1) % 26
return chr(n+65)
def _format_abc(num):
"""Lowercase. Wraps around at 26."""
n = (num -1) % 26
return chr(n+97)
_type2formatter = {
'I':_format_I,
'i':_format_i,
'1':_format_123,
'A':_format_ABC,
'a':_format_abc,
}
class _Counter:
"""Private class used by Sequencer. Each counter
knows its format, and the IDs of anything it
resets, as well as its value. Starts at zero
and increments just before you get the new value,
so that it is still 'Chapter 5' and not 'Chapter 6'
when you print 'Figure 5.1'"""
def __init__(self):
self._base = 0
self._value = self._base
self._formatter = _format_123
self._resets = []
def setFormatter(self, formatFunc):
self._formatter = formatFunc
def reset(self, value=None):
if value:
self._value = value
else:
self._value = self._base
def next(self):
self._value += 1
v = self._value
for counter in self._resets:
counter.reset()
return v
__next__ = next
def _this(self):
return self._value
if isPy3:
def nextf(self):
"""Returns next value formatted"""
return self._formatter(next(self))
else:
def nextf(self):
"""Returns next value formatted"""
return self._formatter(self.__next__())
def thisf(self):
return self._formatter(self._this())
def chain(self, otherCounter):
if not otherCounter in self._resets:
self._resets.append(otherCounter)
class Sequencer:
"""Something to make it easy to number paragraphs, sections,
images and anything else. The features include registering
new string formats for sequences, and 'chains' whereby
some counters are reset when their parents.
It keeps track of a number of
'counters', which are created on request:
Usage::
>>> seq = layout.Sequencer()
>>> seq.next('Bullets')
1
>>> seq.next('Bullets')
2
>>> seq.next('Bullets')
3
>>> seq.reset('Bullets')
>>> seq.next('Bullets')
1
>>> seq.next('Figures')
1
>>>
"""
def __init__(self):
self._counters = {} #map key to current number
self._formatters = {}
self._reset()
def _reset(self):
self._counters.clear()
self._formatters.clear()
self._formatters.update({
# the formats it knows initially
'1':_format_123,
'A':_format_ABC,
'a':_format_abc,
'I':_format_I,
'i':_format_i,
})
d = dict(_counters=self._counters,_formatters=self._formatters)
self.__dict__.clear()
self.__dict__.update(d)
self._defaultCounter = None
def _getCounter(self, counter=None):
"""Creates one if not present"""
try:
return self._counters[counter]
except KeyError:
cnt = _Counter()
self._counters[counter] = cnt
return cnt
def _this(self, counter=None):
"""Retrieves counter value but does not increment. For
new counters, sets base value to 1."""
if not counter:
counter = self._defaultCounter
return self._getCounter(counter)._this()
if isPy3:
def __next__(self):
"""Retrieves the numeric value for the given counter, then
increments it by one. New counters start at one."""
return next(self._getCounter(self._defaultCounter))
def next(self,counter=None):
if not counter:
return next(self)
else:
dc = self._defaultCounter
try:
self._defaultCounter = counter
return next(self)
finally:
self._defaultCounter = dc
else:
def next(self, counter=None):
"""Retrieves the numeric value for the given counter, then
increments it by one. New counters start at one."""
if not counter:
counter = self._defaultCounter
return self._getCounter(counter).next()
def thisf(self, counter=None):
if not counter:
counter = self._defaultCounter
return self._getCounter(counter).thisf()
def nextf(self, counter=None):
"""Retrieves the numeric value for the given counter, then
increments it by one. New counters start at one."""
if not counter:
counter = self._defaultCounter
return self._getCounter(counter).nextf()
def setDefaultCounter(self, default=None):
"""Changes the key used for the default"""
self._defaultCounter = default
def registerFormat(self, format, func):
"""Registers a new formatting function. The funtion
must take a number as argument and return a string;
fmt is a short menmonic string used to access it."""
self._formatters[format] = func
def setFormat(self, counter, format):
"""Specifies that the given counter should use
the given format henceforth."""
func = self._formatters[format]
self._getCounter(counter).setFormatter(func)
def reset(self, counter=None, base=0):
if not counter:
counter = self._defaultCounter
self._getCounter(counter)._value = base
def chain(self, parent, child):
p = self._getCounter(parent)
c = self._getCounter(child)
p.chain(c)
def __getitem__(self, key):
"""Allows compact notation to support the format function.
s['key'] gets current value, s['key+'] increments."""
if key[-1:] == '+':
counter = key[:-1]
return self.nextf(counter)
else:
return self.thisf(key)
def format(self, template):
"""The crowning jewels - formats multi-level lists."""
return template % self
def dump(self):
"""Write current state to stdout for diagnostics"""
counters = list(self._counters.items())
counters.sort()
print('Sequencer dump:')
for (key, counter) in counters:
print(' %s: value = %d, base = %d, format example = %s' % (
key, counter._this(), counter._base, counter.thisf()))
"""Your story builder needs to set this to"""
_sequencer = None
def getSequencer():
global _sequencer
if _sequencer is None:
_sequencer = Sequencer()
return _sequencer
def setSequencer(seq):
global _sequencer
s = _sequencer
_sequencer = seq
return s
def _reset():
global _sequencer
if _sequencer:
_sequencer._reset()
from reportlab.rl_config import register_reset
register_reset(_reset)
del register_reset
def test():
s = Sequencer()
print('Counting using default sequence: %d %d %d' % (next(s),next(s), next(s)))
print('Counting Figures: Figure %d, Figure %d, Figure %d' % (
s.next('figure'), s.next('figure'), s.next('figure')))
print('Back to default again: %d' % next(s))
s.setDefaultCounter('list1')
print('Set default to list1: %d %d %d' % (next(s),next(s), next(s)))
s.setDefaultCounter()
print('Set default to None again: %d %d %d' % (next(s),next(s), next(s)))
print()
print('Creating Appendix counter with format A, B, C...')
s.setFormat('Appendix', 'A')
print(' Appendix %s, Appendix %s, Appendix %s' % (
s.nextf('Appendix'), s.nextf('Appendix'),s.nextf('Appendix')))
def format_french(num):
return ('un','deux','trois','quatre','cinq')[(num-1)%5]
print()
print('Defining a custom format with french words:')
s.registerFormat('french', format_french)
s.setFormat('FrenchList', 'french')
print(' ' +(' '.join(str(s.nextf('FrenchList')) for i in range(1,6))))
print()
print('Chaining H1 and H2 - H2 goes back to one when H1 increases')
s.chain('H1','H2')
print(' H1 = %d' % s.next('H1'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print(' H1 = %d' % s.next('H1'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print(' H2 = %d' % s.next('H2'))
print()
print('GetItem notation - append a plus to increment')
print(' seq["Appendix"] = %s' % s["Appendix"])
print(' seq["Appendix+"] = %s' % s["Appendix+"])
print(' seq["Appendix+"] = %s' % s["Appendix+"])
print(' seq["Appendix"] = %s' % s["Appendix"])
print()
print('Finally, string format notation for nested lists. Cool!')
print('The expression ("Figure %(Chapter)s.%(Figure+)s" % seq) gives:')
print(' Figure %(Chapter)s.%(Figure+)s' % s)
print(' Figure %(Chapter)s.%(Figure+)s' % s)
print(' Figure %(Chapter)s.%(Figure+)s' % s)
if __name__=='__main__':
test()
| {'content_hash': '4b0d1c9590144069a046fd55d3407058', 'timestamp': '', 'source': 'github', 'line_count': 323, 'max_line_length': 86, 'avg_line_length': 31.396284829721363, 'alnum_prop': 0.5627650133122967, 'repo_name': 'yasoob/PythonRSSReader', 'id': '6bc56c86e8fa4b00005dbecd7bffdb25904d1092', 'size': '10221', 'binary': False, 'copies': '32', 'ref': 'refs/heads/master', 'path': 'venv/lib/python2.7/dist-packages/reportlab/lib/sequencer.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '106'}, {'name': 'C', 'bytes': '58615'}, {'name': 'D', 'bytes': '1841'}, {'name': 'HTML', 'bytes': '1638'}, {'name': 'Objective-C', 'bytes': '1291'}, {'name': 'Python', 'bytes': '22979347'}, {'name': 'Shell', 'bytes': '5224'}, {'name': 'XSLT', 'bytes': '152770'}]} |
<template>
<require from="./date-format.js"></require>
<require from="./number-format.js"></require>
${currentDate | dateFormat:'M/D/YYYY h:mm:ss a'} <br/>
${currentDate | dateFormat:'MMMM Mo YYYY'} <br/>
${currentDate | dateFormat:'h:mm:ss a'} <br/>
${netWorth | numberFormat:'$0,0.00'} <br/>
${netWorth | numberFormat:'$0.0a'} <br/>
${netWorth | numberFormat:'0.00000)'}
</template>
| {'content_hash': 'f98713bfb59c706698b8e61b7850bca9', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 56, 'avg_line_length': 36.54545454545455, 'alnum_prop': 0.6268656716417911, 'repo_name': 'stl-florida/casestudy-riskmap', 'id': '3cb0c812b034ae5dcd2dc564bb3997401880d799', 'size': '402', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'node_modules/aurelia-binding/doc/example-dist/binding-value-converters/converter-parameters/app.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2670'}, {'name': 'HTML', 'bytes': '3264'}, {'name': 'JavaScript', 'bytes': '1776505'}]} |
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Text
{
sealed public partial class UTF32Encoding : Encoding
{
#region Methods and constructors
public override bool Equals(Object value)
{
return default(bool);
}
public override int GetByteCount(string s)
{
return default(int);
}
unsafe public override int GetByteCount(char* chars, int count)
{
return default(int);
}
public override int GetByteCount(char[] chars, int index, int count)
{
return default(int);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return default(int);
}
unsafe public override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return default(int);
}
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return default(int);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return default(int);
}
unsafe public override int GetCharCount(byte* bytes, int count)
{
return default(int);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return default(int);
}
unsafe public override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return default(int);
}
public override Decoder GetDecoder()
{
return default(Decoder);
}
public override Encoder GetEncoder()
{
return default(Encoder);
}
public override int GetHashCode()
{
return default(int);
}
public override int GetMaxByteCount(int charCount)
{
return default(int);
}
public override int GetMaxCharCount(int byteCount)
{
return default(int);
}
public override byte[] GetPreamble()
{
return default(byte[]);
}
public override string GetString(byte[] bytes, int index, int count)
{
return default(string);
}
public UTF32Encoding()
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters)
{
}
#endregion
}
}
| {'content_hash': '1264536729c4800b5b6165e674a4adad', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 105, 'avg_line_length': 23.374045801526716, 'alnum_prop': 0.6698236446766819, 'repo_name': 'danielcweber/CodeContracts', 'id': 'e818ca46299cb1a26288ee233c8f060cb7853944', 'size': '4292', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'Microsoft.Research/Contracts/MsCorlib/Sources/System.Text.UTF32Encoding.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '2883'}, {'name': 'Batchfile', 'bytes': '26726'}, {'name': 'C', 'bytes': '232630'}, {'name': 'C#', 'bytes': '53291507'}, {'name': 'C++', 'bytes': '504486'}, {'name': 'F#', 'bytes': '418'}, {'name': 'HTML', 'bytes': '2819'}, {'name': 'JavaScript', 'bytes': '1544'}, {'name': 'Makefile', 'bytes': '8484'}, {'name': 'Perl', 'bytes': '8834'}, {'name': 'PostScript', 'bytes': '1364'}, {'name': 'PowerShell', 'bytes': '3542'}, {'name': 'Python', 'bytes': '1906'}, {'name': 'TeX', 'bytes': '61151'}, {'name': 'Visual Basic', 'bytes': '245561'}, {'name': 'XSLT', 'bytes': '102883'}]} |
(function( $, undefined ) {
// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
return;
}
$.extend( $.ui, {
version: "@VERSION",
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
}
});
// plugins
$.fn.extend({
_focus: $.fn.focus,
focus: function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
this._focus.apply( this, arguments );
},
scrollParent: function() {
var scrollParent;
if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
}
return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.curCSS( elem, "padding" + this, true ) ) || 0;
if ( border ) {
size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.curCSS( elem, "margin" + this, true ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
var map = element.parentNode,
mapName = map.name,
img;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName )
? !element.disabled
: "a" == nodeName
? element.href || isTabIndexNotNaN
: isTabIndexNotNaN)
// the element and all of its ancestors must be visible
&& visible( element );
}
function visible( element ) {
return !$( element ).parents().andSelf().filter(function() {
return $.curCSS( this, "visibility" ) === "hidden" ||
$.expr.filters.hidden( this );
}).length;
}
$.extend( $.expr[ ":" ], {
data: function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support
$(function() {
var body = document.body,
div = body.appendChild( div = document.createElement( "div" ) );
$.extend( div.style, {
minHeight: "100px",
height: "auto",
padding: 0,
borderWidth: 0
});
$.support.minHeight = div.offsetHeight === 100;
$.support.selectstart = "onselectstart" in div;
// set display to none to avoid a layout bug in IE
// http://dev.jquery.com/ticket/4014
body.removeChild( div ).style.display = "none";
});
// deprecated
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use the proxy pattern instead.
plugin: {
add: function( module, option, set ) {
var proto = $.ui[ module ].prototype;
for ( var i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode ) {
return;
}
for ( var i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
contains: $.contains,
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
},
// these are odd functions, fix the API or move into individual plugins
isOverAxis: function( x, reference, size ) {
//Determines when x coordinate is over "b" element axis
return ( x > reference ) && ( x < ( reference + size ) );
},
isOver: function( y, x, top, left, height, width ) {
//Determines when x, y coordinates is over "b" element
return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
}
});
})( jQuery );
/*!
* jQuery UI Widget @VERSION
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Widget
*/
(function( $, undefined ) {
var slice = Array.prototype.slice;
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
//console.log("----- $.widget:ns:" + namespace);
//console.log("----- $.widget:n:" + name);
//console.log("----- $.widget:f:" + fullName);
// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
return !!$.data( elem, name );
};
$[ namespace ] = $[ namespace ] || {};
// create the constructor using $.extend() so we can carry over any
// static properties stored on the existing constructor (if there is one)
$[ namespace ][ name ] = $.extend( function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new $[ namespace ][ name ]( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
}, $[ namespace ][ name ], { version: prototype.version } );
var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super = function( method ) {
return base.prototype[ method ].apply( this, slice.call( arguments, 1 ) );
};
var _superApply = function( method, args ) {
return base.prototype[ method ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
}());
}
});
$[ namespace ][ name ].prototype = $.widget.extend( basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: name,
widgetBaseClass: fullName
}, prototype );
$.widget.bridge( name, $[ namespace ][ name ] );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if (input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
target[ key ] = $.isPlainObject( value ) ? $.widget.extend( {}, target[ key ], value ) : value;
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var instance = $.data( this, name );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
var methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
instance.option( options || {} )._init();
} else {
object( options, this );
}
});
}
return returnValue;
};
};
$.Widget = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new $[ namespace ][ name ]( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetName, this );
this._bind({ remove: "destroy" });
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create" );
this._init();
},
_getCreateOptions: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._bind()
this.element
.unbind( "." + this.widgetName )
.removeData( this.widgetName );
this.widget()
.unbind( "." + this.widgetName )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetBaseClass + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( "." + this.widgetName );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetBaseClass + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_bind: function( element, handlers ) {
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
} else {
// accept selectors, DOM elements
element = $( element );
this.bindings = this.bindings.add( element );
}
var instance = this;
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + "." + instance.widgetName,
selector = match[2];
if ( selector ) {
instance.widget().delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._bind( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._bind( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var callback = this.options[ type ],
args;
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
data = data || {};
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( event.originalEvent ) {
for ( var i = $.event.props.length, prop; i; ) {
prop = $.event.props[ --i ];
event[ prop ] = event.originalEvent[ prop ];
}
}
this.element.trigger( event, data );
args = $.isArray( data ) ?
[ event ].concat( data ) :
[ event, data ];
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], args ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && ( $.effects.effect[ effectName ] || $.uiBackCompat !== false && $.effects[ effectName ] ) ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
// DEPRECATED
if ( $.uiBackCompat !== false ) {
$.Widget.prototype._getCreateOptions = function() {
return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
};
}
})( jQuery );
/*
* jQuery UI Position @VERSION
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Position
*/
(function( $, undefined ) {
$.ui = $.ui || {};
var rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[+-]\d+%?/,
rposition = /^\w+/,
rpercent = /%$/,
center = "center",
_position = $.fn.position;
$.position = {
scrollbarWidth: function() {
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return w1 - w2;
},
getScrollInfo: function(within) {
var notWindow = within[0] !== window,
overflowX = notWindow ? within.css( "overflow-x" ) : "",
overflowY = notWindow ? within.css( "overflow-y" ) : "",
scrollbarWidth = overflowX === "auto" || overflowX === "scroll" ? $.position.scrollbarWidth() : 0,
scrollbarHeight = overflowY === "auto" || overflowY === "scroll" ? $.position.scrollbarWidth() : 0;
return {
height: within.height() < within[0].scrollHeight ? scrollbarHeight : 0,
width: within.width() < within[0].scrollWidth ? scrollbarWidth : 0
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var target = $( options.of ),
within = $( options.within || window ),
targetElem = target[0],
collision = ( options.collision || "flip" ).split( " " ),
offsets = {},
atOffset,
targetWidth,
targetHeight,
basePosition;
if ( targetElem.nodeType === 9 ) {
targetWidth = target.width();
targetHeight = target.height();
basePosition = { top: 0, left: 0 };
} else if ( $.isWindow( targetElem ) ) {
targetWidth = target.width();
targetHeight = target.height();
basePosition = { top: target.scrollTop(), left: target.scrollLeft() };
} else if ( targetElem.preventDefault ) {
// force left top to allow flipping
options.at = "left top";
targetWidth = targetHeight = 0;
basePosition = { top: options.of.pageY, left: options.of.pageX };
} else {
targetWidth = target.outerWidth();
targetHeight = target.outerHeight();
basePosition = target.offset();
}
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ center ] ) :
rvertical.test( pos[ 0 ] ) ?
[ center ].concat( pos ) :
[ center, center ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : center;
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : center;
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === center ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === center ) {
basePosition.top += targetHeight / 2;
}
atOffset = [
parseInt( offsets.at[ 0 ], 10 ) *
( rpercent.test( offsets.at[ 0 ] ) ? targetWidth / 100 : 1 ),
parseInt( offsets.at[ 1 ], 10 ) *
( rpercent.test( offsets.at[ 1 ] ) ? targetHeight / 100 : 1 )
];
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0,
marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0,
scrollInfo = $.position.getScrollInfo( within ),
collisionWidth = elemWidth + marginLeft +
( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop +
( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = [
parseInt( offsets.my[ 0 ], 10 ) *
( rpercent.test( offsets.my[ 0 ] ) ? elem.outerWidth() / 100 : 1 ),
parseInt( offsets.my[ 1 ], 10 ) *
( rpercent.test( offsets.my[ 1 ] ) ? elem.outerHeight() / 100 : 1 )
],
collisionPosition;
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === center ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === center ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = Math.round( position.left );
position.top = Math.round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( $.fn.bgiframe ) {
elem.bgiframe();
}
elem.offset( $.extend( position, { using: options.using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
win = $( window ),
isWindow = $.isWindow( data.within[0] ),
withinOffset = isWindow ? win.scrollLeft() : within.offset().left,
outerWidth = isWindow ? win.width() : within.outerWidth(),
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight,
newOverLeft;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = Math.max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
win = $( window ),
isWindow = $.isWindow( data.within[0] ),
withinOffset = isWindow ? win.scrollTop() : within.offset().top,
outerHeight = isWindow ? win.height() : within.outerHeight(),
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverTop,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = Math.max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
if ( data.at[ 0 ] === center ) {
return;
}
data.elem
.removeClass( "ui-flipped-left ui-flipped-right" );
var within = data.within,
win = $( window ),
isWindow = $.isWindow( data.within[0] ),
withinOffset = ( isWindow ? 0 : within.offset().left ) + within.scrollLeft(),
outerWidth = isWindow ? within.width() : within.outerWidth(),
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - withinOffset,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
left = data.my[ 0 ] === "left",
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
-data.targetWidth,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < Math.abs( overLeft ) ) {
data.elem
.addClass( "ui-flipped-right" );
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - withinOffset;
if ( newOverLeft > 0 || Math.abs( newOverLeft ) < overRight ) {
data.elem
.addClass( "ui-flipped-left" );
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
if ( data.at[ 1 ] === center ) {
return;
}
data.elem
.removeClass( "ui-flipped-top ui-flipped-bottom" );
var within = data.within,
win = $( window ),
isWindow = $.isWindow( data.within[0] ),
withinOffset = ( isWindow ? 0 : within.offset().top ) + within.scrollTop(),
outerHeight = isWindow ? within.height() : within.outerHeight(),
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - withinOffset,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
-data.targetHeight,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < Math.abs( overTop ) ) ) {
data.elem
.addClass( "ui-flipped-bottom" );
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || Math.abs( newOverTop ) < overBottom ) ) {
data.elem
.addClass( "ui-flipped-top" );
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
jQuery.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
// DEPRECATED
if ( $.uiBackCompat !== false ) {
// offset option
(function( $ ) {
var _position = $.fn.position;
$.fn.position = function( options ) {
if ( !options || !options.offset ) {
return _position.call( this, options );
}
var offset = options.offset.split( " " ),
at = options.at.split( " " );
if ( offset.length === 1 ) {
offset[ 1 ] = offset[ 0 ];
}
if ( /^\d/.test( offset[ 0 ] ) ) {
offset[ 0 ] = "+" + offset[ 0 ];
}
if ( /^\d/.test( offset[ 1 ] ) ) {
offset[ 1 ] = "+" + offset[ 1 ];
}
if ( at.length === 1 ) {
if ( /left|center|right/.test( at[ 0 ] ) ) {
at[ 1 ] = "center";
} else {
at[ 1 ] = at[ 0 ];
at[ 0 ] = "center";
}
}
return _position.call( this, $.extend( options, {
at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ],
offset: undefined
} ) );
}
}( jQuery ) );
}
}( jQuery ) );
/*
* jQuery UI Menu @VERSION
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Menu
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function($) {
var idIncrement = 0;
$.widget( "ui.menu", {
version: "@VERSION",
defaultElement: "<ul>",
delay: 150,
options: {
items: "ul",
position: {
my: "left top",
at: "right top"
},
trigger: null
},
_create: function() {
this.activeMenu = this.element;
this.isScrolling = false;
this.menuId = this.element.attr( "id" ) || "ui-menu-" + idIncrement++;
if ( this.element.find( ".ui-icon" ).length ) {
this.element.addClass( "ui-menu-icons" );
}
this.element
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.attr({
id: this.menuId,
role: "menu"
})
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
// If the link is clicked, redirect focus to the menu.
// TODO move to _bind below
.bind( "mousedown.menu", function( event ) {
if ( $( event.target).is( "a" ) ) {
event.preventDefault();
$( this ).focus( 1 );
}
})
// need to catch all clicks on disabled menu
// not possible through _bind
.bind( "click.menu", $.proxy( function( event ) {
if ( this.options.disabled ) {
event.preventDefault();
}
}, this));
this._bind({
"click .ui-menu-item:has(a)": function( event ) {
event.stopImmediatePropagation();
var target = $( event.currentTarget );
// it's possible to click an item without hovering it (#7085)
if ( !this.active || ( this.active[ 0 ] !== target[ 0 ] ) ) {
this.focus( event, target );
}
this.select( event );
},
"mouseover .ui-menu-item": function( event ) {
event.stopImmediatePropagation();
if ( !this.isScrolling ) {
var target = $( event.currentTarget );
// Remove ui-state-active class from siblings of the newly focused menu item to avoid a jump caused by adjacent elements both having a class with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
}
this.isScrolling = false;
},
"mouseleave": "collapseAll",
"mouseleave .ui-menu": "collapseAll",
"mouseout .ui-menu-item": "blur",
"focus": function( event ) {
this.focus( event, $( event.target ).children( ".ui-menu-item:first" ) );
},
blur: function( event ) {
this._delay( function() {
if ( ! $.contains( this.element[0], this.document[0].activeElement ) ) {
this.collapseAll( event );
}
}, 0);
},
scroll: function( event ) {
// Keep track of scrolling to prevent mouseover from firing inadvertently when scrolling the menu
this.isScrolling = true;
}
});
this.refresh();
this.element.attr( "tabIndex", 0 );
this._bind({
"keydown": function( event ) {
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
event.preventDefault();
event.stopImmediatePropagation();
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
event.preventDefault();
event.stopImmediatePropagation();
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
event.preventDefault();
event.stopImmediatePropagation();
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
event.preventDefault();
event.stopImmediatePropagation();
break;
case $.ui.keyCode.UP:
this.previous( event );
event.preventDefault();
event.stopImmediatePropagation();
break;
case $.ui.keyCode.DOWN:
this.next( event );
event.preventDefault();
event.stopImmediatePropagation();
break;
case $.ui.keyCode.LEFT:
if (this.collapse( event )) {
event.stopImmediatePropagation();
}
event.preventDefault();
break;
case $.ui.keyCode.RIGHT:
if (this.expand( event )) {
event.stopImmediatePropagation();
}
event.preventDefault();
break;
case $.ui.keyCode.ENTER:
if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
if ( this.expand( event ) ) {
event.stopImmediatePropagation();
}
}
else {
this.select( event );
event.stopImmediatePropagation();
}
event.preventDefault();
break;
case $.ui.keyCode.ESCAPE:
if ( this.collapse( event ) ) {
event.stopImmediatePropagation();
}
event.preventDefault();
break;
default:
event.stopPropagation();
clearTimeout( this.filterTimer );
var match,
prev = this.previousFilter || "",
character = String.fromCharCode( event.keyCode ),
skip = false;
if (character == prev) {
skip = true;
} else {
character = prev + character;
}
function escape( value ) {
return value.replace( /[-[\]{}()*+?.,\\^$|#\s]/g , "\\$&" );
}
match = this.activeMenu.children( ".ui-menu-item" ).filter( function() {
return new RegExp("^" + escape(character), "i")
.test( $( this ).children( "a" ).text() );
});
match = skip && match.index(this.active.next()) != -1 ? this.active.nextAll(".ui-menu-item") : match;
if ( !match.length ) {
character = String.fromCharCode(event.keyCode);
match = this.activeMenu.children(".ui-menu-item").filter( function() {
return new RegExp("^" + escape(character), "i")
.test( $( this ).children( "a" ).text() );
});
}
if ( match.length ) {
this.focus( event, match );
if (match.length > 1) {
this.previousFilter = character;
this.filterTimer = this._delay( function() {
delete this.previousFilter;
}, 1000 );
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
}
});
this._bind( this.document, {
click: function( event ) {
if ( !$( event.target ).closest( ".ui-menu" ).length ) {
this.collapseAll( event );
}
}
});
if ( this.options.trigger ) {
this.element.popup({
trigger: this.options.trigger,
managed: true,
focusPopup: $.proxy( function( event, ui ) {
this.focus( event, this.element.children( ".ui-menu-item" ).first() );
this.element.focus( 1 );
}, this)
});
}
},
_destroy: function() {
//destroy (sub)menus
if ( this.options.trigger ) {
this.element.popup( "destroy" );
}
this.element
.removeAttr( "aria-activedescendant" )
.find( ".ui-menu" )
.andSelf()
.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.show();
//destroy menu items
this.element.find( ".ui-menu-item" )
.unbind( ".menu" )
.removeClass( "ui-menu-item" )
.removeAttr( "role" )
.children( "a" )
.removeClass( "ui-corner-all ui-state-hover" )
.removeAttr( "tabIndex" )
.removeAttr( "role" )
.removeAttr( "aria-haspopup" )
.removeAttr( "id" )
.children( ".ui-icon" )
.remove();
},
refresh: function() {
// initialize nested menus
var submenus = this.element.find( this.options.items + ":not( .ui-menu )" )
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.attr( "role", "menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" );
// don't refresh list items that are already adapted
var menuId = this.menuId;
submenus.add( this.element ).children( ":not( .ui-menu-item ):has( a )" )
.addClass( "ui-menu-item" )
.attr( "role", "presentation" )
.children( "a" )
.addClass( "ui-corner-all" )
.attr( "tabIndex", -1 )
.attr( "role", "menuitem" )
.attr( "id", function( i ) {
return menuId + "-" + i;
});
submenus.each( function() {
var menu = $( this ),
item = menu.prev( "a" );
item.attr( "aria-haspopup", "true" )
.prepend( '<span class="ui-menu-icon ui-icon ui-icon-carat-1-e"></span>' );
menu.attr( "aria-labelledby", item.attr( "id" ) );
});
},
focus: function( event, item ) {
this.blur( event );
if ( this._hasScroll() ) {
var borderTop = parseFloat( $.curCSS( this.activeMenu[0], "borderTopWidth", true ) ) || 0,
paddingTop = parseFloat( $.curCSS( this.activeMenu[0], "paddingTop", true ) ) || 0,
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop,
scroll = this.activeMenu.scrollTop(),
elementHeight = this.activeMenu.height(),
itemHeight = item.height();
if ( offset < 0 ) {
this.activeMenu.scrollTop( scroll + offset );
} else if ( offset + itemHeight > elementHeight ) {
this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
}
}
this.active = item.first()
.children( "a" )
.addClass( "ui-state-focus" )
.end();
this.element.attr( "aria-activedescendant", this.active.children( "a" ).attr( "id" ) );
// highlight active parent menu item, if any
this.active.parent().closest( ".ui-menu-item" ).children( "a:first" ).addClass( "ui-state-active" );
this.timer = this._delay( function() {
this._close();
}, this.delay );
var nested = $( "> .ui-menu", item );
if ( nested.length && ( /^mouse/.test( event.type ) ) ) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger( "focus", event, { item: item } );
},
blur: function( event ) {
if ( !this.active ) {
return;
}
clearTimeout( this.timer );
this.active.children( "a" ).removeClass( "ui-state-focus" );
this.active = null;
this._trigger( "blur", event, { item: this.active } );
},
_startOpening: function( submenu ) {
clearTimeout( this.timer );
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if ( submenu.attr( "aria-hidden" ) !== "true" ) {
return;
}
this.timer = this._delay( function() {
this._close();
this._open( submenu );
}, this.delay );
},
_open: function( submenu ) {
clearTimeout( this.timer );
this.element
.find( ".ui-menu" )
.not( submenu.parents() )
.hide()
.attr( "aria-hidden", "true" );
var position = $.extend({}, {
of: this.active
}, $.type(this.options.position) == "function"
? this.options.position(this.active)
: this.options.position
);
submenu.show()
.removeAttr( "aria-hidden" )
.attr( "aria-expanded", "true" )
.position( position );
},
collapseAll: function( event, all ) {
// if we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
// if we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if ( !currentMenu.length ) {
currentMenu = this.element;
}
this._close( currentMenu );
this.blur( event );
this.activeMenu = currentMenu;
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function( startMenu ) {
if ( !startMenu ) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find( ".ui-menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" )
.end()
.find( "a.ui-state-active" )
.removeClass( "ui-state-active" );
},
collapse: function( event ) {
var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element );
if ( newItem && newItem.length ) {
this._close();
this.focus( event, newItem );
return true;
}
},
expand: function( event ) {
var newItem = this.active && this.active.children( ".ui-menu " ).children( ".ui-menu-item" ).first();
if ( newItem && newItem.length ) {
this._open( newItem.parent() );
//timeout so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay( function() {
this.focus( event, newItem );
}, 20 );
return true;
}
},
next: function(event) {
this._move( "next", "first", event );
},
previous: function(event) {
this._move( "prev", "last", event );
},
first: function() {
return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
},
last: function() {
return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
},
_move: function( direction, filter, event ) {
if ( !this.active ) {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )[ filter ]() );
return;
}
var next;
if ( direction === "first" || direction === "last" ) {
next = this.active[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ).eq( -1 );
} else {
next = this.active[ direction + "All" ]( ".ui-menu-item" ).eq( 0 );
}
if ( next.length ) {
this.focus( event, next );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )[ filter ]() );
}
},
nextPage: function( event ) {
if ( this._hasScroll() ) {
if ( !this.active ) {
this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
return;
}
if ( this.last() ) {
return;
}
var base = this.active.offset().top,
height = this.element.height(),
result;
this.active.nextAll( ".ui-menu-item" ).each( function() {
result = $( this );
return $( this ).offset().top - base - height < 0;
});
this.focus( event, result );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )
[ !this.active ? "first" : "last" ]() );
}
},
previousPage: function( event ) {
if ( this._hasScroll() ) {
if ( !this.active ) {
this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
return;
}
if ( this.first() ) {
return;
}
var base = this.active.offset().top,
height = this.element.height(),
result;
this.active.prevAll( ".ui-menu-item" ).each( function() {
result = $( this );
return $(this).offset().top - base + height > 0;
});
this.focus( event, result );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
}
},
_hasScroll: function() {
return this.element.height() < this.element.prop( "scrollHeight" );
},
select: function( event ) {
// save active reference before collapseAll triggers blur
var ui = {
item: this.active
};
this.collapseAll( event, true );
if ( this.options.trigger ) {
$( this.options.trigger ).focus( 1 );
this.element.popup( "close" );
}
this._trigger( "select", event, ui );
}
});
}( jQuery ));
/*
* jQuery UI Autocomplete @VERSION
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Autocomplete
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.ui.menu.js
*/
(function( $, undefined ) {
// used to prevent race conditions with remote data sources
var requestIndex = 0;
$.widget( "ui.autocomplete", {
version: "@VERSION",
defaultElement: "<input>",
options: {
appendTo: "body",
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
pending: 0,
_create: function() {
var self = this,
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
suppressKeyPress,
suppressKeyPressRepeat,
suppressInput;
this.valueMethod = this.element[ this.element.is( "input,textarea" ) ? "val" : "text" ];
this.element
.addClass( "ui-autocomplete-input" )
.attr( "autocomplete", "off" )
// TODO verify these actually work as intended
.attr({
role: "textbox",
"aria-autocomplete": "list",
"aria-haspopup": "true"
})
.bind( "keydown.autocomplete", function( event ) {
if ( self.options.disabled || self.element.prop( "readOnly" ) ) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
self._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
self._move( "nextPage", event );
break;
case keyCode.UP:
suppressKeyPress = true;
self._move( "previous", event );
// prevent moving cursor to beginning of text field in some browsers
event.preventDefault();
break;
case keyCode.DOWN:
suppressKeyPress = true;
self._move( "next", event );
// prevent moving cursor to end of text field in some browsers
event.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if ( self.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
}
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
if ( !self.menu.active ) {
return;
}
self.menu.select( event );
break;
case keyCode.ESCAPE:
if ( self.menu.element.is(":visible") ) {
self._value( self.term );
self.close( event );
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
self._searchTimeout( event );
break;
}
})
.bind( "keypress.autocomplete", function( event ) {
if ( suppressKeyPress ) {
suppressKeyPress = false;
event.preventDefault();
return;
}
if ( suppressKeyPressRepeat ) {
return;
}
// replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
self._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
self._move( "nextPage", event );
break;
case keyCode.UP:
self._move( "previous", event );
// prevent moving cursor to beginning of text field in some browsers
event.preventDefault();
break;
case keyCode.DOWN:
self._move( "next", event );
// prevent moving cursor to end of text field in some browsers
event.preventDefault();
break;
}
})
.bind( "input.autocomplete", function(event) {
if ( suppressInput ) {
suppressInput = false;
event.preventDefault();
return;
}
self._searchTimeout( event );
})
.bind( "focus.autocomplete", function() {
if ( self.options.disabled ) {
return;
}
self.selectedItem = null;
self.previous = self._value();
})
.bind( "blur.autocomplete", function( event ) {
if ( self.options.disabled ) {
return;
}
clearTimeout( self.searching );
// clicks on the menu (or a button to trigger a search) will cause a blur event
self.closing = setTimeout(function() {
self.close( event );
self._change( event );
}, 150 );
});
this._initSource();
this.response = function() {
return self._response.apply( self, arguments );
};
this.menu = $( "<ul></ul>" )
.addClass( "ui-autocomplete" )
.appendTo( this.document.find( this.options.appendTo || "body" )[0] )
// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
.mousedown(function( event ) {
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = self.menu.element[ 0 ];
if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
setTimeout(function() {
self.document.one( 'mousedown', function( event ) {
if ( event.target !== self.element[ 0 ] &&
event.target !== menuElement &&
!$.contains( menuElement, event.target ) ) {
self.close();
}
});
}, 1 );
}
// use another timeout to make sure the blur-event-handler on the input was already triggered
setTimeout(function() {
clearTimeout( self.closing );
}, 13);
})
.menu({
// custom key handling for now
input: $(),
focus: function( event, ui ) {
var item = ui.item.data( "item.autocomplete" );
if ( false !== self._trigger( "focus", event, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( /^key/.test(event.originalEvent.type) ) {
self._value( item.value );
}
}
},
select: function( event, ui ) {
var item = ui.item.data( "item.autocomplete" ),
previous = self.previous;
// only trigger when focus was lost (click on menu)
if ( self.element[0] !== self.document[0].activeElement ) {
self.element.focus();
self.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
setTimeout(function() {
self.previous = previous;
self.selectedItem = item;
}, 1);
}
if ( false !== self._trigger( "select", event, { item: item } ) ) {
self._value( item.value );
}
// reset the term after the select event
// this allows custom select handling to work properly
self.term = self._value();
self.close( event );
self.selectedItem = item;
}
})
.zIndex( this.element.zIndex() + 1 )
.hide()
.data( "menu" );
if ( $.fn.bgiframe ) {
this.menu.element.bgiframe();
}
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._bind( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
});
},
_destroy: function() {
clearTimeout( this.searching );
this.element
.removeClass( "ui-autocomplete-input" )
.removeAttr( "autocomplete" )
.removeAttr( "role" )
.removeAttr( "aria-autocomplete" )
.removeAttr( "aria-haspopup" );
this.menu.element.remove();
},
_setOption: function( key, value ) {
this._super( "_setOption", key, value );
if ( key === "source" ) {
this._initSource();
}
if ( key === "appendTo" ) {
this.menu.element.appendTo( this.document.find( value || "body" )[0] );
}
if ( key === "disabled" && value && this.xhr ) {
this.xhr.abort();
}
},
_initSource: function() {
var self = this,
array,
url;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter(array, request.term) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( self.xhr ) {
self.xhr.abort();
}
self.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
autocompleteRequest: ++requestIndex,
success: function( data, status ) {
if ( this.autocompleteRequest === requestIndex ) {
response( data );
}
},
error: function() {
if ( this.autocompleteRequest === requestIndex ) {
response( [] );
}
}
});
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function( event ) {
var self = this;
clearTimeout( self.searching );
self.searching = setTimeout(function() {
// only search if the value has changed
if ( self.term !== self._value() ) {
self.selectedItem = null;
self.search( null, event );
}
}, self.options.delay );
},
search: function( value, event ) {
value = value != null ? value : this._value();
// always save the actual value, not the one passed as an argument
this.term = this._value();
if ( value.length < this.options.minLength ) {
return this.close( event );
}
clearTimeout( this.closing );
if ( this._trigger( "search", event ) === false ) {
return;
}
return this._search( value );
},
_search: function( value ) {
this.pending++;
this.element.addClass( "ui-autocomplete-loading" );
this.source( { term: value }, this.response );
},
_response: function( content ) {
if ( content ) {
content = this._normalize( content );
}
this._trigger( "response", null, { content: content } );
if ( !this.options.disabled && content && content.length ) {
this._suggest( content );
this._trigger( "open" );
} else {
this.close();
}
this.pending--;
if ( !this.pending ) {
this.element.removeClass( "ui-autocomplete-loading" );
}
},
close: function( event ) {
clearTimeout( this.closing );
if ( this.menu.element.is(":visible") ) {
this.menu.element.hide();
this.menu.blur();
this._trigger( "close", event );
}
},
_change: function( event ) {
if ( this.previous !== this._value() ) {
this._trigger( "change", event, { item: this.selectedItem } );
}
},
_normalize: function( items ) {
// assume all items have the right format when the first item is complete
if ( items.length && items[0].label && items[0].value ) {
return items;
}
return $.map( items, function(item) {
if ( typeof item === "string" ) {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item );
});
},
_suggest: function( items ) {
var ul = this.menu.element
.empty()
.zIndex( this.element.zIndex() + 1 );
this._renderMenu( ul, items );
// TODO refresh should check if the active item is still in the dom, removing the need for a manual blur
this.menu.blur();
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend({
of: this.element
}, this.options.position ));
if ( this.options.autoFocus ) {
this.menu.next( new $.Event("mouseover") );
}
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width( "" ).outerWidth() + 1,
this.element.outerWidth()
) );
},
_renderMenu: function( ul, items ) {
var self = this;
$.each( items, function( index, item ) {
self._renderItem( ul, item );
});
},
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).text( item.label ) )
.appendTo( ul );
},
_move: function( direction, event ) {
if ( !this.menu.element.is(":visible") ) {
this.search( null, event );
return;
}
if ( this.menu.first() && /^previous/.test(direction) ||
this.menu.last() && /^next/.test(direction) ) {
this._value( this.term );
this.menu.blur();
return;
}
this.menu[ direction ]( event );
},
widget: function() {
return this.menu.element;
},
extraData2: function ( value ) {
return this.options;
},
_value: function( value ) {
return this.valueMethod.apply( this.element, arguments );
}
});
$.extend( $.ui.autocomplete, {
escapeRegex: function( value ) {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
},
filter: function(array, term) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( value.label || value.value || value );
});
}
});
}( jQuery ));
/*
* jQuery UI Tabs @VERSION
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Tabs
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function( $, undefined ) {
var tabId = 0;
function getNextTabId() {
return ++tabId;
}
var isLocal = (function() {
var rhash = /#.*$/,
currentPage = location.href.replace( rhash, "" );
return function( anchor ) {
// clone the node to work around IE 6 not normalizing the href property
// if it's manually set, i.e., a.href = "#foo" kills the normalization
anchor = anchor.cloneNode( false );
return anchor.hash.length > 1 &&
anchor.href.replace( rhash, "" ) === currentPage;
};
})();
$.widget( "ui.tabs", {
version: "@VERSION",
options: {
active: null,
collapsible: false,
event: "click",
fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
// callbacks
activate: null,
beforeActivate: null,
beforeLoad: null,
load: null
},
_create: function() {
var that = this,
options = that.options,
active = options.active;
that.running = false;
that.element.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" );
that._processTabs();
if ( active === null ) {
// check the fragment identifier in the URL
if ( location.hash ) {
that.anchors.each(function( i, tab ) {
if ( tab.hash === location.hash ) {
active = i;
return false;
}
});
}
// check for a tab marked active via a class
if ( active === null ) {
active = that.lis.filter( ".ui-tabs-active" ).index();
}
// no active tab, set to false
if ( active === null || active === -1 ) {
active = that.lis.length ? 0 : false;
}
}
// handle numbers: negative, out of range
if ( active !== false ) {
active = this.lis.eq( active ).index();
if ( active === -1 ) {
active = options.collapsible ? false : 0;
}
}
options.active = active;
// don't allow collapsible: false and active: false
if ( !options.collapsible && options.active === false && this.anchors.length ) {
options.active = 0;
}
// Take disabling tabs via class attribute from HTML
// into account and update option properly.
if ( $.isArray( options.disabled ) ) {
options.disabled = $.unique( options.disabled.concat(
$.map( this.lis.filter( ".ui-state-disabled" ), function( n, i ) {
return that.lis.index( n );
})
) ).sort();
}
this._setupFx( options.fx );
this._refresh();
// highlight selected tab
this.panels.hide();
this.lis.removeClass( "ui-tabs-active ui-state-active" );
// check for length avoids error when initializing empty list
if ( options.active !== false && this.anchors.length ) {
this.active = this._findActive( options.active );
var panel = that._getPanelForTab( this.active );
panel.show();
this.lis.eq( options.active ).addClass( "ui-tabs-active ui-state-active" );
this.load( options.active );
} else {
this.active = $();
}
},
_setOption: function( key, value ) {
if ( key == "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "disabled" ) {
// don't use the widget factory's disabled handling
this._setupDisabled( value );
return;
}
this._super( "_setOption", key, value);
// setting collapsible: false while collapsed; open first panel
if ( key === "collapsible" && !value && this.options.active === false ) {
this._activate( 0 );
}
if ( key === "event" ) {
this._setupEvents( value );
}
if ( key === "fx" ) {
this._setupFx( value );
}
},
_tabId: function( a ) {
return $( a ).attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
},
_sanitizeSelector: function( hash ) {
// we need this because an id may contain a ":"
return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@[\]^`{|}~]/g, "\\$&" ) : "";
},
refresh: function() {
var self = this,
options = this.options,
lis = this.list.children( ":has(a[href])" );
// get disabled tabs from class attribute from HTML
// this will get converted to a boolean if needed in _refresh()
options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
return lis.index( tab );
});
this._processTabs();
this._refresh();
this.panels.not( this._getPanelForTab( this.active ) ).hide();
// was collapsed or no tabs
if ( options.active === false || !this.anchors.length ) {
options.active = false;
this.active = $();
// was active, but active tab is gone
} else if ( this.active.length && !$.contains( this.list[ 0 ], this.active[ 0 ] ) ) {
// activate previous tab
var next = options.active - 1;
this._activate( next >= 0 ? next : 0 );
// was active, active tab still exists
} else {
// make sure active index is correct
options.active = this.anchors.index( this.active );
}
},
_refresh: function() {
var options = this.options;
this.element.toggleClass( "ui-tabs-collapsible", options.collapsible );
this.list.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" );
this.lis.addClass( "ui-state-default ui-corner-top" );
this.panels.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" );
this._setupDisabled( options.disabled );
this._setupEvents( options.event );
// remove all handlers, may run on existing tabs
this.lis.unbind( ".tabs" );
this._focusable( this.lis );
this._hoverable( this.lis );
},
_processTabs: function() {
var self = this;
this.list = this.element.find( "ol,ul" ).eq( 0 );
this.lis = $( " > li:has(a[href])", this.list );
this.anchors = this.lis.map(function() {
return $( "a", this )[ 0 ];
});
this.panels = $( [] );
this.anchors.each(function( i, a ) {
var selector, panel;
// inline tab
if ( isLocal( a ) ) {
selector = a.hash;
panel = self.element.find( self._sanitizeSelector( selector ) );
// remote tab
} else {
var id = self._tabId( a );
selector = "#" + id;
panel = self.element.find( selector );
if ( !panel.length ) {
panel = self._createPanel( id );
panel.insertAfter( self.panels[ i - 1 ] || self.list );
}
}
if ( panel.length) {
self.panels = self.panels.add( panel );
}
$( a ).attr( "aria-controls", selector.substring( 1 ) );
});
},
_createPanel: function( id ) {
return $( "<div></div>" )
.attr( "id", id )
.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
.data( "destroy.tabs", true );
},
_setupDisabled: function( disabled ) {
if ( $.isArray( disabled ) ) {
if ( !disabled.length ) {
disabled = false;
} else if ( disabled.length === this.anchors.length ) {
disabled = true;
}
}
// disable tabs
for ( var i = 0, li; ( li = this.lis[ i ] ); i++ ) {
$( li ).toggleClass( "ui-state-disabled", ( disabled === true || $.inArray( i, disabled ) !== -1 ) );
}
this.options.disabled = disabled;
},
_setupFx: function( fx ) {
// set up animations
if ( fx ) {
if ( $.isArray( fx ) ) {
this.hideFx = fx[ 0 ];
this.showFx = fx[ 1 ];
} else {
this.hideFx = this.showFx = fx;
}
}
},
// TODO: remove once jQuery core properly removes filters - see #4621
_resetStyle: function ( $el, fx ) {
if ( !$.support.opacity && fx.opacity ) {
$el[ 0 ].style.removeAttribute( "filter" );
}
},
_setupEvents: function( event ) {
// attach tab event handler, unbind to avoid duplicates from former tabifying...
this.anchors.unbind( ".tabs" );
if ( event ) {
this.anchors.bind( event.split( " " ).join( ".tabs " ) + ".tabs",
$.proxy( this, "_eventHandler" ) );
}
// disable click in any case
this.anchors.bind( "click.tabs", function( event ){
event.preventDefault();
});
},
_eventHandler: function( event ) {
var that = this,
options = that.options,
active = that.active,
clicked = $( event.currentTarget ),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : that._getPanelForTab( clicked ),
toHide = !active.length ? $() : that._getPanelForTab( active ),
tab = clicked.closest( "li" ),
eventData = {
oldTab: active,
oldPanel: toHide,
newTab: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if ( tab.hasClass( "ui-state-disabled" ) ||
// tab is already loading
tab.hasClass( "ui-tabs-loading" ) ||
// can't switch durning an animation
that.running ||
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( that._trigger( "beforeActivate", event, eventData ) === false ) ) {
clicked[ 0 ].blur();
return;
}
options.active = collapsing ? false : that.anchors.index( clicked );
that.active = clickedIsActive ? $() : clicked;
if ( that.xhr ) {
that.xhr.abort();
}
if ( !toHide.length && !toShow.length ) {
throw "jQuery UI Tabs: Mismatching fragment identifier.";
}
if ( toShow.length ) {
// TODO make passing in node possible
that.load( that.anchors.index( clicked ), event );
clicked[ 0 ].blur();
}
that._toggle( event, eventData );
},
// handles show/hide for selecting tabs
_toggle: function( event, eventData ) {
var that = this,
options = that.options,
toShow = eventData.newPanel,
toHide = eventData.oldPanel;
that.running = true;
function complete() {
that.running = false;
that._trigger( "activate", event, eventData );
}
function show() {
eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
if ( toShow.length && that.showFx ) {
toShow
.animate( that.showFx, that.showFx.duration || "normal", function() {
that._resetStyle( $( this ), that.showFx );
complete();
});
} else {
toShow.show();
complete();
}
}
// start out by hiding, then showing, then completing
if ( toHide.length && that.hideFx ) {
toHide.animate( that.hideFx, that.hideFx.duration || "normal", function() {
eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
that._resetStyle( $( this ), that.hideFx );
show();
});
} else {
eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
toHide.hide();
show();
}
},
_activate: function( index ) {
var active = this._findActive( index )[ 0 ];
// trying to activate the already active panel
if ( active === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the current active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function( selector ) {
return typeof selector === "number" ? this.anchors.eq( selector ) :
typeof selector === "string" ? this.anchors.filter( "[href$='" + selector + "']" ) : $();
},
_getIndex: function( index ) {
// meta-function to give users option to provide a href string instead of a numerical index.
// also sanitizes numerical indexes to valid values.
if ( typeof index == "string" ) {
index = this.anchors.index( this.anchors.filter( "[href$=" + index + "]" ) );
}
return index;
},
_destroy: function() {
var o = this.options;
if ( this.xhr ) {
this.xhr.abort();
}
this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
this.list.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" );
this.anchors
.unbind( ".tabs" )
.removeData( "href.tabs" )
.removeData( "load.tabs" );
this.lis.unbind( ".tabs" ).add( this.panels ).each(function() {
if ( $.data( this, "destroy.tabs" ) ) {
$( this ).remove();
} else {
$( this ).removeClass([
"ui-state-default",
"ui-corner-top",
"ui-tabs-active",
"ui-state-active",
"ui-state-disabled",
"ui-tabs-panel",
"ui-widget-content",
"ui-corner-bottom"
].join( " " ) );
}
});
return this;
},
enable: function( index ) {
var disabled = this.options.disabled;
if ( disabled === false ) {
return;
}
if ( index === undefined ) {
disabled = false;
} else {
index = this._getIndex( index );
if ( $.isArray( disabled ) ) {
disabled = $.map( disabled, function( num ) {
return num !== index ? num : null;
});
} else {
disabled = $.map( this.lis, function( li, num ) {
return num !== index ? num : null;
});
}
}
this._setupDisabled( disabled );
},
disable: function( index ) {
var disabled = this.options.disabled;
if ( disabled === true ) {
return;
}
if ( index === undefined ) {
disabled = true;
} else {
index = this._getIndex( index );
if ( $.inArray( index, disabled ) !== -1 ) {
return;
}
if ( $.isArray( disabled ) ) {
disabled = $.merge( [ index ], disabled ).sort();
} else {
disabled = [ index ];
}
}
this._setupDisabled( disabled );
},
load: function( index, event ) {
index = this._getIndex( index );
var self = this,
options = this.options,
anchor = this.anchors.eq( index ),
panel = self._getPanelForTab( anchor ),
eventData = {
tab: anchor,
panel: panel
};
// not remote
if ( isLocal( anchor[ 0 ] ) ) {
return;
}
this.xhr = $.ajax({
url: anchor.attr( "href" ),
beforeSend: function( jqXHR, settings ) {
return self._trigger( "beforeLoad", event,
$.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) );
}
});
if ( this.xhr ) {
this.lis.eq( index ).addClass( "ui-tabs-loading" );
this.xhr
.success(function( response ) {
// TODO: IE resolves cached XHRs immediately
// remove when core #10467 is fixed
setTimeout(function() {
panel.html( response );
self._trigger( "load", event, eventData );
}, 1 );
})
.complete(function( jqXHR, status ) {
// TODO: IE resolves cached XHRs immediately
// remove when core #10467 is fixed
setTimeout(function() {
if ( status === "abort" ) {
self.panels.stop( false, true );
}
self.lis.eq( index ).removeClass( "ui-tabs-loading" );
if ( jqXHR === self.xhr ) {
delete self.xhr;
}
}, 1 );
});
}
return this;
},
_getPanelForTab: function( tab ) {
var id = $( tab ).attr( "aria-controls" );
return this.element.find( this._sanitizeSelector( "#" + id ) );
}
});
// DEPRECATED
if ( $.uiBackCompat !== false ) {
// helper method for a lot of the back compat extensions
$.ui.tabs.prototype._ui = function( tab, panel ) {
return {
tab: tab,
panel: panel,
index: this.anchors.index( tab )
};
};
// url method
(function( $, prototype ) {
prototype.url = function( index, url ) {
this.anchors.eq( index ).attr( "href", url );
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// ajaxOptions and cache options
(function( $, prototype ) {
$.extend( prototype.options, {
ajaxOptions: null,
cache: false
});
var _create = prototype._create,
_setOption = prototype._setOption,
_destroy = prototype._destroy,
oldurl = prototype.url || $.noop;
$.extend( prototype, {
_create: function() {
_create.call( this );
var self = this;
this.element.bind( "tabsbeforeload.tabs", function( event, ui ) {
// tab is already cached
if ( $.data( ui.tab[ 0 ], "cache.tabs" ) ) {
event.preventDefault();
return;
}
$.extend( ui.ajaxSettings, self.options.ajaxOptions, {
error: function( xhr, s, e ) {
try {
// Passing index avoid a race condition when this method is
// called after the user has selected another tab.
// Pass the anchor that initiated this request allows
// loadError to manipulate the tab content panel via $(a.hash)
self.options.ajaxOptions.error( xhr, s, ui.tab.closest( "li" ).index(), ui.tab[ 0 ] );
}
catch ( e ) {}
}
});
ui.jqXHR.success(function() {
if ( self.options.cache ) {
$.data( ui.tab[ 0 ], "cache.tabs", true );
}
});
});
},
_setOption: function( key, value ) {
// reset cache if switching from cached to not cached
if ( key === "cache" && value === false ) {
this.anchors.removeData( "cache.tabs" );
}
_setOption.apply( this, arguments );
},
_destroy: function() {
this.anchors.removeData( "cache.tabs" );
_destroy.call( this );
},
url: function( index, url ){
this.anchors.eq( index ).removeData( "cache.tabs" );
oldurl.apply( this, arguments );
}
});
}( jQuery, jQuery.ui.tabs.prototype ) );
// abort method
(function( $, prototype ) {
prototype.abort = function() {
if ( this.xhr ) {
this.xhr.abort();
}
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// spinner
$.widget( "ui.tabs", $.ui.tabs, {
options: {
spinner: "<em>Loading…</em>"
},
_create: function() {
this._super( "_create" );
this._bind({
tabsbeforeload: function( event, ui ) {
if ( !this.options.spinner ) {
return;
}
var span = ui.tab.find( "span" ),
html = span.html();
span.html( this.options.spinner );
ui.jqXHR.complete(function() {
span.html( html );
});
}
});
}
});
// enable/disable events
(function( $, prototype ) {
$.extend( prototype.options, {
enable: null,
disable: null
});
var enable = prototype.enable,
disable = prototype.disable;
prototype.enable = function( index ) {
var options = this.options,
trigger;
if ( index && options.disabled === true ||
( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) !== -1 ) ) {
trigger = true;
}
enable.apply( this, arguments );
if ( trigger ) {
this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
}
};
prototype.disable = function( index ) {
var options = this.options,
trigger;
if ( index && options.disabled === false ||
( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) === -1 ) ) {
trigger = true;
}
disable.apply( this, arguments );
if ( trigger ) {
this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
}
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// add/remove methods and events
(function( $, prototype ) {
$.extend( prototype.options, {
add: null,
remove: null,
tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>"
});
prototype.add = function( url, label, index ) {
if ( index === undefined ) {
index = this.anchors.length;
}
var options = this.options,
li = $( options.tabTemplate
.replace( /#\{href\}/g, url )
.replace( /#\{label\}/g, label ) ),
id = !url.indexOf( "#" ) ?
url.replace( "#", "" ) :
this._tabId( li.find( "a" )[ 0 ] );
li.addClass( "ui-state-default ui-corner-top" ).data( "destroy.tabs", true );
li.find( "a" ).attr( "aria-controls", id );
var doInsertAfter = index >= this.lis.length;
// try to find an existing element before creating a new one
var panel = this.element.find( "#" + id );
if ( !panel.length ) {
panel = this._createPanel( id );
if ( doInsertAfter ) {
if ( index > 0 ) {
panel.insertAfter( this.panels.eq( -1 ) );
} else {
panel.appendTo( this.element );
}
} else {
panel.insertBefore( this.panels[ index ] );
}
}
panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ).hide();
if ( doInsertAfter ) {
li.appendTo( this.list );
} else {
li.insertBefore( this.lis[ index ] );
}
options.disabled = $.map( options.disabled, function( n ) {
return n >= index ? ++n : n;
});
this.refresh();
if ( this.lis.length === 1 && options.active === false ) {
this.option( "active", 0 );
}
this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
return this;
};
prototype.remove = function( index ) {
index = this._getIndex( index );
var options = this.options,
tab = this.lis.eq( index ).remove(),
panel = this._getPanelForTab( tab.find( "a[aria-controls]" ) ).remove();
// If selected tab was removed focus tab to the right or
// in case the last tab was removed the tab to the left.
// We check for more than 2 tabs, because if there are only 2,
// then when we remove this tab, there will only be one tab left
// so we don't need to detect which tab to activate.
if ( tab.hasClass( "ui-tabs-active" ) && this.anchors.length > 2 ) {
this._activate( index + ( index + 1 < this.anchors.length ? 1 : -1 ) );
}
options.disabled = $.map(
$.grep( options.disabled, function( n ) {
return n !== index;
}),
function( n ) {
return n >= index ? --n : n;
});
this.refresh();
this._trigger( "remove", null, this._ui( tab.find( "a" )[ 0 ], panel[ 0 ] ) );
return this;
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// length method
(function( $, prototype ) {
prototype.length = function() {
return this.anchors.length;
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// panel ids (idPrefix option + title attribute)
(function( $, prototype ) {
$.extend( prototype.options, {
idPrefix: "ui-tabs-"
});
var _tabId = prototype._tabId;
prototype._tabId = function( a ) {
return $( a ).attr( "aria-controls" ) ||
a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF-]/g, "" ) ||
this.options.idPrefix + getNextTabId();
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// _createPanel method
(function( $, prototype ) {
$.extend( prototype.options, {
panelTemplate: "<div></div>"
});
var _createPanel = prototype._createPanel;
prototype._createPanel = function( id ) {
return $( this.options.panelTemplate )
.attr( "id", id )
.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
.data( "destroy.tabs", true );
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// selected option
(function( $, prototype ) {
var _create = prototype._create,
_setOption = prototype._setOption,
_eventHandler = prototype._eventHandler;
prototype._create = function() {
var options = this.options;
if ( options.active === null && options.selected !== undefined ) {
options.active = options.selected === -1 ? false : options.selected;
}
_create.call( this );
options.selected = options.active;
if ( options.selected === false ) {
options.selected = -1;
}
};
prototype._setOption = function( key, value ) {
if ( key !== "selected" ) {
return _setOption.apply( this, arguments );
}
var options = this.options;
_setOption.call( this, "active", value === -1 ? false : value );
options.selected = options.active;
if ( options.selected === false ) {
options.selected = -1;
}
};
prototype._eventHandler = function( event ) {
_eventHandler.apply( this, arguments );
this.options.selected = this.options.active;
if ( this.options.selected === false ) {
this.options.selected = -1;
}
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// show and select event
(function( $, prototype ) {
$.extend( prototype.options, {
show: null,
select: null
});
var _create = prototype._create,
_trigger = prototype._trigger;
prototype._create = function() {
_create.call( this );
if ( this.options.active !== false ) {
this._trigger( "show", null, this._ui(
this.active[ 0 ], this._getPanelForTab( this.active )[ 0 ] ) );
}
};
prototype._trigger = function( type, event, data ) {
var ret = _trigger.apply( this, arguments );
if ( !ret ) {
return false;
}
if ( type === "beforeActivate" && data.newTab.length ) {
ret = _trigger.call( this, "select", event, {
tab: data.newTab[ 0],
panel: data.newPanel[ 0 ],
index: data.newTab.closest( "li" ).index()
});
} else if ( type === "activate" && data.newTab.length ) {
ret = _trigger.call( this, "show", event, {
tab: data.newTab[ 0 ],
panel: data.newPanel[ 0 ],
index: data.newTab.closest( "li" ).index()
});
}
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// select method
(function( $, prototype ) {
prototype.select = function( index ) {
index = this._getIndex( index );
if ( index === -1 ) {
if ( this.options.collapsible && this.options.selected !== -1 ) {
index = this.options.selected;
} else {
return;
}
}
this.anchors.eq( index ).trigger( this.options.event + ".tabs" );
};
}( jQuery, jQuery.ui.tabs.prototype ) );
// cookie option
var listId = 0;
function getNextListId() {
return ++listId;
}
$.widget( "ui.tabs", $.ui.tabs, {
options: {
cookie: null // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
},
_create: function() {
var options = this.options,
active;
if ( options.active == null && options.cookie ) {
active = parseInt( this._cookie(), 10 );
if ( active === -1 ) {
active = false;
}
options.active = active;
}
this._super( "_create" );
},
_cookie: function( active ) {
var cookie = [ this.cookie ||
( this.cookie = this.options.cookie.name || "ui-tabs-" + getNextListId() ) ];
if ( arguments.length ) {
cookie.push( active === false ? -1 : active );
cookie.push( this.options.cookie );
}
return $.cookie.apply( null, cookie );
},
_refresh: function() {
this._super( "_refresh" );
if ( this.options.cookie ) {
this._cookie( this.options.active, this.options.cookie );
}
},
_eventHandler: function( event ) {
this._superApply( "_eventHandler", arguments );
if ( this.options.cookie ) {
this._cookie( this.options.active, this.options.cookie );
}
},
_destroy: function() {
this._super( "_destroy" );
if ( this.options.cookie ) {
this._cookie( null, this.options.cookie );
}
}
});
// load event
$.widget( "ui.tabs", $.ui.tabs, {
_trigger: function( type, event, data ) {
var _data = $.extend( {}, data );
if ( type === "load" ) {
_data.panel = _data.panel[ 0 ];
_data.tab = _data.tab[ 0 ];
}
return this._super( "_trigger", type, event, _data );
}
});
}
})( jQuery );
| {'content_hash': '3aad31681b1a8b08b5517a228dfecc60', 'timestamp': '', 'source': 'github', 'line_count': 3321, 'max_line_length': 190, 'avg_line_length': 27.445950015055708, 'alnum_prop': 0.6010993110106639, 'repo_name': 'bmaltzan/jquery-ui-datacomplete', 'id': '3bfede39ca198610bb6ac5d1fa45751caffd7619', 'size': '91358', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/jquery-ui.1.9.pre.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '714721'}]} |
<?php
namespace Omnipay\Oppwa\Message;
abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest
{
const API_VERSION = 'v1';
protected $testEndpoint = 'https://eu-test.oppwa.com';
protected $liveEndpoint = 'https://eu-prod.oppwa.com';
public function getIntegrationType()
{
return $this->getParameter('integrationType');
}
public function setIntegrationType($value)
{
return $this->setParameter('integrationType', $value);
}
public function getToken()
{
return $this->getParameter('token');
}
public function setToken($value)
{
return $this->setParameter('token', $value);
}
public function getEntityId()
{
return $this->getParameter('entityId');
}
public function setEntityId($value)
{
return $this->setParameter('entityId', $value);
}
protected function getEndpoint()
{
$base = $this->getTestMode() ? $this->testEndpoint : $this->liveEndpoint;
return $base . '/' . self::API_VERSION;
}
protected function getHttpMethod()
{
return 'POST';
}
public function sendData($data)
{
$params = array(
'entityId' => $this->getEntityId()
);
$http_query = $this->getHttpMethod() === 'GET' ? '?' . http_build_query($params) : '';
$body = $this->getHttpMethod() === 'POST' ? array_merge($params, $data) : null;
$httpResponse = $this->httpClient->request(
$this->getHttpMethod(),
$this->getEndpoint() . $http_query,
array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Bearer '.$this->getToken()
),
$body ? http_build_query($body) : null
);
return $this->response = new Response(
$this,
json_decode($httpResponse->getBody(), true),
$httpResponse->getStatusCode()
);
}
}
| {'content_hash': 'd21f0cd501708ee15f97c7afc15ba607', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 94, 'avg_line_length': 25.556962025316455, 'alnum_prop': 0.5656265477959386, 'repo_name': 'vdbelt/omnipay-oppwa', 'id': 'c793a5c5a0e7df84fb53967e3698a0ec33d98fe7', 'size': '2019', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Message/AbstractRequest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '18794'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TSQL
{
public struct TSQLVariables
{
private static Dictionary<string, TSQLVariables> variableLookup =
new Dictionary<string, TSQLVariables>(StringComparer.OrdinalIgnoreCase);
public static readonly TSQLVariables None = new TSQLVariables("");
#pragma warning disable 1591
public static readonly TSQLVariables CONNECTIONS = new TSQLVariables("@@CONNECTIONS");
public static readonly TSQLVariables MAX_CONNECTIONS = new TSQLVariables("@@MAX_CONNECTIONS");
public static readonly TSQLVariables CPU_BUSY = new TSQLVariables("@@CPU_BUSY");
public static readonly TSQLVariables ERROR = new TSQLVariables("@@ERROR");
public static readonly TSQLVariables IDENTITY = new TSQLVariables("@@IDENTITY");
public static readonly TSQLVariables IDLE = new TSQLVariables("@@IDLE");
public static readonly TSQLVariables IO_BUSY = new TSQLVariables("@@IO_BUSY");
public static readonly TSQLVariables LANGID = new TSQLVariables("@@LANGID");
public static readonly TSQLVariables LANGUAGE = new TSQLVariables("@@LANGUAGE");
public static readonly TSQLVariables MAXCHARLEN = new TSQLVariables("@@MAXCHARLEN");
public static readonly TSQLVariables PACK_RECEIVED = new TSQLVariables("@@PACK_RECEIVED");
public static readonly TSQLVariables PACK_SENT = new TSQLVariables("@@PACK_SENT");
public static readonly TSQLVariables PACKET_ERRORS = new TSQLVariables("@@PACKET_ERRORS");
public static readonly TSQLVariables ROWCOUNT = new TSQLVariables("@@ROWCOUNT");
public static readonly TSQLVariables SERVERNAME = new TSQLVariables("@@SERVERNAME");
public static readonly TSQLVariables SPID = new TSQLVariables("@@SPID");
public static readonly TSQLVariables TEXTSIZE = new TSQLVariables("@@TEXTSIZE");
public static readonly TSQLVariables TIMETICKS = new TSQLVariables("@@TIMETICKS");
public static readonly TSQLVariables TOTAL_ERRORS = new TSQLVariables("@@TOTAL_ERRORS");
public static readonly TSQLVariables TOTAL_READ = new TSQLVariables("@@TOTAL_READ");
public static readonly TSQLVariables TOTAL_WRITE = new TSQLVariables("@@TOTAL_WRITE");
public static readonly TSQLVariables TRANCOUNT = new TSQLVariables("@@TRANCOUNT");
public static readonly TSQLVariables VERSION = new TSQLVariables("@@VERSION");
public static readonly TSQLVariables DATEFIRST = new TSQLVariables("@@DATEFIRST");
public static readonly TSQLVariables DBTS = new TSQLVariables("@@DBTS");
public static readonly TSQLVariables LOCK_TIMEOUT = new TSQLVariables("@@LOCK_TIMEOUT");
public static readonly TSQLVariables MAX_PRECISION = new TSQLVariables("@@MAX_PRECISION");
public static readonly TSQLVariables NESTLEVEL = new TSQLVariables("@@NESTLEVEL");
public static readonly TSQLVariables OPTIONS = new TSQLVariables("@@OPTIONS");
public static readonly TSQLVariables REMSERVER = new TSQLVariables("@@REMSERVER");
public static readonly TSQLVariables SERVICENAME = new TSQLVariables("@@SERVICENAME");
public static readonly TSQLVariables CURSOR_ROWS = new TSQLVariables("@@CURSOR_ROWS");
public static readonly TSQLVariables FETCH_STATUS = new TSQLVariables("@@FETCH_STATUS");
public static readonly TSQLVariables PROCID = new TSQLVariables("@@PROCID");
#pragma warning restore 1591
private readonly string Variable;
private TSQLVariables(
string variable)
{
Variable = variable;
if (variable.Length > 0)
{
variableLookup[variable] = this;
}
}
public static TSQLVariables Parse(
string token)
{
if (
!string.IsNullOrEmpty(token) &&
variableLookup.ContainsKey(token))
{
return variableLookup[token];
}
else
{
return TSQLVariables.None;
}
}
public static bool IsVariable(
string token)
{
if (!string.IsNullOrWhiteSpace(token))
{
return variableLookup.ContainsKey(token);
}
else
{
return false;
}
}
public bool In(params TSQLVariables[] variables)
{
return
variables != null &&
variables.Contains(this);
}
#pragma warning disable 1591
public static bool operator ==(
TSQLVariables a,
TSQLVariables b)
{
return a.Equals(b);
}
public static bool operator !=(
TSQLVariables a,
TSQLVariables b)
{
return !(a == b);
}
public bool Equals(TSQLVariables obj)
{
return Variable == obj.Variable;
}
public override bool Equals(object obj)
{
if (obj is TSQLVariables)
{
return Equals((TSQLVariables)obj);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return Variable.GetHashCode();
}
#pragma warning restore 1591
}
}
| {'content_hash': '89aab1e793eec488a22f5fcdc8bbcf91', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 96, 'avg_line_length': 34.02836879432624, 'alnum_prop': 0.7157148812005002, 'repo_name': 'bruce-dunwiddie/tsql-parser', 'id': 'd4691defc800628178c20a8ec7525a950a37c438', 'size': '4800', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'TSQL_Parser/TSQL_Parser/TSQLVariables.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1467'}, {'name': 'C#', 'bytes': '352245'}]} |
//
// GTLBigqueryJobConfigurationTableCopy.m
//
// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
// BigQuery API (bigquery/v2)
// Description:
// A data platform for customers to create, manage, share and query data.
// Documentation:
// https://cloud.google.com/bigquery/
// Classes:
// GTLBigqueryJobConfigurationTableCopy (0 custom class methods, 5 custom properties)
#import "GTLBigqueryJobConfigurationTableCopy.h"
#import "GTLBigqueryTableReference.h"
// ----------------------------------------------------------------------------
//
// GTLBigqueryJobConfigurationTableCopy
//
@implementation GTLBigqueryJobConfigurationTableCopy
@dynamic createDisposition, destinationTable, sourceTable, sourceTables,
writeDisposition;
+ (NSDictionary *)arrayPropertyToClassMap {
NSDictionary *map = @{
@"sourceTables" : [GTLBigqueryTableReference class]
};
return map;
}
@end
| {'content_hash': '6ba0daa8dd45bb99b4da36348579e809', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 87, 'avg_line_length': 26.81578947368421, 'alnum_prop': 0.6359175662414132, 'repo_name': 'clody/google-api-objectivec-client', 'id': 'c4ea0d96910f196b283fc15b00710f87cfa1f5b3', 'size': '1614', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'Source/Services/Bigquery/Generated/GTLBigqueryJobConfigurationTableCopy.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '2926'}, {'name': 'Objective-C', 'bytes': '5907427'}]} |
package org.broad.igv.ui;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.track.TrackType;
import java.awt.*;
/**
* @author jrobinso
*/
public class UIConstants {
private static Logger log = Logger.getLogger(UIConstants.class);
final public static String APPLICATION_NAME = "IGV";
final public static int groupGap = 10;
final public static Dimension preferredSize = new Dimension(1000, 750);
// To support mutation track overlay. Generalize later. Cancer specific option.
public static TrackType overlayTrackType = TrackType.MUTATION;
private static int doubleClickInterval = -1;
// Menu tooltips
static final public String LOAD_TRACKS_TOOLTIP = "Load tracks or sample information";
static final public String LOAD_SERVER_DATA_TOOLTIP = "Load tracks or sample information from a server";
static final public String SAVE_IMAGE_TOOLTIP = "Capture and save an image";
static final public String NEW_SESSION_TOOLTIP = "Create a new session";
static final public String SAVE_SESSION_TOOLTIP = "Save the current session";
static final public String RESTORE_SESSION_TOOLTIP = "Reload the session";
static final public String EXIT_TOOLTIP = "Exit the application";
static final public String IMPORT_GENOME_TOOLTIP = "Create a .genome file";
static final public String REMOVE_IMPORTED_GENOME_TOOLTIP = "Removes user-defined genomes from the drop-down list";
static final public String CLEAR_GENOME_CACHE_TOOLTIP = "Clears locally cached versions of IGV hosted genomes";
static final public String SELECT_DISPLAYABLE_ATTRIBUTES_TOOLTIP =
"Customize attribute display to show only checked attributes";
static final public String SORT_TRACKS_TOOLTIP = "Sort tracks by attribute value";
static final public String GROUP_TRACKS_TOOLTIP = "Group tracks by attribute value";
static final public String FILTER_TRACKS_TOOLTIP = "Filter tracks by attribute value";
static final public String SET_DEFAULT_TRACK_HEIGHT_TOOLTIP = "Set the height for all tracks";
static final public String FIT_DATA_TO_WINDOW_TOOLTIP =
"Resize track heights to make best use of vertical space without scrolling";
static final public String EXPORT_REGION_TOOLTIP = "Save all defined regions to a file";
static final public String IMPORT_REGION_TOOLTIP = "Load regions from a file";
static final public String HELP_TOOLTIP = "Open web help page";
static final public String ABOUT_TOOLTIP = "Display application information";
static final public String RESET_FACTORY_TOOLTIP = "Restores all user preferences to their default settings.";
public static final String REGION_NAVIGATOR_TOOLTIP = "Navigate regions";
static final public String CLICK_ITEM_TO_EDIT_TOOLTIP = "Click this item bring up its editor";
static final public String CHANGE_GENOME_TOOLTIP = "Switch the current genome";
static final public String PREFERENCE_TOOLTIP = "Set user specific preferences";
static final public String SHOW_HEATMAP_LEGEND_TOOLTIP = "Edit color legends and scales";
public static Font boldFont = FontManager.getFont(Font.BOLD, 12);
final public static String OVERWRITE_SESSION_MESSAGE =
"<html>Do you want to unload all current data?";
final public static String CANNOT_ACCESS_SERVER_GENOME_LIST = "The Genome server is currently inaccessible.";
final public static int NUMBER_OF_RECENT_SESSIONS_TO_LIST = 3;
final public static String DEFAULT_SESSION_FILE = "igv_session" + Globals.SESSION_FILE_EXTENSION;
static final public String SERVER_BASE_URL = "http://www.broadinstitute.org/";
static final public Color LIGHT_YELLOW = new Color(255, 244, 201);
final public static Color LIGHT_GREY = new Color(238, 239, 240);
final public static Color TRACK_BORDER_GRAY = new Color(200, 200, 210);
public static Color NO_DATA_COLOR = new Color(200, 200, 200, 150);
static final public String REMOVE_GENOME_LIST_MENU_ITEM = "Remove Imported Genomes...";
static final public String GENOME_LIST_SEPARATOR = "--SEPARATOR--";
static final public int DEFAULT_DOUBLE_CLICK_INTERVAL = 400;
public static int getDoubleClickInterval() {
if (doubleClickInterval < 0) {
Number obj = (Number) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
if (obj != null) {
doubleClickInterval = obj.intValue();
} else {
doubleClickInterval = DEFAULT_DOUBLE_CLICK_INTERVAL;
}
}
return doubleClickInterval;
}
}
| {'content_hash': 'e44f79ab36640cf8d320345c989b4795', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 119, 'avg_line_length': 46.54, 'alnum_prop': 0.7260421143102708, 'repo_name': 'popitsch/varan-gie', 'id': '684b0607eb59bdda86e79aa7359342b8b1e35831', 'size': '5809', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/org/broad/igv/ui/UIConstants.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'AngelScript', 'bytes': '1671'}, {'name': 'Batchfile', 'bytes': '628'}, {'name': 'HTML', 'bytes': '14798'}, {'name': 'Java', 'bytes': '8408221'}, {'name': 'JavaScript', 'bytes': '7877'}, {'name': 'PHP', 'bytes': '7953'}, {'name': 'Ruby', 'bytes': '93'}, {'name': 'Shell', 'bytes': '1344'}]} |
<?php
/**
* Created by PhpStorm.
* User: quimmanrique
* Date: 13/02/17
* Time: 16:13
*/
namespace Cmp\Queues\Infrastructure\AmqpLib\v26\RabbitMQ\Queue\Config;
class BindConfig
{
protected $topics = [];
public function addTopic($topic)
{
$this->topics[] = $topic;
return $this;
}
public function getTopics()
{
return $this->topics;
}
} | {'content_hash': '3aafffb92cd519af3f213e4714bd4128', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 70, 'avg_line_length': 15.23076923076923, 'alnum_prop': 0.5959595959595959, 'repo_name': 'CMProductions/queues', 'id': 'd5f804007ee4b636564f2d3e798421299f4521de', 'size': '396', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Cmp/Queues/Infrastructure/AmqpLib/v26/RabbitMQ/Queue/Config/BindConfig.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '578'}, {'name': 'Gherkin', 'bytes': '970'}, {'name': 'Makefile', 'bytes': '2295'}, {'name': 'PHP', 'bytes': '88022'}, {'name': 'Shell', 'bytes': '639'}]} |
package org.auraframework.impl.css.parser.plugin;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.FlavoredStyleDef;
import com.salesforce.omakase.PluginRegistry;
import com.salesforce.omakase.plugin.DependentPlugin;
/**
* An aggregate plugin that registers all of the flavor plugins for parsing and validating flavors in the correct order.
*/
public class FlavorPlugin implements DependentPlugin {
private final DefDescriptor<FlavoredStyleDef> flavoredStyle;
public FlavorPlugin(DefDescriptor<FlavoredStyleDef> flavoredStyle) {
this.flavoredStyle = flavoredStyle;
}
@Override
public void dependencies(PluginRegistry registry) {
// order here is ~important
registry.register(new FlavorDefaultRenamePlugin());
registry.register(new FlavorCollectorPlugin());
registry.register(new FlavorExtendsPlugin(flavoredStyle));
registry.register(new FlavorSelectorScopingPlugin(flavoredStyle));
}
}
| {'content_hash': 'd1d42090b132c48d704cbf7e0fa16255', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 120, 'avg_line_length': 35.392857142857146, 'alnum_prop': 0.7709384460141272, 'repo_name': 'madmax983/aura', 'id': 'd6786a661d769a8e390f1d1835cc20a9610e0171', 'size': '1602', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'aura-impl/src/main/java/org/auraframework/impl/css/parser/plugin/FlavorPlugin.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '782982'}, {'name': 'GAP', 'bytes': '10087'}, {'name': 'HTML', 'bytes': '3296233'}, {'name': 'Java', 'bytes': '9575906'}, {'name': 'JavaScript', 'bytes': '26838648'}, {'name': 'PHP', 'bytes': '3345441'}, {'name': 'Python', 'bytes': '9744'}, {'name': 'Shell', 'bytes': '20356'}, {'name': 'XSLT', 'bytes': '1579'}]} |
layout: post
permalink: /blog/quill-1-0-beta-release/
title: Quill 1.0 Beta Release
---
Today Quill is ready for its first beta preview of 1.0. This is the biggest rewrite to Quill since its inception and enables many new possibilities not available in previous versions of Quill, nor any other editor. The code is as always available on Github and through npm:
```
npm install [email protected]
```
The skeleton of a new documentation site is also being built out at [beta.quilljs.com](http://beta.quilljs.com). Whereas the current site focuses on being a referential resource, the new site will also be a guide to provide insight on approaching different customization goals. There is also an [interactive playground](http://beta.quilljs.com/playground/) to try out various configurations and explore the API.
<!-- more -->
The goal now is of course an official 1.0 release. To get there, Quill will now enter a weekly cadence of beta releases, so you can expect rapid interations on stability and bug fixes each week. Github is still the center of all development so please do report [Issues](https://github.com/quilljs/quill/issues) as you encounter them in the beta preview.
| {'content_hash': '53aa6c71b806fbc540b9468a7e418193', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 411, 'avg_line_length': 74.125, 'alnum_prop': 0.7782462057335582, 'repo_name': 'wdcxc/blog', 'id': '54eeadc9a1252d3025f1dbaf92cae1ebbbb02150', 'size': '1190', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'static/libs/quill-1.3.0/docs/_posts/2016-05-03-quill-1-0-beta-release.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1588009'}, {'name': 'HTML', 'bytes': '42412'}, {'name': 'JavaScript', 'bytes': '2089513'}, {'name': 'Python', 'bytes': '9250'}, {'name': 'Ruby', 'bytes': '5441'}, {'name': 'Shell', 'bytes': '2607'}]} |
package org.chocosolver.sat;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import org.chocosolver.solver.Cause;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.BoolVar;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.util.ESat;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Random;
import static org.chocosolver.sat.PropNogoods.iseq;
import static org.chocosolver.sat.PropNogoods.ivalue;
import static org.chocosolver.sat.PropNogoods.leq;
/**
* Test class for PropNogoods
* Created by cprudhom on 25/11/2015.
* Project: choco.
*/
public class PropNogoodsTest {
IntVar[] vars;
PropNogoods PNG;
int[] lits;
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
Model model = new Model("nogoods");
vars = model.intVarArray("X", 4, -1, 1, false);
PNG = model.getNogoodStore().getPropNogoods();
lits = new int[6];
lits[0] = PNG.Literal(vars[0], 0, true);
lits[1] = PNG.Literal(vars[0], 0, false);
lits[2] = PNG.Literal(vars[1], 0, true);
lits[3] = PNG.Literal(vars[1], 0, false);
lits[4] = PNG.Literal(vars[2], 0, true);
lits[5] = PNG.Literal(vars[2], 0, false);
PNG.initialize();
TIntList list = new TIntArrayList();
list.add(SatSolver.negated(lits[0]));
list.add(lits[1]);
PNG.addNogood(list);
list.clear();
list.add(SatSolver.negated(lits[2]));
list.add(lits[3]);
PNG.addNogood(list);
list.clear();
list.add(SatSolver.negated(lits[4]));
list.add(lits[5]);
PNG.addNogood(list);
PNG.propagate(2);
}
@AfterMethod
public void tearDown() throws Exception {
}
@Test(groups="1s", timeOut=60000)
public void testPropagate() throws Exception {
try {
PNG.propagate(2);
}catch (ContradictionException c){
Assert.fail();
}
Assert.assertEquals(vars[0].getDomainSize(), 3);
Assert.assertEquals(vars[1].getDomainSize(), 3);
Assert.assertEquals(vars[2].getDomainSize(), 3);
TIntList list = new TIntArrayList();
list.add(SatSolver.negated(lits[0]));
list.add(lits[2]);
PNG.addNogood(list);
list.clear();
list.add(SatSolver.negated(lits[2]));
list.add(lits[4]);
PNG.addNogood(list);
vars[0].instantiateTo(0, Cause.Null);
try {
PNG.propagate(2);
}catch (ContradictionException c){
Assert.fail();
}
Assert.assertTrue(vars[0].isInstantiatedTo(0));
Assert.assertTrue(vars[1].isInstantiatedTo(0));
Assert.assertTrue(vars[2].isInstantiatedTo(0));
}
@Test(groups="1s", timeOut=60000)
public void testPropagate1() throws Exception {
PNG.propagate(2);
TIntList list = new TIntArrayList();
list.add(SatSolver.negated(lits[0]));
list.add(lits[2]);
PNG.addNogood(list);
list.clear();
list.add(SatSolver.negated(lits[2]));
list.add(lits[4]);
PNG.addNogood(list);
vars[0].instantiateTo(0, Cause.Null);
try {
PNG.propagate(0, 15);
}catch (ContradictionException c){
Assert.fail();
}
Assert.assertTrue(vars[0].isInstantiatedTo(0));
Assert.assertTrue(vars[1].isInstantiatedTo(0));
Assert.assertTrue(vars[2].isInstantiatedTo(0));
}
@Test(groups="1s", timeOut=60000)
public void testIsEntailed1() throws Exception {
vars[0].instantiateTo(0, Cause.Null);
vars[1].instantiateTo(1, Cause.Null);
vars[2].instantiateTo(-1, Cause.Null);
Assert.assertEquals(PNG.isEntailed(), ESat.TRUE);
}
@Test(groups="1s", timeOut=60000)
public void testIsEntailed2() throws Exception {
Assert.assertEquals(PNG.isEntailed(), ESat.UNDEFINED);
}
@Test(groups="1s", timeOut=60000)
public void testLiteral1() throws Exception {
Assert.assertTrue(lits[0] == 1);
Assert.assertTrue(lits[1] == 3);
Assert.assertTrue(lits[2] == 5);
Assert.assertTrue(lits[3] == 7);
Assert.assertTrue(lits[4] == 9);
Assert.assertTrue(lits[5] == 11);
}
@Test(groups="1s", timeOut=60000)
public void testLiteral2() throws Exception {
BoolVar[] b = vars[0].getModel().boolVarArray("B", 100);
for(int i = 0 ; i < 100; i++){
PNG.Literal(b[i], 0, true);
PNG.Literal(b[i], 0, false);
}
}
@Test(groups="1s", timeOut=60000)
public void testVariableBound1(){
try {
vars[0].instantiateTo(0, Cause.Null);
PNG.VariableBound(0, true);
PNG.VariableBound(1, false);
vars[1].instantiateTo(1, Cause.Null);
PNG.VariableBound(3, true);
PNG.VariableBound(2, false);
vars[2].instantiateTo(-1, Cause.Null);
PNG.VariableBound(5, false);
PNG.VariableBound(4, false);
}catch (ContradictionException cew){
Assert.fail();
}
}
@Test(groups="1s", timeOut=60000)
public void testVariableBound2() throws Exception{
vars[0].instantiateTo(0, Cause.Null);
try {
PNG.VariableBound(1, false);
Assert.fail();
}catch (ContradictionException ce){
}
}
@Test(groups="1s", timeOut=60000)
public void testVariableBound3() throws Exception{
vars[0].instantiateTo(1, Cause.Null);
try {
PNG.VariableBound(0, true);
Assert.fail();
}catch (ContradictionException cew){
}
}
@Test(groups="1s", timeOut=60000)
public void testVariableBound4(){
try {
vars[0].instantiateTo(1, Cause.Null);
PNG.VariableBound(0, true);
Assert.fail();
}catch (ContradictionException cew){
}
}
@Test(groups="1s", timeOut=60000)
public void testApplyEarlyDeductions() throws Exception {
}
@Test(groups="1s", timeOut=60000)
public void testDoReduce1() throws Exception {
PNG.doReduce(1);
Assert.assertTrue(vars[0].isInstantiatedTo(0));
}
@Test(groups="1s", timeOut=60000)
public void testDoReduce2() throws Exception {
PNG.doReduce(0);
Assert.assertFalse(vars[0].contains(0));
}
@Test(groups="1s", timeOut=60000)
public void testDoReduce3() throws Exception {
PNG.doReduce(3);
Assert.assertEquals(vars[0].getUB(),0);
}
@Test(groups="1s", timeOut=60000)
public void testDoReduce4() throws Exception {
PNG.doReduce(2);
Assert.assertEquals(vars[0].getLB(),1);
}
@Test(groups="1s", timeOut=60000)
public void testIvalue(){
int[] values = {0, 1, -1, 10, -10, 181, -181, 210, -210};
for(int value: values) {
long eqvalue = value;
long ltvalue = leq(value);
Assert.assertEquals(ivalue(eqvalue), value, "ivalue eq: " + value + ", " + eqvalue + "");
Assert.assertEquals(ivalue(ltvalue), value, "ivalue leq: " + value + ", " + ltvalue + "");
}
}
@Test(groups="1s", timeOut=60000)
public void testDeclareDomainNogood(){
IntVar var = vars[0].getModel().intVar("X4", -1, 1, false);
PNG.declareDomainNogood(var);
try{
PNG.doReduce(13);
Assert.assertTrue(var.isInstantiatedTo(-1));
}catch (ContradictionException c){
Assert.fail();
}
}
@Test(groups="1s", timeOut=60000)
public void testIseq(){
Model model = new Model("nogoods");
PNG = model.getNogoodStore().getPropNogoods();
Random rnd = new Random();
for(int i = 0 ; i < 1_000_000; i++){
rnd.setSeed(i);
int value = rnd.nextInt() * (1-rnd.nextInt(2));
boolean eq = rnd.nextBoolean();
long lvalue = eq ? value : leq(value);
Assert.assertEquals(iseq(lvalue), eq);
Assert.assertEquals(ivalue(lvalue), value);
}
}
} | {'content_hash': '3be4cc96a45191060c183bf5ee1e9773', 'timestamp': '', 'source': 'github', 'line_count': 271, 'max_line_length': 102, 'avg_line_length': 30.981549815498155, 'alnum_prop': 0.5886136255359695, 'repo_name': 'chocoteam/choco3', 'id': '7bcd00c109bf6aa04e490d16f4f7e0ae4ea10c1d', 'size': '8648', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/test/java/org/chocosolver/sat/PropNogoodsTest.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '6470'}, {'name': 'HTML', 'bytes': '1234'}, {'name': 'Java', 'bytes': '5356648'}, {'name': 'Makefile', 'bytes': '6905'}, {'name': 'Python', 'bytes': '8425'}, {'name': 'Shell', 'bytes': '14652'}, {'name': 'TeX', 'bytes': '17342'}]} |
package org.asynchttpclient.websocket;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.websocket.WebSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.ServerSocket;
public abstract class AbstractBasicTest extends Server {
public abstract class WebSocketHandler extends HandlerWrapper implements WebSocketFactory.Acceptor {
private final WebSocketFactory _webSocketFactory = new WebSocketFactory(this, 32 * 1024);
public WebSocketHandler(){
_webSocketFactory.setMaxIdleTime(10000);
}
public WebSocketFactory getWebSocketFactory() {
return _webSocketFactory;
}
/* ------------------------------------------------------------ */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (_webSocketFactory.acceptWebSocket(request, response) || response.isCommitted())
return;
super.handle(target, baseRequest, request, response);
}
/* ------------------------------------------------------------ */
public boolean checkOrigin(HttpServletRequest request, String origin) {
return true;
}
}
protected final Logger log = LoggerFactory.getLogger(AbstractBasicTest.class);
protected int port1;
SelectChannelConnector _connector;
@AfterClass(alwaysRun = true)
public void tearDownGlobal() throws Exception {
stop();
}
protected int findFreePort() throws IOException {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
return socket.getLocalPort();
} finally {
if (socket != null) {
socket.close();
}
}
}
protected String getTargetUrl() {
return String.format("ws://127.0.0.1:%d/", port1);
}
@BeforeClass(alwaysRun = true)
public void setUpGlobal() throws Exception {
port1 = findFreePort();
_connector = new SelectChannelConnector();
_connector.setPort(port1);
addConnector(_connector);
WebSocketHandler _wsHandler = getWebSocketHandler();
setHandler(_wsHandler);
start();
log.info("Local HTTP server started successfully");
}
public abstract WebSocketHandler getWebSocketHandler() ;
public abstract AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config);
}
| {'content_hash': '667ef4f7f3728ba457965b264c0d348e', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 159, 'avg_line_length': 31.958333333333332, 'alnum_prop': 0.6646023468057366, 'repo_name': 'typesafehub/async-http-client', 'id': 'bbff1213e96e54db317f922b155dac4fcf8ad899', 'size': '3763', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'api/src/test/java/org/asynchttpclient/websocket/AbstractBasicTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2118581'}]} |
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
#ifndef __boosting__training_index_iterators_impl_h__
#define __boosting__training_index_iterators_impl_h__
#include "training_index_iterators.h"
namespace ML {
inline Index_Iterator Joint_Index::begin() const
{
return Index_Iterator(this, 0);
}
inline Index_Iterator Joint_Index::end() const
{
return Index_Iterator(this, size_);
}
inline Index_Iterator Joint_Index::front() const
{
return Index_Iterator(this, 0);
}
inline Index_Iterator Joint_Index::back() const
{
return Index_Iterator(this, size_ - 1);
}
inline Index_Iterator Joint_Index::operator [] (int idx) const
{
return Index_Iterator(this, idx);
}
} // namespace ML
#endif /* __boosting__training_index_iterators_impl_h__ */
| {'content_hash': '78ac77124b47697c9143a528b8b79974', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 78, 'avg_line_length': 19.536585365853657, 'alnum_prop': 0.7028714107365793, 'repo_name': 'mldbai/mldb', 'id': '00707f61bde6b8539b4c92e57a8a51d472c3f40d', 'size': '1048', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugins/jml/jml/training_index_iterators_impl.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '643'}, {'name': 'C', 'bytes': '11754639'}, {'name': 'C++', 'bytes': '14072572'}, {'name': 'CMake', 'bytes': '2737'}, {'name': 'CSS', 'bytes': '17037'}, {'name': 'Dockerfile', 'bytes': '1591'}, {'name': 'Fortran', 'bytes': '16349'}, {'name': 'HTML', 'bytes': '311171'}, {'name': 'JavaScript', 'bytes': '2209253'}, {'name': 'Jupyter Notebook', 'bytes': '7661154'}, {'name': 'Makefile', 'bytes': '290745'}, {'name': 'Perl', 'bytes': '3890'}, {'name': 'Python', 'bytes': '1422764'}, {'name': 'Shell', 'bytes': '32489'}, {'name': 'Smarty', 'bytes': '2938'}, {'name': 'SourcePawn', 'bytes': '52752'}]} |
package dbtools.schema;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Optional.*;
import static com.google.common.collect.FluentIterable.*;
import static com.google.common.collect.ImmutableList.*;
import static com.google.common.collect.Lists.*;
import static dbtools.schema.Tables.*;
public class TableDef {
public static final TableDef EMPTY = TableDef.builder().build();
private static final List<ColDef> EMPTY_COLS = newArrayList();
private final String name;
private final List<ColDef> columns;
public List<ColDef> columns() {
return copyOf(columns);
}
//public Optional<ColDef> col(String name)
public ColDef col(String name) {
return from(columns)
.firstMatch(colNameIs(name))
.get();
}
public int numCols() {
return columns.size();
}
public String name() {
return name;
}
private TableDef(String name, List<ColDef> columns) {
this.name = name;
this.columns = copyOf(fromNullable(columns)
.or(new ArrayList<ColDef>()));
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String name;
private List<ColDef> columns;
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withColumns(List<ColDef> columns) {
this.columns = columns;
return this;
}
public TableDef build() {
return new TableDef(name, columns);
}
}
}
| {'content_hash': '68814e9c0e8bda0c8d7633017a57903d', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 68, 'avg_line_length': 25.12121212121212, 'alnum_prop': 0.6164053075995175, 'repo_name': 'tstout/db-tools', 'id': '37987d0ad002ce4e38570be564c84eff877d6c31', 'size': '1658', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db-tool/src/main/java/dbtools/schema/TableDef.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ANTLR', 'bytes': '1646'}, {'name': 'Java', 'bytes': '87439'}, {'name': 'Ruby', 'bytes': '2026'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - postprocessing</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
margin: 0px;
background-color: #000000;
overflow: hidden;
}
</style>
</head>
<body>
<script src="../build/three.min.js"></script>
<script src="js/shaders/CopyShader.js"></script>
<script src="js/shaders/DotScreenShader.js"></script>
<script src="js/shaders/RGBShiftShader.js"></script>
<script src="js/postprocessing/EffectComposer.js"></script>
<script src="js/postprocessing/RenderPass.js"></script>
<script src="js/postprocessing/MaskPass.js"></script>
<script src="js/postprocessing/ShaderPass.js"></script>
<script>
var camera, scene, renderer, composer;
var object, light;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 400;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0x000000, 1, 1000 );
object = new THREE.Object3D();
scene.add( object );
var geometry = new THREE.SphereGeometry( 1, 4, 4 );
var material = new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } );
for ( var i = 0; i < 100; i ++ ) {
var mesh = new THREE.Mesh( geometry, material );
mesh.position.set( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 ).normalize();
mesh.position.multiplyScalar( Math.random() * 400 );
mesh.rotation.set( Math.random() * 2, Math.random() * 2, Math.random() * 2 );
mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50;
object.add( mesh );
}
scene.add( new THREE.AmbientLight( 0x222222 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
// postprocessing
composer = new THREE.EffectComposer( renderer );
composer.addPass( new THREE.RenderPass( scene, camera ) );
var effect = new THREE.ShaderPass( THREE.DotScreenShader );
effect.uniforms[ 'scale' ].value = 4;
composer.addPass( effect );
var effect = new THREE.ShaderPass( THREE.RGBShiftShader );
effect.uniforms[ 'amount' ].value = 0.0015;
effect.renderToScreen = true;
composer.addPass( effect );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
composer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
object.rotation.x += 0.005;
object.rotation.y += 0.01;
composer.render();
}
</script>
</body>
</html>
| {'content_hash': '014020e0d71b7bd796f88fdec48f793e', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 109, 'avg_line_length': 26.596638655462186, 'alnum_prop': 0.6546603475513428, 'repo_name': 'sebasbaumh/three.js', 'id': 'd6de1fc7da5bf291f0b9f733b4d1cb2ec6daa885', 'size': '3165', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'examples/webgl_postprocessing.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1131'}, {'name': 'C', 'bytes': '80088'}, {'name': 'C++', 'bytes': '116991'}, {'name': 'CSS', 'bytes': '21422'}, {'name': 'GLSL', 'bytes': '46235'}, {'name': 'HTML', 'bytes': '33829'}, {'name': 'JavaScript', 'bytes': '3598142'}, {'name': 'MAXScript', 'bytes': '75494'}, {'name': 'Python', 'bytes': '506959'}, {'name': 'Shell', 'bytes': '10183'}]} |
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'career_builder'
require 'spec'
require 'spec/autorun'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
Spec::Runner.configure do |config|
end
| {'content_hash': 'ca79c126705efac73c1b2a10a4af59d4', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 99, 'avg_line_length': 32.38461538461539, 'alnum_prop': 0.6983372921615202, 'repo_name': 'mguterl/career_builder', 'id': '432233aadb808317ac1665485d854e35214bc84f', 'size': '421', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/spec_helper.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '55855'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect1 id="zend.feed.consuming-atom-single-entry">
<title>Consuming a Single Atom Entry</title>
<para>
Single Atom <command><entry></command> elements are also valid by themselves. Usually
the <acronym>URL</acronym> for an entry is the feed's <acronym>URL</acronym> followed by
<command>/<entryId></command>, such as
<filename>http://atom.example.com/feed/1</filename>, using the example
<acronym>URL</acronym> we used above.
</para>
<para>
If you read a single entry, you will still have a <classname>Zend_Feed_Atom</classname>
object, but it will automatically create an "anonymous" feed to contain the entry.
</para>
<example id="zend.feed.consuming-atom-single-entry.example.atom">
<title>Reading a Single-Entry Atom Feed</title>
<programlisting language="php"><![CDATA[
$feed = new Zend_Feed_Atom('http://atom.example.com/feed/1');
echo 'The feed has: ' . $feed->count() . ' entry.';
$entry = $feed->current();
]]></programlisting>
</example>
<para>
Alternatively, you could instantiate the entry object directly if you know you are accessing
an <command><entry></command>-only document:
</para>
<example id="zend.feed.consuming-atom-single-entry.example.entryatom">
<title>Using the Entry Object Directly for a Single-Entry Atom Feed</title>
<programlisting language="php"><![CDATA[
$entry = new Zend_Feed_Entry_Atom('http://atom.example.com/feed/1');
echo $entry->title();
]]></programlisting>
</example>
</sect1>
<!--
vim:se ts=4 sw=4 et:
--> | {'content_hash': 'd4ed81849c1339c1fd6c4c345b4101db', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 100, 'avg_line_length': 36.630434782608695, 'alnum_prop': 0.656973293768546, 'repo_name': '51systems/Zend-Framework-1x', 'id': 'fdc13584b67a1e33a24412e740ef4a7d0ef30a9f', 'size': '1685', 'binary': False, 'copies': '48', 'ref': 'refs/heads/master', 'path': 'documentation/manual/en/module_specs/Zend_Feed-ConsumingAtomSingle.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
function LinkedList() {
this.head = new Node();
this.tail = new Node();
this.number_of_elements = 0;
this.count = function() {
return this.number_of_elements;
}
this.head.next = this.tail;
this.tail.previous = this.head;
this.pop = function() {
this.head = this.head.next;
this.number_of_elements--;
return this.head.value;
}
this.push = function(value) {
this.head.value = value;
head = new Node();
head.next = this.head;
this.head.previous = head;
this.head = head;
this.number_of_elements++;
}
this.shift = function() {
this.tail = this.tail.previous;
this.number_of_elements--;
return this.tail.value;
}
this.unshift = function(value) {
this.tail.value = value;
tail = new Node();
tail.previous = this.tail;
this.tail.next = tail;
this.tail = tail;
this.number_of_elements++;
}
this.delete = function(value) {
node = head.next;
while (node.value != value) {
node = node.next;
if (!node) {
return -1;
}
}
node.previous.next = node.next;
node.next.previous = node.previous;
this.number_of_elements--;
}
}
function Node() {
this.previous = null;
this.next = null;
this.value = null;
}
module.exports = LinkedList;
| {'content_hash': '3b74d992833bf4112c2901d22dbab5b5', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 39, 'avg_line_length': 22.910714285714285, 'alnum_prop': 0.6048324240062354, 'repo_name': 'm1kal/exercism_javascript', 'id': '70e966569aaa35c3d3b404519fe27a5f5e4f03de', 'size': '1283', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'linked-list/linked-list.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '22098'}]} |
using System.Security;
using System;
using System.IO;
[SecuritySafeCritical]
public class TestFileStream : FileStream
{
public TestFileStream(string path, FileMode mode)
: base(path, mode)
{
}
public void DisposeWrapper(bool disposing)
{
Dispose(disposing);
}
public override bool CanRead
{
[SecuritySafeCritical]
get { throw new Exception("The method or operation is not implemented."); }
}
public override bool CanSeek
{
[SecuritySafeCritical]
get { return base.CanSeek; }
}
public override bool CanWrite
{
[SecuritySafeCritical]
get { throw new Exception("The method or operation is not implemented."); }
}
[SecuritySafeCritical]
public override void Flush()
{
throw new Exception("The method or operation is not implemented.");
}
public override long Length
{
[SecuritySafeCritical]
get { throw new Exception("The method or operation is not implemented."); }
}
public override long Position
{
[SecuritySafeCritical]
get
{
throw new Exception("The method or operation is not implemented.");
}
[SecuritySafeCritical]
set
{
throw new Exception("The method or operation is not implemented.");
}
}
[SecuritySafeCritical]
public override int Read(byte[] buffer, int offset, int count)
{
throw new Exception("The method or operation is not implemented.");
}
[SecuritySafeCritical]
public override long Seek(long offset, SeekOrigin origin)
{
throw new Exception("The method or operation is not implemented.");
}
[SecuritySafeCritical]
public override void SetLength(long value)
{
throw new Exception("The method or operation is not implemented.");
}
[SecuritySafeCritical]
public override void Write(byte[] buffer, int offset, int count)
{
throw new Exception("The method or operation is not implemented.");
}
}
[SecuritySafeCritical]
public class FileStreamDispose
{
#region Private Fileds
const string c_DEFAULT_FILE_PATH = "TestFile";
#endregion
#region Public Methods
public bool RunTesfs()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
// retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Dispose with disposing set to true");
try
{
TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH,FileMode.Append);
tfs.DisposeWrapper(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Dispose twice with disposing set to true");
try
{
TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append);
tfs.DisposeWrapper(true);
tfs.DisposeWrapper(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Dispose with disposing set to false");
try
{
TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append);
tfs.DisposeWrapper(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Dispose twice with disposing set to false");
try
{
TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append);
tfs.DisposeWrapper(false);
tfs.DisposeWrapper(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Call Dispose twice with disposing set to false once and another time set to true");
try
{
TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append);
tfs.DisposeWrapper(false);
tfs.DisposeWrapper(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Call Dispose twice with disposing set to true once and another time set to false");
try
{
TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append);
tfs.DisposeWrapper(true);
tfs.DisposeWrapper(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
FileStreamDispose test = new FileStreamDispose();
TestLibrary.TestFramework.BeginTestCase("FileStreamDispose");
if (test.RunTesfs())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| {'content_hash': 'caf449e454a2f3a7cea751fff3bd8aa1', 'timestamp': '', 'source': 'github', 'line_count': 273, 'max_line_length': 142, 'avg_line_length': 26.454212454212453, 'alnum_prop': 0.5966491276654666, 'repo_name': 'ktos/coreclr', 'id': 'cb153729b891879ce99ecd0586bea88ba5bbbb28', 'size': '7222', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'tests/src/CoreMangLib/cti/system/io/filestream/filestreamdispose.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '940259'}, {'name': 'Awk', 'bytes': '5737'}, {'name': 'Batchfile', 'bytes': '34869'}, {'name': 'C', 'bytes': '6449646'}, {'name': 'C#', 'bytes': '119302073'}, {'name': 'C++', 'bytes': '67233976'}, {'name': 'CMake', 'bytes': '531458'}, {'name': 'Groff', 'bytes': '529523'}, {'name': 'Groovy', 'bytes': '26579'}, {'name': 'HTML', 'bytes': '16196'}, {'name': 'Makefile', 'bytes': '2314'}, {'name': 'Objective-C', 'bytes': '224503'}, {'name': 'Perl', 'bytes': '63850'}, {'name': 'PowerShell', 'bytes': '4332'}, {'name': 'Python', 'bytes': '8165'}, {'name': 'Shell', 'bytes': '59672'}, {'name': 'Smalltalk', 'bytes': '1359502'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. 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.
-->
<artifact name="magnetic_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.magnetic_1.0.0.json</file>
</artifact>
| {'content_hash': 'f5f8f16f2758092e4502581b1a64adac', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 102, 'avg_line_length': 39.17391304347826, 'alnum_prop': 0.7103218645948945, 'repo_name': 'GDLMadushanka/carbon-device-mgt-plugins', 'id': 'e222004ce199b57ae405db2166e4c207c37b794b', 'size': '901', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'components/analytics/iot-analytics/org.wso2.carbon.device.mgt.iot.analytics/src/main/resources/carbonapps/magnetic_sensor/magnetic_stream/artifact.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Arduino', 'bytes': '14451'}, {'name': 'Batchfile', 'bytes': '1054'}, {'name': 'C', 'bytes': '2475'}, {'name': 'CSS', 'bytes': '977941'}, {'name': 'HTML', 'bytes': '738728'}, {'name': 'Java', 'bytes': '3215752'}, {'name': 'JavaScript', 'bytes': '13545546'}, {'name': 'PLSQL', 'bytes': '3627'}, {'name': 'Python', 'bytes': '34465'}, {'name': 'Shell', 'bytes': '23638'}]} |
Verifies that writing a non-object to an object-typed property causes a fatal error
--FILE--
<?php
require_once __DIR__ . '/init.php';
$object = new \StrictPhpTestAsset\ClassWithGenericObjectTypedProperty();
$object->property = 'non-object';
?>
--EXPECTF--
%AFatal error: Uncaught exception 'ErrorException' with message 'NOPE'%a | {'content_hash': '85699e6e6d97ae7d32b75927c3082bcc', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 83, 'avg_line_length': 27.666666666666668, 'alnum_prop': 0.7439759036144579, 'repo_name': 'Roave/StrictPhp', 'id': '7b565c5176be9e96c03fbff65c6e3e1bb86d8b5a', 'size': '341', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'tests/functional/object-typed-property-violation.phpt', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '240795'}]} |
namespace {
bool IsOutermostMainFrame(content::RenderFrame* render_frame) {
return render_frame->IsMainFrame() && !render_frame->IsInFencedFrameTree();
}
} // namespace
gin::WrapperInfo SupervisedUserErrorPageController::kWrapperInfo = {
gin::kEmbedderNativeGin};
void SupervisedUserErrorPageController::Install(
content::RenderFrame* render_frame,
base::WeakPtr<SupervisedUserErrorPageControllerDelegate> delegate) {
v8::Isolate* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::MicrotasksScope microtasks_scope(
isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Local<v8::Context> context =
render_frame->GetWebFrame()->MainWorldScriptContext();
if (context.IsEmpty())
return;
v8::Context::Scope context_scope(context);
gin::Handle<SupervisedUserErrorPageController> controller = gin::CreateHandle(
isolate, new SupervisedUserErrorPageController(delegate, render_frame));
if (controller.IsEmpty())
return;
v8::Local<v8::Object> global = context->Global();
global
->Set(context,
gin::StringToV8(isolate, "supervisedUserErrorPageController"),
controller.ToV8())
.Check();
}
SupervisedUserErrorPageController::SupervisedUserErrorPageController(
base::WeakPtr<SupervisedUserErrorPageControllerDelegate> delegate,
content::RenderFrame* render_frame)
: delegate_(delegate), render_frame_(render_frame) {}
SupervisedUserErrorPageController::~SupervisedUserErrorPageController() {}
void SupervisedUserErrorPageController::GoBack() {
if (delegate_)
delegate_->GoBack();
}
void SupervisedUserErrorPageController::RequestUrlAccessRemote() {
if (delegate_) {
delegate_->RequestUrlAccessRemote(base::BindOnce(
&SupervisedUserErrorPageController::OnRequestUrlAccessRemote,
weak_factory_.GetWeakPtr()));
}
}
void SupervisedUserErrorPageController::RequestUrlAccessLocal() {
if (delegate_) {
delegate_->RequestUrlAccessLocal(base::BindOnce([](bool success) {
// We might want to handle the error in starting local approval flow
// later. For now just log a result.
VLOG(0) << "Local URL approval initiation result: " << success;
}));
}
}
void SupervisedUserErrorPageController::Feedback() {
if (delegate_)
delegate_->Feedback();
}
void SupervisedUserErrorPageController::OnRequestUrlAccessRemote(bool success) {
std::string result = success ? "true" : "false";
std::string is_outermost_main_frame =
IsOutermostMainFrame(render_frame_) ? "true" : "false";
std::string js =
base::StringPrintf("setRequestStatus(%s, %s)", result.c_str(),
is_outermost_main_frame.c_str());
render_frame_->ExecuteJavaScript(base::ASCIIToUTF16(js));
}
gin::ObjectTemplateBuilder
SupervisedUserErrorPageController::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<SupervisedUserErrorPageController>::
GetObjectTemplateBuilder(isolate)
.SetMethod("goBack", &SupervisedUserErrorPageController::GoBack)
.SetMethod("requestUrlAccessRemote",
&SupervisedUserErrorPageController::RequestUrlAccessRemote)
.SetMethod("requestUrlAccessLocal",
&SupervisedUserErrorPageController::RequestUrlAccessLocal)
.SetMethod("feedback", &SupervisedUserErrorPageController::Feedback);
}
| {'content_hash': '9f89ee5930bff142d6227f7943c2bc5c', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 80, 'avg_line_length': 35.95789473684211, 'alnum_prop': 0.7233606557377049, 'repo_name': 'nwjs/chromium.src', 'id': 'da71ced02de17a9831038e93d3949a96d999bb9e', 'size': '4173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/nw70', 'path': 'chrome/renderer/supervised_user/supervised_user_error_page_controller.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
body {
background: #ddd;
}
@-webkit-keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30%,
70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
}
}
@-moz-keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30%,
70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
}
}
@keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30%,
70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
}
}
@-webkit-keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
}
@-moz-keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
}
@keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
}
@-webkit-keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
}
@-moz-keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
}
@keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
}
.dropzone,
.dropzone * {
box-sizing: border-box;
}
.dropzone {
min-height: 150px;
border: 2px dashed #0087F7;
background: white;
margin: 10% 20%;
padding: 20px 20px;
}
.dropzone.dz-clickable {
cursor: pointer;
}
.dropzone.dz-clickable * {
cursor: default;
}
.dropzone.dz-clickable .dz-message,
.dropzone.dz-clickable .dz-message * {
cursor: pointer;
}
.dropzone.dz-started .dz-message {
display: none;
}
.dropzone.dz-drag-hover {
border-style: solid;
}
.dropzone.dz-drag-hover .dz-message {
opacity: 0.5;
}
.dropzone .dz-message {
text-align: center;
margin: 2em 0;
}
.dropzone .dz-preview {
position: relative;
display: inline-block;
vertical-align: top;
margin: 16px;
min-height: 100px;
}
.dropzone .dz-preview:hover {
z-index: 1000;
}
.dropzone .dz-preview:hover .dz-details {
opacity: 1;
}
.dropzone .dz-preview.dz-file-preview .dz-image {
border-radius: 20px;
background: #999;
background: linear-gradient(to bottom, #eee, #ddd);
}
.dropzone .dz-preview.dz-file-preview .dz-details {
opacity: 1;
}
.dropzone .dz-preview.dz-image-preview {
background: white;
}
.dropzone .dz-preview.dz-image-preview .dz-details {
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
-ms-transition: opacity 0.2s linear;
-o-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.dropzone .dz-preview .dz-remove {
font-size: 14px;
text-align: center;
display: block;
cursor: pointer;
border: none;
}
.dropzone .dz-preview .dz-remove:hover {
text-decoration: underline;
}
.dropzone .dz-preview:hover .dz-details {
opacity: 1;
}
.dropzone .dz-preview .dz-details {
z-index: 20;
position: absolute;
top: 0;
left: 0;
opacity: 0;
font-size: 13px;
min-width: 100%;
max-width: 100%;
padding: 2em 1em;
text-align: center;
color: rgba(0, 0, 0, 0.9);
line-height: 150%;
}
.dropzone .dz-preview .dz-details .dz-size {
margin-bottom: 1em;
font-size: 16px;
}
.dropzone .dz-preview .dz-details .dz-filename {
white-space: nowrap;
}
.dropzone .dz-preview .dz-details .dz-filename:hover span {
border: 1px solid rgba(200, 200, 200, 0.8);
background-color: rgba(255, 255, 255, 0.8);
}
.dropzone .dz-preview .dz-details .dz-filename:not(:hover) {
overflow: hidden;
text-overflow: ellipsis;
}
.dropzone .dz-preview .dz-details .dz-filename:not(:hover) span {
border: 1px solid transparent;
}
.dropzone .dz-preview .dz-details .dz-filename span,
.dropzone .dz-preview .dz-details .dz-size span {
background-color: rgba(255, 255, 255, 0.4);
padding: 0 0.4em;
border-radius: 3px;
}
.dropzone .dz-preview:hover .dz-image img {
-webkit-transform: scale(1.05, 1.05);
-moz-transform: scale(1.05, 1.05);
-ms-transform: scale(1.05, 1.05);
-o-transform: scale(1.05, 1.05);
transform: scale(1.05, 1.05);
-webkit-filter: blur(8px);
filter: blur(8px);
}
.dropzone .dz-preview .dz-image {
border-radius: 20px;
overflow: hidden;
width: 120px;
height: 120px;
position: relative;
display: block;
z-index: 10;
}
.dropzone .dz-preview .dz-image img {
display: block;
}
.dropzone .dz-preview.dz-success .dz-success-mark {
-webkit-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-moz-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-ms-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-o-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
}
.dropzone .dz-preview.dz-error .dz-error-mark {
opacity: 1;
-webkit-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-moz-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-ms-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-o-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
}
.dropzone .dz-preview .dz-success-mark,
.dropzone .dz-preview .dz-error-mark {
pointer-events: none;
opacity: 0;
z-index: 500;
position: absolute;
display: block;
top: 50%;
left: 50%;
margin-left: -27px;
margin-top: -27px;
}
.dropzone .dz-preview .dz-success-mark svg,
.dropzone .dz-preview .dz-error-mark svg {
display: block;
width: 54px;
height: 54px;
}
.dropzone .dz-preview.dz-processing .dz-progress {
opacity: 1;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear;
}
.dropzone .dz-preview.dz-complete .dz-progress {
opacity: 0;
-webkit-transition: opacity 0.4s ease-in;
-moz-transition: opacity 0.4s ease-in;
-ms-transition: opacity 0.4s ease-in;
-o-transition: opacity 0.4s ease-in;
transition: opacity 0.4s ease-in;
}
.dropzone .dz-preview:not(.dz-processing) .dz-progress {
-webkit-animation: pulse 6s ease infinite;
-moz-animation: pulse 6s ease infinite;
-ms-animation: pulse 6s ease infinite;
-o-animation: pulse 6s ease infinite;
animation: pulse 6s ease infinite;
}
.dropzone .dz-preview .dz-progress {
opacity: 1;
z-index: 1000;
pointer-events: none;
position: absolute;
height: 16px;
left: 50%;
top: 50%;
margin-top: -8px;
width: 80px;
margin-left: -40px;
background: rgba(255, 255, 255, 0.9);
-webkit-transform: scale(1);
border-radius: 8px;
overflow: hidden;
}
.dropzone .dz-preview .dz-progress .dz-upload {
background: #333;
background: linear-gradient(to bottom, #666, #444);
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 0;
-webkit-transition: width 300ms ease-in-out;
-moz-transition: width 300ms ease-in-out;
-ms-transition: width 300ms ease-in-out;
-o-transition: width 300ms ease-in-out;
transition: width 300ms ease-in-out;
}
.dropzone .dz-preview.dz-error .dz-error-message {
display: block;
}
.dropzone .dz-preview.dz-error:hover .dz-error-message {
opacity: 1;
pointer-events: auto;
}
.dropzone .dz-preview .dz-error-message {
pointer-events: none;
z-index: 1000;
position: absolute;
display: block;
display: none;
opacity: 0;
-webkit-transition: opacity 0.3s ease;
-moz-transition: opacity 0.3s ease;
-ms-transition: opacity 0.3s ease;
-o-transition: opacity 0.3s ease;
transition: opacity 0.3s ease;
border-radius: 8px;
font-size: 13px;
top: 130px;
left: -10px;
width: 140px;
background: #be2626;
background: linear-gradient(to bottom, #be2626, #a92222);
padding: 0.5em 1.2em;
color: white;
}
.dropzone .dz-preview .dz-error-message:after {
content: '';
position: absolute;
top: -6px;
left: 64px;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid #be2626;
} | {'content_hash': '3f217d24d9a68d4aae319cc0b44b0d56', 'timestamp': '', 'source': 'github', 'line_count': 522, 'max_line_length': 74, 'avg_line_length': 24.35823754789272, 'alnum_prop': 0.5996067636649627, 'repo_name': 'helloflask/flask-upload-dropzone', 'id': '666a30cc445cb7167f8310f661fb4ab278c70ca5', 'size': '12786', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'static/dropzone.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12786'}, {'name': 'HTML', 'bytes': '467'}, {'name': 'JavaScript', 'bytes': '64399'}, {'name': 'Python', 'bytes': '714'}]} |
package org.apache.nifi.processors.windows.event.log;
public class AlreadySubscribedException extends Exception {
public AlreadySubscribedException(String message) {
super(message);
}
}
| {'content_hash': 'bffc04b83d7f2b7ddae22b458620490c', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 59, 'avg_line_length': 22.77777777777778, 'alnum_prop': 0.7560975609756098, 'repo_name': 'trixpan/nifi', 'id': 'b28ac616310d5864524bfa6702e5fab91acee884', 'size': '1006', 'binary': False, 'copies': '38', 'ref': 'refs/heads/master', 'path': 'nifi-nar-bundles/nifi-windows-event-log-bundle/nifi-windows-event-log-processors/src/main/java/org/apache/nifi/processors/windows/event/log/AlreadySubscribedException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '18771'}, {'name': 'CSS', 'bytes': '221626'}, {'name': 'Clojure', 'bytes': '3993'}, {'name': 'GAP', 'bytes': '30012'}, {'name': 'Groovy', 'bytes': '1301281'}, {'name': 'HTML', 'bytes': '393167'}, {'name': 'Java', 'bytes': '28062641'}, {'name': 'JavaScript', 'bytes': '2658085'}, {'name': 'Lua', 'bytes': '983'}, {'name': 'Python', 'bytes': '17954'}, {'name': 'Ruby', 'bytes': '8028'}, {'name': 'Shell', 'bytes': '43972'}, {'name': 'XSLT', 'bytes': '5681'}]} |
const ljm = require('./JitsiMeetJS').default;
/**
* Tries to deal with the following problem: {@code JitsiMeetJS} is not only
* this module, it's also a global (i.e. attached to {@code window}) namespace
* for all globals of the projects in the Jitsi Meet family. If lib-jitsi-meet
* is loaded through an HTML {@code script} tag, {@code JitsiMeetJS} will
* automatically be attached to {@code window} by webpack. Unfortunately,
* webpack's source code does not check whether the global variable has already
* been assigned and overwrites it. Which is OK for the module
* {@code JitsiMeetJS} but is not OK for the namespace {@code JitsiMeetJS}
* because it may already contain the values of other projects in the Jitsi Meet
* family. The solution offered here works around webpack by merging all
* existing values of the namespace {@code JitsiMeetJS} into the module
* {@code JitsiMeetJS}.
*
* @param {Object} module - The module {@code JitsiMeetJS} (which will be
* exported and may be attached to {@code window} by webpack later on).
* @private
* @returns {Object} - A {@code JitsiMeetJS} module which contains all existing
* value of the namespace {@code JitsiMeetJS} (if any).
*/
function _mergeNamespaceAndModule(module) {
return (
typeof window.JitsiMeetJS === 'object'
? Object.assign({}, window.JitsiMeetJS, module)
: module);
}
module.exports = _mergeNamespaceAndModule(ljm);
| {'content_hash': '765472ecedd969c4eaf0e41dea66ffd3', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 80, 'avg_line_length': 48.03333333333333, 'alnum_prop': 0.7196391394864677, 'repo_name': 'jitsi/lib-jitsi-meet', 'id': 'ec0d9790ba352a61ec44ade21c379e53068e87d7', 'size': '1441', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '1658192'}, {'name': 'TypeScript', 'bytes': '225417'}]} |
import React from 'react';
import OfflineLicenseModal from './OfflineLicenseModal';
export default {
title: 'admin/info/OfflineLicenseModal',
component: OfflineLicenseModal,
};
export const _default = () => <OfflineLicenseModal onClose={() => {}} />;
| {'content_hash': '1d3f940d9ef62ed8fd07c35de91bfc02', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 73, 'avg_line_length': 25.6, 'alnum_prop': 0.7265625, 'repo_name': 'VoiSmart/Rocket.Chat', 'id': '90aeaeabd38cfabaeaaee23a0b97677285d9eede', 'size': '256', 'binary': False, 'copies': '3', 'ref': 'refs/heads/ng_integration', 'path': 'client/views/admin/info/OfflineLicenseModal.stories.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '549'}, {'name': 'CSS', 'bytes': '818469'}, {'name': 'Dockerfile', 'bytes': '1895'}, {'name': 'HTML', 'bytes': '701096'}, {'name': 'JavaScript', 'bytes': '5470868'}, {'name': 'Shell', 'bytes': '25172'}, {'name': 'Smarty', 'bytes': '1052'}, {'name': 'Standard ML', 'bytes': '1843'}]} |
<?xml version="1.0" encoding="utf-8"?>
<alert-report domain="Cat" start-time="2014-04-25 20:00:00" end-time="2014-04-25 20:59:59">
<domain name="MobileApi" warn-number="18" error-number="55">
<exception id="MobileApi-NPE1" warn-number="6" error-number="20"/>
<exception id="MobileApi-NPE2" warn-number="6" error-number="15"/>
<exception id="MobileApi-NPE3" warn-number="1" error-number="10"/>
<exception id="MobileApi-NPE4" warn-number="5" error-number="10"/>
</domain>
<domain name="TuanGouJob" warn-number="10" error-number="20">
<exception id="TuanGouJob-NPE1" warn-number="5" error-number="10"/>
<exception id="TuanGouJob-NPE2" warn-number="5" error-number="10"/>
</domain>
<domain name="TuangouWeb" warn-number="7" error-number="15">
<exception id="TuangouWeb-NPE1" warn-number="2" error-number="5"/>
<exception id="TuangouWeb-NPE2" warn-number="5" error-number="10"/>
</domain>
</alert-report>
| {'content_hash': 'b1a37309e7de47b5c7e2f83e13b27f7d', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 91, 'avg_line_length': 56.8235294117647, 'alnum_prop': 0.6594202898550725, 'repo_name': 'bryanchou/cat', 'id': 'cc11ee90343546e0eaf27cd55c28f5c10ec384b2', 'size': '966', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'cat-home/src/test/resources/com/dianping/cat/report/alert/result.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '11263'}, {'name': 'CSS', 'bytes': '1550465'}, {'name': 'HTML', 'bytes': '11727'}, {'name': 'Java', 'bytes': '4158514'}, {'name': 'JavaScript', 'bytes': '13804187'}, {'name': 'Python', 'bytes': '11726'}, {'name': 'Shell', 'bytes': '33894'}]} |
package records
package benchmark
import java.io._
import scala.tools.nsc._
import scala.tools.nsc.util._
import scala.tools.nsc.reporters._
import scala.tools.nsc.io._
import scala.io._
import scala.tools.nsc.interpreter.AbstractFileClassLoader
import scala.reflect.internal.util.BatchSourceFile
trait TypecheckingBenchmarkingSuite {
var compiler: Global = _
var cReporter: ConsoleReporter = _
def settings(args: List[String] = Nil): Settings = {
val newSettings = new Settings()
newSettings.classpath.value = this.getClass.getClassLoader match {
case ctx: java.net.URLClassLoader => ctx.getURLs.map(_.getPath).mkString(":")
case _ => System.getProperty("java.class.path")
}
newSettings.bootclasspath.value = Predef.getClass.getClassLoader match {
case ctx: java.net.URLClassLoader => ctx.getURLs.map(_.getPath).mkString(":")
case _ => System.getProperty("sun.boot.class.path")
}
newSettings.encoding.value = "UTF-8"
newSettings.outdir.value = "."
newSettings.extdirs.value = ""
newSettings.processArguments(args, true)
newSettings
}
def setupCompiler(args: List[String] = Nil): Unit = {
cReporter = new ConsoleReporter(settings(args), null, new PrintWriter(System.out))
compiler = new Global(settings(args), cReporter)
val fileSystem = new VirtualDirectory("<vfs>", None)
compiler.settings.outputDirs.setSingleOutput(fileSystem)
}
def compileSource(source: String): Unit = {
val comp = compiler
val run = new comp.Run
run.compileSources(scala.List(new BatchSourceFile("<stdin>", source)))
cReporter.printSummary()
}
}
| {'content_hash': '0e712c2810a23e3e342704b89372111e', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 86, 'avg_line_length': 35.25, 'alnum_prop': 0.6932624113475178, 'repo_name': 'scala-records/scala-records-benchmarks', 'id': '782600c436ce8acd1f96bc8f22d72d85d52bc2b8', 'size': '1692', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/scala/records/benchmark/TypecheckingBenchmarkingSuite.scala', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Scala', 'bytes': '9195'}]} |
<!---
Copyright 2017 The AMP HTML Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
# Video analytics
## Support
AMP video analytics gathers data about how users interact with videos in AMP documents. Only AMP video extensions which implement AMP's common video interface are supported. These are listed below:
| Extension | Support level |
| --------------------- | ----------------------------- |
| `<amp-video>` | Full support |
| `<amp-3q-player>` | Partial support<sup>[1]</sup> |
| `<amp-brid-player>` | Partial support<sup>[1]</sup> |
| `<amp-brightcove>` | Full support |
| `<amp-dailymotion>` | Partial support<sup>[1]</sup> |
| `<amp-ima-video>` | Partial support<sup>[1]</sup> |
| `<amp-nexxtv-player>` | Partial support<sup>[1]</sup> |
| `<amp-ooyala-player>` | Partial support<sup>[1]</sup> |
| `<amp-youtube>` | Partial support<sup>[1]</sup> |
| `<amp-viqeo-player>` | Full support |
<sup>[1]</sup> Partial support means that all [video analytics common variables](#common-variables) are included, except for `currentTime`, `duration`, `playedRangesJson`, and `playedTotal`.
## Video analytics triggers
Supported AMP video extensions issue various analytics events during their lifecycle. These events can be reported through the analytics configuration using `video-*` triggers.
See [the AMP Analytics component](../amp-analytics/amp-analytics.md) for details on _amp-analytics_ configuration.
### Video play trigger (`"on": "video-play"`)
The `video-play` trigger is fired when the video begins playing from a user clicking play or from autoplay beginning or resuming. Use these configurations to fire a request for this event.
```javascript
"triggers": {
"myVideoPlay": {
"on": "video-play",
"request": "event",
"selector": "#myVideo",
"videoSpec": {/* optional videoSpec */}
},
}
```
_Note:_ This event was initially mapped to the `playing` event emitted by video elements instead of the `play` event. This may lead to overcounting as those events are also emitted when playing was interrupted by network issues. While this bug has been fixed in general, individual video players may continue to use the `playing` event internally instead of the `play` event.
### Video pause trigger (`"on": "video-pause"`)
The `video-pause` trigger is fired when the video stops playing from a user clicking pause, from autoplay pausing, or from the video reaching the end. Use these configurations to fire a request for this event.
```javascript
"triggers": {
"myVideoPause": {
"on": "video-pause",
"request": "event",
"selector": "#myVideo",
"videoSpec": {/* optional videoSpec */}
},
}
```
### Video ended trigger (`"on": "video-ended"`)
The `video-ended` trigger is fired when the video has reached the end of playback. Use these configurations to fire a request for this event.
```javascript
"triggers": {
"myVideoEnded": {
"on": "video-ended",
"request": "event",
"selector": "#myVideo",
"videoSpec": {/* optional videoSpec */}
},
}
```
### Video session trigger (`"on": "video-session"`)
The `video-session` trigger is fired when a "video session" has ended. A video session starts when a video is played and ends when the video pauses, ends, or becomes invisible (optionally configurable). This trigger is configurable via the `videoSpec`. Configuration options include:
1. `end-session-when-invisible`
Ends the session when the video becomes invisible after scrolling out of the viewport.
2. `exclude-autoplay`
Excludes autoplaying videos from reporting.
```javascript
"triggers": {
"myVideoSession": {
"on": "video-session",
"request": "event",
"selector": "#myVideo",
"videoSpec": {/* optional videoSpec */}
},
}
```
### Video seconds played trigger (`"on": "video-seconds-played"`)
The `video-seconds-played` trigger is fired every `interval` seconds when the video is playing. The `video-seconds-played` trigger _requires_ `interval` to be set in the `videoSpec`. Use these configurations to fire a request for this event.
```javascript
"triggers": {
"myVideoSecondsPlayed": {
"on": "video-seconds-played",
"request": "event",
"selector": "#myVideo",
"videoSpec": {
"interval": 10, /* required */
/* other optional videoSpec properties */
}
},
}
```
### Video percentage played trigger (`"on": "video-percentage-played"`)
The `video-percentage-played` trigger is fired every `percentages` when the video is playing. The `video-percentage-played` trigger _requires_ `percentages` to be set in the `videoSpec`. Use these configurations to fire a request for this event.
Percentages must be set in increments of 5% and must be over zero.
```javascript
"triggers": {
"myVideoPercentagePlayed": {
"on": "video-percentage-played",
"request": "event",
"selector": "#myVideo",
"videoSpec": {
"percentages": [5, 25, 50, 75, 100], /* required */
/* other optional videoSpec properties */
}
},
}
```
### Ad Start trigger (`"on": "video-ad-start"`)
The `video-ad-start` trigger is fired when an Ad starts playing.
```javascript
"triggers": {
"adStart": {
"on": "video-ad-start",
"request": "event",
"selector": "#myVideo"
},
}
```
### Ad End trigger (`"on": "video-ad-end"`))
The `video-ad-start` trigger is fired when an Ad ends playing.
```javascript
"triggers": {
"adEnd": {
"on": "video-ad-end",
"request": "event",
"selector": "#myVideo"
},
}
```
## Video spec
You can use the `videoSpec` configuration object to control how the requests are fired.
### `end-session-when-invisible`
This spec property controls the `video-session` trigger. If `true`, the trigger will fire when the video is no longer visible, even if it is still playing. The default value is `false`.
### `exclude-autoplay`
This spec property controls all `video-*` triggers. If `true`, the trigger will not fire for videos that are autoplaying when the triggering event occurs. If a user interacts with the video and causes autoplay to stop, `video-*` triggers configured with `"exclude-autoplay": true` will begin to fire for that video. The default value is `false`.
### `interval`
This spec property controls the `video-seconds-played` trigger, and it is _required_ for `video-seconds-played`.The value for `interval` specifies the number of seconds between each `video-seconds-played` event, and it must be greater than `0`. For example, a value of `10` fires the trigger every 10 seconds when the video is playing.
## Common variables
All video analytics triggers expose the following variables. These variables are also available in variable substitution with the [`VIDEO_STATE`](#VIDEO_STATE) variable.
| Var | Type | Description |
| ------------------ | ------- | -------------------------------------------------------------------------------------------------------------- |
| `autoplay` | Boolean | Indicates whether the video began as an autoplay video. |
| `currentTime` | Number | Specifies the current playback time (in seconds) at the time of trigger. |
| `duration` | Number | Specifies the total duration of the video (in seconds). |
| `height` | Number | Specifies the height of video (in px). |
| `id` | String | Specifies the ID of the video element. |
| `playedTotal` | Number | Specifies the total amount of time the user has watched the video. |
| `state` | String | Indicates the state, which can be one “playing_auto”, “playing_manual”, or “paused”. |
| `width` | Number | Specifies the width of video (in px). |
| `playedRangesJson` | String | Represents segments of time the user has watched the video (in JSON format). For example, `[[1, 10], [5, 20]]` |
## Click-to-play Events
Click events set directly on video component elements (like `amp-video`) will not be captured consistently due to implementation details of the browser's native video player or the player component itself.
You can capture independent `play`/`pause` events by using the [`video-play`](#video-play-trigger-on-video-play) and [`video-pause`](#video-pause-trigger-on-video-pause) triggers.
If you'd like to capture the initial `play` event (e.g. click-to-play), you can [place an overlay on the video player](https://amp.dev/documentation/examples/multimedia-animations/click-to-play_overlay_for_amp-video/) and configure a `click` analytics request that refers to the overlay element (`#myOverlay`):
```javascript
"triggers": {
"video-clicked": {
"on": "click",
"request": "event",
"selector": "#myOverlay"
},
}
```
## Video analytics variables
Video analytics contributes the following variables to [AMP URL Variable Substitutions](../../spec/amp-var-substitutions.md).
### VIDEO_STATE
The `VIDEO_STATE(selector,property)` variable is substituted with the value of the selected video's specified property, as defined under [Common variables](#common-variables) above. The `selector` argument can be any valid CSS selector. The `property` argument can be the name of any of the common video analytics variables.
| {'content_hash': 'be3b0e7f15e8f5043cd14ea3f86d3bdc', 'timestamp': '', 'source': 'github', 'line_count': 236, 'max_line_length': 375, 'avg_line_length': 43.66101694915254, 'alnum_prop': 0.6453804347826086, 'repo_name': 'voyagegroup/amphtml', 'id': '448d261e8d3fc94849de165699744c3caf9dafe1', 'size': '10316', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'extensions/amp-analytics/amp-video-analytics.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '1602462'}, {'name': 'CSS', 'bytes': '532090'}, {'name': 'Go', 'bytes': '7573'}, {'name': 'HTML', 'bytes': '2044560'}, {'name': 'JavaScript', 'bytes': '19029249'}, {'name': 'Python', 'bytes': '65270'}, {'name': 'Shell', 'bytes': '21662'}, {'name': 'Starlark', 'bytes': '30908'}, {'name': 'TypeScript', 'bytes': '17646'}, {'name': 'Yacc', 'bytes': '28669'}]} |
โปรเจคแรกของเราใน Cyber Advanced System & Network
| {'content_hash': 'a9dc0277996d9b4a7d242575f9f15656', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 53, 'avg_line_length': 54.0, 'alnum_prop': 0.8518518518518519, 'repo_name': 'mob35/cyber-nodejs-mob35', 'id': '10e7828840d9c47e44485a972eac7436dfc0faf7', 'size': '109', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '6'}]} |
Tainted
=======
Social Game - 3am Insomnia ...
Fun project to Try out some TDD with an nice automated front end :)
Test
Karma
Jasmine
PhantomJS
yo webapp --coffee
bower install & npm install
start using: Grunt serve | {'content_hash': 'a815ca76914815ea3a7c21d890f58060', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 67, 'avg_line_length': 11.3, 'alnum_prop': 0.7123893805309734, 'repo_name': 'Mimieam/Tainted', 'id': '1b0208f59e82aa379eb21e0cf2fd2db28d387baf', 'size': '226', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8296'}, {'name': 'CoffeeScript', 'bytes': '73534'}, {'name': 'JavaScript', 'bytes': '76065'}]} |
#ifndef SVGUnitTypes_h
#define SVGUnitTypes_h
#include "bindings/core/v8/ScriptWrappable.h"
#include "core/svg/SVGEnumeration.h"
#include "platform/heap/Handle.h"
#include "wtf/RefCounted.h"
namespace blink {
class SVGUnitTypes final : public RefCountedWillBeGarbageCollected<SVGUnitTypes>, public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
enum SVGUnitType {
SVG_UNIT_TYPE_UNKNOWN = 0,
SVG_UNIT_TYPE_USERSPACEONUSE = 1,
SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2
};
void trace(Visitor*) { }
private:
SVGUnitTypes(); // No instantiation.
};
template<> const SVGEnumerationStringEntries& getStaticStringEntries<SVGUnitTypes::SVGUnitType>();
} // namespace blink
#endif // SVGUnitTypes_h
| {'content_hash': '1789759b4cfa4608879b3dde79154e87', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 106, 'avg_line_length': 23.96875, 'alnum_prop': 0.7053455019556715, 'repo_name': 'nwjs/blink', 'id': '92bf635b8f85c0874e0082c88a62497aa3c4e531', 'size': '1610', 'binary': False, 'copies': '7', 'ref': 'refs/heads/nw12', 'path': 'Source/core/svg/SVGUnitTypes.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '1835'}, {'name': 'Assembly', 'bytes': '14584'}, {'name': 'Batchfile', 'bytes': '35'}, {'name': 'C', 'bytes': '105608'}, {'name': 'C++', 'bytes': '42652662'}, {'name': 'CSS', 'bytes': '537806'}, {'name': 'CoffeeScript', 'bytes': '163'}, {'name': 'GLSL', 'bytes': '11578'}, {'name': 'Groff', 'bytes': '28067'}, {'name': 'HTML', 'bytes': '56362733'}, {'name': 'Java', 'bytes': '108885'}, {'name': 'JavaScript', 'bytes': '26647564'}, {'name': 'Objective-C', 'bytes': '47905'}, {'name': 'Objective-C++', 'bytes': '342893'}, {'name': 'PHP', 'bytes': '171657'}, {'name': 'Perl', 'bytes': '583379'}, {'name': 'Python', 'bytes': '3788510'}, {'name': 'Ruby', 'bytes': '141818'}, {'name': 'Shell', 'bytes': '8888'}, {'name': 'XSLT', 'bytes': '49926'}, {'name': 'Yacc', 'bytes': '64744'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- Mirrored from bvs.wikidot.com/jutsu:advanced-redeye by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 10 Jul 2022 03:11:29 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack -->
<head>
<title>Advanced RedEye - Billy Vs. SNAKEMAN Wiki</title>
<script type="text/javascript" src="http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--javascript/init.combined.js"></script>
<script type="text/javascript">
var URL_HOST = 'www.wikidot.com';
var URL_DOMAIN = 'wikidot.com';
var USE_SSL = true ;
var URL_STATIC = 'http://d3g0gp89917ko0.cloudfront.net/v--291054f06006';
// global request information
var WIKIREQUEST = {};
WIKIREQUEST.info = {};
WIKIREQUEST.info.domain = "bvs.wikidot.com";
WIKIREQUEST.info.siteId = 32011;
WIKIREQUEST.info.siteUnixName = "bvs";
WIKIREQUEST.info.categoryId = 182049;
WIKIREQUEST.info.themeId = 9564;
WIKIREQUEST.info.requestPageName = "jutsu:advanced-redeye";
OZONE.request.timestamp = 1657419408;
OZONE.request.date = new Date();
WIKIREQUEST.info.lang = 'en';
WIKIREQUEST.info.pageUnixName = "jutsu:advanced-redeye";
WIKIREQUEST.info.pageId = 3061481;
WIKIREQUEST.info.lang = "en";
OZONE.lang = "en";
var isUAMobile = !!/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
</script>
<script type="text/javascript">
require.config({
baseUrl: URL_STATIC + '/common--javascript',
paths: {
'jquery.ui': 'jquery-ui.min',
'jquery.form': 'jquery.form'
}
});
</script>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<meta http-equiv="content-language" content="en"/>
<script type="text/javascript" src="http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--javascript/WIKIDOT.combined.js"></script>
<style type="text/css" id="internal-style">
/* modules */
/* theme */
@import url(http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--theme/base/css/style.css);
@import url(http://bvs.wdfiles.com/local--theme/north/style.css);
</style>
<link rel="shortcut icon" href="local--favicon/favicon.gif"/>
<link rel="icon" type="image/gif" href="local--favicon/favicon.gif"/>
<link rel="apple-touch-icon" href="common--images/apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="72x72" href="common--images/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="114x114" href="common--images/apple-touch-icon-114x114.png" />
<link rel="alternate" type="application/wiki" title="Edit this page" href="javascript:WIKIDOT.page.listeners.editClick()"/>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18234656-1']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
_gaq.push(['old._setAccount', 'UA-68540-5']);
_gaq.push(['old._setDomainName', 'none']);
_gaq.push(['old._setAllowLinker', true]);
_gaq.push(['old._trackPageview']);
_gaq.push(['userTracker._setAccount', 'UA-3581307-1']);
_gaq.push(['userTracker._trackPageview']);
</script>
<script type="text/javascript">
window.google_analytics_uacct = 'UA-18234656-1';
window.google_analytics_domain_name = 'none';
</script>
<link rel="manifest" href="onesignal/manifest.html" />
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" acync=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: null,
});
});
</script>
<script>window.nitroAds=window.nitroAds||{createAd:function(){window.nitroAds.queue.push(["createAd",arguments])},addUserToken:function(){window.nitroAds.queue.push(["addUserToken",arguments])},queue:[]};</script>
<script async src="https://s.nitropay.com/ads-143.js"></script>
</head>
<body id="html-body">
<div id="skrollr-body">
<a name="page-top"></a>
<!-- side slide skyscraper -->
<div id="wad-tier3-side-slide" class="wd-adunit wd-ad-np wd-adunit-side_slide"></div>
<script>
$j( function(){
var $c = $j('#container');
var s = $j(window).width() - ($c.width()+$c.offset().left);
var ri = s - 180;
var $o = $j('#wad-tier3-side-slide');
if( s > 200 ) {
$o.css('right', ri + 'px');
window['nitroAds'].createAd('wad-tier3-side-slide', {
"refreshLimit": 10,
"refreshTime": 85,
"renderVisibleOnly": false,
"refreshVisibleOnly": true,
"sizes": [ [ 160, 600 ] ],
"report": {
"enabled": true,
"wording": "Report Ad",
"position": "bottom-right"
}
});
} else {
$o.remove();
}
});
</script>
<div id="container-wrap-wrap">
<div id="container-wrap">
<div id="container">
<div id="header">
<h1><a href="index.html"><span>Billy Vs. SNAKEMAN Wiki</span></a></h1>
<h2><span>Be the Ultimate Ninja.</span></h2>
<!-- google_ad_section_start(weight=ignore) -->
<div id="search-top-box" class="form-search">
<form id="search-top-box-form" action="http://bvs.wikidot.com/dummy" class="input-append">
<input id="search-top-box-input" class="text empty search-query" type="text" size="15" name="query" value="Search this site" onfocus="if(YAHOO.util.Dom.hasClass(this, 'empty')){YAHOO.util.Dom.removeClass(this,'empty'); this.value='';}"/><input class="button btn" type="submit" name="search" value="Search"/>
</form>
</div>
<div id="top-bar">
<ul>
<li><a href="allies.html">Allies</a>
<ul>
<li><strong><a href="untabbed_allies.html">Allies Untabbed</a></strong></li>
<li><a href="allies.html#toc7">Burger Ninja</a></li>
<li><a href="allies.html#toc5">Reaper</a></li>
<li><a href="allies.html#toc0">Regular</a></li>
<li><a href="allies.html#toc8">R00t</a></li>
<li><a href="allies.html#toc1">Season 2+</a></li>
<li><a href="allies.html#toc2">Season 3+</a></li>
<li><a href="allies.html#toc3">Season 4+</a></li>
<li><a href="allies.html#toc4">The Trade</a></li>
<li><a href="allies.html#toc6">Wasteland</a></li>
<li><a href="allies.html#toc9">World Kaiju</a></li>
<li><strong><a href="summons.html">Summons</a></strong></li>
<li><strong><a href="teams.html">Teams</a></strong></li>
</ul>
</li>
<li><a href="missions.html">Missions</a>
<ul>
<li><strong><a href="untabbed_missions.html">Missions Untabbed</a></strong></li>
<li><strong><em><a href="missions.html#toc0">D-Rank</a></em></strong></li>
<li><strong><em><a href="missions.html#toc1">C-Rank</a></em></strong></li>
<li><strong><em><a href="missions.html#toc2">B-Rank</a></em></strong></li>
<li><strong><em><a href="missions.html#toc3">A-Rank</a></em></strong></li>
<li><strong><em><a href="missions.html#toc4">AA-Rank</a></em></strong></li>
<li><strong><em><a href="missions.html#toc5">S-Rank</a></em></strong></li>
<li><a href="missions.html#toc10">BurgerNinja</a></li>
<li><a href="missions.html#toc14">Cave</a></li>
<li><a href="missions.html#toc13">Jungle</a></li>
<li><a href="missions.html#toc7">Monochrome</a></li>
<li><a href="missions.html#toc8">Outskirts</a></li>
<li><a href="missions.html#toc11">PizzaWitch</a></li>
<li><a href="missions.html#toc6">Reaper</a></li>
<li><a href="missions.html#toc9">Wasteland</a></li>
<li><a href="missions.html#toc12">Witching Hour</a></li>
<li><strong><em><a href="missions.html#toc14">Quests</a></em></strong></li>
<li><a href="wota.html">Mission Lady Alley</a></li>
</ul>
</li>
<li><a href="items.html">Items</a>
<ul>
<li><strong><a href="untabbed_items.html">Items Untabbed</a></strong></li>
<li><a href="items.html#toc6">Ally Drops and Other</a></li>
<li><a href="items.html#toc0">Permanent Items</a></li>
<li><a href="items.html#toc1">Potions/Crafting Items</a>
<ul>
<li><a href="items.html#toc4">Crafting</a></li>
<li><a href="items.html#toc3">Ingredients</a></li>
<li><a href="items.html#toc2">Potions</a></li>
</ul>
</li>
<li><a href="items.html#toc5">Wasteland Items</a></li>
<li><a href="sponsored-items.html">Sponsored Items</a></li>
</ul>
</li>
<li><a href="village.html">Village</a>
<ul>
<li><a href="billycon.html">BillyCon</a>
<ul>
<li><a href="billycon_billy-idol.html">Billy Idol</a></li>
<li><a href="billycon_cosplay.html">Cosplay</a></li>
<li><a href="billycon_dealer-s-room.html">Dealer's Room</a></li>
<li><a href="billycon_events.html">Events</a></li>
<li><a href="billycon_glowslinging.html">Glowslinging</a></li>
<li><a href="billycon_rave.html">Rave</a></li>
<li><a href="billycon_squee.html">Squee</a></li>
<li><a href="billycon_video-game-tournament.html">Video Game Tournament</a></li>
<li><a href="billycon_wander.html">Wander</a></li>
</ul>
</li>
<li><a href="billytv.html">BillyTV</a></li>
<li><a href="bingo-ing.html">Bingo'ing</a></li>
<li><a href="candyween.html">Candyween</a></li>
<li><a href="festival.html">Festival Day</a>
<ul>
<li><a href="festival_bargltron.html">Bargltron</a></li>
<li><a href="festival_billymaze.html">BillyMaze</a></li>
<li><a href="festival_dance-party.html">Dance Party</a></li>
<li><a href="festival_elevensnax.html">ElevenSnax</a></li>
<li><a href="festival_marksman.html">Marksman</a></li>
<li><a href="festival_raffle.html">Raffle</a></li>
<li><a href="festival_rngshack.html">RNGShack</a></li>
<li><a href="festival_tsukiroll.html">TsukiRoll</a></li>
<li><a href="festival_tunnel.html">Tunnel</a></li>
</ul>
</li>
<li><a href="hidden-hoclaus.html">Hidden HoClaus</a></li>
<li><a href="kaiju.html">Kaiju</a></li>
<li><a href="marketplace.html">Marketplace</a></li>
<li><a href="pizzawitch-garage.html">PizzaWitch Garage</a></li>
<li><a href="robo-fighto.html">Robo Fighto</a></li>
<li>R00t
<ul>
<li><a href="fields.html">Fields</a></li>
<li><a href="keys.html">Keys</a></li>
<li><a href="phases.html">Phases</a></li>
</ul>
</li>
<li><a href="upgrade_science-facility.html#toc2">SCIENCE!</a></li>
<li><a href="upgrades.html">Upgrades</a></li>
<li><a href="zombjas.html">Zombjas</a></li>
</ul>
</li>
<li><a href="misc_party-house.html">Party House</a>
<ul>
<li><a href="partyhouse_11dbhk-s-lottery.html">11DBHK's Lottery</a></li>
<li><a href="partyhouse_akatsukiball.html">AkaTsukiBall</a></li>
<li><a href="upgrade_claw-machines.html">Crane Game!</a></li>
<li><a href="upgrade_darts-hall.html">Darts!</a></li>
<li><a href="partyhouse_flower-wars.html">Flower Wars</a></li>
<li><a href="upgrade_juice-bar.html">'Juice' Bar</a></li>
<li><a href="partyhouse_mahjong.html">Mahjong</a></li>
<li><a href="partyhouse_ninja-jackpot.html">Ninja Jackpot!</a></li>
<li><a href="partyhouse_over-11-000.html">Over 11,000</a></li>
<li><a href="partyhouse_pachinko.html">Pachinko</a></li>
<li><a href="partyhouse_party-room.html">Party Room</a></li>
<li><a href="partyhouse_pigeons.html">Pigeons</a></li>
<li><a href="partyhouse_prize-wheel.html">Prize Wheel</a></li>
<li><a href="partyhouse_roulette.html">Roulette</a></li>
<li><a href="partyhouse_scratchy-tickets.html">Scratchy Tickets</a></li>
<li><a href="partyhouse_snakeman.html">SNAKEMAN</a></li>
<li><a href="partyhouse_superfail.html">SUPERFAIL</a></li>
<li><a href="partyhouse_tip-line.html">Tip Line</a></li>
<li><a href="partyhouse_the-big-board.html">The Big Board</a></li>
<li><a href="partyhouse_the-first-loser.html">The First Loser</a></li>
</ul>
</li>
<li><a href="guides.html">Guides</a>
<ul>
<li><a href="guide_billycon.html">BillyCon Guide</a></li>
<li><a href="guide_burgerninja.html">BurgerNinja Guide</a></li>
<li><a href="guide_candyween.html">Candyween Guide</a></li>
<li><a href="guide_glossary.html">Glossary</a></li>
<li><a href="guide_gs.html">Glowslinging Strategy Guide</a></li>
<li><a href="guide_hq.html">Hero's Quest</a></li>
<li><a href="guide_looping.html">Looping Guide</a></li>
<li><a href="guide_monochrome.html">Monochrome Guide</a></li>
<li><a href="overnight-bonuses.html">Overnight Bonuses</a></li>
<li><a href="guide_pizzawitch.html">PizzaWitch Guide</a></li>
<li><a href="tabbed_potions-crafting.html">Potions / Crafting</a>
<ul>
<li><a href="tabbed_potions-crafting.html#toc3">Crafting</a>
<ul>
<li><a href="tabbed_potions-crafting.html#toc4">Items</a></li>
<li><a href="tabbed_potions-crafting.html#toc5">Materials</a></li>
</ul>
</li>
<li><a href="tabbed_potions-crafting.html#toc0">Potion Mixing</a>
<ul>
<li><a href="tabbed_potions-crafting.html#toc2">Mixed Ingredients</a></li>
<li><a href="tabbed_potions-crafting.html#toc1">Potions</a></li>
</ul>
</li>
<li><a href="tabbed_potions-crafting.html#toc6">Reduction Laboratory</a>
<ul>
<li><a href="tabbed_potions-crafting.html#toc8">Potions and Ingredients</a></li>
<li><a href="tabbed_potions-crafting.html#toc7">Wasteland Items</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="guide_impossible-mission.html">Impossible Mission Guide</a></li>
<li><a href="guide_xp.html">Ranking Guide</a></li>
<li><a href="guide_reaper.html">Reaper Guide</a></li>
<li><a href="guide_rgg.html">Reaper's Game Guide</a></li>
<li><a href="guide_r00t.html">R00t Guide</a></li>
<li><a href="guide_speed-content.html">Speed Content Guide</a></li>
<li><a href="guide_speedlooping.html">Speedlooping Guide</a></li>
<li><a href="guide_thetrade.html">The Trade Guide</a></li>
<li><a href="guide_wasteland.html">Wasteland Guide</a></li>
</ul>
</li>
<li>Other
<ul>
<li><a href="arena.html">Arena</a></li>
<li><a href="billy-club.html">Billy Club</a>
<ul>
<li><a href="boosters.html">Boosters</a></li>
<li><a href="karma.html">Karma</a></li>
</ul>
</li>
<li><a href="bloodline.html">Bloodlines</a></li>
<li><a href="jutsu.html">Jutsu</a>
<ul>
<li><a href="jutsu.html#toc2">Bloodline Jutsu</a></li>
<li><a href="jutsu.html#toc0">Regular Jutsu</a></li>
<li><a href="jutsu.html#toc1">Special Jutsu</a></li>
</ul>
</li>
<li><a href="mission-bonus.html">Mission Bonus</a></li>
<li><a href="news-archive.html">News Archive</a></li>
<li><a href="number-one.html">Number One</a></li>
<li><a href="old-news-archive.html">Old News Archive</a></li>
<li><a href="retail_perfect-poker.html">Perfect Poker Bosses</a></li>
<li><a href="pets.html">Pets</a></li>
<li><a href="retail.html">Retail</a></li>
<li><a href="ryo.html">Ryo</a></li>
<li><a href="spar.html">Spar With Friends</a></li>
<li><a href="sponsored-items.html">Sponsored Items</a></li>
<li><a href="store.html">Store</a></li>
<li><a href="themes.html">Themes</a></li>
<li><a href="trophies.html">Trophies</a></li>
<li><a href="untabbed.html">Untabbed</a>
<ul>
<li><a href="untabbed_allies.html">Allies</a></li>
<li><a href="untabbed_items.html">Items</a></li>
<li><a href="untabbed_jutsu.html">Jutsu</a></li>
<li><a href="untabbed_missions.html">Missions</a></li>
<li><a href="untabbed_potions-crafting.html">Potions / Crafting</a></li>
</ul>
</li>
<li><a href="world-kaiju.html">World Kaiju</a></li>
</ul>
</li>
<li><a href="utilities.html">Utilities</a>
<ul>
<li><a href="http://www.cobaltknight.clanteam.com/awesomecalc.html">Awesome Calculator</a></li>
<li><a href="http://timothydryke.byethost17.com/billy/itemchecker.php">Item Checker</a></li>
<li><a href="utility_calculator.html">Mission Calculator</a></li>
<li><a href="utility_r00t-calculator.html">R00t Calculator</a></li>
<li><a href="utility_success-calculator.html">Success Calculator</a></li>
<li><a href="templates.html">Templates</a></li>
<li><a href="utility_chat.html">Wiki Chat Box</a></li>
</ul>
</li>
</ul>
</div>
<div id="login-status"><a href="javascript:;" onclick="WIKIDOT.page.listeners.createAccount(event)" class="login-status-create-account btn">Create account</a> <span>or</span> <a href="javascript:;" onclick="WIKIDOT.page.listeners.loginClick(event)" class="login-status-sign-in btn btn-primary">Sign in</a> </div>
<div id="header-extra-div-1"><span></span></div><div id="header-extra-div-2"><span></span></div><div id="header-extra-div-3"><span></span></div>
</div>
<div id="content-wrap">
<div id="side-bar">
<h3 ><span><a href="http://www.animecubed.com/billy/?57639" onclick="window.open(this.href, '_blank'); return false;">Play BvS Now!</a></span></h3>
<ul>
<li><a href="system_members.html">Site members</a></li>
<li><a href="system_join.html">Wiki Membership</a></li>
</ul>
<hr />
<ul>
<li><a href="forum_start.html">Forum Main</a></li>
<li><a href="forum_recent-posts.html">Recent Posts</a></li>
</ul>
<hr />
<ul>
<li><a href="system_recent-changes.html">Recent changes</a></li>
<li><a href="system_list-all-pages.html">List all pages</a></li>
<li><a href="system_page-tags-list.html">Page Tags</a></li>
</ul>
<hr />
<ul>
<li><a href="players.html">Players</a></li>
<li><a href="villages.html">Villages</a></li>
<li><a href="other-resources.html">Other Resources</a></li>
</ul>
<hr />
<p style="text-align: center;"><span style="font-size:smaller;">Notice: Do not send bug reports based on the information on this site. If this site is not matching up with what you're experiencing in game, that is a problem with this site, not with the game.</span></p>
</div>
<!-- google_ad_section_end -->
<div id="main-content">
<div id="action-area-top"></div>
<div id="page-title">
Advanced RedEye
</div>
<!-- wikidot_top_728x90 -->
<div id="wad-tier3-above-content" class="wd-adunit wd-ad-np wd-adunit-above_content"></div>
<script>
window['nitroAds'].createAd('wad-tier3-above-content', {
"refreshLimit": 10,
"refreshTime": 94,
"renderVisibleOnly": false,
"refreshVisibleOnly": true,
"sizes": [ [ 728, 90 ] ],
"report": {
"enabled": true,
"wording": "Report Ad",
"position": "bottom-right"
}
});
</script>
<div id="page-content">
<h2 id="toc0"><span>Trainer</span></h2>
<ul>
<li>Complete the Quest <a href="quest_jonin-ascension.html">Jonin Ascension (Redeye)</a> / <a href="quest_jonin-ascension-season-2.html">Jonin Ascension (S2+ Redeye)</a> to learn</li>
<li>Buy the Awesome Ability <a href="trophies.html">Inherent Perception</a></li>
</ul>
<h2 id="toc1"><span>Rank Required</span></h2>
<ul>
<li>Jonin (Normal RedEye)</li>
<li>Genin (<a href="trophies.html">Inherent Perception</a>)</li>
</ul>
<h2 id="toc2"><span>Base Training Cost</span></h2>
<ul>
<li>None</li>
</ul>
<h2 id="toc3"><span>Required Items</span></h2>
<ul>
<li>Consumable: None</li>
</ul>
<h2 id="toc4"><span>Chakra Cost</span></h2>
<ul>
<li>100</li>
</ul>
<h2 id="toc5"><span>Effect</span></h2>
<ul>
<li>+1 Strength</li>
<li>Copy Jutsus used on you during missions to learn later</li>
</ul>
<div class="image-container floatright"><img src="http://bvs.wdfiles.com/local--files/include:redeyelearn/RedEye.gif" alt="RedEye.gif" class="image" /></div>
<h2 id="toc6"><span>Jutsu Learned by <a href="bloodline.html#redeye">RedEye</a> (as Trainer)</span></h2>
<table class="wiki-content-table">
<tr>
<th>Jutsu</th>
<th>Mission</th>
<th>Mission Type</th>
<th>Jutsu XP Cost</th>
</tr>
<tr>
<td><a href="jutsu_archer-style_fire-and-flames.html">Archer Style: Fire and Flames</a></td>
<td><a href="mission_a-level-fight-an-arrancar.html">A-Level! Fight an Arrancar</a></td>
<td>Reaper Mission</td>
<td style="text-align: right;">75,000 XP</td>
</tr>
<tr>
<td><a href="jutsu_attack-on-the-nervous-system.html">Attack on the Nervous System</a></td>
<td><a href="mission_fix-a-water-supply.html">Fix a Water Supply!</a></td>
<td>C-Rank</td>
<td style="text-align: right;">12,500 XP</td>
</tr>
<tr>
<td><a href="jutsu_demonic-illusion_tree-bind-death.html">Demonic Illusion: Tree Bind Death</a></td>
<td><a href="mission_ninja-leaping-practice.html">Ninja Leaping Practice</a> / <a href="mission_prune-treetops.html">Prune Treetops</a></td>
<td>D-Rank</td>
<td style="text-align: right;">8,750 XP</td>
</tr>
<tr>
<td><a href="jutsu_earth-style_groundhog-technique-decapitation.html">Earth Style: Groundhog Technique Decapitation</a></td>
<td><a href="mission_mudslide-rescue.html">Mudslide Rescue!</a></td>
<td>D-Rank</td>
<td style="text-align: right;">6,750 XP</td>
</tr>
<tr>
<td><a href="jutsu_fire-style_dragon-flame-jutsu.html">Fire Style: Dragon Flame Jutsu</a></td>
<td><a href="mission_fire.html">Fire!</a></td>
<td>D-Rank</td>
<td style="text-align: right;">6,500 XP</td>
</tr>
<tr>
<td><a href="jutsu_get-in-my-belly.html">Get In My Belly</a></td>
<td><a href="mission_eat-your-fill.html">Eat Your Fill!</a></td>
<td>D-Rank</td>
<td style="text-align: right;">8,750 XP</td>
</tr>
<tr>
<td><a href="jutsu_great-expansion.html">Great Expansion</a></td>
<td><a href="mission_block-a-crumbling-dam.html">Block a Crumbling Dam!</a></td>
<td>A-Rank</td>
<td style="text-align: right;">12,500 XP</td>
</tr>
<tr>
<td><a href="jutsu_mind-body-switch-technique.html">Mind Body Switch Technique</a></td>
<td><a href="mission_shake-off-a-genjutsu.html">Shake off a Genjutsu!</a></td>
<td>D-Rank</td>
<td style="text-align: right;">4,500 XP</td>
</tr>
<tr>
<td><a href="jutsu_ninja-art_poison-fog.html">Ninja Art: Poison Fog</a></td>
<td><a href="mission_clear-an-area-of-deadly-insects.html">Clear an Area of Deadly Insects!</a></td>
<td>C-Rank</td>
<td style="text-align: right;">8,750 XP</td>
</tr>
<tr>
<td><a href="jutsu_second-face-jutsu.html">Second Face Jutsu</a></td>
<td><a href="mission_catch-a-legendary-spy.html">Catch a Legendary Spy</a></td>
<td>A-Rank</td>
<td style="text-align: right;">12,500 XP</td>
</tr>
<tr>
<td><a href="jutsu_soul-reaper-style_imperishable-night.html">Soul Reaper Style: Imperishable Night</a></td>
<td><a href="mission_time-to-kill.html">Time to Kill</a></td>
<td>Monochrome Missions</td>
<td style="text-align: right;">125,000 XP</td>
</tr>
<tr>
<td><a href="jutsu_striking-snake-technique.html">Striking Snake Technique</a></td>
<td><a href="mission_pull-a-jonin-up-from-a-cliff.html">Pull a Jonin Up From a Cliff!</a></td>
<td>B-Rank</td>
<td style="text-align: right;">12500 XP</td>
</tr>
<tr>
<td><a href="jutsu_super-heel-drop.html">Super Heel Drop</a></td>
<td><a href="mission_split-a-fortress-wall.html">Split a Fortress Wall</a></td>
<td>B-Rank</td>
<td style="text-align: right;">12500 XP</td>
</tr>
<tr>
<td><a href="jutsu_the-shocker.html">The Shocker</a></td>
<td><a href="mission_report-a-spy.html">Report a Spy!</a></td>
<td>D-Rank</td>
<td style="text-align: right;">50,000 XP</td>
</tr>
<tr>
<td><a href="jutsu_value-meal.html">Value Meal</a></td>
<td><a href="mission_study-the-menu.html">Study the Menu</a></td>
<td>BurgerNinja Missions</td>
<td style="text-align: right;">100,000 XP</td>
</tr>
<tr>
<td><a href="jutsu_water-clone-technique.html">Water Clone Technique</a></td>
<td><a href="mission_clean-the-pool.html">Clean the Pool</a></td>
<td>D-Rank</td>
<td style="text-align: right;">6,750 XP</td>
</tr>
<tr>
<td><a href="jutsu_water-prison-technique.html">Water Prison Technique</a></td>
<td><a href="mission_repel-an-attack.html">Repel an Attack!</a></td>
<td>C-Rank</td>
<td style="text-align: right;">5,750 XP</td>
</tr>
<tr>
<td><a href="jutsu_water-style_water-dragon-missile.html">Water Style: Water Dragon missile</a></td>
<td><a href="mission_escort-a-bridge-builder.html">Escort a Bridge Builder</a></td>
<td>D-Rank</td>
<td style="text-align: right;">7,500 XP</td>
</tr>
<tr>
<td><a href="jutsu_wind-scythe-jutsu.html">Wind Scythe Jutsu</a></td>
<td><a href="mission_assassin-defense.html">Assassin Defense!</a></td>
<td>C-Rank</td>
<td style="text-align: right;">12,500 XP</td>
</tr>
</table>
<h2 id="toc7"><span>Notes</span></h2>
<ul>
<li>This is an upgrade of <a href="jutsu_redeye.html">RedEye</a></li>
</ul>
</div>
<!-- wikidot_bottom_300x250 -->
<div id="wad-tier3-below-content" class="wd-adunit wd-ad-np wd-adunit-below_content"></div>
<script>
window['nitroAds'].createAd('wad-tier3-below-content', {
"refreshLimit": 10,
"refreshTime": 83,
"renderVisibleOnly": false,
"refreshVisibleOnly": true,
"sizes": [ [ 300, 250 ] ],
"report": {
"enabled": true,
"wording": "Report Ad",
"position": "bottom-right"
}
});
</script>
<!-- mobile bottom 320x50 -->
<script>
$j( function(){
if(isUAMobile && screen.width < 400 && screen.height > 600) {
var $o = $j('<div id="wad-tier3-mobile-anchor" class="wd-adunit wd-ad-np wd-adunit-mobile_anchor"></div>');
$j('body').append($o);
$j('body').css('margin-bottom', '200px');
var res = function(){
$o = $j('#wad-tier3-mobile-anchor');
if($o.length > 0){
$o.show();
var $w = $j(window);
var scale = $w.width() / 320;
$o.css('transform', 'scale('+scale+')');
} else {
$o.hide();
}
}
res();
setInterval(res, 1000);
window['nitroAds'].createAd('wad-tier3-mobile-anchor', {
"refreshLimit": 1,
"refreshTime": 90,
"renderVisibleOnly": false,
"refreshVisibleOnly": true,
"format": "display",
"sizes": [ [ 320, 50 ] ],
"report": {
"enabled": true,
"wording": "Report Ad",
"position": "bottom-right"
}
});
}
});
</script>
<div class="page-tags">
<span>
<a href="system_page-tags/tag/jutsu.html#pages">jutsu</a>
</span>
</div>
<div id="page-info-break"></div>
<div id="page-options-container">
<div id="page-info">page revision: 2, last edited: <span class="odate time_1420254786 format_%25e%20%25b%20%25Y%2C%20%25H%3A%25M%20%28%25O%20ago%29">03 Jan 2015 03:13</span></div>
<div id="page-options-bottom" class="page-options-bottom">
<a href="javascript:;" class="btn btn-default" id="edit-button">Edit</a>
<a href="javascript:;" class="btn btn-default" id="tags-button">Tags</a>
<a href="forum/t-237366/jutsu_advanced-redeye.html" class="btn btn-default" id="discuss-button">Discuss (1)</a>
<a href="javascript:;" class="btn btn-default" id="history-button">History</a>
<a href="javascript:;" class="btn btn-default" id="files-button">Files</a>
<a href="javascript:;" class="btn btn-default" id="print-button">Print</a>
<a href="javascript:;" class="btn btn-default" id="site-tools-button">Site tools</a>
<a href="javascript:;" class="btn btn-default" id="more-options-button">+ Options</a>
</div>
<div id="page-options-bottom-2" class="page-options-bottom form-actions" style="display:none">
<a href="javascript:;" class="btn btn-default" id="edit-sections-button">Edit Sections</a>
<a href="javascript:;" class="btn btn-default" id="edit-append-button">Append</a>
<a href="javascript:;" class="btn btn-default" id="edit-meta-button">Edit Meta</a>
<a href="javascript:;" class="btn btn-default" id="watchers-button">Watchers</a>
<a href="javascript:;" class="btn btn-default" id="backlinks-button">Backlinks</a>
<a href="javascript:;" class="btn btn-default" id="view-source-button">Page Source</a>
<a href="javascript:;" class="btn btn-default" id="parent-page-button">Parent</a>
<a href="javascript:;" class="btn btn-default" id="page-block-button">Lock Page</a>
<a href="javascript:;" class="btn btn-default" id="rename-move-button">Rename</a>
<a href="javascript:;" class="btn btn-default" id="delete-button">Delete</a>
</div>
<div id="page-options-area-bottom">
</div>
</div>
<div id="action-area" style="display: none;"></div>
</div>
</div>
<div id="footer" style="display: block; visibility: visible;">
<div class="options" style="display: block; visibility: visible;">
<a href="http://www.wikidot.com/doc" id="wikidot-help-button">Help</a>
|
<a href="http://www.wikidot.com/legal:terms-of-service" id="wikidot-tos-button">Terms of Service</a>
|
<a href="http://www.wikidot.com/legal:privacy-policy" id="wikidot-privacy-button">Privacy</a>
|
<a href="javascript:;" id="bug-report-button" onclick="WIKIDOT.page.listeners.pageBugReport(event)">Report a bug</a>
|
<a href="javascript:;" id="abuse-report-button" onclick="WIKIDOT.page.listeners.flagPageObjectionable(event)">Flag as objectionable</a>
</div>
Powered by <a href="http://www.wikidot.com/">Wikidot.com</a>
</div>
<div id="license-area" class="license-area">
Unless otherwise stated, the content of this page is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 License</a>
</div>
<div id="extrac-div-1"><span></span></div><div id="extrac-div-2"><span></span></div><div id="extrac-div-3"><span></span></div>
</div>
</div>
<!-- These extra divs/spans may be used as catch-alls to add extra imagery. -->
<div id="extra-div-1"><span></span></div><div id="extra-div-2"><span></span></div><div id="extra-div-3"><span></span></div>
<div id="extra-div-4"><span></span></div><div id="extra-div-5"><span></span></div><div id="extra-div-6"><span></span></div>
</div>
</div>
<div id="dummy-ondomready-block" style="display: none;" ></div>
<!-- Google Analytics load -->
<script type="text/javascript">
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- Quantcast -->
<script type="text/javascript">
_qoptions={
qacct:"p-edL3gsnUjJzw-"
};
(function() {
var qc = document.createElement('script'); qc.type = 'text/javascript'; qc.async = true;
qc.src = ('https:' == document.location.protocol ? 'https://secure' : 'http://edge') + '.quantserve.com/quant.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(qc, s);
})();
</script>
<noscript>
<img src="http://pixel.quantserve.com/pixel/p-edL3gsnUjJzw-.gif" style="display: none;" border="0" height="1" width="1" alt="Quantcast"/>
</noscript>
<div id="page-options-bottom-tips" style="display: none;">
<div id="edit-button-hovertip">
Click here to edit contents of this page. </div>
</div>
<div id="page-options-bottom-2-tips" style="display: none;">
<div id="edit-sections-button-hovertip">
Click here to toggle editing of individual sections of the page (if possible). Watch headings for an "edit" link when available. </div>
<div id="edit-append-button-hovertip">
Append content without editing the whole page source. </div>
<div id="history-button-hovertip">
Check out how this page has evolved in the past. </div>
<div id="discuss-button-hovertip">
If you want to discuss contents of this page - this is the easiest way to do it. </div>
<div id="files-button-hovertip">
View and manage file attachments for this page. </div>
<div id="site-tools-button-hovertip">
A few useful tools to manage this Site. </div>
<div id="backlinks-button-hovertip">
See pages that link to and include this page. </div>
<div id="rename-move-button-hovertip">
Change the name (also URL address, possibly the category) of the page. </div>
<div id="view-source-button-hovertip">
View wiki source for this page without editing. </div>
<div id="parent-page-button-hovertip">
View/set parent page (used for creating breadcrumbs and structured layout). </div>
<div id="abuse-report-button-hovertip">
Notify administrators if there is objectionable content in this page. </div>
<div id="bug-report-button-hovertip">
Something does not work as expected? Find out what you can do. </div>
<div id="wikidot-help-button-hovertip">
General Wikidot.com documentation and help section. </div>
<div id="wikidot-tos-button-hovertip">
Wikidot.com Terms of Service - what you can, what you should not etc. </div>
<div id="wikidot-privacy-button-hovertip">
Wikidot.com Privacy Policy.
</div>
</div>
</body>
<!-- Mirrored from bvs.wikidot.com/jutsu:advanced-redeye by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 10 Jul 2022 03:11:30 GMT -->
</html> | {'content_hash': 'e326454b8caf579c3e854e9750df3a76', 'timestamp': '', 'source': 'github', 'line_count': 870, 'max_line_length': 328, 'avg_line_length': 39.725287356321836, 'alnum_prop': 0.6100517924828563, 'repo_name': 'tn5421/tn5421.github.io', 'id': 'c40a88e48e0151e6d03a1bcdde499a61a6ea8e08', 'size': '34561', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'bvs.wikidot.com/jutsu_advanced-redeye.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '400301089'}]} |
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" >
<head>
<title>Testing image</title>
<style type="text/css">
@import "../../../../dojo/resources/dojo.css";
@import "../../../../dijit/tests/css/dijitTests.css";
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- SVGWEB { -->
<meta name="svg.render.forceflash" content="true"/>
<script src="svgweb/src/svg.js" data-path="svgweb/src"></script>
<script src="../../../../dojo/dojo.js" djConfig="isDebug:true,forceGfxRenderer:'svg'" type="text/javascript"></script>
<!-- } -->
<script type="text/javascript">
dojo.require("dojox.gfx");
var image = null, grid_size = 500, grid_step = 50,
m = dojox.gfx.matrix;
makeShapes = function(){
var surface = dojox.gfx.createSurface("test", 800, 600);
/* SVGWEB { */
surface.whenLoaded(function() {
for(var i = 0; i <= grid_size; i += grid_step){
surface.createLine({x1: 0, x2: grid_size, y1: i, y2: i}).setStroke("black");
surface.createLine({y1: 0, y2: grid_size, x1: i, x2: i}).setStroke("black");
}
image = surface.createImage({width: 150, height: 100, src: "../images/eugene-sm.jpg"});
image.connect("onclick", function(){ alert("You didn't expect a download, did you?"); });
});
/* } */
};
transformImage = function(){
var radio = document.getElementsByName("switch");
if(radio[0].checked){
image.setTransform({});
}else if(radio[1].checked){
image.setTransform({dx: 100, dy: 50});
}else if(radio[2].checked){
image.setTransform(m.rotateg(15));
}else if(radio[3].checked){
image.setTransform([{dx: 70, dy: 90}, {xx: 1.5, yy: 0.5}]);
}else if(radio[4].checked){
image.setTransform([m.rotateg(15), m.skewXg(30)]);
}
var shift = document.getElementsByName("shift");
if(shift[0].checked){
image.setShape({x: 0, y: 0});
}else if(shift[1].checked){
image.setShape({x: 100, y: 50});
}else if(shift[2].checked){
image.setShape({x: 0, y: 0});
image.applyRightTransform({dx: 100, dy: 50});
}
};
dojo.addOnLoad(makeShapes);
</script>
</head>
<body>
<h1>dojox.gfx Image tests</h1>
<p>Note: Silverlight doesn't allow downloading images when run from a file system. This demo should be run from a server.</p>
<p>
<input type="radio" name="switch" id="r1_reset" checked onclick="transformImage()" /><label for="r1_reset">Reset Image</label><br />
<input type="radio" name="switch" id="r1_move" onclick="transformImage()" /><label for="r1_move">Move Image</label><br />
<input type="radio" name="switch" id="r1_rotate" onclick="transformImage()" /><label for="r1_rotate">Rotate Image</label><br />
<input type="radio" name="switch" id="r1_scale" onclick="transformImage()" /><label for="r1_scale">Scale Image</label><br />
<input type="radio" name="switch" id="r1_skew" onclick="transformImage()" /><label for="r1_skew">Skew Image</label><br />
</p>
<p>
<input type="radio" name="shift" id="r2_none" checked onclick="transformImage()" /><label for="r2_none">Place image at (0, 0)</label><br />
<input type="radio" name="shift" id="r2_origin" onclick="transformImage()" /><label for="r2_origin">Place image at (100, 50)</label><br />
<input type="radio" name="shift" id="r2_shift" onclick="transformImage()" /><label for="r2_shift">Shift image by (100, 50)</label>
</p>
<div id="test"></div>
<p>That's all Folks!</p>
</body>
</html>
| {'content_hash': '672804badd0086cca0a3a7732a5c56ac', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 139, 'avg_line_length': 42.2625, 'alnum_prop': 0.6521739130434783, 'repo_name': 'NCIP/cadsr-cdecurate', 'id': '7edc57046b5667bd01b5676fb42e1c51fb27ec7c', 'size': '3383', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'WebRoot/js/dojo/dojox/gfx/tests/svgweb/test_image1.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '21071'}, {'name': 'CSS', 'bytes': '736619'}, {'name': 'Java', 'bytes': '4354026'}, {'name': 'JavaScript', 'bytes': '10319025'}, {'name': 'PHP', 'bytes': '558478'}, {'name': 'Perl', 'bytes': '6881'}, {'name': 'Ruby', 'bytes': '911'}, {'name': 'Shell', 'bytes': '101443'}, {'name': 'XSLT', 'bytes': '104233'}]} |
<?php
namespace Google\Service\Monitoring;
class ServiceLevelObjective extends \Google\Model
{
/**
* @var string
*/
public $calendarPeriod;
/**
* @var string
*/
public $displayName;
public $goal;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $rollingPeriod;
protected $serviceLevelIndicatorType = ServiceLevelIndicator::class;
protected $serviceLevelIndicatorDataType = '';
/**
* @var string[]
*/
public $userLabels;
/**
* @param string
*/
public function setCalendarPeriod($calendarPeriod)
{
$this->calendarPeriod = $calendarPeriod;
}
/**
* @return string
*/
public function getCalendarPeriod()
{
return $this->calendarPeriod;
}
/**
* @param string
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* @return string
*/
public function getDisplayName()
{
return $this->displayName;
}
public function setGoal($goal)
{
$this->goal = $goal;
}
public function getGoal()
{
return $this->goal;
}
/**
* @param string
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string
*/
public function setRollingPeriod($rollingPeriod)
{
$this->rollingPeriod = $rollingPeriod;
}
/**
* @return string
*/
public function getRollingPeriod()
{
return $this->rollingPeriod;
}
/**
* @param ServiceLevelIndicator
*/
public function setServiceLevelIndicator(ServiceLevelIndicator $serviceLevelIndicator)
{
$this->serviceLevelIndicator = $serviceLevelIndicator;
}
/**
* @return ServiceLevelIndicator
*/
public function getServiceLevelIndicator()
{
return $this->serviceLevelIndicator;
}
/**
* @param string[]
*/
public function setUserLabels($userLabels)
{
$this->userLabels = $userLabels;
}
/**
* @return string[]
*/
public function getUserLabels()
{
return $this->userLabels;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ServiceLevelObjective::class, 'Google_Service_Monitoring_ServiceLevelObjective');
| {'content_hash': '4decebf829a4c3b7d46d976866df361d', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 93, 'avg_line_length': 17.976377952755904, 'alnum_prop': 0.6338151554971528, 'repo_name': 'googleapis/google-api-php-client-services', 'id': 'e5241d26eb9018f827689a270846b7815d825c50', 'size': '2873', 'binary': False, 'copies': '6', 'ref': 'refs/heads/main', 'path': 'src/Monitoring/ServiceLevelObjective.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'PHP', 'bytes': '55414116'}, {'name': 'Python', 'bytes': '427325'}, {'name': 'Shell', 'bytes': '787'}]} |
package org.apache.geode.distributed.internal;
import static org.apache.geode.distributed.ConfigurationProperties.ARCHIVE_DISK_SPACE_LIMIT;
import static org.apache.geode.distributed.ConfigurationProperties.ARCHIVE_FILE_SIZE_LIMIT;
import static org.apache.geode.distributed.ConfigurationProperties.CACHE_XML_FILE;
import static org.apache.geode.distributed.ConfigurationProperties.CLUSTER_SSL_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.GATEWAY_SSL_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_SSL_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.LOG_DISK_SPACE_LIMIT;
import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE_SIZE_LIMIT;
import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.distributed.ConfigurationProperties.MEMBERSHIP_PORT_RANGE;
import static org.apache.geode.distributed.ConfigurationProperties.MEMBER_TIMEOUT;
import static org.apache.geode.distributed.ConfigurationProperties.NAME;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS;
import static org.apache.geode.distributed.ConfigurationProperties.SERVER_SSL_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_ENABLED_COMPONENTS;
import static org.apache.geode.distributed.ConfigurationProperties.START_LOCATOR;
import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_ARCHIVE_FILE;
import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLE_RATE;
import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import io.micrometer.core.instrument.MeterRegistry;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.Locator;
import org.apache.geode.internal.AvailablePort;
import org.apache.geode.internal.Config;
import org.apache.geode.internal.ConfigSource;
import org.apache.geode.internal.logging.InternalLogWriter;
import org.apache.geode.metrics.internal.MetricsService;
import org.apache.geode.test.junit.categories.MembershipTest;
import org.apache.geode.util.internal.GeodeGlossary;
/**
* Tests the functionality of the {@link InternalDistributedSystem} class. Mostly checks
* configuration error checking.
*
* @since GemFire 2.1
*/
@Category({MembershipTest.class})
public class InternalDistributedSystemJUnitTest {
/**
* A connection to a distributed system created by this test
*/
private InternalDistributedSystem system;
private InternalDistributedSystem createSystem(Properties props,
MetricsService.Builder metricsSessionBuilder) {
this.system = new InternalDistributedSystem.Builder(props, metricsSessionBuilder)
.build();
return this.system;
}
/**
* Creates a <code>DistributedSystem</code> with the given configuration properties.
*/
private InternalDistributedSystem createSystem(Properties props) {
MetricsService.Builder metricsSessionBuilder = mock(MetricsService.Builder.class);
when(metricsSessionBuilder.build(any())).thenReturn(mock(MetricsService.class));
return createSystem(props, metricsSessionBuilder);
}
/**
* Disconnects any distributed system that was created by this test
*
* @see DistributedSystem#disconnect
*/
@After
public void tearDown() throws Exception {
if (this.system != null) {
this.system.disconnect();
}
}
//////// Test methods
@Test
public void testUnknownArgument() {
Properties props = new Properties();
props.put("UNKNOWN", "UNKNOWN");
try {
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
/**
* Tests that the default values of properties are what we expect
*/
@Test
public void testDefaultProperties() {
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
DistributionConfig config = createSystem(props).getConfig();
assertEquals(DistributionConfig.DEFAULT_NAME, config.getName());
assertEquals(0, config.getMcastPort());
assertEquals(DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[0],
config.getMembershipPortRange()[0]);
assertEquals(DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1],
config.getMembershipPortRange()[1]);
if (System.getProperty(GeodeGlossary.GEMFIRE_PREFIX + "mcast-address") == null) {
assertEquals(DistributionConfig.DEFAULT_MCAST_ADDRESS, config.getMcastAddress());
}
if (System.getProperty(GeodeGlossary.GEMFIRE_PREFIX + "bind-address") == null) {
assertEquals(DistributionConfig.DEFAULT_BIND_ADDRESS, config.getBindAddress());
}
assertEquals(DistributionConfig.DEFAULT_LOG_FILE, config.getLogFile());
// default log level gets overrided by the gemfire.properties created for unit tests.
// assertIndexDetailsEquals(DistributionConfig.DEFAULT_LOG_LEVEL, config.getLogLevel());
assertEquals(DistributionConfig.DEFAULT_STATISTIC_SAMPLING_ENABLED,
config.getStatisticSamplingEnabled());
assertEquals(DistributionConfig.DEFAULT_STATISTIC_SAMPLE_RATE, config.getStatisticSampleRate());
assertEquals(DistributionConfig.DEFAULT_STATISTIC_ARCHIVE_FILE,
config.getStatisticArchiveFile());
// ack-wait-threadshold is overridden on VM's command line using a
// system property. This is not a valid test. Hrm.
// assertIndexDetailsEquals(DistributionConfig.DEFAULT_ACK_WAIT_THRESHOLD,
// config.getAckWaitThreshold());
assertEquals(DistributionConfig.DEFAULT_ACK_SEVERE_ALERT_THRESHOLD,
config.getAckSevereAlertThreshold());
assertEquals(DistributionConfig.DEFAULT_CACHE_XML_FILE, config.getCacheXmlFile());
assertEquals(DistributionConfig.DEFAULT_ARCHIVE_DISK_SPACE_LIMIT,
config.getArchiveDiskSpaceLimit());
assertEquals(DistributionConfig.DEFAULT_ARCHIVE_FILE_SIZE_LIMIT,
config.getArchiveFileSizeLimit());
assertEquals(DistributionConfig.DEFAULT_LOG_DISK_SPACE_LIMIT, config.getLogDiskSpaceLimit());
assertEquals(DistributionConfig.DEFAULT_LOG_FILE_SIZE_LIMIT, config.getLogFileSizeLimit());
assertEquals(DistributionConfig.DEFAULT_ENABLE_NETWORK_PARTITION_DETECTION,
config.getEnableNetworkPartitionDetection());
}
@Test
public void testGetName() {
String name = "testGetName";
Properties props = new Properties();
props.put(NAME, name);
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
DistributionConfig config = createSystem(props).getOriginalConfig();
assertEquals(name, config.getName());
}
@Test
public void testMemberTimeout() {
Properties props = new Properties();
int memberTimeout = 100;
props.put(MEMBER_TIMEOUT, String.valueOf(memberTimeout));
props.put(MCAST_PORT, "0");
DistributionConfig config = createSystem(props).getOriginalConfig();
assertEquals(memberTimeout, config.getMemberTimeout());
}
@Test
public void testMalformedLocators() {
Properties props = new Properties();
try {
// Totally bogus locator
props.put(LOCATORS, "14lasfk^5234");
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
try {
// missing port
props.put(LOCATORS, "localhost[");
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
try {
// Missing ]
props.put(LOCATORS, "localhost[234ty");
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
try {
// Malformed port
props.put(LOCATORS, "localhost[234ty]");
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
try {
// Malformed port in second locator
props.put(LOCATORS, "localhost[12345],localhost[sdf3");
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
/**
* Creates a new <code>DistributionConfigImpl</code> with the given locators string.
*
* @throws IllegalArgumentException If <code>locators</code> is malformed
* @since GemFire 4.0
*/
private void checkLocator(String locator) {
Properties props = new Properties();
props.put(LOCATORS, locator);
new DistributionConfigImpl(props);
}
/**
* Tests that both the traditional syntax ("host[port]") and post bug-32306 syntax ("host:port")
* can be used with locators.
*
* @since GemFire 4.0
*/
@Test
public void testLocatorSyntax() throws Exception {
String localhost = java.net.InetAddress.getLocalHost().getCanonicalHostName();
checkLocator(localhost + "[12345]");
checkLocator(localhost + ":12345");
String bindAddress = getHostAddress(java.net.InetAddress.getLocalHost());
if (bindAddress.indexOf(':') < 0) {
checkLocator(localhost + ":" + bindAddress + "[12345]");
}
checkLocator(localhost + "@" + bindAddress + "[12345]");
if (bindAddress.indexOf(':') < 0) {
checkLocator(localhost + ":" + bindAddress + ":12345");
}
if (localhost.indexOf(':') < 0) {
checkLocator(localhost + ":" + "12345");
}
}
/**
* Tests that getting the log level is what we expect.
*/
@Test
public void testGetLogLevel() {
Level logLevel = Level.FINER;
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(LOG_LEVEL, logLevel.toString());
DistributionConfig config = createSystem(props).getConfig();
assertEquals(logLevel.intValue(), config.getLogLevel());
}
@Test
public void testInvalidLogLevel() {
try {
Properties props = new Properties();
props.put(LOG_LEVEL, "blah blah blah");
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
@Test
public void testGetStatisticSamplingEnabled() {
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(STATISTIC_SAMPLING_ENABLED, "true");
DistributionConfig config = createSystem(props).getConfig();
assertEquals(true, config.getStatisticSamplingEnabled());
}
@Test
public void testGetStatisticSampleRate() {
String rate = String.valueOf(DistributionConfig.MIN_STATISTIC_SAMPLE_RATE);
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(STATISTIC_SAMPLE_RATE, rate);
DistributionConfig config = createSystem(props).getConfig();
// The fix for 48228 causes the rate to be 1000 even if we try to set it less
assertEquals(1000, config.getStatisticSampleRate());
}
@Test
public void testMembershipPortRange() {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.setProperty(MEMBERSHIP_PORT_RANGE, "45100-45200");
DistributionConfig config = createSystem(props).getConfig();
assertEquals(45100, config.getMembershipPortRange()[0]);
assertEquals(45200, config.getMembershipPortRange()[1]);
}
@Test
public void testBadMembershipPortRange() {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.setProperty(MEMBERSHIP_PORT_RANGE, "5200-5100");
Object exception = null;
try {
createSystem(props).getConfig();
} catch (IllegalArgumentException expected) {
exception = expected;
}
assertNotNull("Expected an IllegalArgumentException", exception);
}
@Test
public void testGetStatisticArchiveFile() {
String fileName = "testGetStatisticArchiveFile";
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(STATISTIC_ARCHIVE_FILE, fileName);
DistributionConfig config = createSystem(props).getConfig();
assertEquals(fileName, config.getStatisticArchiveFile().getName());
}
@Test
public void testGetCacheXmlFile() {
String fileName = "blah";
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(CACHE_XML_FILE, fileName);
DistributionConfig config = createSystem(props).getConfig();
assertEquals(fileName, config.getCacheXmlFile().getPath());
}
@Test
public void testGetArchiveDiskSpaceLimit() {
String value = String.valueOf(DistributionConfig.MIN_ARCHIVE_DISK_SPACE_LIMIT);
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(ARCHIVE_DISK_SPACE_LIMIT, value);
DistributionConfig config = createSystem(props).getConfig();
assertEquals(Integer.parseInt(value), config.getArchiveDiskSpaceLimit());
}
@Test
public void testInvalidArchiveDiskSpaceLimit() {
Properties props = new Properties();
props.put(ARCHIVE_DISK_SPACE_LIMIT, "blah");
try {
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
@Test
public void testGetArchiveFileSizeLimit() {
String value = String.valueOf(DistributionConfig.MIN_ARCHIVE_FILE_SIZE_LIMIT);
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(ARCHIVE_FILE_SIZE_LIMIT, value);
DistributionConfig config = createSystem(props).getConfig();
assertEquals(Integer.parseInt(value), config.getArchiveFileSizeLimit());
}
@Test
public void testInvalidArchiveFileSizeLimit() {
Properties props = new Properties();
props.put(ARCHIVE_FILE_SIZE_LIMIT, "blah");
try {
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
@Test
public void testGetLogDiskSpaceLimit() {
String value = String.valueOf(DistributionConfig.MIN_LOG_DISK_SPACE_LIMIT);
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(LOG_DISK_SPACE_LIMIT, value);
DistributionConfig config = createSystem(props).getConfig();
assertEquals(Integer.parseInt(value), config.getLogDiskSpaceLimit());
}
@Test
public void testInvalidLogDiskSpaceLimit() {
Properties props = new Properties();
props.put(LOG_DISK_SPACE_LIMIT, "blah");
try {
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
@Test
public void testGetLogFileSizeLimit() {
String value = String.valueOf(DistributionConfig.MIN_LOG_FILE_SIZE_LIMIT);
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(LOG_FILE_SIZE_LIMIT, value);
DistributionConfig config = createSystem(props).getConfig();
assertEquals(Integer.parseInt(value), config.getLogFileSizeLimit());
}
@Test
public void testInvalidLogFileSizeLimit() {
Properties props = new Properties();
props.put(LOG_FILE_SIZE_LIMIT, "blah");
try {
createSystem(props);
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// pass...
}
}
@Test
public void testAccessingClosedDistributedSystem() {
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
InternalDistributedSystem system = createSystem(props);
system.disconnect();
try {
system.getDistributionManager();
fail("Should have thrown an IllegalStateException");
} catch (DistributedSystemDisconnectedException ex) {
// pass...
}
try {
system.getLogWriter();
} catch (IllegalStateException ex) {
fail("Shouldn't have thrown an IllegalStateException");
}
}
@Test
public void testPropertySources() throws Exception {
// TODO: fix this test on Windows: the File renameTo and delete in finally fails on Windows
String os = System.getProperty("os.name");
if (os != null) {
if (os.indexOf("Windows") != -1) {
return;
}
}
File propFile = new File(GeodeGlossary.GEMFIRE_PREFIX + "properties");
boolean propFileExisted = propFile.exists();
File spropFile = new File("gfsecurity.properties");
boolean spropFileExisted = spropFile.exists();
try {
System.setProperty(GeodeGlossary.GEMFIRE_PREFIX + LOG_LEVEL, "finest");
Properties apiProps = new Properties();
apiProps.setProperty(GROUPS, "foo, bar");
{
if (propFileExisted) {
propFile.renameTo(new File(GeodeGlossary.GEMFIRE_PREFIX + "properties.sav"));
}
Properties fileProps = new Properties();
fileProps.setProperty("name", "myName");
FileWriter fw = new FileWriter(GeodeGlossary.GEMFIRE_PREFIX + "properties");
fileProps.store(fw, null);
fw.close();
}
{
if (spropFileExisted) {
spropFile.renameTo(new File("gfsecurity.properties.sav"));
}
Properties fileProps = new Properties();
fileProps.setProperty(STATISTIC_SAMPLE_RATE, "999");
FileWriter fw = new FileWriter("gfsecurity.properties");
fileProps.store(fw, null);
fw.close();
}
DistributionConfigImpl dci = new DistributionConfigImpl(apiProps);
assertEquals(null, dci.getAttributeSource(MCAST_PORT));
assertEquals(ConfigSource.api(), dci.getAttributeSource(GROUPS));
assertEquals(ConfigSource.sysprop(), dci.getAttributeSource(LOG_LEVEL));
assertEquals(ConfigSource.Type.FILE, dci.getAttributeSource("name").getType());
assertEquals(ConfigSource.Type.SECURE_FILE,
dci.getAttributeSource(STATISTIC_SAMPLE_RATE).getType());
} finally {
System.clearProperty(GeodeGlossary.GEMFIRE_PREFIX + "log-level");
propFile.delete();
if (propFileExisted) {
new File(GeodeGlossary.GEMFIRE_PREFIX + "properties.sav").renameTo(propFile);
}
spropFile.delete();
if (spropFileExisted) {
new File("gfsecurity.properties.sav").renameTo(spropFile);
}
}
}
/**
* Create a <Code>DistributedSystem</code> with a non-default name.
*/
@Test
public void testNonDefaultConnectionName() {
String name = "BLAH";
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.setProperty(NAME, name);
createSystem(props);
}
@Test
public void testNonDefaultLogLevel() {
Level level = Level.FINE;
Properties props = new Properties();
// a loner is all this test needs
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
props.put(LOG_LEVEL, level.toString());
InternalDistributedSystem system = createSystem(props);
assertEquals(level.intValue(), system.getConfig().getLogLevel());
assertEquals(level.intValue(), ((InternalLogWriter) system.getLogWriter()).getLogWriterLevel());
}
@Test
public void testStartLocator() {
Properties props = new Properties();
int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
props.setProperty(MCAST_PORT, "0");
props.setProperty(START_LOCATOR, "localhost[" + unusedPort + "],server=false,peer=true");
deleteStateFile(unusedPort);
createSystem(props);
Collection locators = Locator.getLocators();
Assert.assertEquals(1, locators.size());
Locator locator = (Locator) locators.iterator().next();
// Assert.assertIndexDetailsEquals("127.0.0.1", locator.getBindAddress().getHostAddress());
// removed this check for ipv6 testing
Assert.assertEquals(unusedPort, locator.getPort().intValue());
deleteStateFile(unusedPort);
}
private void deleteStateFile(int port) {
File stateFile = new File("locator" + port + "state.dat");
if (stateFile.exists()) {
stateFile.delete();
}
}
@Test
public void testValidateProps() {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
Config config1 = new DistributionConfigImpl(props, false);
MetricsService.Builder metricsSessionBuilder = mock(MetricsService.Builder.class);
when(metricsSessionBuilder.build(any())).thenReturn(mock(MetricsService.class));
InternalDistributedSystem sys =
new InternalDistributedSystem.Builder(config1.toProperties(), metricsSessionBuilder)
.build();
try {
props.put(MCAST_PORT, "1");
Config config2 = new DistributionConfigImpl(props, false);
try {
sys.validateSameProperties(config2.toProperties(), true);
fail("should have detected different mcast-ports");
} catch (IllegalStateException iex) {
// This passes the test
}
} finally {
sys.disconnect();
}
}
@Test
public void testDeprecatedSSLProps() {
// ssl-* props are copied to cluster-ssl-*.
Properties props = getCommonProperties();
props.setProperty(CLUSTER_SSL_ENABLED, "true");
Config config1 = new DistributionConfigImpl(props, false);
Properties props1 = config1.toProperties();
assertEquals("true", props1.getProperty(CLUSTER_SSL_ENABLED));
Config config2 = new DistributionConfigImpl(props1, false);
assertEquals(true, config1.sameAs(config2));
Properties props3 = new Properties(props1);
props3.setProperty(CLUSTER_SSL_ENABLED, "false");
Config config3 = new DistributionConfigImpl(props3, false);
assertEquals(false, config1.sameAs(config3));
}
@Test
public void testEmptySecurityAuthTokenProp() throws Exception {
Properties props = getCommonProperties();
props.setProperty(SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS, "");
DistributionConfig config1 = new DistributionConfigImpl(props, false);
assertThat(config1.getSecurityAuthTokenEnabledComponents()).hasSize(0);
Properties securityProps = config1.getSecurityProps();
assertThat(securityProps.getProperty(SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS)).isEqualTo("");
assertThat(config1.getSecurityAuthTokenEnabledComponents()).hasSize(0);
}
@Test
public void testSecurityAuthTokenProp() throws Exception {
Properties props = getCommonProperties();
props.setProperty(SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS, "management");
DistributionConfig config1 = new DistributionConfigImpl(props, false);
assertThat(config1.getSecurityAuthTokenEnabledComponents()).containsExactly("MANAGEMENT");
Properties securityProps = config1.getSecurityProps();
assertThat(securityProps.getProperty(SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS))
.isEqualTo("management");
assertThat(config1.getSecurityAuthTokenEnabledComponents()).containsExactly("MANAGEMENT");
}
@Test
public void testSSLEnabledComponents() {
Properties props = getCommonProperties();
props.setProperty(SSL_ENABLED_COMPONENTS, "cluster,server");
Config config1 = new DistributionConfigImpl(props, false);
assertEquals("cluster,server", config1.getAttribute(SSL_ENABLED_COMPONENTS));
}
@Rule
public ExpectedException illegalArgumentException = ExpectedException.none();
@Test(expected = IllegalArgumentException.class)
public void testSSLEnabledComponentsWrongComponentName() {
Properties props = getCommonProperties();
props.setProperty(SSL_ENABLED_COMPONENTS, "testing");
new DistributionConfigImpl(props, false);
illegalArgumentException.expect(IllegalArgumentException.class);
illegalArgumentException
.expectMessage("There is no registered component for the name: testing");
}
@Test(expected = IllegalArgumentException.class)
public void testSSLEnabledComponentsWithLegacyJMXSSLSettings() {
Properties props = getCommonProperties();
props.setProperty(SSL_ENABLED_COMPONENTS, "all");
props.setProperty(JMX_MANAGER_SSL_ENABLED, "true");
new DistributionConfigImpl(props, false);
illegalArgumentException.expect(IllegalArgumentException.class);
illegalArgumentException.expectMessage(
"When using ssl-enabled-components one cannot use any other SSL properties other than "
+ "cluster-ssl-* or the corresponding aliases");
}
@Test(expected = IllegalArgumentException.class)
public void testSSLEnabledComponentsWithLegacyGatewaySSLSettings() {
Properties props = getCommonProperties();
props.setProperty(SSL_ENABLED_COMPONENTS, "all");
props.setProperty(GATEWAY_SSL_ENABLED, "true");
new DistributionConfigImpl(props, false);
illegalArgumentException.expect(IllegalArgumentException.class);
illegalArgumentException.expectMessage(
"When using ssl-enabled-components one cannot use any other SSL properties other than "
+ "cluster-ssl-* or the corresponding aliases");
}
@Test(expected = IllegalArgumentException.class)
public void testSSLEnabledComponentsWithLegacyServerSSLSettings() {
Properties props = getCommonProperties();
props.setProperty(SSL_ENABLED_COMPONENTS, "all");
props.setProperty(SERVER_SSL_ENABLED, "true");
new DistributionConfigImpl(props, false);
illegalArgumentException.expect(IllegalArgumentException.class);
illegalArgumentException.expectMessage(
"When using ssl-enabled-components one cannot use any other SSL properties other than "
+ "cluster-ssl-* or the corresponding aliases");
}
@Test(expected = IllegalArgumentException.class)
public void testSSLEnabledComponentsWithLegacyHTTPServiceSSLSettings() {
Properties props = getCommonProperties();
props.setProperty(SSL_ENABLED_COMPONENTS, "all");
props.setProperty(HTTP_SERVICE_SSL_ENABLED, "true");
new DistributionConfigImpl(props, false);
illegalArgumentException.expect(IllegalArgumentException.class);
illegalArgumentException.expectMessage(
"When using ssl-enabled-components one cannot use any other SSL properties other than "
+ "cluster-ssl-* or the corresponding aliases");
}
@Test
public void usesSessionBuilderToCreateMetricsSession() {
MetricsService metricsSession = mock(MetricsService.class);
MetricsService.Builder metricsSessionBuilder = mock(MetricsService.Builder.class);
when(metricsSessionBuilder.build(any())).thenReturn(metricsSession);
createSystem(getCommonProperties(), metricsSessionBuilder);
verify(metricsSessionBuilder).build(system);
}
@Test
public void startsMetricsSession() {
MetricsService metricsSession = mock(MetricsService.class);
MetricsService.Builder metricsSessionBuilder = mock(MetricsService.Builder.class);
when(metricsSessionBuilder.build(any())).thenReturn(metricsSession);
when(metricsSession.getMeterRegistry()).thenReturn(mock(MeterRegistry.class));
createSystem(getCommonProperties(), metricsSessionBuilder);
verify(metricsSession).start();
}
@Test
public void getMeterRegistry_returnsMetricsSessionMeterRegistry() {
MeterRegistry sessionMeterRegistry = mock(MeterRegistry.class);
MetricsService metricsSession = mock(MetricsService.class);
when(metricsSession.getMeterRegistry()).thenReturn(sessionMeterRegistry);
MetricsService.Builder metricsSessionBuilder = mock(MetricsService.Builder.class);
when(metricsSessionBuilder.build(any())).thenReturn(metricsSession);
when(metricsSession.getMeterRegistry()).thenReturn(sessionMeterRegistry);
createSystem(getCommonProperties(), metricsSessionBuilder);
assertThat(system.getMeterRegistry()).isSameAs(sessionMeterRegistry);
}
private Properties getCommonProperties() {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
return props;
}
public static String getHostAddress(InetAddress addr) {
String address = addr.getHostAddress();
if (addr instanceof Inet4Address || (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress())) {
int idx = address.indexOf('%');
if (idx >= 0) {
address = address.substring(0, idx);
}
}
return address;
}
public static InetAddress getIPAddress() {
return Boolean.getBoolean("java.net.preferIPv6Addresses") ? getIPv6Address() : getIPv4Address();
}
protected static InetAddress getIPv4Address() {
InetAddress host = null;
try {
host = InetAddress.getLocalHost();
if (host instanceof Inet4Address) {
return host;
}
} catch (UnknownHostException e) {
String s = "Local host not found";
throw new RuntimeException(s, e);
}
try {
Enumeration i = NetworkInterface.getNetworkInterfaces();
while (i.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) i.nextElement();
Enumeration j = ni.getInetAddresses();
while (j.hasMoreElements()) {
InetAddress addr = (InetAddress) j.nextElement();
// gemfire won't form connections using link-local addresses
if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
&& (addr instanceof Inet4Address)) {
return addr;
}
}
}
String s = "IPv4 address not found";
throw new RuntimeException(s);
} catch (SocketException e) {
String s = "Problem reading IPv4 address";
throw new RuntimeException(s, e);
}
}
public static InetAddress getIPv6Address() {
try {
Enumeration i = NetworkInterface.getNetworkInterfaces();
while (i.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) i.nextElement();
Enumeration j = ni.getInetAddresses();
while (j.hasMoreElements()) {
InetAddress addr = (InetAddress) j.nextElement();
// gemfire won't form connections using link-local addresses
if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
&& (addr instanceof Inet6Address) && !isIPv6LinkLocalAddress((Inet6Address) addr)) {
return addr;
}
}
}
String s = "IPv6 address not found";
throw new RuntimeException(s);
} catch (SocketException e) {
String s = "Problem reading IPv6 address";
throw new RuntimeException(s, e);
}
}
/**
* Detect LinkLocal IPv6 address where the interface is missing, ie %[0-9].
*
* @see InetAddress#isLinkLocalAddress()
*/
private static boolean isIPv6LinkLocalAddress(Inet6Address addr) {
byte[] addrBytes = addr.getAddress();
return ((addrBytes[0] == (byte) 0xfe) && (addrBytes[1] == (byte) 0x80));
}
}
| {'content_hash': 'a540ca7c62fb731d842e9f3396a6e08a', 'timestamp': '', 'source': 'github', 'line_count': 906, 'max_line_length': 106, 'avg_line_length': 36.59713024282561, 'alnum_prop': 0.7156859788280001, 'repo_name': 'davinash/geode', 'id': 'eb36865a3ac19db2b33f4f591c83b1b6aa9e481b', 'size': '33946', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'geode-core/src/integrationTest/java/org/apache/geode/distributed/internal/InternalDistributedSystemJUnitTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '106707'}, {'name': 'Go', 'bytes': '1205'}, {'name': 'Groovy', 'bytes': '2783'}, {'name': 'HTML', 'bytes': '3917327'}, {'name': 'Java', 'bytes': '28126965'}, {'name': 'JavaScript', 'bytes': '1781013'}, {'name': 'Python', 'bytes': '5014'}, {'name': 'Ruby', 'bytes': '6686'}, {'name': 'Shell', 'bytes': '46841'}]} |
<?php
namespace Cerad\Bundle\TournBundle\Controller\AccountPassword;
// Cerad\Bundle\TournBundle\Controller\BaseController as MyBaseController;
use Cerad\Bundle\TournBundle\Controller\AccountPassword\AccountPasswordResetEmailController as MyBaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\EqualTo as EqualToConstraint;
use Symfony\Component\Validator\Constraints\NotBlank as NotBlankConstraint;
class AccountPasswordResetRequestedController extends MyBaseController
{
public function requestedAction(Request $request, $id = null, $token = null)
{
$userId = $id;
$model = $this->getModel($userId,$token);
if ($model instanceOf Response) return $model;
$form = $this->getModelForm($model);
$form->handleRequest($request);
if ($form->isValid())
{
$model1 = $form->getData();
$model2 = $this->processModel($model1);
// Log the user in
$this->loginUser($request,$model2['user']);
return $this->redirect('cerad_tourn_home');
}
// Pass on email information for testing
$emailModel = $this->getEmailModel($userId);
// Render
$tplData = array();
$tplData['form'] = $form->createView();
$tplData['user'] = $model['user'];
$tplData['userToken'] = $model['userToken'];
$tplData['emailBody'] = $emailModel['emailBody'];
$tplData['emailSubject'] = $emailModel['emailSubject'];
return $this->render('@CeradTourn/AccountPassword/ResetRequested/AccountPasswordResetRequestedIndex.html.twig',$tplData);
}
protected function fakeEmail($model)
{
}
protected function processModel($model)
{
$user = $model['user'];
$user->setPasswordResetToken(null);
$user->setPasswordPlain($model['password']);
$userManager = $this->get('cerad_user.user_manager');
$userManager->updateUser($user);
return $model;
}
protected function getModel($userId,$token)
{
if (!$userId) return $this->redirect('cerad_tourn_welcome');
$userManager = $this->get('cerad_user.user_manager');
$user = $userManager->findUser($userId);
if (!$user) return $this->redirect('cerad_tourn_welcome');
$userToken = $user->getPasswordResetToken();
if (!$userToken) return $this->redirect('cerad_tourn_welcome');
$model = array();
$model['user'] = $user;
$model['userToken'] = $userToken;
$model['token'] = $token;
$model['password'] = null;
return $model;
}
protected function getModelForm($model)
{
$equalToConstraintOptions = array(
'value' => $model['userToken'],
'message' => 'Invalid token value',
);
$builder = $this->createFormBuilder($model);
$builder->add('token','text', array(
'required' => true,
'label' => 'Password Reset Token (4 digits)',
'trim' => true,
'constraints' => array(
new NotBlankConstraint(),
new EqualToConstraint($equalToConstraintOptions),
),
'attr' => array('size' => 30),
));
$builder->add('password', 'repeated', array(
'type' => 'password',
'label' => 'Zayso Password',
'required' => true,
'attr' => array('size' => 20),
'invalid_message' => 'The password fields must match.',
'constraints' => new NotBlankConstraint(),
'first_options' => array('label' => 'New Password'),
'second_options' => array('label' => 'New Password(confirm)'),
'first_name' => 'pass1',
'second_name' => 'pass2',
));
return $builder->getForm();
}
}
?>
| {'content_hash': '20dfee6b1303d5f5d198ce6e0aed71ba', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 135, 'avg_line_length': 34.25196850393701, 'alnum_prop': 0.5326436781609195, 'repo_name': 'cerad/cerad2', 'id': 'e5fae65661cef6af3dacca7b6a4972c200d20edc', 'size': '4350', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Cerad/Bundle/TournBundle/Controller/AccountPassword/AccountPasswordResetRequestedController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '2614'}, {'name': 'PHP', 'bytes': '1279235'}, {'name': 'Shell', 'bytes': '188'}]} |
#ifndef _INC_DXVA
#define _INC_DXVA
#include <objbase.h>
#include <guiddef.h>
#ifdef __cplusplus
extern "C" {
#endif
DEFINE_GUID(DXVA_NoEncrypt, 0x1b81bed0, 0xa0c7,0x11d3, 0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5);
/* DXVA H264 */
typedef struct {
__C89_NAMELESS union {
__C89_NAMELESS struct {
UCHAR Index7Bits : 7;
UCHAR AssociatedFlag : 1;
};
UCHAR bPicEntry;
};
} DXVA_PicEntry_H264;
#pragma pack(push, 1)
typedef struct {
USHORT wFrameWidthInMbsMinus1;
USHORT wFrameHeightInMbsMinus1;
DXVA_PicEntry_H264 InPic;
DXVA_PicEntry_H264 OutPic;
USHORT PicOrderCnt_offset;
INT CurrPicOrderCnt;
UINT StatusReportFeedbackNumber;
UCHAR model_id;
UCHAR separate_colour_description_present_flag;
UCHAR film_grain_bit_depth_luma_minus8;
UCHAR film_grain_bit_depth_chroma_minus8;
UCHAR film_grain_full_range_flag;
UCHAR film_grain_colour_primaries;
UCHAR film_grain_transfer_characteristics;
UCHAR film_grain_matrix_coefficients;
UCHAR blending_mode_id;
UCHAR log2_scale_factor;
UCHAR comp_model_present_flag[4];
UCHAR num_intensity_intervals_minus1[4];
UCHAR num_model_values_minus1[4];
UCHAR intensity_interval_lower_bound[3][16];
UCHAR intensity_interval_upper_bound[3][16];
SHORT comp_model_value[3][16][8];
} DXVA_FilmGrainChar_H264;
#pragma pack(pop)
/* DXVA MPEG-I/II and VC-1 */
typedef struct _DXVA_PictureParameters {
USHORT wDecodedPictureIndex;
USHORT wDeblockedPictureIndex;
USHORT wForwardRefPictureIndex;
USHORT wBackwardRefPictureIndex;
USHORT wPicWidthInMBminus1;
USHORT wPicHeightInMBminus1;
UCHAR bMacroblockWidthMinus1;
UCHAR bMacroblockHeightMinus1;
UCHAR bBlockWidthMinus1;
UCHAR bBlockHeightMinus1;
UCHAR bBPPminus1;
UCHAR bPicStructure;
UCHAR bSecondField;
UCHAR bPicIntra;
UCHAR bPicBackwardPrediction;
UCHAR bBidirectionalAveragingMode;
UCHAR bMVprecisionAndChromaRelation;
UCHAR bChromaFormat;
UCHAR bPicScanFixed;
UCHAR bPicScanMethod;
UCHAR bPicReadbackRequests;
UCHAR bRcontrol;
UCHAR bPicSpatialResid8;
UCHAR bPicOverflowBlocks;
UCHAR bPicExtrapolation;
UCHAR bPicDeblocked;
UCHAR bPicDeblockConfined;
UCHAR bPic4MVallowed;
UCHAR bPicOBMC;
UCHAR bPicBinPB;
UCHAR bMV_RPS;
UCHAR bReservedBits;
USHORT wBitstreamFcodes;
USHORT wBitstreamPCEelements;
UCHAR bBitstreamConcealmentNeed;
UCHAR bBitstreamConcealmentMethod;
} DXVA_PictureParameters, *LPDXVA_PictureParameters;
typedef struct _DXVA_QmatrixData {
BYTE bNewQmatrix[4];
WORD Qmatrix[4][8 * 8];
} DXVA_QmatrixData, *LPDXVA_QmatrixData;
#pragma pack(push, 1)
typedef struct _DXVA_SliceInfo {
USHORT wHorizontalPosition;
USHORT wVerticalPosition;
UINT dwSliceBitsInBuffer;
UINT dwSliceDataLocation;
UCHAR bStartCodeBitOffset;
UCHAR bReservedBits;
USHORT wMBbitOffset;
USHORT wNumberMBsInSlice;
USHORT wQuantizerScaleCode;
USHORT wBadSliceChopping;
} DXVA_SliceInfo, *LPDXVA_SliceInfo;
#pragma pack(pop)
typedef struct {
USHORT wFrameWidthInMbsMinus1;
USHORT wFrameHeightInMbsMinus1;
DXVA_PicEntry_H264 CurrPic;
UCHAR num_ref_frames;
__C89_NAMELESS union {
__C89_NAMELESS struct {
USHORT field_pic_flag : 1;
USHORT MbaffFrameFlag : 1;
USHORT residual_colour_transform_flag : 1;
USHORT sp_for_switch_flag : 1;
USHORT chroma_format_idc : 2;
USHORT RefPicFlag : 1;
USHORT constrained_intra_pred_flag : 1;
USHORT weighted_pred_flag : 1;
USHORT weighted_bipred_idc : 2;
USHORT MbsConsecutiveFlag : 1;
USHORT frame_mbs_only_flag : 1;
USHORT transform_8x8_mode_flag : 1;
USHORT MinLumaBipredSize8x8Flag : 1;
USHORT IntraPicFlag : 1;
};
USHORT wBitFields;
};
UCHAR bit_depth_luma_minus8;
UCHAR bit_depth_chroma_minus8;
USHORT Reserved16Bits;
UINT StatusReportFeedbackNumber;
DXVA_PicEntry_H264 RefFrameList[16];
INT CurrFieldOrderCnt[2];
INT FieldOrderCntList[16][2];
CHAR pic_init_qs_minus26;
CHAR chroma_qp_index_offset;
CHAR second_chroma_qp_index_offset;
UCHAR ContinuationFlag;
CHAR pic_init_qp_minus26;
UCHAR num_ref_idx_l0_active_minus1;
UCHAR num_ref_idx_l1_active_minus1;
UCHAR Reserved8BitsA;
USHORT FrameNumList[16];
UINT UsedForReferenceFlags;
USHORT NonExistingFrameFlags;
USHORT frame_num;
UCHAR log2_max_frame_num_minus4;
UCHAR pic_order_cnt_type;
UCHAR log2_max_pic_order_cnt_lsb_minus4;
UCHAR delta_pic_order_always_zero_flag;
UCHAR direct_8x8_inference_flag;
UCHAR entropy_coding_mode_flag;
UCHAR pic_order_present_flag;
UCHAR num_slice_groups_minus1;
UCHAR slice_group_map_type;
UCHAR deblocking_filter_control_present_flag;
UCHAR redundant_pic_cnt_present_flag;
UCHAR Reserved8BitsB;
USHORT slice_group_change_rate_minus1;
UCHAR SliceGroupMap[810];
} DXVA_PicParams_H264;
typedef struct {
UCHAR bScalingLists4x4[6][16];
UCHAR bScalingLists8x8[2][64];
} DXVA_Qmatrix_H264;
typedef struct {
UINT BSNALunitDataLocation;
UINT SliceBytesInBuffer;
USHORT wBadSliceChopping;
USHORT first_mb_in_slice;
USHORT NumMbsForSlice;
USHORT BitOffsetToSliceData;
UCHAR slice_type;
UCHAR luma_log2_weight_denom;
UCHAR chroma_log2_weight_denom;
UCHAR num_ref_idx_l0_active_minus1;
UCHAR num_ref_idx_l1_active_minus1;
CHAR slice_alpha_c0_offset_div2;
CHAR slice_beta_offset_div2;
UCHAR Reserved8Bits;
DXVA_PicEntry_H264 RefPicList[2][32];
SHORT Weights[2][32][3][2];
CHAR slice_qs_delta;
CHAR slice_qp_delta;
UCHAR redundant_pic_cnt;
UCHAR direct_spatial_mv_pred_flag;
UCHAR cabac_init_idc;
UCHAR disable_deblocking_filter_idc;
USHORT slice_id;
} DXVA_Slice_H264_Long;
#pragma pack(push, 1)
typedef struct {
UINT BSNALunitDataLocation;
UINT SliceBytesInBuffer;
USHORT wBadSliceChopping;
} DXVA_Slice_H264_Short;
#pragma pack(pop)
#ifdef __cplusplus
}
#endif
#endif /*_INC_DXVA */
| {'content_hash': 'f6c1a9f0de78db55a0be3e2d9b6b78c6', 'timestamp': '', 'source': 'github', 'line_count': 214, 'max_line_length': 96, 'avg_line_length': 30.827102803738317, 'alnum_prop': 0.6649992420797333, 'repo_name': 'BaladiDogGames/baladidoggames.github.io', 'id': 'e1793d97839080a227264220886943572ba71cd2', 'size': '6812', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'mingw/x86_64-w64-mingw32/include/dxva.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Awk', 'bytes': '15017'}, {'name': 'Batchfile', 'bytes': '7644'}, {'name': 'C', 'bytes': '15612499'}, {'name': 'C++', 'bytes': '27658068'}, {'name': 'CSS', 'bytes': '29978'}, {'name': 'Groff', 'bytes': '2485806'}, {'name': 'HTML', 'bytes': '39059'}, {'name': 'JavaScript', 'bytes': '1777'}, {'name': 'Logos', 'bytes': '12151'}, {'name': 'M4', 'bytes': '1261905'}, {'name': 'Makefile', 'bytes': '70349'}, {'name': 'Objective-C', 'bytes': '145718'}, {'name': 'Perl', 'bytes': '11840799'}, {'name': 'Perl6', 'bytes': '495961'}, {'name': 'PowerShell', 'bytes': '361'}, {'name': 'Prolog', 'bytes': '553295'}, {'name': 'Pure Data', 'bytes': '456'}, {'name': 'Python', 'bytes': '7792798'}, {'name': 'Ruby', 'bytes': '10035'}, {'name': 'Shell', 'bytes': '985968'}, {'name': 'TeX', 'bytes': '295145'}, {'name': 'XSLT', 'bytes': '55335'}]} |
module.exports = {
// Shared discordid by mock discord users and test players
discordid: '1234567890'
};
| {'content_hash': '420e7f7aea09918ef483ee07f177bf73', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 62, 'avg_line_length': 28.25, 'alnum_prop': 0.6991150442477876, 'repo_name': 'RocketLeagueLatvia/discord-bot', 'id': 'ef861b6dcd02c4c6d7ecdcd3fed3a65aff36eb91', 'size': '113', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/lib/constants.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '86817'}]} |
layout: archive
permalink: /tags/
title: "按标签分类"
author_profile: true
---
{% include group-by-array collection=site.posts field="tags" %}
{% for tag in group_names %}
{% assign posts = group_items[forloop.index0] %}
<h2 id="{{ tag | slugify }}" class="archive__subtitle">{{ tag }}</h2>
{% for post in posts %}
{% include archive-single.html %}
{% endfor %}
{% endfor %} | {'content_hash': 'd6d52fe1d5887a38df7dab89cb2c5288', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 71, 'avg_line_length': 25.533333333333335, 'alnum_prop': 0.6292428198433421, 'repo_name': 'leeic007/leeic007.github.com', 'id': 'edbc1dd754591976981ca6fb01f775c3f299a253', 'size': '397', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_pages/tag-archive.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '69476'}, {'name': 'HTML', 'bytes': '323244'}, {'name': 'JavaScript', 'bytes': '53831'}, {'name': 'Ruby', 'bytes': '4067'}]} |
package org.apache.kafka.clients.producer.internals;
import org.apache.kafka.clients.ClientResponse;
import org.apache.kafka.clients.RequestCompletionHandler;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.AuthenticationException;
import org.apache.kafka.common.errors.GroupAuthorizationException;
import org.apache.kafka.common.errors.TopicAuthorizationException;
import org.apache.kafka.common.protocol.Errors;
import org.apache.kafka.common.record.RecordBatch;
import org.apache.kafka.common.requests.AbstractRequest;
import org.apache.kafka.common.requests.AbstractResponse;
import org.apache.kafka.common.requests.AddOffsetsToTxnRequest;
import org.apache.kafka.common.requests.AddOffsetsToTxnResponse;
import org.apache.kafka.common.requests.AddPartitionsToTxnRequest;
import org.apache.kafka.common.requests.AddPartitionsToTxnResponse;
import org.apache.kafka.common.requests.EndTxnRequest;
import org.apache.kafka.common.requests.EndTxnResponse;
import org.apache.kafka.common.requests.FindCoordinatorRequest;
import org.apache.kafka.common.requests.FindCoordinatorResponse;
import org.apache.kafka.common.requests.InitProducerIdRequest;
import org.apache.kafka.common.requests.InitProducerIdResponse;
import org.apache.kafka.common.requests.ProduceResponse;
import org.apache.kafka.common.requests.TransactionResult;
import org.apache.kafka.common.requests.TxnOffsetCommitRequest;
import org.apache.kafka.common.requests.TxnOffsetCommitRequest.CommittedOffset;
import org.apache.kafka.common.requests.TxnOffsetCommitResponse;
import org.apache.kafka.common.utils.LogContext;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import static org.apache.kafka.common.record.RecordBatch.NO_PRODUCER_EPOCH;
import static org.apache.kafka.common.record.RecordBatch.NO_PRODUCER_ID;
/**
* A class which maintains state for transactions. Also keeps the state necessary to ensure idempotent production.
*/
public class TransactionManager {
private static final int NO_INFLIGHT_REQUEST_CORRELATION_ID = -1;
private final Logger log;
private final String transactionalId;
private final int transactionTimeoutMs;
// The base sequence of the next batch bound for a given partition.
private final Map<TopicPartition, Integer> nextSequence;
// The sequence of the last record of the last ack'd batch from the given partition. When there are no
// in flight requests for a partition, the lastAckedSequence(topicPartition) == nextSequence(topicPartition) - 1.
private final Map<TopicPartition, Integer> lastAckedSequence;
// If a batch bound for a partition expired locally after being sent at least once, the partition has is considered
// to have an unresolved state. We keep track fo such partitions here, and cannot assign any more sequence numbers
// for this partition until the unresolved state gets cleared. This may happen if other inflight batches returned
// successfully (indicating that the expired batch actually made it to the broker). If we don't get any successful
// responses for the partition once the inflight request count falls to zero, we reset the producer id and
// consequently clear this data structure as well.
private final Set<TopicPartition> partitionsWithUnresolvedSequences;
// Keep track of the in flight batches bound for a partition, ordered by sequence. This helps us to ensure that
// we continue to order batches by the sequence numbers even when the responses come back out of order during
// leader failover. We add a batch to the queue when it is drained, and remove it when the batch completes
// (either successfully or through a fatal failure).
private final Map<TopicPartition, PriorityQueue<ProducerBatch>> inflightBatchesBySequence;
// We keep track of the last acknowledged offset on a per partition basis in order to disambiguate UnknownProducer
// responses which are due to the retention period elapsing, and those which are due to actual lost data.
private final Map<TopicPartition, Long> lastAckedOffset;
private final PriorityQueue<TxnRequestHandler> pendingRequests;
private final Set<TopicPartition> newPartitionsInTransaction;
private final Set<TopicPartition> pendingPartitionsInTransaction;
private final Set<TopicPartition> partitionsInTransaction;
private final Map<TopicPartition, CommittedOffset> pendingTxnOffsetCommits;
// This is used by the TxnRequestHandlers to control how long to back off before a given request is retried.
// For instance, this value is lowered by the AddPartitionsToTxnHandler when it receives a CONCURRENT_TRANSACTIONS
// error for the first AddPartitionsRequest in a transaction.
private final long retryBackoffMs;
// The retryBackoff is overridden to the following value if the first AddPartitions receives a
// CONCURRENT_TRANSACTIONS error.
private static final long ADD_PARTITIONS_RETRY_BACKOFF_MS = 20L;
private int inFlightRequestCorrelationId = NO_INFLIGHT_REQUEST_CORRELATION_ID;
private Node transactionCoordinator;
private Node consumerGroupCoordinator;
private volatile State currentState = State.UNINITIALIZED;
private volatile RuntimeException lastError = null;
private volatile ProducerIdAndEpoch producerIdAndEpoch;
private volatile boolean transactionStarted = false;
private enum State {
UNINITIALIZED,
INITIALIZING,
READY,
IN_TRANSACTION,
COMMITTING_TRANSACTION,
ABORTING_TRANSACTION,
ABORTABLE_ERROR,
FATAL_ERROR;
private boolean isTransitionValid(State source, State target) {
switch (target) {
case INITIALIZING:
return source == UNINITIALIZED;
case READY:
return source == INITIALIZING || source == COMMITTING_TRANSACTION || source == ABORTING_TRANSACTION;
case IN_TRANSACTION:
return source == READY;
case COMMITTING_TRANSACTION:
return source == IN_TRANSACTION;
case ABORTING_TRANSACTION:
return source == IN_TRANSACTION || source == ABORTABLE_ERROR;
case ABORTABLE_ERROR:
return source == IN_TRANSACTION || source == COMMITTING_TRANSACTION || source == ABORTABLE_ERROR;
case FATAL_ERROR:
default:
// We can transition to FATAL_ERROR unconditionally.
// FATAL_ERROR is never a valid starting state for any transition. So the only option is to close the
// producer or do purely non transactional requests.
return true;
}
}
}
// We use the priority to determine the order in which requests need to be sent out. For instance, if we have
// a pending FindCoordinator request, that must always go first. Next, If we need a producer id, that must go second.
// The endTxn request must always go last.
private enum Priority {
FIND_COORDINATOR(0),
INIT_PRODUCER_ID(1),
ADD_PARTITIONS_OR_OFFSETS(2),
END_TXN(3);
final int priority;
Priority(int priority) {
this.priority = priority;
}
}
public TransactionManager(LogContext logContext, String transactionalId, int transactionTimeoutMs, long retryBackoffMs) {
this.producerIdAndEpoch = new ProducerIdAndEpoch(NO_PRODUCER_ID, NO_PRODUCER_EPOCH);
this.nextSequence = new HashMap<>();
this.lastAckedSequence = new HashMap<>();
this.transactionalId = transactionalId;
this.log = logContext.logger(TransactionManager.class);
this.transactionTimeoutMs = transactionTimeoutMs;
this.transactionCoordinator = null;
this.consumerGroupCoordinator = null;
this.newPartitionsInTransaction = new HashSet<>();
this.pendingPartitionsInTransaction = new HashSet<>();
this.partitionsInTransaction = new HashSet<>();
this.pendingTxnOffsetCommits = new HashMap<>();
this.pendingRequests = new PriorityQueue<>(10, new Comparator<TxnRequestHandler>() {
@Override
public int compare(TxnRequestHandler o1, TxnRequestHandler o2) {
return Integer.compare(o1.priority().priority, o2.priority().priority);
}
});
this.partitionsWithUnresolvedSequences = new HashSet<>();
this.inflightBatchesBySequence = new HashMap<>();
this.lastAckedOffset = new HashMap<>();
this.retryBackoffMs = retryBackoffMs;
}
TransactionManager() {
this(new LogContext(), null, 0, 100);
}
public synchronized TransactionalRequestResult initializeTransactions() {
ensureTransactional();
transitionTo(State.INITIALIZING);
setProducerIdAndEpoch(ProducerIdAndEpoch.NONE);
this.nextSequence.clear();
InitProducerIdRequest.Builder builder = new InitProducerIdRequest.Builder(transactionalId, transactionTimeoutMs);
InitProducerIdHandler handler = new InitProducerIdHandler(builder);
enqueueRequest(handler);
return handler.result;
}
public synchronized void beginTransaction() {
ensureTransactional();
maybeFailWithError();
transitionTo(State.IN_TRANSACTION);
}
public synchronized TransactionalRequestResult beginCommit() {
ensureTransactional();
maybeFailWithError();
transitionTo(State.COMMITTING_TRANSACTION);
return beginCompletingTransaction(TransactionResult.COMMIT);
}
public synchronized TransactionalRequestResult beginAbort() {
ensureTransactional();
if (currentState != State.ABORTABLE_ERROR)
maybeFailWithError();
transitionTo(State.ABORTING_TRANSACTION);
// We're aborting the transaction, so there should be no need to add new partitions
newPartitionsInTransaction.clear();
return beginCompletingTransaction(TransactionResult.ABORT);
}
private TransactionalRequestResult beginCompletingTransaction(TransactionResult transactionResult) {
if (!newPartitionsInTransaction.isEmpty())
enqueueRequest(addPartitionsToTransactionHandler());
EndTxnRequest.Builder builder = new EndTxnRequest.Builder(transactionalId, producerIdAndEpoch.producerId,
producerIdAndEpoch.epoch, transactionResult);
EndTxnHandler handler = new EndTxnHandler(builder);
enqueueRequest(handler);
return handler.result;
}
public synchronized TransactionalRequestResult sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets,
String consumerGroupId) {
ensureTransactional();
maybeFailWithError();
if (currentState != State.IN_TRANSACTION)
throw new KafkaException("Cannot send offsets to transaction either because the producer is not in an " +
"active transaction");
log.debug("Begin adding offsets {} for consumer group {} to transaction", offsets, consumerGroupId);
AddOffsetsToTxnRequest.Builder builder = new AddOffsetsToTxnRequest.Builder(transactionalId,
producerIdAndEpoch.producerId, producerIdAndEpoch.epoch, consumerGroupId);
AddOffsetsToTxnHandler handler = new AddOffsetsToTxnHandler(builder, offsets);
enqueueRequest(handler);
return handler.result;
}
public synchronized void maybeAddPartitionToTransaction(TopicPartition topicPartition) {
failIfNotReadyForSend();
if (isPartitionAdded(topicPartition) || isPartitionPendingAdd(topicPartition))
return;
log.debug("Begin adding new partition {} to transaction", topicPartition);
newPartitionsInTransaction.add(topicPartition);
}
RuntimeException lastError() {
return lastError;
}
public synchronized void failIfNotReadyForSend() {
if (hasError())
throw new KafkaException("Cannot perform send because at least one previous transactional or " +
"idempotent request has failed with errors.", lastError);
if (isTransactional()) {
if (!hasProducerId())
throw new IllegalStateException("Cannot perform a 'send' before completing a call to initTransactions " +
"when transactions are enabled.");
if (currentState != State.IN_TRANSACTION)
throw new IllegalStateException("Cannot call send in state " + currentState);
}
}
synchronized boolean isSendToPartitionAllowed(TopicPartition tp) {
if (hasFatalError())
return false;
return !isTransactional() || partitionsInTransaction.contains(tp);
}
public String transactionalId() {
return transactionalId;
}
public boolean hasProducerId() {
return producerIdAndEpoch.isValid();
}
public boolean isTransactional() {
return transactionalId != null;
}
synchronized boolean hasPartitionsToAdd() {
return !newPartitionsInTransaction.isEmpty() || !pendingPartitionsInTransaction.isEmpty();
}
synchronized boolean isCompleting() {
return currentState == State.COMMITTING_TRANSACTION || currentState == State.ABORTING_TRANSACTION;
}
synchronized boolean hasError() {
return currentState == State.ABORTABLE_ERROR || currentState == State.FATAL_ERROR;
}
synchronized boolean isAborting() {
return currentState == State.ABORTING_TRANSACTION;
}
synchronized void transitionToAbortableError(RuntimeException exception) {
if (currentState == State.ABORTING_TRANSACTION) {
log.debug("Skipping transition to abortable error state since the transaction is already being " +
"aborted. Underlying exception: ", exception);
return;
}
transitionTo(State.ABORTABLE_ERROR, exception);
}
synchronized void transitionToFatalError(RuntimeException exception) {
transitionTo(State.FATAL_ERROR, exception);
}
// visible for testing
synchronized boolean isPartitionAdded(TopicPartition partition) {
return partitionsInTransaction.contains(partition);
}
// visible for testing
synchronized boolean isPartitionPendingAdd(TopicPartition partition) {
return newPartitionsInTransaction.contains(partition) || pendingPartitionsInTransaction.contains(partition);
}
/**
* Get the current producer id and epoch without blocking. Callers must use {@link ProducerIdAndEpoch#isValid()} to
* verify that the result is valid.
*
* @return the current ProducerIdAndEpoch.
*/
ProducerIdAndEpoch producerIdAndEpoch() {
return producerIdAndEpoch;
}
boolean hasProducerId(long producerId) {
return producerIdAndEpoch.producerId == producerId;
}
boolean hasProducerIdAndEpoch(long producerId, short producerEpoch) {
ProducerIdAndEpoch idAndEpoch = this.producerIdAndEpoch;
return idAndEpoch.producerId == producerId && idAndEpoch.epoch == producerEpoch;
}
/**
* Set the producer id and epoch atomically.
*/
void setProducerIdAndEpoch(ProducerIdAndEpoch producerIdAndEpoch) {
log.info("ProducerId set to {} with epoch {}", producerIdAndEpoch.producerId, producerIdAndEpoch.epoch);
this.producerIdAndEpoch = producerIdAndEpoch;
}
/**
* This method is used when the producer needs to reset its internal state because of an irrecoverable exception
* from the broker.
*
* We need to reset the producer id and associated state when we have sent a batch to the broker, but we either get
* a non-retriable exception or we run out of retries, or the batch expired in the producer queue after it was already
* sent to the broker.
*
* In all of these cases, we don't know whether batch was actually committed on the broker, and hence whether the
* sequence number was actually updated. If we don't reset the producer state, we risk the chance that all future
* messages will return an OutOfOrderSequenceException.
*
* Note that we can't reset the producer state for the transactional producer as this would mean bumping the epoch
* for the same producer id. This might involve aborting the ongoing transaction during the initPidRequest, and the user
* would not have any way of knowing this happened. So for the transactional producer, it's best to return the
* produce error to the user and let them abort the transaction and close the producer explicitly.
*/
synchronized void resetProducerId() {
if (isTransactional())
throw new IllegalStateException("Cannot reset producer state for a transactional producer. " +
"You must either abort the ongoing transaction or reinitialize the transactional producer instead");
setProducerIdAndEpoch(ProducerIdAndEpoch.NONE);
this.nextSequence.clear();
this.lastAckedSequence.clear();
this.inflightBatchesBySequence.clear();
this.partitionsWithUnresolvedSequences.clear();
this.lastAckedOffset.clear();
}
/**
* Returns the next sequence number to be written to the given TopicPartition.
*/
synchronized Integer sequenceNumber(TopicPartition topicPartition) {
Integer currentSequenceNumber = nextSequence.get(topicPartition);
if (currentSequenceNumber == null) {
currentSequenceNumber = 0;
nextSequence.put(topicPartition, currentSequenceNumber);
}
return currentSequenceNumber;
}
synchronized void incrementSequenceNumber(TopicPartition topicPartition, int increment) {
Integer currentSequenceNumber = nextSequence.get(topicPartition);
if (currentSequenceNumber == null)
throw new IllegalStateException("Attempt to increment sequence number for a partition with no current sequence.");
currentSequenceNumber += increment;
nextSequence.put(topicPartition, currentSequenceNumber);
}
synchronized void addInFlightBatch(ProducerBatch batch) {
if (!batch.hasSequence())
throw new IllegalStateException("Can't track batch for partition " + batch.topicPartition + " when sequence is not set.");
if (!inflightBatchesBySequence.containsKey(batch.topicPartition)) {
inflightBatchesBySequence.put(batch.topicPartition, new PriorityQueue<>(5, new Comparator<ProducerBatch>() {
@Override
public int compare(ProducerBatch o1, ProducerBatch o2) {
return o1.baseSequence() - o2.baseSequence();
}
}));
}
inflightBatchesBySequence.get(batch.topicPartition).offer(batch);
}
/**
* Returns the first inflight sequence for a given partition. This is the base sequence of an inflight batch with
* the lowest sequence number.
* @return the lowest inflight sequence if the transaction manager is tracking inflight requests for this partition.
* If there are no inflight requests being tracked for this partition, this method will return
* RecordBatch.NO_SEQUENCE.
*/
synchronized int firstInFlightSequence(TopicPartition topicPartition) {
PriorityQueue<ProducerBatch> inFlightBatches = inflightBatchesBySequence.get(topicPartition);
if (inFlightBatches == null)
return RecordBatch.NO_SEQUENCE;
ProducerBatch firstInFlightBatch = inFlightBatches.peek();
if (firstInFlightBatch == null)
return RecordBatch.NO_SEQUENCE;
return firstInFlightBatch.baseSequence();
}
synchronized ProducerBatch nextBatchBySequence(TopicPartition topicPartition) {
PriorityQueue<ProducerBatch> queue = inflightBatchesBySequence.get(topicPartition);
if (queue == null)
return null;
return queue.peek();
}
synchronized void removeInFlightBatch(ProducerBatch batch) {
PriorityQueue<ProducerBatch> queue = inflightBatchesBySequence.get(batch.topicPartition);
if (queue == null)
return;
queue.remove(batch);
}
synchronized void maybeUpdateLastAckedSequence(TopicPartition topicPartition, int sequence) {
if (sequence > lastAckedSequence(topicPartition))
lastAckedSequence.put(topicPartition, sequence);
}
synchronized int lastAckedSequence(TopicPartition topicPartition) {
Integer currentLastAckedSequence = lastAckedSequence.get(topicPartition);
if (currentLastAckedSequence == null)
return -1;
return currentLastAckedSequence;
}
synchronized long lastAckedOffset(TopicPartition topicPartition) {
Long offset = lastAckedOffset.get(topicPartition);
if (offset == null)
return ProduceResponse.INVALID_OFFSET;
return offset;
}
synchronized void updateLastAckedOffset(ProduceResponse.PartitionResponse response, ProducerBatch batch) {
if (response.baseOffset == ProduceResponse.INVALID_OFFSET)
return;
long lastOffset = response.baseOffset + batch.recordCount - 1;
if (lastOffset > lastAckedOffset(batch.topicPartition)) {
lastAckedOffset.put(batch.topicPartition, lastOffset);
} else {
log.trace("Partition {} keeps lastOffset at {}", batch.topicPartition, lastOffset);
}
}
// If a batch is failed fatally, the sequence numbers for future batches bound for the partition must be adjusted
// so that they don't fail with the OutOfOrderSequenceException.
//
// This method must only be called when we know that the batch is question has been unequivocally failed by the broker,
// ie. it has received a confirmed fatal status code like 'Message Too Large' or something similar.
synchronized void adjustSequencesDueToFailedBatch(ProducerBatch batch) {
if (!this.nextSequence.containsKey(batch.topicPartition))
// Sequence numbers are not being tracked for this partition. This could happen if the producer id was just
// reset due to a previous OutOfOrderSequenceException.
return;
log.debug("producerId: {}, send to partition {} failed fatally. Reducing future sequence numbers by {}",
batch.producerId(), batch.topicPartition, batch.recordCount);
int currentSequence = sequenceNumber(batch.topicPartition);
currentSequence -= batch.recordCount;
if (currentSequence < 0)
throw new IllegalStateException("Sequence number for partition " + batch.topicPartition + " is going to become negative : " + currentSequence);
setNextSequence(batch.topicPartition, currentSequence);
for (ProducerBatch inFlightBatch : inflightBatchesBySequence.get(batch.topicPartition)) {
if (inFlightBatch.baseSequence() < batch.baseSequence())
continue;
int newSequence = inFlightBatch.baseSequence() - batch.recordCount;
if (newSequence < 0)
throw new IllegalStateException("Sequence number for batch with sequence " + inFlightBatch.baseSequence()
+ " for partition " + batch.topicPartition + " is going to become negative :" + newSequence);
log.info("Resetting sequence number of batch with current sequence {} for partition {} to {}", inFlightBatch.baseSequence(), batch.topicPartition, newSequence);
inFlightBatch.resetProducerState(new ProducerIdAndEpoch(inFlightBatch.producerId(), inFlightBatch.producerEpoch()), newSequence, inFlightBatch.isTransactional());
}
}
private synchronized void startSequencesAtBeginning(TopicPartition topicPartition) {
int sequence = 0;
for (ProducerBatch inFlightBatch : inflightBatchesBySequence.get(topicPartition)) {
log.info("Resetting sequence number of batch with current sequence {} for partition {} to {}",
inFlightBatch.baseSequence(), inFlightBatch.topicPartition, sequence);
inFlightBatch.resetProducerState(new ProducerIdAndEpoch(inFlightBatch.producerId(),
inFlightBatch.producerEpoch()), sequence, inFlightBatch.isTransactional());
sequence += inFlightBatch.recordCount;
}
setNextSequence(topicPartition, sequence);
lastAckedSequence.remove(topicPartition);
}
synchronized boolean hasInflightBatches(TopicPartition topicPartition) {
return inflightBatchesBySequence.containsKey(topicPartition) && !inflightBatchesBySequence.get(topicPartition).isEmpty();
}
synchronized boolean hasUnresolvedSequences() {
return !partitionsWithUnresolvedSequences.isEmpty();
}
synchronized boolean hasUnresolvedSequence(TopicPartition topicPartition) {
return partitionsWithUnresolvedSequences.contains(topicPartition);
}
synchronized void markSequenceUnresolved(TopicPartition topicPartition) {
log.debug("Marking partition {} unresolved", topicPartition);
partitionsWithUnresolvedSequences.add(topicPartition);
}
// Checks if there are any partitions with unresolved partitions which may now be resolved. Returns true if
// the producer id needs a reset, false otherwise.
synchronized boolean shouldResetProducerStateAfterResolvingSequences() {
if (isTransactional())
// We should not reset producer state if we are transactional. We will transition to a fatal error instead.
return false;
for (Iterator<TopicPartition> iter = partitionsWithUnresolvedSequences.iterator(); iter.hasNext(); ) {
TopicPartition topicPartition = iter.next();
if (!hasInflightBatches(topicPartition)) {
// The partition has been fully drained. At this point, the last ack'd sequence should be once less than
// next sequence destined for the partition. If so, the partition is fully resolved. If not, we should
// reset the sequence number if necessary.
if (isNextSequence(topicPartition, sequenceNumber(topicPartition))) {
// This would happen when a batch was expired, but subsequent batches succeeded.
iter.remove();
} else {
// We would enter this branch if all in flight batches were ultimately expired in the producer.
log.info("No inflight batches remaining for {}, last ack'd sequence for partition is {}, next sequence is {}. " +
"Going to reset producer state.", topicPartition, lastAckedSequence(topicPartition), sequenceNumber(topicPartition));
return true;
}
}
}
return false;
}
synchronized boolean isNextSequence(TopicPartition topicPartition, int sequence) {
return sequence - lastAckedSequence(topicPartition) == 1;
}
private synchronized void setNextSequence(TopicPartition topicPartition, int sequence) {
if (!nextSequence.containsKey(topicPartition) && sequence != 0)
throw new IllegalStateException("Trying to set the sequence number for " + topicPartition + " to " + sequence +
", but the sequence number was never set for this partition.");
nextSequence.put(topicPartition, sequence);
}
synchronized TxnRequestHandler nextRequestHandler(boolean hasIncompleteBatches) {
if (!newPartitionsInTransaction.isEmpty())
enqueueRequest(addPartitionsToTransactionHandler());
TxnRequestHandler nextRequestHandler = pendingRequests.peek();
if (nextRequestHandler == null)
return null;
// Do not send the EndTxn until all batches have been flushed
if (nextRequestHandler.isEndTxn() && hasIncompleteBatches)
return null;
pendingRequests.poll();
if (maybeTerminateRequestWithError(nextRequestHandler)) {
log.trace("Not sending transactional request {} because we are in an error state",
nextRequestHandler.requestBuilder());
return null;
}
if (nextRequestHandler.isEndTxn() && !transactionStarted) {
nextRequestHandler.result.done();
if (currentState != State.FATAL_ERROR) {
log.debug("Not sending EndTxn for completed transaction since no partitions " +
"or offsets were successfully added");
completeTransaction();
}
nextRequestHandler = pendingRequests.poll();
}
if (nextRequestHandler != null)
log.trace("Request {} dequeued for sending", nextRequestHandler.requestBuilder());
return nextRequestHandler;
}
synchronized void retry(TxnRequestHandler request) {
request.setRetry();
enqueueRequest(request);
}
synchronized void authenticationFailed(AuthenticationException e) {
for (TxnRequestHandler request : pendingRequests)
request.fatalError(e);
}
Node coordinator(FindCoordinatorRequest.CoordinatorType type) {
switch (type) {
case GROUP:
return consumerGroupCoordinator;
case TRANSACTION:
return transactionCoordinator;
default:
throw new IllegalStateException("Received an invalid coordinator type: " + type);
}
}
void lookupCoordinator(TxnRequestHandler request) {
lookupCoordinator(request.coordinatorType(), request.coordinatorKey());
}
void setInFlightTransactionalRequestCorrelationId(int correlationId) {
inFlightRequestCorrelationId = correlationId;
}
void clearInFlightTransactionalRequestCorrelationId() {
inFlightRequestCorrelationId = NO_INFLIGHT_REQUEST_CORRELATION_ID;
}
boolean hasInFlightTransactionalRequest() {
return inFlightRequestCorrelationId != NO_INFLIGHT_REQUEST_CORRELATION_ID;
}
// visible for testing.
boolean hasFatalError() {
return currentState == State.FATAL_ERROR;
}
// visible for testing.
boolean hasAbortableError() {
return currentState == State.ABORTABLE_ERROR;
}
// visible for testing
synchronized boolean transactionContainsPartition(TopicPartition topicPartition) {
return partitionsInTransaction.contains(topicPartition);
}
// visible for testing
synchronized boolean hasPendingOffsetCommits() {
return !pendingTxnOffsetCommits.isEmpty();
}
// visible for testing
synchronized boolean hasOngoingTransaction() {
// transactions are considered ongoing once started until completion or a fatal error
return currentState == State.IN_TRANSACTION || isCompleting() || hasAbortableError();
}
synchronized boolean canRetry(ProduceResponse.PartitionResponse response, ProducerBatch batch) {
if (!hasProducerId(batch.producerId()))
return false;
Errors error = response.error;
if (error == Errors.OUT_OF_ORDER_SEQUENCE_NUMBER && !hasUnresolvedSequence(batch.topicPartition) &&
(batch.sequenceHasBeenReset() || !isNextSequence(batch.topicPartition, batch.baseSequence())))
// We should retry the OutOfOrderSequenceException if the batch is _not_ the next batch, ie. its base
// sequence isn't the lastAckedSequence + 1. However, if the first in flight batch fails fatally, we will
// adjust the sequences of the other inflight batches to account for the 'loss' of the sequence range in
// the batch which failed. In this case, an inflight batch will have a base sequence which is
// the lastAckedSequence + 1 after adjustment. When this batch fails with an OutOfOrderSequence, we want to retry it.
// To account for the latter case, we check whether the sequence has been reset since the last drain.
// If it has, we will retry it anyway.
return true;
if (error == Errors.UNKNOWN_PRODUCER_ID) {
if (response.logStartOffset == -1)
// We don't know the log start offset with this response. We should just retry the request until we get it.
// The UNKNOWN_PRODUCER_ID error code was added along with the new ProduceResponse which includes the
// logStartOffset. So the '-1' sentinel is not for backward compatibility. Instead, it is possible for
// a broker to not know the logStartOffset at when it is returning the response because the partition
// may have moved away from the broker from the time the error was initially raised to the time the
// response was being constructed. In these cases, we should just retry the request: we are guaranteed
// to eventually get a logStartOffset once things settle down.
return true;
if (batch.sequenceHasBeenReset()) {
// When the first inflight batch fails due to the truncation case, then the sequences of all the other
// in flight batches would have been restarted from the beginning. However, when those responses
// come back from the broker, they would also come with an UNKNOWN_PRODUCER_ID error. In this case, we should not
// reset the sequence numbers to the beginning.
return true;
} else if (lastAckedOffset(batch.topicPartition) < response.logStartOffset) {
// The head of the log has been removed, probably due to the retention time elapsing. In this case,
// we expect to lose the producer state. Reset the sequences of all inflight batches to be from the beginning
// and retry them.
startSequencesAtBeginning(batch.topicPartition);
return true;
}
}
return false;
}
// visible for testing
synchronized boolean isReady() {
return isTransactional() && currentState == State.READY;
}
private void transitionTo(State target) {
transitionTo(target, null);
}
private synchronized void transitionTo(State target, RuntimeException error) {
if (!currentState.isTransitionValid(currentState, target)) {
String idString = transactionalId == null ? "" : "TransactionalId " + transactionalId + ": ";
throw new KafkaException(idString + "Invalid transition attempted from state "
+ currentState.name() + " to state " + target.name());
}
if (target == State.FATAL_ERROR || target == State.ABORTABLE_ERROR) {
if (error == null)
throw new IllegalArgumentException("Cannot transition to " + target + " with an null exception");
lastError = error;
} else {
lastError = null;
}
if (lastError != null)
log.debug("Transition from state {} to error state {}", currentState, target, lastError);
else
log.debug("Transition from state {} to {}", currentState, target);
currentState = target;
}
private void ensureTransactional() {
if (!isTransactional())
throw new IllegalStateException("Transactional method invoked on a non-transactional producer.");
}
private void maybeFailWithError() {
if (hasError())
throw new KafkaException("Cannot execute transactional method because we are in an error state", lastError);
}
private boolean maybeTerminateRequestWithError(TxnRequestHandler requestHandler) {
if (hasError()) {
if (hasAbortableError() && requestHandler instanceof FindCoordinatorHandler)
// No harm letting the FindCoordinator request go through if we're expecting to abort
return false;
requestHandler.fail(lastError);
return true;
}
return false;
}
private void enqueueRequest(TxnRequestHandler requestHandler) {
log.debug("Enqueuing transactional request {}", requestHandler.requestBuilder());
pendingRequests.add(requestHandler);
}
private synchronized void lookupCoordinator(FindCoordinatorRequest.CoordinatorType type, String coordinatorKey) {
switch (type) {
case GROUP:
consumerGroupCoordinator = null;
break;
case TRANSACTION:
transactionCoordinator = null;
break;
default:
throw new IllegalStateException("Invalid coordinator type: " + type);
}
FindCoordinatorRequest.Builder builder = new FindCoordinatorRequest.Builder(type, coordinatorKey);
enqueueRequest(new FindCoordinatorHandler(builder));
}
private synchronized void completeTransaction() {
transitionTo(State.READY);
lastError = null;
transactionStarted = false;
newPartitionsInTransaction.clear();
pendingPartitionsInTransaction.clear();
partitionsInTransaction.clear();
}
private synchronized TxnRequestHandler addPartitionsToTransactionHandler() {
pendingPartitionsInTransaction.addAll(newPartitionsInTransaction);
newPartitionsInTransaction.clear();
AddPartitionsToTxnRequest.Builder builder = new AddPartitionsToTxnRequest.Builder(transactionalId,
producerIdAndEpoch.producerId, producerIdAndEpoch.epoch, new ArrayList<>(pendingPartitionsInTransaction));
return new AddPartitionsToTxnHandler(builder);
}
private TxnOffsetCommitHandler txnOffsetCommitHandler(TransactionalRequestResult result,
Map<TopicPartition, OffsetAndMetadata> offsets,
String consumerGroupId) {
for (Map.Entry<TopicPartition, OffsetAndMetadata> entry : offsets.entrySet()) {
OffsetAndMetadata offsetAndMetadata = entry.getValue();
CommittedOffset committedOffset = new CommittedOffset(offsetAndMetadata.offset(), offsetAndMetadata.metadata());
pendingTxnOffsetCommits.put(entry.getKey(), committedOffset);
}
TxnOffsetCommitRequest.Builder builder = new TxnOffsetCommitRequest.Builder(transactionalId, consumerGroupId,
producerIdAndEpoch.producerId, producerIdAndEpoch.epoch, pendingTxnOffsetCommits);
return new TxnOffsetCommitHandler(result, builder);
}
abstract class TxnRequestHandler implements RequestCompletionHandler {
protected final TransactionalRequestResult result;
private boolean isRetry = false;
TxnRequestHandler(TransactionalRequestResult result) {
this.result = result;
}
TxnRequestHandler() {
this(new TransactionalRequestResult());
}
void fatalError(RuntimeException e) {
result.setError(e);
transitionToFatalError(e);
result.done();
}
void abortableError(RuntimeException e) {
result.setError(e);
transitionToAbortableError(e);
result.done();
}
void fail(RuntimeException e) {
result.setError(e);
result.done();
}
void reenqueue() {
synchronized (TransactionManager.this) {
this.isRetry = true;
enqueueRequest(this);
}
}
long retryBackoffMs() {
return retryBackoffMs;
}
@Override
public void onComplete(ClientResponse response) {
if (response.requestHeader().correlationId() != inFlightRequestCorrelationId) {
fatalError(new RuntimeException("Detected more than one in-flight transactional request."));
} else {
clearInFlightTransactionalRequestCorrelationId();
if (response.wasDisconnected()) {
log.debug("Disconnected from {}. Will retry.", response.destination());
if (this.needsCoordinator())
lookupCoordinator(this.coordinatorType(), this.coordinatorKey());
reenqueue();
} else if (response.versionMismatch() != null) {
fatalError(response.versionMismatch());
} else if (response.hasResponse()) {
log.trace("Received transactional response {} for request {}", response.responseBody(),
requestBuilder());
synchronized (TransactionManager.this) {
handleResponse(response.responseBody());
}
} else {
fatalError(new KafkaException("Could not execute transactional request for unknown reasons"));
}
}
}
boolean needsCoordinator() {
return coordinatorType() != null;
}
FindCoordinatorRequest.CoordinatorType coordinatorType() {
return FindCoordinatorRequest.CoordinatorType.TRANSACTION;
}
String coordinatorKey() {
return transactionalId;
}
void setRetry() {
this.isRetry = true;
}
boolean isRetry() {
return isRetry;
}
boolean isEndTxn() {
return false;
}
abstract AbstractRequest.Builder<?> requestBuilder();
abstract void handleResponse(AbstractResponse responseBody);
abstract Priority priority();
}
private class InitProducerIdHandler extends TxnRequestHandler {
private final InitProducerIdRequest.Builder builder;
private InitProducerIdHandler(InitProducerIdRequest.Builder builder) {
this.builder = builder;
}
@Override
InitProducerIdRequest.Builder requestBuilder() {
return builder;
}
@Override
Priority priority() {
return Priority.INIT_PRODUCER_ID;
}
@Override
public void handleResponse(AbstractResponse response) {
InitProducerIdResponse initProducerIdResponse = (InitProducerIdResponse) response;
Errors error = initProducerIdResponse.error();
if (error == Errors.NONE) {
ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(initProducerIdResponse.producerId(), initProducerIdResponse.epoch());
setProducerIdAndEpoch(producerIdAndEpoch);
transitionTo(State.READY);
lastError = null;
result.done();
} else if (error == Errors.NOT_COORDINATOR || error == Errors.COORDINATOR_NOT_AVAILABLE) {
lookupCoordinator(FindCoordinatorRequest.CoordinatorType.TRANSACTION, transactionalId);
reenqueue();
} else if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.CONCURRENT_TRANSACTIONS) {
reenqueue();
} else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED) {
fatalError(error.exception());
} else {
fatalError(new KafkaException("Unexpected error in InitProducerIdResponse; " + error.message()));
}
}
}
private class AddPartitionsToTxnHandler extends TxnRequestHandler {
private final AddPartitionsToTxnRequest.Builder builder;
private long retryBackoffMs;
private AddPartitionsToTxnHandler(AddPartitionsToTxnRequest.Builder builder) {
this.builder = builder;
this.retryBackoffMs = TransactionManager.this.retryBackoffMs;
}
@Override
AddPartitionsToTxnRequest.Builder requestBuilder() {
return builder;
}
@Override
Priority priority() {
return Priority.ADD_PARTITIONS_OR_OFFSETS;
}
@Override
public void handleResponse(AbstractResponse response) {
AddPartitionsToTxnResponse addPartitionsToTxnResponse = (AddPartitionsToTxnResponse) response;
Map<TopicPartition, Errors> errors = addPartitionsToTxnResponse.errors();
boolean hasPartitionErrors = false;
Set<String> unauthorizedTopics = new HashSet<>();
retryBackoffMs = TransactionManager.this.retryBackoffMs;
for (Map.Entry<TopicPartition, Errors> topicPartitionErrorEntry : errors.entrySet()) {
TopicPartition topicPartition = topicPartitionErrorEntry.getKey();
Errors error = topicPartitionErrorEntry.getValue();
if (error == Errors.NONE) {
continue;
} else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR) {
lookupCoordinator(FindCoordinatorRequest.CoordinatorType.TRANSACTION, transactionalId);
reenqueue();
return;
} else if (error == Errors.CONCURRENT_TRANSACTIONS) {
maybeOverrideRetryBackoffMs();
reenqueue();
return;
} else if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.UNKNOWN_TOPIC_OR_PARTITION) {
reenqueue();
return;
} else if (error == Errors.INVALID_PRODUCER_EPOCH) {
fatalError(error.exception());
return;
} else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED) {
fatalError(error.exception());
return;
} else if (error == Errors.INVALID_PRODUCER_ID_MAPPING
|| error == Errors.INVALID_TXN_STATE) {
fatalError(new KafkaException(error.exception()));
return;
} else if (error == Errors.TOPIC_AUTHORIZATION_FAILED) {
unauthorizedTopics.add(topicPartition.topic());
} else if (error == Errors.OPERATION_NOT_ATTEMPTED) {
log.debug("Did not attempt to add partition {} to transaction because other partitions in the " +
"batch had errors.", topicPartition);
hasPartitionErrors = true;
} else {
log.error("Could not add partition {} due to unexpected error {}", topicPartition, error);
hasPartitionErrors = true;
}
}
Set<TopicPartition> partitions = errors.keySet();
// Remove the partitions from the pending set regardless of the result. We use the presence
// of partitions in the pending set to know when it is not safe to send batches. However, if
// the partitions failed to be added and we enter an error state, we expect the batches to be
// aborted anyway. In this case, we must be able to continue sending the batches which are in
// retry for partitions that were successfully added.
pendingPartitionsInTransaction.removeAll(partitions);
if (!unauthorizedTopics.isEmpty()) {
abortableError(new TopicAuthorizationException(unauthorizedTopics));
} else if (hasPartitionErrors) {
abortableError(new KafkaException("Could not add partitions to transaction due to errors: " + errors));
} else {
log.debug("Successfully added partitions {} to transaction", partitions);
partitionsInTransaction.addAll(partitions);
transactionStarted = true;
result.done();
}
}
@Override
public long retryBackoffMs() {
return Math.min(TransactionManager.this.retryBackoffMs, this.retryBackoffMs);
}
private void maybeOverrideRetryBackoffMs() {
// We only want to reduce the backoff when retrying the first AddPartition which errored out due to a
// CONCURRENT_TRANSACTIONS error since this means that the previous transaction is still completing and
// we don't want to wait too long before trying to start the new one.
//
// This is only a temporary fix, the long term solution is being tracked in
// https://issues.apache.org/jira/browse/KAFKA-5482
if (partitionsInTransaction.isEmpty())
this.retryBackoffMs = ADD_PARTITIONS_RETRY_BACKOFF_MS;
}
}
private class FindCoordinatorHandler extends TxnRequestHandler {
private final FindCoordinatorRequest.Builder builder;
private FindCoordinatorHandler(FindCoordinatorRequest.Builder builder) {
this.builder = builder;
}
@Override
FindCoordinatorRequest.Builder requestBuilder() {
return builder;
}
@Override
Priority priority() {
return Priority.FIND_COORDINATOR;
}
@Override
FindCoordinatorRequest.CoordinatorType coordinatorType() {
return null;
}
@Override
String coordinatorKey() {
return null;
}
@Override
public void handleResponse(AbstractResponse response) {
FindCoordinatorResponse findCoordinatorResponse = (FindCoordinatorResponse) response;
Errors error = findCoordinatorResponse.error();
if (error == Errors.NONE) {
Node node = findCoordinatorResponse.node();
switch (builder.coordinatorType()) {
case GROUP:
consumerGroupCoordinator = node;
break;
case TRANSACTION:
transactionCoordinator = node;
}
result.done();
} else if (error == Errors.COORDINATOR_NOT_AVAILABLE) {
reenqueue();
} else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED) {
fatalError(error.exception());
} else if (findCoordinatorResponse.error() == Errors.GROUP_AUTHORIZATION_FAILED) {
abortableError(new GroupAuthorizationException(builder.coordinatorKey()));
} else {
fatalError(new KafkaException(String.format("Could not find a coordinator with type %s with key %s due to" +
"unexpected error: %s", builder.coordinatorType(), builder.coordinatorKey(),
findCoordinatorResponse.error().message())));
}
}
}
private class EndTxnHandler extends TxnRequestHandler {
private final EndTxnRequest.Builder builder;
private EndTxnHandler(EndTxnRequest.Builder builder) {
this.builder = builder;
}
@Override
EndTxnRequest.Builder requestBuilder() {
return builder;
}
@Override
Priority priority() {
return Priority.END_TXN;
}
@Override
boolean isEndTxn() {
return true;
}
@Override
public void handleResponse(AbstractResponse response) {
EndTxnResponse endTxnResponse = (EndTxnResponse) response;
Errors error = endTxnResponse.error();
if (error == Errors.NONE) {
completeTransaction();
result.done();
} else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR) {
lookupCoordinator(FindCoordinatorRequest.CoordinatorType.TRANSACTION, transactionalId);
reenqueue();
} else if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.CONCURRENT_TRANSACTIONS) {
reenqueue();
} else if (error == Errors.INVALID_PRODUCER_EPOCH) {
fatalError(error.exception());
} else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED) {
fatalError(error.exception());
} else if (error == Errors.INVALID_TXN_STATE) {
fatalError(error.exception());
} else {
fatalError(new KafkaException("Unhandled error in EndTxnResponse: " + error.message()));
}
}
}
private class AddOffsetsToTxnHandler extends TxnRequestHandler {
private final AddOffsetsToTxnRequest.Builder builder;
private final Map<TopicPartition, OffsetAndMetadata> offsets;
private AddOffsetsToTxnHandler(AddOffsetsToTxnRequest.Builder builder,
Map<TopicPartition, OffsetAndMetadata> offsets) {
this.builder = builder;
this.offsets = offsets;
}
@Override
AddOffsetsToTxnRequest.Builder requestBuilder() {
return builder;
}
@Override
Priority priority() {
return Priority.ADD_PARTITIONS_OR_OFFSETS;
}
@Override
public void handleResponse(AbstractResponse response) {
AddOffsetsToTxnResponse addOffsetsToTxnResponse = (AddOffsetsToTxnResponse) response;
Errors error = addOffsetsToTxnResponse.error();
if (error == Errors.NONE) {
log.debug("Successfully added partition for consumer group {} to transaction", builder.consumerGroupId());
// note the result is not completed until the TxnOffsetCommit returns
pendingRequests.add(txnOffsetCommitHandler(result, offsets, builder.consumerGroupId()));
transactionStarted = true;
} else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR) {
lookupCoordinator(FindCoordinatorRequest.CoordinatorType.TRANSACTION, transactionalId);
reenqueue();
} else if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.CONCURRENT_TRANSACTIONS) {
reenqueue();
} else if (error == Errors.INVALID_PRODUCER_EPOCH) {
fatalError(error.exception());
} else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED) {
fatalError(error.exception());
} else if (error == Errors.GROUP_AUTHORIZATION_FAILED) {
abortableError(new GroupAuthorizationException(builder.consumerGroupId()));
} else {
fatalError(new KafkaException("Unexpected error in AddOffsetsToTxnResponse: " + error.message()));
}
}
}
private class TxnOffsetCommitHandler extends TxnRequestHandler {
private final TxnOffsetCommitRequest.Builder builder;
private TxnOffsetCommitHandler(TransactionalRequestResult result,
TxnOffsetCommitRequest.Builder builder) {
super(result);
this.builder = builder;
}
@Override
TxnOffsetCommitRequest.Builder requestBuilder() {
return builder;
}
@Override
Priority priority() {
return Priority.ADD_PARTITIONS_OR_OFFSETS;
}
@Override
FindCoordinatorRequest.CoordinatorType coordinatorType() {
return FindCoordinatorRequest.CoordinatorType.GROUP;
}
@Override
String coordinatorKey() {
return builder.consumerGroupId();
}
@Override
public void handleResponse(AbstractResponse response) {
TxnOffsetCommitResponse txnOffsetCommitResponse = (TxnOffsetCommitResponse) response;
boolean coordinatorReloaded = false;
boolean hadFailure = false;
Map<TopicPartition, Errors> errors = txnOffsetCommitResponse.errors();
for (Map.Entry<TopicPartition, Errors> entry : errors.entrySet()) {
TopicPartition topicPartition = entry.getKey();
Errors error = entry.getValue();
if (error == Errors.NONE) {
log.debug("Successfully added offsets {} from consumer group {} to transaction.",
builder.offsets(), builder.consumerGroupId());
pendingTxnOffsetCommits.remove(topicPartition);
} else if (error == Errors.COORDINATOR_NOT_AVAILABLE
|| error == Errors.NOT_COORDINATOR
|| error == Errors.REQUEST_TIMED_OUT) {
hadFailure = true;
if (!coordinatorReloaded) {
coordinatorReloaded = true;
lookupCoordinator(FindCoordinatorRequest.CoordinatorType.GROUP, builder.consumerGroupId());
}
} else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION) {
hadFailure = true;
} else if (error == Errors.GROUP_AUTHORIZATION_FAILED) {
abortableError(new GroupAuthorizationException(builder.consumerGroupId()));
return;
} else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED
|| error == Errors.INVALID_PRODUCER_EPOCH
|| error == Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT) {
fatalError(error.exception());
return;
} else {
fatalError(new KafkaException("Unexpected error in TxnOffsetCommitResponse: " + error.message()));
return;
}
}
if (!hadFailure || !result.isSuccessful()) {
// all attempted partitions were either successful, or there was a fatal failure.
// either way, we are not retrying, so complete the request.
result.done();
return;
}
// retry the commits which failed with a retriable error.
if (!pendingTxnOffsetCommits.isEmpty())
reenqueue();
}
}
}
| {'content_hash': 'f527ee3f777b3abd8c3829a81ef0bb61', 'timestamp': '', 'source': 'github', 'line_count': 1306, 'max_line_length': 174, 'avg_line_length': 45.16615620214395, 'alnum_prop': 0.6537881228067202, 'repo_name': 'richhaase/kafka', 'id': 'b242d5a65a639424125993c106968962ad907580', 'size': '59785', 'binary': False, 'copies': '4', 'ref': 'refs/heads/trunk', 'path': 'clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '26635'}, {'name': 'Dockerfile', 'bytes': '6592'}, {'name': 'HTML', 'bytes': '3739'}, {'name': 'Java', 'bytes': '14025660'}, {'name': 'Python', 'bytes': '737819'}, {'name': 'Scala', 'bytes': '5421222'}, {'name': 'Shell', 'bytes': '92931'}, {'name': 'XSLT', 'bytes': '7116'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
# Copyright 2015 WSO2 Inc. (http://wso2.org)
#
# 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.
-->
<Analytics>
<Name>http_event_script</Name>
<Script>
create temporary table RequestsPerMinute using CarbonJDBC options (dataSource "WSO2AS_MONITORING_DB", tableName "TEMP_REQUESTS_SUMMARY_PER_MINUTE");
create temporary table ServiceRequestData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_CARBON_MSS_HTTPMONITORING");
CREATE TEMPORARY TABLE MSS_REQUESTS_SUMMARY_PER_MINUTE_FINAL USING CarbonAnalytics OPTIONS (tableName "MSS_REQUESTS_SUMMARY_PER_MINUTE",
schema "service_class string,
application_type string,
server_addess string,
avg_request_count int,
avg_response_time int,
http_success_count int,
http_error_count int,
session_count int,
time string",
primaryKeys "service_class,time"
);
insert into table MSS_REQUESTS_SUMMARY_PER_MINUTE_FINAL select service_class,
meta_application_type as application_type,
meta_server_addess as server_addess,
count(request_uri) as avg_request_count,
avg(response_time) as avg_response_time,
sum(if(http_status_code<400, 1, 0)) as http_success_count,
sum(if(http_status_code>=400, 1, 0)) as http_error_count,
0 as session_count,
substring(cast(meta_timestamp/1000 as timestamp),0,16) as time from ServiceRequestData group by meta_application_type, meta_server_addess, service_class, substring(cast(meta_timestamp/1000 as timestamp),0,16);
INSERT OVERWRITE TABLE RequestsPerMinute SELECT service_class as webappName, application_type as webappType, server_addess as serverName, avg_request_count as averageRequestCount, avg_response_time as averageResponseTime, http_success_count as httpSuccessCount, http_error_count as httpErrorCount, session_count as sessionCount, time as TIME FROM MSS_REQUESTS_SUMMARY_PER_MINUTE_FINAL;
create temporary table HttpStatus using CarbonJDBC options (dataSource "WSO2AS_MONITORING_DB", tableName "TEMP_HTTP_STATUS");
CREATE TEMPORARY TABLE MSS_HTTP_STATUS_FINAL USING CarbonAnalytics OPTIONS (tableName "MSS_HTTP_STATUS",
schema "service_class string,
server_addess string,
avg_request_count int,
http_status_code int,
time string",
primaryKeys "service_class,time"
);
insert into table MSS_HTTP_STATUS_FINAL select service_class,
meta_server_addess as server_addess,
count(request_uri) as avg_request_count,
http_status_code,
substring(cast(meta_timestamp/1000 as timestamp),0,16) as time from ServiceRequestData group by meta_server_addess, service_class, http_status_code, substring(cast(meta_timestamp/1000 as timestamp),0,16);
INSERT OVERWRITE TABLE HttpStatus SELECT service_class as webappName, server_addess as serverName, avg_request_count as averageRequestCount, http_status_code as responseHttpStatusCode, time as TIME FROM MSS_HTTP_STATUS_FINAL;
create temporary table WebappContext using CarbonJDBC options (dataSource "WSO2AS_MONITORING_DB", tableName "TEMP_WEBAPP_CONTEXT");
CREATE TEMPORARY TABLE MSS_SERVICE_CONTEXT_FINAL USING CarbonAnalytics OPTIONS (tableName "MSS_SERVICE_CONTEXT",
schema "service_class string,
server_addess string,
avg_request_count int,
service_context string,
time string",
primaryKeys "service_class,time"
);
insert into table MSS_SERVICE_CONTEXT_FINAL select service_class,
meta_server_addess as server_addess,
count(request_uri) as avg_request_count,
service_context,
substring(cast(meta_timestamp/1000 as timestamp),0,16) as time from ServiceRequestData group by meta_server_addess, service_class, service_context, substring(cast(meta_timestamp/1000 as timestamp),0,16);
INSERT OVERWRITE TABLE WebappContext SELECT service_class as webappName, server_addess as serverName, avg_request_count as averageRequestCount, service_context as webappcontext, time as TIME FROM MSS_SERVICE_CONTEXT_FINAL;
</Script>
<CronExpression>0 0/5 * 1/1 * ? *</CronExpression>
</Analytics>
| {'content_hash': '4e6fb30b94be7694c98177db99124904', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 385, 'avg_line_length': 47.242105263157896, 'alnum_prop': 0.7731729055258467, 'repo_name': 'samiyuru/product-mss', 'id': 'b1f8dfd6946ff8efa6b9009228453a90b1c60921', 'size': '4488', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'analytics/mss_http_monitoring_capp_source/mss_http_monitoring_capp/spark_script_1.0.0/http_event_script.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '372614'}, {'name': 'Shell', 'bytes': '3072'}]} |
typedef unsigned long cycles_t;
static inline cycles_t get_cycles (void)
{
return 0;
}
#define CLOCK_TICK_RATE (HZ)
#endif
| {'content_hash': '9b5bf64377de763b15736ba0e61a926b', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 40, 'avg_line_length': 12.7, 'alnum_prop': 0.7165354330708661, 'repo_name': 'manuelmagix/kernel_bq_piccolo', 'id': '0f4ada08f7488d6f37448fdc15c71d818db93a91', 'size': '170', 'binary': False, 'copies': '14357', 'ref': 'refs/heads/master', 'path': 'arch/um/include/asm/timex.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '4528'}, {'name': 'Assembly', 'bytes': '9818830'}, {'name': 'Awk', 'bytes': '18681'}, {'name': 'C', 'bytes': '494602785'}, {'name': 'C++', 'bytes': '4382330'}, {'name': 'Clojure', 'bytes': '480'}, {'name': 'Groff', 'bytes': '22012'}, {'name': 'Lex', 'bytes': '40805'}, {'name': 'Makefile', 'bytes': '1373737'}, {'name': 'Objective-C', 'bytes': '1218215'}, {'name': 'Perl', 'bytes': '406175'}, {'name': 'Python', 'bytes': '37296'}, {'name': 'Scilab', 'bytes': '21433'}, {'name': 'Shell', 'bytes': '137667'}, {'name': 'SourcePawn', 'bytes': '4687'}, {'name': 'UnrealScript', 'bytes': '6113'}, {'name': 'Yacc', 'bytes': '83091'}]} |
<!--
Copyright 2013,2014 IBM Corp.
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.
-->
<script type="text/x-red" data-template-name="e-mail">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-envelope"></i> To</label>
<input type="text" id="node-input-name" placeholder="[email protected]">
</div>
<!-- <div class="form-row">
<label for="node-input-pin"><i class="fa fa-asterisk"></i> Service</label>
<select type="text" id="node-input-pin" style="width: 150px;">
<option value="-" disabled> </option>
<option value="DynectEmail">DynectEmail</option>
<option value="Gmail">Gmail</option>
<option value="hot.ee">hot.ee</option>
<option value="Hotmail">Hotmail</option>
<option value="iCloud">iCloud</option>
<option value="mail.ee">mail.ee</option>
<option value="Mail.Ru">Mail.Ru</option>
<option value="Mailgun">Mailgun</option>
<option value="Mailjet">Mailjet</option>
<option value="Mandrill">Mandrill</option>
<option value="Postmark">Postmark</option>
<option value="QQ">QQ</option>
<option value="QQex">QQex</option>
<option value="SendGrid">SendGrid</option>
<option value="SendCloud">SendCloud</option>
<option value="SES">SES</option>
<option value="Yahoo">Yahoo</option>
<option value="yandex">yandex</option>
<option value="Zoho">Zoho</option>
</select>
</div> -->
<div class="form-row">
<label for="node-input-server"><i class="fa fa-globe"></i> Server</label>
<input type="text" id="node-input-server" placeholder="smtp.gmail.com">
</div>
<div class="form-row">
<label for="node-input-port"><i class="fa fa-random"></i> Port</label>
<input type="text" id="node-input-port" placeholder="465">
</div>
<div class="form-row">
<label for="node-input-userid"><i class="fa fa-user"></i> Userid</label>
<input type="text" id="node-input-userid">
</div>
<div class="form-row">
<label for="node-input-password"><i class="fa fa-lock"></i> Password</label>
<input type="password" id="node-input-password">
</div>
<br/>
<div class="form-row">
<label for="node-input-dname"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-dname" placeholder="Name">
</div>
<div class="form-tips" id="node-tip"><b>Note:</b> Copied credentials from global emailkeys.js file.</div>
</script>
<script type="text/x-red" data-help-name="e-mail">
<p>Sends the <b>msg.payload</b> as an email, with a subject of <b>msg.topic</b>.</p>
<p>The default message recipient can be configured in the node, if it is left
blank it should be set using the <b>msg.to</b> property of the incoming message.</p>
<p>The payload can be html format.</p>
<p>If the payload is a binary buffer then it will be converted to an attachment.
The filename should be set using <b>msg.filename</b>. Optionally <b>msg.description</b> can be added for the body text.</p>
<p>Alternatively you may provide <b>msg.attachments</b> which should contain an array of one or
more attachments in <a href="https://www.npmjs.com/package/nodemailer#attachments" target="_new">nodemailer</a> format.</p>
</script>
<script type="text/javascript">
(function() {
RED.nodes.registerType('e-mail',{
category: 'social-output',
color:"#c7e9c0",
defaults: {
server: {value:"smtp.gmail.com",required:true},
port: {value:"465",required:true},
name: {value:"",required:true},
dname: {value:""}
},
credentials: {
userid: {type:"text"},
password: {type: "password"},
global: { type:"boolean"}
},
inputs:1,
outputs:0,
icon: "envelope.png",
align: "right",
label: function() {
return this.dname||this.name||"email";
},
labelStyle: function() {
return (this.dname||!this.topic)?"node_label_italic":"";
},
oneditprepare: function() {
if (this.credentials.global) {
$('#node-tip').show();
} else {
$('#node-tip').hide();
};
}
});
})();
</script>
<script type="text/x-red" data-template-name="e-mail in">
<div class="form-row node-input-repeat">
<label for="node-input-repeat"><i class="fa fa-repeat"></i> Check Repeat (S)</label>
<input type="text" id="node-input-repeat" placeholder="300">
</div>
<div class="form-row">
<label for="node-input-server"><i class="fa fa-globe"></i> Server</label>
<input type="text" id="node-input-server" placeholder="imap.gmail.com">
</div>
<div class="form-row">
<label for="node-input-port"><i class="fa fa-random"></i> Port</label>
<input type="text" id="node-input-port" placeholder="993">
</div>
<div class="form-row">
<label for="node-input-userid"><i class="fa fa-user"></i> Userid</label>
<input type="text" id="node-input-userid">
</div>
<div class="form-row">
<label for="node-config-input-password"><i class="fa fa-lock"></i> Password</label>
<input type="password" id="node-input-password">
</div>
<br/>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name">
</div>
<div class="form-tips" id="node-tip"><b>Note:</b> Copied credentials from global emailkeys.js file.</div>
<div id="node-input-tip" class="form-tips">Tip: <b>ONLY</b> retrieves the single most recent email.</div>
</script>
<script type="text/x-red" data-help-name="e-mail in">
<p>Repeatedly gets a <b>single email</b> from an IMAP server and forwards on as a msg if not already seen.</p>
<p>The subject is loaded into <b>msg.topic</b> and <b>msg.payload</b> is the plain text body.
If there is text/html then that is returned in <b>msg.html</b>. <b>msg.from</b> and <b>msg.date</b> are also set if you need them.</p>
<p>Uses the imap module.</p>
<p><b>Note:</b> this node <i>only</i> gets the most recent single email from the inbox, so set the repeat (polling) time appropriately.</p>
</script>
<script type="text/javascript">
(function() {
RED.nodes.registerType('e-mail in',{
category: 'social-input',
color:"#c7e9c0",
defaults: {
repeat: {value:"300",required:true},
server: {value:"imap.gmail.com",required:true},
port: {value:"993",required:true},
name: {value:""}
},
credentials: {
userid: {type:"text"},
password: {type: "password"},
global: { type:"boolean"}
},
inputs:0,
outputs:1,
icon: "envelope.png",
label: function() {
return this.name||"email";
},
labelStyle: function() {
return (this.name||!this.topic)?"node_label_italic":"";
},
oneditprepare: function() {
if (this.credentials.global) {
$('#node-tip').show();
} else {
$('#node-tip').hide();
};
}
});
})();
</script>
| {'content_hash': 'a7071375c8688d3052c01565a58c1297', 'timestamp': '', 'source': 'github', 'line_count': 193, 'max_line_length': 143, 'avg_line_length': 41.4559585492228, 'alnum_prop': 0.5843019622547182, 'repo_name': 'FlowDesigner/node-red', 'id': 'cc660ee406a8038a34c1a7d103c178b31835594b', 'size': '8001', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'nodes/core/social/61-email.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '49720'}, {'name': 'HTML', 'bytes': '258264'}, {'name': 'JavaScript', 'bytes': '1054947'}, {'name': 'Python', 'bytes': '6338'}, {'name': 'Shell', 'bytes': '629'}]} |
const nsIAppShellService = Components.interfaces.nsIAppShellService;
const nsISupports = Components.interfaces.nsISupports;
const nsICategoryManager = Components.interfaces.nsICategoryManager;
const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
const nsICommandLine = Components.interfaces.nsICommandLine;
const nsICommandLineHandler = Components.interfaces.nsICommandLineHandler;
const nsIFactory = Components.interfaces.nsIFactory;
const nsIModule = Components.interfaces.nsIModule;
const nsIWindowWatcher = Components.interfaces.nsIWindowWatcher;
// CHANGEME: to the chrome URI of your extension or application
const CHROME_URI = "chrome://nixos-gui/content/myviewer.xul";
// CHANGEME: change the contract id, CID, and category to be unique
// to your application.
const clh_contractID = "@mozilla.org/commandlinehandler/general-startup;1?type=myapp";
// use uuidgen to generate a unique ID
const clh_CID = Components.ID("{2991c315-b871-42cd-b33f-bfee4fcbf682}");
// category names are sorted alphabetically. Typical command-line handlers use a
// category that begins with the letter "m".
const clh_category = "m-myapp";
/**
* Utility functions
*/
/**
* Opens a chrome window.
* @param aChromeURISpec a string specifying the URI of the window to open.
* @param aArgument an argument to pass to the window (may be null)
*/
function openWindow(aChromeURISpec, aArgument)
{
var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
getService(Components.interfaces.nsIWindowWatcher);
ww.openWindow(null, aChromeURISpec, "_blank",
"chrome,menubar,toolbar,status,resizable,dialog=no",
aArgument);
}
/**
* The XPCOM component that implements nsICommandLineHandler.
* It also implements nsIFactory to serve as its own singleton factory.
*/
const myAppHandler = {
/* nsISupports */
QueryInterface : function clh_QI(iid)
{
if (iid.equals(nsICommandLineHandler) ||
iid.equals(nsIFactory) ||
iid.equals(nsISupports))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
},
/* nsICommandLineHandler */
handle : function clh_handle(cmdLine)
{
openWindow(CHROME_URI, cmdLine);
cmdLine.preventDefault = true;
},
// CHANGEME: change the help info as appropriate, but
// follow the guidelines in nsICommandLineHandler.idl
// specifically, flag descriptions should start at
// character 24, and lines should be wrapped at
// 72 characters with embedded newlines,
// and finally, the string should end with a newline
helpInfo : " <filename> Open the file in the viewer\n",
/* nsIFactory */
createInstance : function clh_CI(outer, iid)
{
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return this.QueryInterface(iid);
},
lockFactory : function clh_lock(lock)
{
/* no-op */
}
};
/**
* The XPCOM glue that implements nsIModule
*/
const myAppHandlerModule = {
/* nsISupports */
QueryInterface : function mod_QI(iid)
{
if (iid.equals(nsIModule) ||
iid.equals(nsISupports))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
},
/* nsIModule */
getClassObject : function mod_gch(compMgr, cid, iid)
{
if (cid.equals(clh_CID))
return myAppHandler.QueryInterface(iid);
throw Components.results.NS_ERROR_NOT_REGISTERED;
},
registerSelf : function mod_regself(compMgr, fileSpec, location, type)
{
compMgr.QueryInterface(nsIComponentRegistrar);
compMgr.registerFactoryLocation(clh_CID,
"myAppHandler",
clh_contractID,
fileSpec,
location,
type);
var catMan = Components.classes["@mozilla.org/categorymanager;1"].
getService(nsICategoryManager);
catMan.addCategoryEntry("command-line-handler",
clh_category,
clh_contractID, true, true);
},
unregisterSelf : function mod_unreg(compMgr, location, type)
{
compMgr.QueryInterface(nsIComponentRegistrar);
compMgr.unregisterFactoryLocation(clh_CID, location);
var catMan = Components.classes["@mozilla.org/categorymanager;1"].
getService(nsICategoryManager);
catMan.deleteCategoryEntry("command-line-handler", clh_category);
},
canUnload : function (compMgr)
{
return true;
}
};
/* The NSGetModule function is the magic entry point that XPCOM uses to find what XPCOM objects
* this component provides
*/
function NSGetModule(comMgr, fileSpec)
{
return myAppHandlerModule;
}
| {'content_hash': '1f9a78378c7e861935d58a377ea796fb', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 95, 'avg_line_length': 30.928571428571427, 'alnum_prop': 0.684232626495906, 'repo_name': 'rbvermaa/nixos-svn', 'id': 'fd85422d6c85da2fcbae47fec0439114a50599f4', 'size': '4763', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'gui/components/clh.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2619'}, {'name': 'JavaScript', 'bytes': '25593'}, {'name': 'Perl', 'bytes': '27672'}, {'name': 'Shell', 'bytes': '77057'}]} |
using UnityEngine;
using System.Collections.Generic;
namespace DataMesh.AR.UI
{
[System.Serializable]
public class BlockMenuData
{
public string name;
public BlockPanelData rootPanel = null;
}
[System.Serializable]
public class BlockPanelData
{
//public GameObject[] buttonPrefabs = new GameObject[4];
public List<BlockButtonData> buttons = new List<BlockButtonData>();
}
[System.Serializable]
public class BlockButtonData
{
public string buttonId;
public string buttonName;
public BlockButtonColor buttonColor = new BlockButtonColor();
public string buttonPic;
public bool canClick = true;
public BlockPanelData subPanel = null;
}
[System.Serializable]
public class BlockButtonColor
{
public float r = 3f / 255f;
public float g = 169f / 255f;
public float b = 244f / 255f;
public float a = 1f;
public static bool operator ==(BlockButtonColor lhs, BlockButtonColor rhs)
{
return (lhs.r == rhs.r) && (lhs.g == rhs.g) && (lhs.b == rhs.b) && (lhs.a == rhs.a);
}
public static bool operator !=(BlockButtonColor lhs, BlockButtonColor rhs)
{
return (lhs.r != rhs.r) || (lhs.g != rhs.g) || (lhs.b != rhs.b) || (lhs.a != rhs.a);
}
public override bool Equals(object other)
{
BlockButtonColor c = (BlockButtonColor)other;
return (this == c);
}
public override int GetHashCode()
{
return BlockButtonColor.ColorToInt(this);
}
public static implicit operator BlockButtonColor(Color c)
{
BlockButtonColor rs = new BlockButtonColor();
rs.r = c.r;
rs.g = c.g;
rs.b = c.b;
rs.a = c.a;
return rs;
}
public static implicit operator Color(BlockButtonColor c)
{
Color rs = new Color(c.r, c.g, c.b, c.a);
return rs;
}
static public int ColorToInt(BlockButtonColor c)
{
int retVal = 0;
retVal |= Mathf.RoundToInt(c.r * 255f) << 24;
retVal |= Mathf.RoundToInt(c.g * 255f) << 16;
retVal |= Mathf.RoundToInt(c.b * 255f) << 8;
retVal |= Mathf.RoundToInt(c.a * 255f);
return retVal;
}
}
} | {'content_hash': 'f64c207f94499f14104581c1d8bdf316', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 96, 'avg_line_length': 26.170212765957448, 'alnum_prop': 0.5479674796747968, 'repo_name': 'DataMesh-OpenSource/SolarSystemExplorer', 'id': '1a3ed215949f563c9837ced82bb7dab1b0ff644b', 'size': '2460', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Assets/DataMesh/ARModule/UI/Scripts/Data/BlockMenuData.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '1050339'}, {'name': 'GLSL', 'bytes': '7653'}, {'name': 'HLSL', 'bytes': '8841'}, {'name': 'ShaderLab', 'bytes': '108075'}]} |
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1alpha1
import (
resourcev1alpha1 "k8s.io/api/resource/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
managedfields "k8s.io/apimachinery/pkg/util/managedfields"
internal "k8s.io/client-go/applyconfigurations/internal"
v1 "k8s.io/client-go/applyconfigurations/meta/v1"
)
// ResourceClaimApplyConfiguration represents an declarative configuration of the ResourceClaim type for use
// with apply.
type ResourceClaimApplyConfiguration struct {
v1.TypeMetaApplyConfiguration `json:",inline"`
*v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"`
Spec *ResourceClaimSpecApplyConfiguration `json:"spec,omitempty"`
Status *ResourceClaimStatusApplyConfiguration `json:"status,omitempty"`
}
// ResourceClaim constructs an declarative configuration of the ResourceClaim type for use with
// apply.
func ResourceClaim(name, namespace string) *ResourceClaimApplyConfiguration {
b := &ResourceClaimApplyConfiguration{}
b.WithName(name)
b.WithNamespace(namespace)
b.WithKind("ResourceClaim")
b.WithAPIVersion("resource.k8s.io/v1alpha1")
return b
}
// ExtractResourceClaim extracts the applied configuration owned by fieldManager from
// resourceClaim. If no managedFields are found in resourceClaim for fieldManager, a
// ResourceClaimApplyConfiguration is returned with only the Name, Namespace (if applicable),
// APIVersion and Kind populated. It is possible that no managed fields were found for because other
// field managers have taken ownership of all the fields previously owned by fieldManager, or because
// the fieldManager never owned fields any fields.
// resourceClaim must be a unmodified ResourceClaim API object that was retrieved from the Kubernetes API.
// ExtractResourceClaim provides a way to perform a extract/modify-in-place/apply workflow.
// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously
// applied if another fieldManager has updated or force applied any of the previously applied fields.
// Experimental!
func ExtractResourceClaim(resourceClaim *resourcev1alpha1.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error) {
return extractResourceClaim(resourceClaim, fieldManager, "")
}
// ExtractResourceClaimStatus is the same as ExtractResourceClaim except
// that it extracts the status subresource applied configuration.
// Experimental!
func ExtractResourceClaimStatus(resourceClaim *resourcev1alpha1.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error) {
return extractResourceClaim(resourceClaim, fieldManager, "status")
}
func extractResourceClaim(resourceClaim *resourcev1alpha1.ResourceClaim, fieldManager string, subresource string) (*ResourceClaimApplyConfiguration, error) {
b := &ResourceClaimApplyConfiguration{}
err := managedfields.ExtractInto(resourceClaim, internal.Parser().Type("io.k8s.api.resource.v1alpha1.ResourceClaim"), fieldManager, b, subresource)
if err != nil {
return nil, err
}
b.WithName(resourceClaim.Name)
b.WithNamespace(resourceClaim.Namespace)
b.WithKind("ResourceClaim")
b.WithAPIVersion("resource.k8s.io/v1alpha1")
return b, nil
}
// WithKind sets the Kind field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Kind field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithKind(value string) *ResourceClaimApplyConfiguration {
b.Kind = &value
return b
}
// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the APIVersion field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithAPIVersion(value string) *ResourceClaimApplyConfiguration {
b.APIVersion = &value
return b
}
// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithName(value string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Name = &value
return b
}
// WithGenerateName sets the GenerateName field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the GenerateName field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithGenerateName(value string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.GenerateName = &value
return b
}
// WithNamespace sets the Namespace field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Namespace field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithNamespace(value string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Namespace = &value
return b
}
// WithUID sets the UID field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the UID field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithUID(value types.UID) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.UID = &value
return b
}
// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ResourceVersion field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithResourceVersion(value string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.ResourceVersion = &value
return b
}
// WithGeneration sets the Generation field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Generation field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithGeneration(value int64) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Generation = &value
return b
}
// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the CreationTimestamp field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.CreationTimestamp = &value
return b
}
// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DeletionTimestamp field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.DeletionTimestamp = &value
return b
}
// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.DeletionGracePeriodSeconds = &value
return b
}
// WithLabels puts the entries into the Labels field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, the entries provided by each call will be put on the Labels field,
// overwriting an existing map entries in Labels field with the same key.
func (b *ResourceClaimApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
if b.Labels == nil && len(entries) > 0 {
b.Labels = make(map[string]string, len(entries))
}
for k, v := range entries {
b.Labels[k] = v
}
return b
}
// WithAnnotations puts the entries into the Annotations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, the entries provided by each call will be put on the Annotations field,
// overwriting an existing map entries in Annotations field with the same key.
func (b *ResourceClaimApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
if b.Annotations == nil && len(entries) > 0 {
b.Annotations = make(map[string]string, len(entries))
}
for k, v := range entries {
b.Annotations[k] = v
}
return b
}
// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the OwnerReferences field.
func (b *ResourceClaimApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
for i := range values {
if values[i] == nil {
panic("nil value passed to WithOwnerReferences")
}
b.OwnerReferences = append(b.OwnerReferences, *values[i])
}
return b
}
// WithFinalizers adds the given value to the Finalizers field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Finalizers field.
func (b *ResourceClaimApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
for i := range values {
b.Finalizers = append(b.Finalizers, values[i])
}
return b
}
func (b *ResourceClaimApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {
if b.ObjectMetaApplyConfiguration == nil {
b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{}
}
}
// WithSpec sets the Spec field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Spec field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimApplyConfiguration {
b.Spec = value
return b
}
// WithStatus sets the Status field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Status field is set to the value of the last call.
func (b *ResourceClaimApplyConfiguration) WithStatus(value *ResourceClaimStatusApplyConfiguration) *ResourceClaimApplyConfiguration {
b.Status = value
return b
}
| {'content_hash': '568aed3f8fc0417d3fa51d8e4f39f823', 'timestamp': '', 'source': 'github', 'line_count': 244, 'max_line_length': 157, 'avg_line_length': 49.89754098360656, 'alnum_prop': 0.7982751540041068, 'repo_name': 'warmchang/kubernetes', 'id': 'f94811a9b1078709020bb6063a17df5ab5524a32', 'size': '12739', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha1/resourceclaim.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '833'}, {'name': 'C', 'bytes': '3902'}, {'name': 'Dockerfile', 'bytes': '47376'}, {'name': 'Go', 'bytes': '64172023'}, {'name': 'HTML', 'bytes': '106'}, {'name': 'Makefile', 'bytes': '64194'}, {'name': 'PowerShell', 'bytes': '144474'}, {'name': 'Python', 'bytes': '23655'}, {'name': 'Shell', 'bytes': '1818574'}, {'name': 'sed', 'bytes': '1262'}]} |
{-# OPTIONS_GHC -cpp #-}
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE MultiParamTypeClasses, OverlappingInstances, UndecidableInstances, FunctionalDependencies, NoMonomorphismRestriction #-}
module ExceptM (module ExceptM, HasExcept(..)) where
import MT
import Control_Monad_Fix
import Control.Monad (liftM)
{- use newtype to avoid conflicts with class instances! -}
newtype ExceptM l r = ExceptM {removeExcept :: Either l r}
{- not used
removeExcept :: ExceptM x a -> Either x a
removeExcept = id
mapEither f g = either (Left . f) (Right . g)
seqEither x = either (fmap Left) (fmap Right) x
fromEither f (Right x)= x
fromEither f (Left x) = f x
unLeft (Left x) = x
unLeft _ = error "unLeft"
-}
unRight (ExceptM (Right x)) = x
unRight _ = error "unRight"
instance Functor (ExceptM x) where
fmap = liftM
instance Monad (ExceptM x) where
return = ExceptM . Right
ExceptM (Right x) >>= f = f x
ExceptM (Left x) >>= f = ExceptM (Left x)
ExceptM (Right _) >> m = m
ExceptM (Left x) >> m = ExceptM (Left x)
instance HasExcept (ExceptM x) x where
raise = ExceptM . Left
handle h (ExceptM (Left x)) = h x
handle h (ExceptM (Right x)) = ExceptM (Right x)
instance MonadFix (ExceptM x) where
mfix f = let a = f (unRight a) in a
instance HasBaseMonad (ExceptM x) (ExceptM x) where
inBase = id
| {'content_hash': 'd05ef5aaef97cfb31c9aa33d42f5d17d', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 133, 'avg_line_length': 27.054545454545455, 'alnum_prop': 0.6081989247311828, 'repo_name': 'mpickering/HaRe', 'id': '27d2b3baa4770d5cb088e852adfbef8d35da238c', 'size': '1488', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'old/tools/base/lib/Monads/ExceptM.hs', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '7740'}, {'name': 'Emacs Lisp', 'bytes': '118236'}, {'name': 'Groff', 'bytes': '107'}, {'name': 'HTML', 'bytes': '231247'}, {'name': 'Haskell', 'bytes': '6457762'}, {'name': 'Isabelle', 'bytes': '5201'}, {'name': 'LLVM', 'bytes': '385'}, {'name': 'Makefile', 'bytes': '17891'}, {'name': 'Objective-C++', 'bytes': '382'}, {'name': 'Ruby', 'bytes': '4178'}, {'name': 'Shell', 'bytes': '66440'}, {'name': 'TeX', 'bytes': '329808'}, {'name': 'VimL', 'bytes': '35502'}, {'name': 'Yacc', 'bytes': '120163'}]} |
"use strict";
// import {Handler,application} from "./webkool";
var _webkool = require("./webkool");
var Handler = _webkool.Handler;
class _MySQL {
constructor() {
this._connection = null;
this._mysql = null;
this._credentials = null;
}
_connect() {
if (!this._connection) {
this._mysql = require('mysql');
this._connection = this._mysql.createConnection(this._credentials);
this._onDisconnect();
this._connection.connect();
}
}
_onDisconnect() {
var MySQL = this;
this._connection.on('error', function (error) {
if (!error.fatal) {
return;
}
if (error.code !== 'PROTOCOL_CONNECTION_LOST') {
throw error;
}
_webkool.application.warn('Re-connecting lost connection: ' + error.stack);
MySQL._connection = MySQL._mysql.createConnection(this._connection.config);
MySQL._onDisconnect();
MySQL._connection.connect();
});
}
close() {
if (this._connection) {
this._connection.end(function(err) {
});
}
}
connect(host, user, database, password, charset, ssl) {
this._credentials = {
host: host,
user: user,
database: database,
password: password,
timezone: '+00:00',
charset: charset,
ssl: ssl
};
}
escape(name) {
if (!this._connection) this._connect();
return this._connection.escape(name);
}
query(...args) {
if (!this._connection) this._connect();
return this._connection.query(...args);
}
}
var MySQL = exports.MySQL = new _MySQL();
class SQLHandler extends Handler {
doPrepare(data) {
var result = {};
if (!data || !('statement' in data)) {
throw new Error('SQLHandler "' + this.url + '" has no statement.');
}
else {
result.statement = data.statement;
}
if (!data.values) {
result.values = [];
}
else {
result.values = data.values;
}
return result;
}
doResult(result) {
return result;
}
doRequest() {
try {
var handler = this, behavior = handler.behavior;
if (behavior && 'onConstruct' in behavior) {
var data = handler.doPrepare(behavior.onConstruct(handler, handler.model, handler.query));
MySQL._connect();
MySQL.query(data.statement, data.values, function (error, result) {
try {
if (!error)
handler.result = handler.doResult(result);
else
handler.doError(new Error('SQL "' + data.statement + '" ' + error));
handler.synchronize();
}
catch (e) {
_webkool.application.reportError(handler, e);
}
});
}
else
throw new Error('SQLHandler "' + handler.url + '" has no statement.');
}
catch (e) {
_webkool.application.reportError(handler, e);
}
}
}
exports.SQLHandler = SQLHandler;
class SQLCountHandler extends SQLHandler {
doResult(result) {
if (result.length) {
var row = result[0];
for (var field in row) {
return parseInt(row[field], 10);
}
}
}
}
exports.SQLCountHandler = SQLCountHandler;
class SQLDeleteHandler extends SQLHandler {
doPrepare(data) {
var property = [], values = [], query = this.query, result = {};
if (!('table' in data)) {
throw new Error('SQLDeleteHandler "' + this.url + '" has no table name.');
}
for (var i = 0; i < data.columns.length; i++) {
var column = data.columns[i];
if (query.hasOwnProperty(column)) {
property.push("`" + column + "` = ?");
values.push(query[column]);
}
}
if (property.length) {
result.statement = "DELETE FROM " + data.table + " WHERE " + property.join(" AND ");
result.values = values;
if (query.extra) {
result.statement += " " + query.extra;
}
}
else if (query.all) {
result.statement = "DELETE FROM " + data.table;
result.values = undefined;
if (query.extra) {
result.statement += " " + query.extra;
}
}
else {
throw new Error('SQLDeleteHandler "' + this.url + '" has where clause.');
}
return result;
}
}
exports.SQLDeleteHandler = SQLDeleteHandler;
class SQLFirstHandler extends SQLHandler {
doResult(result) {
if (result.length)
return result[0];
}
}
exports.SQLFirstHandler = SQLFirstHandler;
class SQLInsertHandler extends SQLHandler {
doPrepare(data) {
var property = [], items = [], values = [], query = this.query, result = {};
if (!('table' in data)) {
throw new Error('SQLInsertHandler "' + this.url + '" has no table name.');
}
if (!('columns' in data)) {
throw new Error('SQLInsertHandler "' + this.url + '" has no columns.');
}
for (var i = 0; i < data.columns.length; i++) {
var column = data.columns[i];
if (query.hasOwnProperty(column)) {
property.push("`" + column + "`");
items.push('?');
values.push(query[column]);
}
}
result.statement = "INSERT INTO " + data.table + " (" + property.join(", ") + ") VALUES (" + items.join(", ") + ")";
result.values = values;
if (query.extra) {
result.statement += " " + query.extra;
}
return result;
}
doResult(result) {
return result.insertId;
}
}
exports.SQLInsertHandler = SQLInsertHandler;
class SQLInsertIgnoreHandler extends SQLHandler {
doPrepare(data) {
var property = [], items = [], values = [], query = this.query, result = {};
if (!('table' in data)) {
throw new Error('SQLInsertHandler "' + this.url + '" has no table name.');
}
if (!('columns' in data)) {
throw new Error('SQLInsertHandler "' + this.url + '" has no columns.');
}
for (var i = 0; i < data.columns.length; i++) {
var column = data.columns[i];
if (query.hasOwnProperty(column)) {
property.push("`" + column + "`");
items.push('?');
values.push(query[column]);
}
}
result.statement = "INSERT IGNORE INTO " + data.table + " (" + property.join(", ") + ") VALUES (" + items.join(", ") + ")";
result.values = values;
if (query.extra) {
result.statement += " " + query.extra;
}
return result;
}
doResult(result) {
return result.insertId;
}
}
exports.SQLInsertIgnoreHandler = SQLInsertIgnoreHandler;
class SQLSelectHandler extends SQLHandler {
doPrepare(data) {
var property = [], values = [], query = this.query, result = {};
if (!('table' in data)) {
throw new Error('SQLSelectHandler "' + this.url + '" has no table name.');
}
if (!('columns' in data)) {
throw new Error('SQLSelectHandler "' + this.url + '" has no columns.');
}
for (var i = 0; i < data.columns.length; i++) {
var column = data.columns[i];
if (query.hasOwnProperty(column)) {
property.push("`" + column + "` = ?");
values.push(query[column]);
}
}
if (property.length) {
result.statement = "SELECT * FROM " + data.table + " WHERE " + property.join(" AND ");
result.values = values;
}
else {
result.statement = "SELECT * FROM " + data.table;
}
if (query.extra) {
result.statement += " " + query.extra;
}
return result;
}
}
exports.SQLSelectHandler = SQLSelectHandler;
class SQLSelectFirstHandler extends SQLSelectHandler {
doResult(result) {
if (result.length)
return result[0];
}
}
exports.SQLSelectFirstHandler = SQLSelectFirstHandler;
class SQLSelectCountHandler extends SQLCountHandler {
doPrepare(data) {
var property = [], values = [], query = this.query, result = {};
if (!('table' in data)) {
throw new Error('SQLSelectHandler "' + this.url + '" has no table name.');
}
if (!('columns' in data)) {
throw new Error('SQLSelectHandler "' + this.url + '" has no columns.');
}
for (var i = 0; i < data.columns.length; i++) {
var column = data.columns[i];
if (query.hasOwnProperty(column)) {
property.push("`" + column + "` = ?");
values.push(query[column]);
}
}
if (property.length) {
result.statement = "SELECT COUNT(*) FROM " + data.table + " WHERE " + property.join(" AND ");
result.values = values;
}
else {
result.statement = "SELECT COUNT(*) FROM " + data.table;
}
if (query.extra) {
result.statement += " " + query.extra;
}
return result;
}
}
exports.SQLSelectCountHandler = SQLSelectCountHandler;
class SQLUpdateHandler extends SQLHandler {
doPrepare(data) {
var property = [], values = [], query = this.query, result = {};
if (!('table' in data)) {
throw new Error('SQLUpdateHandler "' + this.url + '" has no table name.');
}
if (!('columns' in data)) {
throw new Error('SQLUpdateHandler "' + this.url + '" has no columns.');
}
if (!('id' in query)) {
throw new Error('SQLUpdateHandler "' + this.url + '" has no id.');
}
for (var i = 0; i < data.columns.length; i++) {
var column = data.columns[i];
if (column != 'id' && query.hasOwnProperty(column)) {
property.push("`" + column + "` = ?");
values.push(query[column]);
}
}
values.push(query.id);
result.statement = "UPDATE " + data.table + " SET " + property.join(", ") + " WHERE id = ?";
result.values = values;
if (query.extra) {
result.statement += " " + query.extra;
}
return result;
}
}
exports.SQLUpdateHandler = SQLUpdateHandler;
| {'content_hash': 'da630e07b2643cff5ac7dddd645d001d', 'timestamp': '', 'source': 'github', 'line_count': 354, 'max_line_length': 125, 'avg_line_length': 25.087570621468927, 'alnum_prop': 0.6131066321360207, 'repo_name': 'webkool/webkooljs', 'id': '7fbbaf0d40e601b3337a9741684860994793f2ca', 'size': '9572', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MySQLHandler.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '54624'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>projective-geometry: 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.13.0 / projective-geometry - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
projective-geometry
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-07-22 08:40:03 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-22 08:40:03 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/projective-geometry"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ProjectiveGeometry"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: geometry"
"keyword: projective"
"keyword: Fano"
"keyword: homogeneous coordinates model"
"keyword: flat"
"keyword: rank"
"keyword: Desargues"
"keyword: Moulton"
"category: Mathematics/Geometry/General"
"date: 2009-10"
]
authors: [
"Nicolas Magaud <[email protected]>"
"Julien Narboux <[email protected]>"
"Pascal Schreck <[email protected]>"
]
bug-reports: "https://github.com/coq-contribs/projective-geometry/issues"
dev-repo: "git+https://github.com/coq-contribs/projective-geometry.git"
synopsis: "Projective Geometry"
description: """
This contributions contains elements of formalization of projective geometry.
In the plane:
Two axiom systems are shown equivalent. We prove some results about the
decidability of the the incidence and equality predicates. The classic
notion of duality between points and lines is formalized thanks to a
functor. The notion of 'flat' is defined and flats are characterized.
Fano's plane, the smallest projective plane is defined. We show that Fano's plane is desarguesian.
In the space:
We prove Desargues' theorem."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/projective-geometry/archive/v8.10.0.tar.gz"
checksum: "md5=d6807a8a37bfd7aee33f251ef1709f54"
}
</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-projective-geometry.8.10.0 coq.8.13.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0).
The following dependencies couldn't be met:
- coq-projective-geometry -> coq < 8.11~ -> 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-projective-geometry.8.10.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': '1c352351370bce48ce045275bf7f4956', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 159, 'avg_line_length': 42.12234042553192, 'alnum_prop': 0.5729258744791009, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '8d9c6e7aa5257f5b8e21607abe82cbcae6f81417', 'size': '7944', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.08.1-2.0.5/released/8.13.0/projective-geometry/8.10.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
from hbmqtt.errors import HBMQTTException
from hbmqtt.mqtt.packet import (
CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, PUBCOMP, SUBSCRIBE,
SUBACK, UNSUBSCRIBE, UNSUBACK, PINGREQ, PINGRESP, DISCONNECT,
MQTTFixedHeader)
from hbmqtt.mqtt.connect import ConnectPacket
from hbmqtt.mqtt.connack import ConnackPacket
from hbmqtt.mqtt.disconnect import DisconnectPacket
from hbmqtt.mqtt.pingreq import PingReqPacket
from hbmqtt.mqtt.pingresp import PingRespPacket
from hbmqtt.mqtt.publish import PublishPacket
from hbmqtt.mqtt.puback import PubackPacket
from hbmqtt.mqtt.pubrec import PubrecPacket
from hbmqtt.mqtt.pubrel import PubrelPacket
from hbmqtt.mqtt.pubcomp import PubcompPacket
from hbmqtt.mqtt.subscribe import SubscribePacket
from hbmqtt.mqtt.suback import SubackPacket
from hbmqtt.mqtt.unsubscribe import UnsubscribePacket
from hbmqtt.mqtt.unsuback import UnsubackPacket
packet_dict = {
CONNECT: ConnectPacket,
CONNACK: ConnackPacket,
PUBLISH: PublishPacket,
PUBACK: PubackPacket,
PUBREC: PubrecPacket,
PUBREL: PubrelPacket,
PUBCOMP: PubcompPacket,
SUBSCRIBE: SubscribePacket,
SUBACK: SubackPacket,
UNSUBSCRIBE: UnsubscribePacket,
UNSUBACK: UnsubackPacket,
PINGREQ: PingReqPacket,
PINGRESP: PingRespPacket,
DISCONNECT: DisconnectPacket
}
def packet_class(fixed_header: MQTTFixedHeader):
try:
cls = packet_dict[fixed_header.packet_type]
return cls
except KeyError:
raise HBMQTTException("Unexpected packet Type '%s'" % fixed_header.packet_type)
| {'content_hash': '2ae4b833cec2a36f500f10e301a46520', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 87, 'avg_line_length': 35.43181818181818, 'alnum_prop': 0.7844772289929441, 'repo_name': 'beerfactory/hbmqtt', 'id': '8c80c382b57985206d1408066b6097448e9ea733', 'size': '1649', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'hbmqtt/mqtt/__init__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '305024'}]} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="4dp">
<TextView
android:id="@+id/tv_where"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:maxLines="1"
android:padding="4dp"
android:textSize="12sp"/>
<TextView
android:id="@+id/tv_whom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="3"
android:ellipsize="end"
android:maxLines="1"
android:padding="4dp"
android:textSize="12sp"/>
<ImageButton
android:id="@+id/button_delete_buffer_recipient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="4dp"
android:background="@null"
android:src="@mipmap/ic_action_navigation_close"/>
</LinearLayout> | {'content_hash': 'a5eec61fdc81bdebc2d39918e9db3ad8', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 72, 'avg_line_length': 33.473684210526315, 'alnum_prop': 0.6147798742138365, 'repo_name': 'DOIS/ecampus-client-android', 'id': 'fe27f76ddbfb7f0296c66aae56f06fd95495852e', 'size': '1272', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/recyclerview_buffer_recipient_item.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '204091'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is part of the Sylius package.
(c) Paweł Jędrzejewski
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
-->
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<defaults public="true" />
<service id="sylius.oauth.user_provider" class="Sylius\Bundle\CoreBundle\OAuth\UserProvider" lazy="true">
<argument type="string" id="%sylius.model.shop_user.class%" />
<argument type="service" id="sylius.factory.customer" />
<argument type="service" id="sylius.factory.shop_user" />
<argument type="service" id="sylius.repository.shop_user" />
<argument type="service" id="sylius.factory.oauth_user" />
<argument type="service" id="sylius.repository.oauth_user" />
<argument type="service" id="sylius.manager.shop_user" />
<argument type="service" id="sylius.canonicalizer" />
<argument type="service" id="sylius.repository.customer" />
</service>
</services>
</container>
| {'content_hash': 'acdd49c34cab02ec16af5604da58bf39', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 228, 'avg_line_length': 44.166666666666664, 'alnum_prop': 0.660377358490566, 'repo_name': 'bitbager/Sylius', 'id': 'f096364e9156f8ce9c18452116aa4c4349b22694', 'size': '1327', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'src/Sylius/Bundle/CoreBundle/Resources/config/services/integrations/hwi_oauth.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3198'}, {'name': 'Gherkin', 'bytes': '885682'}, {'name': 'HTML', 'bytes': '311906'}, {'name': 'JavaScript', 'bytes': '78578'}, {'name': 'PHP', 'bytes': '6257080'}, {'name': 'Shell', 'bytes': '28833'}]} |
require 'spec_helper'
require 'helpers/app_creator'
require 'helpers/fakable_pathman_tester'
require 'helpers/act_like_rails2311'
describe 'sync' do
before :all do
FakablePathManTester.switch_on 'spec/fixtures/rails2311/fully-loaded/'
ActLikeRails2311.switch_on
end
before :each do
AppCreator.create
end
after :all do
AppCreator.reset
FakablePathManTester.switch_off
ActLikeRails2311.switch_off
end
it "replaces all images" do
local = Asset.all
Asset.sync
remote = RemoteAsset.all
remote.count.should == 8
local.each{|l| remote.should include(l) }
end
end | {'content_hash': 'f66ea4ec6f4c0e66d8145d24155cf1c9', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 74, 'avg_line_length': 19.967741935483872, 'alnum_prop': 0.7221324717285945, 'repo_name': 'SynApps/trackman', 'id': 'bc561c6c53b5a80286f6d674506b7bfc16a5bd93', 'size': '619', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/rails2311/first_push_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '2367'}, {'name': 'Ruby', 'bytes': '160715'}]} |
#import <UIKit/UIKit.h>
@interface BlobTableViewController : UITableViewController
@property (nonatomic, weak) NSString *containerName;
@end
| {'content_hash': '95ccf8ff1ed6f09e9c2661855ca8dd86', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 58, 'avg_line_length': 21.142857142857142, 'alnum_prop': 0.777027027027027, 'repo_name': 'Azure-Samples/iOS-MobileServices-Storage', 'id': 'b7051d26fcfb26bb7270497cf059c952d24b79dc', 'size': '718', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'source/end/StorageDemo/StorageDemo/BlobTableViewController.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '14463'}, {'name': 'JavaScript', 'bytes': '7933'}, {'name': 'Objective-C', 'bytes': '143565'}]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.