code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package flex2.linker;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import flex2.compiler.common.FramesConfiguration.FrameInfo;
/**
* This interface is used to restrict consumers of
* flex2.compiler.common.Configuration to linker specific options.
*
* @author Clement Wong
*/
public interface LinkerConfiguration
{
// C: If you add a method here, please add it to
// flex2.tools.oem.internal.LinkerConfiguration as well.
int backgroundColor();
/**
* Generate SWFs for debugging.
*/
boolean debug();
boolean verboseStacktraces();
boolean optimize();
boolean useNetwork();
boolean lazyInit();
boolean scriptLimitsSet();
int getScriptTimeLimit();
int getScriptRecursionLimit();
int getFrameRate();
String getMetadata();
/**
* The password to include in debuggable swfs.
*/
String debugPassword();
/**
* SWF width
*/
String width();
int defaultWidth();
/**
* SWF height
*/
String height();
int defaultHeight();
/**
* SWF height percentage
*/
String heightPercent();
/**
* SWF width percentage
*/
String widthPercent();
/**
* browser page title
*/
String pageTitle();
/**
* @param mainDefinition the name of the app class to instantiate
*/
void setMainDefinition( String mainDefinition );
String getMainDefinition();
/**
* @return the name of the root SWF class
*/
String getRootClassName();
/**
* @param rootClassName the name of the root SWF class
*/
void setRootClassName( String rootClassName );
/**
* @return list of frame classes
*/
List<FrameInfo> getFrameList();
/**
* @return set of configured external symbols
*/
Set<String> getExterns();
/**
* @return set of symbols to always include
*/
Set<String> getIncludes();
/**
* @return set of symbols that were not resolved (includes any referenced externs)
*/
Set<String> getUnresolved();
/**
* @return name of compile report file, null if none
*/
String getLinkReportFileName();
boolean generateLinkReport();
/**
* @return name of size report file, null if none
*/
String getSizeReportFileName();
boolean generateSizeReport();
/**
* @return name of resource bundle list file, null if none
*/
String getRBListFileName();
boolean generateRBList();
/**
* @return set of resource bundles for resource bundle list
*/
SortedSet<String> getResourceBundles();
/**
* @return the as3 metadata to keep
*/
String[] getMetadataToKeep();
/**
* @return true if the digest should be computed, false otherwise.
*/
boolean getComputeDigest();
String getCompatibilityVersionString();
int getCompatibilityVersion();
String getMinimumSupportedVersionString();
int getMinimumSupportedVersion();
/**
* @return The major version of the player targeted by this application.
* The returned value will be greater to or equal to 9.
*/
int getTargetPlayerMajorVersion();
/**
* @return The minor version of the player targeted by this application.
* The returned value will be greater to or equal to 0.
*/
int getTargetPlayerMinorVersion();
/**
* @return The revision of the player targeted by this application.
* The returned value will be greater to or equal to 0.
*/
int getTargetPlayerRevision();
/**
* @return The version of the generated SWF file.
*/
int getSwfVersion();
boolean getUseGpu();
boolean getUseDirectBlit();
/**
*
* @return true if only inheritance
*/
boolean getIncludeInheritanceDependenciesOnly();
boolean getAdvancedTelemetry();
}
| greg-dove/flex-falcon | flex-compiler-oem/src/main/java/flex2/linker/LinkerConfiguration.java | Java | apache-2.0 | 4,562 |
import logging
import os
import random
import luigi.hadoop
import luigi.hdfs
logger = logging.getLogger('luigi-interface')
def fix_paths(job):
"""Coerce input arguments to use temporary files when used for output.
Return a list of temporary file pairs (tmpfile, destination path) and
a list of arguments. Converts each HdfsTarget to a string for the
path."""
tmp_files = []
args = []
for x in job.args():
if isinstance(x, luigi.hdfs.HdfsTarget): # input/output
if x.exists() or not job.atomic_output(): # input
args.append(x.path)
else: # output
x_path_no_slash = x.path[:-1] if x.path[-1] == '/' else x.path
y = luigi.hdfs.HdfsTarget(x_path_no_slash + '-luigi-tmp-%09d' % random.randrange(0, 1e10))
tmp_files.append((y, x_path_no_slash))
logger.info("Using temp path: {0} for path {1}".format(y.path, x.path))
args.append(y.path)
else:
args.append(str(x))
return (tmp_files, args)
class HadoopJarJobRunner(luigi.hadoop.JobRunner):
"""JobRunner for `hadoop jar` commands. Used to run a HadoopJarJobTask"""
def __init__(self):
pass
def run_job(self, job):
# TODO(jcrobak): libjars, files, etc. Can refactor out of
# hadoop.HadoopJobRunner
if not job.jar() or not os.path.exists(job.jar()):
logger.error("Can't find jar: {0}, full path {1}".format(job.jar(),
os.path.abspath(job.jar())))
raise Exception("job jar does not exist")
arglist = [luigi.hdfs.load_hadoop_cmd(), 'jar', job.jar()]
if job.main():
arglist.append(job.main())
jobconfs = job.jobconfs()
for jc in jobconfs:
arglist += ['-D' + jc]
(tmp_files, job_args) = fix_paths(job)
arglist += job_args
luigi.hadoop.run_and_track_hadoop_job(arglist)
for a, b in tmp_files:
a.move(b)
class HadoopJarJobTask(luigi.hadoop.BaseHadoopJobTask):
"""A job task for `hadoop jar` commands that define a jar and (optional)
main method"""
def jar(self):
"""Path to the jar for this Hadoop Job"""
return None
def main(self):
"""optional main method for this Hadoop Job"""
return None
def job_runner(self):
# We recommend that you define a subclass, override this method and set up your own config
return HadoopJarJobRunner()
def atomic_output(self):
"""If True, then rewrite output arguments to be temp locations and
atomically move them into place after the job finishes"""
return True
def args(self):
"""returns an array of args to pass to the job (after hadoop jar <jar> <main>)."""
return []
| mortardata/luigi | luigi/hadoop_jar.py | Python | apache-2.0 | 2,852 |
package com.aloeapps.common.repository;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.aloeapps.common.bean.User;
public interface UserRepository extends
PagingAndSortingRepository<User, String> {
public List<User> findAll();
public User findByUsername(String username);
}
| pedrazamiguez/aloe-startup-project | src/main/java/com/aloeapps/common/repository/UserRepository.java | Java | apache-2.0 | 344 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.ocm.manager.uuid;
import java.util.ArrayList;
import java.util.Collection;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase;
import org.apache.jackrabbit.ocm.manager.ObjectContentManager;
import org.apache.jackrabbit.ocm.testmodel.uuid.A;
import org.apache.jackrabbit.ocm.testmodel.uuid.B;
import org.apache.jackrabbit.ocm.testmodel.uuid.B2;
import org.apache.jackrabbit.ocm.testmodel.uuid.Descendant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test on UUID & references
*
* @author <a href="mailto:christophe.lombart@sword-technologies.com">Christophe Lombart</a>
*/
public class DigesterUuidTest extends DigesterRepositoryTestBase
{
private final static Logger log = LoggerFactory.getLogger(DigesterUuidTest.class);
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(DigesterUuidTest.class);
}
/**
*
* Map the jcr uuid into a String attribute
*
*/
public void testUuid()
{
try
{
ObjectContentManager ocm = getObjectContentManager();
// --------------------------------------------------------------------------------
// Create and store an object A in the repository
// --------------------------------------------------------------------------------
A a = new A();
a.setPath("/test");
a.setStringData("testdata");
ocm.insert(a);
String uuidA = a.getUuid();
assertNotNull("uuid is null", uuidA);
ocm.save();
// --------------------------------------------------------------------------------
// Get the object
// --------------------------------------------------------------------------------
a = (A) ocm.getObject( "/test");
assertNotNull("a is null", a);
uuidA = a.getUuid();
assertNotNull("uuid is null", uuidA);
log.info("UUID : " + uuidA);
// --------------------------------------------------------------------------------
// Update the object
// --------------------------------------------------------------------------------
a.setStringData("testdata2");
ocm.update(a);
ocm.save();
// --------------------------------------------------------------------------------
// Get the object
// --------------------------------------------------------------------------------
a = (A) ocm.getObject("/test");
assertNotNull("a is null", a);
assertTrue("The uuid has been modified", uuidA.equals(a.getUuid()));
// --------------------------------------------------------------------------------
// Get the object with the uuid
// --------------------------------------------------------------------------------
a = (A) ocm.getObjectByUuid(uuidA);
assertNotNull("a is null", a);
assertTrue("Invalid object found with the uuid ", "testdata2".equals(a.getStringData()));
// --------------------------------------------------------------------------------
// Get the object with an invalid uuid
// --------------------------------------------------------------------------------
try
{
a = (A) ocm.getObjectByUuid("1234");
fail("Exception not throw");
}
catch(Exception e)
{
//Throws an exception due to an invalid uuid
log.info("Invalid uuid : " + e);
}
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception occurs during the unit test : " + e);
}
}
/**
*
* Map a Reference into a String attribute.
* Object B has an attribute containing the object A uuid.
*
*/
public void testFieldReference()
{
try
{
ObjectContentManager ocm = getObjectContentManager();
// --------------------------------------------------------------------------------
// Create and store an object A in the repository
// --------------------------------------------------------------------------------
A a = new A();
a.setPath("/test");
a.setStringData("testdata");
ocm.insert(a);
ocm.save();
// --------------------------------------------------------------------------------
// Get the object
// --------------------------------------------------------------------------------
a = (A) ocm.getObject( "/test");
assertNotNull("a is null", a);
String uuidA = a.getUuid();
assertNotNull("uuid is null", uuidA);
log.info("UUID : " + uuidA);
// --------------------------------------------------------------------------------
// Create and store an object B in the repository which has a reference to A
// --------------------------------------------------------------------------------
B b = new B();
b.setReference2A(uuidA);
b.setPath("/testB");
ocm.insert(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve the object B with an invalid reference
// --------------------------------------------------------------------------------
b = (B) ocm.getObject("/testB");
assertNotNull("b is null", b);
assertTrue("Invalid uuid property", b.getReference2A().equals(uuidA));
// --------------------------------------------------------------------------------
// Update the object B with an invalid reference
// --------------------------------------------------------------------------------
b.setReference2A("1245");
try
{
ocm.update(b);
fail("Exception not throw");
}
catch(Exception e)
{
//Throws an exception due to an invalid uuid
log.info("Invalid uuid : " + e);
}
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception occurs during the unit test : " + e);
}
}
/**
*
* Map a Reference into a bean attribute.
* Object B has an attribute containing the object A.
* The jcr node matching to the object B contains a reference (the jcr node matching to the object B).
*
*/
public void testBeanReference()
{
try
{
ObjectContentManager ocm = getObjectContentManager();
// --------------------------------------------------------------------------------
// Create and store an object A in the repository
// --------------------------------------------------------------------------------
A a = new A();
a.setPath("/test");
a.setStringData("testdata");
ocm.insert(a);
ocm.save();
// --------------------------------------------------------------------------------
// Get the object a
// --------------------------------------------------------------------------------
a = (A) ocm.getObject( "/test");
assertNotNull("a is null", a);
String uuidA = a.getUuid();
assertNotNull("uuid is null", uuidA);
log.info("UUID : " + uuidA);
// --------------------------------------------------------------------------------
// Create and store an object B in the repository which has a reference to A
// --------------------------------------------------------------------------------
B2 b = new B2();
b.setA(a);
b.setPath("/testB2");
ocm.insert(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve object B
// --------------------------------------------------------------------------------
b = (B2) ocm.getObject("/testB2");
a = b.getA();
assertNotNull("a is null", a);
assertTrue("Invalid object a", a.getStringData().equals("testdata"));
assertTrue("Invalid uuid property", a.getUuid().equals(uuidA));
// --------------------------------------------------------------------------------
// Update object B with an null value
// --------------------------------------------------------------------------------
b.setA(null);
ocm.update(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve object B
// --------------------------------------------------------------------------------
b = (B2) ocm.getObject("/testB2");
a = b.getA();
assertNull("a is not null", a);
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception occurs during the unit test : " + e);
}
}
/**
* Map a list of uuid into a collection of String
* The list is defined in a jcr property (Referece type / multi values)
*
*/
public void testCollectionOfUuid()
{
try
{
ObjectContentManager ocm = getObjectContentManager();
// --------------------------------------------------------------------------------
// Create and store an object A in the repository
// --------------------------------------------------------------------------------
A a1 = new A();
a1.setPath("/a1");
a1.setStringData("testdata1");
ocm.insert(a1);
A a2 = new A();
a2.setPath("/a2");
a2.setStringData("testdata2");
ocm.insert(a2);
ocm.save();
// --------------------------------------------------------------------------------
// Get the objects
// --------------------------------------------------------------------------------
a1 = (A) ocm.getObject( "/a1");
assertNotNull("a1 is null", a1);
a2 = (A) ocm.getObject( "/a2");
assertNotNull("a2 is null", a2);
ArrayList references = new ArrayList();
references.add(a1.getUuid());
references.add(a2.getUuid());
// --------------------------------------------------------------------------------
// Create and store an object B in the repository which has a collection of A
// --------------------------------------------------------------------------------
B b = new B();
b.setPath("/testB");
b.setMultiReferences(references);
ocm.insert(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve object B
// --------------------------------------------------------------------------------
b = (B) ocm.getObject("/testB");
Collection allref = b.getMultiReferences();
assertNotNull("collection is null", allref);
assertTrue("Invalid number of items in the collection", allref.size() == 2);
// --------------------------------------------------------------------------------
// Update object B with invalid uuid
// --------------------------------------------------------------------------------
allref.add("12345");
b.setMultiReferences(allref);
try
{
ocm.update(b);
fail("Exception not throw");
}
catch(Exception e)
{
//Throws an exception due to an invalid uuid
log.info("Invalid uuid value in the collection : " + e);
}
// --------------------------------------------------------------------------------
// Update object B with an null value
// --------------------------------------------------------------------------------
b.setMultiReferences(null);
ocm.update(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve object B
// --------------------------------------------------------------------------------
b = (B) ocm.getObject("/testB");
assertNull("a is not null", b.getMultiReferences());
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception occurs during the unit test : " + e);
}
}
/**
* Map a list of uuid into a collection
* The list is defined in a jcr property (multi values)
*
*/
public void testCollectionOfBeanWithUuid()
{
try
{
ObjectContentManager ocm = getObjectContentManager();
// --------------------------------------------------------------------------------
// Create and store an object A in the repository
// --------------------------------------------------------------------------------
A a1 = new A();
a1.setPath("/a1");
a1.setStringData("testdata1");
ocm.insert(a1);
A a2 = new A();
a2.setPath("/a2");
a2.setStringData("testdata2");
ocm.insert(a2);
ocm.save();
// --------------------------------------------------------------------------------
// Get the objects
// --------------------------------------------------------------------------------
a1 = (A) ocm.getObject( "/a1");
assertNotNull("a1 is null", a1);
a2 = (A) ocm.getObject( "/a2");
assertNotNull("a2 is null", a2);
ArrayList references = new ArrayList();
references.add(a1);
references.add(a2);
// --------------------------------------------------------------------------------
// Create and store an object B in the repository which has a collection of A
// --------------------------------------------------------------------------------
B2 b = new B2();
b.setPath("/testB2");
b.setMultiReferences(references);
ocm.insert(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve object B
// --------------------------------------------------------------------------------
b = (B2) ocm.getObject("/testB2");
Collection allref = b.getMultiReferences();
assertNotNull("collection is null", allref);
assertTrue("Invalid number of items in the collection", allref.size() == 2);
this.contains(allref, "/a1" , A.class);
this.contains(allref, "/a2" , A.class);
// --------------------------------------------------------------------------------
// Update object B with an null value
// --------------------------------------------------------------------------------
b.setMultiReferences(null);
ocm.update(b);
ocm.save();
// --------------------------------------------------------------------------------
// Retrieve object B
// --------------------------------------------------------------------------------
b = (B2) ocm.getObject("/testB2");
assertNull("a is not null", b.getMultiReferences());
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception occurs during the unit test : " + e);
}
}
/**
* Test on uuid field defined in an ancestor class
*
*/
public void testDescendantAncestor()
{
try
{
ObjectContentManager ocm = getObjectContentManager();
// --------------------------------------------------------------------------------
// Create and store an object A in the repository
// --------------------------------------------------------------------------------
Descendant a = new Descendant();
a.setPath("/descendant");
a.setStringData("testdata");
ocm.insert(a);
ocm.save();
// --------------------------------------------------------------------------------
// Get the object
// --------------------------------------------------------------------------------
a = (Descendant) ocm.getObject( "/descendant");
assertNotNull("a is null", a);
String uuidA = a.getUuid();
assertNotNull("uuid is null", uuidA);
log.info("UUID : " + uuidA);
// --------------------------------------------------------------------------------
// Update the object
// --------------------------------------------------------------------------------
a.setStringData("testdata2");
ocm.update(a);
ocm.save();
// --------------------------------------------------------------------------------
// Get the object
// --------------------------------------------------------------------------------
a = (Descendant) ocm.getObject("/descendant");
assertNotNull("a is null", a);
assertTrue("The uuid has been modified", uuidA.equals(a.getUuid()));
// --------------------------------------------------------------------------------
// Get the object with the uuid
// --------------------------------------------------------------------------------
a = (Descendant) ocm.getObjectByUuid(uuidA);
assertNotNull("a is null", a);
assertTrue("Invalid object found with the uuid ", "testdata2".equals(a.getStringData()));
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception occurs during the unit test : " + e);
}
}
} | apache/jackrabbit-ocm | src/test/java/org/apache/jackrabbit/ocm/manager/uuid/DigesterUuidTest.java | Java | apache-2.0 | 19,903 |
#
# Copyright 2008-2010 Amazon.com, Inc. or its affiliates. All Rights Reserved.
require 'openssl'
require 'base64'
require 'time'
module Amazon
module Coral
# Performs AWS V2 signatures on QueryStringMap objects.
class V2SignatureHelper
def initialize(aws_access_key_id, aws_secret_key)
@aws_access_key_id = aws_access_key_id.to_s
@aws_secret_key = aws_secret_key.to_s
end
def sign(args)
signT(Time.now.iso8601, args)
end
def signT(time, args)
query_string_map = args[:query_string_map]
add_fields(query_string_map, time)
query_string_map['Signature'] = compute_signature(canonicalize(args))
end
def canonicalize(args)
query_string_map = args[:query_string_map]
uri = args[:uri]
verb = args[:verb]
host = args[:host].downcase
# exclude any existing Signature parameter from the canonical string
sorted = sort(query_string_map.reject { |k, v| k == 'Signature' })
canonical = "#{verb}\n#{host}\n#{uri}\n"
isFirst = true
sorted.each { |v|
if(isFirst) then
isFirst = false
else
canonical << '&'
end
canonical << UrlEncoding.encode(v[0])
unless(v[1].nil?) then
canonical << '='
canonical << UrlEncoding.encode(v[1])
end
}
return canonical
end
def compute_signature(canonical)
digest = OpenSSL::Digest::Digest.new('sha256')
return Base64.encode64(OpenSSL::HMAC.digest(digest, @aws_secret_key, canonical)).strip
end
def add_fields(query_string_map, time)
query_string_map['AWSAccessKeyId'] = @aws_access_key_id
query_string_map['SignatureVersion'] = '2'
query_string_map['SignatureMethod'] = 'HmacSHA256'
query_string_map['Timestamp'] = time.to_s
end
def sort(hash)
hash.sort
end
end
end
end
| bizo/aws-tools | emr/elastic-mapreduce-ruby-20130708/amazon/coral/v2signaturehelper.rb | Ruby | apache-2.0 | 2,012 |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.uzaygezen.core;
import com.google.common.base.Preconditions;
/**
* @author Daniel Aioanei
*/
public class BitVectorMath {
private BitVectorMath() {}
/**
* Splits the bits from {@code bs} into {@code result} by putting the
* lowest bits at the end of {@code result} and so on until the highest bits
* are put at the beginning of {@code result}. This is similar to the big
* endian representation of numbers, only that each digit has a potentially
* different size. The bit set length must be equal to {@code
* sum(elementLengths)}.
*
* @param bs little endian bit set
* @param result output
*/
public static void split(BitVector bs, BitVector[] result) {
int sum = 0;
for (BitVector bv : result) {
sum += bv.size();
}
Preconditions.checkArgument(sum == bs.size(), "size sum does not match");
int startIndex = 0;
for (int i = result.length; --i >= 0; ) {
result[i].copyFromSection(bs, startIndex);
startIndex += result[i].size();
}
Preconditions.checkArgument(startIndex >= bs.length(), "bit length is too high");
}
}
| lossyrob/uzaygezen | uzaygezen-core/src/main/java/com/google/uzaygezen/core/BitVectorMath.java | Java | apache-2.0 | 1,730 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.search.SearchHit.NestedIdentity;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
public class NestedIdentityTests extends ESTestCase {
public static NestedIdentity createTestItem(int depth) {
String field = frequently() ? randomAlphaOfLengthBetween(1, 20) : randomRealisticUnicodeOfCodepointLengthBetween(1, 20);
int offset = randomInt(10);
NestedIdentity child = null;
if (depth > 0) {
child = createTestItem(depth - 1);
}
return new NestedIdentity(field, offset, child);
}
public void testFromXContent() throws IOException {
NestedIdentity nestedIdentity = createTestItem(randomInt(3));
XContentType xcontentType = randomFrom(XContentType.values());
XContentBuilder builder = XContentFactory.contentBuilder(xcontentType);
if (randomBoolean()) {
builder.prettyPrint();
}
builder = nestedIdentity.innerToXContent(builder, ToXContent.EMPTY_PARAMS);
try (XContentParser parser = createParser(builder)) {
NestedIdentity parsedNestedIdentity = NestedIdentity.fromXContent(parser);
assertEquals(nestedIdentity, parsedNestedIdentity);
assertNull(parser.nextToken());
}
}
public void testToXContent() throws IOException {
NestedIdentity nestedIdentity = new NestedIdentity("foo", 5, null);
XContentBuilder builder = JsonXContent.contentBuilder();
builder.prettyPrint();
builder.startObject();
nestedIdentity.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
assertEquals(
"{\n" +
" \"_nested\" : {\n" +
" \"field\" : \"foo\",\n" +
" \"offset\" : 5\n" +
" }\n" +
"}", Strings.toString(builder));
nestedIdentity = new NestedIdentity("foo", 5, new NestedIdentity("bar", 3, null));
builder = JsonXContent.contentBuilder();
builder.prettyPrint();
builder.startObject();
nestedIdentity.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
assertEquals(
"{\n" +
" \"_nested\" : {\n" +
" \"field\" : \"foo\",\n" +
" \"offset\" : 5,\n" +
" \"_nested\" : {\n" +
" \"field\" : \"bar\",\n" +
" \"offset\" : 3\n" +
" }\n" +
" }\n" +
"}", Strings.toString(builder));
}
/**
* Test equality and hashCode properties
*/
public void testEqualsAndHashcode() {
checkEqualsAndHashCode(createTestItem(randomInt(3)), NestedIdentityTests::copy, NestedIdentityTests::mutate);
}
public void testSerialization() throws IOException {
NestedIdentity nestedIdentity = createTestItem(randomInt(3));
try (BytesStreamOutput output = new BytesStreamOutput()) {
nestedIdentity.writeTo(output);
try (StreamInput in = output.bytes().streamInput()) {
NestedIdentity deserializedCopy = new NestedIdentity(in);
assertEquals(nestedIdentity, deserializedCopy);
assertEquals(nestedIdentity.hashCode(), deserializedCopy.hashCode());
assertNotSame(nestedIdentity, deserializedCopy);
}
}
}
private static NestedIdentity mutate(NestedIdentity original) {
if (original == null) {
return createTestItem(0);
}
List<Supplier<NestedIdentity>> mutations = new ArrayList<>();
int offset = original.getOffset();
NestedIdentity child = original.getChild();
String fieldName = original.getField().string();
mutations.add(() ->
new NestedIdentity(original.getField().string() + "_prefix", offset, child));
mutations.add(() -> new NestedIdentity(fieldName, offset + 1, child));
mutations.add(() -> new NestedIdentity(fieldName, offset, mutate(child)));
return randomFrom(mutations).get();
}
private static NestedIdentity copy(NestedIdentity original) {
NestedIdentity child = original.getChild();
return new NestedIdentity(original.getField().string(), original.getOffset(), child != null ? copy(child) : null);
}
}
| ern/elasticsearch | server/src/test/java/org/elasticsearch/search/NestedIdentityTests.java | Java | apache-2.0 | 5,461 |
// Copyright 2017 The Bazel 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.
package com.google.devtools.build.lib.rules.objc;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.getFirstArtifactEndingWith;
import com.google.common.base.Joiner;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.CommandAction;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.util.ScratchAttributeWriter;
import com.google.devtools.build.lib.rules.apple.AppleConfiguration.ConfigurationDistinguisher;
import com.google.devtools.build.lib.rules.cpp.CppConfiguration;
import com.google.devtools.build.lib.rules.cpp.CppLinkAction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test case for the use of the OSX crosstool. */
@RunWith(JUnit4.class)
public class AppleToolchainSelectionTest extends ObjcRuleTestCase {
@Test
public void testToolchainSelectionDefault() throws Exception {
createLibraryTargetWriter("//a:lib").write();
BuildConfiguration config = getAppleCrosstoolConfiguration();
CppConfiguration cppConfig = config.getFragment(CppConfiguration.class);
assertThat(cppConfig.getRuleProvidingCcToolchainProvider().toString())
.isEqualTo("//tools/osx/crosstool:crosstool");
assertThat(config.getCpu()).isEqualTo("darwin_x86_64");
}
@Test
public void testToolchainSelectionIosDevice() throws Exception {
useConfiguration("--apple_platform_type=ios", "--cpu=ios_armv7");
createLibraryTargetWriter("//a:lib").write();
BuildConfiguration config = getAppleCrosstoolConfiguration();
CppConfiguration cppConfig = config.getFragment(CppConfiguration.class);
assertThat(cppConfig.getRuleProvidingCcToolchainProvider().toString())
.isEqualTo("//tools/osx/crosstool:crosstool");
assertThat(config.getCpu()).isEqualTo("ios_armv7");
}
@Test
public void testToolchainSelectionCcDepDefault() throws Exception {
ScratchAttributeWriter
.fromLabelString(this, "cc_library", "//b:lib")
.setList("srcs", "b.cc")
.write();
createBinaryTargetWriter("//a:bin")
.setList("deps", "//b:lib")
.write();
Action lipoAction = actionProducingArtifact("//a:bin", "_lipobin");
String x8664Bin =
configurationBin("x86_64", ConfigurationDistinguisher.APPLEBIN_IOS) + "a/bin_bin";
Artifact binArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), x8664Bin);
CppLinkAction linkAction = (CppLinkAction) getGeneratingAction(binArtifact);
CppLinkAction ccArchiveAction =
(CppLinkAction)
getGeneratingAction(getFirstArtifactEndingWith(linkAction.getInputs(), "liblib.a"));
Artifact ccObjectFile = getFirstArtifactEndingWith(ccArchiveAction.getInputs(), ".o");
CommandAction ccCompileAction = (CommandAction) getGeneratingAction(ccObjectFile);
assertThat(ccCompileAction.getArguments()).contains("tools/osx/crosstool/iossim/wrapped_clang");
}
@Test
public void testToolchainSelectionCcDepDevice() throws Exception {
useConfiguration("--apple_platform_type=ios", "--cpu=ios_armv7");
ScratchAttributeWriter
.fromLabelString(this, "cc_library", "//b:lib")
.setList("srcs", "b.cc")
.write();
createBinaryTargetWriter("//a:bin")
.setList("deps", "//b:lib")
.write();
Action lipoAction = actionProducingArtifact("//a:bin", "_lipobin");
String armv7Bin =
configurationBin("armv7", ConfigurationDistinguisher.APPLEBIN_IOS) + "a/bin_bin";
Artifact binArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), armv7Bin);
CppLinkAction linkAction = (CppLinkAction) getGeneratingAction(binArtifact);
CppLinkAction ccArchiveAction =
(CppLinkAction)
getGeneratingAction(getFirstArtifactEndingWith(linkAction.getInputs(), "liblib.a"));
Artifact ccObjectFile = getFirstArtifactEndingWith(ccArchiveAction.getInputs(), ".o");
CommandAction ccCompileAction = (CommandAction) getGeneratingAction(ccObjectFile);
assertThat(ccCompileAction.getArguments()).contains("tools/osx/crosstool/ios/wrapped_clang");
}
@Test
public void testToolchainSelectionMultiArchIos() throws Exception {
useConfiguration("--ios_multi_cpus=armv7,arm64");
ScratchAttributeWriter
.fromLabelString(this, "cc_library", "//b:lib")
.setList("srcs", "a.cc")
.write(getAppleCrosstoolConfiguration());
ScratchAttributeWriter
.fromLabelString(this, "apple_binary", "//a:bin")
.set("platform_type", "'ios'")
.setList("deps", "//b:lib")
.write();
Action lipoAction = actionProducingArtifact("//a:bin", "_lipobin");
String armv64Bin =
configurationBin("arm64", ConfigurationDistinguisher.APPLEBIN_IOS) + "a/bin_bin";
Artifact binArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), armv64Bin);
CppLinkAction linkAction = (CppLinkAction) getGeneratingAction(binArtifact);
CppLinkAction objcLibArchiveAction = (CppLinkAction) getGeneratingAction(
getFirstArtifactEndingWith(linkAction.getInputs(), "liblib.a"));
assertThat(Joiner.on(" ").join(objcLibArchiveAction.getArguments())).contains("ios_arm64");
}
@Test
public void testToolchainSelectionMultiArchWatchos() throws Exception {
useConfiguration(
"--ios_multi_cpus=armv7,arm64",
"--watchos_cpus=armv7k");
ScratchAttributeWriter
.fromLabelString(this, "cc_library", "//b:lib")
.setList("srcs", "a.cc")
.write(getAppleCrosstoolConfiguration());
ScratchAttributeWriter
.fromLabelString(this, "apple_binary", "//a:bin")
.setList("deps", "//b:lib")
.set("platform_type", "\"watchos\"")
.write();
CommandAction linkAction = linkAction("//a:bin");
CppLinkAction objcLibCompileAction = (CppLinkAction) getGeneratingAction(
getFirstArtifactEndingWith(linkAction.getInputs(), "liblib.a"));
assertThat(Joiner.on(" ").join(objcLibCompileAction.getArguments())).contains("watchos_armv7k");
}
}
| twitter-forks/bazel | src/test/java/com/google/devtools/build/lib/rules/objc/AppleToolchainSelectionTest.java | Java | apache-2.0 | 6,822 |
package edu.harvard.iq.dataverse.externaltools;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.DataTable;
import edu.harvard.iq.dataverse.authorization.users.ApiToken;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class ExternalToolServiceBeanTest {
public ExternalToolServiceBeanTest() {
}
@Test
public void testfindAll() {
DataFile dataFile = new DataFile();
dataFile.setId(42l);
List<DataTable> dataTables = new ArrayList<DataTable>();
dataTables.add(new DataTable());
dataFile.setDataTables(dataTables);
ApiToken apiToken = new ApiToken();
apiToken.setTokenString("7196b5ce-f200-4286-8809-03ffdbc255d7");
ExternalTool.Type type = ExternalTool.Type.EXPLORE;
ExternalTool externalTool = new ExternalTool("displayName", "description", type, "http://foo.com", "{}");
ExternalToolHandler externalToolHandler4 = new ExternalToolHandler(externalTool, dataFile, apiToken);
List<ExternalTool> externalTools = new ArrayList<>();
externalTools.add(externalTool);
List<ExternalTool> availableExternalTools = ExternalToolServiceBean.findExternalToolsByFile(externalTools, dataFile);
assertEquals(availableExternalTools.size(), 1);
}
@Test
public void testParseAddExternalToolInput() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("displayName", "AwesomeTool");
job.add("description", "This tool is awesome.");
job.add("type", "explore");
job.add("toolUrl", "http://awesometool.com");
job.add("toolParameters", Json.createObjectBuilder()
.add("queryParameters", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("fileid", "{fileId}")
.build())
.add(Json.createObjectBuilder()
.add("key", "{apiToken}")
.build())
.build())
.build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
assertEquals("AwesomeTool", externalTool.getDisplayName());
DataFile dataFile = new DataFile();
dataFile.setId(42l);
ApiToken apiToken = new ApiToken();
apiToken.setTokenString("7196b5ce-f200-4286-8809-03ffdbc255d7");
ExternalToolHandler externalToolHandler = new ExternalToolHandler(externalTool, dataFile, apiToken);
String toolUrl = externalToolHandler.getToolUrlWithQueryParams();
System.out.println("result: " + toolUrl);
assertEquals("http://awesometool.com?fileid=42&key=7196b5ce-f200-4286-8809-03ffdbc255d7", toolUrl);
}
@Test
public void testParseAddExternalToolInputNoFileId() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("displayName", "AwesomeTool");
job.add("description", "This tool is awesome.");
job.add("type", "explore");
job.add("toolUrl", "http://awesometool.com");
job.add("toolParameters", Json.createObjectBuilder()
.add("queryParameters", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("key", "{apiToken}")
.build())
.build())
.build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("Required reserved word not found: {fileId}", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputNull() {
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(null);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("External tool manifest was null or empty!", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputEmptyString() {
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest("");
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("External tool manifest was null or empty!", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputUnknownReservedWord() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("displayName", "AwesomeTool");
job.add("description", "This tool is awesome.");
job.add("type", "explore");
job.add("toolUrl", "http://awesometool.com");
job.add("toolParameters", Json.createObjectBuilder()
.add("queryParameters", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("fileid", "{fileId}")
.build())
.add(Json.createObjectBuilder()
.add("key", "{apiToken}")
.build())
.add(Json.createObjectBuilder()
.add("mode", "mode1")
.build())
.build())
.build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("Unknown reserved word: mode1", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputNoDisplayName() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("description", "This tool is awesome.");
job.add("toolUrl", "http://awesometool.com");
job.add("toolParameters", Json.createObjectBuilder().build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("displayName is required.", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputNoDescription() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("displayName", "AwesomeTool");
job.add("toolUrl", "http://awesometool.com");
job.add("toolParameters", Json.createObjectBuilder().build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("description is required.", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputNoToolUrl() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("displayName", "AwesomeTool");
job.add("description", "This tool is awesome.");
job.add("type", "explore");
job.add("toolParameters", Json.createObjectBuilder().build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
assertEquals("toolUrl is required.", expectedException.getMessage());
}
@Test
public void testParseAddExternalToolInputWrongType() {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("displayName", "AwesomeTool");
job.add("description", "This tool is awesome.");
job.add("type", "noSuchType");
job.add("toolUrl", "http://awesometool.com");
job.add("toolParameters", Json.createObjectBuilder().build());
String tool = job.build().toString();
System.out.println("tool: " + tool);
Exception expectedException = null;
try {
ExternalTool externalTool = ExternalToolServiceBean.parseAddExternalToolManifest(tool);
} catch (Exception ex) {
expectedException = ex;
}
assertNotNull(expectedException);
System.out.println("exception: " + expectedException);
assertEquals("Type must be one of these values: [explore, configure].", expectedException.getMessage());
}
}
| JayanthyChengan/dataverse | src/test/java/edu/harvard/iq/dataverse/externaltools/ExternalToolServiceBeanTest.java | Java | apache-2.0 | 9,867 |
/*
Copyright (c) 2015 VMware, Inc. 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.
*/
package vapp
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"golang.org/x/net/context"
)
type power struct {
*flags.SearchFlag
On bool
Off bool
Suspend bool
Force bool
}
func init() {
cli.Register("vapp.power", &power{})
}
func (cmd *power) Register(f *flag.FlagSet) {
cmd.SearchFlag = flags.NewSearchFlag(flags.SearchVirtualApps)
f.BoolVar(&cmd.On, "on", false, "Power on")
f.BoolVar(&cmd.Off, "off", false, "Power off")
f.BoolVar(&cmd.Suspend, "suspend", false, "Power suspend")
f.BoolVar(&cmd.Force, "force", false, "Force (If force is false, the shutdown order in the vApp is executed. If force is true, all virtual machines are powered-off (regardless of shutdown order))")
}
func (cmd *power) Process() error {
opts := []bool{cmd.On, cmd.Off, cmd.Suspend}
selected := false
for _, opt := range opts {
if opt {
if selected {
return flag.ErrHelp
}
selected = opt
}
}
if !selected {
return flag.ErrHelp
}
return nil
}
func (cmd *power) Run(f *flag.FlagSet) error {
vapps, err := cmd.VirtualApps(f.Args())
if err != nil {
return err
}
for _, vapp := range vapps {
var task *object.Task
switch {
case cmd.On:
fmt.Fprintf(cmd, "Powering on %s... ", vapp.Reference())
task, err = vapp.PowerOnVApp_Task(context.TODO())
case cmd.Off:
fmt.Fprintf(cmd, "Powering off %s... ", vapp.Reference())
task, err = vapp.PowerOffVApp_Task(context.TODO(), cmd.Force)
case cmd.Suspend:
fmt.Fprintf(cmd, "Suspend %s... ", vapp.Reference())
task, err = vapp.SuspendVApp_Task(context.TODO())
}
if err != nil {
return err
}
if task != nil {
err = task.Wait(context.TODO())
}
if err == nil {
fmt.Fprintf(cmd, "OK\n")
continue
}
return err
}
return nil
}
| kristinn/govmomi | govc/vapp/power.go | GO | apache-2.0 | 2,439 |
# Copyright 2018 The TensorFlow 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import json
import os
import pickle
from absl.testing import parameterized
import numpy
import six
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.python.keras.engine import sequential
from tensorflow.python.keras.engine import training
from tensorflow.python.keras.layers import core
from tensorflow.python.keras.layers import normalization
from tensorflow.python.layers import core as non_keras_core
from tensorflow.python.module import module
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables
from tensorflow.python.training.tracking import data_structures
from tensorflow.python.training.tracking import tracking
from tensorflow.python.training.tracking import util
from tensorflow.python.util import nest
from tensorflow.python.util import serialization
class HasList(training.Model):
def __init__(self):
super(HasList, self).__init__()
self.layer_list = data_structures.List([core.Dense(3)])
self.layer_list.append(core.Dense(4))
self.layer_list.extend(
[core.Dense(5),
core.Dense(6, kernel_regularizer=math_ops.reduce_sum)])
self.layer_list += [
core.Dense(7, bias_regularizer=math_ops.reduce_sum),
core.Dense(8)
]
self.layer_list += (
data_structures.List([core.Dense(9)]) + data_structures.List(
[core.Dense(10)]))
self.layer_list.extend(
data_structures.List(
list([core.Dense(11)]) + [core.Dense(12)]))
self.layers_with_updates = data_structures.List(
(normalization.BatchNormalization(),))
def call(self, x):
aggregation = 0.
for l in self.layer_list:
x = l(x)
aggregation += math_ops.reduce_sum(x)
bn, = self.layers_with_updates
return bn(x) / aggregation
class ListTests(test.TestCase):
@test_util.run_in_graph_and_eager_modes
@test_util.run_v1_only("b/120545219")
def testTracking(self):
model = HasList()
output = model(array_ops.ones([32, 2]))
self.assertAllEqual([32, 12], output.shape)
self.assertEqual(11, len(model.layers))
self.assertEqual(10, len(model.layer_list.layers))
six.assertCountEqual(
self,
model.layers,
model.layer_list.layers + model.layers_with_updates)
for index in range(10):
self.assertEqual(3 + index, model.layer_list.layers[index].units)
self.assertEqual(2, len(model._checkpoint_dependencies))
self.assertIs(model.layer_list, model._checkpoint_dependencies[0].ref)
self.assertIs(model.layers_with_updates,
model._checkpoint_dependencies[1].ref)
self.assertEqual(
10, len(model._checkpoint_dependencies[0].ref._checkpoint_dependencies))
self.evaluate([v.initializer for v in model.variables])
self.evaluate(model.variables[0].assign([[1., 2., 3.], [4., 5., 6.]]))
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
self.evaluate(model.variables[0].assign(array_ops.zeros([2, 3])))
model.load_weights(save_path)
self.assertAllEqual([[1., 2., 3.], [4., 5., 6.]],
self.evaluate(model.variables[0]))
v = variables.Variable(1.)
model.var_list = [v]
self.assertIn(v, model.variables)
self.assertIn(v, model.trainable_variables)
self.assertNotIn(v, model.non_trainable_variables)
self.assertIn(model.layer_list[0].trainable_weights[0],
model.trainable_weights)
def testSubModelTracking(self):
model = training.Model()
model.v = variables.Variable(1.)
self.assertIn(model.v, model.trainable_weights)
model2 = training.Model()
model2.m = [model]
self.assertIn(model.v, model2.trainable_weights)
def testSubSequentialTracking(self):
class _Subclassed(training.Model):
def __init__(self, wrapped):
super(_Subclassed, self).__init__()
self._wrapped = wrapped
def call(self, x):
return self._wrapped(x)
model = sequential.Sequential()
layer = core.Dense(1)
model.add(layer)
model2 = _Subclassed(model)
model2(array_ops.ones([1, 2]))
model2.m = [model]
self.assertIn(layer.kernel, model2.trainable_weights)
def testLayerTrackedThroughSequential(self):
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def ffnet(layer_sizes, name):
ff = sequential.Sequential(name=name)
for i, width in enumerate(layer_sizes):
ff.add(core.Dense(
width,
activation=("relu" if i < len(layer_sizes)-1 else None)))
return ff
class MyModel2(training.Model):
def __init__(self, config, name="my_model_2"):
super(MyModel2, self).__init__(name=name)
self._num_tokens = config.num_tokens
# list of sub-models
self._ffnet = [ffnet(config.module_layers + (self._num_tokens,), "ff")]
def null_input(self):
return array_ops.zeros([1, self._num_tokens], dtype=dtypes.float32)
def call(self, input_, module_index=None):
return self._ffnet[0](input_)
m2 = MyModel2(AttrDict(
num_tokens=5,
module_layers=(50, 30)))
# Construct
m2(m2.null_input())
self.assertLen(m2.trainable_variables, 6)
def testJSONSerialization(self):
obj = tracking.AutoTrackable()
obj.l = [1]
json.dumps(obj.l, default=serialization.get_json_type)
@test_util.run_v1_only("b/120545219")
def testUpdatesForwarded(self):
with context.graph_mode():
model = HasList()
model_input = array_ops.ones([32, 2])
model(model_input)
self.assertGreater(len(model.layers_with_updates[0].updates), 0)
self.assertEqual(set(model.layers_with_updates[0].updates),
set(model.updates))
with context.eager_mode():
model = HasList()
model_input = array_ops.ones([32, 2])
model(model_input)
self.assertEqual(0, len(model.updates))
@test_util.run_in_graph_and_eager_modes
@test_util.run_v1_only("b/120545219")
def testLossesForwarded(self):
model = HasList()
model_input = array_ops.ones([32, 2])
model(model_input)
self.assertEqual(2, len(model.losses))
def testModelContainersCompareEqual(self):
class HasEqualContainers(training.Model):
def __init__(self):
super(HasEqualContainers, self).__init__()
self.l1 = []
self.l2 = []
model = HasEqualContainers()
first_layer = HasEqualContainers()
model.l1.append(first_layer)
second_layer = HasEqualContainers()
model.l2.append(second_layer)
self.assertEqual([first_layer, second_layer], model.layers)
def testNotTrackable(self):
class NotTrackable(object):
pass
with self.assertRaises(ValueError):
data_structures.List([NotTrackable()])
def testCallNotImplemented(self):
with self.assertRaisesRegexp(TypeError, "not callable"):
data_structures.List()(1.)
def testNoPop(self):
with self.assertRaises(AttributeError):
data_structures.List().pop()
@test_util.run_in_graph_and_eager_modes
def testTensorConversion(self):
class ListToTensor(training.Model):
def __init__(self):
super(ListToTensor, self).__init__()
self.l = [1., 2., 3.]
self.assertAllEqual(
[1., 2., 3.],
self.evaluate(constant_op.constant(ListToTensor().l)))
self.assertAllEqual(
[1., 2., 3.],
self.evaluate(array_ops.pack(ListToTensor().l)))
def testNesting(self):
with context.graph_mode():
inner = data_structures.List()
outer = data_structures.List([inner])
inner.append(non_keras_core.Dense(1))
inner[0](array_ops.ones([2, 3]))
self.assertEqual(2, len(outer.variables))
self.assertIsInstance(
outer.variables[0],
resource_variable_ops.ResourceVariable)
def testNonLayerVariables(self):
v = resource_variable_ops.ResourceVariable([1.])
l = data_structures.List([v])
self.assertTrue(l.trainable)
self.assertEqual([], l.layers)
self.assertEqual([v], l.variables)
self.assertEqual([v], l.trainable_weights)
self.assertEqual([], l.non_trainable_variables)
l.trainable = False
self.assertEqual([v], l.variables)
self.assertEqual([], l.trainable_variables)
self.assertEqual([v], l.non_trainable_variables)
l.trainable = True
v2 = resource_variable_ops.ResourceVariable(1., trainable=False)
l.append(v2)
self.assertEqual([v, v2], l.weights)
self.assertEqual([v], l.trainable_weights)
self.assertEqual([v2], l.non_trainable_weights)
def testCopy(self):
v1 = resource_variable_ops.ResourceVariable(1.)
v2 = resource_variable_ops.ResourceVariable(1.)
v3 = resource_variable_ops.ResourceVariable(1.)
l1 = data_structures.List([v1, v2])
l2 = l1.copy()
l2.append(v3)
self.assertEqual(list(l1), [v1, v2])
self.assertEqual(list(l2), [v1, v2, v3])
def testSlicing(self):
v1 = resource_variable_ops.ResourceVariable(1.)
v2 = resource_variable_ops.ResourceVariable(1.)
v3 = resource_variable_ops.ResourceVariable(1.)
v4 = resource_variable_ops.ResourceVariable(1.)
l = data_structures.List([v1, v2, v3, v4])
self.assertEqual(l[1:], [v2, v3, v4])
self.assertEqual(l[1:-1], [v2, v3])
self.assertEqual(l[:-1], [v1, v2, v3])
def testHash(self):
has_sequences = set([data_structures.List(),
data_structures.List()])
self.assertEqual(2, len(has_sequences))
self.assertNotIn(data_structures.List(), has_sequences)
def testIMul_zero(self):
l = data_structures.List([])
with self.assertRaisesRegexp(ValueError, "List only supports append"):
l *= 0
def testIMul(self):
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures.List([v])
l *= 2
self.assertEqual(list(l), [v] * 2)
def testMul(self):
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures.List([v, v, v])
self.assertEqual(list(l * 2), [v, v, v] * 2)
def testRMul(self):
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures.List([v, v, v])
self.assertEqual(list(2 * l), [v, v, v] * 2)
class ListWrapperTest(test.TestCase):
IGNORED = ("__new__", "__init__", "__subclasshook__", "__getattribute__")
def test_overrides_all_list_methods(self):
not_overridden = []
for name in dir(list):
if name in ListWrapperTest.IGNORED:
continue
list_method = getattr(list, name)
if not callable(list_method):
continue
object_method = getattr(object, name, None)
if object_method is not None and object_method == list_method:
# Skip methods that aren't overridden from object.
continue
if list_method == getattr(data_structures.ListWrapper, name):
not_overridden.append(name)
if not_overridden:
self.fail("ListWrapper does not override %s" % (not_overridden))
def testPickle(self):
original = data_structures.ListWrapper([1, 2])
serialized = pickle.dumps(original)
del original
deserialized = pickle.loads(serialized)
self.assertEqual([1, 2], deserialized)
def testSameStructure(self):
l = [1]
nest.assert_same_structure(l, data_structures.ListWrapper(copy.copy(l)))
def testFunctionCaching(self):
@def_function.function
def f(list_input):
return list_input[0] + constant_op.constant(1.)
first_trace = f.get_concrete_function([constant_op.constant(2.)])
second_trace = f.get_concrete_function(
data_structures.ListWrapper([constant_op.constant(3.)]))
self.assertIs(first_trace, second_trace)
def testListWrapperBasic(self):
# ListWrapper, unlike List, compares like the built-in list type (since it
# is used to automatically replace lists).
a = tracking.AutoTrackable()
b = tracking.AutoTrackable()
self.assertEqual([a, a],
[a, a])
self.assertEqual(data_structures.ListWrapper([a, a]),
data_structures.ListWrapper([a, a]))
self.assertEqual([a, a],
data_structures.ListWrapper([a, a]))
self.assertEqual(data_structures.ListWrapper([a, a]),
[a, a])
self.assertNotEqual([a, a],
[b, a])
self.assertNotEqual(data_structures.ListWrapper([a, a]),
data_structures.ListWrapper([b, a]))
self.assertNotEqual([a, a],
data_structures.ListWrapper([b, a]))
self.assertLess([a], [a, b])
self.assertLess(data_structures.ListWrapper([a]),
data_structures.ListWrapper([a, b]))
self.assertLessEqual([a], [a, b])
self.assertLessEqual(data_structures.ListWrapper([a]),
data_structures.ListWrapper([a, b]))
self.assertGreater([a, b], [a])
self.assertGreater(data_structures.ListWrapper([a, b]),
data_structures.ListWrapper([a]))
self.assertGreaterEqual([a, b], [a])
self.assertGreaterEqual(data_structures.ListWrapper([a, b]),
data_structures.ListWrapper([a]))
self.assertEqual([a], data_structures.ListWrapper([a]))
self.assertEqual([a], list(data_structures.List([a])))
self.assertEqual([a, a], data_structures.ListWrapper([a]) + [a])
self.assertEqual([a, a], [a] + data_structures.ListWrapper([a]))
self.assertIsInstance(data_structures.ListWrapper([a]), list)
self.assertEqual(
tensor_shape.TensorShape([None, 2]).as_list(),
(data_structures.ListWrapper([None])
+ tensor_shape.TensorShape([2])).as_list())
def testAcceptsNonTrackableContent(self):
l = data_structures.ListWrapper([1, 2, 3])
self.assertEqual(l, [1, 2, 3])
def testWrapperChangesList(self):
l = []
l_wrapper = data_structures.ListWrapper(l)
l_wrapper.append(1)
self.assertEqual([1], l)
def testListChangesWrapper(self):
l = []
l_wrapper = data_structures.ListWrapper(l)
l.append(1)
self.assertEqual([1], l_wrapper)
def testLayerCollectionWithExternalMutation(self):
l = []
l_wrapper = data_structures.ListWrapper(l)
layer = core.Dense(1)
l.append(layer)
self.assertEqual([layer], l_wrapper.layers)
def testNotHashable(self):
with self.assertRaises(TypeError):
hash(data_structures.ListWrapper())
def testDelItem(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
del l[0]
self.assertEqual(l, [2, 3, 4])
self.assertUnableToSave(l, "Unable to save .*__delitem__")
def testDelSlice(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
del l[2:3]
self.assertEqual(l, [1, 2, 4])
self.assertUnableToSave(l, "Unable to save .*__delslice__")
def testSetSlice_canSaveForNonTrackableItems(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
l[:] = 2, 8, 9, 0
self.assertEqual(l, [2, 8, 9, 0])
l._maybe_initialize_trackable() # pylint: disable=protected-access
self.assertEqual(len(l._checkpoint_dependencies), 0) # pylint: disable=protected-access
def testSetSlice_cannotSaveIfTrackableModified(self):
v1 = resource_variable_ops.ResourceVariable(1.)
v2 = resource_variable_ops.ResourceVariable(1.)
l = data_structures.ListWrapper([1, 2, v1, v2])
l[:] = 2, 8, 9, v2
self.assertEqual(l, [2, 8, 9, v2])
self.assertUnableToSave(l, "Unable to save .*__setslice__")
def testSetSlice_truncate(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
l[:] = []
self.assertEqual(l, [])
def testSetSlice_extend(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
l[2:] = 1, 2, 3, 4
self.assertEqual(l, [1, 2, 1, 2, 3, 4])
def testIMulNegative(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
l *= -1
self.assertEqual(l, [1, 2, 3, 4] * -1)
self.assertUnableToSave(l, "Unable to save")
def testIMulPositive(self):
v = variables.Variable(1.)
l = data_structures.ListWrapper([1, 2, 3, 4, v])
self.assertEqual([("4", v)], l._checkpoint_dependencies)
root = util.Checkpoint(l=l)
prefix = os.path.join(self.get_temp_dir(), "ckpt")
path = root.save(prefix)
v.assign(5.)
l *= 2
self.assertEqual(l, [1, 2, 3, 4, v, 1, 2, 3, 4, v])
self.assertEqual([("4", v), ("9", v)], l._checkpoint_dependencies)
root.restore(path)
self.assertAllClose(1., v.numpy())
def testSort(self):
l = data_structures.ListWrapper([1, 2, 3, 4])
l.sort()
self.assertEqual(l, [1, 2, 3, 4])
# Regardless of being a no-op for the input list, we still refuse to save.
# This is intentional since otherwise we would end up with a hard to debug
# case for users (e.g. sometimes sort on a ListWrapper is trackable and
# other times it is not).
self.assertUnableToSave(l, "Unable to save .*sort")
def assertUnableToSave(self, l, msg):
l._maybe_initialize_trackable() # pylint: disable=protected-access
with self.assertRaisesRegexp(ValueError, msg):
return l._checkpoint_dependencies # pylint: disable=protected-access
class HasMapping(training.Model):
def __init__(self):
super(HasMapping, self).__init__()
self.layer_dict = data_structures.Mapping(output=core.Dense(7))
self.layer_dict["norm"] = data_structures.List()
self.layer_dict["dense"] = data_structures.List()
self.layer_dict["dense"].extend(
[core.Dense(5),
core.Dense(6, kernel_regularizer=math_ops.reduce_sum)])
self.layer_dict["norm"].append(
normalization.BatchNormalization())
self.layer_dict["norm"].append(
normalization.BatchNormalization())
def call(self, x):
aggregation = 0.
for norm, dense in zip(self.layer_dict["norm"], self.layer_dict["dense"]):
x = norm(dense(x))
aggregation += math_ops.reduce_sum(x)
return self.layer_dict["output"](x) / aggregation
class MappingTests(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def testTracking(self):
model = HasMapping()
output = model(array_ops.ones([32, 2]))
self.assertAllEqual([32, 7], output.shape.as_list())
self.assertEqual(5, len(model.layers))
six.assertCountEqual(self, model.layers, model.layer_dict.layers)
self.assertEqual(1, len(model._checkpoint_dependencies))
self.assertIs(model.layer_dict, model._checkpoint_dependencies[0].ref)
self.evaluate([v.initializer for v in model.variables])
test_var = model.layer_dict["output"].kernel
self.evaluate(test_var.assign(array_ops.ones([6, 7])))
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
self.evaluate(test_var.assign(array_ops.zeros([6, 7])))
model.load_weights(save_path)
self.assertAllEqual(numpy.ones([6, 7]),
self.evaluate(test_var))
def testJSONSerialization(self):
obj = tracking.AutoTrackable()
obj.d = {"a": 2}
json.dumps(obj.d, default=serialization.get_json_type)
def testNoOverwrite(self):
mapping = data_structures.Mapping()
original = data_structures.List()
mapping["a"] = original
with self.assertRaises(ValueError):
mapping["a"] = data_structures.List()
self.assertIs(original, mapping["a"])
with self.assertRaises(AttributeError):
del mapping["a"]
mapping.update(b=data_structures.Mapping())
with self.assertRaises(ValueError):
mapping.update({"b": data_structures.Mapping()})
def testNonStringKeys(self):
mapping = data_structures.Mapping()
with self.assertRaises(TypeError):
mapping[1] = data_structures.List()
def testLayerCollectionWithExternalMutation(self):
d = {}
root = tracking.AutoTrackable()
root.wrapper = d
self.assertEqual([], root.wrapper.layers)
self.assertEqual([], root.wrapper.trainable_weights)
layer1 = core.Dense(1)
layer2 = core.Dense(1)
d["a"] = layer1
d["b"] = layer2
self.assertEqual([layer1, layer2], root.wrapper.layers)
# The layers have still not created variables
self.assertEqual([], root.wrapper.trainable_weights)
def testHashing(self):
has_mappings = set([data_structures.Mapping(),
data_structures.Mapping()])
self.assertEqual(2, len(has_mappings))
self.assertNotIn(data_structures.Mapping(), has_mappings)
# In contrast to Mapping, dict wrappers are not hashable
a = tracking.AutoTrackable()
a.d = {}
self.assertEqual({}, a.d)
self.assertFalse({} != a.d) # pylint: disable=g-explicit-bool-comparison
self.assertNotEqual({1: 2}, a.d)
with self.assertRaisesRegexp(TypeError, "unhashable"):
set([a.d])
def testDictWrapperBadKeys(self):
a = tracking.AutoTrackable()
a.d = {}
a.d[1] = data_structures.List()
model = training.Model()
model.sub = a
save_path = os.path.join(self.get_temp_dir(), "ckpt")
with self.assertRaisesRegexp(ValueError, "non-string key"):
model.save_weights(save_path)
def testDictWrapperNoDependency(self):
a = tracking.AutoTrackable()
a.d = data_structures.NoDependency({})
a.d[1] = [3]
self.assertEqual([a], util.list_objects(a))
model = training.Model()
model.sub = a
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
model.load_weights(save_path)
def testNonStringKeyNotTrackableValue(self):
a = tracking.AutoTrackable()
a.d = {}
a.d["a"] = [3]
a.d[1] = data_structures.NoDependency([3])
self.assertEqual([a, a.d, a.d["a"]], util.list_objects(a))
model = training.Model()
model.sub = a
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
model.load_weights(save_path)
def testNonAppendNotTrackable(self):
# Non-append mutations (deleting or overwriting values) are OK when the
# values aren't tracked.
a = tracking.AutoTrackable()
a.d = {}
a.d["a"] = [3]
a.d[1] = 3
a.d[1] = 2
self.assertEqual(2, a.d[1])
del a.d[1]
a.d[2] = data_structures.NoDependency(tracking.AutoTrackable())
second = tracking.AutoTrackable()
a.d[2] = data_structures.NoDependency(second)
self.assertIs(second, a.d[2])
self.assertEqual([a, a.d, a.d["a"]], util.list_objects(a))
model = training.Model()
model.sub = a
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
model.load_weights(save_path)
def testPopNoSave(self):
model = training.Model()
model.d = {}
model.d["a"] = []
model.d.pop("a")
save_path = os.path.join(self.get_temp_dir(), "ckpt")
with self.assertRaisesRegexp(ValueError, "Unable to save"):
model.save_weights(save_path)
def testExternalModificationNoSave(self):
model = training.Model()
external_reference = {}
model.d = external_reference
external_reference["a"] = []
save_path = os.path.join(self.get_temp_dir(), "ckpt")
with self.assertRaisesRegexp(ValueError, "modified outside the wrapper"):
model.save_weights(save_path)
def testOverwriteCanStillSave(self):
model = training.Model()
model.d = {}
model.d["a"] = {}
model.d["a"] = {}
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
def testIter(self):
model = training.Model()
model.d = {1: 3}
model.d[1] = 3
self.assertEqual([1], list(model.d))
new_dict = {}
# This update() is super tricky. If the dict wrapper subclasses dict,
# CPython will access its storage directly instead of calling any
# methods/properties on the object. So the options are either not to
# subclass dict (in which case update will call normal iter methods, but the
# object won't pass isinstance checks) or to subclass dict and keep that
# storage updated (no shadowing all its methods like ListWrapper).
new_dict.update(model.d)
self.assertEqual({1: 3}, new_dict)
def testListShallowCopy(self):
root = tracking.AutoTrackable()
orig_list = [[1.]]
root.a = orig_list
copied = copy.copy(root.a)
self.assertAllEqual([[1.]], copied)
self.assertIsNot(root.a, copied)
self.assertIs(root.a[0], copied[0])
# Dirtiness should be inherited
util.list_objects(root.a)
orig_list.append(1.)
with self.assertRaises(ValueError):
util.list_objects(root.a)
with self.assertRaises(ValueError):
util.list_objects(copy.copy(root.a))
def testListDeepCopy(self):
root = tracking.AutoTrackable()
orig_list = [[1.]]
root.a = orig_list
copied = copy.deepcopy(root.a)
self.assertAllEqual([[1.]], copied)
self.assertIsNot(root.a, copied)
self.assertIsNot(root.a[0], copied[0])
# Dirtiness should be inherited
util.list_objects(root.a)
orig_list.append(1.)
with self.assertRaises(ValueError):
util.list_objects(root.a)
with self.assertRaises(ValueError):
util.list_objects(copy.deepcopy(root.a))
def testDictShallowCopy(self):
root = tracking.AutoTrackable()
orig_dict = {"a": [1.]}
root.a = orig_dict
copied = copy.copy(root.a)
self.assertAllEqual([1.], copied["a"])
self.assertIsNot(root.a, copied)
self.assertIs(root.a["a"], copied["a"])
copied = root.a.copy()
self.assertAllEqual([1.], copied["a"])
self.assertIsNot(root.a, copied)
self.assertIs(root.a["a"], copied["a"])
# Dirtiness should be inherited
util.list_objects(root.a)
orig_dict["b"] = []
with self.assertRaises(ValueError):
util.list_objects(root.a)
with self.assertRaises(ValueError):
util.list_objects(copy.copy(root.a))
def testDictDeepCopy(self):
root = tracking.AutoTrackable()
orig_dict = {"a": [1.]}
root.a = orig_dict
copied = copy.deepcopy(root.a)
self.assertAllEqual([1.], copied["a"])
self.assertIsNot(root.a, copied)
self.assertIsNot(root.a["a"], copied["a"])
# Dirtiness should be inherited
util.list_objects(root.a)
orig_dict["b"] = []
with self.assertRaises(ValueError):
util.list_objects(root.a)
with self.assertRaises(ValueError):
util.list_objects(copy.deepcopy(root.a))
def testShallowCopyTrackable(self):
original = tracking.AutoTrackable()
original_sub = tracking.AutoTrackable()
original.a = [[1.]]
original.b = {"a": original_sub}
shallow_copied = copy.copy(original)
self.assertIs(original_sub, shallow_copied.b["a"])
self.assertIsNot(original, shallow_copied)
self.assertEqual([[1.]], shallow_copied.a)
shallow_deps = util.list_objects(shallow_copied)
self.assertIn(shallow_copied.a, shallow_deps)
self.assertIn(shallow_copied.b, shallow_deps)
self.assertIn(shallow_copied.b["a"], shallow_deps)
def testDeepCopyTrackable(self):
original = tracking.AutoTrackable()
original_sub = tracking.AutoTrackable()
original.a = [[1.]]
original.b = {"a": original_sub}
self.assertIsInstance(original.b, dict)
deep_copied = copy.deepcopy(original)
self.assertIsInstance(deep_copied.b, dict)
self.assertIsNot(original, deep_copied)
self.assertIsNot(original_sub, deep_copied.b["a"])
self.assertEqual([[1.]], deep_copied.a)
self.assertIsInstance(deep_copied.b["a"], tracking.AutoTrackable)
deps = util.list_objects(deep_copied)
self.assertIn(deep_copied.a, deps)
self.assertIn(deep_copied.b, deps)
self.assertIn(deep_copied.b["a"], deps)
self.assertNotIn(original_sub, deps)
def testConstructableFromSequence(self):
result = data_structures._DictWrapper([(1, 2), (3, 4)])
self.assertIsInstance(result, dict)
self.assertEqual({1: 2, 3: 4}, result)
def testPickle(self):
original = data_structures._DictWrapper(dict(a=1, b=2))
serialized = pickle.dumps(original)
del original
deserialized = pickle.loads(serialized)
self.assertEqual(dict(a=1, b=2), deserialized)
def testListAddOrder(self):
self.assertEqual([1., 2.],
data_structures.ListWrapper([1.])
+ data_structures.ListWrapper([2.]))
self.assertEqual([1., 2.],
data_structures.ListWrapper([1.])
+ [2.])
self.assertEqual([1., 2.],
[1.]
+ data_structures.ListWrapper([2.]))
def testSameStructure(self):
d = {1: "a"}
nest.assert_same_structure(d, data_structures._DictWrapper(d.copy()))
def testFunctionCaching(self):
@def_function.function
def f(dict_input):
return dict_input["x"] + constant_op.constant(1.)
first_trace = f.get_concrete_function({"x": constant_op.constant(2.)})
second_trace = f.get_concrete_function(
data_structures._DictWrapper({"x": constant_op.constant(3.)}))
self.assertIs(first_trace, second_trace)
class HasTuple(training.Model):
def __init__(self):
super(HasTuple, self).__init__()
self.layer_list = (
core.Dense(3), core.Dense(4),
core.Dense(5, kernel_regularizer=math_ops.reduce_sum))
self.layers_with_updates = (normalization.BatchNormalization(),)
def call(self, x):
aggregation = 0.
for l in self.layer_list:
x = l(x)
aggregation += math_ops.reduce_sum(x)
bn, = self.layers_with_updates
return bn(x) / aggregation
class TupleTests(test.TestCase, parameterized.TestCase):
@test_util.run_in_graph_and_eager_modes
def testTracking(self):
model = HasTuple()
output = model(array_ops.ones([32, 2]))
self.assertAllEqual([32, 5], output.shape.as_list())
self.assertLen(model.layers, 4)
self.assertLen(model.layer_list.layers, 3)
six.assertCountEqual(
self,
model.layers,
tuple(model.layer_list.layers) + model.layers_with_updates)
self.assertEqual(3, model.layer_list.layers[0].units)
self.assertEqual(4, model.layer_list.layers[1].units)
self.assertEqual(5, model.layer_list.layers[2].units)
self.assertLen(model._checkpoint_dependencies, 2)
self.assertIs(model.layer_list, model._checkpoint_dependencies[0].ref)
self.assertIs(model.layers_with_updates,
model._checkpoint_dependencies[1].ref)
self.assertLen(
model._checkpoint_dependencies[0].ref._checkpoint_dependencies, 3)
self.evaluate([v.initializer for v in model.variables])
self.evaluate(model.variables[0].assign([[1., 2., 3.], [4., 5., 6.]]))
save_path = os.path.join(self.get_temp_dir(), "ckpt")
model.save_weights(save_path)
self.evaluate(model.variables[0].assign(array_ops.zeros([2, 3])))
model.load_weights(save_path)
self.assertAllEqual([[1., 2., 3.], [4., 5., 6.]],
self.evaluate(model.variables[0]))
v = variables.Variable(1.)
model.var_list = (v,)
self.assertIn(id(v), [id(obj) for obj in model.variables])
self.assertIn(id(v), [id(obj) for obj in model.trainable_variables])
self.assertNotIn(id(v), [id(obj) for obj in model.non_trainable_variables])
self.assertIn(id(model.layer_list[0].trainable_weights[0]),
[id(obj) for obj in model.trainable_weights])
@parameterized.named_parameters(
("Module", module.Module),
("Model", training.Model),
)
def testSubModelTracking(self, module_subclass):
model = module_subclass()
model.v = variables.Variable(1.)
self.assertIn(model.v, model.trainable_variables)
model2 = module_subclass()
model2.m = (model,)
self.assertIn(model.v, model2.trainable_variables)
def testSubSequentialTracking(self):
class _Subclassed(training.Model):
def __init__(self, wrapped):
super(_Subclassed, self).__init__()
self._wrapped = wrapped
def call(self, x):
return self._wrapped(x)
model = sequential.Sequential()
layer = core.Dense(1)
model.add(layer)
model2 = _Subclassed(model)
model2(array_ops.ones([1, 2]))
model2.m = (model,)
self.assertIn(layer.kernel, model2.trainable_weights)
def testJSONSerialization(self):
obj = tracking.AutoTrackable()
obj.l = (1,)
json.dumps(obj.l, default=serialization.get_json_type)
def testUpdatesForwarded(self):
with ops.Graph().as_default():
model = HasTuple()
model_input = array_ops.ones([32, 2])
model(model_input)
self.assertNotEmpty(model.layers_with_updates[0].updates)
self.assertEqual(set(model.layers_with_updates[0].updates),
set(model.updates))
model = HasTuple()
model_input = array_ops.ones([32, 2])
model(model_input)
self.assertEmpty(model.updates)
@test_util.run_in_graph_and_eager_modes
def testLossesForwarded(self):
model = HasTuple()
model_input = array_ops.ones([32, 2])
model(model_input)
self.assertLen(model.losses, 1)
def testModelContainersCompareEqual(self):
class HasEqualContainers(training.Model):
def __init__(self):
super(HasEqualContainers, self).__init__()
self.l1 = ()
self.l2 = ()
model = HasEqualContainers()
first_layer = HasEqualContainers()
model.l1 = (first_layer,)
second_layer = HasEqualContainers()
model.l2 = (second_layer,)
self.assertEqual((first_layer,), model.l1)
d = {model.l1: 1, model.l2: 2}
self.assertEqual(1, d[model.l1])
self.assertEqual(1, d[(first_layer,)])
self.assertEqual(2, d[model.l2])
self.assertEqual(2, d[(second_layer,)])
self.assertEqual([first_layer, second_layer], model.layers)
@test_util.run_in_graph_and_eager_modes
def testTensorConversion(self):
class TupleToTensor(training.Model):
def __init__(self):
super(TupleToTensor, self).__init__()
self.l = (1., 2., 3.)
self.assertAllEqual(
(1., 2., 3.),
self.evaluate(constant_op.constant(TupleToTensor().l)))
self.assertAllEqual(
(1., 2., 3.),
self.evaluate(array_ops.pack(TupleToTensor().l)))
def testNonLayerVariables(self):
v = resource_variable_ops.ResourceVariable([1.])
l = data_structures._TupleWrapper((v,))
self.assertEqual([], l.layers)
self.assertEqual([v], l.variables)
self.assertEqual([v], l.trainable_weights)
self.assertEqual([], l.non_trainable_variables)
def testCopy(self):
v1 = resource_variable_ops.ResourceVariable(1.)
v2 = resource_variable_ops.ResourceVariable(1.)
l1 = data_structures._TupleWrapper((v1, v2))
l2 = copy.copy(l1)
self.assertEqual(l1, (v1, v2))
self.assertEqual(l2, (v1, v2))
self.assertIs(l1[0], l2[0])
l2_deep = copy.deepcopy(l1)
self.assertIsNot(l1[0], l2_deep[0])
with self.assertRaises(AttributeError):
l2.append(v1)
def testSlicing(self):
v1 = resource_variable_ops.ResourceVariable(1.)
v2 = resource_variable_ops.ResourceVariable(1.)
v3 = resource_variable_ops.ResourceVariable(1.)
v4 = resource_variable_ops.ResourceVariable(1.)
l = data_structures._TupleWrapper((v1, v2, v3, v4))
self.assertEqual(l[1:], (v2, v3, v4))
self.assertEqual(l[1:-1], (v2, v3))
self.assertEqual(l[:-1], (v1, v2, v3))
def testHash(self):
has_sequences = set([data_structures._TupleWrapper(),
data_structures._TupleWrapper()])
self.assertLen(has_sequences, 1)
self.assertIn(data_structures._TupleWrapper(), has_sequences)
def testIMul_zero(self):
l = data_structures._TupleWrapper((1,))
l *= 0
self.assertEqual((), l)
def testIMul(self):
# Note: tuple behavior differs from list behavior. Lists are mutated by
# imul/iadd, tuples assign a new object to the left hand side of the
# expression.
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures._TupleWrapper((v,))
original = l
l *= 2
self.assertEqual(l, (v,) * 2)
self.assertNotEqual(original, (v,) * 2)
def testIAdd(self):
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures._TupleWrapper((v,))
original = l
l += (1,)
self.assertEqual(l, (v, 1))
self.assertNotEqual(original, (v, 1))
self.assertEqual(original, (v,))
def testMul(self):
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures._TupleWrapper((v, v, v))
self.assertEqual(l * 2, (v, v, v) * 2)
def testRMul(self):
v = resource_variable_ops.ResourceVariable(1.)
l = data_structures._TupleWrapper((v, v, v))
self.assertEqual(2 * l, (v, v, v) * 2)
def testPickle(self):
original = data_structures._TupleWrapper((1, 2))
serialized = pickle.dumps(original)
del original
deserialized = pickle.loads(serialized)
self.assertEqual((1, 2), deserialized)
def testNamedTuple(self):
named = collections.namedtuple("Named", ("x", "y"))
v = variables.Variable(2)
nt = named(x=v, y=2)
m = module.Module()
m.nt = nt
self.assertIs(v, m.nt.x)
self.assertIs(v, m.nt[0])
self.assertIs(
v, m._checkpoint_dependencies[0].ref._checkpoint_dependencies[0].ref)
self.assertEqual(2, m.nt.y)
def testNamedSubclassing(self):
named = collections.namedtuple("Named", ("x", "y"))
v = variables.Variable(2)
class NamedSubclass(named):
def __new__(cls, x, y):
del y # unused
return super(NamedSubclass, cls).__new__(cls, x, 3)
@property
def summed(self):
return self.x + self.y
nt = NamedSubclass(x=v, y=2)
m = module.Module()
m.nt = nt
self.assertEqual(3, m.nt.y)
self.assertIs(v, m.nt.x)
self.assertIs(
v, m._checkpoint_dependencies[0].ref._checkpoint_dependencies[0].ref)
self.assertEqual("x", m.nt._checkpoint_dependencies[0].name)
self.assertEqual("0", m.nt._checkpoint_dependencies[1].name)
self.assertEqual(5, self.evaluate(m.nt.summed))
def testUnnamedSubclassing(self):
v = variables.Variable(2)
class UnnamedSubclass(tuple):
@property
def summed(self):
return self[0] + self[1]
unt = UnnamedSubclass([v, 2])
m = module.Module()
m.unt = unt
self.assertEqual("0", m.unt._checkpoint_dependencies[0].name)
self.assertLen(m.unt._checkpoint_dependencies, 1)
self.assertEqual(4, self.evaluate(m.unt.summed))
nest.assert_same_structure(
[m.unt], nest.map_structure(lambda x: x, [m.unt]))
def testNamedtupleSubclassWithCustomNew(self):
class SubclassWithDifferentArgs(collections.namedtuple("A", ["x"])):
def __new__(cls):
return super(SubclassWithDifferentArgs, cls).__new__(cls, [])
nt = SubclassWithDifferentArgs()
m = module.Module()
m.nt = nt
m.nt.x.append(variables.Variable(1.))
prefix = os.path.join(self.get_temp_dir(), "ckpt")
ckpt = util.Checkpoint(m=m)
with self.assertRaises(ValueError):
ckpt.save(prefix)
def testSameStructure(self):
t = (variables.Variable(1.),)
m = module.Module()
m.t = t
nest.assert_same_structure(t, m.t)
nest.assert_same_structure(m.t, t)
nt_type = collections.namedtuple("nt", ["x", "y"])
nt = nt_type(x=1, y=2)
m.nt = nt
nest.assert_same_structure(m.nt, nt)
with self.assertRaises(TypeError): # pylint: disable=g-error-prone-assert-raises
nest.assert_same_structure(m.nt, m.t)
def testFlatten(self):
t = data_structures._TupleWrapper((1, data_structures._TupleWrapper((2,))))
self.assertEqual([1, 2], nest.flatten(t))
self.assertEqual(
nest.flatten_with_tuple_paths((1, (2,))),
nest.flatten_with_tuple_paths(t))
self.assertEqual((3, (4,)),
nest.pack_sequence_as(t, [3, 4]))
nt_type = collections.namedtuple("nt", ["x", "y"])
nt = nt_type(1., 2.)
wrapped_nt = data_structures._TupleWrapper(nt)
self.assertEqual(
nest.flatten_with_tuple_paths(nt),
nest.flatten_with_tuple_paths(wrapped_nt))
self.assertEqual((3, 4,),
nest.pack_sequence_as(wrapped_nt, [3, 4]))
self.assertEqual(3, nest.pack_sequence_as(wrapped_nt, [3, 4]).x)
def testFunctionCaching(self):
@def_function.function
def f(tuple_input):
return tuple_input[0] + constant_op.constant(1.)
first_trace = f.get_concrete_function((constant_op.constant(2.),))
second_trace = f.get_concrete_function(
data_structures._TupleWrapper((constant_op.constant(3.),)))
self.assertIs(first_trace, second_trace)
def testPythonMapImpl(self):
t = data_structures._TupleWrapper((1, data_structures._TupleWrapper((2,))))
self.assertEqual(
(4, (5,)),
nest.map_structure_up_to((None, (None,)), lambda x: x + 3, t,
check_types=True))
nest.assert_shallow_structure((None, None), t)
def testDatasetMap(self):
dataset = dataset_ops.Dataset.from_tensor_slices(
constant_op.constant([1, 2, 3]))
dataset = dataset.map(lambda x: data_structures._TupleWrapper((x,)))
for index, element in enumerate(dataset):
self.assertEqual((index + 1,), self.evaluate(element))
def testDatasetMapNamed(self):
nt_type = collections.namedtuple("A", ["x"])
dataset = dataset_ops.Dataset.from_tensor_slices(
constant_op.constant([1, 2, 3]))
dataset = dataset.map(lambda x: data_structures._TupleWrapper(nt_type(x)))
for index, element in enumerate(dataset):
self.assertEqual((index + 1,), self.evaluate(element))
def testLoopAssignedModule(self):
m = module.Module()
m.s = (m,)
self.assertLen(m._checkpoint_dependencies, 1)
self.assertIs(m.s, m._checkpoint_dependencies[0].ref)
self.assertIs("s", m._checkpoint_dependencies[0].name)
self.assertEqual((), m.trainable_variables)
if __name__ == "__main__":
test.main()
| gunan/tensorflow | tensorflow/python/training/tracking/data_structures_test.py | Python | apache-2.0 | 43,039 |
package requirements_test
import (
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/models"
. "code.cloudfoundry.org/cli/cf/requirements"
testconfig "code.cloudfoundry.org/cli/testhelpers/configuration"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("TargetedSpaceRequirement", func() {
var (
config coreconfig.ReadWriter
)
BeforeEach(func() {
config = testconfig.NewRepositoryWithDefaults()
})
Context("when the user has targeted a space", func() {
It("succeeds", func() {
req := NewTargetedSpaceRequirement(config)
err := req.Execute()
Expect(err).NotTo(HaveOccurred())
})
})
Context("when the user does not have a space targeted", func() {
It("errors", func() {
config.SetSpaceFields(models.SpaceFields{})
err := NewTargetedSpaceRequirement(config).Execute()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("No space targeted"))
})
})
})
| cloudfoundry/v3-cli-plugin | vendor/code.cloudfoundry.org/cli/cf/requirements/targeted_space_test.go | GO | apache-2.0 | 981 |
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package scouter.client.popup;
import java.util.ArrayList;
import java.util.Date;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import scouter.client.model.AgentColorManager;
import scouter.client.model.AgentModelThread;
import scouter.client.model.PropertyData;
import scouter.client.net.TcpProxy;
import scouter.client.server.ServerManager;
import scouter.client.util.ColorUtil;
import scouter.client.util.ConsoleProxy;
import scouter.client.util.ExUtil;
import scouter.client.util.UIUtil;
import scouter.lang.ObjectType;
import scouter.lang.counters.CounterEngine;
import scouter.lang.pack.MapPack;
import scouter.lang.pack.ObjectPack;
import scouter.net.RequestCmd;
import scouter.util.CastUtil;
import scouter.util.DateUtil;
import scouter.util.FormatUtil;
public class ObjectPropertiesDialog {
private final Display display;
private Shell dialog;
private final int objHash;
private int serverId;
private ObjectPack objectPack;
private TableViewer propertyTableViewer;
private TableColumnLayout tableColumnLayout;
ArrayList<PropertyData> propertyList = new ArrayList<PropertyData>();
public ObjectPropertiesDialog(Display display, int objHash, int serverId) {
this.display = display;
this.objHash = objHash;
this.serverId = serverId;
}
public void show() {
dialog = setDialogLayout();
UIUtil.setDialogDefaultFunctions(dialog);
findObjectPack();
makeTableContents();
}
public void show(final String date) {
dialog = setDialogLayout();
UIUtil.setDialogDefaultFunctions(dialog);
ExUtil.asyncRun(new Runnable() {
public void run() {
ObjectPack objectPack = null;
TcpProxy proxy = TcpProxy.getTcpProxy(serverId);
try {
MapPack param = new MapPack();
param.put("date", date);
param.put("objHash", objHash);
objectPack = (ObjectPack) proxy.getSingle(RequestCmd.OBJECT_INFO, param);
CounterEngine counterEngine = ServerManager.getInstance().getServer(serverId).getCounterEngine();
String code = counterEngine.getMasterCounter(objectPack.objType);
objectPack.tags.put("main counter", code);
} catch (Throwable t) {
ConsoleProxy.errorSafe(t.toString());
} finally {
TcpProxy.putTcpProxy(proxy);
}
ObjectPropertiesDialog.this.objectPack = objectPack;
ExUtil.exec(propertyTableViewer.getTable(), new Runnable() {
public void run() {
makeTableContents();
}
});
}
});
}
private Shell setDialogLayout() {
Shell dialog = new Shell(display, SWT.DIALOG_TRIM | SWT.RESIZE);
dialog.setText("Properties");
dialog.setLayout(new FillLayout());
Composite tableComposite = new Composite(dialog, SWT.NONE);
initialTable(tableComposite);
return dialog;
}
private void findObjectPack() {
ArrayList<ObjectPack> packList= AgentModelThread.getInstance().getAgentPackList();
for (ObjectPack objectPack : packList) {
if (objectPack.objHash == this.objHash) {
CounterEngine counterEngine = ServerManager.getInstance().getServer(serverId).getCounterEngine();
String code = counterEngine.getMasterCounter(objectPack.objType);
objectPack.tags.put("main counter", code);
this.objectPack = objectPack;
break;
}
}
}
private void makeTableContents() {
if (this.objectPack == null) {
return;
}
CounterEngine counterEngine = ServerManager.getInstance().getServer(serverId).getCounterEngine();
ObjectType type = counterEngine.getObjectType(this.objectPack.objType);
propertyList.clear();
propertyList.add(new PropertyData("objectName", this.objectPack.objName));
propertyList.add(new PropertyData("objectType", this.objectPack.objType));
propertyList.add(new PropertyData("family", type == null ? "undefined" : type.getFamily().getName()));
propertyList.add(new PropertyData("address", this.objectPack.address));
propertyList.add(new PropertyData("version", this.objectPack.version));
propertyList.add(new PropertyData("alive", String.valueOf(this.objectPack.alive)));
propertyList.add(new PropertyData("wakeUp", FormatUtil.print(new Date(this.objectPack.wakeup), "yyyyMMdd HH:mm:ss.SSS")));
propertyList.add(new PropertyData("color", AgentColorManager.getInstance().assignColor(this.objectPack.objType, objHash)));
for (String key : this.objectPack.tags.keySet()) {
propertyList.add(new PropertyData(key, CastUtil.cString(this.objectPack.tags.get(key))));
}
propertyTableViewer.refresh();
dialog.pack();
dialog.open();
}
private void initialTable(Composite composite) {
propertyTableViewer = new TableViewer(composite, SWT.MULTI | SWT.BORDER);
tableColumnLayout = new TableColumnLayout();
composite.setLayout(tableColumnLayout);
TableViewerColumn cdummy = createTableViewerDummyColumn("", 0, SWT.FILL, true, true);
cdummy.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
return "";
}
});
TableViewerColumn c = createTableViewerColumn("Property", 150, SWT.FILL, true, true);
c.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
if (element instanceof PropertyData) {
Object property = ((PropertyData) element).property;
if (property instanceof String) {
return (String) property;
}
}
return null;
}
public Image getImage(Object element) {
return null;
}
});
c = createTableViewerColumn("Value", 300, SWT.FILL, true, true);
c.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
if (element instanceof PropertyData) {
Object value = ((PropertyData) element).value;
if (value instanceof String) {
return (String) value;
} else if (value instanceof Color) {
Color color = (Color) value;
return String.format("#%02X%02X%02X", color.getRed(), color.getGreen(), color.getBlue());
}
}
return null;
}
public Image getImage(Object element) {
if (element instanceof PropertyData) {
Object value = ((PropertyData) element).value;
if (value instanceof Color) {
Image im = new Image(Display.getCurrent(), 20, 12);
GC gc = new GC(im);
gc.setBackground((Color) value);
gc.fillRectangle(8, 1, 10, 10);
gc.setForeground(ColorUtil.getInstance().getColor(SWT.COLOR_BLACK));
gc.drawRectangle(8, 1, 10, 10);
gc.dispose();
return im;
}
}
return null;
}
});
final Table table = propertyTableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
propertyTableViewer.setContentProvider(new ArrayContentProvider());
propertyTableViewer.setInput(propertyList);
}
private TableViewerColumn createTableViewerColumn(String title, int width, int alignment, boolean resizable, boolean moveable) {
final TableViewerColumn viewerColumn = new TableViewerColumn(propertyTableViewer, SWT.NONE);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setAlignment(alignment);
column.setMoveable(moveable);
tableColumnLayout.setColumnData(column, new ColumnWeightData(30, width, resizable));
return viewerColumn;
}
private TableViewerColumn createTableViewerDummyColumn(String title, int width, int alignment, boolean resizable, boolean moveable) {
final TableViewerColumn viewerColumn = new TableViewerColumn(propertyTableViewer, SWT.NONE);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setAlignment(alignment);
column.setMoveable(moveable);
tableColumnLayout.setColumnData(column, new ColumnWeightData(0, width, false));
return viewerColumn;
}
}
| yuyupapa/OpenSource | scouter.client/src/scouter/client/popup/ObjectPropertiesDialog.java | Java | apache-2.0 | 9,185 |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dep
import (
"fmt"
"os"
"path/filepath"
"sort"
"sync"
"github.com/golang/dep/gps"
"github.com/golang/dep/gps/pkgtree"
"github.com/golang/dep/gps/verify"
"github.com/golang/dep/internal/fs"
"github.com/pkg/errors"
)
var (
errProjectNotFound = fmt.Errorf("could not find project %s, use dep init to initiate a manifest", ManifestName)
errVendorBackupFailed = fmt.Errorf("failed to create vendor backup. File with same name exists")
)
// findProjectRoot searches from the starting directory upwards looking for a
// manifest file until we get to the root of the filesystem.
func findProjectRoot(from string) (string, error) {
for {
mp := filepath.Join(from, ManifestName)
_, err := os.Stat(mp)
if err == nil {
return from, nil
}
if !os.IsNotExist(err) {
// Some err other than non-existence - return that out
return "", err
}
parent := filepath.Dir(from)
if parent == from {
return "", errProjectNotFound
}
from = parent
}
}
// checkGopkgFilenames validates filename case for the manifest and lock files.
//
// This is relevant on case-insensitive file systems like the defaults in Windows and
// macOS.
//
// If manifest file is not found, it returns an error indicating the project could not be
// found. If it is found but the case does not match, an error is returned. If a lock
// file is not found, no error is returned as lock file is optional. If it is found but
// the case does not match, an error is returned.
func checkGopkgFilenames(projectRoot string) error {
// ReadActualFilenames is actually costly. Since the check to validate filename case
// for Gopkg filenames is not relevant to case-sensitive filesystems like
// ext4(linux), try for an early return.
caseSensitive, err := fs.IsCaseSensitiveFilesystem(projectRoot)
if err != nil {
return errors.Wrap(err, "could not check validity of configuration filenames")
}
if caseSensitive {
return nil
}
actualFilenames, err := fs.ReadActualFilenames(projectRoot, []string{ManifestName, LockName})
if err != nil {
return errors.Wrap(err, "could not check validity of configuration filenames")
}
actualMfName, found := actualFilenames[ManifestName]
if !found {
// Ideally this part of the code won't ever be executed if it is called after
// `findProjectRoot`. But be thorough and handle it anyway.
return errProjectNotFound
}
if actualMfName != ManifestName {
return fmt.Errorf("manifest filename %q does not match %q", actualMfName, ManifestName)
}
// If a file is not found, the string map returned by `fs.ReadActualFilenames` will
// not have an entry for the given filename. Since the lock file is optional, we
// should check for equality only if it was found.
actualLfName, found := actualFilenames[LockName]
if found && actualLfName != LockName {
return fmt.Errorf("lock filename %q does not match %q", actualLfName, LockName)
}
return nil
}
// A Project holds a Manifest and optional Lock for a project.
type Project struct {
// AbsRoot is the absolute path to the root directory of the project.
AbsRoot string
// ResolvedAbsRoot is the resolved absolute path to the root directory of the project.
// If AbsRoot is not a symlink, then ResolvedAbsRoot should equal AbsRoot.
ResolvedAbsRoot string
// ImportRoot is the import path of the project's root directory.
ImportRoot gps.ProjectRoot
// The Manifest, as read from Gopkg.toml on disk.
Manifest *Manifest
// The Lock, as read from Gopkg.lock on disk.
Lock *Lock // Optional
// The above Lock, with changes applied to it. There are two possible classes of
// changes:
// 1. Changes to InputImports
// 2. Changes to per-project prune options
ChangedLock *Lock
// The PackageTree representing the project, with hidden and ignored
// packages already trimmed.
RootPackageTree pkgtree.PackageTree
// Oncer to manage access to initial check of vendor.
CheckVendor sync.Once
// The result of calling verify.CheckDepTree against the current lock and
// vendor dir.
VendorStatus map[string]verify.VendorStatus
// The error, if any, from checking vendor.
CheckVendorErr error
}
// VerifyVendor checks the vendor directory against the hash digests in
// Gopkg.lock.
//
// This operation is overseen by the sync.Once in CheckVendor. This is intended
// to facilitate running verification in the background while solving, then
// having the results ready later.
func (p *Project) VerifyVendor() (map[string]verify.VendorStatus, error) {
p.CheckVendor.Do(func() {
p.VendorStatus = make(map[string]verify.VendorStatus)
vendorDir := filepath.Join(p.AbsRoot, "vendor")
var lps []gps.LockedProject
if p.Lock != nil {
lps = p.Lock.Projects()
}
sums := make(map[string]verify.VersionedDigest)
for _, lp := range lps {
sums[string(lp.Ident().ProjectRoot)] = lp.(verify.VerifiableProject).Digest
}
p.VendorStatus, p.CheckVendorErr = verify.CheckDepTree(vendorDir, sums)
})
return p.VendorStatus, p.CheckVendorErr
}
// SetRoot sets the project AbsRoot and ResolvedAbsRoot. If root is not a symlink, ResolvedAbsRoot will be set to root.
func (p *Project) SetRoot(root string) error {
rroot, err := filepath.EvalSymlinks(root)
if err != nil {
return err
}
p.ResolvedAbsRoot, p.AbsRoot = rroot, root
return nil
}
// MakeParams is a simple helper to create a gps.SolveParameters without setting
// any nils incorrectly.
func (p *Project) MakeParams() gps.SolveParameters {
params := gps.SolveParameters{
RootDir: p.AbsRoot,
ProjectAnalyzer: Analyzer{},
RootPackageTree: p.RootPackageTree,
}
if p.Manifest != nil {
params.Manifest = p.Manifest
}
// It should be impossible for p.ChangedLock to be nil if p.Lock is non-nil;
// we always want to use the former for solving.
if p.ChangedLock != nil {
params.Lock = p.ChangedLock
}
return params
}
// parseRootPackageTree analyzes the root project's disk contents to create a
// PackageTree, trimming out packages that are not relevant for root projects
// along the way.
//
// The resulting tree is cached internally at p.RootPackageTree.
func (p *Project) parseRootPackageTree() (pkgtree.PackageTree, error) {
if p.RootPackageTree.Packages == nil {
ptree, err := pkgtree.ListPackages(p.ResolvedAbsRoot, string(p.ImportRoot))
if err != nil {
return pkgtree.PackageTree{}, errors.Wrap(err, "analysis of current project's packages failed")
}
// We don't care about (unreachable) hidden packages for the root project,
// so drop all of those.
var ig *pkgtree.IgnoredRuleset
if p.Manifest != nil {
ig = p.Manifest.IgnoredPackages()
}
p.RootPackageTree = ptree.TrimHiddenPackages(true, true, ig)
}
return p.RootPackageTree, nil
}
// GetDirectDependencyNames returns the set of unique Project Roots that are the
// direct dependencies of this Project.
//
// A project is considered a direct dependency if at least one of its packages
// is named in either this Project's required list, or if there is at least one
// non-ignored import statement from a non-ignored package in the current
// project's package tree.
//
// The returned map of Project Roots contains only boolean true values; this
// makes a "false" value always indicate an absent key, which makes conditional
// checks against the map more ergonomic.
//
// This function will correctly utilize ignores and requireds from an existing
// manifest, if one is present, but will also do the right thing without a
// manifest.
func (p *Project) GetDirectDependencyNames(sm gps.SourceManager) (map[gps.ProjectRoot]bool, error) {
var reach []string
if p.ChangedLock != nil {
reach = p.ChangedLock.InputImports()
} else {
ptree, err := p.parseRootPackageTree()
if err != nil {
return nil, err
}
reach = externalImportList(ptree, p.Manifest)
}
directDeps := map[gps.ProjectRoot]bool{}
for _, ip := range reach {
pr, err := sm.DeduceProjectRoot(ip)
if err != nil {
return nil, err
}
directDeps[pr] = true
}
return directDeps, nil
}
// FindIneffectualConstraints looks for constraint rules expressed in the
// manifest that will have no effect during solving, as they are specified for
// projects that are not direct dependencies of the Project.
//
// "Direct dependency" here is as implemented by GetDirectDependencyNames();
// it correctly incorporates all "ignored" and "required" rules.
func (p *Project) FindIneffectualConstraints(sm gps.SourceManager) []gps.ProjectRoot {
if p.Manifest == nil {
return nil
}
dd, err := p.GetDirectDependencyNames(sm)
if err != nil {
return nil
}
var ineff []gps.ProjectRoot
for pr := range p.Manifest.DependencyConstraints() {
if !dd[pr] {
ineff = append(ineff, pr)
}
}
sort.Slice(ineff, func(i, j int) bool {
return ineff[i] < ineff[j]
})
return ineff
}
// BackupVendor looks for existing vendor directory and if it's not empty,
// creates a backup of it to a new directory with the provided suffix.
func BackupVendor(vpath, suffix string) (string, error) {
// Check if there's a non-empty vendor directory
vendorExists, err := fs.IsNonEmptyDir(vpath)
if err != nil && !os.IsNotExist(err) {
return "", err
}
if vendorExists {
// vpath is a full filepath. We need to split it to prefix the backup dir
// with an "_"
vpathDir, name := filepath.Split(vpath)
vendorbak := filepath.Join(vpathDir, "_"+name+"-"+suffix)
// Check if a directory with same name exists
if _, err = os.Stat(vendorbak); os.IsNotExist(err) {
// Copy existing vendor to vendor-{suffix}
if err := fs.CopyDir(vpath, vendorbak); err != nil {
return "", err
}
return vendorbak, nil
}
return "", errVendorBackupFailed
}
return "", nil
}
| kargakis/test-infra | vendor/github.com/golang/dep/project.go | GO | apache-2.0 | 9,833 |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.io.MorePaths;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleSuccessType;
import com.facebook.buck.testutil.integration.BuckBuildLog;
import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.martiansoftware.nailgun.NGContext;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Map;
@RunWith(Parameterized.class)
public class CxxPreprocessAndCompileIntegrationTest {
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
return ImmutableList.of(
new Object[] {CxxPreprocessMode.COMBINED},
new Object[] {CxxPreprocessMode.SEPARATE},
new Object[] {CxxPreprocessMode.PIPED});
}
@Parameterized.Parameter
public CxxPreprocessMode mode;
@Rule
public DebuggableTemporaryFolder tmp = new DebuggableTemporaryFolder();
private ProjectWorkspace workspace;
@Before
public void setUp() throws IOException {
workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "step_test", tmp);
workspace.setUp();
workspace.writeContentsToPath(
"[cxx]\n" +
" preprocess_mode = " + mode.toString().toLowerCase() + "\n" +
" cppflags = -g\n" +
" cflags = -g\n" +
" cxxppflags = -g\n" +
" cxxflags = -g\n" +
"[build]\n" +
" depfiles = false\n",
".buckconfig");
}
@Test
public void sanitizeWorkingDirectory() throws IOException {
// TODO(user): Currently, we don't properly sanitize the working directory for the default
// platform when using the clang compiler.
assumeNotUsingSeparateOrPipedModesWithClang();
workspace.runBuckBuild("//:simple#default,static").assertSuccess();
Path lib = workspace.getPath("buck-out/gen/simple#default,static/libsimple.a");
String contents =
Files.asByteSource(lib.toFile())
.asCharSource(Charsets.ISO_8859_1)
.read();
assertFalse(lib.toString(), contents.contains(tmp.getRootPath().toString()));
}
@Test
public void sanitizeSymlinkedWorkingDirectory() throws IOException {
// TODO(user): Currently, we don't properly sanitize the working directory for the default
// platform when using the clang compiler.
assumeNotUsingSeparateOrPipedModesWithClang();
TemporaryFolder folder = new TemporaryFolder();
folder.create();
// Setup up a symlink to our working directory.
Path symlinkedRoot = folder.getRoot().toPath().resolve("symlinked-root");
java.nio.file.Files.createSymbolicLink(symlinkedRoot, tmp.getRootPath());
// Run the build, setting PWD to the above symlink. Typically, this causes compilers to use
// the symlinked directory, even though it's not the right project root.
Map<String, String> envCopy = Maps.newHashMap(System.getenv());
envCopy.put("PWD", symlinkedRoot.toString());
workspace.runBuckCommandWithEnvironmentAndContext(
tmp.getRootPath(),
Optional.<NGContext>absent(),
Optional.<BuckEventListener>absent(),
Optional.of(ImmutableMap.copyOf(envCopy)),
"build",
"//:simple#default,static")
.assertSuccess();
// Verify that we still sanitized this path correctly.
Path lib = workspace.getPath("buck-out/gen/simple#default,static/libsimple.a");
String contents =
Files.asByteSource(lib.toFile())
.asCharSource(Charsets.ISO_8859_1)
.read();
assertFalse(lib.toString(), contents.contains(tmp.getRootPath().toString()));
assertFalse(lib.toString(), contents.contains(symlinkedRoot.toString()));
folder.delete();
}
@Test
public void inputBasedRuleKeyAvoidsRerunningIfGeneratedSourceDoesNotChange() throws Exception {
CxxPlatform cxxPlatform = DefaultCxxPlatforms.build(new CxxBuckConfig(new FakeBuckConfig()));
BuildTarget target = BuildTargetFactory.newInstance("//:binary_using_generated_source");
String unusedGenruleInput = "unused.dat";
BuildTarget genrule = BuildTargetFactory.newInstance("//:gensource");
String sourceName = "bar.cpp";
CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of(target, cxxPlatform);
BuildTarget preprocessTarget =
cxxSourceRuleFactory.createPreprocessBuildTarget(
sourceName,
AbstractCxxSource.Type.CXX,
CxxSourceRuleFactory.PicType.PDC);
BuildTarget compileTarget =
cxxSourceRuleFactory.createCompileBuildTarget(
sourceName,
CxxSourceRuleFactory.PicType.PDC);
// Run the build and verify that the C++ source was (preprocessed and) compiled.
workspace.runBuckBuild(target.toString()).assertSuccess();
if (mode == CxxPreprocessMode.SEPARATE) {
assertThat(
workspace.getBuildLog().getLogEntry(preprocessTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
}
assertThat(
workspace.getBuildLog().getLogEntry(compileTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
// Now modify the unused genrule input.
workspace.writeContentsToPath(
"SOMETHING ELSE",
unusedGenruleInput);
// Run the build again and verify that got a matching input-based rule key, and therefore
// didn't recompile.
workspace.runBuckBuild(target.toString()).assertSuccess();
// Verify that the genrule actually re-ran.
assertThat(
workspace.getBuildLog().getLogEntry(genrule).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
// Verify that the (preprocess and) compile rules aren't re-run.
if (mode == CxxPreprocessMode.SEPARATE) {
assertThat(
workspace.getBuildLog().getLogEntry(preprocessTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY)));
}
assertThat(
workspace.getBuildLog().getLogEntry(compileTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY)));
}
@Test
public void inputBasedRuleKeyAvoidsRerunningIfGeneratedHeaderDoesNotChange() throws Exception {
CxxPlatform cxxPlatform = DefaultCxxPlatforms.build(new CxxBuckConfig(new FakeBuckConfig()));
BuildTarget target = BuildTargetFactory.newInstance("//:binary_using_generated_header");
String unusedGenruleInput = "unused.dat";
BuildTarget genrule = BuildTargetFactory.newInstance("//:genheader");
String sourceName = "foo.cpp";
CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of(target, cxxPlatform);
BuildTarget preprocessTarget =
cxxSourceRuleFactory.createPreprocessBuildTarget(
sourceName,
AbstractCxxSource.Type.CXX,
CxxSourceRuleFactory.PicType.PDC);
BuildTarget compileTarget =
cxxSourceRuleFactory.createCompileBuildTarget(
sourceName,
CxxSourceRuleFactory.PicType.PDC);
// Run the build and verify that the C++ source was (preprocessed and) compiled.
workspace.runBuckBuild(target.toString()).assertSuccess();
if (mode == CxxPreprocessMode.SEPARATE) {
assertThat(
workspace.getBuildLog().getLogEntry(preprocessTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
}
assertThat(
workspace.getBuildLog().getLogEntry(compileTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
// Now modify the unused genrule input.
workspace.writeContentsToPath(
"SOMETHING ELSE",
unusedGenruleInput);
// Run the build again and verify that got a matching input-based rule key, and therefore
// didn't recompile.
workspace.runBuckBuild(target.toString()).assertSuccess();
// Verify that the genrule actually re-ran.
assertThat(
workspace.getBuildLog().getLogEntry(genrule).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
// Verify that the (preprocess and) compile rules aren't re-run.
if (mode == CxxPreprocessMode.SEPARATE) {
assertThat(
workspace.getBuildLog().getLogEntry(preprocessTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY)));
}
assertThat(
workspace.getBuildLog().getLogEntry(compileTarget).getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY)));
}
@Test
public void inputBasedRuleKeyAvoidsRecompilingAfterChangeToUnusedHeader() throws Exception {
// This test is only meant to check the separate flow, as we want to avoid recompiling if only
// unused headers have changed.
assumeTrue(
"only tests \"separate\" preprocess mode",
mode == CxxPreprocessMode.SEPARATE);
CxxPlatform cxxPlatform = DefaultCxxPlatforms.build(new CxxBuckConfig(new FakeBuckConfig()));
BuildTarget target = BuildTargetFactory.newInstance("//:binary_with_unused_header");
CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of(target, cxxPlatform);
String unusedHeaderName = "unused_header.h";
String sourceName = "source.cpp";
BuildTarget compileTarget =
cxxSourceRuleFactory.createCompileBuildTarget(
sourceName,
CxxSourceRuleFactory.PicType.PDC);
// Run the build and verify that the C++ source was compiled.
workspace.runBuckBuild(target.toString());
BuckBuildLog.BuildLogEntry firstRunEntry = workspace.getBuildLog().getLogEntry(compileTarget);
assertThat(
firstRunEntry.getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
// Now modify the unused header.
workspace.writeContentsToPath(
"static inline int newFunction() { return 20; }",
unusedHeaderName);
// Run the build again and verify that got a matching input-based rule key, and therefore
// didn't recompile.
workspace.runBuckBuild(target.toString());
BuckBuildLog.BuildLogEntry secondRunEntry = workspace.getBuildLog().getLogEntry(compileTarget);
assertThat(
secondRunEntry.getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY)));
// Also, make sure the original rule keys are actually different.
assertThat(
secondRunEntry.getRuleKey(),
Matchers.not(Matchers.equalTo(firstRunEntry.getRuleKey())));
}
@Test
public void parentDirectoryReferenceInSource() throws IOException {
MorePaths.append(
workspace.getPath(".buckconfig"),
"\n[project]\n check_package_boundary = false\n",
UTF_8);
workspace.runBuckBuild("//parent_dir_ref:simple#default,static").assertSuccess();
}
public void assumeNotUsingSeparateOrPipedModesWithClang() {
assumeTrue(
Platform.detect() != Platform.MACOS ||
!ImmutableSet.of(CxxPreprocessMode.SEPARATE, CxxPreprocessMode.PIPED).contains(mode));
}
}
| hgl888/buck | test/com/facebook/buck/cxx/CxxPreprocessAndCompileIntegrationTest.java | Java | apache-2.0 | 12,907 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ql.querydsl.query;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate;
import org.elasticsearch.xpack.ql.tree.Source;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import static java.util.Map.entry;
public class MultiMatchQuery extends LeafQuery {
private static final Map<String, BiConsumer<MultiMatchQueryBuilder, String>> BUILDER_APPLIERS;
static {
// TODO: it'd be great if these could be constants instead of Strings, needs a core change to make the fields public first
BUILDER_APPLIERS = Map.ofEntries(
entry("slop", (qb, s) -> qb.slop(Integer.valueOf(s))),
// TODO: add zero terms query support, I'm not sure the best way to parse it yet...
// appliers.put("zero_terms_query", (qb, s) -> qb.zeroTermsQuery(s));
entry("analyzer", MultiMatchQueryBuilder::analyzer),
entry("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))),
entry("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))),
entry("fuzzy_rewrite", MultiMatchQueryBuilder::fuzzyRewrite),
entry("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))),
entry("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))),
entry("max_expansions", (qb, s) -> qb.maxExpansions(Integer.valueOf(s))),
entry("minimum_should_match", MultiMatchQueryBuilder::minimumShouldMatch),
entry("operator", (qb, s) -> qb.operator(Operator.fromString(s))),
entry("prefix_length", (qb, s) -> qb.prefixLength(Integer.valueOf(s))),
entry("tie_breaker", (qb, s) -> qb.tieBreaker(Float.valueOf(s))),
entry("type", MultiMatchQueryBuilder::type));
}
private final String query;
private final Map<String, Float> fields;
private final Map<String, String> options;
private final MultiMatchQueryPredicate predicate;
public MultiMatchQuery(Source source, String query, Map<String, Float> fields, MultiMatchQueryPredicate predicate) {
super(source);
this.query = query;
this.fields = fields;
this.predicate = predicate;
this.options = predicate.optionMap();
}
@Override
public QueryBuilder asBuilder() {
final MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(query);
queryBuilder.fields(fields);
queryBuilder.analyzer(predicate.analyzer());
options.forEach((k, v) -> {
if (BUILDER_APPLIERS.containsKey(k)) {
BUILDER_APPLIERS.get(k).accept(queryBuilder, v);
} else {
throw new IllegalArgumentException("illegal multi_match option [" + k + "]");
}
});
return queryBuilder;
}
@Override
public int hashCode() {
return Objects.hash(query, fields, predicate);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
MultiMatchQuery other = (MultiMatchQuery) obj;
return Objects.equals(query, other.query)
&& Objects.equals(fields, other.fields)
&& Objects.equals(predicate, other.predicate);
}
@Override
protected String innerToString() {
return fields + ":" + query;
}
}
| ern/elasticsearch | x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/querydsl/query/MultiMatchQuery.java | Java | apache-2.0 | 4,197 |
// -----------------------------------------------------------------------
// <copyright file="HttpMessageExtensions.cs" company="OSharp开源团队">
// Copyright (c) 2014-2015 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2015-10-09 0:40</last-date>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Routing;
using OSharp.Core;
using OSharp.Core.Dependency;
using OSharp.Core.Security;
using OSharp.Utility.Extensions;
namespace OSharp.Web.Http.Extensions
{
/// <summary>
///
/// </summary>
public static class HttpMessageExtensions
{
private const string HttpContextKey = "MS_HttpContext";
private const string OwinContextKey = "MS_OwinContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
/// <summary>
/// 返回请求<see cref="HttpRequestMessage"/>是否来自本地
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static bool IsLocal(this HttpRequestMessage request)
{
var localFlag = request.Properties["MS_IsLocal"] as Lazy<bool>;
return localFlag != null && localFlag.Value;
}
/// <summary>
/// 获取区域信息,如不存在则返回null
/// </summary>
public static string GetAreaName(this HttpRequestMessage request)
{
const string key = "area";
object value;
IHttpRouteData data = request.GetRouteData();
if (data.Route.DataTokens == null || data.Route.DataTokens.Count == 0)
{
if (data.Values.TryGetValue(key, out value))
{
return value.ToString();
}
return null;
}
return data.Route.DataTokens.TryGetValue(key, out value) ? value.ToString() : null;
}
/// <summary>
/// 获取当前执行的功能信息
/// </summary>
public static IFunction GetExecuteFunction(this HttpRequestMessage request, IServiceProvider provider)
{
const string key = Constants.CurrentWebApiFunctionKey;
IDictionary<string, object> items = request.Properties;
if (items.ContainsKey(key))
{
return (IFunction)items[key];
}
string area = request.GetAreaName();
string controller = request.GetControllerName();
string action = request.GetActionName();
IFunctionHandler handler = provider.GetService<IFunctionHandler>();
if (handler == null)
{
return null;
}
IFunction function = handler.GetFunction(area, controller, action);
if (function != null)
{
items.Add(key, function);
}
return function;
}
/// <summary>
/// 获取控制器名称
/// </summary>
public static string GetControllerName(this HttpRequestMessage request)
{
const string key = "controller";
object value;
IHttpRouteData data = request.GetRouteData();
if (data.Route.DataTokens == null || data.Route.DataTokens.Count == 0)
{
if (data.Values.TryGetValue(key, out value))
{
return value.ToString();
}
return null;
}
return data.Route.DataTokens.TryGetValue(key, out value) ? value.ToString() : null;
}
/// <summary>
/// 获取控制器名称
/// </summary>
public static string GetActionName(this HttpRequestMessage request)
{
const string key = "action";
object value;
IHttpRouteData data = request.GetRouteData();
if (data.Route.DataTokens == null || data.Route.DataTokens.Count == 0)
{
if (data.Values.TryGetValue(key, out value))
{
return value.ToString();
}
return null;
}
return data.Route.DataTokens.TryGetValue(key, out value) ? value.ToString() : null;
}
/// <summary>
/// 获取客户端IP
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContextKey))
{
dynamic ctx = request.Properties[HttpContextKey];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(OwinContextKey))
{
dynamic ctx = request.Properties[OwinContextKey];
if (ctx != null)
{
return ctx.Request.RemoteIpAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
/// <summary>
/// 将<see cref="HttpResponseMessage"/>使用<see cref="Task{}"/>来包装
/// </summary>
/// <param name="responseMessage"></param>
/// <returns></returns>
public static Task<HttpResponseMessage> ToTask(this HttpResponseMessage responseMessage)
{
TaskCompletionSource<HttpResponseMessage> taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
taskCompletionSource.SetResult(responseMessage);
return taskCompletionSource.Task;
}
/// <summary>
/// 获取<see cref="HttpResponseMessage"/>中包装的错误信息
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static string GetErrorMessage(this HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
string msg = "请求处理失败";
switch (response.StatusCode)
{
case HttpStatusCode.NotFound:
msg = "请求的资源不存在";
break;
case HttpStatusCode.BadRequest:
msg = "请求中止";
break;
case HttpStatusCode.Forbidden:
msg = "请求被拒绝";
break;
case HttpStatusCode.ServiceUnavailable:
msg = "服务器忙或停机维护";
break;
}
MediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
if (contentType == null || contentType.MediaType != "text/html")
{
HttpError error = response.Content.ReadAsAsync<HttpError>().Result;
if (error != null)
{
string errorMsg = error.Message;
if (errorMsg.Contains("An error has occurred"))
{
#if NET45
errorMsg = error.ExceptionMessage;
#else
errorMsg = "请求处理发生错误";
#endif
}
msg = "{0},详情:{1}".FormatWith(msg, errorMsg);
}
}
return msg;
}
return null;
}
}
} | vebin/osharp-1 | src/OSharp.Web.WebApi/Extensions/HttpMessageExtensions.cs | C# | apache-2.0 | 8,265 |
package fs
import (
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/cgroups/fscommon"
"github.com/opencontainers/runc/libcontainer/configs"
)
type RdmaGroup struct{}
func (s *RdmaGroup) Name() string {
return "rdma"
}
func (s *RdmaGroup) Apply(path string, _ *configs.Resources, pid int) error {
return apply(path, pid)
}
func (s *RdmaGroup) Set(path string, r *configs.Resources) error {
return fscommon.RdmaSet(path, r)
}
func (s *RdmaGroup) GetStats(path string, stats *cgroups.Stats) error {
return fscommon.RdmaGetStats(path, stats)
}
| opencontainers/runc | libcontainer/cgroups/fs/rdma.go | GO | apache-2.0 | 604 |
class Hdf5 < Formula
desc "File format designed to store large amounts of data"
homepage "https://www.hdfgroup.org/HDF5"
url "https://www.hdfgroup.org/package/source-bzip2/?wpdmdl=4300"
mirror "https://dl.bintray.com/homebrew/mirror/hdf5-1.10.1"
version "1.10.1"
sha256 "9c5ce1e33d2463fb1a42dd04daacbc22104e57676e2204e3d66b1ef54b88ebf2"
revision 2
bottle do
rebuild 1
sha256 "ce60d6ad246ecf8baae4e007a359da7c1cae8c3e199a2f9422f601fb0dc50e03" => :high_sierra
sha256 "13fb989ccd1ce01a88be9159d15afd1898e7d358e7f338fec8542cef1204903c" => :sierra
sha256 "fffbe4774667aa473e7ab6b004dea0247b98fab63ae7581b70ea129b6092c369" => :el_capitan
end
option "with-mpi", "Enable parallel support"
deprecated_option "enable-parallel" => "with-mpi"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "gcc" # for gfortran
depends_on "open-mpi" if build.with? "mpi"
depends_on "szip"
def install
inreplace %w[c++/src/h5c++.in fortran/src/h5fc.in tools/src/misc/h5cc.in],
"${libdir}/libhdf5.settings", "#{pkgshare}/libhdf5.settings"
inreplace "src/Makefile.am", "settingsdir=$(libdir)", "settingsdir=#{pkgshare}"
system "autoreconf", "-fiv"
args = %W[
--disable-dependency-tracking
--disable-silent-rules
--prefix=#{prefix}
--with-szlib=#{Formula["szip"].opt_prefix}
--enable-build-mode=production
--enable-fortran
]
if build.without?("mpi")
args << "--enable-cxx"
else
args << "--disable-cxx"
end
if build.with? "mpi"
ENV["CC"] = "mpicc"
ENV["CXX"] = "mpicxx"
ENV["FC"] = "mpif90"
args << "--enable-parallel"
end
system "./configure", *args
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <stdio.h>
#include "hdf5.h"
int main()
{
printf("%d.%d.%d\\n", H5_VERS_MAJOR, H5_VERS_MINOR, H5_VERS_RELEASE);
return 0;
}
EOS
system "#{bin}/h5cc", "test.c"
assert_equal version.to_s, shell_output("./a.out").chomp
(testpath/"test.f90").write <<~EOS
use hdf5
integer(hid_t) :: f, dspace, dset
integer(hsize_t), dimension(2) :: dims = [2, 2]
integer :: error = 0, major, minor, rel
call h5open_f (error)
if (error /= 0) call abort
call h5fcreate_f ("test.h5", H5F_ACC_TRUNC_F, f, error)
if (error /= 0) call abort
call h5screate_simple_f (2, dims, dspace, error)
if (error /= 0) call abort
call h5dcreate_f (f, "data", H5T_NATIVE_INTEGER, dspace, dset, error)
if (error /= 0) call abort
call h5dclose_f (dset, error)
if (error /= 0) call abort
call h5sclose_f (dspace, error)
if (error /= 0) call abort
call h5fclose_f (f, error)
if (error /= 0) call abort
call h5close_f (error)
if (error /= 0) call abort
CALL h5get_libversion_f (major, minor, rel, error)
if (error /= 0) call abort
write (*,"(I0,'.',I0,'.',I0)") major, minor, rel
end
EOS
system "#{bin}/h5fc", "test.f90"
assert_equal version.to_s, shell_output("./a.out").chomp
end
end
| ylluminarious/homebrew-core | Formula/hdf5.rb | Ruby | bsd-2-clause | 3,217 |
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, Ravi Sharma
#
# Distributed under the terms of the Lesser GNU General Public License (LGPL)
#-----------------------------------------------------------------------------
'''
Created on Jan 15, 2014
@author: Ravi Sharma
'''
from lxml import etree
from kayako.core.lib import UnsetParameter
from kayako.core.object import KayakoObject
from kayako.exception import KayakoRequestError, KayakoResponseError
class KnowledgebaseCategory(KayakoObject):
'''
Knowledgebase Category API Object.
title The title of the Category.
categorytype Category type. Global: 1, public: 2, private:3, inherit: 4.
parentkbcategoryid The parent category ID.
displayorder A positive integer that the helpdesk will use to sort Category when displaying them (ascending).
articlesortorder A article sort order. Sort inherti: 1, sort title: 2, sort rating: 3, sort creationdate: 4, sort displayorder: 5 .
allowcomments 1 or 0 boolean that controls whether or not to Allow comments of this category.
allowrating 1 or 0 boolean that controls whether or not to Allow rating of this category.
ispublished Toggle the published yes/no property using this flag.
uservisibilitycustom 1 or 0 boolean that controls whether or not to restrict visibility of this category to particular user groups.
usergroupidlist A list of usergroup id's identifying the user groups to be assigned to this category (see usergroupidlist[]).
staffvisibilitycustom Toggle the staff visibility custom yes/no property using this flag.
staffgroupidlist The staff group ID list. Multiple values can be comma separated like 1,2,3.
staffid The creator staff ID.
'''
controller = '/Knowledgebase/Category'
__parameters__ = ['id', 'title', 'categorytype', 'parentkbcategoryid', 'displayorder', 'totalarticles', 'articlesortorder', 'allowcomments', 'allowrating', 'ispublished', 'uservisibilitycustom',
'usergroupidlist', 'staffvisibilitycustom', 'staffgroupidlist', 'staffid']
__required_add_parameters__ = ['title', 'categorytype']
__add_parameters__ = ['id', 'title', 'categorytype', 'parentkbcategoryid', 'displayorder', 'articlesortorder', 'allowcomments', 'allowrating', 'ispublished', 'uservisibilitycustom',
'usergroupidlist', 'staffvisibilitycustom', 'staffgroupidlist', 'staffid']
__required_save_parameters__ = ['title', 'categorytype']
__save_parameters__ = ['id', 'title', 'categorytype', 'parentkbcategoryid', 'displayorder', 'articlesortorder', 'allowcomments', 'allowrating', 'ispublished', 'uservisibilitycustom',
'usergroupidlist', 'staffvisibilitycustom', 'staffgroupidlist', 'staffid']
@classmethod
def _parse_knowledgebase_category(cls, api, _parse_knowledgebase_category):
usergroups = []
usergroups_node = _parse_knowledgebase_category.find('usergroupidlist')
if usergroups_node is not None:
for id_node in usergroups_node.findall('usergroupid'):
id = cls._get_int(id_node)
usergroups.append(id)
staffgroups = []
staffgroups_node = _parse_knowledgebase_category.find('staffgroupidlist')
if staffgroups_node is not None:
for id_node in staffgroups_node.findall('staffgroupid'):
id = cls._get_int(id_node)
staffgroups.append(id)
params = dict(
id=cls._get_int(_parse_knowledgebase_category.find('id')),
parentkbcategoryid=cls._get_int(_parse_knowledgebase_category.find('parentkbcategoryid')),
staffid=cls._get_int(_parse_knowledgebase_category.find('staffid')),
title=cls._get_string(_parse_knowledgebase_category.find('title')),
totalarticles=cls._get_int(_parse_knowledgebase_category.find('totalarticles')),
categorytype=cls._get_int(_parse_knowledgebase_category.find('categorytype')),
displayorder=cls._get_int(_parse_knowledgebase_category.find('displayorder')),
allowcomments=cls._get_boolean(_parse_knowledgebase_category.find('allowcomments')),
uservisibilitycustom=cls._get_boolean(_parse_knowledgebase_category.find('uservisibilitycustom')),
usergroupidlist=usergroups,
staffvisibilitycustom=cls._get_boolean(_parse_knowledgebase_category.find('staffvisibilitycustom')),
staffgroupidlist=staffgroups,
allowrating=cls._get_boolean(_parse_knowledgebase_category.find('allowrating')),
ispublished=cls._get_boolean(_parse_knowledgebase_category.find('ispublished')),
)
return params
def _update_from_response(self, _parse_knowledgebase_category):
usergroups_node = _parse_knowledgebase_category.find('usergroupidlist')
if usergroups_node is not None:
usergroups = []
for id_node in usergroups_node.findall('usergroupid'):
id = self._get_int(id_node)
usergroups.append(id)
self.usergroupidlist = usergroups
for int_node in ['id', 'categorytype', 'parentkbcategoryid', 'displayorder', 'articlesortorder', 'uservisibilitycustom', 'staffid']:
node = _parse_knowledgebase_category.find(int_node)
if node is not None:
setattr(self, int_node, self._get_int(node, required=False))
for str_node in ['title', 'staffvisibilitycustom']:
node = _parse_knowledgebase_category.find(str_node)
if node is not None:
setattr(self, str_node, self._get_string(node))
for bool_node in ['allowcomments', 'allowrating', 'ispublished']:
node = _parse_knowledgebase_category.find(bool_node)
if node is not None:
setattr(self, bool_node, self._get_boolean(node, required=False))
@classmethod
def get_all(cls, api, count=100, start=0):
response = api._request('%s/ListAll/%s/%s/' % (cls.controller, count, start), 'GET')
tree = etree.parse(response)
return [KnowledgebaseCategory(api, **cls._parse_knowledgebase_category(api, _parse_knowledgebase_category)) for _parse_knowledgebase_category in tree.findall('kbcategory')]
@classmethod
def get(cls, api, id):
response = api._request('%s/%s/' % (cls.controller, id), 'GET')
tree = etree.parse(response)
node = tree.find('kbcategory')
if node is None:
return None
params = cls._parse_knowledgebase_category(api, node)
return KnowledgebaseCategory(api, **params)
def add(self):
response = self._add(self.controller)
tree = etree.parse(response)
node = tree.find('kbcategory')
self._update_from_response(node)
def save(self):
response = self._save('%s/%s/' % (self.controller, self.id))
tree = etree.parse(response)
node = tree.find('kbcategory')
self._update_from_response(node)
def delete(self):
self._delete('%s/%s/' % (self.controller, self.id))
def __str__(self):
return '<KnowledgebaseCategory (%s): %s>' % (self.id, self.title) | sahilsehgal81/python-api-library | src/kayako/objects/knowledgebase/knowledgebase_category.py | Python | bsd-2-clause | 6,763 |
"""
Comparison of Lomb-Scargle Methods
----------------------------------
This shows a comparison of the Lomb-Scargle periodogram
and the Modified Lomb-Scargle periodogram for a single star,
along with the multi-term results.
"""
# Author: Jake VanderPlas
# License: BSD
# The figure produced by this code is published in the textbook
# "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
# For more information, see http://astroML.github.com
# To report a bug or issue, use the following forum:
# https://groups.google.com/forum/#!forum/astroml-general
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
from astroML.time_series import\
lomb_scargle, search_frequencies, multiterm_periodogram
from astroML.datasets import fetch_LINEAR_sample
#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX. This may
# result in an error if LaTeX is not installed on your system. In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
#id, period = 11375941, 58.4
id, period = 18525697, 17.05
data = fetch_LINEAR_sample()
t, y, dy = data[id].T
omega = np.linspace(period, period + 0.1, 1000)
fig = plt.figure(figsize=(5, 3.75))
ax = plt.subplot(211)
for n_terms in [1, 2, 3]:
P1 = multiterm_periodogram(t, y, dy, omega, n_terms=n_terms)
plt.plot(omega, P1, lw=1, label='m = %i' % n_terms)
plt.legend(loc=2)
plt.xlim(period, period + 0.1)
plt.ylim(0, 1.0)
plt.ylabel('$1 - \chi^2(\omega) / \chi^2_{ref}$')
plt.subplot(212, sharex=ax)
for generalized in [True, False]:
if generalized:
label = 'generalized LS'
else:
label = 'standard LS'
P2 = lomb_scargle(t, y, dy, omega, generalized=generalized)
plt.plot(omega, P2, lw=1, label=label)
plt.legend(loc=2)
plt.xlim(period, period + 0.1)
plt.ylim(0, 1.0)
plt.xlabel('frequency $\omega$')
plt.ylabel('$P_{LS}(\omega)$')
plt.show()
| nhuntwalker/astroML | book_figures/chapter10/fig_LS_comparison.py | Python | bsd-2-clause | 2,128 |
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where `Hash#merge!` can be replaced by
# `Hash#[]=`.
# You can set the maximum number of key-value pairs to consider
# an offense with `MaxKeyValuePairs`.
#
# @example
# # bad
# hash.merge!(a: 1)
# hash.merge!({'key' => 'value'})
#
# # good
# hash[:a] = 1
# hash['key'] = 'value'
#
# @example MaxKeyValuePairs: 2 (default)
# # bad
# hash.merge!(a: 1, b: 2)
#
# # good
# hash[:a] = 1
# hash[:b] = 2
class RedundantMerge < Base
extend AutoCorrector
AREF_ASGN = '%<receiver>s[%<key>s] = %<value>s'
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[merge!].freeze
WITH_MODIFIER_CORRECTION = <<~RUBY
%<keyword>s %<condition>s
%<leading_space>s%<indent>s%<body>s
%<leading_space>send
RUBY
def_node_matcher :redundant_merge_candidate, <<~PATTERN
(send $!nil? :merge! [(hash $...) !kwsplat_type?])
PATTERN
def_node_matcher :modifier_flow_control?, <<~PATTERN
[{if while until} modifier_form?]
PATTERN
def on_send(node)
each_redundant_merge(node) do |redundant_merge_node|
message = message(node)
add_offense(redundant_merge_node, message: message) do |corrector|
redundant_merge_candidate(node) do |receiver, pairs|
new_source = to_assignments(receiver, pairs).join("\n")
if node.parent && pairs.size > 1
correct_multiple_elements(corrector, node, node.parent, new_source)
else
correct_single_element(corrector, node, new_source)
end
end
end
end
end
private
def message(node)
redundant_merge_candidate(node) do |receiver, pairs|
assignments = to_assignments(receiver, pairs).join('; ')
format(MSG, prefer: assignments, current: node.source)
end
end
def each_redundant_merge(node)
redundant_merge_candidate(node) do |receiver, pairs|
next if non_redundant_merge?(node, receiver, pairs)
yield node
end
end
def non_redundant_merge?(node, receiver, pairs)
pairs.empty? ||
non_redundant_pairs?(receiver, pairs) ||
kwsplat_used?(pairs) ||
non_redundant_value_used?(receiver, node)
end
def non_redundant_pairs?(receiver, pairs)
pairs.size > 1 && !receiver.pure? || pairs.size > max_key_value_pairs
end
def kwsplat_used?(pairs)
pairs.any?(&:kwsplat_type?)
end
def non_redundant_value_used?(receiver, node)
node.value_used? &&
!EachWithObjectInspector.new(node, receiver).value_used?
end
def correct_multiple_elements(corrector, node, parent, new_source)
if modifier_flow_control?(parent)
new_source = rewrite_with_modifier(node, parent, new_source)
node = parent
else
padding = "\n#{leading_spaces(node)}"
new_source.gsub!(/\n/, padding)
end
corrector.replace(node.source_range, new_source)
end
def correct_single_element(corrector, node, new_source)
corrector.replace(node.source_range, new_source)
end
def to_assignments(receiver, pairs)
pairs.map do |pair|
key, value = *pair
key = key.sym_type? && pair.colon? ? ":#{key.source}" : key.source
format(AREF_ASGN, receiver: receiver.source,
key: key,
value: value.source)
end
end
def rewrite_with_modifier(node, parent, new_source)
indent = ' ' * indent_width
padding = "\n#{indent + leading_spaces(node)}"
new_source.gsub!(/\n/, padding)
format(WITH_MODIFIER_CORRECTION, keyword: parent.loc.keyword.source,
condition: parent.condition.source,
leading_space: leading_spaces(node),
indent: indent,
body: new_source).chomp
end
def leading_spaces(node)
node.source_range.source_line[/\A\s*/]
end
def indent_width
@config.for_cop('Layout/IndentationWidth')['Width'] || 2
end
def max_key_value_pairs
Integer(cop_config['MaxKeyValuePairs'] || 2)
end
# A utility class for checking the use of values within an
# `each_with_object` call.
class EachWithObjectInspector
extend NodePattern::Macros
def initialize(node, receiver)
@node = node
@receiver = unwind(receiver)
end
def value_used?
return false unless eligible_receiver? && second_argument
receiver.loc.name.source == second_argument.loc.name.source
end
private
attr_reader :node, :receiver
def eligible_receiver?
receiver.respond_to?(:lvar_type?) && receiver.lvar_type?
end
def second_argument
parent = node.parent
parent = parent.parent if parent.begin_type?
@second_argument ||= each_with_object_node(parent)
end
def unwind(receiver)
receiver, = *receiver while receiver.respond_to?(:send_type?) && receiver.send_type?
receiver
end
def_node_matcher :each_with_object_node, <<~PATTERN
(block (send _ :each_with_object _) (args _ $_) ...)
PATTERN
end
end
end
end
end
| konqui/brew | Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/rubocop-performance-1.9.1/lib/rubocop/cop/performance/redundant_merge.rb | Ruby | bsd-2-clause | 6,079 |
cask :v1 => 'macdrops' do
version '1.1'
sha256 'c91f10418d8dd88f395603f9b824fc1ef319ec91affe2326cff5bce7f2bd63bb'
url "http://interfacelift.com/apps/macdrops/v1/Macdrops_v#{version}.dmg"
homepage 'http://interfacelift.com/apps/macdrops/v1'
license :unknown # todo: improve this machine-generated value
app "Macdrops v#{version}.app"
end
| andyshinn/homebrew-cask | Casks/macdrops.rb | Ruby | bsd-2-clause | 354 |
class Gocr < Formula
desc "Optical Character Recognition (OCR), converts images back to text"
homepage "https://wasd.urz.uni-magdeburg.de/jschulen/ocr/"
url "https://wasd.urz.uni-magdeburg.de/jschulen/ocr/gocr-0.52.tar.gz"
sha256 "df906463105f5f4273becc2404570f187d4ea52bd5769d33a7a8661a747b8686"
revision 1
livecheck do
url "https://wasd.urz.uni-magdeburg.de/jschulen/ocr/download.html"
regex(%r{href=(?:["']?|.*?/)gocr[._-]v?(\d+(?:\.\d+)+)\.t}i)
end
bottle do
sha256 cellar: :any, arm64_big_sur: "a3639ecb89f70562106db696e43f8ccdbe770b812ba2cdc695637b5f8e8dba7f"
sha256 cellar: :any, big_sur: "e2fecccba7638297e89075dd8a21bf64d124a9f4f341f2437411abadf90b1f33"
sha256 cellar: :any, catalina: "d0408f223b941c6d81c0edd843ab5916475a4ea4b94892b548da6403e4c3af2a"
sha256 cellar: :any, mojave: "d173d60e8d8f139b4e7e310b84d1bfc56e406eb026c51beba9d4b2facaac3ae1"
sha256 cellar: :any, high_sierra: "2a5cfa5a815706b2ecb11658ad9132bba21de5304e4541118d8d061a5bb7779a"
end
depends_on "jpeg"
depends_on "netpbm"
# Edit makefile to install libs per developer documentation
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/85fa66a9/gocr/0.50.patch"
sha256 "0ed4338c3233a8d1d165f687d6cbe6eee3d393628cdf711a4f8f06b5edc7c4dc"
end
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}"
# --mandir doesn't work correctly; fix broken Makefile
inreplace "man/Makefile" do |s|
s.change_make_var! "mandir", "/share/man"
end
system "make", "libs"
system "make", "install"
end
test do
system "#{bin}/gocr", "--help"
end
end
| JCount/homebrew-core | Formula/gocr.rb | Ruby | bsd-2-clause | 1,761 |
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\UserSettings\Columns;
use Piwik\Common;
use Piwik\Plugin\Dimension\VisitDimension;
use Piwik\Tracker\Request;
use Piwik\Tracker\Visitor;
use Piwik\Tracker\Action;
class PluginSilverlight extends VisitDimension
{
protected $columnName = 'config_silverlight';
protected $columnType = 'TINYINT(1) NOT NULL';
/**
* @param Request $request
* @param Visitor $visitor
* @param Action|null $action
* @return mixed
*/
public function onNewVisit(Request $request, Visitor $visitor, $action)
{
return Common::getRequestVar('ag', 0, 'int', $request->getParams());
}
} | KingNoosh/Teknik | stats/plugins/UserSettings/Columns/PluginSilverlight.php | PHP | bsd-3-clause | 795 |
// nnet2bin/nnet-am-shrink.cc
// Copyright 2012 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "hmm/transition-model.h"
#include "nnet2/shrink-nnet.h"
#include "nnet2/am-nnet.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using namespace kaldi::nnet2;
typedef kaldi::int32 int32;
typedef kaldi::int64 int64;
const char *usage =
"Using a validation set, compute optimal scaling parameters for each\n"
"class of neural network parameters (i.e. each updatable component), "
"to\n"
"maximize validation-set objective function.\n"
"\n"
"Usage: nnet-am-shrink [options] <model-in> <valid-examples-in> "
"<model-out>\n"
"\n"
"e.g.:\n"
" nnet-am-shrink 1.nnet ark:valid.egs 2.nnet\n";
bool binary_write = true;
NnetShrinkConfig shrink_config;
ParseOptions po(usage);
po.Register("binary", &binary_write, "Write output in binary mode");
shrink_config.Register(&po);
po.Read(argc, argv);
if (po.NumArgs() != 3) {
po.PrintUsage();
exit(1);
}
std::string nnet_rxfilename = po.GetArg(1),
valid_examples_rspecifier = po.GetArg(2),
nnet_wxfilename = po.GetArg(3);
TransitionModel trans_model;
AmNnet am_nnet;
{
bool binary_read;
Input ki(nnet_rxfilename, &binary_read);
trans_model.Read(ki.Stream(), binary_read);
am_nnet.Read(ki.Stream(), binary_read);
}
std::vector<NnetExample> validation_set; // stores validation
// frames.
{ // This block adds samples to "validation_set".
SequentialNnetExampleReader example_reader(valid_examples_rspecifier);
for (; !example_reader.Done(); example_reader.Next())
validation_set.push_back(example_reader.Value());
KALDI_LOG << "Read " << validation_set.size() << " examples from the "
<< "validation set.";
KALDI_ASSERT(validation_set.size() > 0);
}
ShrinkNnet(shrink_config, validation_set, &(am_nnet.GetNnet()));
{
Output ko(nnet_wxfilename, binary_write);
trans_model.Write(ko.Stream(), binary_write);
am_nnet.Write(ko.Stream(), binary_write);
}
KALDI_LOG << "Finished shrinking neural net, wrote model to "
<< nnet_wxfilename;
return (validation_set.size() == 0 ? 1 : 0);
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return -1;
}
}
| ypkang/djinn | tonic-suite/asr/src/nnet2bin/nnet-am-shrink.cc | C++ | bsd-3-clause | 3,229 |
module Intrigue
module Handler
class Base
def self.inherited(base)
HandlerFactory.register(base)
end
end
end
end
| CaledoniaProject/intrigue-core | lib/handlers/base.rb | Ruby | bsd-3-clause | 133 |
/*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.orchestration;
public final class BaseOrchestrationContextBuilder implements OrchestrationContextBuilder {
private OrchestrationStrategy strategy;
private OutboundOrchestratable message;
public OrchestrationContextBuilder setStrategy(OrchestrationStrategy strategy) {
this.strategy = strategy;
return this;
}
public OrchestrationStrategy getStrategy() {
return strategy;
}
public OrchestrationContextBuilder setMessage(OutboundOrchestratable message) {
this.message = message;
return this;
}
public OutboundOrchestratable getMessage() {
return message;
}
/*
* (non-Javadoc)
*
* @see gov.hhs.fha.nhinc.orchestration.OrchestraionContextBuilder#build()
*/
@Override
public OrchestrationContext build() {
return new OrchestrationContext(getStrategy(), getMessage());
}
}
| alameluchidambaram/CONNECT | Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/orchestration/BaseOrchestrationContextBuilder.java | Java | bsd-3-clause | 2,628 |
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
module egret.gui {
/**
* @classdesc
* HScrollBar(水平 ScrollBar)控件可以在因数据太多而不能在显示区域中以水平方向完全显示时控制显示的数据部分。
尽管可以使用 HScrollBar 控件作为独立控件,但通常将其结合作为另一组组件的一部分来提供滚动功能
*/
export class HScrollBar extends HSlider {
private _thumbLengthRatio = 1;
/**
*
* @param width
* @param contentWidth
* @private
*/
public _setViewportMetric(width:number, contentWidth:number) {
var max = Math.max(0, contentWidth - width);
this._setMaximun(max);
this._setMinimun(0);
this._thumbLengthRatio = (contentWidth > width) ? width / contentWidth : 1;
}
/**
* @deprecated
*/
public set trackAlpha(value:number){
$warn(1016, "HScrollBar.trackAlpha");
}
public get trackAlpha():number {
return 1;
}
/**
* @deprecated
*/
public set thumbAlpha(value: number) {
$warn(1016, "HScrollBar.thumbAlpha");
}
public get thumbAlpha():number {
return 1;
}
public setPosition(value: number) {
this._setValue(value);
}
public getPosition() {
return this._getValue();
}
/**
*
* @param value
* @private
*/
public _setValue(value: number) {
value = Math.max(0, value);
super._setValue(value);
}
/**
* [覆盖] 更新 value 属性,并且如果 viewport 为非 null,则将其 horizontalScrollPosition 设置为 value
* @param value
*/
public setValue(value: number) {
super.setValue(value);
}
/**
*
* @param animation
* @private
*/
public _animationUpdateHandler(animation: Animation): void {
this.pendingValue = animation.currentValue["value"];
this.value = animation.currentValue["value"];
this.dispatchEventWith(Event.CHANGE);
}
/**
* 设置外观部件的边界,这些外观部件的几何图形不是完全由外观的布局指定的
*/
public updateSkinDisplayList(): void {
if (!this.thumb || !this.track)
return;
var thumbWidth = this.track.layoutBoundsWidth * this._thumbLengthRatio;
var oldThumbWidth: number = this.thumb.layoutBoundsWidth;
var thumbRange: number = this.track.layoutBoundsWidth - this.thumb.layoutBoundsWidth;
var range: number = this.maximum - this.minimum;
var thumbPosTrackX: number = (range > 0) ? ((this.pendingValue - this.minimum) / range) * thumbRange : 0;
var thumbPos: Point = this.track.localToGlobal(thumbPosTrackX, 0);
var thumbPosX: number = thumbPos.x;
var thumbPosY: number = thumbPos.y;
var thumbPosParentX: number = this.thumb.parent.globalToLocal(thumbPosX, thumbPosY, Point.identity).x;
this.thumb.setLayoutBoundsPosition(Math.round(thumbPosParentX), this.thumb.layoutBoundsY);
if (thumbWidth != oldThumbWidth)
this.thumb.setLayoutBoundsSize(thumbWidth, this.thumb.layoutBoundsHeight);
}
}
} | wisdomsword/egret-core | src/extension/gui/components/HScrollBar.ts | TypeScript | bsd-3-clause | 5,400 |
from twisted.internet.defer import inlineCallbacks
from txtwitter.tests.fake_twitter import FakeTwitter
from vumi.tests.utils import LogCatcher
from vumi.tests.helpers import VumiTestCase
from vumi.config import Config
from vumi.errors import ConfigError
from vumi.transports.twitter import (
ConfigTwitterEndpoints, TwitterTransport)
from vumi.transports.tests.helpers import TransportHelper
class TestTwitterEndpointsConfig(VumiTestCase):
def test_clean_no_endpoints(self):
class ToyConfig(Config):
endpoints = ConfigTwitterEndpoints("test endpoints")
self.assertRaises(ConfigError, ToyConfig, {'endpoints': {}})
def test_clean_same_endpoints(self):
class ToyConfig(Config):
endpoints = ConfigTwitterEndpoints("test endpoints")
self.assertRaises(ConfigError, ToyConfig, {'endpoints': {
'dms': 'default',
'tweets': 'default'
}})
class TestTwitterTransport(VumiTestCase):
@inlineCallbacks
def setUp(self):
self.twitter = FakeTwitter()
self.user = self.twitter.new_user('me', 'me')
self.client = self.twitter.get_client(self.user.id_str)
self.patch(
TwitterTransport, 'get_client', lambda *a, **kw: self.client)
self.tx_helper = self.add_helper(TransportHelper(TwitterTransport))
self.config = {
'screen_name': 'me',
'consumer_key': 'consumer1',
'consumer_secret': 'consumersecret1',
'access_token': 'token1',
'access_token_secret': 'tokensecret1',
'terms': ['arnold', 'the', 'term'],
'endpoints': {
'tweets': 'tweet_endpoint',
'dms': 'dm_endpoint'
}
}
self.transport = yield self.tx_helper.get_transport(self.config)
def test_config_endpoints_default(self):
del self.config['endpoints']
self.config['transport_name'] = 'twitter'
config = TwitterTransport.CONFIG_CLASS(self.config)
self.assertEqual(config.endpoints, {'tweets': 'default'})
@inlineCallbacks
def test_config_no_tracking_stream(self):
self.config['terms'] = []
transport = yield self.tx_helper.get_transport(self.config)
self.assertEqual(transport.track_stream, None)
@inlineCallbacks
def test_tracking_tweets(self):
someone = self.twitter.new_user('someone', 'someone')
tweet = self.twitter.new_tweet('arnold', someone.id_str)
[msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
self.assertEqual(msg['from_addr'], '@someone')
self.assertEqual(msg['to_addr'], 'NO_USER')
self.assertEqual(msg['content'], 'arnold')
self.assertEqual(
msg['transport_metadata'],
{'twitter': {'status_id': tweet.id_str}})
self.assertEqual(msg['helper_metadata'], {
'twitter': {
'in_reply_to_status_id': None,
'in_reply_to_screen_name': None,
'user_mentions': []
}
})
@inlineCallbacks
def test_tracking_reply_tweets(self):
someone = self.twitter.new_user('someone', 'someone')
someone_else = self.twitter.new_user('someone_else', 'someone_else')
tweet1 = self.twitter.new_tweet('@someone_else hello', someone.id_str)
tweet2 = self.twitter.new_tweet(
'@someone arnold', someone_else.id_str, reply_to=tweet1.id_str)
[msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
self.assertEqual(msg['from_addr'], '@someone_else')
self.assertEqual(msg['to_addr'], '@someone')
self.assertEqual(msg['content'], 'arnold')
self.assertEqual(
msg['transport_metadata'],
{'twitter': {'status_id': tweet2.id_str}})
self.assertEqual(msg['helper_metadata'], {
'twitter': {
'in_reply_to_status_id': tweet1.id_str,
'in_reply_to_screen_name': 'someone',
'user_mentions': [{
'id_str': someone.id_str,
'id': int(someone.id_str),
'indices': [0, 8],
'screen_name': someone.screen_name,
'name': someone.name,
}]
}
})
def test_tracking_own_messages(self):
with LogCatcher() as lc:
tweet = self.twitter.new_tweet('arnold', self.user.id_str)
tweet = tweet.to_dict(self.twitter)
self.assertTrue(any(
"Tracked own tweet:" in msg for msg in lc.messages()))
@inlineCallbacks
def test_inbound_tweet(self):
someone = self.twitter.new_user('someone', 'someone')
tweet = self.twitter.new_tweet('@me hello', someone.id_str)
[msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
self.assertEqual(msg['from_addr'], '@someone')
self.assertEqual(msg['to_addr'], '@me')
self.assertEqual(msg['content'], 'hello')
self.assertEqual(msg.get_routing_endpoint(), 'tweet_endpoint')
self.assertEqual(
msg['transport_metadata'],
{'twitter': {'status_id': tweet.id_str}})
self.assertEqual(msg['helper_metadata'], {
'twitter': {
'in_reply_to_status_id': None,
'in_reply_to_screen_name': 'me',
'user_mentions': [{
'id_str': self.user.id_str,
'id': int(self.user.id_str),
'indices': [0, 3],
'screen_name': self.user.screen_name,
'name': self.user.name,
}]
}
})
@inlineCallbacks
def test_inbound_tweet_reply(self):
someone = self.twitter.new_user('someone', 'someone')
tweet1 = self.twitter.new_tweet('@someone hello', self.user.id_str)
tweet2 = self.twitter.new_tweet(
'@me goodbye', someone.id_str, reply_to=tweet1.id_str)
[msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
self.assertEqual(msg['from_addr'], '@someone')
self.assertEqual(msg['to_addr'], '@me')
self.assertEqual(msg['content'], 'goodbye')
self.assertEqual(
msg['transport_metadata'],
{'twitter': {'status_id': tweet2.id_str}})
self.assertEqual(msg['helper_metadata'], {
'twitter': {
'in_reply_to_status_id': tweet1.id_str,
'in_reply_to_screen_name': 'me',
'user_mentions': [{
'id_str': self.user.id_str,
'id': int(self.user.id_str),
'indices': [0, 3],
'screen_name': self.user.screen_name,
'name': self.user.name,
}]
}
})
def test_inbound_own_tweet(self):
with LogCatcher() as lc:
self.twitter.new_tweet('hello', self.user.id_str)
self.assertTrue(any(
"Received own tweet on user stream" in msg
for msg in lc.messages()))
@inlineCallbacks
def test_inbound_tweet_no_endpoint(self):
self.config['endpoints'] = {'dms': 'default'}
yield self.tx_helper.get_transport(self.config)
someone = self.twitter.new_user('someone', 'someone')
with LogCatcher() as lc:
self.twitter.new_tweet('@me hello', someone.id_str)
self.assertTrue(any(
"Discarding tweet received on user stream, no endpoint "
"configured for tweets" in msg
for msg in lc.messages()))
@inlineCallbacks
def test_inbound_dm(self):
someone = self.twitter.new_user('someone', 'someone')
dm = self.twitter.new_dm('hello @me', someone.id_str, self.user.id_str)
[msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
self.assertEqual(msg['from_addr'], '@someone')
self.assertEqual(msg['to_addr'], '@me')
self.assertEqual(msg['content'], 'hello @me')
self.assertEqual(msg.get_routing_endpoint(), 'dm_endpoint')
self.assertEqual(msg['helper_metadata'], {
'dm_twitter': {
'id': dm.id_str,
'user_mentions': [{
'id_str': self.user.id_str,
'id': int(self.user.id_str),
'indices': [6, 9],
'screen_name': self.user.screen_name,
'name': self.user.name,
}]
}
})
def test_inbound_own_dm(self):
with LogCatcher() as lc:
someone = self.twitter.new_user('someone', 'someone')
self.twitter.new_dm('hello', self.user.id_str, someone.id_str)
self.assertTrue(any(
"Received own DM on user stream" in msg
for msg in lc.messages()))
@inlineCallbacks
def test_inbound_dm_no_endpoint(self):
self.config['endpoints'] = {'tweets': 'default'}
yield self.tx_helper.get_transport(self.config)
someone = self.twitter.new_user('someone', 'someone')
with LogCatcher() as lc:
self.twitter.new_dm('hello @me', someone.id_str, self.user.id_str)
self.assertTrue(any(
"Discarding DM received on user stream, no endpoint "
"configured for DMs" in msg
for msg in lc.messages()))
@inlineCallbacks
def test_auto_following(self):
self.config['autofollow'] = True
yield self.tx_helper.get_transport(self.config)
with LogCatcher() as lc:
someone = self.twitter.new_user('someone', 'someone')
self.twitter.add_follow(someone.id_str, self.user.id_str)
self.assertTrue(any(
"Received follow on user stream" in msg
for msg in lc.messages()))
self.assertTrue(any(
"Auto-following '@someone'" in msg
for msg in lc.messages()))
follow = self.twitter.get_follow(self.user.id_str, someone.id_str)
self.assertEqual(follow.source_id, self.user.id_str)
self.assertEqual(follow.target_id, someone.id_str)
@inlineCallbacks
def test_auto_following_disabled(self):
self.config['autofollow'] = False
yield self.tx_helper.get_transport(self.config)
with LogCatcher() as lc:
someone = self.twitter.new_user('someone', 'someone')
self.twitter.add_follow(someone.id_str, self.user.id_str)
self.assertTrue(any(
"Received follow on user stream" in msg
for msg in lc.messages()))
follow = self.twitter.get_follow(self.user.id_str, someone.id_str)
self.assertTrue(follow is None)
def test_inbound_own_follow(self):
with LogCatcher() as lc:
someone = self.twitter.new_user('someone', 'someone')
self.twitter.add_follow(self.user.id_str, someone.id_str)
self.assertTrue(any(
"Received own follow on user stream" in msg
for msg in lc.messages()))
@inlineCallbacks
def test_tweet_sending(self):
self.twitter.new_user('someone', 'someone')
msg = yield self.tx_helper.make_dispatch_outbound(
'hello', to_addr='@someone', endpoint='tweet_endpoint')
[ack] = yield self.tx_helper.wait_for_dispatched_events(1)
self.assertEqual(ack['user_message_id'], msg['message_id'])
tweet = self.twitter.get_tweet(ack['sent_message_id'])
self.assertEqual(tweet.text, '@someone hello')
self.assertEqual(tweet.reply_to, None)
@inlineCallbacks
def test_tweet_reply_sending(self):
tweet1 = self.twitter.new_tweet(
'hello', self.user.id_str, endpoint='tweet_endpoint')
inbound_msg = self.tx_helper.make_inbound(
'hello',
from_addr='@someone',
endpoint='tweet_endpoint',
transport_metadata={
'twitter': {'status_id': tweet1.id_str}
})
msg = yield self.tx_helper.make_dispatch_reply(inbound_msg, "goodbye")
[ack] = yield self.tx_helper.wait_for_dispatched_events(1)
self.assertEqual(ack['user_message_id'], msg['message_id'])
tweet2 = self.twitter.get_tweet(ack['sent_message_id'])
self.assertEqual(tweet2.text, '@someone goodbye')
self.assertEqual(tweet2.reply_to, tweet1.id_str)
@inlineCallbacks
def test_tweet_sending_failure(self):
def fail(*a, **kw):
raise Exception(':(')
self.patch(self.client, 'statuses_update', fail)
with LogCatcher() as lc:
msg = yield self.tx_helper.make_dispatch_outbound(
'hello', endpoint='tweet_endpoint')
self.assertEqual(
[e['message'][0] for e in lc.errors],
["'Outbound twitter message failed: :('"])
[nack] = yield self.tx_helper.wait_for_dispatched_events(1)
self.assertEqual(nack['user_message_id'], msg['message_id'])
self.assertEqual(nack['sent_message_id'], msg['message_id'])
self.assertEqual(nack['nack_reason'], ':(')
@inlineCallbacks
def test_dm_sending(self):
self.twitter.new_user('someone', 'someone')
msg = yield self.tx_helper.make_dispatch_outbound(
'hello', to_addr='@someone', endpoint='dm_endpoint')
[ack] = yield self.tx_helper.wait_for_dispatched_events(1)
self.assertEqual(ack['user_message_id'], msg['message_id'])
dm = self.twitter.get_dm(ack['sent_message_id'])
sender = self.twitter.get_user(dm.sender_id_str)
recipient = self.twitter.get_user(dm.recipient_id_str)
self.assertEqual(dm.text, 'hello')
self.assertEqual(sender.screen_name, 'me')
self.assertEqual(recipient.screen_name, 'someone')
@inlineCallbacks
def test_dm_sending_failure(self):
def fail(*a, **kw):
raise Exception(':(')
self.patch(self.client, 'direct_messages_new', fail)
with LogCatcher() as lc:
msg = yield self.tx_helper.make_dispatch_outbound(
'hello', endpoint='dm_endpoint')
self.assertEqual(
[e['message'][0] for e in lc.errors],
["'Outbound twitter message failed: :('"])
[nack] = yield self.tx_helper.wait_for_dispatched_events(1)
self.assertEqual(nack['user_message_id'], msg['message_id'])
self.assertEqual(nack['sent_message_id'], msg['message_id'])
self.assertEqual(nack['nack_reason'], ':(')
def test_track_stream_for_non_tweet(self):
with LogCatcher() as lc:
self.transport.handle_track_stream({'foo': 'bar'})
self.assertEqual(
lc.messages(),
["Received non-tweet from tracking stream: {'foo': 'bar'}"])
def test_user_stream_for_unsupported_message(self):
with LogCatcher() as lc:
self.transport.handle_user_stream({'foo': 'bar'})
self.assertEqual(
lc.messages(),
["Received a user stream message that we do not handle: "
"{'foo': 'bar'}"])
def test_tweet_content_with_mention_at_start(self):
self.assertEqual('hello', self.transport.tweet_content({
'id_str': '12345',
'text': '@fakeuser hello',
'user': {},
'entities': {
'user_mentions': [{
'id_str': '123',
'screen_name': 'fakeuser',
'name': 'Fake User',
'indices': [0, 8]
}]
},
}))
def test_tweet_content_with_mention_not_at_start(self):
self.assertEqual('hello @fakeuser!', self.transport.tweet_content({
'id_str': '12345',
'text': 'hello @fakeuser!',
'user': {},
'entities': {
'user_mentions': [{
'id_str': '123',
'screen_name': 'fakeuser',
'name': 'Fake User',
'indices': [6, 14]
}]
},
}))
def test_tweet_content_with_no_mention(self):
self.assertEqual('hello', self.transport.tweet_content({
'id_str': '12345',
'text': 'hello',
'user': {},
'entities': {
'user_mentions': []
},
}))
def test_tweet_content_with_no_user_in_text(self):
self.assertEqual('NO_USER hello', self.transport.tweet_content({
'id_str': '12345',
'text': 'NO_USER hello',
'user': {},
'entities': {
'user_mentions': []
},
}))
| TouK/vumi | vumi/transports/twitter/tests/test_twitter.py | Python | bsd-3-clause | 16,928 |
/**
* this model contains information about the organization for
* the current user and the users who are inside the organizacion.
*
* Attributes:
*
* - users: collection with user instances whithin the organization (see cdb.admin.Organization.Users
*
*
*/
cdb.admin.Organization = cdb.core.Model.extend({
url: '/api/v1/org/',
initialize: function(attrs, opts) {
this.owner = new cdb.admin.User(this.get('owner'));
this.users = new cdb.admin.Organization.Users(
null, {
organizationId: this.id,
currentUserId: opts && opts.currentUserId
}
);
this.display_email = ((typeof attrs) != 'undefined' && attrs != null && (typeof attrs.admin_email) != 'undefined') && attrs.admin_email != null && (attrs.admin_email == '' ? this.owner.email : attrs.admin_email);
this.users.reset(this.get('users'));
// make sure all the users have a reference to this organization
var self = this;
this.users.each(function (u) {
u.organization = self;
});
},
fetch: function() {
throw new Error("organization should not be fetch, should be static");
},
containsUser: function(user) {
return !!this.users.find(function(u) {
return u.id === user.id;
})
},
viewUrl: function() {
return new cdb.common.OrganizationUrl({
base_url: this.get('base_url')
})
}
});
// helper to manage organization users
cdb.admin.Organization.Users = Backbone.Collection.extend({
model: cdb.admin.User,
params: {
per_page: 50,
page: 1,
order: 'username',
q: ''
},
url: function() {
if (!this.organizationId) {
throw new Error('Organization id is needed for fetching organization users');
}
var u = '/api/v1/organization/' + this.organizationId + '/users';
u += "?" + this._createUrlParameters();
return u;
},
initialize: function(users, opts) {
this.elder('initialize');
this.organizationId = opts.organizationId;
this.currentUserId = opts.currentUserId;
// Let's add abort behaviour
this.sync = Backbone.syncAbort;
},
comparator: function(mdl) {
return mdl.get('username');
},
_createUrlParameters: function() {
return _.compact(_(this.params).map(
function(v, k) {
return k + "=" + encodeURIComponent(v)
}
)).join('&');
},
parse: function(r) {
var self = this;
var users = _.map(r.users, function(user) {
if (user.id !== self.currentUserId) {
return user;
} else {
r.total_user_entries--;
r.total_entries--;
}
});
this.total_user_entries = r.total_user_entries;
this.total_entries = r.total_entries;
return _.compact(users);
},
fetch: function(opts) {
this.trigger('loading');
this.elder('fetch');
},
// Helper functions
setParameters: function(data) {
var self = this;
_.each(data, function(val, key) {
self.params[key] = val;
});
return this;
},
getParameter: function(key) {
return this.params[key]
},
getTotalUsers: function() {
return this.total_user_entries
},
getSearch: function() {
return this.getParameter('q')
}
});
| future-analytics/cartodb | lib/assets/javascripts/cartodb/models/organization.js | JavaScript | bsd-3-clause | 3,194 |
#!/usr/bin/env python
import os
import sys
import envdir
if __name__ == "__main__":
if 'test' in sys.argv:
env_dir = os.path.join('tests', 'envdir')
else:
env_dir = 'envdir'
envdir.read(os.path.join(os.path.dirname(__file__), env_dir))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| feedhq/feedhq | manage.py | Python | bsd-3-clause | 374 |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <list>
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"
#include "webrtc/modules/rtp_rtcp/source/fec_test_helper.h"
#include "webrtc/modules/rtp_rtcp/source/forward_error_correction.h"
#include "webrtc/modules/rtp_rtcp/source/producer_fec.h"
namespace webrtc {
void VerifyHeader(uint16_t seq_num,
uint32_t timestamp,
int red_pltype,
int fec_pltype,
RedPacket* packet,
bool marker_bit) {
EXPECT_GT(packet->length(), kRtpHeaderSize);
EXPECT_TRUE(packet->data() != NULL);
uint8_t* data = packet->data();
// Marker bit not set.
EXPECT_EQ(marker_bit ? 0x80 : 0, data[1] & 0x80);
EXPECT_EQ(red_pltype, data[1] & 0x7F);
EXPECT_EQ(seq_num, (data[2] << 8) + data[3]);
uint32_t parsed_timestamp = (data[4] << 24) + (data[5] << 16) +
(data[6] << 8) + data[7];
EXPECT_EQ(timestamp, parsed_timestamp);
EXPECT_EQ(static_cast<uint8_t>(fec_pltype), data[kRtpHeaderSize]);
}
class ProducerFecTest : public ::testing::Test {
protected:
virtual void SetUp() {
fec_ = new ForwardErrorCorrection();
producer_ = new ProducerFec(fec_);
generator_ = new FrameGenerator;
}
virtual void TearDown() {
delete producer_;
delete fec_;
delete generator_;
}
ForwardErrorCorrection* fec_;
ProducerFec* producer_;
FrameGenerator* generator_;
};
// Verifies bug found via fuzzing, where a gap in the packet sequence caused us
// to move past the end of the current FEC packet mask byte without moving to
// the next byte. That likely caused us to repeatedly read from the same byte,
// and if that byte didn't protect packets we would generate empty FEC.
TEST_F(ProducerFecTest, NoEmptyFecWithSeqNumGaps) {
struct Packet {
size_t header_size;
size_t payload_size;
uint16_t seq_num;
bool marker_bit;
};
std::vector<Packet> protected_packets;
protected_packets.push_back({15, 3, 41, 0});
protected_packets.push_back({14, 1, 43, 0});
protected_packets.push_back({19, 0, 48, 0});
protected_packets.push_back({19, 0, 50, 0});
protected_packets.push_back({14, 3, 51, 0});
protected_packets.push_back({13, 8, 52, 0});
protected_packets.push_back({19, 2, 53, 0});
protected_packets.push_back({12, 3, 54, 0});
protected_packets.push_back({21, 0, 55, 0});
protected_packets.push_back({13, 3, 57, 1});
FecProtectionParams params = {117, 0, 3, kFecMaskBursty};
producer_->SetFecParameters(¶ms, 0);
uint8_t packet[28] = {0};
for (Packet p : protected_packets) {
if (p.marker_bit) {
packet[1] |= 0x80;
} else {
packet[1] &= ~0x80;
}
ByteWriter<uint16_t>::WriteBigEndian(&packet[2], p.seq_num);
producer_->AddRtpPacketAndGenerateFec(packet, p.payload_size,
p.header_size);
uint16_t num_fec_packets = producer_->NumAvailableFecPackets();
std::vector<RedPacket*> fec_packets;
if (num_fec_packets > 0) {
fec_packets =
producer_->GetFecPackets(kRedPayloadType, 99, 100, p.header_size);
EXPECT_EQ(num_fec_packets, fec_packets.size());
}
for (RedPacket* fec_packet : fec_packets) {
delete fec_packet;
}
}
}
TEST_F(ProducerFecTest, OneFrameFec) {
// The number of media packets (|kNumPackets|), number of frames (one for
// this test), and the protection factor (|params->fec_rate|) are set to make
// sure the conditions for generating FEC are satisfied. This means:
// (1) protection factor is high enough so that actual overhead over 1 frame
// of packets is within |kMaxExcessOverhead|, and (2) the total number of
// media packets for 1 frame is at least |minimum_media_packets_fec_|.
const int kNumPackets = 4;
FecProtectionParams params = {15, false, 3};
std::list<RtpPacket*> rtp_packets;
generator_->NewFrame(kNumPackets);
producer_->SetFecParameters(¶ms, 0); // Expecting one FEC packet.
uint32_t last_timestamp = 0;
for (int i = 0; i < kNumPackets; ++i) {
RtpPacket* rtp_packet = generator_->NextPacket(i, 10);
rtp_packets.push_back(rtp_packet);
EXPECT_EQ(0, producer_->AddRtpPacketAndGenerateFec(rtp_packet->data,
rtp_packet->length,
kRtpHeaderSize));
last_timestamp = rtp_packet->header.header.timestamp;
}
EXPECT_TRUE(producer_->FecAvailable());
uint16_t seq_num = generator_->NextSeqNum();
std::vector<RedPacket*> packets = producer_->GetFecPackets(kRedPayloadType,
kFecPayloadType,
seq_num,
kRtpHeaderSize);
EXPECT_FALSE(producer_->FecAvailable());
ASSERT_EQ(1u, packets.size());
VerifyHeader(seq_num, last_timestamp,
kRedPayloadType, kFecPayloadType, packets.front(), false);
while (!rtp_packets.empty()) {
delete rtp_packets.front();
rtp_packets.pop_front();
}
delete packets.front();
}
TEST_F(ProducerFecTest, TwoFrameFec) {
// The number of media packets/frame (|kNumPackets|), the number of frames
// (|kNumFrames|), and the protection factor (|params->fec_rate|) are set to
// make sure the conditions for generating FEC are satisfied. This means:
// (1) protection factor is high enough so that actual overhead over
// |kNumFrames| is within |kMaxExcessOverhead|, and (2) the total number of
// media packets for |kNumFrames| frames is at least
// |minimum_media_packets_fec_|.
const int kNumPackets = 2;
const int kNumFrames = 2;
FecProtectionParams params = {15, 0, 3};
std::list<RtpPacket*> rtp_packets;
producer_->SetFecParameters(¶ms, 0); // Expecting one FEC packet.
uint32_t last_timestamp = 0;
for (int i = 0; i < kNumFrames; ++i) {
generator_->NewFrame(kNumPackets);
for (int j = 0; j < kNumPackets; ++j) {
RtpPacket* rtp_packet = generator_->NextPacket(i * kNumPackets + j, 10);
rtp_packets.push_back(rtp_packet);
EXPECT_EQ(0, producer_->AddRtpPacketAndGenerateFec(rtp_packet->data,
rtp_packet->length,
kRtpHeaderSize));
last_timestamp = rtp_packet->header.header.timestamp;
}
}
EXPECT_TRUE(producer_->FecAvailable());
uint16_t seq_num = generator_->NextSeqNum();
std::vector<RedPacket*> packets = producer_->GetFecPackets(kRedPayloadType,
kFecPayloadType,
seq_num,
kRtpHeaderSize);
EXPECT_FALSE(producer_->FecAvailable());
ASSERT_EQ(1u, packets.size());
VerifyHeader(seq_num, last_timestamp, kRedPayloadType, kFecPayloadType,
packets.front(), false);
while (!rtp_packets.empty()) {
delete rtp_packets.front();
rtp_packets.pop_front();
}
delete packets.front();
}
TEST_F(ProducerFecTest, BuildRedPacket) {
generator_->NewFrame(1);
RtpPacket* packet = generator_->NextPacket(0, 10);
rtc::scoped_ptr<RedPacket> red_packet(producer_->BuildRedPacket(
packet->data, packet->length - kRtpHeaderSize, kRtpHeaderSize,
kRedPayloadType));
EXPECT_EQ(packet->length + 1, red_packet->length());
VerifyHeader(packet->header.header.sequenceNumber,
packet->header.header.timestamp,
kRedPayloadType,
packet->header.header.payloadType,
red_packet.get(),
true); // Marker bit set.
for (int i = 0; i < 10; ++i)
EXPECT_EQ(i, red_packet->data()[kRtpHeaderSize + 1 + i]);
delete packet;
}
} // namespace webrtc
| aleonliao/webrtc-trunk | modules/rtp_rtcp/source/producer_fec_unittest.cc | C++ | bsd-3-clause | 8,274 |
from __future__ import division, absolute_import, print_function
import warnings
import numpy.core.numeric as _nx
from numpy.core.numeric import (
asarray, zeros, outer, concatenate, isscalar, array, asanyarray
)
from numpy.core.fromnumeric import product, reshape
from numpy.core import vstack, atleast_3d
__all__ = [
'column_stack', 'row_stack', 'dstack', 'array_split', 'split',
'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims',
'apply_along_axis', 'kron', 'tile', 'get_array_wrap'
]
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
"""
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a`
is a 1-D slice of `arr` along `axis`.
Parameters
----------
func1d : function
This function should accept 1-D arrays. It is applied to 1-D
slices of `arr` along the specified axis.
axis : integer
Axis along which `arr` is sliced.
arr : ndarray
Input array.
args : any
Additional arguments to `func1d`.
kwargs: any
Additional named arguments to `func1d`.
.. versionadded:: 1.9.0
Returns
-------
apply_along_axis : ndarray
The output array. The shape of `outarr` is identical to the shape of
`arr`, except along the `axis` dimension, where the length of `outarr`
is equal to the size of the return value of `func1d`. If `func1d`
returns a scalar `outarr` will have one fewer dimensions than `arr`.
See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.
Examples
--------
>>> def my_func(a):
... \"\"\"Average first and last element of a 1-D array\"\"\"
... return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([ 4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([ 2., 5., 8.])
For a function that doesn't return a scalar, the number of dimensions in
`outarr` is the same as `arr`.
>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
"""
arr = asarray(arr)
nd = arr.ndim
if axis < 0:
axis += nd
if (axis >= nd):
raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d."
% (axis, nd))
ind = [0]*(nd-1)
i = zeros(nd, 'O')
indlist = list(range(nd))
indlist.remove(axis)
i[axis] = slice(None, None)
outshape = asarray(arr.shape).take(indlist)
i.put(indlist, ind)
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
# if res is a number, then we have a smaller output array
if isscalar(res):
outarr = zeros(outshape, asarray(res).dtype)
outarr[tuple(ind)] = res
Ntot = product(outshape)
k = 1
while k < Ntot:
# increment the index
ind[-1] += 1
n = -1
while (ind[n] >= outshape[n]) and (n > (1-nd)):
ind[n-1] += 1
ind[n] = 0
n -= 1
i.put(indlist, ind)
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
outarr[tuple(ind)] = res
k += 1
return outarr
else:
Ntot = product(outshape)
holdshape = outshape
outshape = list(arr.shape)
outshape[axis] = len(res)
outarr = zeros(outshape, asarray(res).dtype)
outarr[tuple(i.tolist())] = res
k = 1
while k < Ntot:
# increment the index
ind[-1] += 1
n = -1
while (ind[n] >= holdshape[n]) and (n > (1-nd)):
ind[n-1] += 1
ind[n] = 0
n -= 1
i.put(indlist, ind)
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
outarr[tuple(i.tolist())] = res
k += 1
return outarr
def apply_over_axes(func, a, axes):
"""
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has one less dimension than `a`, a dimension is inserted before
`axis`. The call to `func` is then repeated for each axis in `axes`,
with `res` as the first argument.
Parameters
----------
func : function
This function must take two arguments, `func(a, axis)`.
a : array_like
Input array.
axes : array_like
Axes over which `func` is applied; the elements must be integers.
Returns
-------
apply_over_axis : ndarray
The output array. The number of dimensions is the same as `a`,
but the shape can be different. This depends on whether `func`
changes the shape of its output with respect to its input.
See Also
--------
apply_along_axis :
Apply a function to 1-D slices of an array along the given axis.
Notes
------
This function is equivalent to tuple axis arguments to reorderable ufuncs
with keepdims=True. Tuple axis arguments to ufuncs have been availabe since
version 1.7.0.
Examples
--------
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Sum over axes 0 and 2. The result has same number of dimensions
as the original array:
>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
[ 92],
[124]]])
Tuple axis arguments to ufuncs are equivalent:
>>> np.sum(a, axis=(0,2), keepdims=True)
array([[[ 60],
[ 92],
[124]]])
"""
val = asarray(a)
N = a.ndim
if array(axes).ndim == 0:
axes = (axes,)
for axis in axes:
if axis < 0:
axis = N + axis
args = (val, axis)
res = func(*args)
if res.ndim == val.ndim:
val = res
else:
res = expand_dims(res, axis)
if res.ndim == val.ndim:
val = res
else:
raise ValueError("function is not returning "
"an array of the correct shape")
return val
def expand_dims(a, axis):
"""
Expand the shape of an array.
Insert a new axis, corresponding to a given position in the array shape.
Parameters
----------
a : array_like
Input array.
axis : int
Position (amongst axes) where new axis is to be inserted.
Returns
-------
res : ndarray
Output array. The number of dimensions is one greater than that of
the input array.
See Also
--------
doc.indexing, atleast_1d, atleast_2d, atleast_3d
Examples
--------
>>> x = np.array([1,2])
>>> x.shape
(2,)
The following is equivalent to ``x[np.newaxis,:]`` or ``x[np.newaxis]``:
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1) # Equivalent to x[:,newaxis]
>>> y
array([[1],
[2]])
>>> y.shape
(2, 1)
Note that some examples may use ``None`` instead of ``np.newaxis``. These
are the same objects:
>>> np.newaxis is None
True
"""
a = asarray(a)
shape = a.shape
if axis < 0:
axis = axis + len(shape) + 1
return a.reshape(shape[:axis] + (1,) + shape[axis:])
row_stack = vstack
def column_stack(tup):
"""
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
-------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
hstack, vstack, concatenate
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
"""
arrays = []
for v in tup:
arr = array(v, copy=False, subok=True)
if arr.ndim < 2:
arr = array(arr, copy=False, subok=True, ndmin=2).T
arrays.append(arr)
return _nx.concatenate(arrays, 1)
def dstack(tup):
"""
Stack arrays in sequence depth wise (along third axis).
Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by `dsplit`.
This is a simple way to stack 2D arrays (images) into a single
3D array for processing.
Parameters
----------
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all
but the third axis.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays.
See Also
--------
stack : Join a sequence of arrays along a new axis.
vstack : Stack along first axis.
hstack : Stack along second axis.
concatenate : Join a sequence of arrays along an existing axis.
dsplit : Split array along third axis.
Notes
-----
Equivalent to ``np.concatenate(tup, axis=2)``.
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
"""
return _nx.concatenate([atleast_3d(_m) for _m in tup], 2)
def _replace_zero_by_x_arrays(sub_arys):
for i in range(len(sub_arys)):
if len(_nx.shape(sub_arys[i])) == 0:
sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)):
sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
return sub_arys
def array_split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
"""
try:
Ntotal = ary.shape[axis]
except AttributeError:
Ntotal = len(ary)
try:
# handle scalar case.
Nsections = len(indices_or_sections) + 1
div_points = [0] + list(indices_or_sections) + [Ntotal]
except TypeError:
# indices_or_sections is a scalar, not an array.
Nsections = int(indices_or_sections)
if Nsections <= 0:
raise ValueError('number sections must be larger than 0.')
Neach_section, extras = divmod(Ntotal, Nsections)
section_sizes = ([0] +
extras * [Neach_section+1] +
(Nsections-extras) * [Neach_section])
div_points = _nx.array(section_sizes).cumsum()
sub_arys = []
sary = _nx.swapaxes(ary, axis, 0)
for i in range(Nsections):
st = div_points[i]
end = div_points[i + 1]
sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
return sub_arys
def split(ary,indices_or_sections,axis=0):
"""
Split an array into multiple sub-arrays.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a 1-D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis=0``, result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
axis : int, optional
The axis along which to split, default is 0.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays.
Raises
------
ValueError
If `indices_or_sections` is given as an integer, but
a split does not result in equal division.
See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
near-equal size. Does not raise an exception if
an equal division cannot be made.
hsplit : Split array into multiple sub-arrays horizontally (column-wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
Examples
--------
>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]
"""
try:
len(indices_or_sections)
except TypeError:
sections = indices_or_sections
N = ary.shape[axis]
if N % sections:
raise ValueError(
'array split does not result in an equal division')
res = array_split(ary, indices_or_sections, axis)
return res
def hsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis regardless of the array dimension.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[ 12., 13., 14.]]),
array([[ 3.],
[ 7.],
[ 11.],
[ 15.]]),
array([], dtype=float64)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0., 1.]],
[[ 4., 5.]]]),
array([[[ 2., 3.]],
[[ 6., 7.]]])]
"""
if len(_nx.shape(ary)) == 0:
raise ValueError('hsplit only works on arrays of 1 or more dimensions')
if len(ary.shape) > 1:
return split(ary, indices_or_sections, 1)
else:
return split(ary, indices_or_sections, 0)
def vsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the ``split`` documentation. ``vsplit`` is equivalent
to ``split`` with `axis=0` (default), the array is always split along the
first axis regardless of the array dimension.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.vsplit(x, 2)
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]]),
array([[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])]
>>> np.vsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]),
array([[ 12., 13., 14., 15.]]),
array([], dtype=float64)]
With a higher dimensional array the split is still along the first axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.vsplit(x, 2)
[array([[[ 0., 1.],
[ 2., 3.]]]),
array([[[ 4., 5.],
[ 6., 7.]]])]
"""
if len(_nx.shape(ary)) < 2:
raise ValueError('vsplit only works on arrays of 2 or more dimensions')
return split(ary, indices_or_sections, 0)
def dsplit(ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0., 1.],
[ 4., 5.]],
[[ 8., 9.],
[ 12., 13.]]]),
array([[[ 2., 3.],
[ 6., 7.]],
[[ 10., 11.],
[ 14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[ 12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
[[ 11.],
[ 15.]]]),
array([], dtype=float64)]
"""
if len(_nx.shape(ary)) < 3:
raise ValueError('dsplit only works on arrays of 3 or more dimensions')
return split(ary, indices_or_sections, 2)
def get_array_prepare(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_prepare__) for i, x in enumerate(args)
if hasattr(x, '__array_prepare__'))
if wrappers:
return wrappers[-1][-1]
return None
def get_array_wrap(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_wrap__) for i, x in enumerate(args)
if hasattr(x, '__array_wrap__'))
if wrappers:
return wrappers[-1][-1]
return None
def kron(a, b):
"""
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Parameters
----------
a, b : array_like
Returns
-------
out : ndarray
See Also
--------
outer : The outer product
Notes
-----
The function assumes that the number of dimensions of `a` and `b`
are the same, if necessary prepending the smallest with ones.
If `a.shape = (r0,r1,..,rN)` and `b.shape = (s0,s1,...,sN)`,
the Kronecker product has shape `(r0*s0, r1*s1, ..., rN*SN)`.
The elements are products of elements from `a` and `b`, organized
explicitly by::
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
where::
kt = it * st + jt, t = 0,...,N
In the common 2-D case (N=1), the block structure can be visualized::
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
[ ... ... ],
[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
Examples
--------
>>> np.kron([1,10,100], [5,6,7])
array([ 5, 6, 7, 50, 60, 70, 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([ 5, 50, 500, 6, 60, 600, 7, 70, 700])
>>> np.kron(np.eye(2), np.ones((2,2)))
array([[ 1., 1., 0., 0.],
[ 1., 1., 0., 0.],
[ 0., 0., 1., 1.],
[ 0., 0., 1., 1.]])
>>> a = np.arange(100).reshape((2,5,2,5))
>>> b = np.arange(24).reshape((2,3,4))
>>> c = np.kron(a,b)
>>> c.shape
(2, 10, 6, 20)
>>> I = (1,3,0,2)
>>> J = (0,2,1)
>>> J1 = (0,) + J # extend to ndim=4
>>> S1 = (1,) + b.shape
>>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
>>> c[K] == a[I]*b[J]
True
"""
b = asanyarray(b)
a = array(a, copy=False, subok=True, ndmin=b.ndim)
ndb, nda = b.ndim, a.ndim
if (nda == 0 or ndb == 0):
return _nx.multiply(a, b)
as_ = a.shape
bs = b.shape
if not a.flags.contiguous:
a = reshape(a, as_)
if not b.flags.contiguous:
b = reshape(b, bs)
nd = ndb
if (ndb != nda):
if (ndb > nda):
as_ = (1,)*(ndb-nda) + as_
else:
bs = (1,)*(nda-ndb) + bs
nd = nda
result = outer(a, b).reshape(as_+bs)
axis = nd-1
for _ in range(nd):
result = concatenate(result, axis=axis)
wrapper = get_array_prepare(a, b)
if wrapper is not None:
result = wrapper(result)
wrapper = get_array_wrap(a, b)
if wrapper is not None:
result = wrapper(result)
return result
def tile(A, reps):
"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.
If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).
Parameters
----------
A : array_like
The input array.
reps : array_like
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The tiled output array.
See Also
--------
repeat : Repeat elements of an array.
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
[[0, 1, 2, 0, 1, 2]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
"""
try:
tup = tuple(reps)
except TypeError:
tup = (reps,)
d = len(tup)
if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray):
# Fixes the problem that the function does not make a copy if A is a
# numpy array and the repetitions are 1 in all dimensions
return _nx.array(A, copy=True, subok=True, ndmin=d)
else:
# Note that no copy of zero-sized arrays is made. However since they
# have no data there is no risk of an inadvertent overwrite.
c = _nx.array(A, copy=False, subok=True, ndmin=d)
if (d < c.ndim):
tup = (1,)*(c.ndim-d) + tup
shape_out = tuple(s*t for s, t in zip(c.shape, tup))
n = c.size
if n > 0:
for dim_in, nrep in zip(c.shape, tup):
if nrep != 1:
c = c.reshape(-1, n).repeat(nrep, 0)
n //= dim_in
return c.reshape(shape_out)
| WillieMaddox/numpy | numpy/lib/shape_base.py | Python | bsd-3-clause | 25,222 |
/*
* Copyright (c) 2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
* Andreas Hansson
*/
#ifndef __ARCH_X86_INTERRUPTS_HH__
#define __ARCH_X86_INTERRUPTS_HH__
#include "arch/x86/regs/apic.hh"
#include "arch/x86/faults.hh"
#include "arch/x86/intmessage.hh"
#include "base/bitfield.hh"
#include "cpu/thread_context.hh"
#include "dev/x86/intdev.hh"
#include "dev/io_device.hh"
#include "params/X86LocalApic.hh"
#include "sim/eventq.hh"
class ThreadContext;
class BaseCPU;
int divideFromConf(uint32_t conf);
namespace X86ISA {
ApicRegIndex decodeAddr(Addr paddr);
class Interrupts : public BasicPioDevice, IntDevice
{
protected:
// Storage for the APIC registers
uint32_t regs[NUM_APIC_REGS];
BitUnion32(LVTEntry)
Bitfield<7, 0> vector;
Bitfield<10, 8> deliveryMode;
Bitfield<12> status;
Bitfield<13> polarity;
Bitfield<14> remoteIRR;
Bitfield<15> trigger;
Bitfield<16> masked;
Bitfield<17> periodic;
EndBitUnion(LVTEntry)
/*
* Timing related stuff.
*/
EventFunctionWrapper apicTimerEvent;
void processApicTimerEvent();
/*
* A set of variables to keep track of interrupts that don't go through
* the IRR.
*/
bool pendingSmi;
uint8_t smiVector;
bool pendingNmi;
uint8_t nmiVector;
bool pendingExtInt;
uint8_t extIntVector;
bool pendingInit;
uint8_t initVector;
bool pendingStartup;
uint8_t startupVector;
bool startedUp;
// This is a quick check whether any of the above (except ExtInt) are set.
bool pendingUnmaskableInt;
// A count of how many IPIs are in flight.
int pendingIPIs;
/*
* IRR and ISR maintenance.
*/
uint8_t IRRV;
uint8_t ISRV;
int
findRegArrayMSB(ApicRegIndex base)
{
int offset = 7;
do {
if (regs[base + offset] != 0) {
return offset * 32 + findMsbSet(regs[base + offset]);
}
} while (offset--);
return 0;
}
void
updateIRRV()
{
IRRV = findRegArrayMSB(APIC_INTERRUPT_REQUEST_BASE);
}
void
updateISRV()
{
ISRV = findRegArrayMSB(APIC_IN_SERVICE_BASE);
}
void
setRegArrayBit(ApicRegIndex base, uint8_t vector)
{
regs[base + (vector / 32)] |= (1 << (vector % 32));
}
void
clearRegArrayBit(ApicRegIndex base, uint8_t vector)
{
regs[base + (vector / 32)] &= ~(1 << (vector % 32));
}
bool
getRegArrayBit(ApicRegIndex base, uint8_t vector)
{
return bits(regs[base + (vector / 32)], vector % 32);
}
void requestInterrupt(uint8_t vector, uint8_t deliveryMode, bool level);
BaseCPU *cpu;
int initialApicId;
// Port for receiving interrupts
IntSlavePort intSlavePort;
public:
int getInitialApicId() { return initialApicId; }
/*
* Params stuff.
*/
typedef X86LocalApicParams Params;
void setCPU(BaseCPU * newCPU);
const Params *
params() const
{
return dynamic_cast<const Params *>(_params);
}
/*
* Initialize this object by registering it with the IO APIC.
*/
void init() override;
/*
* Functions to interact with the interrupt port from IntDevice.
*/
Tick read(PacketPtr pkt) override;
Tick write(PacketPtr pkt) override;
Tick recvMessage(PacketPtr pkt) override;
Tick recvResponse(PacketPtr pkt) override;
bool
triggerTimerInterrupt()
{
LVTEntry entry = regs[APIC_LVT_TIMER];
if (!entry.masked)
requestInterrupt(entry.vector, entry.deliveryMode, entry.trigger);
return entry.periodic;
}
AddrRangeList getIntAddrRange() const override;
BaseMasterPort &getMasterPort(const std::string &if_name,
PortID idx = InvalidPortID) override
{
if (if_name == "int_master") {
return intMasterPort;
}
return BasicPioDevice::getMasterPort(if_name, idx);
}
BaseSlavePort &getSlavePort(const std::string &if_name,
PortID idx = InvalidPortID) override
{
if (if_name == "int_slave") {
return intSlavePort;
}
return BasicPioDevice::getSlavePort(if_name, idx);
}
/*
* Functions to access and manipulate the APIC's registers.
*/
uint32_t readReg(ApicRegIndex miscReg);
void setReg(ApicRegIndex reg, uint32_t val);
void
setRegNoEffect(ApicRegIndex reg, uint32_t val)
{
regs[reg] = val;
}
/*
* Constructor.
*/
Interrupts(Params * p);
/*
* Functions for retrieving interrupts for the CPU to handle.
*/
bool checkInterrupts(ThreadContext *tc) const;
/**
* Check if there are pending interrupts without ignoring the
* interrupts disabled flag.
*
* @return true if there are interrupts pending.
*/
bool checkInterruptsRaw() const;
/**
* Check if there are pending unmaskable interrupts.
*
* @return true there are unmaskable interrupts pending.
*/
bool hasPendingUnmaskable() const { return pendingUnmaskableInt; }
Fault getInterrupt(ThreadContext *tc);
void updateIntrInfo(ThreadContext *tc);
/*
* Serialization.
*/
void serialize(CheckpointOut &cp) const override;
void unserialize(CheckpointIn &cp) override;
/*
* Old functions needed for compatability but which will be phased out
* eventually.
*/
void
post(int int_num, int index)
{
panic("Interrupts::post unimplemented!\n");
}
void
clear(int int_num, int index)
{
panic("Interrupts::clear unimplemented!\n");
}
void
clearAll()
{
panic("Interrupts::clearAll unimplemented!\n");
}
};
} // namespace X86ISA
#endif // __ARCH_X86_INTERRUPTS_HH__
| rallylee/gem5 | src/arch/x86/interrupts.hh | C++ | bsd-3-clause | 8,657 |
module Less
#
# Functions useable from within the style-sheet go here
#
module Functions
def rgb *rgb
rgba rgb, 1.0
end
def hsl *args
hsla *[args, 1.0].flatten
end
#
# RGBA to Node::Color
#
def rgba *rgba
Node::Color.new *rgba.flatten
end
#
# HSLA to RGBA
#
def hsla h, s, l, a = 1.0
m2 = ( l <= 0.5 ) ? l * ( s + 1 ) : l + s - l * s
m1 = l * 2 - m2;
hue = lambda do |h|
h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h)
if h * 6 < 1 then m1 + (m2 - m1) * h * 6
elsif h * 2 < 1 then m2
elsif h * 3 < 2 then m1 + (m2 - m1) * (2/3 - h) * 6
else m1
end
end
rgba hue[ h + 1/3 ], hue[ h ], hue[ h - 1/3 ], a
end
def self.available
self.instance_methods.map(&:to_sym)
end
end
module Node
#
# A CSS function, like rgb() or url()
#
# it calls functions from the Functions module
#
class Function < String
include Entity
include Functions
def initialize name, args
@args = if args.is_a? Array
args.map {|e| e.is_a?(Expression) ? e : Expression.new(e, self)}
else
[args]
end
super name
end
def to_css env = nil
self.evaluate(env).to_css
end
def nearest node
parent.nearest node
end
#
# Call the function
#
# If the function isn't found, we just print it out,
# this is the case for url(), for example,
#
def evaluate context = nil
if Functions.available.include? self.to_sym
send to_sym, *@args
else
args = @args.map { |e|
e.parent = self.parent
e = e.evaluate(context) if e.respond_to?(:evaluate)
e.to_css
} * ', '
Node::Anonymous.new("#{to_sym}(#{args})")
end
end
end
end
end
| nithinstany/peprime | vendor/gems/less-1.2.20/lib/less/engine/nodes/function.rb | Ruby | bsd-3-clause | 1,990 |
require "#{File.dirname __FILE__}/../../../spec_helper"
require "#{File.dirname __FILE__}/../fixtures/classes"
shared :unboundmethod_to_s do |cmd|
describe "UnboundMethod##{cmd}" do
before :each do
@from_module = UnboundMethodSpecs::Methods.instance_method(:from_mod)
@from_method = UnboundMethodSpecs::Methods.new.method(:from_mod).unbind
end
it "returns a String" do
@from_module.send(cmd).class.should == String
@from_method.send(cmd).class.should == String
end
it "the String reflects that this is an UnboundMethod object" do
@from_module.send(cmd).should =~ /\bUnboundMethod\b/
@from_method.send(cmd).should =~ /\bUnboundMethod\b/
end
it "the String shows the method name, Module defined in and Module extracted from" do
@from_module.send(cmd).should =~ /\bfrom_mod\b/
@from_module.send(cmd).should =~ /\bUnboundMethodSpecs::Mod\b/
@from_method.send(cmd).should =~ /\bUnboundMethodSpecs::Methods\b/
end
end
end
| chad/rubinius | spec/frozen/1.8/core/unboundmethod/shared/to_s.rb | Ruby | bsd-3-clause | 1,011 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "public/web/WebDocument.h"
#include "core/CSSPropertyNames.h"
#include "core/HTMLNames.h"
#include "core/dom/NodeComputedStyle.h"
#include "core/dom/StyleEngine.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLLinkElement.h"
#include "core/page/Page.h"
#include "core/style/ComputedStyle.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/graphics/Color.h"
#include "platform/testing/URLTestHelpers.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "web/tests/FrameTestHelpers.h"
namespace blink {
using blink::FrameTestHelpers::WebViewHelper;
using blink::URLTestHelpers::toKURL;
const char kDefaultOrigin[] = "https://example.test/";
const char kManifestDummyFilePath[] = "manifest-dummy.html";
class WebDocumentTest : public ::testing::Test {
protected:
static void SetUpTestCase();
void loadURL(const std::string& url);
Document* topDocument() const;
WebDocument topWebDocument() const;
WebViewHelper m_webViewHelper;
};
void WebDocumentTest::SetUpTestCase()
{
URLTestHelpers::registerMockedURLLoad(toKURL(std::string(kDefaultOrigin) + kManifestDummyFilePath), WebString::fromUTF8(kManifestDummyFilePath));
}
void WebDocumentTest::loadURL(const std::string& url)
{
m_webViewHelper.initializeAndLoad(url);
}
Document* WebDocumentTest::topDocument() const
{
return toLocalFrame(m_webViewHelper.webViewImpl()->page()->mainFrame())->document();
}
WebDocument WebDocumentTest::topWebDocument() const
{
return m_webViewHelper.webView()->mainFrame()->document();
}
TEST_F(WebDocumentTest, InsertStyleSheet)
{
loadURL("about:blank");
WebDocument webDoc = topWebDocument();
Document* coreDoc = topDocument();
unsigned startCount = coreDoc->styleEngine().styleForElementCount();
webDoc.insertStyleSheet("body { color: green }");
// Check insertStyleSheet did not cause a synchronous style recalc.
unsigned elementCount = coreDoc->styleEngine().styleForElementCount() - startCount;
ASSERT_EQ(0U, elementCount);
HTMLElement* bodyElement = coreDoc->body();
DCHECK(bodyElement);
const ComputedStyle& styleBeforeInsertion = bodyElement->computedStyleRef();
// Inserted stylesheet not yet applied.
ASSERT_EQ(Color(0, 0, 0), styleBeforeInsertion.visitedDependentColor(CSSPropertyColor));
// Apply inserted stylesheet.
coreDoc->updateStyleAndLayoutTree();
const ComputedStyle& styleAfterInsertion = bodyElement->computedStyleRef();
// Inserted stylesheet applied.
ASSERT_EQ(Color(0, 128, 0), styleAfterInsertion.visitedDependentColor(CSSPropertyColor));
}
TEST_F(WebDocumentTest, ManifestURL)
{
loadURL(std::string(kDefaultOrigin) + kManifestDummyFilePath);
WebDocument webDoc = topWebDocument();
Document* document = topDocument();
HTMLLinkElement* linkManifest = document->linkManifest();
// No href attribute was set.
ASSERT_EQ(linkManifest->href(), static_cast<KURL>(webDoc.manifestURL()));
// Set to some absolute url.
linkManifest->setAttribute(HTMLNames::hrefAttr, "http://example.com/manifest.json");
ASSERT_EQ(linkManifest->href(), static_cast<KURL>(webDoc.manifestURL()));
// Set to some relative url.
linkManifest->setAttribute(HTMLNames::hrefAttr, "static/manifest.json");
ASSERT_EQ(linkManifest->href(), static_cast<KURL>(webDoc.manifestURL()));
}
TEST_F(WebDocumentTest, ManifestUseCredentials)
{
loadURL(std::string(kDefaultOrigin) + kManifestDummyFilePath);
WebDocument webDoc = topWebDocument();
Document* document = topDocument();
HTMLLinkElement* linkManifest = document->linkManifest();
// No crossorigin attribute was set so credentials shouldn't be used.
ASSERT_FALSE(linkManifest->fastHasAttribute(HTMLNames::crossoriginAttr));
ASSERT_FALSE(webDoc.manifestUseCredentials());
// Crossorigin set to a random string shouldn't trigger using credentials.
linkManifest->setAttribute(HTMLNames::crossoriginAttr, "foobar");
ASSERT_FALSE(webDoc.manifestUseCredentials());
// Crossorigin set to 'anonymous' shouldn't trigger using credentials.
linkManifest->setAttribute(HTMLNames::crossoriginAttr, "anonymous");
ASSERT_FALSE(webDoc.manifestUseCredentials());
// Crossorigin set to 'use-credentials' should trigger using credentials.
linkManifest->setAttribute(HTMLNames::crossoriginAttr, "use-credentials");
ASSERT_TRUE(webDoc.manifestUseCredentials());
}
namespace {
const char* baseURLOriginA = "http://example.test:0/";
const char* baseURLOriginSubA = "http://subdomain.example.test:0/";
const char* baseURLOriginSecureA = "https://example.test:0/";
const char* baseURLOriginB = "http://not-example.test:0/";
const char* emptyFile = "first_party/empty.html";
const char* nestedData = "first_party/nested-data.html";
const char* nestedOriginA = "first_party/nested-originA.html";
const char* nestedOriginSubA = "first_party/nested-originSubA.html";
const char* nestedOriginSecureA = "first_party/nested-originSecureA.html";
const char* nestedOriginAInOriginA = "first_party/nested-originA-in-originA.html";
const char* nestedOriginAInOriginB = "first_party/nested-originA-in-originB.html";
const char* nestedOriginB = "first_party/nested-originB.html";
const char* nestedOriginBInOriginA = "first_party/nested-originB-in-originA.html";
const char* nestedOriginBInOriginB = "first_party/nested-originB-in-originB.html";
const char* nestedSrcDoc = "first_party/nested-srcdoc.html";
KURL toOriginA(const char* file)
{
return toKURL(std::string(baseURLOriginA) + file);
}
KURL toOriginSubA(const char* file)
{
return toKURL(std::string(baseURLOriginSubA) + file);
}
KURL toOriginSecureA(const char* file)
{
return toKURL(std::string(baseURLOriginSecureA) + file);
}
KURL toOriginB(const char* file)
{
return toKURL(std::string(baseURLOriginB) + file);
}
} // anonymous namespace
class WebDocumentFirstPartyTest : public WebDocumentTest {
public:
static void SetUpTestCase();
protected:
void load(const char*);
Document* nestedDocument() const;
Document* nestedNestedDocument() const;
};
void WebDocumentFirstPartyTest::SetUpTestCase()
{
URLTestHelpers::registerMockedURLLoad(toOriginA(emptyFile), WebString::fromUTF8(emptyFile));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedData), WebString::fromUTF8(nestedData));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginA), WebString::fromUTF8(nestedOriginA));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginSubA), WebString::fromUTF8(nestedOriginSubA));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginSecureA), WebString::fromUTF8(nestedOriginSecureA));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginAInOriginA), WebString::fromUTF8(nestedOriginAInOriginA));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginAInOriginB), WebString::fromUTF8(nestedOriginAInOriginB));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginB), WebString::fromUTF8(nestedOriginB));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginBInOriginA), WebString::fromUTF8(nestedOriginBInOriginA));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedOriginBInOriginB), WebString::fromUTF8(nestedOriginBInOriginB));
URLTestHelpers::registerMockedURLLoad(toOriginA(nestedSrcDoc), WebString::fromUTF8(nestedSrcDoc));
URLTestHelpers::registerMockedURLLoad(toOriginSubA(emptyFile), WebString::fromUTF8(emptyFile));
URLTestHelpers::registerMockedURLLoad(toOriginSecureA(emptyFile), WebString::fromUTF8(emptyFile));
URLTestHelpers::registerMockedURLLoad(toOriginB(emptyFile), WebString::fromUTF8(emptyFile));
URLTestHelpers::registerMockedURLLoad(toOriginB(nestedOriginA), WebString::fromUTF8(nestedOriginA));
URLTestHelpers::registerMockedURLLoad(toOriginB(nestedOriginB), WebString::fromUTF8(nestedOriginB));
}
void WebDocumentFirstPartyTest::load(const char* file)
{
m_webViewHelper.initializeAndLoad(std::string(baseURLOriginA) + file);
}
Document* WebDocumentFirstPartyTest::nestedDocument() const
{
return toLocalFrame(m_webViewHelper.webViewImpl()->page()->mainFrame()->tree().firstChild())->document();
}
Document* WebDocumentFirstPartyTest::nestedNestedDocument() const
{
return toLocalFrame(m_webViewHelper.webViewImpl()->page()->mainFrame()->tree().firstChild()->tree().firstChild())->document();
}
TEST_F(WebDocumentFirstPartyTest, Empty)
{
load(emptyFile);
ASSERT_EQ(toOriginA(emptyFile), topDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginA)
{
load(nestedOriginA);
ASSERT_EQ(toOriginA(nestedOriginA), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginA), nestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginSubA)
{
load(nestedOriginSubA);
ASSERT_EQ(toOriginA(nestedOriginSubA), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginSubA), nestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginSecureA)
{
load(nestedOriginSecureA);
ASSERT_EQ(toOriginA(nestedOriginSecureA), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginSecureA), nestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginAInOriginA)
{
load(nestedOriginAInOriginA);
ASSERT_EQ(toOriginA(nestedOriginAInOriginA), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginAInOriginA), nestedDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginAInOriginA), nestedNestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginAInOriginB)
{
load(nestedOriginAInOriginB);
ASSERT_EQ(toOriginA(nestedOriginAInOriginB), topDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedNestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginB)
{
load(nestedOriginB);
ASSERT_EQ(toOriginA(nestedOriginB), topDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginBInOriginA)
{
load(nestedOriginBInOriginA);
ASSERT_EQ(toOriginA(nestedOriginBInOriginA), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginBInOriginA), nestedDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedNestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginBInOriginB)
{
load(nestedOriginBInOriginB);
ASSERT_EQ(toOriginA(nestedOriginBInOriginB), topDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedNestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedSrcdoc)
{
load(nestedSrcDoc);
ASSERT_EQ(toOriginA(nestedSrcDoc), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedSrcDoc), nestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedData)
{
load(nestedData);
ASSERT_EQ(toOriginA(nestedData), topDocument()->firstPartyForCookies());
ASSERT_EQ(SecurityOrigin::urlWithUniqueSecurityOrigin(), nestedDocument()->firstPartyForCookies());
}
TEST_F(WebDocumentFirstPartyTest, NestedOriginAInOriginBWithFirstPartyOverride)
{
load(nestedOriginAInOriginB);
SchemeRegistry::registerURLSchemeAsFirstPartyWhenTopLevel("http");
ASSERT_EQ(toOriginA(nestedOriginAInOriginB), topDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginAInOriginB), nestedDocument()->firstPartyForCookies());
ASSERT_EQ(toOriginA(nestedOriginAInOriginB), nestedNestedDocument()->firstPartyForCookies());
}
} // namespace blink
| axinging/chromium-crosswalk | third_party/WebKit/Source/web/tests/WebDocumentTest.cpp | C++ | bsd-3-clause | 12,455 |
/*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Copyright (c) 2011 Helge Bahmann
* Copyright (c) 2013 Tim Blechmann
* Copyright (c) 2014 Andrey Semashev
*/
/*!
* \file atomic/fences.hpp
*
* This header contains definition of \c atomic_thread_fence and \c atomic_signal_fence functions.
*/
#ifndef BOOST_ATOMIC_FENCES_HPP_INCLUDED_
#define BOOST_ATOMIC_FENCES_HPP_INCLUDED_
#include <boost/memory_order.hpp>
#include <boost/atomic/capabilities.hpp>
#include <boost/atomic/detail/operations.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
/*
* IMPLEMENTATION NOTE: All interface functions MUST be declared with BOOST_FORCEINLINE,
* see comment for convert_memory_order_to_gcc in ops_gcc_atomic.hpp.
*/
namespace pdalboost {
namespace atomics {
#if BOOST_ATOMIC_THREAD_FENCE > 0
BOOST_FORCEINLINE void atomic_thread_fence(memory_order order) BOOST_NOEXCEPT
{
detail::thread_fence(order);
}
#else
BOOST_FORCEINLINE void atomic_thread_fence(memory_order) BOOST_NOEXCEPT
{
detail::lockpool::thread_fence();
}
#endif
#if BOOST_ATOMIC_SIGNAL_FENCE > 0
BOOST_FORCEINLINE void atomic_signal_fence(memory_order order) BOOST_NOEXCEPT
{
detail::signal_fence(order);
}
#else
BOOST_FORCEINLINE void atomic_signal_fence(memory_order) BOOST_NOEXCEPT
{
detail::lockpool::signal_fence();
}
#endif
} // namespace atomics
using atomics::atomic_thread_fence;
using atomics::atomic_signal_fence;
} // namespace pdalboost
#endif // BOOST_ATOMIC_FENCES_HPP_INCLUDED_
| lucadelu/PDAL | vendor/pdalboost/boost/atomic/fences.hpp | C++ | bsd-3-clause | 1,626 |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <random>
// template<class Engine, size_t w, class UIntType>
// class independent_bits_engine
// independent_bits_engine(const independent_bits_engine&);
#include <random>
#include <cassert>
void
test1()
{
typedef std::independent_bits_engine<std::ranlux24, 32, unsigned> E;
E e1;
(void)e1();
E e2 = e1;
assert(e1 == e2);
assert(e1() == e2());
E::result_type k = e1();
assert(e1 != e2);
assert(e2() == k);
assert(e1 == e2);
}
void
test2()
{
typedef std::independent_bits_engine<std::ranlux48, 64, unsigned long long> E;
E e1;
(void)e1();
E e2 = e1;
assert(e1 == e2);
assert(e1() == e2());
E::result_type k = e1();
assert(e1 != e2);
assert(e2() == k);
assert(e1 == e2);
}
int main()
{
test1();
test2();
}
| youtube/cobalt | third_party/llvm-project/libcxx/test/std/numerics/rand/rand.adapt/rand.adapt.ibits/copy.pass.cpp | C++ | bsd-3-clause | 1,158 |
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of
# its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
from copy import copy
from nose import tools as nt
from neurom.check.runner import CheckRunner
from neurom.exceptions import ConfigError
_path = os.path.dirname(os.path.abspath(__file__))
SWC_PATH = os.path.join(_path, '../../../test_data/swc/')
NRN_PATH_0 = os.path.join(SWC_PATH, 'Neuron.swc')
NRN_PATH_1 = os.path.join(SWC_PATH, 'Neuron_zero_length_sections.swc')
NRN_PATH_2 = os.path.join(SWC_PATH, 'Single_apical.swc')
NRN_PATH_3 = os.path.join(SWC_PATH, 'Single_basal.swc')
NRN_PATH_4 = os.path.join(SWC_PATH, 'Single_axon.swc')
NRN_PATH_5 = os.path.join(SWC_PATH, 'Single_apical_no_soma.swc')
CONFIG = {
'checks': {
'structural_checks': [
'is_single_tree',
'has_soma_points',
'has_sequential_ids',
'has_increasing_ids',
'has_valid_soma',
'has_valid_neurites'
],
'neuron_checks': [
'has_basal_dendrite',
'has_axon',
'has_apical_dendrite',
'has_all_nonzero_segment_lengths',
'has_all_nonzero_section_lengths',
'has_all_nonzero_neurite_radii',
'has_nonzero_soma_radius'
]
},
'options': {
'has_nonzero_soma_radius': 0.0,
"has_all_nonzero_neurite_radii": 0.007,
"has_all_nonzero_segment_lengths": 0.01,
"has_all_nonzero_section_lengths": [0.01]
},
}
CONFIG_COLOR = copy(CONFIG)
CONFIG_COLOR['color'] = True
REF_0 = {
'files': {
NRN_PATH_0: {
"Is single tree": True,
"Has soma points": True,
"Has sequential ids": True,
"Has increasing ids": True,
"Has valid soma": True,
"Has valid neurites": True,
"Has basal dendrite": True,
"Has axon": True,
"Has apical dendrite": True,
"Has all nonzero segment lengths": True,
"Has all nonzero section lengths": True,
"Has all nonzero neurite radii": True,
"Has nonzero soma radius": True,
"ALL": True
}
},
"STATUS": "PASS"
}
REF_1 = {
'files': {
NRN_PATH_1: {
"Is single tree": True,
"Has soma points": True,
"Has sequential ids": True,
"Has increasing ids": True,
"Has valid soma": True,
"Has valid neurites": True,
"Has basal dendrite": True,
"Has axon": True,
"Has apical dendrite": True,
"Has all nonzero segment lengths": False,
"Has all nonzero section lengths": False,
"Has all nonzero neurite radii": True,
"Has nonzero soma radius": True,
"ALL": False
}
},
"STATUS": "FAIL"
}
REF_2 = {
'files': {
NRN_PATH_2: {
"Is single tree": True,
"Has soma points": True,
"Has sequential ids": True,
"Has increasing ids": True,
"Has valid soma": True,
"Has valid neurites": True,
"Has basal dendrite": False,
"Has axon": False,
"Has apical dendrite": True,
"Has all nonzero segment lengths": False,
"Has all nonzero section lengths": True,
"Has all nonzero neurite radii": True,
"Has nonzero soma radius": True,
"ALL": False
}
},
"STATUS": "FAIL"
}
REF_3 = {
'files': {
NRN_PATH_3: {
"Is single tree": True,
"Has soma points": True,
"Has sequential ids": True,
"Has increasing ids": True,
"Has valid soma": True,
"Has valid neurites": True,
"Has basal dendrite": True,
"Has axon": False,
"Has apical dendrite": False,
"Has all nonzero segment lengths": False,
"Has all nonzero section lengths": True,
"Has all nonzero neurite radii": True,
"Has nonzero soma radius": False,
"ALL": False
}
},
"STATUS": "FAIL"
}
REF_4 = {
'files': {
NRN_PATH_4: {
"Is single tree": True,
"Has soma points": True,
"Has sequential ids": True,
"Has increasing ids": True,
"Has valid soma": True,
"Has valid neurites": True,
"Has basal dendrite": False,
"Has axon": True,
"Has apical dendrite": False,
"Has all nonzero segment lengths": False,
"Has all nonzero section lengths": True,
"Has all nonzero neurite radii": True,
"Has nonzero soma radius": True,
"ALL": False
}
},
"STATUS": "FAIL"
}
REF_5 = {
'files': {
NRN_PATH_5: {
"Is single tree": True,
"Has soma points": False,
"Has sequential ids": True,
"Has increasing ids": True,
"Has valid soma": False,
"Has valid neurites": False,
"ALL": False
}
},
"STATUS": "FAIL"
}
def test_ok_neuron():
checker = CheckRunner(CONFIG)
summ = checker.run(NRN_PATH_0)
nt.assert_equal(summ, REF_0)
def test_ok_neuron_color():
checker = CheckRunner(CONFIG_COLOR)
summ = checker.run(NRN_PATH_0)
nt.assert_equal(summ, REF_0)
def test_zero_length_sections_neuron():
checker = CheckRunner(CONFIG)
summ = checker.run(NRN_PATH_1)
nt.assert_equal(summ, REF_1)
def test_single_apical_neuron():
checker = CheckRunner(CONFIG)
summ = checker.run(NRN_PATH_2)
nt.assert_equal(summ, REF_2)
def test_single_basal_neuron():
checker = CheckRunner(CONFIG)
summ = checker.run(NRN_PATH_3)
nt.assert_equal(summ, REF_3)
def test_single_axon_neuron():
checker = CheckRunner(CONFIG)
summ = checker.run(NRN_PATH_4)
nt.assert_equal(summ, REF_4)
def test_single_apical_no_soma():
checker = CheckRunner(CONFIG)
summ = checker.run(NRN_PATH_5)
nt.assert_equal(summ, REF_5)
def test_directory_input():
checker = CheckRunner(CONFIG)
summ = checker.run(SWC_PATH)
nt.eq_(summ['files'][NRN_PATH_0]['Has axon'], True)
nt.eq_(summ['files'][NRN_PATH_2]['Has axon'], False)
@nt.raises(IOError)
def test_invalid_data_path_raises_IOError():
checker = CheckRunner(CONFIG)
_ = checker.run('foo/bar/baz')
def test__sanitize_config():
# fails if missing 'checks'
nt.assert_raises(ConfigError, CheckRunner._sanitize_config, {})
# creates minimal config
new_config = CheckRunner._sanitize_config({'checks': {}})
nt.eq_(new_config, {'checks':
{'structural_checks': [],
'neuron_checks': [],
},
'options': {},
'color': False,
})
# makes no changes to already filled out config
new_config = CheckRunner._sanitize_config(CONFIG)
nt.eq_(CONFIG, new_config)
| eleftherioszisis/NeuroM | neurom/check/tests/test_runner.py | Python | bsd-3-clause | 8,711 |
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/runtime_javascript_dialog_manager.h"
#include <string>
#include "components/url_formatter/url_formatter.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/web_contents.h"
#if defined(OS_ANDROID)
#include "xwalk/runtime/browser/android/xwalk_contents_client_bridge.h"
#endif // defined(OS_ANDROID)
namespace xwalk {
RuntimeJavaScriptDialogManager::RuntimeJavaScriptDialogManager() {
}
RuntimeJavaScriptDialogManager::~RuntimeJavaScriptDialogManager() {
}
void RuntimeJavaScriptDialogManager::RunJavaScriptDialog(
content::WebContents* web_contents,
const GURL& origin_url,
const std::string& accept_lang,
content::JavaScriptMessageType javascript_message_type,
const base::string16& message_text,
const base::string16& default_prompt_text,
const DialogClosedCallback& callback,
bool* did_suppress_message) {
#if defined(OS_ANDROID)
XWalkContentsClientBridgeBase* bridge =
XWalkContentsClientBridgeBase::FromWebContents(web_contents);
bridge->RunJavaScriptDialog(javascript_message_type,
origin_url,
message_text,
default_prompt_text,
callback);
#else
*did_suppress_message = true;
NOTIMPLEMENTED();
#endif
}
void RuntimeJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
const base::string16& message_text,
bool is_reload,
const DialogClosedCallback& callback) {
#if defined(OS_ANDROID)
XWalkContentsClientBridgeBase* bridge =
XWalkContentsClientBridgeBase::FromWebContents(web_contents);
bridge->RunBeforeUnloadDialog(web_contents->GetURL(),
message_text,
callback);
#else
NOTIMPLEMENTED();
callback.Run(true, base::string16());
return;
#endif
}
void RuntimeJavaScriptDialogManager::CancelActiveAndPendingDialogs(
content::WebContents* web_contents) {
NOTIMPLEMENTED();
}
void RuntimeJavaScriptDialogManager::ResetDialogState(
content::WebContents* web_contents) {
NOTIMPLEMENTED();
}
} // namespace xwalk
| marcuspridham/crosswalk | runtime/browser/runtime_javascript_dialog_manager.cc | C++ | bsd-3-clause | 2,372 |
package main
import (
"math/rand"
"github.com/fogleman/gg"
)
func CreatePoints(n int) []gg.Point {
points := make([]gg.Point, n)
for i := 0; i < n; i++ {
x := 0.5 + rand.NormFloat64()*0.1
y := x + rand.NormFloat64()*0.1
points[i] = gg.Point{x, y}
}
return points
}
func main() {
const S = 1024
const P = 64
dc := gg.NewContext(S, S)
dc.InvertY()
dc.SetRGB(1, 1, 1)
dc.Clear()
points := CreatePoints(1000)
dc.Translate(P, P)
dc.Scale(S-P*2, S-P*2)
// draw minor grid
for i := 1; i <= 10; i++ {
x := float64(i) / 10
dc.MoveTo(x, 0)
dc.LineTo(x, 1)
dc.MoveTo(0, x)
dc.LineTo(1, x)
}
dc.SetRGBA(0, 0, 0, 0.25)
dc.SetLineWidth(1)
dc.Stroke()
// draw axes
dc.MoveTo(0, 0)
dc.LineTo(1, 0)
dc.MoveTo(0, 0)
dc.LineTo(0, 1)
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(4)
dc.Stroke()
// draw points
dc.SetRGBA(0, 0, 1, 0.5)
for _, p := range points {
dc.DrawCircle(p.X, p.Y, 3.0/S)
dc.Fill()
}
// draw text
dc.Identity()
dc.SetRGB(0, 0, 0)
if err := dc.LoadFontFace("/Library/Fonts/Arial Bold.ttf", 24); err != nil {
panic(err)
}
dc.DrawStringAnchored("Chart Title", S/2, P/2, 0.5, 0.5)
if err := dc.LoadFontFace("/Library/Fonts/Arial.ttf", 18); err != nil {
panic(err)
}
dc.DrawStringAnchored("X Axis Title", S/2, S-P/2, 0.5, 0.5)
dc.SavePNG("out.png")
}
| whosonfirst/go-whosonfirst-utils | vendor/src/github.com/fogleman/gg/examples/scatter.go | GO | bsd-3-clause | 1,307 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/input_method/mock_input_method_manager.h"
namespace chromeos {
namespace input_method {
MockInputMethodManager::MockInputMethodManager()
: add_observer_count_(0),
remove_observer_count_(0),
util_(&delegate_),
mod3_used_(false) {
active_input_method_ids_.push_back("xkb:us::eng");
}
MockInputMethodManager::~MockInputMethodManager() {
}
InputMethodManager::State MockInputMethodManager::GetState() {
return InputMethodManager::STATE_BROWSER_SCREEN;
}
void MockInputMethodManager::AddObserver(
InputMethodManager::Observer* observer) {
++add_observer_count_;
}
void MockInputMethodManager::AddCandidateWindowObserver(
InputMethodManager::CandidateWindowObserver* observer) {
}
void MockInputMethodManager::RemoveObserver(
InputMethodManager::Observer* observer) {
++remove_observer_count_;
}
void MockInputMethodManager::RemoveCandidateWindowObserver(
InputMethodManager::CandidateWindowObserver* observer) {
}
scoped_ptr<InputMethodDescriptors>
MockInputMethodManager::GetSupportedInputMethods() const {
scoped_ptr<InputMethodDescriptors> result(new InputMethodDescriptors);
result->push_back(
InputMethodUtil::GetFallbackInputMethodDescriptor());
return result.Pass();
}
scoped_ptr<InputMethodDescriptors>
MockInputMethodManager::GetActiveInputMethods() const {
scoped_ptr<InputMethodDescriptors> result(new InputMethodDescriptors);
result->push_back(
InputMethodUtil::GetFallbackInputMethodDescriptor());
return result.Pass();
}
const std::vector<std::string>&
MockInputMethodManager::GetActiveInputMethodIds() const {
return active_input_method_ids_;
}
size_t MockInputMethodManager::GetNumActiveInputMethods() const {
return 1;
}
const InputMethodDescriptor* MockInputMethodManager::GetInputMethodFromId(
const std::string& input_method_id) const {
static const InputMethodDescriptor defaultInputMethod =
InputMethodUtil::GetFallbackInputMethodDescriptor();
for (size_t i = 0; i < active_input_method_ids_.size(); i++) {
if (input_method_id == active_input_method_ids_[i]) {
return &defaultInputMethod;
}
}
return NULL;
}
void MockInputMethodManager::EnableLoginLayouts(
const std::string& language_code,
const std::vector<std::string>& initial_layout) {
}
bool MockInputMethodManager::ReplaceEnabledInputMethods(
const std::vector<std::string>& new_active_input_method_ids) {
return true;
}
bool MockInputMethodManager::EnableInputMethod(
const std::string& new_active_input_method_id) {
return true;
}
void MockInputMethodManager::ChangeInputMethod(
const std::string& input_method_id) {
}
void MockInputMethodManager::ActivateInputMethodMenuItem(
const std::string& key) {
}
void MockInputMethodManager::AddInputMethodExtension(
const std::string& extension_id,
const InputMethodDescriptors& descriptors,
InputMethodEngineInterface* instance) {
}
void MockInputMethodManager::RemoveInputMethodExtension(
const std::string& extension_id) {
}
void MockInputMethodManager::GetInputMethodExtensions(
InputMethodDescriptors* result) {
}
void MockInputMethodManager::SetEnabledExtensionImes(
std::vector<std::string>* ids) {
}
void MockInputMethodManager::SetInputMethodLoginDefault() {
}
void MockInputMethodManager::SetInputMethodLoginDefaultFromVPD(
const std::string& locale, const std::string& layout) {
}
bool MockInputMethodManager::SwitchToNextInputMethod() {
return true;
}
bool MockInputMethodManager::SwitchToPreviousInputMethod(
const ui::Accelerator& accelerator) {
return true;
}
bool MockInputMethodManager::SwitchInputMethod(
const ui::Accelerator& accelerator) {
return true;
}
InputMethodDescriptor MockInputMethodManager::GetCurrentInputMethod() const {
InputMethodDescriptor descriptor =
InputMethodUtil::GetFallbackInputMethodDescriptor();
if (!current_input_method_id_.empty()) {
return InputMethodDescriptor(current_input_method_id_,
descriptor.name(),
descriptor.indicator(),
descriptor.keyboard_layouts(),
descriptor.language_codes(),
true,
GURL(), // options page url.
GURL()); // input view page url.
}
return descriptor;
}
bool MockInputMethodManager::IsISOLevel5ShiftUsedByCurrentInputMethod() const {
return mod3_used_;
}
bool MockInputMethodManager::IsAltGrUsedByCurrentInputMethod() const {
return false;
}
ImeKeyboard* MockInputMethodManager::GetImeKeyboard() { return &keyboard_; }
InputMethodUtil* MockInputMethodManager::GetInputMethodUtil() {
return &util_;
}
ComponentExtensionIMEManager*
MockInputMethodManager::GetComponentExtensionIMEManager() {
return comp_ime_manager_.get();
}
void MockInputMethodManager::SetComponentExtensionIMEManager(
scoped_ptr<ComponentExtensionIMEManager> comp_ime_manager) {
comp_ime_manager_ = comp_ime_manager.Pass();
}
void MockInputMethodManager::set_application_locale(const std::string& value) {
delegate_.set_active_locale(value);
}
bool MockInputMethodManager::IsLoginKeyboard(
const std::string& layout) const {
return true;
}
bool MockInputMethodManager::MigrateInputMethods(
std::vector<std::string>* input_method_ids) {
return false;
}
} // namespace input_method
} // namespace chromeos
| ondra-novak/chromium.src | chrome/browser/chromeos/input_method/mock_input_method_manager.cc | C++ | bsd-3-clause | 5,672 |
package edu.gemini.qpt.ui.util;
import static edu.gemini.qpt.core.Variant.Flag.BACKGROUND_CNS;
import static edu.gemini.qpt.core.Variant.Flag.BLOCKED;
import static edu.gemini.qpt.core.Variant.Flag.CC_UQUAL;
import static edu.gemini.qpt.core.Variant.Flag.CONFIG_UNAVAILABLE;
import static edu.gemini.qpt.core.Variant.Flag.LGS_UNAVAILABLE;
import static edu.gemini.qpt.core.Variant.Flag.ELEVATION_CNS;
import static edu.gemini.qpt.core.Variant.Flag.INACTIVE;
import static edu.gemini.qpt.core.Variant.Flag.INSTRUMENT_UNAVAILABLE;
import static edu.gemini.qpt.core.Variant.Flag.IN_PROGRESS;
import static edu.gemini.qpt.core.Variant.Flag.IQ_UQUAL;
import static edu.gemini.qpt.core.Variant.Flag.MULTI_CNS;
import static edu.gemini.qpt.core.Variant.Flag.OVER_ALLOCATED;
import static edu.gemini.qpt.core.Variant.Flag.OVER_QUALIFIED;
import static edu.gemini.qpt.core.Variant.Flag.SCHEDULED;
import static edu.gemini.qpt.core.Variant.Flag.TIME_CONSTRAINED;
import static edu.gemini.qpt.core.Variant.Flag.TIMING_CNS;
import static edu.gemini.qpt.core.Variant.Flag.WV_UQUAL;
import static edu.gemini.qpt.shared.util.StructuredProgramID.Type.ENG;
import static edu.gemini.qpt.shared.util.StructuredProgramID.Type.CAL;
import static edu.gemini.qpt.ui.util.SharedIcons.*;
import java.awt.Color;
import java.util.EnumSet;
import java.util.Set;
import javax.swing.Icon;
import edu.gemini.qpt.core.Variant.Flag;
import edu.gemini.qpt.shared.sp.Obs;
public class CandidateDecorator {
private static final EnumSet<Flag> DARK_GRAY = EnumSet.of(
OVER_QUALIFIED
);
private static final EnumSet<Flag> GRAY = EnumSet.of(
INSTRUMENT_UNAVAILABLE,
CONFIG_UNAVAILABLE,
LGS_UNAVAILABLE,
BLOCKED,
INACTIVE,
IQ_UQUAL,
WV_UQUAL,
CC_UQUAL,
OVER_ALLOCATED,
ELEVATION_CNS,
BACKGROUND_CNS,
TIMING_CNS,
MULTI_CNS
);
private static final EnumSet<Flag> CROSSED_OUT = EnumSet.of(
IQ_UQUAL,
WV_UQUAL,
CC_UQUAL,
INSTRUMENT_UNAVAILABLE,
CONFIG_UNAVAILABLE,
LGS_UNAVAILABLE,
ELEVATION_CNS,
BACKGROUND_CNS,
TIMING_CNS,
MULTI_CNS
);
public static Icon getIcon(Set<Flag> flags, Obs obs) {
boolean isGray = isGray(flags);
boolean isDim = isDarkGray(flags);
// Find the base icon.
Icon icon;
if (obs.getObsClass() == null) {
icon = ICON_BOGUS;
} else {
switch (obs.getObsClass()) {
case ACQ:
case ACQ_CAL: icon = ICON_ACQ; break;
case DAY_CAL:
case PARTNER_CAL:
case PROG_CAL: icon = isGray ? ICON_CALIB_DIS : isDim ? ICON_CALIB_DIM : ICON_CALIB; break;
case SCIENCE: icon = isGray ? ICON_SCIENCE_DIS : isDim ? ICON_SCIENCE_DIM : ICON_SCIENCE; break;
default:
throw new Error("Impossible.");
}
}
if ( obs.getProg().getStructuredProgramId().getType() == ENG ) {
icon = isGray ? ICON_DAYCAL_DIS : isDim ? ICON_DAYENG_DIM : ICON_DAYENG;
} else if ( obs.getProg().getStructuredProgramId().getType() == CAL ) {
icon = isGray ? ICON_DAYCAL_DIS : isDim ? ICON_DAYCAL_DIM : ICON_DAYCAL;
}
// If in progress
if (flags.contains(IN_PROGRESS)) {
icon = new CompositeIcon(icon, OVL_IN_PROGRESS);
}
// Add slash if we need to.
if (isCrossedOut(flags)) {
icon = new CompositeIcon(icon, OVL_CROSSED_OUT);
}
// If timing window (after slash so it's on top)
if (flags.contains(TIME_CONSTRAINED)) {
icon = new CompositeIcon(icon, OVL_TIMING);
}
if (flags.contains(SCHEDULED)) {
icon = new CompositeIcon(icon, OVL_SCHEDULED);
}
//If LGS observation
if (obs.getLGS()) {
icon = new CompositeIcon(icon, OVL_LGS);
}
return icon;
}
public static Color getColor(Set<Flag> flags) {
return isGray(flags) ? Color.GRAY :
isDarkGray(flags) ? Color.DARK_GRAY : Color.BLACK;
}
private static boolean isGray(Set<Flag> flags) {
for (Flag f: GRAY) {
if (flags.contains(f)) return true;
}
return isCrossedOut(flags);
}
private static boolean isDarkGray(Set<Flag> flags) {
if (isGray(flags)) return false;
for (Flag f: DARK_GRAY) {
if (flags.contains(f)) return true;
}
return false;
}
private static boolean isCrossedOut(Set<Flag> flags) {
for (Flag f: CROSSED_OUT) {
if (flags.contains(f)) return true;
}
return false;
}
}
| arturog8m/ocs | bundle/edu.gemini.qpt.client/src/main/java/edu/gemini/qpt/ui/util/CandidateDecorator.java | Java | bsd-3-clause | 4,273 |
using System;
namespace NServiceKit.DataAnnotations
{
/// <summary>Attribute for alias.</summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class | AttributeTargets.Struct)]
public class AliasAttribute : Attribute
{
/// <summary>Gets or sets the name.</summary>
///
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>Initializes a new instance of the NServiceKit.DataAnnotations.AliasAttribute class.</summary>
///
/// <param name="name">The name.</param>
public AliasAttribute(string name)
{
this.Name = name;
}
}
} | NServiceKit/NServiceKit | src/NServiceKit.Interfaces/DataAnnotations/AliasAttribute.cs | C# | bsd-3-clause | 653 |
import numpy as np
import glob
dir2data = "/Volumes/HGST5/APS1504_AlCu/recon/D_Coarsening_2/recon_2/"
prefix = "recon_"
dir2out = "/Volumes/HGST5/APS1504_AlCu/recon/D_Coarsening_2/combine_test/"
flist = glob.glob(dir2data+prefix+"*.bin")
def parse_filename(filename):
t, z = filename.split('.')[0].split('_')[-3::2]
return int(t), int(z)
fdict = {}
for f in flist:
t, z = parse_filename(f)
try:
fdict[t].append(z)
except KeyError:
fdict[t] = [z]
for t, zlist in fdict.items():
out_name = dir2out+prefix+"t_%d.bin" % t
print("Opening output file %s" % out_name)
fout = open(out_name, 'wb')
for z in sorted(zlist):
data_name = dir2data+prefix+"t_%d_z_%d.bin" % (t, z)
print("Reading data file %s" % data_name)
fin = open(data_name, 'rb')
fout.write(fin.read())
fin.close()
fout.close()
| decarlof/timbir | doc/collection/APS_32ID/non-interlaced/combine_bin.py | Python | bsd-3-clause | 889 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/mediastream/RTCStatsResponse.h"
namespace WebCore {
PassRefPtr<RTCStatsResponse> RTCStatsResponse::create()
{
return adoptRef(new RTCStatsResponse());
}
RTCStatsResponse::RTCStatsResponse()
{
ScriptWrappable::init(this);
}
PassRefPtr<RTCStatsReport> RTCStatsResponse::namedItem(const AtomicString& name)
{
if (m_idmap.find(name) != m_idmap.end())
return m_result[m_idmap.get(name)];
return 0;
}
size_t RTCStatsResponse::addReport(String id, String type, double timestamp)
{
m_result.append(RTCStatsReport::create(id, type, timestamp));
m_idmap.add(id, m_result.size() - 1);
return m_result.size() - 1;
}
void RTCStatsResponse::addStatistic(size_t report, String name, String value)
{
ASSERT_WITH_SECURITY_IMPLICATION(report >= 0 && report < m_result.size());
m_result[report]->addStatistic(name, value);
}
} // namespace WebCore
| windyuuy/opera | chromium/src/third_party/WebKit/Source/modules/mediastream/RTCStatsResponse.cpp | C++ | bsd-3-clause | 2,278 |
var test = require("test");
try {
require("a");
require("A");
test.assert(false, "should fail to require alternate spelling");
} catch (error) {
}
test.print("DONE", "info");
| kriskowal/mr | test/case-sensitive/program.js | JavaScript | bsd-3-clause | 187 |
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/cpu/compiler/passes/memory_sequence_combination_pass.h"
#include "xenia/base/profiling.h"
namespace xe {
namespace cpu {
namespace compiler {
namespace passes {
// TODO(benvanik): remove when enums redefined.
using namespace xe::cpu::hir;
using xe::cpu::hir::HIRBuilder;
using xe::cpu::hir::Instr;
using xe::cpu::hir::Value;
MemorySequenceCombinationPass::MemorySequenceCombinationPass()
: CompilerPass() {}
MemorySequenceCombinationPass::~MemorySequenceCombinationPass() = default;
bool MemorySequenceCombinationPass::Run(HIRBuilder* builder) {
// Run over all loads and stores and see if we can collapse sequences into the
// fat opcodes. See the respective utility functions for examples.
auto block = builder->first_block();
while (block) {
auto i = block->instr_head;
while (i) {
if (i->opcode == &OPCODE_LOAD_info ||
i->opcode == &OPCODE_LOAD_OFFSET_info) {
CombineLoadSequence(i);
} else if (i->opcode == &OPCODE_STORE_info ||
i->opcode == &OPCODE_STORE_OFFSET_info) {
CombineStoreSequence(i);
}
i = i->next;
}
block = block->next;
}
return true;
}
void MemorySequenceCombinationPass::CombineLoadSequence(Instr* i) {
// Load with swap:
// v1.i32 = load v0
// v2.i32 = byte_swap v1.i32
// becomes:
// v1.i32 = load v0, [swap]
//
// Load with swap and extend:
// v1.i32 = load v0
// v2.i32 = byte_swap v1.i32
// v3.i64 = zero_extend v2.i32
// becomes:
// v1.i64 = load_convert v0, [swap|i32->i64,zero]
if (!i->dest->use_head) {
// No uses of the load result - ignore. Will be killed by DCE.
return;
}
// Ensure all uses of the load result are BYTE_SWAP - if it's mixed we
// shouldn't transform as we'd have to introduce new swaps!
auto use = i->dest->use_head;
while (use) {
if (use->instr->opcode != &OPCODE_BYTE_SWAP_info) {
// Not a swap.
return;
}
// TODO(benvanik): allow uses by STORE (we can make that swap).
use = use->next;
}
// Merge byte swap into load.
// Note that we may have already been a swapped operation - this inverts that.
i->flags ^= LoadStoreFlags::LOAD_STORE_BYTE_SWAP;
// Replace use of byte swap value with loaded value.
// It's byte_swap vN -> assign vN, so not much to do.
use = i->dest->use_head;
while (use) {
auto next_use = use->next;
use->instr->opcode = &OPCODE_ASSIGN_info;
use->instr->flags = 0;
use = next_use;
}
// TODO(benvanik): merge in extend/truncate.
}
void MemorySequenceCombinationPass::CombineStoreSequence(Instr* i) {
// Store with swap:
// v1.i32 = ...
// v2.i32 = byte_swap v1.i32
// store v0, v2.i32
// becomes:
// store v0, v1.i32, [swap]
//
// Store with truncate and swap:
// v1.i64 = ...
// v2.i32 = truncate v1.i64
// v3.i32 = byte_swap v2.i32
// store v0, v3.i32
// becomes:
// store_convert v0, v1.i64, [swap|i64->i32,trunc]
auto src = i->src2.value;
if (i->opcode == &OPCODE_STORE_OFFSET_info) {
src = i->src3.value;
}
if (src->IsConstant()) {
// Constant value write - ignore.
return;
}
// Find source and ensure it is a byte swap.
auto def = src->def;
while (def && def->opcode == &OPCODE_ASSIGN_info) {
// Skip asignments.
def = def->src1.value->def;
}
if (!def || def->opcode != &OPCODE_BYTE_SWAP_info) {
// Not a swap/not defined?
return;
}
// Merge byte swap into store.
// Note that we may have already been a swapped operation - this inverts
// that.
i->flags ^= LoadStoreFlags::LOAD_STORE_BYTE_SWAP;
// Pull the original value (from before the byte swap).
// The byte swap itself will go away in DCE.
if (i->opcode == &OPCODE_STORE_info) {
i->set_src2(def->src1.value);
} else if (i->opcode == &OPCODE_STORE_OFFSET_info) {
i->set_src3(def->src1.value);
}
// TODO(benvanik): extend/truncate.
}
} // namespace passes
} // namespace compiler
} // namespace cpu
} // namespace xe
| sephiroth99/xenia | src/xenia/cpu/compiler/passes/memory_sequence_combination_pass.cc | C++ | bsd-3-clause | 4,525 |
// RUN: %clangxx_tsan -O1 --std=c++11 %s -o %t && %deflake %run %t 2>&1 | FileCheck %s
#include "custom_mutex.h"
// Test that failed TryLock does not induce parasitic synchronization.
Mutex mu(true, 0);
long data;
void *thr(void *arg) {
mu.Lock();
data++;
mu.Unlock();
mu.Lock();
barrier_wait(&barrier);
barrier_wait(&barrier);
mu.Unlock();
return 0;
}
int main() {
barrier_init(&barrier, 2);
pthread_t th;
pthread_create(&th, 0, thr, 0);
barrier_wait(&barrier);
if (mu.TryLock()) {
fprintf(stderr, "TryLock succeeded, should not\n");
exit(0);
}
data++;
barrier_wait(&barrier);
pthread_join(th, 0);
fprintf(stderr, "DONE\n");
return 0;
}
// CHECK: ThreadSanitizer: data race
// CHECK-NEXT: Write of size 8 at {{.*}} by main thread:
// CHECK-NEXT: #0 main {{.*}}custom_mutex1.cc:29
// CHECK: DONE
| youtube/cobalt | third_party/llvm-project/compiler-rt/test/tsan/custom_mutex1.cc | C++ | bsd-3-clause | 853 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/synchronization/waitable_event.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/intents/register_intent_handler_infobar_delegate.h"
#include "chrome/browser/intents/web_intents_registry.h"
#include "chrome/browser/intents/web_intents_registry_factory.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/browser/ui/tab_contents/test_tab_contents.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/web_intent_service_data.h"
using content::BrowserThread;
namespace {
class MockWebIntentsRegistry : public WebIntentsRegistry {
public:
MOCK_METHOD1(RegisterIntentService,
void(const webkit_glue::WebIntentServiceData&));
};
ProfileKeyedService* BuildMockWebIntentsRegistry(Profile* profile) {
return new MockWebIntentsRegistry;
}
MockWebIntentsRegistry* BuildForProfile(Profile* profile) {
return static_cast<MockWebIntentsRegistry*>(
WebIntentsRegistryFactory::GetInstance()->SetTestingFactoryAndUse(
profile, BuildMockWebIntentsRegistry));
}
class RegisterIntentHandlerInfoBarDelegateTest
: public TabContentsTestHarness {
protected:
RegisterIntentHandlerInfoBarDelegateTest()
: ui_thread_(BrowserThread::UI, MessageLoopForUI::current()),
db_thread_(BrowserThread::DB, MessageLoopForUI::current()) {}
virtual void SetUp() {
TabContentsTestHarness::SetUp();
profile()->CreateWebDataService();
web_intents_registry_ = BuildForProfile(profile());
}
virtual void TearDown() {
web_intents_registry_ = NULL;
TabContentsTestHarness::TearDown();
}
MockWebIntentsRegistry* web_intents_registry_;
private:
content::TestBrowserThread ui_thread_;
content::TestBrowserThread db_thread_;
DISALLOW_COPY_AND_ASSIGN(RegisterIntentHandlerInfoBarDelegateTest);
};
TEST_F(RegisterIntentHandlerInfoBarDelegateTest, Accept) {
webkit_glue::WebIntentServiceData service;
service.service_url = GURL("google.com");
service.action = ASCIIToUTF16("http://webintents.org/share");
service.type = ASCIIToUTF16("text/url");
RegisterIntentHandlerInfoBarDelegate delegate(
tab_contents()->infobar_tab_helper(),
WebIntentsRegistryFactory::GetForProfile(profile()),
service, NULL, GURL());
EXPECT_CALL(*web_intents_registry_, RegisterIntentService(service));
delegate.Accept();
}
} // namespace
| keishi/chromium | chrome/browser/intents/register_intent_handler_infobar_delegate_unittest.cc | C++ | bsd-3-clause | 2,699 |
var cdb = require('cartodb.js-v3');
var _ = require('underscore-cdb-v3');
/**
* Model for an individual WMS/WMTS layer.
*/
module.exports = cdb.core.Model.extend({
defaults: {
state: 'idle', //, saving, saveDone, saveFail
layer: undefined // set after saveDone
},
canSave: function(baseLayers) {
return !_.any(baseLayers.custom(), function(customLayer) {
return customLayer.get('name') === this.get('title');
}, this);
},
save: function() {
this.set('state', 'saving');
this._shouldBeProxied() ? this._createProxiedLayer() : this._newTileLayer();
},
_shouldBeProxied: function() {
if (this.get('type') === 'wmts') {
var supportedMatrixSets = cdb.admin.WMSService.supportedMatrixSets(this.get('matrix_sets') || []);
return supportedMatrixSets.length > 0;
}
return true;
},
_createProxiedLayer: function() {
var self = this;
var w = new cdb.admin.WMSService({
wms_url: this.url(),
title: this.get('title'),
name: this.get('name'),
layer: this.get('name'),
srs: this.get('srs'),
bounding_boxes: this.get('llbbox'),
type: this.get('type'), // wms/wmts
matrix_sets: this.get('matrix_sets')
});
// Event tracking "WMS layer selected"
cdb.god.trigger('metrics', 'select_wms', {
email: window.user_data.email
});
var self = this;
w.save({}, {
success: function(m) {
var tileLayer;
try {
tileLayer = m.newTileLayer();
} catch(e) {
}
if (tileLayer) {
self._setNewTileLayer(tileLayer);
} else {
self.set('state', 'saveFail');
}
},
error: function() {
self.set('state', 'saveFail');
}
});
return w;
},
_setNewTileLayer: function(tileLayer) {
this.set({
state: 'saveDone',
tileLayer: tileLayer
});
},
_newTileLayer: function() {
var tileLayer = cdb.admin.TileLayer.byCustomURL(this._xyzURLTemplate(), false);
tileLayer.set({
name: this.get('title') || this.get('name'),
attribution: this.get('attribution'),
bounding_boxes: this.get('llbbox')
});
this._setNewTileLayer(tileLayer);
return tileLayer;
},
_xyzURLTemplate: function() {
var urlTemplate = this.get('url_template') || '';
// Convert the proxy template variables to XYZ format, http://foo.com/bar/%%(z)s/%%(x)s/%%(y)s.png"
return urlTemplate.replace(/%%\((\w)\)s/g, '{$1}');
}
});
| codeandtheory/cartodb | lib/assets/javascripts/cartodb/common/dialogs/add_custom_basemap/wms/layer_model.js | JavaScript | bsd-3-clause | 2,510 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/display/shared_display_edge_indicator.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/wm/coordinate_conversion.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/gfx/animation/throb_animation.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/display.h"
#include "ui/gfx/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
const int kIndicatorAnimationDurationMs = 1000;
class IndicatorView : public views::View {
public:
IndicatorView() {
}
~IndicatorView() override {}
void SetColor(SkColor color) {
color_ = color;
SchedulePaint();
}
// views::Views overrides:
void OnPaint(gfx::Canvas* canvas) override {
canvas->FillRect(gfx::Rect(bounds().size()), color_);
}
private:
SkColor color_;
DISALLOW_COPY_AND_ASSIGN(IndicatorView);
};
views::Widget* CreateWidget(const gfx::Rect& bounds,
views::View* contents_view) {
views::Widget* widget = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.keep_on_top = true;
// We set the context to the primary root window; this is OK because the ash
// stacking controller will still place us in the correct RootWindow.
params.context = Shell::GetPrimaryRootWindow();
widget->set_focus_on_creation(false);
widget->Init(params);
widget->SetVisibilityChangedAnimationsEnabled(false);
widget->GetNativeWindow()->SetName("SharedEdgeIndicator");
widget->SetContentsView(contents_view);
gfx::Display display = gfx::Screen::GetScreen()->GetDisplayMatching(bounds);
aura::Window* window = widget->GetNativeWindow();
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(window->GetRootWindow());
screen_position_client->SetBounds(window, bounds, display);
widget->Show();
return widget;
}
} // namespace
SharedDisplayEdgeIndicator::SharedDisplayEdgeIndicator()
: src_indicator_(NULL),
dst_indicator_(NULL) {
}
SharedDisplayEdgeIndicator::~SharedDisplayEdgeIndicator() {
Hide();
}
void SharedDisplayEdgeIndicator::Show(const gfx::Rect& src_bounds,
const gfx::Rect& dst_bounds) {
DCHECK(!src_indicator_);
DCHECK(!dst_indicator_);
src_indicator_ = new IndicatorView;
dst_indicator_ = new IndicatorView;
CreateWidget(src_bounds, src_indicator_);
CreateWidget(dst_bounds, dst_indicator_);
animation_.reset(new gfx::ThrobAnimation(this));
animation_->SetThrobDuration(kIndicatorAnimationDurationMs);
animation_->StartThrobbing(-1 /* infinite */);
}
void SharedDisplayEdgeIndicator::Hide() {
if (src_indicator_)
src_indicator_->GetWidget()->Close();
src_indicator_ = NULL;
if (dst_indicator_)
dst_indicator_->GetWidget()->Close();
dst_indicator_ = NULL;
}
void SharedDisplayEdgeIndicator::AnimationProgressed(
const gfx::Animation* animation) {
int value = animation->CurrentValueBetween(0, 255);
SkColor color = SkColorSetARGB(0xFF, value, value, value);
if (src_indicator_)
static_cast<IndicatorView*>(src_indicator_)->SetColor(color);
if (dst_indicator_)
static_cast<IndicatorView*>(dst_indicator_)->SetColor(color);
}
} // namespace ash
| was4444/chromium.src | ash/display/shared_display_edge_indicator.cc | C++ | bsd-3-clause | 3,615 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "core/html/parser/HTMLEntityParser.h"
#include <gtest/gtest.h>
namespace blink {
TEST(HTMLEntityParserTest, ConsumeHTMLEntityIncomplete)
{
String original("am"); // Incomplete by purpose.
SegmentedString src(original);
DecodedHTMLEntity entity;
bool notEnoughCharacters = false;
bool success = consumeHTMLEntity(src, entity, notEnoughCharacters);
EXPECT_TRUE(notEnoughCharacters);
EXPECT_FALSE(success);
// consumeHTMLEntity should recover the original SegmentedString state if failed.
EXPECT_EQ(original, src.toString());
}
} // namespace blink
| Bysmyyr/chromium-crosswalk | third_party/WebKit/Source/core/html/parser/HTMLEntityParserTest.cpp | C++ | bsd-3-clause | 783 |
<?php
$lang["reports_all"] = "Todo";
$lang["reports_all_time"] = "Todos";
$lang["reports_categories"] = "Categorías";
$lang["reports_categories_summary_report"] = "Reporte de Resumen de Categorías";
$lang["reports_category"] = "Categoría";
$lang["reports_comments"] = "Comentarios";
$lang["reports_count"] = "Cuenta";
$lang["reports_customer"] = "Cliente";
$lang["reports_customers"] = "Clientes";
$lang["reports_customers_summary_report"] = "Reporte de Resumen de Clientes";
$lang["reports_date"] = "Fecha";
$lang["reports_date_range"] = "Rango de Fecha";
$lang["reports_description"] = "Descripción";
$lang["reports_detailed_receivings_report"] = "Reporte Detallado de Entradas";
$lang["reports_detailed_reports"] = "Reportes Detallados";
$lang["reports_detailed_requisition_report"] = "Reporte Detallado de Requisiciones";
$lang["reports_detailed_sales_report"] = "Reporte de Ventas Detallado";
$lang["reports_discount"] = "Descuento";
$lang["reports_discount_percent"] = "Porcentaje de Descuento";
$lang["reports_discounts"] = "Descuentos";
$lang["reports_discounts_summary_report"] = "Reporte de Resumen de Descuentos";
$lang["reports_employee"] = "Empleado";
$lang["reports_employees"] = "Empleados";
$lang["reports_employees_summary_report"] = "Reporte de Resumen de Empleados";
$lang["reports_graphical_reports"] = "Reportes Gráficos";
$lang["reports_inventory"] = "Inventario";
$lang["reports_inventory_low"] = "Inventario Bajo";
$lang["reports_inventory_low_report"] = "Reporte de Inventario Bajo";
$lang["reports_inventory_reports"] = "Reportes de Inventario";
$lang["reports_inventory_summary"] = "Resumen de Inventario";
$lang["reports_inventory_summary_report"] = "Reporte de Resumen de Inventario";
$lang["reports_item"] = "Artículo";
$lang["reports_item_name"] = "Nombre del Artículo";
$lang["reports_item_number"] = "Número de Artículo";
$lang["reports_items"] = "Artículos";
$lang["reports_items_purchased"] = "Artículos Comprados";
$lang["reports_items_received"] = "Artículos Recibidos";
$lang["reports_items_summary_report"] = "Reporte de Resumen de Artículos";
$lang["reports_last_7"] = "Últimos 7 Días";
$lang["reports_last_month"] = "Último Mes";
$lang["reports_last_year"] = "Último Año";
$lang["reports_low_inventory"] = "Inventario Bajo";
$lang["reports_low_inventory_report"] = "Reporte de Inventario Bajo";
$lang["reports_name"] = "Nombre";
$lang["reports_payment_type"] = "Tipo de Pago";
$lang["reports_payments"] = "Pagos";
$lang["reports_payments_summary_report"] = "Reporte de Resumen de Pagos";
$lang["reports_profit"] = "Ganancia";
$lang["reports_quantity_purchased"] = "Cantidad Comprada";
$lang["reports_received_by"] = "Recibido por";
$lang["reports_receiving_id"] = "ID de Recepción";
$lang["reports_receiving_type"] = "Tipo de Recepción";
$lang["reports_receivings"] = "Entradas";
$lang["reports_reorder_level"] = "Cantidad Mínima";
$lang["reports_report"] = "Reporte";
$lang["reports_report_input"] = "Entrada de Reporte";
$lang["reports_reports"] = "Reportes";
$lang["reports_requisition"] = "Requisición";
$lang["reports_requisition_by"] = "Requisición por";
$lang["reports_requisition_id"] = "ID de Requisición";
$lang["reports_requisition_item"] = "Articulo de Requisición";
$lang["reports_requisition_item_quantity"] = "Cantidad de Articulo de Requisición";
$lang["reports_requisition_related_item"] = "Articulo de Requisición relacionado";
$lang["reports_requisition_related_item_total_quantity"] = "Cantidad Total de Articulo de Requisición";
$lang["reports_requisition_related_item_unit_quantity"] = "Cantidad Unitaria de Articulo de Requisición";
$lang["reports_requisitions"] = "Requisiciones";
$lang["reports_returns"] = "Devoluciones";
$lang["reports_revenue"] = "Ingresos";
$lang["reports_sale_id"] = "ID de Venta";
$lang["reports_sale_type"] = "Tipo de Venta";
$lang["reports_sales"] = "Ventas";
$lang["reports_sales_amount"] = "Monto de ventas";
$lang["reports_sales_summary_report"] = "Reporte de Resumen de Ventas";
$lang["reports_serial_number"] = "S/N:";
$lang["reports_sold_by"] = "Vendido Por";
$lang["reports_sold_to"] = "Vendido A";
$lang["reports_stock_location"] = "Ubicación de Inventario";
$lang["reports_subtotal"] = "Subtotal";
$lang["reports_summary_reports"] = "Reportes Resumidos";
$lang["reports_supplied_by"] = "Provisto por";
$lang["reports_supplier"] = "Proveedor";
$lang["reports_suppliers"] = "Proveedores";
$lang["reports_suppliers_summary_report"] = "Reporte de Resumen de Proveedores";
$lang["reports_tax"] = "Impuesto";
$lang["reports_tax_percent"] = "Porcentaje de Impuestos";
$lang["reports_taxes"] = "Impuestos";
$lang["reports_taxes_summary_report"] = "Reporte de Resumen de Impuestos";
$lang["reports_this_month"] = "Este Mes";
$lang["reports_this_year"] = "Este Año";
$lang["reports_today"] = "Hoy";
$lang["reports_total"] = "Total";
$lang["reports_type"] = "Tipo";
$lang["reports_welcome_message"] = "Bienvenido(a) al panel de reportes. Selecciona un reporte para verlo.";
$lang["reports_yesterday"] = "Ayer";
| bravokeyl502/opensourcepos | application/language/es/reports_lang.php | PHP | mit | 5,033 |
<?php
/*
* 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.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\ThemeBundle\Translation\Finder;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ThemeBundle\Translation\Finder\TranslationFilesFinderInterface;
/**
* @author Kamil Kokot <kamil@kokot.me>
*/
final class OrderingTranslationFilesFinderSpec extends ObjectBehavior
{
function let(TranslationFilesFinderInterface $translationFilesFinder): void
{
$this->beConstructedWith($translationFilesFinder);
}
function it_implements_Translation_Files_Finder_interface(): void
{
$this->shouldImplement(TranslationFilesFinderInterface::class);
}
function it_puts_application_translations_files_before_bundle_translations_files(
TranslationFilesFinderInterface $translationFilesFinder
): void {
$translationFilesFinder->findTranslationFiles('/some/path/to/theme')->willReturn([
'/some/path/to/theme/AcmeBundle/messages.en.yml',
'/some/path/to/theme/translations/messages.en.yml',
'/some/path/to/theme/YcmeBundle/messages.en.yml',
]);
$this->findTranslationFiles('/some/path/to/theme')->shouldStartIteratingAs(['/some/path/to/theme/translations/messages.en.yml']);
}
}
| rainlike/justshop | vendor/sylius/sylius/src/Sylius/Bundle/ThemeBundle/spec/Translation/Finder/OrderingTranslationFilesFinderSpec.php | PHP | mit | 1,448 |
#!/usr/bin/env python
""" Sincronizarea a doua directoare """
import os
import time
import shutil
# pylint: disable=too-many-locals
# pylint: disable=global-statement
OLD_FILESET = dict()
def copyfile(src, dest):
""" Copiaza fisiere cu metadate """
destinatie = os.path.split(dest)
dest = destinatie[0]
if not os.path.exists(dest):
os.makedirs(dest)
shutil.copy2(src, dest)
def get_fileset(path):
""" Construieste lista de fisiere din directorul dat si din subdirectoare,
cu data ultimei moficari """
fileset = dict()
for root, _, files in list(os.walk(path)):
if not os.path.islink(root):
for fname in files:
cfil = os.path.join(os.path.relpath(root, path), fname)
fileset[cfil] = int(os.path.getmtime(os.path.join(path, cfil)))
return fileset
def sync_folders(folder1, folder2):
""" Functia de sincronizare a directoarelor """
fileset1 = get_fileset(folder1)
files1 = set(fileset1.keys())
fileset2 = get_fileset(folder2)
files2 = set(fileset2.keys())
total_files = files1.union(files2)
common_files = files1.intersection(files2)
ch_comm_files = {o for o in common_files if fileset1[o] != fileset2[o]}
ch_fs1_files = {o for o in ch_comm_files if fileset1[o] > fileset2[o]}
ch_fs2_files = {o for o in ch_comm_files if fileset2[o] > fileset1[o]}
files_only_in_set1 = total_files - files2
files_only_in_set2 = total_files - files1
deleted_set1 = files_only_in_set2.intersection(set(OLD_FILESET.keys()))
deleted_set2 = files_only_in_set1.intersection(set(OLD_FILESET.keys()))
new_files_in_set1 = files_only_in_set1 - deleted_set2
new_files_in_set2 = files_only_in_set2 - deleted_set1
for fisier in new_files_in_set1.union(ch_fs1_files):
copyfile(os.path.join(folder1, fisier), os.path.join(folder2, fisier))
print "se copiaza 1->2 ", fisier
for fisier in new_files_in_set2.union(ch_fs2_files):
copyfile(os.path.join(folder2, fisier), os.path.join(folder1, fisier))
print "se copiaza 2->1 ", fisier
for fisier in deleted_set1:
os.remove(os.path.join(folder2, fisier))
print "se sterge din 2 ", fisier
for fisier in deleted_set2:
os.remove(os.path.join(folder1, fisier))
print "se sterge din 1 ", fisier
def main():
""" Sincronizeaza 2 directoare """
global OLD_FILESET
folder1 = "/home/iulian/Desktop/testSync/A"
folder2 = "/home/iulian/Desktop/testSync/B"
interval_sincronizare = 10 # sec
while 1:
sync_folders(folder1, folder2)
OLD_FILESET = get_fileset(folder1)
time.sleep(interval_sincronizare)
if __name__ == "__main__":
main()
| c-square/python-lab | python/solutii/iulian_bute/sync.py | Python | mit | 2,742 |
package org.bouncycastle.openpgp.operator.bc;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.bcpg.ECDHPublicBCPGKey;
import org.bouncycastle.bcpg.ECSecretBCPGKey;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedAsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.Wrapper;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ElGamalPrivateKeyParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.operator.PGPDataDecryptor;
import org.bouncycastle.openpgp.operator.PGPPad;
import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.RFC6637KDFCalculator;
/**
* A decryptor factory for handling public key decryption operations.
*/
public class BcPublicKeyDataDecryptorFactory
implements PublicKeyDataDecryptorFactory
{
private BcPGPKeyConverter keyConverter = new BcPGPKeyConverter();
private PGPPrivateKey privKey;
public BcPublicKeyDataDecryptorFactory(PGPPrivateKey privKey)
{
this.privKey = privKey;
}
public byte[] recoverSessionData(int keyAlgorithm, byte[][] secKeyData)
throws PGPException
{
try
{
if (keyAlgorithm != PGPPublicKey.ECDH)
{
AsymmetricBlockCipher c = BcImplProvider.createPublicKeyCipher(keyAlgorithm);
AsymmetricKeyParameter key = keyConverter.getPrivateKey(privKey);
BufferedAsymmetricBlockCipher c1 = new BufferedAsymmetricBlockCipher(c);
c1.init(false, key);
if (keyAlgorithm == PGPPublicKey.RSA_ENCRYPT
|| keyAlgorithm == PGPPublicKey.RSA_GENERAL)
{
byte[] bi = secKeyData[0];
c1.processBytes(bi, 2, bi.length - 2);
}
else
{
BcPGPKeyConverter converter = new BcPGPKeyConverter();
ElGamalPrivateKeyParameters parms = (ElGamalPrivateKeyParameters)converter.getPrivateKey(privKey);
int size = (parms.getParameters().getP().bitLength() + 7) / 8;
byte[] tmp = new byte[size];
byte[] bi = secKeyData[0]; // encoded MPI
if (bi.length - 2 > size) // leading Zero? Shouldn't happen but...
{
c1.processBytes(bi, 3, bi.length - 3);
}
else
{
System.arraycopy(bi, 2, tmp, tmp.length - (bi.length - 2), bi.length - 2);
c1.processBytes(tmp, 0, tmp.length);
}
bi = secKeyData[1]; // encoded MPI
for (int i = 0; i != tmp.length; i++)
{
tmp[i] = 0;
}
if (bi.length - 2 > size) // leading Zero? Shouldn't happen but...
{
c1.processBytes(bi, 3, bi.length - 3);
}
else
{
System.arraycopy(bi, 2, tmp, tmp.length - (bi.length - 2), bi.length - 2);
c1.processBytes(tmp, 0, tmp.length);
}
}
return c1.doFinal();
}
else
{
ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey)privKey.getPublicKeyPacket().getKey();
X9ECParameters x9Params = NISTNamedCurves.getByOID(ecKey.getCurveOID());
byte[] enc = secKeyData[0];
int pLen = ((((enc[0] & 0xff) << 8) + (enc[1] & 0xff)) + 7) / 8;
byte[] pEnc = new byte[pLen];
System.arraycopy(enc, 2, pEnc, 0, pLen);
byte[] keyEnc = new byte[enc[pLen + 2]];
System.arraycopy(enc, 2 + pLen + 1, keyEnc, 0, keyEnc.length);
Wrapper c = BcImplProvider.createWrapper(ecKey.getSymmetricKeyAlgorithm());
ECPoint S = x9Params.getCurve().decodePoint(pEnc).multiply(((ECSecretBCPGKey)privKey.getPrivateKeyDataPacket()).getX()).normalize();
RFC6637KDFCalculator rfc6637KDFCalculator = new RFC6637KDFCalculator(new BcPGPDigestCalculatorProvider().get(ecKey.getHashAlgorithm()), ecKey.getSymmetricKeyAlgorithm());
KeyParameter key = new KeyParameter(rfc6637KDFCalculator.createKey(ecKey.getCurveOID(), S, new BcKeyFingerprintCalculator().calculateFingerprint(privKey.getPublicKeyPacket())));
c.init(false, key);
return PGPPad.unpadSessionData(c.unwrap(keyEnc, 0, keyEnc.length));
}
}
catch (InvalidCipherTextException e)
{
throw new PGPException("exception encrypting session info: " + e.getMessage(), e);
}
}
public PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, int encAlgorithm, byte[] key)
throws PGPException
{
BlockCipher engine = BcImplProvider.createBlockCipher(encAlgorithm);
return BcUtil.createDataDecryptor(withIntegrityPacket, engine, key);
}
}
| sergeypayu/bc-java | pg/src/main/java/org/bouncycastle/openpgp/operator/bc/BcPublicKeyDataDecryptorFactory.java | Java | mit | 5,636 |
using System;
using System.Collections.Generic;
using System.Reflection;
using JetBrains.Annotations;
namespace Abp.Modules
{
/// <summary>
/// Used to store all needed information for a module.
/// </summary>
public class AbpModuleInfo
{
/// <summary>
/// The assembly which contains the module definition.
/// </summary>
public Assembly Assembly { get; }
/// <summary>
/// Type of the module.
/// </summary>
public Type Type { get; }
/// <summary>
/// Instance of the module.
/// </summary>
public AbpModule Instance { get; }
/// <summary>
/// All dependent modules of this module.
/// </summary>
public List<AbpModuleInfo> Dependencies { get; }
/// <summary>
/// Creates a new AbpModuleInfo object.
/// </summary>
public AbpModuleInfo([NotNull] Type type, [NotNull] AbpModule instance)
{
Check.NotNull(type, nameof(type));
Check.NotNull(instance, nameof(instance));
Type = type;
Instance = instance;
Assembly = Type.Assembly;
Dependencies = new List<AbpModuleInfo>();
}
public override string ToString()
{
return Type.AssemblyQualifiedName ??
Type.FullName;
}
}
} | 4nonym0us/aspnetboilerplate | src/Abp/Modules/AbpModuleInfo.cs | C# | mit | 1,401 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HoloToolkit.Unity
{
// Base class for show / hide - shows or hides fields & properties in the editor based on the value of a member in the target object
public abstract class ShowIfAttribute : Attribute
{
public string MemberName { get; protected set; }
public bool ShowIfConditionMet { get; protected set; }
#if UNITY_EDITOR
public abstract bool ShouldShow(object target);
protected static object GetMemberValue(object target, string memberName)
{
if (target == null)
throw new NullReferenceException("Target cannot be null.");
if (string.IsNullOrEmpty(memberName))
throw new NullReferenceException("MemberName cannot be null.");
Type targetType = target.GetType();
MemberInfo[] members = targetType.GetMember(memberName);
if (members.Length == 0)
throw new MissingMemberException("Couldn't find member '" + memberName + "'");
object memberValue;
switch (members[0].MemberType)
{
case MemberTypes.Field:
FieldInfo fieldInfo = targetType.GetField(memberName);
memberValue = fieldInfo.GetValue(target);
break;
case MemberTypes.Property:
PropertyInfo propertyInfo = targetType.GetProperty(memberName);
memberValue = propertyInfo.GetValue(target, null);
break;
default:
throw new MissingMemberException("Member '" + memberName + "' must be a field or property");
}
return memberValue;
}
protected static bool IsNullable(object target, string memberName)
{
if (target == null)
throw new NullReferenceException("Target cannot be null.");
if (string.IsNullOrEmpty(memberName))
throw new NullReferenceException("MemberName cannot be null.");
Type targetType = target.GetType();
MemberInfo[] members = targetType.GetMember(memberName);
if (members.Length == 0)
throw new MissingMemberException("Couldn't find member '" + memberName + "'");
Type memberType = members[0].DeclaringType;
if (!memberType.IsValueType)
return true;
if (Nullable.GetUnderlyingType(memberType) != null)
return true;
return false;
}
#endif
}
} | davidezordan/MixedRealitySamples | CubesDemoMRT/Assets/HoloToolkit/Utilities/Scripts/Attributes/ShowIfAttribute.cs | C# | mit | 2,808 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
export default [
'en-IE', [['a', 'p'], ['AM', 'PM'], ['a.m.', 'p.m.']],
[
['AM', 'PM'],
,
],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 0, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
[
'{1}, {0}',
,
'{1} \'at\' {0}',
],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '€', 'Euro',
{'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural
];
| rkirov/angular | packages/common/locales/en-IE.ts | TypeScript | mit | 1,554 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="id_ID" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About BlackCoin</source>
<translation>Tentang BlackCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>BlackCoin</b> version</source>
<translation><b>BlackCoin</b> versi</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers</source>
<translation>Copyright © 2009-2014 para pengembang Bitcoin
Copyright © 2012-2014 para pengembang NovaCoin
Copyright © 2014 para pengembang BlackCoin</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Buku Alamat</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Klik dua-kali untuk mengubah alamat atau label</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Buat alamat baru</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Salin alamat yang dipilih ke clipboard</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Alamat Baru</translation>
</message>
<message>
<location line="-43"/>
<source>These are your BlackCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Ini adalah alamat BlackCoin Anda untuk menerima pembayaran. Anda dapat memberikan alamat yang berbeda untuk setiap pengirim, sehingga Anda dapat melacak siapa yang membayar Anda.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Salin Alamat</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>Unjukkan &Kode QR</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a BlackCoin address</source>
<translation>Masukan pesan untuk membuktikan bahwa anda telah mempunyai adress BlackCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign & Pesan</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Menghapus alamat yang saat ini dipilih dari daftar yang tersedia</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified BlackCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Hapus</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+66"/>
<source>Copy &Label</source>
<translation>Salin &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Ubah</translation>
</message>
<message>
<location line="+248"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>File CSV (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Penulisan data ke file gagal %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(tidak ada label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog Kata kunci</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Masukkan kata kunci</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Kata kunci baru</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Ulangi kata kunci baru</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Hanya untuk staking</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Meng-enkripsikan dompet</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Operasi ini memerlukan kata kunci dompet Anda untuk membuka dompet ini.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Buka dompet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Operasi ini memerlukan kata kunci dompet Anda untuk mendekripsi dompet ini.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Men-dekripsikan dompet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Ubah kata kunci</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Masukkan kata kunci lama dan baru ke dompet ini.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Menkonfirmasi enkripsi dompet</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Apakah Anda yakin untuk mengenkripsi dompet Anda?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Peringatan: tombol Caps Lock aktif!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Dompet terenkripsi</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>BlackCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>BlackCoin akan ditutup untuk menyelesaikan proses enkripsi. Ingat bahwa dompet Anda tidak bisa di lindungi dengan enkripsi sepenuhny dari pencurian melalui infeksi malware di komputer Anda.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Enkripsi dompet gagal</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Enkripsi dompet gagal karena kesalahan internal. Dompet Anda tidak dienkripsi.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Kata kunci yang dimasukkan tidak cocok.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Gagal buka dompet</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Kata kunci yang dimasukkan untuk dekripsi dompet tidak cocok.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekripsi dompet gagal</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Passphrase dompet telah berhasil diubah.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>Pesan &penanda...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Tampilkan kilasan umum dari dompet</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transaksi</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Jelajah sejarah transaksi</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Buku Alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Mengedit daftar alamat-alamat dan label</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Tampilkan daftar alamat untuk menerima pembayaran</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>K&eluar</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Keluar dari aplikasi</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about BlackCoin</source>
<translation>Tunjukkan informasi tentang BlackCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Mengenai &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Tampilkan informasi mengenai Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Pilihan...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>%Enkripsi Dompet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>&Cadangkan Dompet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Ubah Kata Kunci...</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Ekspor...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a BlackCoin address</source>
<translation>Kirim koin ke alamat BlackCoin</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for BlackCoin</source>
<translation>Memodifikasi opsi aturan untuk BlackCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Mengekspor data dari tab saat ini ke dalam file</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Mengenkripsi atau mendekripsi dompet</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Cadangkan dompet ke lokasi lain</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Ubah kata kunci yang digunakan untuk enkripsi dompet</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Jendela Debug</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Buka konsol debug dan diagnosa</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifikasi pesan...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>BlackCoin</source>
<translation>BlackCoin (CoinHitam)</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Dompet</translation>
</message>
<message>
<location line="+193"/>
<source>&About BlackCoin</source>
<translation>&Tentang BlackCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Tunjukkan / Sembunyikan</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Buka Dompet</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Kunci Dompet</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Kunci dompet</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Berkas</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Pengaturan</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Bantuan</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Baris tab</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>BlackCoin client</source>
<translation>Klien BlackCoin</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to BlackCoin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>&Buka Dompet</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Terbaru</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Menyusul...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transaksi terkirim</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transaksi diterima</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tanggal: %1
Jumlah: %2
Jenis: %3
Alamat: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid BlackCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Dompet saat ini <b>terenkripsi</b> dan <b>terbuka</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Dompet saat ini <b>terenkripsi</b> dan <b>terkunci</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Back-up Gagal</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n detik</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n menit</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n jam</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n hari</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation>Lagi tidak staking</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. BlackCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+119"/>
<source>Network Alert</source>
<translation>Notifikasi Jaringan</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Biaya:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+493"/>
<source>no</source>
<translation>tidak</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Setelah biaya:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Perubahan:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>mode Daftar</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Terkonfirmasi</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioritas</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-456"/>
<source>Copy address</source>
<translation>Salin alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Salin label</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Salin jumlah</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Salikan jumlah</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Salinkan Biaya</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Salinkan setelah biaya</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Salinkan bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Salinkan output rendah</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Salinkan perubahan</translation>
</message>
<message>
<location line="+423"/>
<source>DUST</source>
<translation>DUST</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>ya</translation>
</message>
<message>
<location line="+9"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<location line="+58"/>
<source>(no label)</source>
<translation>(tidak ada label)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>perubahan dari %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(perubahan)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Ubah Alamat</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Alamat</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Alamat menerima baru</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Alamat mengirim baru</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Ubah alamat menerima</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Ubah alamat mengirim</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Alamat yang dimasukkan "%1" sudah ada di dalam buku alamat.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid BlackCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Tidak dapat membuka dompet.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Pembuatan kunci baru gagal.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>BlackCoin-Qt</source>
<translation>BlackCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versi</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Penggunaan:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Pilihan</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Utama</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Bayar &biaya transaksi</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start BlackCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start BlackCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Jaringan</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the BlackCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Petakan port dengan &UPnP</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>IP Proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port proxy (cth. 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the BlackCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Jendela</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Hanya tampilkan ikon tray setelah meminilisasi jendela</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Meminilisasi ke tray daripada taskbar</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&eminilisasi saat tutup</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Tampilan</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Bahasa Antarmuka Pengguna:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting BlackCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unit untuk menunjukkan jumlah:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&YA</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Batal</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>standar</translation>
</message>
<message>
<location line="+147"/>
<location line="+9"/>
<source>Warning</source>
<translation>Peringatan</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting BlackCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Alamat proxy yang diisi tidak valid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulir</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the BlackCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation>Stake:</translation>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Dompet</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Total saldo anda saat ini</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Transaksi sebelumnya</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>tidak tersinkron</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start blackcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Permintaan Pembayaran</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Pesan:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Simpan Sebagai...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Simpan Code QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Gambar PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nama Klien</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>T/S</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Versi Klien</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasi</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Menggunakan versi OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Waktu nyala</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Jaringan</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Jumlah hubungan</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Rantai blok</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Jumlah blok terkini</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<location filename="../rpcconsole.cpp" line="+352"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<location filename="../rpcconsole.cpp" line="+1"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Waktu blok terakhir</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Buka</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the BlackCoin-Qt help message to get a list with possible BlackCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Tunjukkan</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Tanggal pembuatan</translation>
</message>
<message>
<location line="-104"/>
<source>BlackCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>BlackCoin Core</source>
<translation>Inti BlackCoin</translation>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the BlackCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Bersihkan konsol</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-28"/>
<source>Welcome to the BlackCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Gunakan panah keatas dan kebawah untuk menampilkan sejarah, dan <b>Ctrl-L</b> untuk bersihkan layar.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Ketik <b>help</b> untuk menampilkan perintah tersedia.</translation>
</message>
<message>
<location line="+134"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+179"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Kirim Koin</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Jumlah dana dibutuhkan tidak mencukupi!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="+54"/>
<source>Fee:</source>
<translation>Biaya:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Output Rendah:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>tidak</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Setelah Biaya:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Perubahan</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Kirim ke beberapa penerima sekaligus</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Hapus %Semua</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Konfirmasi aksi pengiriman</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-171"/>
<source>Enter a BlackCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Salin jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+85"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Konfirmasi pengiriman koin</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Jumlah yang dibayar harus lebih besar dari 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Jumlah melebihi saldo Anda.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Kelebihan total saldo Anda ketika biaya transaksi %1 ditambahkan.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Ditemukan alamat ganda, hanya dapat mengirim ke tiap alamat sekali per operasi pengiriman.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+241"/>
<source>WARNING: Invalid BlackCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(tidak ada label)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>J&umlah:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Kirim &Ke:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Masukkan label bagi alamat ini untuk menambahkannya ke buku alamat Anda</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+J</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Tempel alamat dari salinan</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+B</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a BlackCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+J</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Tempel alamat dari salinan</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+B</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this BlackCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Hapus %Semua</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified BlackCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a BlackCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter BlackCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Alamat yang dimasukkan tidak sesuai.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Silahkan periksa alamat dan coba lagi.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Buka hingga %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/tidak terkonfirmasi</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 konfirmasi</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Dari</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Untuk</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Pesan:</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksi</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, belum berhasil disiarkan</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>tidak diketahui</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Rincian transaksi</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Jendela ini menampilkan deskripsi rinci dari transaksi tersebut</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Jenis</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Buka hingga %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Terkonfirmasi (%1 konfirmasi)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Blok ini tidak diterima oleh node lainnya dan kemungkinan tidak akan diterima!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Terbuat tetapi tidak diterima</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Diterima dengan</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Diterima dari</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Terkirim ke</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pembayaran ke Anda sendiri</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Tertambang</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(t/s)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status transaksi. Arahkan ke bagian ini untuk menampilkan jumlah konfrimasi.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Tanggal dan waktu transaksi tersebut diterima.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Jenis transaksi.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Alamat tujuan dari transaksi.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Jumlah terbuang dari atau ditambahkan ke saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Semua</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Hari ini</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Minggu ini</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Bulan ini</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Bulan kemarin</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Tahun ini</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Jarak...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>DIterima dengan</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Terkirim ke</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Ke Anda sendiri</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Ditambang</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Lainnya</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Masukkan alamat atau label untuk mencari</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Jumlah min</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Salin alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Salin label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Salin jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Ubah label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Tampilkan rincian transaksi</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Berkas CSV (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Terkonfirmasi</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Jenis</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Jarak:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ke</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+212"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+8"/>
<source>BlackCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Penggunaan:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or blackcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Daftar perintah</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Dapatkan bantuan untuk perintah</translation>
</message>
<message>
<location line="+1"/>
<source>Options:</source>
<translation>Pilihan:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: blackcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: blackcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Tentukan direktori data</translation>
</message>
<message>
<location line="+163"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=blackcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "BlackCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-161"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Atur ukuran tembolok dalam megabyte (standar: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mengatur hubungan paling banyak <n> ke peer (standar: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Hubungkan ke node untuk menerima alamat peer, dan putuskan</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Tentukan alamat publik Anda sendiri</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Batas untuk memutuskan peer buruk (standar: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Jumlah kedua untuk menjaga peer buruk dari hubung-ulang (standar: 86400)</translation>
</message>
<message>
<location line="+153"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-126"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Menerima perintah baris perintah dan JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Berjalan dibelakang sebagai daemin dan menerima perintah</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Gunakan jaringan uji</translation>
</message>
<message>
<location line="-23"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+160"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong BlackCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-66"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+97"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-85"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+30"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Kirim info lacak/debug ke konsol sebaliknya dari berkas debug.log</translation>
</message>
<message>
<location line="+33"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-33"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-41"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Username for JSON-RPC connections</source>
<translation>Nama pengguna untuk hubungan JSON-RPC</translation>
</message>
<message>
<location line="+50"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-55"/>
<source>Password for JSON-RPC connections</source>
<translation>Kata sandi untuk hubungan JSON-RPC</translation>
</message>
<message>
<location line="-47"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Izinkan hubungan JSON-RPC dari alamat IP yang ditentukan</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Kirim perintah ke node berjalan pada <ip> (standar: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Menjalankan perintah ketika perubahan blok terbaik (%s dalam cmd digantikan oleh hash blok)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Perbarui dompet ke format terbaru</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Kirim ukuran kolam kunci ke <n> (standar: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Pindai ulang rantai-blok untuk transaksi dompet yang hilang</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> MiB of unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Gunakan OpenSSL (https) untuk hubungan JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Berkas sertifikat server (standar: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Kunci pribadi server (standar: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. BlackCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Eror: Dompet hanya di-buka hanya untuk staking, transaksi gagal dilaksanakan</translation>
</message>
<message>
<location line="-14"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-135"/>
<source>This help message</source>
<translation>Pesan bantuan ini</translation>
</message>
<message>
<location line="+100"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Tidak dapat mengikat ke %s dengan komputer ini (ikatan gagal %d, %s)</translation>
</message>
<message>
<location line="-136"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Izinkan peninjauan DNS untuk -addnote, -seednode dan -connect</translation>
</message>
<message>
<location line="+121"/>
<source>Loading addresses...</source>
<translation>Memuat alamat...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Gagal memuat wallet.dat: Dompet rusak</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of BlackCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart BlackCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Gagal memuat wallet.dat</translation>
</message>
<message>
<location line="-15"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Alamat -proxy salah: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Jaringan tidak diketahui yang ditentukan dalam -onlynet: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Tidak dapat menyelesaikan alamat -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Tidak dapat menyelesaikan alamat -externalip: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Jumlah salah untuk -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+59"/>
<source>Sending...</source>
<translation>Mengirim...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Jumlah salah</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Saldo tidak mencukupi</translation>
</message>
<message>
<location line="-41"/>
<source>Loading block index...</source>
<translation>Memuat indeks blok...</translation>
</message>
<message>
<location line="-105"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Tambahkan node untuk dihubungkan dan upaya untuk menjaga hubungan tetap terbuka</translation>
</message>
<message>
<location line="+131"/>
<source>Unable to bind to %s on this computer. BlackCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-108"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. BlackCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Loading wallet...</source>
<translation>Memuat dompet...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Tidak dapat menurunkan versi dompet</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Tidak dapat menyimpan alamat standar</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Memindai ulang...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Memuat selesai</translation>
</message>
<message>
<location line="+33"/>
<source>To use the %s option</source>
<translation>Gunakan pilihan %s</translation>
</message>
<message>
<location line="-27"/>
<source>Error</source>
<translation>Gagal</translation>
</message>
<message>
<location line="+22"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Anda harus mengatur rpcpassword=<kata sandi> dalam berkas konfigurasi:
%s
Jika berkas tidak ada, buatlah dengan permisi berkas hanya-dapat-dibaca-oleh-pemilik.</translation>
</message>
</context>
</TS> | rat4/blackcoin | src/qt/locale/bitcoin_id_ID.ts | TypeScript | mit | 111,933 |
#if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
#define T2U_IS_UNITY_4
#endif
#if !UNITY_WEBPLAYER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using UnityEngine;
using UnityEditor;
namespace Tiled2Unity
{
partial class ImportTiled2Unity
{
public void PrefabImported(string prefabPath)
{
// Find the import behaviour that was waiting on this prefab to be imported
string asset = Path.GetFileName(prefabPath);
ImportBehaviour importComponent = ImportBehaviour.FindImportBehavior_ByWaitingPrefab(asset);
if (importComponent != null)
{
// The prefab has finished loading. Keep track of that status.
if (!importComponent.ImportComplete_Prefabs.Contains(asset))
{
importComponent.ImportComplete_Prefabs.Add(asset);
}
// Are we done importing all Prefabs? If so then we have completed the import process.
if (importComponent.IsPrefabImportingCompleted())
{
string msg = String.Format("Succefully imported prefab '{0}' from '{1}'", prefabPath, importComponent.Tiled2UnityXmlPath);
Debug.Log(msg);
importComponent.DestroyImportBehaviour();
}
}
}
private void ImportAllPrefabs(Tiled2Unity.ImportBehaviour importComponent, string objPath)
{
foreach (var xmlPrefab in importComponent.XmlDocument.Root.Elements("Prefab"))
{
CreatePrefab(xmlPrefab, objPath, importComponent);
}
}
private void CreatePrefab(XElement xmlPrefab, string objPath, Tiled2Unity.ImportBehaviour importComponent)
{
var customImporters = GetCustomImporterInstances();
// Part 1: Create the prefab
string prefabName = xmlPrefab.Attribute("name").Value;
float prefabScale = ImportUtils.GetAttributeAsFloat(xmlPrefab, "scale", 1.0f);
GameObject tempPrefab = new GameObject(prefabName);
HandleTiledAttributes(tempPrefab, xmlPrefab);
HandleCustomProperties(tempPrefab, xmlPrefab, customImporters);
// Part 2: Build out the prefab
// We may have an 'isTrigger' attribute that we want our children to obey
bool isTrigger = ImportUtils.GetAttributeAsBoolean(xmlPrefab, "isTrigger", false);
AddGameObjectsTo(tempPrefab, xmlPrefab, isTrigger, objPath, importComponent, customImporters);
// Part 3: Allow for customization from other editor scripts to be made on the prefab
// (These are generally for game-specific needs)
CustomizePrefab(tempPrefab, customImporters);
// Part 3.5: Apply the scale only after all children have been added
tempPrefab.transform.localScale = new Vector3(prefabScale, prefabScale, prefabScale);
// Part 4: Save the prefab, keeping references intact.
string resourcePath = ImportUtils.GetAttributeAsString(xmlPrefab, "resourcePath", "");
bool isResource = !String.IsNullOrEmpty(resourcePath) || ImportUtils.GetAttributeAsBoolean(xmlPrefab, "resource", false);
string prefabPath = GetPrefabAssetPath(prefabName, isResource, resourcePath);
string prefabFile = Path.GetFileName(prefabPath);
// Keep track of the prefab file being imported
if (!importComponent.ImportWait_Prefabs.Contains(prefabFile))
{
importComponent.ImportWait_Prefabs.Add(prefabFile);
importComponent.ImportingAssets.Add(prefabPath);
}
UnityEngine.Object finalPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
if (finalPrefab == null)
{
// The prefab needs to be created
ImportUtils.ReadyToWrite(prefabPath);
finalPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
}
// Replace the prefab, keeping connections based on name. This imports the prefab asset as a side-effect.
PrefabUtility.ReplacePrefab(tempPrefab, finalPrefab, ReplacePrefabOptions.ReplaceNameBased);
// Destroy the instance from the current scene hiearchy.
UnityEngine.Object.DestroyImmediate(tempPrefab);
}
private void AddGameObjectsTo(GameObject parent, XElement xml, bool isParentTrigger, string objPath, ImportBehaviour importComponent, IList<ICustomTiledImporter> customImporters)
{
foreach (XElement goXml in xml.Elements("GameObject"))
{
string name = ImportUtils.GetAttributeAsString(goXml, "name", "");
string copyFrom = ImportUtils.GetAttributeAsString(goXml, "copy", "");
GameObject child = null;
if (!String.IsNullOrEmpty(copyFrom))
{
float opacity = ImportUtils.GetAttributeAsFloat(goXml, "opacity", 1);
child = CreateCopyFromMeshObj(copyFrom, objPath, opacity, importComponent);
if (child == null)
{
// We're in trouble. Errors should already be in the log.
return;
}
// Apply the sorting to the renderer of the mesh object we just copied into the child
Renderer renderer = child.GetComponent<Renderer>();
string sortingLayer = ImportUtils.GetAttributeAsString(goXml, "sortingLayerName", "");
if (!String.IsNullOrEmpty(sortingLayer) && !SortingLayerExposedEditor.GetSortingLayerNames().Contains(sortingLayer))
{
Debug.LogError(string.Format("Sorting Layer \"{0}\" does not exist. Check your Project Settings -> Tags and Layers", sortingLayer));
renderer.sortingLayerName = "Default";
}
else
{
renderer.sortingLayerName = sortingLayer;
}
// Set the sorting order
renderer.sortingOrder = ImportUtils.GetAttributeAsInt(goXml, "sortingOrder", 0);
}
else
{
child = new GameObject();
}
if (!String.IsNullOrEmpty(name))
{
child.name = name;
}
// Assign the child to the parent
child.transform.parent = parent.transform;
// Set the position
float x = ImportUtils.GetAttributeAsFloat(goXml, "x", 0);
float y = ImportUtils.GetAttributeAsFloat(goXml, "y", 0);
float z = ImportUtils.GetAttributeAsFloat(goXml, "z", 0);
child.transform.localPosition = new Vector3(x, y, z);
// Add any tile objects
AddTileObjectComponentsTo(child, goXml);
// Add any tile animators
AddTileAnimatorsTo(child, goXml);
// Do we have any collision data?
// Check if we are setting 'isTrigger' for ourselves or for our childen
bool isTrigger = ImportUtils.GetAttributeAsBoolean(goXml, "isTrigger", isParentTrigger);
AddCollidersTo(child, isTrigger, goXml);
// Do we have any children of our own?
AddGameObjectsTo(child, goXml, isTrigger, objPath, importComponent, customImporters);
// Does this game object have a tag?
AssignTagTo(child, goXml);
// Does this game object have a layer?
AssignLayerTo(child, goXml);
// Are there any custom properties?
HandleCustomProperties(child, goXml, customImporters);
// Set scale and rotation *after* children are added otherwise Unity will have child+parent transform cancel each other out
float sx = ImportUtils.GetAttributeAsFloat(goXml, "scaleX", 1.0f);
float sy = ImportUtils.GetAttributeAsFloat(goXml, "scaleY", 1.0f);
child.transform.localScale = new Vector3(sx, sy, 1.0f);
// Set the rotation
// Use negative rotation on the z component because of change in coordinate systems between Tiled and Unity
Vector3 localRotation = new Vector3();
localRotation.z = -ImportUtils.GetAttributeAsFloat(goXml, "rotation", 0);
child.transform.eulerAngles = localRotation;
}
}
private void AssignLayerTo(GameObject gameObject, XElement xml)
{
string layerName = ImportUtils.GetAttributeAsString(xml, "layer", "");
if (String.IsNullOrEmpty(layerName))
return;
int layerId = LayerMask.NameToLayer(layerName);
if (layerId == -1)
{
string msg = String.Format("Layer '{0}' is not defined for '{1}'. Check project settings in Edit->Project Settings->Tags & Layers",
layerName,
GetFullGameObjectName(gameObject.transform));
Debug.LogError(msg);
return;
}
// Set the layer on ourselves (and our children)
AssignLayerIdTo(gameObject, layerId);
}
private void AssignLayerIdTo(GameObject gameObject, int layerId)
{
if (gameObject == null)
return;
gameObject.layer = layerId;
foreach (Transform child in gameObject.transform)
{
if (child.gameObject == null)
continue;
// Do not set the layerId on a child that has already had his layerId explicitly set
if (child.gameObject.layer != 0)
continue;
AssignLayerIdTo(child.gameObject, layerId);
}
}
private void AssignTagTo(GameObject gameObject, XElement xml)
{
string tag = ImportUtils.GetAttributeAsString(xml, "tag", "");
if (String.IsNullOrEmpty(tag))
return;
// Let the user know if the tag doesn't exist in our project sttings
try
{
gameObject.tag = tag;
}
catch (UnityException)
{
string msg = String.Format("Tag '{0}' is not defined for '{1}'. Check project settings in Edit->Project Settings->Tags & Layers",
tag,
GetFullGameObjectName(gameObject.transform));
Debug.LogError(msg);
}
}
private string GetFullGameObjectName(Transform xform)
{
if (xform == null)
return "";
string parentName = GetFullGameObjectName(xform.parent);
if (String.IsNullOrEmpty(parentName))
return xform.name;
return String.Format("{0}/{1}", parentName, xform.name);
}
private void AddCollidersTo(GameObject gameObject, bool isTrigger, XElement xml)
{
// Box colliders
foreach (XElement xmlBoxCollider2D in xml.Elements("BoxCollider2D"))
{
BoxCollider2D collider = gameObject.AddComponent<BoxCollider2D>();
collider.isTrigger = isTrigger;
float width = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "width");
float height = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "height");
collider.size = new Vector2(width, height);
#if T2U_IS_UNITY_4
collider.center = new Vector2(width * 0.5f, -height * 0.5f);
#else
collider.offset = new Vector2(width * 0.5f, -height * 0.5f);
#endif
// Apply the offsets (if any)
float offset_x = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "offsetX", 0);
float offset_y = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "offsetY", 0);
#if T2U_IS_UNITY_4
collider.center += new Vector2(offset_x, offset_y);
#else
collider.offset += new Vector2(offset_x, offset_y);
#endif
}
// Circle colliders
foreach (XElement xmlCircleCollider2D in xml.Elements("CircleCollider2D"))
{
CircleCollider2D collider = gameObject.AddComponent<CircleCollider2D>();
collider.isTrigger = isTrigger;
float radius = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "radius");
collider.radius = radius;
#if T2U_IS_UNITY_4
collider.center = new Vector2(radius, -radius);
#else
collider.offset = new Vector2(radius, -radius);
#endif
// Apply the offsets (if any)
float offset_x = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "offsetX", 0);
float offset_y = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "offsetY", 0);
#if T2U_IS_UNITY_4
collider.center += new Vector2(offset_x, offset_y);
#else
collider.offset += new Vector2(offset_x, offset_y);
#endif
}
// Edge colliders
foreach (XElement xmlEdgeCollider2D in xml.Elements("EdgeCollider2D"))
{
EdgeCollider2D collider = gameObject.AddComponent<EdgeCollider2D>();
collider.isTrigger = isTrigger;
string data = xmlEdgeCollider2D.Element("Points").Value;
// The data looks like this:
// x0,y0 x1,y1 x2,y2 ...
var points = from pt in data.Split(' ')
let x = Convert.ToSingle(pt.Split(',')[0])
let y = Convert.ToSingle(pt.Split(',')[1])
select new Vector2(x, y);
collider.points = points.ToArray();
// Apply the offsets (if any)
float offset_x = ImportUtils.GetAttributeAsFloat(xmlEdgeCollider2D, "offsetX", 0);
float offset_y = ImportUtils.GetAttributeAsFloat(xmlEdgeCollider2D, "offsetY", 0);
#if T2U_IS_UNITY_4
// This is kind of a hack for Unity 4.x which doesn't support offset/center on the edge collider
var offsetPoints = from pt in points
select new Vector2(pt.x + offset_x, pt.y + offset_y);
collider.points = offsetPoints.ToArray();
#else
collider.offset += new Vector2(offset_x, offset_y);
#endif
}
// Polygon colliders
foreach (XElement xmlPolygonCollider2D in xml.Elements("PolygonCollider2D"))
{
PolygonCollider2D collider = gameObject.AddComponent<PolygonCollider2D>();
collider.isTrigger = isTrigger;
// Apply the offsets (if any)
float offset_x = ImportUtils.GetAttributeAsFloat(xmlPolygonCollider2D, "offsetX", 0);
float offset_y = ImportUtils.GetAttributeAsFloat(xmlPolygonCollider2D, "offsetY", 0);
var paths = xmlPolygonCollider2D.Elements("Path").ToArray();
collider.pathCount = paths.Count();
for (int p = 0; p < collider.pathCount; ++p)
{
string data = paths[p].Value;
// The data looks like this:
// x0,y0 x1,y1 x2,y2 ...
var points = from pt in data.Split(' ')
let x = Convert.ToSingle(pt.Split(',')[0])
let y = Convert.ToSingle(pt.Split(',')[1])
#if T2U_IS_UNITY_4
// Hack for Unity 4.x
select new Vector2(x + offset_x, y + offset_y);
#else
select new Vector2(x, y);
#endif
collider.SetPath(p, points.ToArray());
}
#if !T2U_IS_UNITY_4
collider.offset += new Vector2(offset_x, offset_y);
#endif
}
}
private GameObject CreateCopyFromMeshObj(string copyFromName, string objPath, float opacity, ImportBehaviour importComponent)
{
// Find a matching game object within the mesh object and "copy" it
// (In Unity terms, the Instantiated object is a copy)
UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath(objPath);
foreach (var obj in objects)
{
if (obj.name != copyFromName)
continue;
// We have a match but is it a game object?
GameObject gameObj = GameObject.Instantiate(obj) as GameObject;
if (gameObj == null)
continue;
// Add a component that will control our initial shader properties
TiledInitialShaderProperties shaderProps = gameObj.AddComponent<TiledInitialShaderProperties>();
shaderProps.InitialOpacity = opacity;
// Reset the name so it is not decorated by the Instantiate call
gameObj.name = obj.name;
return gameObj;
}
// If we're here then there's an error with the mesh name
string msg = String.Format("No mesh named '{0}' to copy from.\nXml File: {1}\nObject: {2}", copyFromName, importComponent.Tiled2UnityXmlPath, objPath);
Debug.LogError(msg);
return null;
}
private void AddTileObjectComponentsTo(GameObject gameObject, XElement goXml)
{
var tileXml = goXml.Element("TileObjectComponent");
if (tileXml != null)
{
TileObject tileObject = gameObject.AddComponent<TileObject>();
tileObject.TileWidth = ImportUtils.GetAttributeAsFloat(tileXml, "width");
tileObject.TileHeight = ImportUtils.GetAttributeAsFloat(tileXml, "height");
}
}
private void AddTileAnimatorsTo(GameObject gameObject, XElement goXml)
{
// This object will only visible for a given moment of time within an animation
var animXml = goXml.Element("TileAnimator");
if (animXml != null)
{
TileAnimator tileAnimator = gameObject.AddComponent<TileAnimator>();
tileAnimator.StartTime = ImportUtils.GetAttributeAsInt(animXml, "startTimeMs") * 0.001f;
tileAnimator.Duration = ImportUtils.GetAttributeAsInt(animXml, "durationMs") * 0.001f;
tileAnimator.TotalAnimationTime = ImportUtils.GetAttributeAsInt(animXml, "fullTimeMs") * 0.001f;
}
}
private void HandleTiledAttributes(GameObject gameObject, XElement goXml)
{
// Add the TiledMap component
TiledMap map = gameObject.AddComponent<TiledMap>();
try
{
map.Orientation = ImportUtils.GetAttributeAsEnum<TiledMap.MapOrientation>(goXml, "orientation");
map.StaggerAxis = ImportUtils.GetAttributeAsEnum<TiledMap.MapStaggerAxis>(goXml, "staggerAxis");
map.StaggerIndex = ImportUtils.GetAttributeAsEnum<TiledMap.MapStaggerIndex>(goXml, "staggerIndex");
map.HexSideLength = ImportUtils.GetAttributeAsInt(goXml, "hexSideLength");
map.NumLayers = ImportUtils.GetAttributeAsInt(goXml, "numLayers");
map.NumTilesWide = ImportUtils.GetAttributeAsInt(goXml, "numTilesWide");
map.NumTilesHigh = ImportUtils.GetAttributeAsInt(goXml, "numTilesHigh");
map.TileWidth = ImportUtils.GetAttributeAsInt(goXml, "tileWidth");
map.TileHeight = ImportUtils.GetAttributeAsInt(goXml, "tileHeight");
map.ExportScale = ImportUtils.GetAttributeAsFloat(goXml, "exportScale");
map.MapWidthInPixels = ImportUtils.GetAttributeAsInt(goXml, "mapWidthInPixels");
map.MapHeightInPixels = ImportUtils.GetAttributeAsInt(goXml, "mapHeightInPixels");
}
catch
{
Debug.LogWarning(String.Format("Error adding TiledMap component. Are you using an old version of Tiled2Unity in your Unity project?"));
GameObject.DestroyImmediate(map);
}
}
private void HandleCustomProperties(GameObject gameObject, XElement goXml, IList<ICustomTiledImporter> importers)
{
var props = from p in goXml.Elements("Property")
select new { Name = p.Attribute("name").Value, Value = p.Attribute("value").Value };
if (props.Count() > 0)
{
var dictionary = props.OrderBy(p => p.Name).ToDictionary(p => p.Name, p => p.Value);
foreach (ICustomTiledImporter importer in importers)
{
importer.HandleCustomProperties(gameObject, dictionary);
}
}
}
private void CustomizePrefab(GameObject prefab, IList<ICustomTiledImporter> importers)
{
foreach (ICustomTiledImporter importer in importers)
{
importer.CustomizePrefab(prefab);
}
}
private IList<ICustomTiledImporter> GetCustomImporterInstances()
{
// Report an error for ICustomTiledImporter classes that don't have the CustomTiledImporterAttribute
var errorTypes = from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where typeof(ICustomTiledImporter).IsAssignableFrom(t)
where !t.IsAbstract
where System.Attribute.GetCustomAttribute(t, typeof(CustomTiledImporterAttribute)) == null
select t;
foreach (var t in errorTypes)
{
Debug.LogError(String.Format("ICustomTiledImporter type '{0}' is missing CustomTiledImporterAttribute", t));
}
// Find all the types with the CustomTiledImporterAttribute, instantiate them, and give them a chance to customize our prefab
var types = from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where typeof(ICustomTiledImporter).IsAssignableFrom(t)
where !t.IsAbstract
from attr in System.Attribute.GetCustomAttributes(t, typeof(CustomTiledImporterAttribute))
let custom = attr as CustomTiledImporterAttribute
orderby custom.Order
select t;
var instances = types.Select(t => (ICustomTiledImporter)Activator.CreateInstance(t));
return instances.ToList();
}
}
}
#endif | Densaugeo/GGJ-Heard-Mentality | Heard Mentality/Assets/Tiled2Unity/Scripts/Editor/ImportTiled2Unity.Prefab.cs | C# | mit | 23,388 |
from qtpy.QtCore import QTimer
class Spin:
def __init__(self, parent_widget, interval=10, step=1):
self.parent_widget = parent_widget
self.interval, self.step = interval, step
self.info = {}
def _update(self, parent_widget):
if self.parent_widget in self.info:
timer, angle, step = self.info[self.parent_widget]
if angle >= 360:
angle = 0
angle += step
self.info[parent_widget] = timer, angle, step
parent_widget.update()
def setup(self, icon_painter, painter, rect):
if self.parent_widget not in self.info:
timer = QTimer()
timer.timeout.connect(lambda: self._update(self.parent_widget))
self.info[self.parent_widget] = [timer, 0, self.step]
timer.start(self.interval)
else:
timer, angle, self.step = self.info[self.parent_widget]
x_center = rect.width() * 0.5
y_center = rect.height() * 0.5
painter.translate(x_center, y_center)
painter.rotate(angle)
painter.translate(-x_center, -y_center)
class Pulse(Spin):
def __init__(self, parent_widget):
Spin.__init__(self, parent_widget, interval=300, step=45)
| daodaoliang/qtawesome | qtawesome/animation.py | Python | mit | 1,284 |
require File.expand_path('../instagram/error', __FILE__)
require File.expand_path('../instagram/configuration', __FILE__)
require File.expand_path('../instagram/api', __FILE__)
require File.expand_path('../instagram/client', __FILE__)
module Instagram
extend Configuration
# Alias for Instagram::Client.new
#
# @return [Instagram::Client]
def self.client(options={})
Instagram::Client.new(options)
end
# Delegate to Instagram::Client
def self.method_missing(method, *args, &block)
return super unless client.respond_to?(method)
client.send(method, *args, &block)
end
# Delegate to Instagram::Client
def self.respond_to?(method)
return client.respond_to?(method) || super
end
end | mitukiii/undersky | vendor/gems/instagram-0.8/lib/instagram.rb | Ruby | mit | 722 |
require 'spec_helper'
describe Match do
pending "add some examples to (or delete) #{__FILE__}"
end
| pavel-anisimov/GoalsPlus | spec/models/match_spec.rb | Ruby | mit | 102 |
'use strict';
angular.module('copayApp.controllers').controller('walletHomeController', function($scope, $rootScope, $timeout, $filter, $modal, $log, notification, txStatus, isCordova, profileService, lodash, configService, rateService, storageService, bitcore, isChromeApp, gettext, gettextCatalog, nodeWebkit, addressService, feeService, bwsError, utilService) {
var self = this;
$rootScope.hideMenuBar = false;
$rootScope.wpInputFocused = false;
$scope.currentSpendUnconfirmed = configService.getSync().wallet.spendUnconfirmed;
// INIT
var config = configService.getSync().wallet.settings;
this.unitToSatoshi = config.unitToSatoshi;
this.satToUnit = 1 / this.unitToSatoshi;
this.unitName = config.unitName;
this.alternativeIsoCode = config.alternativeIsoCode;
this.alternativeName = config.alternativeName;
this.alternativeAmount = 0;
this.unitDecimals = config.unitDecimals;
this.isCordova = isCordova;
this.addresses = [];
this.isMobile = isMobile.any();
this.isWindowsPhoneApp = isMobile.Windows() && isCordova;
this.blockUx = false;
this.isRateAvailable = false;
this.showScanner = false;
this.isMobile = isMobile.any();
this.addr = {};
var disableScannerListener = $rootScope.$on('dataScanned', function(event, data) {
self.setForm(data);
$rootScope.$emit('Local/SetTab', 'send');
var form = $scope.sendForm;
if (form.address.$invalid) {
self.resetForm();
self.error = gettext('Could not recognize a valid Bitcoin QR Code');
}
});
var disablePaymentUriListener = $rootScope.$on('paymentUri', function(event, uri) {
$timeout(function() {
$rootScope.$emit('Local/SetTab', 'send');
self.setForm(uri);
}, 100);
});
var disableAddrListener = $rootScope.$on('Local/NeedNewAddress', function() {
self.setAddress(true);
});
var disableFocusListener = $rootScope.$on('Local/NewFocusedWallet', function() {
self.addr = {};
self.resetForm();
});
var disableResumeListener = $rootScope.$on('Local/Resume', function() {
// This is needed then the apps go to sleep
self.bindTouchDown();
});
var disableTabListener = $rootScope.$on('Local/TabChanged', function(e, tab) {
// This will slow down switch, do not add things here!
switch (tab) {
case 'receive':
// just to be sure we have an address
self.setAddress();
break;
case 'send':
self.resetError();
};
});
var disableOngoingProcessListener = $rootScope.$on('Addon/OngoingProcess', function(e, name) {
self.setOngoingProcess(name);
});
$scope.$on('$destroy', function() {
disableAddrListener();
disableScannerListener();
disablePaymentUriListener();
disableTabListener();
disableFocusListener();
disableResumeListener();
disableOngoingProcessListener();
$rootScope.hideMenuBar = false;
});
rateService.whenAvailable(function() {
self.isRateAvailable = true;
$rootScope.$digest();
});
var accept_msg = gettextCatalog.getString('Accept');
var cancel_msg = gettextCatalog.getString('Cancel');
var confirm_msg = gettextCatalog.getString('Confirm');
$scope.openCopayersModal = function(copayers, copayerId) {
var fc = profileService.focusedClient;
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.copayers = copayers;
$scope.copayerId = copayerId;
$scope.color = fc.backgroundColor;
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var modalInstance = $modal.open({
templateUrl: 'views/modals/copayers.html',
windowClass: 'full animated slideInUp',
controller: ModalInstanceCtrl,
});
modalInstance.result.finally(function() {
var m = angular.element(document.getElementsByClassName('reveal-modal'));
m.addClass('slideOutDown');
});
};
$scope.openWalletsModal = function(wallets) {
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.wallets = wallets;
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
$scope.selectWallet = function(walletId, walletName) {
$scope.gettingAddress = true;
$scope.selectedWalletName = walletName;
$timeout(function() {
$scope.$apply();
});
addressService.getAddress(walletId, false, function(err, addr) {
$scope.gettingAddress = false;
if (err) {
self.error = err;
$modalInstance.dismiss('cancel');
return;
}
$modalInstance.close(addr);
});
};
};
var modalInstance = $modal.open({
templateUrl: 'views/modals/wallets.html',
windowClass: 'full animated slideInUp',
controller: ModalInstanceCtrl,
});
modalInstance.result.finally(function() {
var m = angular.element(document.getElementsByClassName('reveal-modal'));
m.addClass('slideOutDown');
});
modalInstance.result.then(function(addr) {
if (addr) {
self.setForm(addr);
}
});
};
this.openTxpModal = function(tx, copayers) {
var fc = profileService.focusedClient;
var refreshUntilItChanges = false;
var currentSpendUnconfirmed = $scope.currentSpendUnconfirmed;
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.error = null;
$scope.tx = tx;
$scope.copayers = copayers
$scope.copayerId = fc.credentials.copayerId;
$scope.canSign = fc.canSign();
$scope.loading = null;
$scope.color = fc.backgroundColor;
refreshUntilItChanges = false;
$scope.currentSpendUnconfirmed = currentSpendUnconfirmed;
$scope.getShortNetworkName = function() {
return fc.credentials.networkName.substring(0, 4);
};
lodash.each(['TxProposalRejectedBy', 'TxProposalAcceptedBy', 'transactionProposalRemoved', 'TxProposalRemoved', 'NewOutgoingTx'], function(eventName) {
$rootScope.$on(eventName, function() {
fc.getTx($scope.tx.id, function(err, tx) {
if (err) {
if (err.code && err.code == 'BADREQUEST' &&
(eventName == 'transactionProposalRemoved' || eventName == 'TxProposalRemoved')) {
$scope.tx.removed = true;
$scope.tx.canBeRemoved = false;
$scope.tx.pendingForUs = false;
$scope.$apply();
return;
}
return;
}
var action = lodash.find(tx.actions, {
copayerId: fc.credentials.copayerId
});
$scope.tx = utilService.processTx(tx);
if (!action && tx.status == 'pending')
$scope.tx.pendingForUs = true;
$scope.updateCopayerList();
$scope.$apply();
});
});
});
$scope.updateCopayerList = function() {
lodash.map($scope.copayers, function(cp) {
lodash.each($scope.tx.actions, function(ac) {
if (cp.id == ac.copayerId) {
cp.action = ac.type;
}
});
});
};
$scope.sign = function(txp) {
var fc = profileService.focusedClient;
if (!fc.canSign())
return;
if (fc.isPrivKeyEncrypted()) {
profileService.unlockFC(function(err) {
if (err) {
$scope.error = bwsError.msg(err);
return;
}
return $scope.sign(txp);
});
return;
};
self.setOngoingProcess(gettext('Signing payment'));
$scope.loading = true;
$scope.error = null;
$timeout(function() {
fc.signTxProposal(txp, function(err, txpsi) {
profileService.lockFC();
self.setOngoingProcess();
if (err) {
$scope.loading = false;
$scope.error = bwsError.msg(err, gettextCatalog.getString('Could not accept payment'));
$scope.$digest();
} else {
//if txp has required signatures then broadcast it
var txpHasRequiredSignatures = txpsi.status == 'accepted';
if (txpHasRequiredSignatures) {
self.setOngoingProcess(gettext('Broadcasting transaction'));
$scope.loading = true;
fc.broadcastTxProposal(txpsi, function(err, txpsb, memo) {
self.setOngoingProcess();
$scope.loading = false;
if (err) {
$scope.error = bwsError.msg(err, gettextCatalog.getString('Could not broadcast payment'));
$scope.$digest();
} else {
$log.debug('Transaction signed and broadcasted')
if (memo)
$log.info(memo);
refreshUntilItChanges = true;
$modalInstance.close(txpsb);
}
});
} else {
$scope.loading = false;
$modalInstance.close(txpsi);
}
}
});
}, 100);
};
$scope.reject = function(txp) {
self.setOngoingProcess(gettext('Rejecting payment'));
$scope.loading = true;
$scope.error = null;
$timeout(function() {
fc.rejectTxProposal(txp, null, function(err, txpr) {
self.setOngoingProcess();
$scope.loading = false;
if (err) {
$scope.error = bwsError.msg(err, gettextCatalog.getString('Could not reject payment'));
$scope.$digest();
} else {
$modalInstance.close(txpr);
}
});
}, 100);
};
$scope.remove = function(txp) {
self.setOngoingProcess(gettext('Deleting payment'));
$scope.loading = true;
$scope.error = null;
$timeout(function() {
fc.removeTxProposal(txp, function(err, txpb) {
self.setOngoingProcess();
$scope.loading = false;
// Hacky: request tries to parse an empty response
if (err && !(err.message && err.message.match(/Unexpected/))) {
$scope.error = bwsError.msg(err, gettextCatalog.getString('Could not delete payment proposal'));
$scope.$digest();
return;
}
$modalInstance.close();
});
}, 100);
};
$scope.broadcast = function(txp) {
self.setOngoingProcess(gettext('Broadcasting Payment'));
$scope.loading = true;
$scope.error = null;
$timeout(function() {
fc.broadcastTxProposal(txp, function(err, txpb, memo) {
self.setOngoingProcess();
$scope.loading = false;
if (err) {
$scope.error = bwsError.msg(err, gettextCatalog.getString('Could not broadcast payment'));
$scope.$digest();
} else {
if (memo)
$log.info(memo);
refreshUntilItChanges = true;
$modalInstance.close(txpb);
}
});
}, 100);
};
$scope.copyAddress = function(addr) {
if (!addr) return;
self.copyAddress(addr);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var modalInstance = $modal.open({
templateUrl: 'views/modals/txp-details.html',
windowClass: 'full animated slideInRight',
controller: ModalInstanceCtrl,
});
modalInstance.result.finally(function() {
var m = angular.element(document.getElementsByClassName('reveal-modal'));
m.addClass('slideOutRight');
});
modalInstance.result.then(function(txp) {
self.setOngoingProcess();
if (txp) {
txStatus.notify(txp, function() {
$scope.$emit('Local/TxProposalAction', refreshUntilItChanges);
});
} else {
$timeout(function() {
$scope.$emit('Local/TxProposalAction', refreshUntilItChanges);
}, 100);
}
});
};
this.setAddress = function(forceNew) {
self.addrError = null;
var fc = profileService.focusedClient;
if (!fc)
return;
// Address already set?
if (!forceNew && self.addr[fc.credentials.walletId]) {
return;
}
self.generatingAddress = true;
$timeout(function() {
addressService.getAddress(fc.credentials.walletId, forceNew, function(err, addr) {
self.generatingAddress = false;
if (err) {
self.addrError = err;
} else {
if (addr)
self.addr[fc.credentials.walletId] = addr;
}
$scope.$digest();
});
});
};
this.copyAddress = function(addr) {
if (isCordova) {
window.cordova.plugins.clipboard.copy(addr);
window.plugins.toast.showShortCenter(gettextCatalog.getString('Copied to clipboard'));
} else if (nodeWebkit.isDefined()) {
nodeWebkit.writeToClipboard(addr);
}
};
this.shareAddress = function(addr) {
if (isCordova) {
if (isMobile.Android() || isMobile.Windows()) {
window.ignoreMobilePause = true;
}
window.plugins.socialsharing.share('bitcoin:' + addr, null, null, null);
}
};
this.openCustomizedAmountModal = function(addr) {
var self = this;
var fc = profileService.focusedClient;
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.addr = addr;
$scope.color = fc.backgroundColor;
$scope.unitName = self.unitName;
$scope.alternativeAmount = self.alternativeAmount;
$scope.alternativeName = self.alternativeName;
$scope.alternativeIsoCode = self.alternativeIsoCode;
$scope.isRateAvailable = self.isRateAvailable;
$scope.unitToSatoshi = self.unitToSatoshi;
$scope.unitDecimals = self.unitDecimals;
var satToUnit = 1 / self.unitToSatoshi;
$scope.showAlternative = false;
Object.defineProperty($scope,
"_customAlternative", {
get: function() {
return $scope.customAlternative;
},
set: function(newValue) {
$scope.customAlternative = newValue;
if (typeof(newValue) === 'number' && $scope.isRateAvailable) {
$scope.customAmount = parseFloat((rateService.fromFiat(newValue, $scope.alternativeIsoCode) * satToUnit).toFixed($scope.unitDecimals), 10);
} else {
$scope.customAmount = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty($scope,
"_customAmount", {
get: function() {
return $scope.customAmount;
},
set: function(newValue) {
$scope.customAmount = newValue;
if (typeof(newValue) === 'number' && $scope.isRateAvailable) {
$scope.customAlternative = parseFloat((rateService.toFiat(newValue * $scope.unitToSatoshi, $scope.alternativeIsoCode)).toFixed(2), 10);
} else {
$scope.customAlternative = null;
}
$scope.alternativeAmount = $scope.customAlternative;
},
enumerable: true,
configurable: true
});
$scope.submitForm = function(form) {
var satToBtc = 1 / 100000000;
var amount = form.amount.$modelValue;
var amountSat = parseInt((amount * $scope.unitToSatoshi).toFixed(0));
$timeout(function() {
$scope.customizedAmountUnit = amount + ' ' + $scope.unitName;
$scope.customizedAlternativeUnit = $filter('noFractionNumber')(form.alternative.$modelValue, 2) + ' ' + $scope.alternativeIsoCode;
if ($scope.unitName == 'bits') {
amount = (amountSat * satToBtc).toFixed(8);
}
$scope.customizedAmountBtc = amount;
}, 1);
};
$scope.toggleAlternative = function() {
$scope.showAlternative = !$scope.showAlternative;
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var modalInstance = $modal.open({
templateUrl: 'views/modals/customized-amount.html',
windowClass: 'full animated slideInUp',
controller: ModalInstanceCtrl,
});
modalInstance.result.finally(function() {
var m = angular.element(document.getElementsByClassName('reveal-modal'));
m.addClass('slideOutDown');
});
};
// Send
var unwatchSpendUnconfirmed = $scope.$watch('currentSpendUnconfirmed', function(newVal, oldVal) {
if (newVal == oldVal) return;
$scope.currentSpendUnconfirmed = newVal;
});
$scope.$on('$destroy', function() {
unwatchSpendUnconfirmed();
});
this.canShowAlternative = function() {
return $scope.showAlternative;
};
this.showAlternative = function() {
$scope.showAlternative = true;
};
this.hideAlternative = function() {
$scope.showAlternative = false;
};
this.resetError = function() {
this.error = this.success = null;
};
this.bindTouchDown = function(tries) {
var self = this;
tries = tries || 0;
if (tries > 5) return;
var e = document.getElementById('menu-walletHome');
if (!e) return $timeout(function() {
self.bindTouchDown(++tries);
}, 500);
// on touchdown elements
$log.debug('Binding touchstart elements...');
['hamburger', 'menu-walletHome', 'menu-send', 'menu-receive', 'menu-history'].forEach(function(id) {
var e = document.getElementById(id);
if (e) e.addEventListener('touchstart', function() {
try {
event.preventDefault();
} catch (e) {};
angular.element(e).triggerHandler('click');
}, true);
});
}
this.hideMenuBar = lodash.debounce(function(hide) {
if (hide) {
$rootScope.hideMenuBar = true;
this.bindTouchDown();
} else {
$rootScope.hideMenuBar = false;
}
$rootScope.$digest();
}, 100);
this.formFocus = function(what) {
if (isCordova && !this.isWindowsPhoneApp) {
this.hideMenuBar(what);
}
if (!this.isWindowsPhoneApp) return
if (!what) {
this.hideAddress = false;
this.hideAmount = false;
} else {
if (what == 'amount') {
this.hideAddress = true;
} else if (what == 'msg') {
this.hideAddress = true;
this.hideAmount = true;
}
}
$timeout(function() {
$rootScope.$digest();
}, 1);
};
this.setSendFormInputs = function() {
var unitToSat = this.unitToSatoshi;
var satToUnit = 1 / unitToSat;
/**
* Setting the two related amounts as properties prevents an infinite
* recursion for watches while preserving the original angular updates
*
*/
Object.defineProperty($scope,
"_alternative", {
get: function() {
return $scope.__alternative;
},
set: function(newValue) {
$scope.__alternative = newValue;
if (typeof(newValue) === 'number' && self.isRateAvailable) {
$scope._amount = parseFloat((rateService.fromFiat(newValue, self.alternativeIsoCode) * satToUnit).toFixed(self.unitDecimals), 10);
} else {
$scope.__amount = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty($scope,
"_amount", {
get: function() {
return $scope.__amount;
},
set: function(newValue) {
$scope.__amount = newValue;
if (typeof(newValue) === 'number' && self.isRateAvailable) {
$scope.__alternative = parseFloat((rateService.toFiat(newValue * self.unitToSatoshi, self.alternativeIsoCode)).toFixed(2), 10);
} else {
$scope.__alternative = null;
}
self.alternativeAmount = $scope.__alternative;
self.resetError();
},
enumerable: true,
configurable: true
});
Object.defineProperty($scope,
"_address", {
get: function() {
return $scope.__address;
},
set: function(newValue) {
$scope.__address = self.onAddressChange(newValue);
},
enumerable: true,
configurable: true
});
};
this.setSendError = function(err) {
var fc = profileService.focusedClient;
var prefix =
fc.credentials.m > 1 ? gettextCatalog.getString('Could not create payment proposal') : gettextCatalog.getString('Could not send payment');
this.error = bwsError.msg(err, prefix);
$timeout(function() {
$scope.$digest();
}, 1);
};
this.setOngoingProcess = function(name) {
var self = this;
self.blockUx = !!name;
if (isCordova) {
if (name) {
window.plugins.spinnerDialog.hide();
window.plugins.spinnerDialog.show(null, name + '...', true);
} else {
window.plugins.spinnerDialog.hide();
}
} else {
self.onGoingProcess = name;
$timeout(function() {
$rootScope.$apply();
});
};
};
this.setFee = function(level) {
this.currentSendFeeLevel = level;
};
this.submitForm = function() {
var fc = profileService.focusedClient;
var unitToSat = this.unitToSatoshi;
if (isCordova && this.isWindowsPhoneApp) {
this.hideAddress = false;
this.hideAmount = false;
}
var form = $scope.sendForm;
if (form.$invalid) {
this.error = gettext('Unable to send transaction proposal');
return;
}
if (fc.isPrivKeyEncrypted()) {
profileService.unlockFC(function(err) {
if (err) return self.setSendError(err);
return self.submitForm();
});
return;
};
self.setOngoingProcess(gettext('Creating transaction'));
$timeout(function() {
var comment = form.comment.$modelValue;
var paypro = self._paypro;
var address, amount;
address = form.address.$modelValue;
amount = parseInt((form.amount.$modelValue * unitToSat).toFixed(0));
var getFee = function(cb) {
if (form.feePerKb) {
cb(null, form.feePerKb);
} else {
feeService.getCurrentFeeValue(self.currentSendFeeLevel, cb);
}
};
getFee(function(err, feePerKb) {
if (err) $log.debug(err);
fc.sendTxProposal({
toAddress: address,
amount: amount,
message: comment,
payProUrl: paypro ? paypro.url : null,
feePerKb: feePerKb,
excludeUnconfirmedUtxos: $scope.currentSpendUnconfirmed ? false : true
}, function(err, txp) {
if (err) {
self.setOngoingProcess();
profileService.lockFC();
return self.setSendError(err);
}
if (!fc.canSign()) {
$log.info('No signing proposal: No private key')
self.setOngoingProcess();
self.resetForm();
txStatus.notify(txp, function() {
return $scope.$emit('Local/TxProposalAction');
});
return;
}
self.signAndBroadcast(txp, function(err) {
self.setOngoingProcess();
profileService.lockFC();
self.resetForm();
if (err) {
self.error = err.message ? err.message : gettext('The payment was created but could not be completed. Please try again from home screen');
$scope.$emit('Local/TxProposalAction');
$timeout(function() {
$scope.$digest();
}, 1);
}
});
});
});
}, 100);
};
this.signAndBroadcast = function(txp, cb) {
var fc = profileService.focusedClient;
self.setOngoingProcess(gettext('Signing transaction'));
fc.signTxProposal(txp, function(err, signedTx) {
profileService.lockFC();
self.setOngoingProcess();
if (err) {
err.message = bwsError.msg(err, gettextCatalog.getString('The payment was created but could not be signed. Please try again from home screen'));
return cb(err);
}
if (signedTx.status == 'accepted') {
self.setOngoingProcess(gettext('Broadcasting transaction'));
fc.broadcastTxProposal(signedTx, function(err, btx, memo) {
self.setOngoingProcess();
if (err) {
err.message = bwsError.msg(err, gettextCatalog.getString('The payment was signed but could not be broadcasted. Please try again from home screen'));
return cb(err);
}
if (memo)
$log.info(memo);
txStatus.notify(btx, function() {
$scope.$emit('Local/TxProposalAction', true);
return cb();
});
});
} else {
self.setOngoingProcess();
txStatus.notify(signedTx, function() {
$scope.$emit('Local/TxProposalAction');
return cb();
});
}
});
};
this.setForm = function(to, amount, comment, feeRate) {
var form = $scope.sendForm;
if (to) {
form.address.$setViewValue(to);
form.address.$isValid = true;
form.address.$render();
this.lockAddress = true;
}
if (amount) {
form.amount.$setViewValue("" + amount);
form.amount.$isValid = true;
form.amount.$render();
this.lockAmount = true;
}
if (comment) {
form.comment.$setViewValue(comment);
form.comment.$isValid = true;
form.comment.$render();
}
if (feeRate) {
form.feeRate = feeRate;
}
};
this.resetForm = function() {
this.resetError();
this._paypro = null;
this.lockAddress = false;
this.lockAmount = false;
this.currentSendFeeLevel = null;
this.hideAdvSend = true;
$scope.currentSpendUnconfirmed = configService.getSync().wallet.spendUnconfirmed;
this._amount = this._address = null;
var form = $scope.sendForm;
if (form && form.feeRate) {
form.feeRate = null;
}
if (form && form.amount) {
form.amount.$pristine = true;
form.amount.$setViewValue('');
form.amount.$render();
form.comment.$setViewValue('');
form.comment.$render();
form.$setPristine();
if (form.address) {
form.address.$pristine = true;
form.address.$setViewValue('');
form.address.$render();
}
}
$timeout(function() {
$rootScope.$digest();
}, 1);
};
this.openPPModal = function(paypro) {
var ModalInstanceCtrl = function($scope, $modalInstance) {
var fc = profileService.focusedClient;
var satToUnit = 1 / self.unitToSatoshi;
$scope.paypro = paypro;
$scope.alternative = self.alternativeAmount;
$scope.alternativeIsoCode = self.alternativeIsoCode;
$scope.isRateAvailable = self.isRateAvailable;
$scope.unitTotal = (paypro.amount * satToUnit).toFixed(self.unitDecimals);
$scope.unitName = self.unitName;
$scope.color = fc.backgroundColor;
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var modalInstance = $modal.open({
templateUrl: 'views/modals/paypro.html',
windowClass: 'full animated slideInUp',
controller: ModalInstanceCtrl,
});
modalInstance.result.finally(function() {
var m = angular.element(document.getElementsByClassName('reveal-modal'));
m.addClass('slideOutDown');
});
};
this.setFromPayPro = function(uri) {
var fc = profileService.focusedClient;
if (isChromeApp) {
this.error = gettext('Payment Protocol not supported on Chrome App');
return;
}
var satToUnit = 1 / this.unitToSatoshi;
var self = this;
/// Get information of payment if using Payment Protocol
self.setOngoingProcess(gettext('Fetching Payment Information'));
$log.debug('Fetch PayPro Request...', uri);
$timeout(function() {
fc.fetchPayPro({
payProUrl: uri,
}, function(err, paypro) {
self.setOngoingProcess();
if (err) {
$log.warn(err);
self.resetForm();
var msg = err.toString();
if (msg.match('HTTP')) {
msg = gettext('Could not fetch payment information');
}
self.error = msg;
} else {
self._paypro = paypro;
self.setForm(paypro.toAddress, (paypro.amount * satToUnit).toFixed(self.unitDecimals),
paypro.memo);
}
});
}, 1);
};
this.setFromUri = function(uri) {
function sanitizeUri(uri) {
// Fixes when a region uses comma to separate decimals
var regex = /[\?\&]amount=(\d+([\,\.]\d+)?)/i;
var match = regex.exec(uri);
if (!match || match.length === 0) {
return uri;
}
var value = match[0].replace(',', '.');
var newUri = uri.replace(regex, value);
return newUri;
};
var satToUnit = 1 / this.unitToSatoshi;
uri = sanitizeUri(uri);
if (!bitcore.URI.isValid(uri)) {
return uri;
}
var parsed = new bitcore.URI(uri);
var addr = parsed.address.toString();
var message = parsed.message;
if (parsed.r)
return this.setFromPayPro(parsed.r);
var amount = parsed.amount ?
(parsed.amount.toFixed(0) * satToUnit).toFixed(this.unitDecimals) : 0;
this.setForm(addr, amount, message);
return addr;
};
this.onAddressChange = function(value) {
this.resetError();
if (!value) return '';
if (this._paypro)
return value;
if (value.indexOf('bitcoin:') === 0) {
return this.setFromUri(value);
} else if (/^https?:\/\//.test(value)) {
return this.setFromPayPro(value);
} else {
return value;
}
};
// History
function strip(number) {
return (parseFloat(number.toPrecision(12)));
}
this.getUnitName = function() {
return this.unitName;
};
this.getAlternativeIsoCode = function() {
return this.alternativeIsoCode;
};
this.openTxModal = function(btx) {
var self = this;
var fc = profileService.focusedClient;
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.btx = btx;
$scope.settings = config;
$scope.color = fc.backgroundColor;
$scope.copayerId = fc.credentials.copayerId;
$scope.isShared = fc.credentials.n > 1;
$scope.getAmount = function(amount) {
return self.getAmount(amount);
};
$scope.getUnitName = function() {
return self.getUnitName();
};
$scope.getShortNetworkName = function() {
var n = fc.credentials.network;
return n.substring(0, 4);
};
$scope.copyAddress = function(addr) {
if (!addr) return;
self.copyAddress(addr);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var modalInstance = $modal.open({
templateUrl: 'views/modals/tx-details.html',
windowClass: 'full animated slideInRight',
controller: ModalInstanceCtrl,
});
modalInstance.result.finally(function() {
var m = angular.element(document.getElementsByClassName('reveal-modal'));
m.addClass('slideOutRight');
});
};
this.hasAction = function(actions, action) {
return actions.hasOwnProperty('create');
};
this._doSendAll = function(amount, feeRate) {
this.setForm(null, amount, null, feeRate);
};
this.confirmDialog = function(msg, cb) {
if (isCordova) {
navigator.notification.confirm(
msg,
function(buttonIndex) {
if (buttonIndex == 1) {
$timeout(function() {
return cb(true);
}, 1);
} else {
return cb(false);
}
},
confirm_msg, [accept_msg, cancel_msg]
);
} else if (isChromeApp) {
// No feedback, alert/confirm not supported.
return cb(true);
} else {
return cb(confirm(msg));
}
};
this.sendAll = function(amount, feeStr, feeRate) {
var self = this;
var msg = gettextCatalog.getString("{{fee}} will be discounted for bitcoin networking fees", {
fee: feeStr
});
this.confirmDialog(msg, function(confirmed) {
if (confirmed)
self._doSendAll(amount, feeRate);
});
};
/* Start setup */
this.bindTouchDown();
this.setAddress();
this.setSendFormInputs();
});
| FuzzyHobbit/copay | src/js/controllers/walletHome.js | JavaScript | mit | 32,485 |
<?php
/*
* This file is part of the FOSJsRoutingBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\JsRoutingBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* FOSJsRoutingExtension
* Load configuration.
*
* @author William DURAND <william.durand1@gmail.com>
*/
class FOSJsRoutingExtension extends Extension
{
/**
* Load configuration.
*/
public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$configuration = new Configuration();
$config = $processor->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$loader->load('controllers.xml');
if (isset($config['serializer'])) {
$container->setAlias('fos_js_routing.serializer', new Alias($config['serializer'], false));
} else {
$loader->load('serializer.xml');
}
$container
->getDefinition('fos_js_routing.extractor')
->replaceArgument(1, $config['routes_to_expose']);
}
}
| danieloliveira079/OMLET | vendor/bundles/FOS/JsRoutingBundle/DependencyInjection/FOSJsRoutingExtension.php | PHP | mit | 1,644 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NControl.Forms.Xamarin.Plugins.WP81")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NControl.Forms.Xamarin.Plugins.WP81")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9e684606-7520-4c66-a530-f65aaa129b8f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion ("0.2.*")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| chrfalch/NControl | NControl/NControl.WP81/Properties/AssemblyInfo.cs | C# | mit | 1,441 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = {
// Options.jsx
items_per_page: '/ 쪽',
jump_to: '이동하기',
page: '',
// Pagination.jsx
prev_page: '이전 페이지',
next_page: '다음 페이지',
prev_5: '이전 5 페이지',
next_5: '다음 5 페이지',
prev_3: '이전 3 페이지',
next_3: '다음 3 페이지'
};
module.exports = exports['default']; | prodigalyijun/demo-by-antd | node_modules/rc-pagination/lib/locale/ko_KR.js | JavaScript | mit | 439 |
//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Driver.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/OptTable.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/Tool.h"
#include "clang/Driver/ToolChain.h"
#include "clang/Basic/Version.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "InputInfo.h"
#include "ToolChains.h"
#include <map>
#include "clang/Config/config.h"
using namespace clang::driver;
using namespace clang;
Driver::Driver(StringRef ClangExecutable,
StringRef DefaultTargetTriple,
StringRef DefaultImageName,
bool IsProduction,
DiagnosticsEngine &Diags)
: Opts(createDriverOptTable()), Diags(Diags),
ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
DefaultImageName(DefaultImageName),
DriverTitle("clang \"gcc-compatible\" driver"),
CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
CCLogDiagnosticsFilename(0), CCCIsCXX(false),
CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
CCCUsePCH(true), SuppressMissingInputWarning(false) {
if (IsProduction) {
// In a "production" build, only use clang on architectures we expect to
// work.
//
// During development its more convenient to always have the driver use
// clang, but we don't want users to be confused when things don't work, or
// to file bugs for things we don't support.
CCCClangArchs.insert(llvm::Triple::x86);
CCCClangArchs.insert(llvm::Triple::x86_64);
CCCClangArchs.insert(llvm::Triple::arm);
}
Name = llvm::sys::path::stem(ClangExecutable);
Dir = llvm::sys::path::parent_path(ClangExecutable);
// Compute the path to the resource directory.
StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
SmallString<128> P(Dir);
if (ClangResourceDir != "")
llvm::sys::path::append(P, ClangResourceDir);
else
llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
ResourceDir = P.str();
}
Driver::~Driver() {
delete Opts;
for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
E = ToolChains.end();
I != E; ++I)
delete I->second;
}
InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
unsigned MissingArgIndex, MissingArgCount;
InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
MissingArgIndex, MissingArgCount);
// Check for missing argument error.
if (MissingArgCount)
Diag(clang::diag::err_drv_missing_argument)
<< Args->getArgString(MissingArgIndex) << MissingArgCount;
// Check for unsupported options.
for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
it != ie; ++it) {
Arg *A = *it;
if (A->getOption().isUnsupported()) {
Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
continue;
}
// Warn about -mcpu= without an argument.
if (A->getOption().matches(options::OPT_mcpu_EQ) &&
A->containsValue("")) {
Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(*Args);
}
}
return Args;
}
// Determine which compilation mode we are in. We look for options which
// affect the phase, starting with the earliest phases, and record which
// option we used to determine the final phase.
phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
const {
Arg *PhaseArg = 0;
phases::ID FinalPhase;
// -{E,M,MM} only run the preprocessor.
if (CCCIsCPP ||
(PhaseArg = DAL.getLastArg(options::OPT_E)) ||
(PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
FinalPhase = phases::Preprocess;
// -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
} else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
(PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
(PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
(PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
(PhaseArg = DAL.getLastArg(options::OPT__analyze,
options::OPT__analyze_auto)) ||
(PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
(PhaseArg = DAL.getLastArg(options::OPT_S))) {
FinalPhase = phases::Compile;
// -c only runs up to the assembler.
} else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
FinalPhase = phases::Assemble;
// Otherwise do everything.
} else
FinalPhase = phases::Link;
if (FinalPhaseArg)
*FinalPhaseArg = PhaseArg;
return FinalPhase;
}
DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
DerivedArgList *DAL = new DerivedArgList(Args);
bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
for (ArgList::const_iterator it = Args.begin(),
ie = Args.end(); it != ie; ++it) {
const Arg *A = *it;
// Unfortunately, we have to parse some forwarding options (-Xassembler,
// -Xlinker, -Xpreprocessor) because we either integrate their functionality
// (assembler and preprocessor), or bypass a previous driver ('collect2').
// Rewrite linker options, to replace --no-demangle with a custom internal
// option.
if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
A->getOption().matches(options::OPT_Xlinker)) &&
A->containsValue("--no-demangle")) {
// Add the rewritten no-demangle argument.
DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
// Add the remaining values as Xlinker arguments.
for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
if (StringRef(A->getValue(Args, i)) != "--no-demangle")
DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
A->getValue(Args, i));
continue;
}
// Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
// some build systems. We don't try to be complete here because we don't
// care to encourage this usage model.
if (A->getOption().matches(options::OPT_Wp_COMMA) &&
A->getNumValues() == 2 &&
(A->getValue(Args, 0) == StringRef("-MD") ||
A->getValue(Args, 0) == StringRef("-MMD"))) {
// Rewrite to -MD/-MMD along with -MF.
if (A->getValue(Args, 0) == StringRef("-MD"))
DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
else
DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
A->getValue(Args, 1));
continue;
}
// Rewrite reserved library names.
if (A->getOption().matches(options::OPT_l)) {
StringRef Value = A->getValue(Args);
// Rewrite unless -nostdlib is present.
if (!HasNostdlib && Value == "stdc++") {
DAL->AddFlagArg(A, Opts->getOption(
options::OPT_Z_reserved_lib_stdcxx));
continue;
}
// Rewrite unconditionally.
if (Value == "cc_kext") {
DAL->AddFlagArg(A, Opts->getOption(
options::OPT_Z_reserved_lib_cckext));
continue;
}
}
DAL->append(*it);
}
// Add a default value of -mlinker-version=, if one was given and the user
// didn't specify one.
#if defined(HOST_LINK_VERSION)
if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
HOST_LINK_VERSION);
DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
}
#endif
return DAL;
}
Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
llvm::PrettyStackTraceString CrashInfo("Compilation construction");
// FIXME: Handle environment options which affect driver behavior, somewhere
// (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
if (char *env = ::getenv("COMPILER_PATH")) {
StringRef CompilerPath = env;
while (!CompilerPath.empty()) {
std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
PrefixDirs.push_back(Split.first);
CompilerPath = Split.second;
}
}
// FIXME: What are we going to do with -V and -b?
// FIXME: This stuff needs to go into the Compilation, not the driver.
bool CCCPrintOptions = false, CCCPrintActions = false;
InputArgList *Args = ParseArgStrings(ArgList.slice(1));
// -no-canonical-prefixes is used very early in main.
Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
// Ignore -pipe.
Args->ClaimAllArgs(options::OPT_pipe);
// Extract -ccc args.
//
// FIXME: We need to figure out where this behavior should live. Most of it
// should be outside in the client; the parts that aren't should have proper
// options, either by introducing new ones or by overloading gcc ones like -V
// or -b.
CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
CCCEcho = Args->hasArg(options::OPT_ccc_echo);
if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
CCCGenericGCCName = A->getValue(*Args);
CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
options::OPT_ccc_no_clang_cxx,
CCCUseClangCXX);
CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
options::OPT_ccc_pch_is_pth);
CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
StringRef Cur = A->getValue(*Args);
CCCClangArchs.clear();
while (!Cur.empty()) {
std::pair<StringRef, StringRef> Split = Cur.split(',');
if (!Split.first.empty()) {
llvm::Triple::ArchType Arch =
llvm::Triple(Split.first, "", "").getArch();
if (Arch == llvm::Triple::UnknownArch)
Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
CCCClangArchs.insert(Arch);
}
Cur = Split.second;
}
}
// FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
// and getToolChain is const.
if (const Arg *A = Args->getLastArg(options::OPT_target))
DefaultTargetTriple = A->getValue(*Args);
if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
Dir = InstalledDir = A->getValue(*Args);
for (arg_iterator it = Args->filtered_begin(options::OPT_B),
ie = Args->filtered_end(); it != ie; ++it) {
const Arg *A = *it;
A->claim();
PrefixDirs.push_back(A->getValue(*Args, 0));
}
if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
SysRoot = A->getValue(*Args);
if (Args->hasArg(options::OPT_nostdlib))
UseStdLib = false;
// Perform the default argument translations.
DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
// Owned by the host.
const ToolChain &TC = getToolChain(*Args);
// The compilation takes ownership of Args.
Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
// FIXME: This behavior shouldn't be here.
if (CCCPrintOptions) {
PrintOptions(C->getInputArgs());
return C;
}
if (!HandleImmediateArgs(*C))
return C;
// Construct the list of inputs.
InputList Inputs;
BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
// Construct the list of abstract actions to perform for this compilation. On
// Darwin target OSes this uses the driver-driver and universal actions.
if (TC.getTriple().isOSDarwin())
BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
Inputs, C->getActions());
else
BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
C->getActions());
if (CCCPrintActions) {
PrintActions(*C);
return C;
}
BuildJobs(*C);
return C;
}
// When clang crashes, produce diagnostic information including the fully
// preprocessed source file(s). Request that the developer attach the
// diagnostic information to a bug report.
void Driver::generateCompilationDiagnostics(Compilation &C,
const Command *FailingCommand) {
if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
return;
// Don't try to generate diagnostics for link jobs.
if (FailingCommand->getCreator().isLinkJob())
return;
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Please submit a bug report to " BUG_REPORT_URL " and include command"
" line arguments and all diagnostic information.";
// Suppress driver output and emit preprocessor output to temp file.
CCCIsCPP = true;
CCGenDiagnostics = true;
// Save the original job command(s).
std::string Cmd;
llvm::raw_string_ostream OS(Cmd);
C.PrintJob(OS, C.getJobs(), "\n", false);
OS.flush();
// Clear stale state and suppress tool output.
C.initCompilationForDiagnostics();
Diags.Reset();
// Construct the list of inputs.
InputList Inputs;
BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
bool IgnoreInput = false;
// Ignore input from stdin or any inputs that cannot be preprocessed.
if (!strcmp(it->second->getValue(C.getArgs()), "-")) {
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating preprocessed source(s) - ignoring input from stdin"
".";
IgnoreInput = true;
} else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
IgnoreInput = true;
}
if (IgnoreInput) {
it = Inputs.erase(it);
ie = Inputs.end();
} else {
++it;
}
}
// Don't attempt to generate preprocessed files if multiple -arch options are
// used, unless they're all duplicates.
llvm::StringSet<> ArchNames;
for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
it != ie; ++it) {
Arg *A = *it;
if (A->getOption().matches(options::OPT_arch)) {
StringRef ArchName = A->getValue(C.getArgs());
ArchNames.insert(ArchName);
}
}
if (ArchNames.size() > 1) {
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating preprocessed source(s) - cannot generate "
"preprocessed source with multiple -arch options.";
return;
}
if (Inputs.empty()) {
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating preprocessed source(s) - no preprocessable inputs.";
return;
}
// Construct the list of abstract actions to perform for this compilation. On
// Darwin OSes this uses the driver-driver and builds universal actions.
const ToolChain &TC = C.getDefaultToolChain();
if (TC.getTriple().isOSDarwin())
BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
else
BuildActions(TC, C.getArgs(), Inputs, C.getActions());
BuildJobs(C);
// If there were errors building the compilation, quit now.
if (Diags.hasErrorOccurred()) {
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating preprocessed source(s).";
return;
}
// Generate preprocessed output.
FailingCommand = 0;
int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
// If the command succeeded, we are done.
if (Res == 0) {
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Preprocessed source(s) and associated run script(s) are located at:";
ArgStringList Files = C.getTempFiles();
for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
it != ie; ++it) {
Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
std::string Err;
std::string Script = StringRef(*it).rsplit('.').first;
Script += ".sh";
llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
llvm::raw_fd_ostream::F_Excl |
llvm::raw_fd_ostream::F_Binary);
if (!Err.empty()) {
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating run script: " + Script + " " + Err;
} else {
ScriptOS << Cmd;
Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
}
}
} else {
// Failure, remove preprocessed files.
if (!C.getArgs().hasArg(options::OPT_save_temps))
C.CleanupFileList(C.getTempFiles(), true);
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating preprocessed source(s).";
}
}
int Driver::ExecuteCompilation(const Compilation &C,
const Command *&FailingCommand) const {
// Just print if -### was present.
if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
return 0;
}
// If there were errors building the compilation, quit now.
if (Diags.hasErrorOccurred())
return 1;
int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
// Remove temp files.
C.CleanupFileList(C.getTempFiles());
// If the command succeeded, we are done.
if (Res == 0)
return Res;
// Otherwise, remove result files as well.
if (!C.getArgs().hasArg(options::OPT_save_temps)) {
C.CleanupFileList(C.getResultFiles(), true);
// Failure result files are valid unless we crashed.
if (Res < 0) {
C.CleanupFileList(C.getFailureResultFiles(), true);
#ifdef _WIN32
// Exit status should not be negative on Win32,
// unless abnormal termination.
Res = 1;
#endif
}
}
// Print extra information about abnormal failures, if possible.
//
// This is ad-hoc, but we don't want to be excessively noisy. If the result
// status was 1, assume the command failed normally. In particular, if it was
// the compiler then assume it gave a reasonable error code. Failures in other
// tools are less common, and they generally have worse diagnostics, so always
// print the diagnostic there.
const Tool &FailingTool = FailingCommand->getCreator();
if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
// FIXME: See FIXME above regarding result code interpretation.
if (Res < 0)
Diag(clang::diag::err_drv_command_signalled)
<< FailingTool.getShortName();
else
Diag(clang::diag::err_drv_command_failed)
<< FailingTool.getShortName() << Res;
}
return Res;
}
void Driver::PrintOptions(const ArgList &Args) const {
unsigned i = 0;
for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
it != ie; ++it, ++i) {
Arg *A = *it;
llvm::errs() << "Option " << i << " - "
<< "Name: \"" << A->getOption().getName() << "\", "
<< "Values: {";
for (unsigned j = 0; j < A->getNumValues(); ++j) {
if (j)
llvm::errs() << ", ";
llvm::errs() << '"' << A->getValue(Args, j) << '"';
}
llvm::errs() << "}\n";
}
}
void Driver::PrintHelp(bool ShowHidden) const {
getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
ShowHidden);
}
void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
// FIXME: The following handlers should use a callback mechanism, we don't
// know what the client would like to do.
OS << getClangFullVersion() << '\n';
const ToolChain &TC = C.getDefaultToolChain();
OS << "Target: " << TC.getTripleString() << '\n';
// Print the threading model.
//
// FIXME: Implement correctly.
OS << "Thread model: " << "posix" << '\n';
}
/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
/// option.
static void PrintDiagnosticCategories(raw_ostream &OS) {
// Skip the empty category.
for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
i != max; ++i)
OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
}
bool Driver::HandleImmediateArgs(const Compilation &C) {
// The order these options are handled in gcc is all over the place, but we
// don't expect inconsistencies w.r.t. that to matter in practice.
if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
return false;
}
if (C.getArgs().hasArg(options::OPT_dumpversion)) {
// Since -dumpversion is only implemented for pedantic GCC compatibility, we
// return an answer which matches our definition of __VERSION__.
//
// If we want to return a more correct answer some day, then we should
// introduce a non-pedantically GCC compatible mode to Clang in which we
// provide sensible definitions for -dumpversion, __VERSION__, etc.
llvm::outs() << "4.2.1\n";
return false;
}
if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
PrintDiagnosticCategories(llvm::outs());
return false;
}
if (C.getArgs().hasArg(options::OPT__help) ||
C.getArgs().hasArg(options::OPT__help_hidden)) {
PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
return false;
}
if (C.getArgs().hasArg(options::OPT__version)) {
// Follow gcc behavior and use stdout for --version and stderr for -v.
PrintVersion(C, llvm::outs());
return false;
}
if (C.getArgs().hasArg(options::OPT_v) ||
C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
PrintVersion(C, llvm::errs());
SuppressMissingInputWarning = true;
}
const ToolChain &TC = C.getDefaultToolChain();
if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
llvm::outs() << "programs: =";
for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
ie = TC.getProgramPaths().end(); it != ie; ++it) {
if (it != TC.getProgramPaths().begin())
llvm::outs() << ':';
llvm::outs() << *it;
}
llvm::outs() << "\n";
llvm::outs() << "libraries: =" << ResourceDir;
StringRef sysroot = C.getSysRoot();
for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
ie = TC.getFilePaths().end(); it != ie; ++it) {
llvm::outs() << ':';
const char *path = it->c_str();
if (path[0] == '=')
llvm::outs() << sysroot << path + 1;
else
llvm::outs() << path;
}
llvm::outs() << "\n";
return false;
}
// FIXME: The following handlers should use a callback mechanism, we don't
// know what the client would like to do.
if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
return false;
}
if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
return false;
}
if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
return false;
}
if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
// FIXME: We need tool chain support for this.
llvm::outs() << ".;\n";
switch (C.getDefaultToolChain().getTriple().getArch()) {
default:
break;
case llvm::Triple::x86_64:
llvm::outs() << "x86_64;@m64" << "\n";
break;
case llvm::Triple::ppc64:
llvm::outs() << "ppc64;@m64" << "\n";
break;
}
return false;
}
// FIXME: What is the difference between print-multi-directory and
// print-multi-os-directory?
if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
switch (C.getDefaultToolChain().getTriple().getArch()) {
default:
case llvm::Triple::x86:
case llvm::Triple::ppc:
llvm::outs() << "." << "\n";
break;
case llvm::Triple::x86_64:
llvm::outs() << "x86_64" << "\n";
break;
case llvm::Triple::ppc64:
llvm::outs() << "ppc64" << "\n";
break;
}
return false;
}
return true;
}
static unsigned PrintActions1(const Compilation &C, Action *A,
std::map<Action*, unsigned> &Ids) {
if (Ids.count(A))
return Ids[A];
std::string str;
llvm::raw_string_ostream os(str);
os << Action::getClassName(A->getKind()) << ", ";
if (InputAction *IA = dyn_cast<InputAction>(A)) {
os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
} else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
os << '"' << (BIA->getArchName() ? BIA->getArchName() :
C.getDefaultToolChain().getArchName()) << '"'
<< ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
} else {
os << "{";
for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
os << PrintActions1(C, *it, Ids);
++it;
if (it != ie)
os << ", ";
}
os << "}";
}
unsigned Id = Ids.size();
Ids[A] = Id;
llvm::errs() << Id << ": " << os.str() << ", "
<< types::getTypeName(A->getType()) << "\n";
return Id;
}
void Driver::PrintActions(const Compilation &C) const {
std::map<Action*, unsigned> Ids;
for (ActionList::const_iterator it = C.getActions().begin(),
ie = C.getActions().end(); it != ie; ++it)
PrintActions1(C, *it, Ids);
}
/// \brief Check whether the given input tree contains any compilation or
/// assembly actions.
static bool ContainsCompileOrAssembleAction(const Action *A) {
if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
return true;
for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
if (ContainsCompileOrAssembleAction(*it))
return true;
return false;
}
void Driver::BuildUniversalActions(const ToolChain &TC,
const DerivedArgList &Args,
const InputList &BAInputs,
ActionList &Actions) const {
llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
// Collect the list of architectures. Duplicates are allowed, but should only
// be handled once (in the order seen).
llvm::StringSet<> ArchNames;
SmallVector<const char *, 4> Archs;
for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
it != ie; ++it) {
Arg *A = *it;
if (A->getOption().matches(options::OPT_arch)) {
// Validate the option here; we don't save the type here because its
// particular spelling may participate in other driver choices.
llvm::Triple::ArchType Arch =
llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
if (Arch == llvm::Triple::UnknownArch) {
Diag(clang::diag::err_drv_invalid_arch_name)
<< A->getAsString(Args);
continue;
}
A->claim();
if (ArchNames.insert(A->getValue(Args)))
Archs.push_back(A->getValue(Args));
}
}
// When there is no explicit arch for this platform, make sure we still bind
// the architecture (to the default) so that -Xarch_ is handled correctly.
if (!Archs.size())
Archs.push_back(0);
// FIXME: We killed off some others but these aren't yet detected in a
// functional manner. If we added information to jobs about which "auxiliary"
// files they wrote then we could detect the conflict these cause downstream.
if (Archs.size() > 1) {
// No recovery needed, the point of this is just to prevent
// overwriting the same files.
if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
<< A->getAsString(Args);
}
ActionList SingleActions;
BuildActions(TC, Args, BAInputs, SingleActions);
// Add in arch bindings for every top level action, as well as lipo and
// dsymutil steps if needed.
for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
Action *Act = SingleActions[i];
// Make sure we can lipo this kind of output. If not (and it is an actual
// output) then we disallow, since we can't create an output file with the
// right name without overwriting it. We could remove this oddity by just
// changing the output names to include the arch, which would also fix
// -save-temps. Compatibility wins for now.
if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
<< types::getTypeName(Act->getType());
ActionList Inputs;
for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
Inputs.push_back(new BindArchAction(Act, Archs[i]));
if (i != 0)
Inputs.back()->setOwnsInputs(false);
}
// Lipo if necessary, we do it this way because we need to set the arch flag
// so that -Xarch_ gets overwritten.
if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
Actions.append(Inputs.begin(), Inputs.end());
else
Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
// Handle debug info queries.
Arg *A = Args.getLastArg(options::OPT_g_Group);
if (A && !A->getOption().matches(options::OPT_g0) &&
!A->getOption().matches(options::OPT_gstabs) &&
ContainsCompileOrAssembleAction(Actions.back())) {
// Add a 'dsymutil' step if necessary, when debug info is enabled and we
// have a compile input. We need to run 'dsymutil' ourselves in such cases
// because the debug info will refer to a temporary object file which is
// will be removed at the end of the compilation process.
if (Act->getType() == types::TY_Image) {
ActionList Inputs;
Inputs.push_back(Actions.back());
Actions.pop_back();
Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
}
// Verify the output (debug information only) if we passed '-verify'.
if (Args.hasArg(options::OPT_verify)) {
ActionList VerifyInputs;
VerifyInputs.push_back(Actions.back());
Actions.pop_back();
Actions.push_back(new VerifyJobAction(VerifyInputs,
types::TY_Nothing));
}
}
}
}
// Construct a the list of inputs and their types.
void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
InputList &Inputs) const {
// Track the current user specified (-x) input. We also explicitly track the
// argument used to set the type; we only want to claim the type when we
// actually use it, so we warn about unused -x arguments.
types::ID InputType = types::TY_Nothing;
Arg *InputTypeArg = 0;
for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
it != ie; ++it) {
Arg *A = *it;
if (isa<InputOption>(A->getOption())) {
const char *Value = A->getValue(Args);
types::ID Ty = types::TY_INVALID;
// Infer the input type if necessary.
if (InputType == types::TY_Nothing) {
// If there was an explicit arg for this, claim it.
if (InputTypeArg)
InputTypeArg->claim();
// stdin must be handled specially.
if (memcmp(Value, "-", 2) == 0) {
// If running with -E, treat as a C input (this changes the builtin
// macros, for example). This may be overridden by -ObjC below.
//
// Otherwise emit an error but still use a valid type to avoid
// spurious errors (e.g., no inputs).
if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
Diag(clang::diag::err_drv_unknown_stdin_type);
Ty = types::TY_C;
} else {
// Otherwise lookup by extension.
// Fallback is C if invoked as C preprocessor or Object otherwise.
// We use a host hook here because Darwin at least has its own
// idea of what .s is.
if (const char *Ext = strrchr(Value, '.'))
Ty = TC.LookupTypeForExtension(Ext + 1);
if (Ty == types::TY_INVALID) {
if (CCCIsCPP)
Ty = types::TY_C;
else
Ty = types::TY_Object;
}
// If the driver is invoked as C++ compiler (like clang++ or c++) it
// should autodetect some input files as C++ for g++ compatibility.
if (CCCIsCXX) {
types::ID OldTy = Ty;
Ty = types::lookupCXXTypeForCType(Ty);
if (Ty != OldTy)
Diag(clang::diag::warn_drv_treating_input_as_cxx)
<< getTypeName(OldTy) << getTypeName(Ty);
}
}
// -ObjC and -ObjC++ override the default language, but only for "source
// files". We just treat everything that isn't a linker input as a
// source file.
//
// FIXME: Clean this up if we move the phase sequence into the type.
if (Ty != types::TY_Object) {
if (Args.hasArg(options::OPT_ObjC))
Ty = types::TY_ObjC;
else if (Args.hasArg(options::OPT_ObjCXX))
Ty = types::TY_ObjCXX;
}
} else {
assert(InputTypeArg && "InputType set w/o InputTypeArg");
InputTypeArg->claim();
Ty = InputType;
}
// Check that the file exists, if enabled.
if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
SmallString<64> Path(Value);
if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
SmallString<64> Directory(WorkDir->getValue(Args));
if (llvm::sys::path::is_absolute(Directory.str())) {
llvm::sys::path::append(Directory, Value);
Path.assign(Directory);
}
}
bool exists = false;
if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
Diag(clang::diag::err_drv_no_such_file) << Path.str();
else
Inputs.push_back(std::make_pair(Ty, A));
} else
Inputs.push_back(std::make_pair(Ty, A));
} else if (A->getOption().isLinkerInput()) {
// Just treat as object type, we could make a special type for this if
// necessary.
Inputs.push_back(std::make_pair(types::TY_Object, A));
} else if (A->getOption().matches(options::OPT_x)) {
InputTypeArg = A;
InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
A->claim();
// Follow gcc behavior and treat as linker input for invalid -x
// options. Its not clear why we shouldn't just revert to unknown; but
// this isn't very important, we might as well be bug compatible.
if (!InputType) {
Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
InputType = types::TY_Object;
}
}
}
if (CCCIsCPP && Inputs.empty()) {
// If called as standalone preprocessor, stdin is processed
// if no other input is present.
unsigned Index = Args.getBaseArgs().MakeIndex("-");
Arg *A = Opts->ParseOneArg(Args, Index);
A->claim();
Inputs.push_back(std::make_pair(types::TY_C, A));
}
}
void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
const InputList &Inputs, ActionList &Actions) const {
llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
if (!SuppressMissingInputWarning && Inputs.empty()) {
Diag(clang::diag::err_drv_no_input_files);
return;
}
Arg *FinalPhaseArg;
phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
// Reject -Z* at the top level, these options should never have been exposed
// by gcc.
if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
// Construct the actions to perform.
ActionList LinkerInputs;
unsigned NumSteps = 0;
for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
types::ID InputType = Inputs[i].first;
const Arg *InputArg = Inputs[i].second;
NumSteps = types::getNumCompilationPhases(InputType);
assert(NumSteps && "Invalid number of steps!");
// If the first step comes after the final phase we are doing as part of
// this compilation, warn the user about it.
phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
if (InitialPhase > FinalPhase) {
// Claim here to avoid the more general unused warning.
InputArg->claim();
// Suppress all unused style warnings with -Qunused-arguments
if (Args.hasArg(options::OPT_Qunused_arguments))
continue;
// Special case '-E' warning on a previously preprocessed file to make
// more sense.
if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
getPreprocessedType(InputType) == types::TY_INVALID)
Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
<< InputArg->getAsString(Args)
<< FinalPhaseArg->getOption().getName();
else
Diag(clang::diag::warn_drv_input_file_unused)
<< InputArg->getAsString(Args)
<< getPhaseName(InitialPhase)
<< FinalPhaseArg->getOption().getName();
continue;
}
// Build the pipeline for this file.
OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
for (unsigned i = 0; i != NumSteps; ++i) {
phases::ID Phase = types::getCompilationPhase(InputType, i);
// We are done if this step is past what the user requested.
if (Phase > FinalPhase)
break;
// Queue linker inputs.
if (Phase == phases::Link) {
assert(i + 1 == NumSteps && "linking must be final compilation step.");
LinkerInputs.push_back(Current.take());
break;
}
// Some types skip the assembler phase (e.g., llvm-bc), but we can't
// encode this in the steps because the intermediate type depends on
// arguments. Just special case here.
if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
continue;
// Otherwise construct the appropriate action.
Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
if (Current->getType() == types::TY_Nothing)
break;
}
// If we ended with something, add to the output list.
if (Current)
Actions.push_back(Current.take());
}
// Add a link action if necessary.
if (!LinkerInputs.empty())
Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
// If we are linking, claim any options which are obviously only used for
// compilation.
if (FinalPhase == phases::Link && (NumSteps == 1))
Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
}
Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
Action *Input) const {
llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
// Build the appropriate action.
switch (Phase) {
case phases::Link: llvm_unreachable("link action invalid here.");
case phases::Preprocess: {
types::ID OutputTy;
// -{M, MM} alter the output type.
if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
OutputTy = types::TY_Dependencies;
} else {
OutputTy = types::getPreprocessedType(Input->getType());
assert(OutputTy != types::TY_INVALID &&
"Cannot preprocess this input type!");
}
return new PreprocessJobAction(Input, OutputTy);
}
case phases::Precompile:
return new PrecompileJobAction(Input, types::TY_PCH);
case phases::Compile: {
if (Args.hasArg(options::OPT_fsyntax_only)) {
return new CompileJobAction(Input, types::TY_Nothing);
} else if (Args.hasArg(options::OPT_rewrite_objc)) {
return new CompileJobAction(Input, types::TY_RewrittenObjC);
} else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
} else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
return new AnalyzeJobAction(Input, types::TY_Plist);
} else if (Args.hasArg(options::OPT__migrate)) {
return new MigrateJobAction(Input, types::TY_Remap);
} else if (Args.hasArg(options::OPT_emit_ast)) {
return new CompileJobAction(Input, types::TY_AST);
} else if (IsUsingLTO(Args)) {
types::ID Output =
Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
return new CompileJobAction(Input, Output);
} else {
return new CompileJobAction(Input, types::TY_PP_Asm);
}
}
case phases::Assemble:
return new AssembleJobAction(Input, types::TY_Object);
}
llvm_unreachable("invalid phase in ConstructPhaseAction");
}
bool Driver::IsUsingLTO(const ArgList &Args) const {
// Check for -emit-llvm or -flto.
if (Args.hasArg(options::OPT_emit_llvm) ||
Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
return true;
// Check for -O4.
if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
return A->getOption().matches(options::OPT_O4);
return false;
}
void Driver::BuildJobs(Compilation &C) const {
llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
// It is an error to provide a -o option if we are making multiple output
// files.
if (FinalOutput) {
unsigned NumOutputs = 0;
for (ActionList::const_iterator it = C.getActions().begin(),
ie = C.getActions().end(); it != ie; ++it)
if ((*it)->getType() != types::TY_Nothing)
++NumOutputs;
if (NumOutputs > 1) {
Diag(clang::diag::err_drv_output_argument_with_multiple_files);
FinalOutput = 0;
}
}
for (ActionList::const_iterator it = C.getActions().begin(),
ie = C.getActions().end(); it != ie; ++it) {
Action *A = *it;
// If we are linking an image for multiple archs then the linker wants
// -arch_multiple and -final_output <final image name>. Unfortunately, this
// doesn't fit in cleanly because we have to pass this information down.
//
// FIXME: This is a hack; find a cleaner way to integrate this into the
// process.
const char *LinkingOutput = 0;
if (isa<LipoJobAction>(A)) {
if (FinalOutput)
LinkingOutput = FinalOutput->getValue(C.getArgs());
else
LinkingOutput = DefaultImageName.c_str();
}
InputInfo II;
BuildJobsForAction(C, A, &C.getDefaultToolChain(),
/*BoundArch*/0,
/*AtTopLevel*/ true,
/*LinkingOutput*/ LinkingOutput,
II);
}
// If the user passed -Qunused-arguments or there were errors, don't warn
// about any unused arguments.
if (Diags.hasErrorOccurred() ||
C.getArgs().hasArg(options::OPT_Qunused_arguments))
return;
// Claim -### here.
(void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
it != ie; ++it) {
Arg *A = *it;
// FIXME: It would be nice to be able to send the argument to the
// DiagnosticsEngine, so that extra values, position, and so on could be
// printed.
if (!A->isClaimed()) {
if (A->getOption().hasNoArgumentUnused())
continue;
// Suppress the warning automatically if this is just a flag, and it is an
// instance of an argument we already claimed.
const Option &Opt = A->getOption();
if (isa<FlagOption>(Opt)) {
bool DuplicateClaimed = false;
for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
ie = C.getArgs().filtered_end(); it != ie; ++it) {
if ((*it)->isClaimed()) {
DuplicateClaimed = true;
break;
}
}
if (DuplicateClaimed)
continue;
}
Diag(clang::diag::warn_drv_unused_argument)
<< A->getAsString(C.getArgs());
}
}
}
static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
const JobAction *JA,
const ActionList *&Inputs) {
const Tool *ToolForJob = 0;
// See if we should look for a compiler with an integrated assembler. We match
// bottom up, so what we are actually looking for is an assembler job with a
// compiler input.
if (C.getArgs().hasFlag(options::OPT_integrated_as,
options::OPT_no_integrated_as,
TC->IsIntegratedAssemblerDefault()) &&
!C.getArgs().hasArg(options::OPT_save_temps) &&
isa<AssembleJobAction>(JA) &&
Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
const Tool &Compiler = TC->SelectTool(
C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
if (Compiler.hasIntegratedAssembler()) {
Inputs = &(*Inputs)[0]->getInputs();
ToolForJob = &Compiler;
}
}
// Otherwise use the tool for the current job.
if (!ToolForJob)
ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
// See if we should use an integrated preprocessor. We do so when we have
// exactly one input, since this is the only use case we care about
// (irrelevant since we don't support combine yet).
if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
!C.getArgs().hasArg(options::OPT_traditional_cpp) &&
!C.getArgs().hasArg(options::OPT_save_temps) &&
ToolForJob->hasIntegratedCPP())
Inputs = &(*Inputs)[0]->getInputs();
return *ToolForJob;
}
void Driver::BuildJobsForAction(Compilation &C,
const Action *A,
const ToolChain *TC,
const char *BoundArch,
bool AtTopLevel,
const char *LinkingOutput,
InputInfo &Result) const {
llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
if (const InputAction *IA = dyn_cast<InputAction>(A)) {
// FIXME: It would be nice to not claim this here; maybe the old scheme of
// just using Args was better?
const Arg &Input = IA->getInputArg();
Input.claim();
if (Input.getOption().matches(options::OPT_INPUT)) {
const char *Name = Input.getValue(C.getArgs());
Result = InputInfo(Name, A->getType(), Name);
} else
Result = InputInfo(&Input, A->getType(), "");
return;
}
if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
const ToolChain *TC = &C.getDefaultToolChain();
if (BAA->getArchName())
TC = &getToolChain(C.getArgs(), BAA->getArchName());
BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
AtTopLevel, LinkingOutput, Result);
return;
}
const ActionList *Inputs = &A->getInputs();
const JobAction *JA = cast<JobAction>(A);
const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
// Only use pipes when there is exactly one input.
InputInfoList InputInfos;
for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
it != ie; ++it) {
// Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
// temporary output names.
//
// FIXME: Clean this up.
bool SubJobAtTopLevel = false;
if (AtTopLevel && isa<DsymutilJobAction>(A))
SubJobAtTopLevel = true;
// Also treat verify sub-jobs as being at the top-level. They don't
// produce any output and so don't need temporary output names.
if (AtTopLevel && isa<VerifyJobAction>(A))
SubJobAtTopLevel = true;
InputInfo II;
BuildJobsForAction(C, *it, TC, BoundArch,
SubJobAtTopLevel, LinkingOutput, II);
InputInfos.push_back(II);
}
// Always use the first input as the base input.
const char *BaseInput = InputInfos[0].getBaseInput();
// ... except dsymutil actions, which use their actual input as the base
// input.
if (JA->getType() == types::TY_dSYM)
BaseInput = InputInfos[0].getFilename();
// Determine the place to write output to, if any.
if (JA->getType() == types::TY_Nothing) {
Result = InputInfo(A->getType(), BaseInput);
} else {
Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
A->getType(), BaseInput);
}
if (CCCPrintBindings && !CCGenDiagnostics) {
llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
<< " - \"" << T.getName() << "\", inputs: [";
for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
llvm::errs() << InputInfos[i].getAsString();
if (i + 1 != e)
llvm::errs() << ", ";
}
llvm::errs() << "], output: " << Result.getAsString() << "\n";
} else {
T.ConstructJob(C, *JA, Result, InputInfos,
C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
}
}
const char *Driver::GetNamedOutputPath(Compilation &C,
const JobAction &JA,
const char *BaseInput,
bool AtTopLevel) const {
llvm::PrettyStackTraceString CrashInfo("Computing output path");
// Output to a user requested destination?
if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
!isa<VerifyJobAction>(JA)) {
if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
return C.addResultFile(FinalOutput->getValue(C.getArgs()));
}
// Default to writing to stdout?
if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
return "-";
// Output to a temporary file?
if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
CCGenDiagnostics) {
StringRef Name = llvm::sys::path::filename(BaseInput);
std::pair<StringRef, StringRef> Split = Name.split('.');
std::string TmpName =
GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
}
SmallString<128> BasePath(BaseInput);
StringRef BaseName;
// Dsymutil actions should use the full path.
if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
BaseName = BasePath;
else
BaseName = llvm::sys::path::filename(BasePath);
// Determine what the derived output name should be.
const char *NamedOutput;
if (JA.getType() == types::TY_Image) {
NamedOutput = DefaultImageName.c_str();
} else {
const char *Suffix = types::getTypeTempSuffix(JA.getType());
assert(Suffix && "All types used for output should have a suffix.");
std::string::size_type End = std::string::npos;
if (!types::appendSuffixForType(JA.getType()))
End = BaseName.rfind('.');
std::string Suffixed(BaseName.substr(0, End));
Suffixed += '.';
Suffixed += Suffix;
NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
}
// If we're saving temps and the temp filename conflicts with the input
// filename, then avoid overwriting input file.
if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
NamedOutput == BaseName) {
StringRef Name = llvm::sys::path::filename(BaseInput);
std::pair<StringRef, StringRef> Split = Name.split('.');
std::string TmpName =
GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
}
// As an annoying special case, PCH generation doesn't strip the pathname.
if (JA.getType() == types::TY_PCH) {
llvm::sys::path::remove_filename(BasePath);
if (BasePath.empty())
BasePath = NamedOutput;
else
llvm::sys::path::append(BasePath, NamedOutput);
return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
} else {
return C.addResultFile(NamedOutput);
}
}
std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
// Respect a limited subset of the '-Bprefix' functionality in GCC by
// attempting to use this prefix when lokup up program paths.
for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
ie = PrefixDirs.end(); it != ie; ++it) {
std::string Dir(*it);
if (Dir.empty())
continue;
if (Dir[0] == '=')
Dir = SysRoot + Dir.substr(1);
llvm::sys::Path P(Dir);
P.appendComponent(Name);
bool Exists;
if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
return P.str();
}
llvm::sys::Path P(ResourceDir);
P.appendComponent(Name);
bool Exists;
if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
return P.str();
const ToolChain::path_list &List = TC.getFilePaths();
for (ToolChain::path_list::const_iterator
it = List.begin(), ie = List.end(); it != ie; ++it) {
std::string Dir(*it);
if (Dir.empty())
continue;
if (Dir[0] == '=')
Dir = SysRoot + Dir.substr(1);
llvm::sys::Path P(Dir);
P.appendComponent(Name);
bool Exists;
if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
return P.str();
}
return Name;
}
static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
bool Exists;
return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
: P.canExecute());
}
std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
bool WantFile) const {
// FIXME: Needs a better variable than DefaultTargetTriple
std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
// Respect a limited subset of the '-Bprefix' functionality in GCC by
// attempting to use this prefix when lokup up program paths.
for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
ie = PrefixDirs.end(); it != ie; ++it) {
llvm::sys::Path P(*it);
P.appendComponent(TargetSpecificExecutable);
if (isPathExecutable(P, WantFile)) return P.str();
P.eraseComponent();
P.appendComponent(Name);
if (isPathExecutable(P, WantFile)) return P.str();
}
const ToolChain::path_list &List = TC.getProgramPaths();
for (ToolChain::path_list::const_iterator
it = List.begin(), ie = List.end(); it != ie; ++it) {
llvm::sys::Path P(*it);
P.appendComponent(TargetSpecificExecutable);
if (isPathExecutable(P, WantFile)) return P.str();
P.eraseComponent();
P.appendComponent(Name);
if (isPathExecutable(P, WantFile)) return P.str();
}
// If all else failed, search the path.
llvm::sys::Path
P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
if (!P.empty())
return P.str();
P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
if (!P.empty())
return P.str();
return Name;
}
std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
const {
// FIXME: This is lame; sys::Path should provide this function (in particular,
// it should know how to find the temporary files dir).
std::string Error;
const char *TmpDir = ::getenv("TMPDIR");
if (!TmpDir)
TmpDir = ::getenv("TEMP");
if (!TmpDir)
TmpDir = ::getenv("TMP");
if (!TmpDir)
TmpDir = "/tmp";
llvm::sys::Path P(TmpDir);
P.appendComponent(Prefix);
if (P.makeUnique(false, &Error)) {
Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
return "";
}
// FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837.
P.eraseFromDisk(false, 0);
P.appendSuffix(Suffix);
return P.str();
}
/// \brief Compute target triple from args.
///
/// This routine provides the logic to compute a target triple from various
/// args passed to the driver and the default triple string.
static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
const ArgList &Args,
StringRef DarwinArchName) {
// FIXME: Already done in Compilation *Driver::BuildCompilation
if (const Arg *A = Args.getLastArg(options::OPT_target))
DefaultTargetTriple = A->getValue(Args);
llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
// Handle Darwin-specific options available here.
if (Target.isOSDarwin()) {
// If an explict Darwin arch name is given, that trumps all.
if (!DarwinArchName.empty()) {
Target.setArch(
llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
return Target;
}
// Handle the Darwin '-arch' flag.
if (Arg *A = Args.getLastArg(options::OPT_arch)) {
llvm::Triple::ArchType DarwinArch
= llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
if (DarwinArch != llvm::Triple::UnknownArch)
Target.setArch(DarwinArch);
}
}
// Skip further flag support on OSes which don't support '-m32' or '-m64'.
if (Target.getArchName() == "tce" ||
Target.getOS() == llvm::Triple::AuroraUX ||
Target.getOS() == llvm::Triple::Minix)
return Target;
// Handle pseudo-target flags '-m32' and '-m64'.
// FIXME: Should this information be in llvm::Triple?
if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
if (A->getOption().matches(options::OPT_m32)) {
if (Target.getArch() == llvm::Triple::x86_64)
Target.setArch(llvm::Triple::x86);
if (Target.getArch() == llvm::Triple::ppc64)
Target.setArch(llvm::Triple::ppc);
} else {
if (Target.getArch() == llvm::Triple::x86)
Target.setArch(llvm::Triple::x86_64);
if (Target.getArch() == llvm::Triple::ppc)
Target.setArch(llvm::Triple::ppc64);
}
}
return Target;
}
const ToolChain &Driver::getToolChain(const ArgList &Args,
StringRef DarwinArchName) const {
llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
DarwinArchName);
ToolChain *&TC = ToolChains[Target.str()];
if (!TC) {
switch (Target.getOS()) {
case llvm::Triple::AuroraUX:
TC = new toolchains::AuroraUX(*this, Target, Args);
break;
case llvm::Triple::Darwin:
case llvm::Triple::MacOSX:
case llvm::Triple::IOS:
if (Target.getArch() == llvm::Triple::x86 ||
Target.getArch() == llvm::Triple::x86_64 ||
Target.getArch() == llvm::Triple::arm ||
Target.getArch() == llvm::Triple::thumb)
TC = new toolchains::DarwinClang(*this, Target);
else
TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
break;
case llvm::Triple::DragonFly:
TC = new toolchains::DragonFly(*this, Target, Args);
break;
case llvm::Triple::OpenBSD:
TC = new toolchains::OpenBSD(*this, Target, Args);
break;
case llvm::Triple::NetBSD:
TC = new toolchains::NetBSD(*this, Target, Args);
break;
case llvm::Triple::FreeBSD:
TC = new toolchains::FreeBSD(*this, Target, Args);
break;
case llvm::Triple::Minix:
TC = new toolchains::Minix(*this, Target, Args);
break;
case llvm::Triple::Linux:
if (Target.getArch() == llvm::Triple::hexagon)
TC = new toolchains::Hexagon_TC(*this, Target);
else
TC = new toolchains::Linux(*this, Target, Args);
break;
case llvm::Triple::Solaris:
TC = new toolchains::Solaris(*this, Target, Args);
break;
case llvm::Triple::Win32:
TC = new toolchains::Windows(*this, Target);
break;
case llvm::Triple::MinGW32:
// FIXME: We need a MinGW toolchain. Fallthrough for now.
default:
// TCE is an OSless target
if (Target.getArchName() == "tce") {
TC = new toolchains::TCEToolChain(*this, Target);
break;
}
TC = new toolchains::Generic_GCC(*this, Target, Args);
break;
}
}
return *TC;
}
bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
const llvm::Triple &Triple) const {
// Check if user requested no clang, or clang doesn't understand this type (we
// only handle single inputs for now).
if (!CCCUseClang || JA.size() != 1 ||
!types::isAcceptedByClang((*JA.begin())->getType()))
return false;
// Otherwise make sure this is an action clang understands.
if (isa<PreprocessJobAction>(JA)) {
if (!CCCUseClangCPP) {
Diag(clang::diag::warn_drv_not_using_clang_cpp);
return false;
}
} else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
return false;
// Use clang for C++?
if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
Diag(clang::diag::warn_drv_not_using_clang_cxx);
return false;
}
// Always use clang for precompiling, AST generation, and rewriting,
// regardless of archs.
if (isa<PrecompileJobAction>(JA) ||
types::isOnlyAcceptedByClang(JA.getType()))
return true;
// Finally, don't use clang if this isn't one of the user specified archs to
// build.
if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
return false;
}
return true;
}
/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
/// grouped values as integers. Numbers which are not provided are set to 0.
///
/// \return True if the entire string was parsed (9.2), or all groups were
/// parsed (10.3.5extrastuff).
bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
unsigned &Minor, unsigned &Micro,
bool &HadExtra) {
HadExtra = false;
Major = Minor = Micro = 0;
if (*Str == '\0')
return true;
char *End;
Major = (unsigned) strtol(Str, &End, 10);
if (*Str != '\0' && *End == '\0')
return true;
if (*End != '.')
return false;
Str = End+1;
Minor = (unsigned) strtol(Str, &End, 10);
if (*Str != '\0' && *End == '\0')
return true;
if (*End != '.')
return false;
Str = End+1;
Micro = (unsigned) strtol(Str, &End, 10);
if (*Str != '\0' && *End == '\0')
return true;
if (Str == End)
return false;
HadExtra = true;
return true;
}
| abduld/clreflect | extern/llvm/tools/clang/lib/Driver/Driver.cpp | C++ | mit | 63,596 |
var path = require('path');
var webpack = require('webpack');
var prodCfg = require('./webpack.prod.config');
Object.assign = require('object-assign');
module.exports = Object.assign(prodCfg, {
entry: [
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/only-dev-server',
'./client'
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel']
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
devtool: 'inline-source-map',
devServer: {
hot: true,
proxy: {
'*': 'http://localhost:' + (process.env.PORT || 3000)
}
}
});
| kirbyk/isomorphic-redux | webpack.config.js | JavaScript | mit | 729 |
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Document;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* @ODM\Document
* @ApiResource(itemOperations={
* "get",
* "get_custom"={"method"="GET", "path"="custom_action_collection_dummies/{id}"},
* "custom_normalization"={"method"="GET", "route_name"="custom_normalization"},
* "short_custom_normalization"={"method"="GET", "route_name"="short_custom_normalization"},
* },
* collectionOperations={
* "get",
* "get_custom"={"method"="GET", "path"="custom_action_collection_dummies"},
* "custom_denormalization"={"method"="GET", "route_name"="custom_denormalization"},
* "short_custom_denormalization"={"method"="GET", "route_name"="short_custom_denormalization"},
* })
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class CustomActionDummy
{
/**
* @var int
*
* @ODM\Id(strategy="INCREMENT", type="integer")
*/
private $id;
/**
* @var string
*
* @ODM\Field
*/
private $foo = '';
public function getId(): int
{
return $this->id;
}
public function getFoo(): string
{
return $this->foo;
}
public function setFoo(string $foo)
{
$this->foo = $foo;
}
}
| soyuka/DunglasApiBundle | tests/Fixtures/TestBundle/Document/CustomActionDummy.php | PHP | mit | 1,591 |
// check rdns against forward
// NOTICE: the functionality of this plugin is duplicated by the
// FCrDNS plugin. Consider using it instead. This plugin
// may be deprecated in the future.
//
// To achieve the same results using FCrDNS (in addition to
// the additional features), set [reject] no_rdns=true in
// connect.fcrdns.ini.
//
// The FCrDNS plugin uses the white/blacklist functionality in the
// access plugin.
var dns = require('dns');
// _dns_error handles err from node.dns callbacks. It will always call next()
// with a DENYDISCONNECT for this plugin.
function _dns_error(connection, next, err, host, plugin, nxdomain, dnserror) {
switch (err.code) {
case dns.NXDOMAIN:
connection.loginfo(plugin, 'could not find a address for ' + host +
'. Disconnecting.');
next(DENYDISCONNECT, 'Sorry we could not find address for ' +
host + '. ' + nxdomain);
break;
default:
connection.loginfo(plugin, 'encountered an error when looking up ' +
host + '. Disconnecting.');
next(DENYDISCONNECT, 'Sorry we encountered an error when ' +
'looking up ' + host + '. ' + dnserror);
break;
}
}
function _in_whitelist(connection, plugin, address) {
var domain = address.toLowerCase();
var host_list =
plugin.config.get('lookup_rdns.strict.whitelist', 'list');
var host_list_regex =
plugin.config.get('lookup_rdns.strict.whitelist_regex', 'list');
connection.logdebug(plugin, "Checking if " + address + " is in the " +
"lookup_rdns.strict.whitelist files");
var i;
for (i in host_list) {
connection.logdebug(plugin, "checking " + domain + " against " + host_list[i]);
if (host_list[i].toLowerCase() === domain) {
connection.logdebug(plugin, "Allowing " + domain);
return 1;
}
}
if (host_list_regex.length) {
var regex = new RegExp ('^(?:' + host_list_regex.join('|') + ')$', 'i');
connection.logdebug(plugin, "checking " + domain + " against " + regex.source);
if (domain.match(regex)) {
connection.logdebug(plugin, "Allowing " + domain);
return 1;
}
}
return 0;
}
exports.hook_lookup_rdns = function (next, connection) {
var plugin = this;
var total_checks = 0;
var called_next = 0;
var timeout_id = 0;
var config = this.config.get('lookup_rdns.strict.ini');
var rdns = '';
var fwd_nxdomain = config.forward && (config.forward['nxdomain'] || '');
var fwd_dnserror = config.forward && (config.forward['dnserror'] || '');
var rev_nxdomain = config.reverse && (config.reverse['nxdomain'] || '');
var rev_dnserror = config.reverse && (config.reverse['dnserror'] || '');
var nomatch = config.general && (config.general['nomatch'] || '');
var timeout = config.general && (config.general['timeout'] || 60);
var timeout_msg = config.general && (config.general['timeout_msg'] || '');
if (_in_whitelist(connection, plugin, connection.remote_ip)) {
called_next++;
return next(OK, connection.remote_ip);
}
timeout_id = setTimeout(function () {
if (!called_next) {
connection.loginfo(plugin, 'timed out when looking up ' +
connection.remote_ip + '. Disconnecting.');
called_next++;
next(DENYDISCONNECT, '[' + connection.remote_ip + '] ' +
timeout_msg);
}
}, timeout * 1000);
dns.reverse(connection.remote_ip, function (err, domains) {
if (err) {
if (!called_next) {
called_next++;
clearTimeout(timeout_id);
connection.auth_results("iprev=permerror");
_dns_error(connection, next, err, connection.remote_ip, plugin,
rev_nxdomain, rev_dnserror);
}
} else {
// Anything this strange needs documentation. Since we are
// checking M (A) addresses for N (PTR) records, we need to
// keep track of our total progress. That way, at the end,
// we know to send an error of nothing has been found. Also,
// on err, this helps us figure out if we still have more to check.
total_checks = domains.length;
// Check whitelist before we start doing a bunch more DNS queries.
for(var i = 0; i < domains.length; i++) {
if (_in_whitelist(connection, plugin, domains[i])) {
called_next++;
clearTimeout(timeout_id);
return next(OK, domains[i]);
}
}
// Now we should make sure that the reverse response matches
// the forward address. Almost no one will have more than one
// PTR record for a domain, however, DNS protocol does not
// restrict one from having multiple PTR records for the same
// address. So here we are, dealing with that case.
domains.forEach(function (rdns) {
dns.resolve4(rdns, function (err, addresses) {
total_checks--;
if (err) {
if (!called_next && !total_checks) {
called_next++;
clearTimeout(timeout_id);
connection.auth_results("iprev=fail");
_dns_error(connection, next, err, rdns, plugin,
fwd_nxdomain, fwd_dnserror);
}
} else {
for (var i = 0; i < addresses.length ; i++) {
if (addresses[i] === connection.remote_ip) {
// We found a match, call next() and return
if (!called_next) {
called_next++;
clearTimeout(timeout_id);
connection.auth_results("iprev=pass");
return next(OK, rdns);
}
}
}
if (!called_next && !total_checks) {
called_next++;
clearTimeout(timeout_id);
next(DENYDISCONNECT, rdns + ' [' +
connection.remote_ip + '] ' + nomatch);
}
}
});
});
}
});
};
| danucalovj/Haraka | plugins/lookup_rdns.strict.js | JavaScript | mit | 6,842 |
export * from './todo-item.interface';
| tarlepp/angular2-firebase-material-demo | src/app/todos/interfaces/index.ts | TypeScript | mit | 39 |
// ***********************************************************************
// Copyright (c) 2017 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
namespace NUnit.Framework.Internal.Commands
{
/// <summary>
/// EmptyTestCommand is a TestCommand that does nothing. It simply
/// returns the current result from the context when executed. We
/// use it to avoid testing for null when executing a chain of
/// DelegatingTestCommands.
/// </summary>
public class EmptyTestCommand : TestCommand
{
/// <summary>
/// Construct a NullCommand for a test
/// </summary>
public EmptyTestCommand(Test test) : base(test) { }
/// <summary>
/// Execute the command
/// </summary>
public override TestResult Execute(TestExecutionContext context)
{
return context.CurrentResult;
}
}
}
| Suremaker/nunit | src/NUnitFramework/framework/Internal/Commands/EmptyTestCommand.cs | C# | mit | 2,035 |
'use strict';
/**
* Module for all communication with LB
*/
define((require) => {
const Util = require('util/util');
const BaseScrobbler = require('scrobbler/base-scrobbler');
const ServiceCallResult = require('object/service-call-result');
const listenBrainzTokenPage = 'https://listenbrainz.org/profile/';
const apiUrl = 'https://api.listenbrainz.org/1/submit-listens';
class ListenBrainz extends BaseScrobbler {
/** @override */
async getAuthUrl() {
const data = await this.storage.get();
data.isAuthStarted = true;
delete data.sessionID;
delete data.sessionName;
await this.storage.set(data);
return 'https://listenbrainz.org/login/musicbrainz?next=%2Fprofile%2F';
}
/** @override */
getBaseProfileUrl() {
return 'https://listenbrainz.org/user/';
}
/** @override */
getId() {
return 'listenbrainz';
}
/** @override */
getLabel() {
return 'ListenBrainz';
}
/** @override */
async getProfileUrl() {
if (this.userToken) {
return null;
}
return super.getProfileUrl();
}
/** @override */
getStatusUrl() {
if (this.userToken) {
return null;
}
return 'https://listenbrainz.org/current-status';
}
/** @override */
getStorageName() {
return 'ListenBrainz';
}
/** @override */
getUsedDefinedProperties() {
return ['userApiUrl', 'userToken'];
}
/** @override */
async signOut() {
if (this.userApiUrl || this.userToken) {
await this.applyUserProperties({
userApiUrl: null,
userToken: null,
});
}
await super.signOut();
}
/** @override */
async getSession() {
if (this.userToken) {
return { sessionID: this.userToken };
}
const data = await this.storage.get();
if (data.isAuthStarted) {
let session = {};
try {
session = await this.requestSession();
} catch (err) {
this.debugLog('Failed to get session', 'warn');
await this.signOut();
throw ServiceCallResult.ERROR_AUTH;
}
data.sessionID = session.sessionID;
data.sessionName = session.sessionName;
delete data.isAuthStarted;
await this.storage.set(data);
return session;
} else if (!data.sessionID) {
throw ServiceCallResult.ERROR_AUTH;
}
return {
sessionID: data.sessionID,
sessionName: data.sessionName,
};
}
/** @override */
async isReadyForGrantAccess() {
if (this.userToken) {
return false;
}
const data = await this.storage.get();
return data.isAuthStarted;
}
/** @override */
async sendNowPlaying(song) {
const { sessionID } = await this.getSession();
const trackMeta = this.makeTrackMetadata(song);
const params = {
listen_type: 'playing_now',
payload: [
{
track_metadata: trackMeta,
},
],
};
return this.sendRequest(params, sessionID);
}
/** @override */
async scrobble(song) {
const { sessionID } = await this.getSession();
const params = {
listen_type: 'single',
payload: [
{
listened_at: song.metadata.startTimestamp,
track_metadata: this.makeTrackMetadata(song),
},
],
};
return this.sendRequest(params, sessionID);
}
/** Private methods. */
async sendRequest(params, sessionID) {
const requestInfo = {
method: 'POST',
headers: {
Authorization: `Token ${sessionID}`,
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(params),
};
const promise = fetch(this.userApiUrl || apiUrl, requestInfo);
const timeout = BaseScrobbler.REQUEST_TIMEOUT;
let result = null;
let response = null;
try {
response = await Util.timeoutPromise(timeout, promise);
result = await response.json();
} catch (e) {
this.debugLog('Error while sending request', 'error');
throw ServiceCallResult.ERROR_OTHER;
}
switch (response.status) {
case 400:
this.debugLog('Invalid JSON sent', 'error');
throw ServiceCallResult.ERROR_AUTH;
case 401:
this.debugLog('Invalid Authorization sent', 'error');
throw ServiceCallResult.ERROR_AUTH;
}
this.debugLog(JSON.stringify(result, null, 2));
return this.processResult(result);
}
async requestSession() {
const authUrls = [listenBrainzTokenPage, this.authUrl];
let session = null;
for (const url of authUrls) {
try {
session = await this.fetchSession(url);
} catch (e) {
this.debugLog('request session timeout', 'warn');
continue;
}
if (session) {
break;
}
}
if (session) {
const safeId = Util.hideObjectValue(session.sessionID);
this.debugLog(`Session ID: ${safeId}`);
return session;
}
throw ServiceCallResult.ERROR_AUTH;
}
async fetchSession(url) {
this.debugLog(`Use ${url}`);
// NOTE: Use 'same-origin' credentials to fix login on Firefox ESR 60.
const promise = fetch(url, {
method: 'GET',
credentials: 'same-origin',
});
const timeout = BaseScrobbler.REQUEST_TIMEOUT;
const response = await Util.timeoutPromise(timeout, promise);
if (response.ok) {
const parser = new DOMParser();
const rawHtml = await response.text();
const doc = parser.parseFromString(rawHtml, 'text/html');
let sessionName = null;
let sessionID = null;
const sessionNameEl = doc.querySelector('.page-title');
const sessionIdEl = doc.querySelector('#auth-token');
if (sessionNameEl) {
sessionName = sessionNameEl.textContent;
}
if (sessionIdEl) {
sessionID = sessionIdEl.getAttribute('value');
}
if (sessionID && sessionName) {
return { sessionID, sessionName };
}
}
return null;
}
processResult(result) {
if (result.status !== 'ok') {
return ServiceCallResult.ERROR_OTHER;
}
return ServiceCallResult.RESULT_OK;
}
makeTrackMetadata(song) {
const trackMeta = {
artist_name: song.getArtist(),
track_name: song.getTrack(),
additional_info: {},
};
if (song.getAlbum()) {
trackMeta.release_name = song.getAlbum();
}
if (song.getOriginUrl()) {
trackMeta.additional_info.origin_url = song.getOriginUrl();
}
if (song.getAlbumArtist()) {
trackMeta.additional_info.release_artist_name = song.getAlbumArtist();
}
return trackMeta;
}
}
return ListenBrainz;
});
| galeksandrp/web-scrobbler | src/core/background/scrobbler/listenbrainz-scrobbler.js | JavaScript | mit | 6,314 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
/** @typedef {import("../MainTemplate")} MainTemplate */
class StartupEntrypointRuntimeModule extends RuntimeModule {
constructor(asyncChunkLoading) {
super("startup entrypoint");
this.asyncChunkLoading = asyncChunkLoading;
}
/**
* @returns {string} runtime code
*/
generate() {
const { compilation } = this;
const { runtimeTemplate } = compilation;
return `${
RuntimeGlobals.startupEntrypoint
} = ${runtimeTemplate.basicFunction(
"chunkIds, moduleId",
this.asyncChunkLoading
? `return Promise.all(chunkIds.map(${
RuntimeGlobals.ensureChunk
}, __webpack_require__)).then(${runtimeTemplate.returningFunction(
"__webpack_require__(moduleId)"
)})`
: [
`chunkIds.map(${RuntimeGlobals.ensureChunk}, __webpack_require__)`,
"return __webpack_require__(moduleId)"
]
)}`;
}
}
module.exports = StartupEntrypointRuntimeModule;
| arvenil/resume | node_modules/webpack/lib/runtime/StartupEntrypointRuntimeModule.js | JavaScript | mit | 1,092 |
using System;
using System.Linq;
using Dealership.CommandHandlers.Base;
using Dealership.Common.Enums;
using Dealership.Engine;
using Dealership.Factories;
namespace Dealership.CommandHandlers
{
public class RegisterUserCommandHandler : BaseCommandHandler
{
private const string CanHandleCommandName = "RegisterUser";
private const string UserAlreadyExist = "User {0} already exist. Choose a different username!";
private const string UserLoggedInAlready = "User {0} is logged in! Please log out first!";
private const string UserRegisterеd = "User {0} registered successfully!";
private readonly IDealershipFactory factory;
public RegisterUserCommandHandler(IDealershipFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
this.factory = factory;
}
protected override bool CanHandle(ICommand command)
{
return command.Name == RegisterUserCommandHandler.CanHandleCommandName;
}
protected override string Handle(ICommand command, IEngine engine)
{
var username = command.Parameters[0];
var firstName = command.Parameters[1];
var lastName = command.Parameters[2];
var password = command.Parameters[3];
var role = Role.Normal;
if (command.Parameters.Count > 4)
{
role = (Role)Enum.Parse(typeof(Role), command.Parameters[4]);
}
if (engine.LoggedUser != null)
{
return string.Format(RegisterUserCommandHandler.UserLoggedInAlready, engine.LoggedUser.Username);
}
if (engine.Users.Any(u => u.Username.ToLower() == username.ToLower()))
{
return string.Format(RegisterUserCommandHandler.UserAlreadyExist, username);
}
var user = this.factory.CreateUser(username, firstName, lastName, password, role.ToString());
engine.SetLoggedUser(user);
engine.Users.Add(user);
return string.Format(RegisterUserCommandHandler.UserRegisterеd, username);
}
}
}
| owolp/Telerik-Academy | Module-2/Design-Patterns/Materials/Dealership-AuthorSolution/Dealership/CommandHandlers/RegisterUserCommandHandler.cs | C# | mit | 2,258 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.UseCoalesceExpression
{
internal abstract class AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TConditionalExpressionSyntax,
TBinaryExpressionSyntax,
TMemberAccessExpression,
TPrefixUnaryExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TConditionalExpressionSyntax : TExpressionSyntax
where TBinaryExpressionSyntax : TExpressionSyntax
where TMemberAccessExpression : TExpressionSyntax
where TPrefixUnaryExpressionSyntax : TExpressionSyntax
{
protected AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId,
CodeStyleOptions2.PreferCoalesceExpression,
new LocalizableResourceString(nameof(AnalyzersResources.Use_coalesce_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected abstract ISyntaxFacts GetSyntaxFacts();
protected override void InitializeWorker(AnalysisContext context)
{
var syntaxKinds = GetSyntaxFacts().SyntaxKinds;
context.RegisterSyntaxNodeAction(AnalyzeSyntax,
syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.TernaryConditionalExpression));
}
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var conditionalExpression = (TConditionalExpressionSyntax)context.Node;
var cancellationToken = context.CancellationToken;
var option = context.GetOption(CodeStyleOptions2.PreferCoalesceExpression, conditionalExpression.Language);
if (!option.Value)
{
return;
}
var syntaxFacts = GetSyntaxFacts();
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var conditionNode, out var whenTrueNodeHigh, out var whenFalseNodeHigh);
conditionNode = syntaxFacts.WalkDownParentheses(conditionNode);
var whenTrueNodeLow = syntaxFacts.WalkDownParentheses(whenTrueNodeHigh);
var whenFalseNodeLow = syntaxFacts.WalkDownParentheses(whenFalseNodeHigh);
var notHasValueExpression = false;
if (syntaxFacts.IsLogicalNotExpression(conditionNode))
{
notHasValueExpression = true;
conditionNode = syntaxFacts.GetOperandOfPrefixUnaryExpression(conditionNode);
}
if (!(conditionNode is TMemberAccessExpression conditionMemberAccess))
{
return;
}
syntaxFacts.GetPartsOfMemberAccessExpression(conditionMemberAccess, out var conditionExpression, out var conditionSimpleName);
syntaxFacts.GetNameAndArityOfSimpleName(conditionSimpleName, out var conditionName, out _);
if (conditionName != nameof(Nullable<int>.HasValue))
{
return;
}
var whenPartToCheck = notHasValueExpression ? whenFalseNodeLow : whenTrueNodeLow;
if (!(whenPartToCheck is TMemberAccessExpression whenPartMemberAccess))
{
return;
}
syntaxFacts.GetPartsOfMemberAccessExpression(whenPartMemberAccess, out var whenPartExpression, out var whenPartSimpleName);
syntaxFacts.GetNameAndArityOfSimpleName(whenPartSimpleName, out var whenPartName, out _);
if (whenPartName != nameof(Nullable<int>.Value))
{
return;
}
if (!syntaxFacts.AreEquivalent(conditionExpression, whenPartExpression))
{
return;
}
// Syntactically this looks like something we can simplify. Make sure we're
// actually looking at something Nullable (and not some type that uses a similar
// syntactic pattern).
var semanticModel = context.SemanticModel;
var nullableType = semanticModel.Compilation.GetTypeByMetadataName(typeof(Nullable<>).FullName!);
if (nullableType == null)
{
return;
}
var type = semanticModel.GetTypeInfo(conditionExpression, cancellationToken);
if (!nullableType.Equals(type.Type?.OriginalDefinition))
{
return;
}
var whenPartToKeep = notHasValueExpression ? whenTrueNodeHigh : whenFalseNodeHigh;
var locations = ImmutableArray.Create(
conditionalExpression.GetLocation(),
conditionExpression.GetLocation(),
whenPartToKeep.GetLocation());
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
conditionalExpression.GetLocation(),
option.Notification.Severity,
locations,
properties: null));
}
}
}
| genlu/roslyn | src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs | C# | mit | 5,692 |
module.exports=/[\u2FF2\u2FF3]/ | marclundgren/mithril-fidm-app | node_modules/gulp-jscs/node_modules/jscs/node_modules/unicode-6.3.0/properties/IDS_Trinary_Operator/regex.js | JavaScript | mit | 31 |
steal("can/view/stache/mustache_core.js", "can/view/parser",function(mustacheCore, parser){
return function(source){
var template = mustacheCore.cleanLineEndings(source);
var imports = [],
inImport = false,
inFrom = false;
var keepToken = function(){
return inImport ? false : true;
};
var intermediate = parser(template, {
start: function( tagName, unary ){
if(tagName === "can-import") {
inImport = true;
}
return keepToken();
},
end: function( tagName, unary ){
if(tagName === "can-import") {
inImport = false;
return false;
}
return keepToken();
},
attrStart: function( attrName ){
if(attrName === "from") {
inFrom = true;
}
return keepToken();
},
attrEnd: function( attrName ){
if(attrName === "from") {
inFrom = false;
}
return keepToken();
},
attrValue: function( value ){
if(inFrom && inImport) {
imports.push(value);
}
return keepToken();
},
chars: keepToken,
comment: keepToken,
special: keepToken,
done: keepToken
}, true);
return {intermediate: intermediate, imports: imports};
};
});
| beno/canjs | view/stache/intermediate_and_imports.js | JavaScript | mit | 1,176 |
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../_references.ts"/>
module powerbi.visuals {
import Color = jsCommon.color;
export interface PlayChartConstructorOptions extends CartesianVisualConstructorOptions {
isFrozen?: boolean;
}
export interface PlayChartDataPoint extends SelectableDataPoint, TooltipEnabledDataPoint, LabelEnabledDataPoint {
x: any;
y: any;
size: any;
radius: RadiusData;
fill: string;
category: string;
}
export interface PlayChartData {
xCol: DataViewMetadataColumn;
yCol: DataViewMetadataColumn;
dataPoints: PlayChartDataPoint[];
legendData: LegendData;
axesLabels: ChartAxesLabels;
size?: DataViewMetadataColumn;
sizeRange: NumberRange;
dataLabelsSettings: PointDataLabelsSettings;
defaultDataPointColor?: string;
showAllDataPoints?: boolean;
hasDynamicSeries?: boolean;
fillPoint?: boolean;
colorBorder?: boolean;
frameKeys: any[];
allDataPoints?: PlayChartDataPoint[][];
currentFrameIndex?: number;
lastRenderedFrameIndex?: number;
colorByCategory?: boolean;
currentViewport?: IViewport;
}
interface PlayChartMeasureMetadata {
idx: {
x?: number;
y?: number;
size?: number;
};
cols: {
x?: DataViewMetadataColumn;
y?: DataViewMetadataColumn;
size?: DataViewMetadataColumn;
};
axesLabels: ChartAxesLabels;
}
interface MouseCoordinates {
x: number;
y: number;
}
interface PlayObjectProperties {
defaultDataPointColor?: string;
showAllDataPoints?: boolean;
colorByCategory: boolean;
currentFrameIndex?: number;
}
export class PlayChart implements ICartesianVisual {
private static PlayChartCircleTagName = 'circle';
private static BubbleRadius = 3 * 2;
public static DefaultBubbleOpacity = 0.85;
public static DimmedBubbleOpacity = 0.3;
public static StrokeDarkenColorValue = 255 * 0.25;
// Chart Area and size range values as defined by PV charts
private static AreaOf300By300Chart = 90000;
private static MinSizeRange = 200;
private static MaxSizeRange = 3000;
private static ClassName = 'playChart';
private static MainGraphicsContextClassName = 'mainGraphicsContext';
private static DataLabelsContextClassName = 'dataLabelsContext';
private static FrameDuration = 1000;
private static FrameDurationFudge = 48; // animating the traceLine during play needs this to ensure we finish animating the line before the next frame plays
private static SliderMarginLeft = 15;
private static SliderMarginRight = 35;
private static DotClasses: ClassAndSelector = {
class: 'dot',
selector: '.dot'
};
private svg: D3.Selection;
private element: JQuery;
private mainGraphicsContext: D3.Selection;
private dataLabelsContext: D3.Selection;
private clearCatcher: D3.Selection;
private mainGraphicsG: D3.Selection;
private currentViewport: IViewport;
private lastRenderedViewport: IViewport;
private style: IVisualStyle;
private data: PlayChartData;
private dataView: DataView;
private host: IVisualHostServices;
private margin: IMargin;
private xAxisProperties: IAxisProperties;
private yAxisProperties: IAxisProperties;
private colors: IDataColorPalette;
private options: VisualInitOptions;
private interactivity: InteractivityOptions;
private cartesianVisualHost: ICartesianVisualHost;
private isInteractiveChart: boolean;
private interactivityService: IInteractivityService;
private categoryAxisProperties: DataViewObject;
private valueAxisProperties: DataViewObject;
private animator: IGenericAnimator;
private isFrozen: boolean;
private frameCount: number;
private isPlaying: boolean;
private playAxisContainer: JQuery; //contains the playButton and slider
private playButton: JQuery;
private slider: JQuery;
private callout: JQuery;
// do not call converter() when we call persistProperties and a new update() happens
// NOTE: calling persistProperties will still cause a render() call to come from cartesianChart
private ridiculousFlagForPersistProperties: boolean;
constructor(options: PlayChartConstructorOptions) {
this.isFrozen = false;
if (options) {
this.interactivityService = options.interactivityService;
this.animator = options.animator;
this.isFrozen = !!options.isFrozen;
}
}
public init(options: CartesianVisualInitOptions) {
this.options = options;
let element = this.element = options.element;
this.currentViewport = options.viewport;
this.lastRenderedViewport = {
height: this.currentViewport.height,
width: this.currentViewport.width
};
this.style = options.style;
this.host = options.host;
this.colors = this.style.colorPalette.dataColors;
this.interactivity = options.interactivity;
this.cartesianVisualHost = options.cartesianHost;
this.isInteractiveChart = options.interactivity && options.interactivity.isInteractiveLegend;
element.addClass(PlayChart.ClassName);
let svg = this.svg = options.svg;
this.clearCatcher = this.svg.select(".clearCatcher");
this.mainGraphicsG = svg.append('g')
.classed(PlayChart.MainGraphicsContextClassName, true);
this.mainGraphicsContext = this.mainGraphicsG.append('svg');
this.dataLabelsContext = this.mainGraphicsG.append('g')
.classed(PlayChart.DataLabelsContextClassName, true);
}
private static convertMatrixToCategorical(matrix: DataViewMatrix, frame: number): DataViewCategorical {
var node = matrix.rows.root.children[frame];
var categorical: DataViewCategorical = {
categories: [],
values: powerbi.data.DataViewTransform.createValueColumns()
};
let category: DataViewCategoryColumn = {
source: matrix.rows.levels[1].sources[0],
values: [],
objects: undefined,
identity: []
};
if (matrix.columns.levels.length > 1) {
categorical.values.source = matrix.columns.levels[0].sources[0];
//let leafCount = 0;
let leafOfGroup = matrix.columns.root;
while (leafOfGroup.children && leafOfGroup.children[0].children) {
leafOfGroup = leafOfGroup.children[0];
}
let nodeQueue = [];
let columnNode = matrix.columns.root;
let leafOffset = 0;
while (columnNode) {
if (columnNode.children && columnNode.children[0].children) {
for (var j = 0, jlen = columnNode.children.length; j < jlen; j++) {
nodeQueue.push(columnNode.children[j]);
}
} else if (columnNode.children) {
let columnLength = columnNode.children.length;
for (let j = 0; j < columnLength; j++) {
let source = <any>_.create(matrix.valueSources[j], { groupName: columnNode.value });
let dataViewColumn: DataViewValueColumn = {
identity: columnNode.identity,
values: [],
source: source,
value: columnNode.value,
};
categorical.values.push(dataViewColumn);
}
for (let i = 0, len = node.children.length; i < len; i++) {
let innerNode = node.children[i];
category.identity.push(innerNode.identity);
category.values.push(innerNode.value);
for (let j = 0; j < columnLength; j++) {
categorical.values[j+leafOffset].values.push(innerNode.values[j+leafOffset].value);
}
}
leafOffset += columnLength;
}
if (nodeQueue.length > 0) {
columnNode = nodeQueue[0];
nodeQueue = nodeQueue.splice(1);
} else
columnNode = undefined;
}
} else {
let columnLength = matrix.columns.root.children.length;
for (let j = 0; j < columnLength; j++) {
let dataViewColumn: DataViewValueColumn = {
identity: undefined,
values: [],
source: matrix.valueSources[j]
};
categorical.values.push(dataViewColumn);
}
for (let i = 0, len = node.children.length; i < len; i++) {
let innerNode = node.children[i];
category.identity.push(innerNode.identity);
category.values.push(innerNode.value);
// v1, no series.
for (let j = 0; j < columnLength; j++) {
categorical.values[j].values.push(innerNode.values[j].value);
}
}
}
categorical.categories.push(category);
return categorical;
}
private static getObjectProperties(dataViewMetadata: DataViewMetadata, dataLabelsSettings?: PointDataLabelsSettings): PlayObjectProperties {
let objectProperties: PlayObjectProperties = {
colorByCategory: true, //default to true
};
if (dataViewMetadata && dataViewMetadata.objects) {
var objects = dataViewMetadata.objects;
objectProperties.defaultDataPointColor = DataViewObjects.getFillColor(objects, columnChartProps.dataPoint.defaultColor);
objectProperties.showAllDataPoints = DataViewObjects.getValue<boolean>(objects, columnChartProps.dataPoint.showAllDataPoints);
var labelsObj = objects['categoryLabels'];
if (labelsObj && dataLabelsSettings) {
dataLabelsSettings.show = (labelsObj['show'] !== undefined) ? <boolean>labelsObj['show'] : dataLabelsSettings.show;
dataLabelsSettings.precision = (labelsObj['labelsPrecision'] !== undefined) ? +<string>labelsObj['labelsPrecision'] : dataLabelsSettings.precision;
if (labelsObj['color'] !== undefined) {
dataLabelsSettings.labelColor = (<Fill>labelsObj['color']).solid.color;
}
}
var generalObj = objects['general'];
if (generalObj) {
if (generalObj['colorByCategory'] != null)
objectProperties.colorByCategory = !!generalObj['colorByCategory'];
if (generalObj['frozenIndex'] != null)
objectProperties.currentFrameIndex = <number>generalObj['frozenIndex'];
}
}
return objectProperties;
}
public static converter(dataView: DataView, currentViewport: IViewport, colorPalette: IDataColorPalette, interactivityService?: IInteractivityService, categoryAxisProperties?: DataViewObject, valueAxisProperties?: DataViewObject): PlayChartData {
var categoryValues: any[],
categoryFormatter: IValueFormatter,
categoryObjects: DataViewObjects[],
categoryIdentities: DataViewScopeIdentity[];
let dataViewCategorical: DataViewCategorical = dataView.categorical;
if (!dataViewCategorical && dataView.matrix) {
dataViewCategorical = PlayChart.convertMatrixToCategorical(dataView.matrix, dataView.matrix.rows.root.children.length - 1);
}
let dataViewMetadata: DataViewMetadata = dataView.metadata;
if (dataViewCategorical.categories && dataViewCategorical.categories.length > 0) {
categoryValues = dataViewCategorical.categories[0].values;
categoryFormatter = valueFormatter.create({ format: valueFormatter.getFormatString(dataViewCategorical.categories[0].source, playChartProps.general.formatString), value: categoryValues[0], value2: categoryValues[categoryValues.length - 1] });
categoryIdentities = dataViewCategorical.categories[0].identity;
categoryObjects = dataViewCategorical.categories[0].objects;
}
else {
categoryValues = [null];
// creating default formatter for null value (to get the right string of empty value from the locale)
categoryFormatter = valueFormatter.createDefaultFormatter(null);
}
let categories = dataViewCategorical.categories;
let dataValues = dataViewCategorical.values;
if (!dataValues)
return;
let hasDynamicSeries = !!dataValues.source;
let grouped = dataValues.grouped();
let dvSource = dataValues.source;
let playMetadata = PlayChart.getMetadata(grouped, dvSource);
let dataLabelsSettings = dataLabelUtils.getDefaultPointLabelSettings();
let objectProperties = PlayChart.getObjectProperties(dataViewMetadata, dataLabelsSettings);
let allDataPoints = [];
let frameKeys = [];
let dataPoints = undefined;
let rowChildrenLength = dataView.matrix.rows.root.children.length;
if (!dataView.categorical && dataView.matrix && rowChildrenLength > 0) {
let keySourceColumn = dataView.matrix.rows.levels[0].sources[0];
let keyFormatter = valueFormatter.create({
format: valueFormatter.getFormatString(keySourceColumn, playChartProps.general.formatString),
value: dataView.matrix.rows.root.children[0],
value2: dataView.matrix.rows.root.children[rowChildrenLength-1],
});
for (let i = 0, len = rowChildrenLength; i < len; i++) {
var key = dataView.matrix.rows.root.children[i];
frameKeys.push(keyFormatter.format(key.value));
dataViewCategorical = PlayChart.convertMatrixToCategorical(dataView.matrix, i);
categoryValues = dataViewCategorical.categories[0].values;
categoryFormatter = valueFormatter.create({
format: valueFormatter.getFormatString(dataViewCategorical.categories[0].source, playChartProps.general.formatString),
value: categoryValues[0],
value2: categoryValues[categoryValues.length - 1],
});
categoryIdentities = dataViewCategorical.categories[0].identity;
categoryObjects = dataViewCategorical.categories[0].objects;
categories = dataViewCategorical.categories;
dataValues = dataViewCategorical.values;
dataPoints = PlayChart.createDataPoints(
dataValues,
playMetadata,
categories,
categoryValues,
categoryFormatter,
categoryIdentities,
categoryObjects,
colorPalette,
currentViewport,
hasDynamicSeries,
dataLabelsSettings,
objectProperties.defaultDataPointColor,
objectProperties.colorByCategory);
allDataPoints.push(dataPoints);
}
}
else {
dataPoints = PlayChart.createDataPoints(
dataValues,
playMetadata,
categories,
categoryValues,
categoryFormatter,
categoryIdentities,
categoryObjects,
colorPalette,
currentViewport,
hasDynamicSeries,
dataLabelsSettings,
objectProperties.defaultDataPointColor,
objectProperties.colorByCategory);
}
// use the saved frame index, or default to the last frame
if (objectProperties.currentFrameIndex == null) {
objectProperties.currentFrameIndex = frameKeys.length - 1; //default
// current dataPoints is already the last frame
}
else if (objectProperties.currentFrameIndex < frameKeys.length) {
dataPoints = allDataPoints[objectProperties.currentFrameIndex];
}
if (interactivityService) {
interactivityService.applySelectionStateToData(dataPoints);
}
let legendItems = hasDynamicSeries
? PlayChart.createSeriesLegend(dataValues, colorPalette, dataValues,
valueFormatter.getFormatString(dvSource, playChartProps.general.formatString),
objectProperties.defaultDataPointColor)
: [];
let legendTitle = dataValues && dvSource ? dvSource.displayName : "";
if (!legendTitle) {
legendTitle = categories && categories[0].source.displayName ? categories[0].source.displayName : "";
}
let legendData = { title: legendTitle, dataPoints: legendItems };
let sizeRange = PlayChart.getSizeRangeForGroups(grouped, playMetadata.idx.size);
if (categoryAxisProperties && categoryAxisProperties["showAxisTitle"] !== null && categoryAxisProperties["showAxisTitle"] === false) {
playMetadata.axesLabels.x = null;
}
if (valueAxisProperties && valueAxisProperties["showAxisTitle"] !== null && valueAxisProperties["showAxisTitle"] === false) {
playMetadata.axesLabels.y = null;
}
return {
xCol: playMetadata.cols.x,
yCol: playMetadata.cols.y,
dataPoints: dataPoints,
legendData: legendData,
axesLabels: playMetadata.axesLabels,
hasSelection: false,
selectedIds: [],
size: playMetadata.cols.size,
sizeRange: sizeRange,
dataLabelsSettings: dataLabelsSettings,
defaultDataPointColor: objectProperties.defaultDataPointColor,
hasDynamicSeries: hasDynamicSeries,
showAllDataPoints: objectProperties.showAllDataPoints,
allDataPoints: allDataPoints,
frameKeys: frameKeys,
colorByCategory: objectProperties.colorByCategory,
currentFrameIndex: objectProperties.currentFrameIndex,
};
}
private static getSizeRangeForGroups(
dataViewValueGroups: DataViewValueColumnGroup[],
sizeColumnIndex: number): NumberRange {
let result: NumberRange = {};
if (dataViewValueGroups) {
dataViewValueGroups.forEach((group) => {
let sizeColumn = PlayChart.getMeasureValue(sizeColumnIndex, group.values);
let currentRange: NumberRange = AxisHelper.getRangeForColumn(sizeColumn);
if (result.min == null || result.min > currentRange.min) {
result.min = currentRange.min;
}
if (result.max == null || result.max < currentRange.max) {
result.max = currentRange.max;
}
});
}
return result;
}
private static createDataPoints(
dataValues: DataViewValueColumns,
metadata: PlayChartMeasureMetadata,
categories: DataViewCategoryColumn[],
categoryValues: any[],
categoryFormatter: IValueFormatter,
categoryIdentities: DataViewScopeIdentity[],
categoryObjects: DataViewObjects[],
colorPalette: IDataColorPalette,
viewport: IViewport,
hasDynamicSeries: boolean,
labelSettings: PointDataLabelsSettings,
defaultDataPointColor?: string,
colorByCategory?: boolean): PlayChartDataPoint[]{
let dataPoints: PlayChartDataPoint[] = [],
indicies = metadata.idx,
formatStringProp = playChartProps.general.formatString,
dataValueSource = dataValues.source,
grouped = dataValues.grouped();
let colorHelper = new ColorHelper(colorPalette, playChartProps.dataPoint.fill, defaultDataPointColor);
for (let categoryIdx = 0, ilen = categoryValues.length; categoryIdx < ilen; categoryIdx++) {
let categoryValue = categoryValues[categoryIdx];
for (let seriesIdx = 0, len = grouped.length; seriesIdx < len; seriesIdx++) {
let grouping = grouped[seriesIdx];
let seriesValues = grouping.values;
let measureX = PlayChart.getMeasureValue(indicies.x, seriesValues);
let measureY = PlayChart.getMeasureValue(indicies.y, seriesValues);
let measureSize = PlayChart.getMeasureValue(indicies.size, seriesValues);
let xVal = measureX && measureX.values ? measureX.values[categoryIdx] : null;
let yVal = measureY && measureY.values ? measureY.values[categoryIdx] : 0;
let size = measureSize && measureSize.values ? measureSize.values[categoryIdx] : null;
let hasNullValue = (xVal == null) || (yVal == null);
if (hasNullValue)
continue;
let color: string;
if (hasDynamicSeries) {
color = colorHelper.getColorForSeriesValue(grouping.objects, dataValues.identityFields, grouping.name);
}
else if (colorByCategory) {
color = colorHelper.getColorForSeriesValue(categoryObjects && categoryObjects[categoryIdx], dataValues.identityFields, categoryValue);
}
else {
// If we have no Size measure then use a blank query name
let measureSource = (measureSize != null)
? measureSize.source.queryName
: '';
color = colorHelper.getColorForMeasure(categoryObjects && categoryObjects[categoryIdx], measureSource);
}
let category = categories && categories.length > 0 ? categories[0] : null;
let identity = SelectionIdBuilder.builder()
.withCategory(category, categoryIdx)
.withSeries(dataValues, grouping)
.createSelectionId();
let seriesData: TooltipSeriesDataItem[] = [];
if (dataValueSource) {
// Dynamic series
seriesData.push({ value: grouping.name, metadata: { source: dataValueSource, values: [] } });
}
if (measureX) {
seriesData.push({ value: xVal, metadata: measureX });
}
if (measureY) {
seriesData.push({ value: yVal, metadata: measureY });
}
if (measureSize && measureSize.values && measureSize.values.length > 0) {
seriesData.push({ value: measureSize.values[categoryIdx], metadata: measureSize });
}
let tooltipInfo: TooltipDataItem[] = TooltipBuilder.createTooltipInfo(formatStringProp, null, categoryValue, null, categories, seriesData);
let dataPoint: PlayChartDataPoint = {
x: xVal,
y: yVal,
size: size,
radius: { sizeMeasure: measureSize, index: categoryIdx },
fill: color,
category: categoryFormatter.format(categoryValue),
selected: false,
identity: identity,
tooltipInfo: tooltipInfo,
labelFill: labelSettings.labelColor,
};
dataPoints.push(dataPoint);
}
}
// TODO: is it more efficient to calculate min/max for the frame here and pass back {dp, min, max}?
return dataPoints;
}
private static createSeriesLegend(
dataValues: DataViewValueColumns,
colorPalette: IDataColorPalette,
categorical: DataViewValueColumns,
formatString: string,
defaultDataPointColor: string): LegendDataPoint[] {
let grouped = dataValues.grouped();
let colorHelper = new ColorHelper(colorPalette, playChartProps.dataPoint.fill, defaultDataPointColor);
let legendItems: LegendDataPoint[] = [];
for (let i = 0, len = grouped.length; i < len; i++) {
let grouping = grouped[i];
let color = colorHelper.getColorForSeriesValue(grouping.objects, dataValues.identityFields, grouping.name);
legendItems.push({
color: color,
icon: LegendIcon.Circle,
label: valueFormatter.format(grouping.name, formatString),
identity: grouping.identity ? SelectionId.createWithId(grouping.identity) : SelectionId.createNull(),
selected: false,
});
}
return legendItems;
}
public static getBubbleRadius(radiusData: RadiusData, sizeRange: NumberRange, viewPort: IViewport): number {
let actualSizeDataRange = null;
let bubblePixelAreaSizeRange = null;
let measureSize = radiusData.sizeMeasure;
if (!measureSize)
return PlayChart.BubbleRadius;
let minSize = sizeRange.min ? sizeRange.min : 0;
let maxSize = sizeRange.max ? sizeRange.max : 0;
let min = Math.min(minSize, 0);
let max = Math.max(maxSize, 0);
actualSizeDataRange = {
minRange: min,
maxRange: max,
delta: max - min
};
bubblePixelAreaSizeRange = PlayChart.getBubblePixelAreaSizeRange(viewPort, PlayChart.MinSizeRange, PlayChart.MaxSizeRange);
if (measureSize.values) {
let sizeValue = measureSize.values[radiusData.index];
if (sizeValue != null) {
return PlayChart.projectSizeToPixels(sizeValue, actualSizeDataRange, bubblePixelAreaSizeRange) / 2;
}
}
return PlayChart.BubbleRadius;
}
public static getMeasureValue(measureIndex: number, seriesValues: DataViewValueColumn[]): DataViewValueColumn {
if (measureIndex >= 0)
return seriesValues[measureIndex];
return null;
}
private static getMetadata(grouped: DataViewValueColumnGroup[], source: DataViewMetadataColumn): PlayChartMeasureMetadata {
let xIndex = DataRoleHelper.getMeasureIndexOfRole(grouped, 'X');
let yIndex = DataRoleHelper.getMeasureIndexOfRole(grouped, 'Y');
let sizeIndex = DataRoleHelper.getMeasureIndexOfRole(grouped, 'Size');
let xCol: DataViewMetadataColumn;
let yCol: DataViewMetadataColumn;
let sizeCol: DataViewMetadataColumn;
let xAxisLabel = "";
let yAxisLabel = "";
if (grouped && grouped.length) {
let firstGroup = grouped[0],
measureCount = firstGroup.values.length;
if (!(xIndex >= 0))
xIndex = PlayChart.getDefaultMeasureIndex(measureCount, yIndex, sizeIndex);
if (!(yIndex >= 0))
yIndex = PlayChart.getDefaultMeasureIndex(measureCount, xIndex, sizeIndex);
if (!(sizeIndex >= 0))
sizeIndex = PlayChart.getDefaultMeasureIndex(measureCount, xIndex, yIndex);
if (xIndex >= 0) {
xCol = firstGroup.values[xIndex].source;
xAxisLabel = firstGroup.values[xIndex].source.displayName;
}
if (yIndex >= 0) {
yCol = firstGroup.values[yIndex].source;
yAxisLabel = firstGroup.values[yIndex].source.displayName;
}
if (sizeIndex >= 0) {
sizeCol = firstGroup.values[sizeIndex].source;
}
}
return {
idx: {
x: xIndex,
y: yIndex,
size: sizeIndex,
},
cols: {
x: xCol,
y: yCol,
size: sizeCol,
},
axesLabels: {
x: xAxisLabel,
y: yAxisLabel
}
};
}
private static getDefaultMeasureIndex(count: number, usedIndex: number, usedIndex2: number): number {
for (let i = 0; i < count; i++) {
if (i !== usedIndex && i !== usedIndex2)
return i;
}
}
public setData(dataViews: DataView[]) {
let defaultData = {
xCol: undefined,
yCol: undefined,
dataPoints: [],
legendData: { dataPoints: [] },
axesLabels: { x: '', y: '' },
selectedIds: [],
sizeRange: [],
dataLabelsSettings: dataLabelUtils.getDefaultPointLabelSettings(),
defaultDataPointColor: null,
hasDynamicSeries: false,
frameKeys: [],
};
if (dataViews.length > 0 && dataViews[0] != null) {
let dataView = dataViews[0];
this.categoryAxisProperties = CartesianHelper.getCategoryAxisProperties(dataView.metadata, true);
this.valueAxisProperties = CartesianHelper.getValueAxisProperties(dataView.metadata, true);
this.dataView = dataView;
if (this.ridiculousFlagForPersistProperties && dataView.metadata) {
let objectProps = PlayChart.getObjectProperties(dataView.metadata);
// only copy frameIndex since it is the only property using persistProperties
if (this.data) {
this.data.currentFrameIndex = objectProps.currentFrameIndex;
}
// turn off the flag that was set by our persistProperties call
this.ridiculousFlagForPersistProperties = false;
}
else if (dataView.matrix || dataView.categorical) {
let data = PlayChart.converter(dataView, this.currentViewport, this.colors, this.interactivityService, this.categoryAxisProperties, this.valueAxisProperties);
if (data) {
this.data = data;
if (this.interactivityService && this.data.dataPoints) {
this.interactivityService.applySelectionStateToData(this.data.dataPoints);
}
}
else
this.data = defaultData;
}
else
this.data = defaultData;
}
else {
this.data = defaultData;
}
}
public calculateLegend(): LegendData {
return this.data.legendData;
}
public hasLegend(): boolean {
return this.data && this.data.hasDynamicSeries;
}
public enumerateObjectInstances(enumeration: ObjectEnumerationBuilder, options: EnumerateVisualObjectInstancesOptions): void {
switch (options.objectName) {
case 'general':
enumeration.pushInstance({
selector: null,
properties: {
colorByCategory: this.data ? this.data.colorByCategory : true,
},
objectName: 'general'
});
break;
// NOT WORKING RIGHT NOW
case 'dataPoint - butNotWorkingAndLeavingHereForTSLINT':
let categoricalDataView: DataViewCategorical = this.dataView && this.dataView.categorical ? this.dataView.categorical : null;
if (!GradientUtils.hasGradientRole(categoricalDataView))
return this.enumerateDataPoints(enumeration);
break;
case 'categoryAxis':
enumeration.pushInstance({
selector: null,
properties: {
showAxisTitle: !this.categoryAxisProperties || this.categoryAxisProperties["showAxisTitle"] == null ? true : this.categoryAxisProperties["showAxisTitle"]
},
objectName: 'categoryAxis'
});
break;
case 'valueAxis':
enumeration.pushInstance({
selector: null,
properties: {
showAxisTitle: !this.valueAxisProperties || this.valueAxisProperties["showAxisTitle"] == null ? true : this.valueAxisProperties["showAxisTitle"]
},
objectName: 'valueAxis'
});
break;
case 'categoryLabels':
if (this.data)
dataLabelUtils.enumerateCategoryLabels(enumeration, this.data.dataLabelsSettings, true);
else
dataLabelUtils.enumerateCategoryLabels(enumeration, null, true);
break;
case 'fillPoint':
// Check if the card should be shown or not based on the existance of size measure
if (this.hasSizeMeasure())
return;
enumeration.pushInstance({
objectName: 'fillPoint',
selector: null,
properties: {
show: this.data.fillPoint,
},
});
break;
case 'colorBorder':
// Check if the card should be shown or not based on the existance of size measure
if (this.hasSizeMeasure())
enumeration.pushInstance({
objectName: 'colorBorder',
selector: null,
properties: {
show: this.data.colorBorder,
},
});
break;
}
}
private hasSizeMeasure(): boolean {
let sizeRange = this.data.sizeRange;
return sizeRange && sizeRange.min !== undefined;
}
private enumerateDataPoints(enumeration: ObjectEnumerationBuilder): void {
let data = this.data;
if (!data)
return;
let seriesCount = data.dataPoints.length;
if (!data.hasDynamicSeries) {
// Add default color and show all slices
enumeration.pushInstance({
objectName: 'dataPoint',
selector: null,
properties: {
defaultColor: { solid: { color: data.defaultDataPointColor || this.colors.getColorByIndex(0).value } },
}
}).pushInstance({
objectName: 'dataPoint',
selector: null,
properties: {
showAllDataPoints: !!data.showAllDataPoints
}
});
for (let i = 0; i < seriesCount; i++) {
let seriesDataPoints = data.dataPoints[i];
enumeration.pushInstance({
objectName: 'dataPoint',
displayName: seriesDataPoints.category,
selector: ColorHelper.normalizeSelector(seriesDataPoints.identity.getSelector(), /*isSingleSeries*/ true),
properties: {
fill: { solid: { color: seriesDataPoints.fill } }
},
});
}
}
else {
let legendDataPointLength = data.legendData.dataPoints.length;
for (let i = 0; i < legendDataPointLength; i++) {
let series = data.legendData.dataPoints[i];
enumeration.pushInstance({
objectName: 'dataPoint',
displayName: series.label,
selector: ColorHelper.normalizeSelector(series.identity.getSelector()),
properties: {
fill: { solid: { color: series.color } },
},
});
}
}
}
public calculateAxesProperties(options: CalculateScaleAndDomainOptions): IAxisProperties[] {
let data = this.data;
let dataPoints = data.dataPoints;
let viewport = this.currentViewport = options.viewport;
let margin = options.margin;
this.currentViewport = viewport;
this.margin = margin;
if (this.data) {
this.data.currentViewport = {
height: viewport.height,
width: viewport.width
};
}
let width = viewport.width - (margin.left + margin.right);
let height = viewport.height - (margin.top + margin.bottom);
let minY = 0,
maxY = 10,
minX = 0,
maxX = 10;
if (dataPoints.length > 0) {
if (data.allDataPoints && data.allDataPoints.length > 0) {
minY = minX = Number.MAX_VALUE;
maxY = maxX = Number.MIN_VALUE;
for (let i = 0, len = data.allDataPoints.length; i < len; i++) {
let dps = data.allDataPoints[i];
minY = Math.min(d3.min<PlayChartDataPoint, number>(dps, d => d.y), minY);
maxY = Math.max(d3.max<PlayChartDataPoint, number>(dps, d => d.y), maxY);
minX = Math.min(d3.min<PlayChartDataPoint, number>(dps, d => d.x), minX);
maxX = Math.max(d3.max<PlayChartDataPoint, number>(dps, d => d.x), maxX);
}
} else {
minY = d3.min<PlayChartDataPoint, number>(dataPoints, d => d.y);
maxY = d3.max<PlayChartDataPoint, number>(dataPoints, d => d.y);
minX = d3.min<PlayChartDataPoint, number>(dataPoints, d => d.x);
maxX = d3.max<PlayChartDataPoint, number>(dataPoints, d => d.x);
}
}
let xDomain = [minX, maxX];
let combinedXDomain = AxisHelper.combineDomain(options.forcedXDomain, xDomain);
this.xAxisProperties = AxisHelper.createAxis({
pixelSpan: width,
dataDomain: combinedXDomain,
metaDataColumn: data.xCol,
formatStringProp: playChartProps.general.formatString,
outerPadding: 0,
isScalar: true,
isVertical: false,
forcedTickCount: options.forcedTickCount,
useTickIntervalForDisplayUnits: true,
isCategoryAxis: true,//Play doesn't have a categorical axis, but this is needed for the pane to react correctly to the x-axis toggle one/off
scaleType: options.categoryAxisScaleType,
});
this.xAxisProperties.axis.tickSize(-height, 0);
this.xAxisProperties.axisLabel = this.data.axesLabels.x;
let combinedDomain = AxisHelper.combineDomain(options.forcedYDomain, [minY, maxY]);
this.yAxisProperties = AxisHelper.createAxis({
pixelSpan: height,
dataDomain: combinedDomain,
metaDataColumn: data.yCol,
formatStringProp: playChartProps.general.formatString,
outerPadding: 0,
isScalar: true,
isVertical: true,
forcedTickCount: options.forcedTickCount,
useTickIntervalForDisplayUnits: true,
isCategoryAxis: false,
scaleType: options.valueAxisScaleType
});
this.yAxisProperties.axisLabel = this.data.axesLabels.y;
return [this.xAxisProperties, this.yAxisProperties];
}
public overrideXScale(xProperties: IAxisProperties): void {
this.xAxisProperties = xProperties;
}
private createSliderDOM(): void {
// a container to position the button and the slider together
this.playAxisContainer = $('<div></div>')
.css('position', 'absolute')
.css('left', '15px')
.css('bottom', '35px')
.appendTo(this.element);
var playButtonCircle = $('<div class="button-container"></div>')
.appendTo(this.playAxisContainer)
.on('click', () => {
this.play();
});
this.playButton = $('<div class="play"></div>')
.appendTo(playButtonCircle);
// the noUiSlider
this.slider = $('<div class="sliders"></div>')
.appendTo(this.playAxisContainer);
}
private createSliderControl(slider: any, sliderWidth: number): void {
// re-create the slider
if ((<any>slider[0]).noUiSlider)
(<any>slider[0]).noUiSlider.destroy();
var numFrames = this.data.frameKeys.length;
if (numFrames > 0) {
var filterPipLabels = this.createPipsFilterFn(sliderWidth);
var lastIndex = numFrames - 1;
noUiSlider.create(
slider[0],
{
step: 1,
start: [this.data.currentFrameIndex],
range: {
min: [0],
max: [lastIndex],
},
pips: {
mode: 'steps',
density: 12,
format: {
to: (index) => this.data.frameKeys[index],
from: (value) => this.data.frameKeys.indexOf(value),
},
filter: filterPipLabels,
},
});
(<any>slider[0]).noUiSlider.on('slide', () => {
this.isPlaying = false; //stop the play sequence
var indexToShow = Math.round((<any>slider[0]).noUiSlider.get());
if (indexToShow >= 0 && indexToShow !== this.data.currentFrameIndex && indexToShow < this.data.allDataPoints.length) {
this.data.currentFrameIndex = indexToShow;
var data = this.data.allDataPoints[indexToShow];
this.data.dataPoints = data;
this.persistFrameIndex(indexToShow); //this will cause a render
}
});
}
else {
noUiSlider.create(
slider[0],
{
step: 1,
start: [0],
range: {
min: [0],
max: [0],
},
});
}
}
private createPipsFilterFn(sliderWidth: number): any {
let textProperties: TextProperties = {
fontFamily: 'wf_segoe-ui_normal',
fontSize: jsCommon.PixelConverter.toString(14),
};
let maxLabelWidth = 0;
let anyWillWordBreak = false;
for (var key of this.data.frameKeys) {
maxLabelWidth = Math.max(maxLabelWidth, jsCommon.WordBreaker.getMaxWordWidth(key + "", TextMeasurementService.measureSvgTextWidth, textProperties));
anyWillWordBreak = anyWillWordBreak || jsCommon.WordBreaker.hasBreakers(key);
}
var pipSize = 1; //0=hide, 1=large, 2=small
var skipMod = 1;
var maxAllowedLabelWidth = this.frameCount > 1 ? sliderWidth / (this.frameCount - 1) : sliderWidth;
var widthRatio = maxLabelWidth / maxAllowedLabelWidth;
if (widthRatio > 1.25) {
skipMod = Math.ceil(widthRatio);
pipSize = 2;
}
else if (widthRatio > 1.0 || anyWillWordBreak) {
// wordbreak line wrapping is automatic, and we don't reserve enough space to show two lines of text with the larger font
pipSize = 2;
}
var filterPipLabels = (index: any, type: any) => {
// noUiSlider will word break / wrap to new lines, so max width is the max word length
if (index % skipMod === 0) {
return pipSize;
}
return 0; //hide
};
return filterPipLabels;
}
public render(suppressAnimations: boolean): CartesianVisualRenderResult {
if (!this.data || !this.dataView)
return { dataPoints: [], behaviorOptions: null, labelDataPoints: [] };
let data = this.data;
let dataPoints = this.data.dataPoints;
let margin = this.margin;
let viewport = this.currentViewport;
let width = viewport.width - (margin.left + margin.right);
let height = viewport.height - (margin.top + margin.bottom);
let xScale = this.xAxisProperties.scale;
let yScale = this.yAxisProperties.scale;
var hasSelection = false;
if (this.interactivityService) {
this.interactivityService.applySelectionStateToData(dataPoints);
hasSelection = this.interactivityService.hasSelection();
}
this.mainGraphicsContext
.attr('width', width)
.attr('height', height);
let sortedData = dataPoints.sort(function (a, b) {
return b.radius.sizeMeasure ? (b.radius.sizeMeasure.values[b.radius.index] - a.radius.sizeMeasure.values[a.radius.index]) : 0;
});
var playMarkers = this.drawPlayMarkers(sortedData, hasSelection, data.sizeRange, suppressAnimations);
var labelsSelection: D3.Selection;
if (this.data.dataLabelsSettings.show) {
var layout = dataLabelUtils.getScatterChartLabelLayout(xScale, yScale, this.data.dataLabelsSettings, viewport, data.sizeRange);
labelsSelection = dataLabelUtils.drawDefaultLabelsForDataPointChart(
dataPoints,
this.dataLabelsContext,
layout,
this.currentViewport,
!!this.animator && !suppressAnimations,
PlayChart.FrameDuration,
hasSelection);
}
else {
dataLabelUtils.cleanDataLabels(this.dataLabelsContext);
}
TooltipManager.addTooltip(playMarkers, (tooltipEvent: TooltipEvent) => tooltipEvent.data.tooltipInfo);
if (this.data) {
if (!this.playAxisContainer && !this.isFrozen) {
this.createSliderDOM();
}
let frameKeys = this.data.frameKeys;
let currentFrameIndex = this.data.currentFrameIndex;
// callout / currentFrameIndex label
if (!this.callout) {
this.callout = $('<span class="callout"></span>').appendTo(this.element);
}
var slider = this.slider;
var sliderWidth = (width - PlayChart.SliderMarginLeft - PlayChart.SliderMarginRight);
if (slider)
slider.css('width', sliderWidth + 'px');
// TODO: make this smarter
let resized = this.currentViewport.width !== this.lastRenderedViewport.width
|| this.currentViewport.height !== this.lastRenderedViewport.height;
let changed = !this.playAxisContainer
|| frameKeys.length !== this.frameCount
|| resized;
// default to last frame if frameKeys have changed and it's not the first time we are rendering
if (this.frameCount && (frameKeys.length !== this.frameCount || currentFrameIndex >= frameKeys.length))
currentFrameIndex = frameKeys.length - 1;
if (changed && slider) {
this.frameCount = frameKeys.length;
this.createSliderControl(slider, sliderWidth);
}
// update callout to current frame index
var calloutDimension = Math.min(height, width * 1.3); //compensate for tall and narrow-width viewport
var fontSize = Math.max(12, Math.round(calloutDimension / 7)) + 'px';
if (currentFrameIndex < frameKeys.length && currentFrameIndex >= 0) {
this.callout
.text(frameKeys[currentFrameIndex])
.css('font-size', fontSize);
}
else {
this.callout.text('');
}
if (slider) {
// ensure slider position
(<any>slider[0]).noUiSlider.set([currentFrameIndex]);
}
this.lastRenderedViewport = {
height: this.currentViewport.height,
width: this.currentViewport.width
};
}
if (this.interactivityService) {
var behaviorOptions: PlayBehaviorOptions = {
host: this.cartesianVisualHost,
root: this.svg,
dataPointsSelection: playMarkers,
labelsSelection: labelsSelection,
mainContext: this.mainGraphicsContext,
data: this.data,
visualInitOptions: this.options,
xAxisProperties: this.xAxisProperties,
yAxisProperties: this.yAxisProperties,
background: d3.select(this.element.get(0)),
clearCatcher: this.clearCatcher,
dataViewCat: this.dataView.categorical,
svg: this.mainGraphicsContext,
dataView: this.dataView,
renderTraceLine: PlayChart.renderTraceLine,
};
if (hasSelection) {
let flatAllDataPoints = _.flatten<SelectableDataPoint>(this.data.allDataPoints);
let uniqueDataPoints = _.uniq(flatAllDataPoints, (d: PlayChartDataPoint) => d.identity.getKey());
PlayChart.renderTraceLine(behaviorOptions, _.filter(uniqueDataPoints, 'selected'), !suppressAnimations);
}
}
SVGUtil.flushAllD3TransitionsIfNeeded(this.options);
// pass allDataPoints to keep track of current selected bubble even if it drops out for a few frames
return { dataPoints: _.flatten<SelectableDataPoint>(this.data.allDataPoints), behaviorOptions: behaviorOptions, labelDataPoints: [] };
}
public static renderTraceLine(options: PlayBehaviorOptions, selectedPoints: SelectableDataPoint[], shouldAnimate: boolean): void {
var seriesPoints: PlayChartDataPoint[][] = [];
if (selectedPoints && selectedPoints.length > 0) {
let currentFrameIndex = options.data.currentFrameIndex;
let lastRenderedFrameIndex = options.data.lastRenderedFrameIndex;
// filter to the selected identity, only up to and including the current frame. Add frames during play.
let hasBubbleAtCurrentFrame = [];
for (var selectedIndex = 0, selectedLen = selectedPoints.length; selectedIndex < selectedLen; selectedIndex++) {
seriesPoints[selectedIndex] = [];
hasBubbleAtCurrentFrame[selectedIndex] = false;
for (let frameIndex = 0, frameLen = options.data.allDataPoints.length; frameIndex < frameLen && frameIndex <= currentFrameIndex; frameIndex++) {
let values = options.data.allDataPoints[frameIndex].filter((value, index) => {
return value.identity.getKey() === selectedPoints[selectedIndex].identity.getKey();
});
if (values && values.length > 0) {
seriesPoints[selectedIndex].push(values[0]);
if (frameIndex === currentFrameIndex)
hasBubbleAtCurrentFrame[selectedIndex] = true;
}
}
}
if (seriesPoints.length > 0) {
let xScale = options.xAxisProperties.scale;
let yScale = options.yAxisProperties.scale;
let line = d3.svg.line()
.x((d: PlayChartDataPoint) => {
return xScale(d.x);
})
.y((d: PlayChartDataPoint) => {
return yScale(d.y);
})
.defined((d: PlayChartDataPoint) => {
return d.x !== null && d.y !== null;
});
// Render Lines
let traceLines = options.svg.selectAll('.traceLine').data(selectedPoints, (sp: PlayChartDataPoint) => sp.identity.getKey());
traceLines.enter()
.append('path')
.classed('traceLine', true);
// prepare array of new/previous lengths
// NOTE: can't use lambda because we need the "this" context to be the DOM Element associated with the .each()
let previousLengths = [], newLengths = [];
traceLines.each(function (d, i) {
let existingPath = (<SVGPathElement>this);
let previousLength = existingPath.hasAttribute('d') ? existingPath.getTotalLength() : 0;
previousLengths.push(previousLength);
// create offline SVG for new path measurement
let tempSvgPath = $('<svg><path></path></svg>');
let tempPath = $('path', tempSvgPath);
tempPath.attr('d', line(seriesPoints[i]));
let newLength = (<SVGPathElement>tempPath.get()[0]).getTotalLength();
newLengths.push(newLength);
});
// animate using stroke-dash* trick
if (lastRenderedFrameIndex == null || currentFrameIndex >= lastRenderedFrameIndex) {
// growing line
traceLines
.style('stroke', (d: PlayChartDataPoint) => PlayChart.getStrokeFill(d, true))
.attr({
'd': (d, i: number) => {
return line(seriesPoints[i]);
},
'stroke-dasharray': (d, i) => newLengths[i] + " " + newLengths[i],
'stroke-dashoffset': (d, i) => newLengths[i] - previousLengths[i],
});
if (shouldAnimate) {
traceLines
.transition()
.duration(PlayChart.FrameDuration - PlayChart.FrameDurationFudge)
.attr('stroke-dashoffset', 0);
}
else {
traceLines.attr('stroke-dashoffset', 0);
}
}
else {
// shrinking line
if (shouldAnimate) {
traceLines
.transition()
.duration(PlayChart.FrameDuration - PlayChart.FrameDurationFudge)
.attr('stroke-dashoffset', (d, i) => previousLengths[i] - newLengths[i])
.transition()
.duration(1) // animate the shrink first, then update with new line properties
.delay(PlayChart.FrameDuration - PlayChart.FrameDurationFudge)
.style('stroke', (d: PlayChartDataPoint) => PlayChart.getStrokeFill(d, true))
.attr({
'd': (d, i) => {
return line(seriesPoints[i]);
},
'stroke-dasharray': (d, i) => newLengths[i] + " " + newLengths[i],
'stroke-dashoffset': 0,
});
}
else {
traceLines
.style('stroke', (d: PlayChartDataPoint) => PlayChart.getStrokeFill(d, true))
.attr({
'd': (d, i) => {
return line(seriesPoints[i]);
},
'stroke-dasharray': (d, i) => newLengths[i] + " " + newLengths[i],
'stroke-dashoffset': 0,
});
}
}
traceLines.exit()
.remove();
// Render circles
// slice to length-1 because we draw lines to the current bubble but we don't need to draw the current frame's bubble
let circlePoints: PlayChartDataPoint[] = [];
for (var selectedIndex = 0; selectedIndex < seriesPoints.length; selectedIndex++) {
let points = seriesPoints[selectedIndex];
let newPoints = hasBubbleAtCurrentFrame[selectedIndex] ? points.slice(0, points.length - 1) : points;
circlePoints = circlePoints.concat(newPoints);
}
let circles = options.svg.selectAll('.traceBubble').data(circlePoints, (d: PlayChartDataPoint) => d.identity.getKey() + d.x + d.y + d.size);
circles.enter()
.append('circle')
.style('opacity', 0) //fade new bubbles into visibility
.classed('traceBubble', true);
circles
.attr('cx', (d: PlayChartDataPoint) => xScale(d.x))
.attr('cy', (d: PlayChartDataPoint) => yScale(d.y))
.attr('r', (d: PlayChartDataPoint) => PlayChart.getBubbleRadius(d.radius, options.data.sizeRange, options.data.currentViewport))
.style({
'stroke-opacity': (d: PlayChartDataPoint) => PlayChart.getBubbleOpacity(d, true),
'stroke-width': '1px',
'stroke': (d: PlayChartDataPoint) => PlayChart.getStrokeFill(d, true),
'fill': (d: PlayChartDataPoint) => d.fill,
'fill-opacity': (d: PlayChartDataPoint) => d.size != null ? PlayChart.getBubbleOpacity(d, true) : 0,
})
.transition()
.duration(PlayChart.FrameDuration)
.style('opacity',1);
circles.exit()
.transition()
.duration(PlayChart.FrameDuration)
.style('opacity', 0) //fade exiting bubbles out
.remove();
TooltipManager.addTooltip(circles, (tooltipEvent: TooltipEvent) => tooltipEvent.data.tooltipInfo);
// sort the z-order, smallest size on top
circles.sort((d1: PlayChartDataPoint, d2: PlayChartDataPoint) => { return d2.size - d1.size; });
}
else {
options.svg.selectAll('.traceLine').remove();
options.svg.selectAll('.traceBubble').remove();
}
}
else {
options.svg.selectAll('.traceLine').remove();
options.svg.selectAll('.traceBubble').remove();
}
options.data.lastRenderedFrameIndex = options.data.currentFrameIndex;
}
private play(): void {
if (this.isPlaying) {
// Toggle the flag and allow the animation logic to kill it
this.isPlaying = false;
}
else if ((<any>this.slider[0]).noUiSlider != null) {
this.isPlaying = true;
this.playButton.removeClass('play').addClass('pause');
let indexToShow = Math.round((<any>this.slider[0]).noUiSlider.get());
if (indexToShow >= this.data.allDataPoints.length - 1) {
this.data.currentFrameIndex = -1;
} else {
this.data.currentFrameIndex = indexToShow - 1;
}
this.playNextFrame();
}
}
private persistFrameIndex(frameIndex: number): void {
this.ridiculousFlagForPersistProperties = true;
let properties: { [name: string]: data.SQExpr } = {};
properties['frozenIndex'] = data.SQExprBuilder.integer(frameIndex);
this.host.persistProperties([{
selector: null,
properties: properties,
objectName: 'general'
}]);
}
private playNextFrame(startFrame?: number, endFrame?: number): void {
if (!this.isPlaying) {
this.playComplete();
return;
}
let nextFrame = this.data.currentFrameIndex + 1;
if (startFrame != null && endFrame != null) {
nextFrame = Math.abs(endFrame - startFrame + 1);
startFrame = nextFrame;
}
if (nextFrame < this.data.allDataPoints.length && nextFrame > -1) {
this.data.currentFrameIndex = nextFrame;
this.data.dataPoints = this.data.allDataPoints[nextFrame];
this.persistFrameIndex(nextFrame); //this will cause a render call
(<any>this.slider[0]).noUiSlider.set([nextFrame]);
if (nextFrame < this.data.allDataPoints.length) {
let timePerFrame = PlayChart.FrameDuration;
window.setTimeout(() => {
// Update the rangeSlider to show the correct offset
(<any>this.slider[0]).noUiSlider.set([nextFrame]);
// Play next frame
this.playNextFrame(startFrame, endFrame);
}, timePerFrame);
}
} else {
this.playComplete();
}
}
private playComplete(): void {
this.playButton.removeClass('pause').addClass('play');
this.isPlaying = false;
this.render(false);
}
private drawPlayMarkers(playData: PlayChartDataPoint[], hasSelection: boolean, sizeRange: NumberRange, suppressAnimations: boolean) {
let duration = PlayChart.FrameDuration;
let xScale = this.xAxisProperties.scale;
let yScale = this.yAxisProperties.scale;
let markerTagName = PlayChart.PlayChartCircleTagName;
let markers = this.mainGraphicsContext.selectAll(PlayChart.DotClasses.selector).data(playData, (d: PlayChartDataPoint) => d.identity.getKey());
markers.enter().append(markerTagName)
.classed(PlayChart.DotClasses.class, true)
.style('opacity', 0) //fade new bubbles into visibility
.attr('r', 0);
markers
.style({
'stroke-opacity': (d: PlayChartDataPoint) => PlayChart.getBubbleOpacity(d, hasSelection),
'stroke-width': '1px',
'stroke': (d: PlayChartDataPoint) => PlayChart.getStrokeFill(d, true),
'fill': (d: PlayChartDataPoint) => d.fill,
'fill-opacity': (d: PlayChartDataPoint) => d.size != null ? PlayChart.getBubbleOpacity(d, hasSelection) : 0,
});
if (suppressAnimations) {
markers
.style('opacity', 1)
.attr({
r: (d: PlayChartDataPoint) => PlayChart.getBubbleRadius(d.radius, sizeRange, this.currentViewport),
cx: d => xScale(d.x),
cy: d => yScale(d.y),
});
}
else {
markers
.transition()
.duration(duration)
.style('opacity', 1)
.attr({
r: (d: PlayChartDataPoint) => PlayChart.getBubbleRadius(d.radius, sizeRange, this.currentViewport),
cx: d => xScale(d.x),
cy: d => yScale(d.y),
});
}
markers
.exit()
.transition()
.duration(duration)
.style('opacity', 0) //fade out bubbles that are removed
.attr('r', 0)
.remove();
return markers;
}
public static getStrokeFill(d: ScatterChartDataPoint, colorBorder: boolean): string {
if (d.size != null && colorBorder) {
let colorRgb = Color.parseRgb(d.fill);
return Color.rgbToHexString(Color.darken(colorRgb, ScatterChart.StrokeDarkenColorValue));
}
return d.fill;
}
public static getBubblePixelAreaSizeRange(viewPort: IViewport, minSizeRange: number, maxSizeRange: number): DataRange {
let ratio = 1.0;
if (viewPort.height > 0 && viewPort.width > 0) {
let minSize = Math.min(viewPort.height, viewPort.width);
ratio = (minSize * minSize) / PlayChart.AreaOf300By300Chart;
}
let minRange = Math.round(minSizeRange * ratio);
let maxRange = Math.round(maxSizeRange * ratio);
return {
minRange: minRange,
maxRange: maxRange,
delta: maxRange - minRange
};
}
public static project(value: number, actualSizeDataRange: DataRange, bubblePixelAreaSizeRange: DataRange): number {
if (actualSizeDataRange.delta === 0 || bubblePixelAreaSizeRange.delta === 0) {
return (PlayChart.rangeContains(actualSizeDataRange, value)) ? bubblePixelAreaSizeRange.minRange : null;
}
let relativeX = (value - actualSizeDataRange.minRange) / actualSizeDataRange.delta;
return bubblePixelAreaSizeRange.minRange + relativeX * bubblePixelAreaSizeRange.delta;
}
public static projectSizeToPixels(size: number, actualSizeDataRange: DataRange, bubblePixelAreaSizeRange: DataRange): number {
let projectedSize = 0;
if (actualSizeDataRange) {
// Project value on the required range of bubble area sizes
projectedSize = bubblePixelAreaSizeRange.maxRange;
if (actualSizeDataRange.delta !== 0) {
let value = Math.min(Math.max(size, actualSizeDataRange.minRange), actualSizeDataRange.maxRange);
projectedSize = PlayChart.project(value, actualSizeDataRange, bubblePixelAreaSizeRange);
}
projectedSize = Math.sqrt(projectedSize / Math.PI) * 2;
}
return Math.round(projectedSize);
}
public static rangeContains(range: DataRange, value: number): boolean {
return range.minRange <= value && value <= range.maxRange;
}
public static getBubbleOpacity(d: PlayChartDataPoint, hasSelection: boolean): number {
if (hasSelection && !d.selected) {
return PlayChart.DimmedBubbleOpacity;
}
return PlayChart.DefaultBubbleOpacity;
}
public onClearSelection(): void {
if (this.interactivityService)
this.interactivityService.clearSelection();
}
public getSupportedCategoryAxisType(): string {
return axisType.scalar;
}
}
}
| kristianolssonadvectas/powerbivisuals | src/Clients/Visuals/cartesian/playChart.ts | TypeScript | mit | 73,145 |
var gulp = require('gulp');
var browserSync = require('browser-sync');
var paths = require('../paths');
// this task utilizes the browsersync plugin
// to create a dev server instance
// at http://localhost:9000
gulp.task('e2e-serve', ['e2e-build'], function(done) {
browserSync({
open: false,
port: 9000,
server: {
baseDir: ["."],
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
}
}
}, done);
});
| Mordred/aurelia-compiler | build/tasks/e2e-serve.js | JavaScript | mit | 504 |
package cucumber.runtime.jruby;
import cucumber.api.Scenario;
import cucumber.runtime.HookDefinition;
import gherkin.TagExpression;
import gherkin.formatter.model.Tag;
import org.jruby.RubyObject;
import java.util.Collection;
import java.util.List;
import static java.util.Arrays.asList;
public class JRubyHookDefinition implements HookDefinition {
private final TagExpression tagExpression;
private final RubyObject hookRunner;
private String file;
private Long line;
private final JRubyBackend jRubyBackend;
public JRubyHookDefinition(JRubyBackend jRubyBackend, String[] tagExpressions, RubyObject hookRunner) {
this.jRubyBackend = jRubyBackend;
this.tagExpression = new TagExpression(asList(tagExpressions));
this.hookRunner = hookRunner;
}
@Override
public String getLocation(boolean detail) {
if (file == null) {
List fileAndLine = (List) hookRunner.callMethod("file_and_line").toJava(List.class);
file = (String) fileAndLine.get(0);
line = (Long) fileAndLine.get(1);
}
return file + ":" + line;
}
@Override
public void execute(Scenario scenario) throws Throwable {
jRubyBackend.executeHook(hookRunner, scenario);
}
@Override
public boolean matches(Collection<Tag> tags) {
return tagExpression.evaluate(tags);
}
@Override
public int getOrder() {
return 0;
}
}
| VivaceVivo/cucumber-mod-DI | jruby/src/main/java/cucumber/runtime/jruby/JRubyHookDefinition.java | Java | mit | 1,460 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function write(v) { WScript.Echo(v + ""); }
function foo() {}
write(undefined >= undefined);
write(undefined >= null);
write(undefined >= true);
write(undefined >= false);
write(undefined >= Boolean(true));
write(undefined >= Boolean(false));
write(undefined >= new Boolean(true));
write(undefined >= new Boolean(false));
write(undefined >= NaN);
write(undefined >= +0);
write(undefined >= -0);
write(undefined >= 0);
write(undefined >= 0.0);
write(undefined >= -0.0);
write(undefined >= +0.0);
write(undefined >= 1);
write(undefined >= 10);
write(undefined >= 10.0);
write(undefined >= 10.1);
write(undefined >= -1);
write(undefined >= -10);
write(undefined >= -10.0);
write(undefined >= -10.1);
write(undefined >= Number.MAX_VALUE);
write(undefined >= Number.MIN_VALUE);
write(undefined >= Number.NaN);
write(undefined >= Number.POSITIVE_INFINITY);
write(undefined >= Number.NEGATIVE_INFINITY);
write(undefined >= new Number(NaN));
write(undefined >= new Number(+0));
write(undefined >= new Number(-0));
write(undefined >= new Number(0));
write(undefined >= new Number(0.0));
write(undefined >= new Number(-0.0));
write(undefined >= new Number(+0.0));
write(undefined >= new Number(1));
write(undefined >= new Number(10));
write(undefined >= new Number(10.0));
write(undefined >= new Number(10.1));
write(undefined >= new Number(-1));
write(undefined >= new Number(-10));
write(undefined >= new Number(-10.0));
write(undefined >= new Number(-10.1));
write(undefined >= new Number(Number.MAX_VALUE));
write(undefined >= new Number(Number.MIN_VALUE));
write(undefined >= new Number(Number.NaN));
write(undefined >= new Number(Number.POSITIVE_INFINITY));
write(undefined >= new Number(Number.NEGATIVE_INFINITY));
write(undefined >= '');
write(undefined >= 0xa);
write(undefined >= 04);
write(undefined >= 'hello');
write(undefined >= 'hel' + 'lo');
write(undefined >= String(''));
write(undefined >= String('hello'));
write(undefined >= String('h' + 'ello'));
write(undefined >= new String(''));
write(undefined >= new String('hello'));
write(undefined >= new String('he' + 'llo'));
write(undefined >= new Object());
write(undefined >= new Object());
write(undefined >= [1, 2, 3]);
write(undefined >= [1 ,2 , 3]);
write(undefined >= new Array(3));
write(undefined >= Array(3));
write(undefined >= new Array(1 ,2 ,3));
write(undefined >= Array(1));
write(undefined >= foo);
write(null >= undefined);
write(null >= null);
write(null >= true);
write(null >= false);
write(null >= Boolean(true));
write(null >= Boolean(false));
write(null >= new Boolean(true));
write(null >= new Boolean(false));
write(null >= NaN);
write(null >= +0);
write(null >= -0);
write(null >= 0);
write(null >= 0.0);
write(null >= -0.0);
write(null >= +0.0);
write(null >= 1);
write(null >= 10);
write(null >= 10.0);
write(null >= 10.1);
write(null >= -1);
write(null >= -10);
write(null >= -10.0);
write(null >= -10.1);
write(null >= Number.MAX_VALUE);
write(null >= Number.MIN_VALUE);
write(null >= Number.NaN);
write(null >= Number.POSITIVE_INFINITY);
write(null >= Number.NEGATIVE_INFINITY);
write(null >= new Number(NaN));
write(null >= new Number(+0));
write(null >= new Number(-0));
write(null >= new Number(0));
write(null >= new Number(0.0));
write(null >= new Number(-0.0));
write(null >= new Number(+0.0));
write(null >= new Number(1));
write(null >= new Number(10));
write(null >= new Number(10.0));
write(null >= new Number(10.1));
write(null >= new Number(-1));
write(null >= new Number(-10));
write(null >= new Number(-10.0));
write(null >= new Number(-10.1));
write(null >= new Number(Number.MAX_VALUE));
write(null >= new Number(Number.MIN_VALUE));
write(null >= new Number(Number.NaN));
write(null >= new Number(Number.POSITIVE_INFINITY));
write(null >= new Number(Number.NEGATIVE_INFINITY));
write(null >= '');
write(null >= 0xa);
write(null >= 04);
write(null >= 'hello');
write(null >= 'hel' + 'lo');
write(null >= String(''));
write(null >= String('hello'));
write(null >= String('h' + 'ello'));
write(null >= new String(''));
write(null >= new String('hello'));
write(null >= new String('he' + 'llo'));
write(null >= new Object());
write(null >= new Object());
write(null >= [1, 2, 3]);
write(null >= [1 ,2 , 3]);
write(null >= new Array(3));
write(null >= Array(3));
write(null >= new Array(1 ,2 ,3));
write(null >= Array(1));
write(null >= foo);
write(true >= undefined);
write(true >= null);
write(true >= true);
write(true >= false);
write(true >= Boolean(true));
write(true >= Boolean(false));
write(true >= new Boolean(true));
write(true >= new Boolean(false));
write(true >= NaN);
write(true >= +0);
write(true >= -0);
write(true >= 0);
write(true >= 0.0);
write(true >= -0.0);
write(true >= +0.0);
write(true >= 1);
write(true >= 10);
write(true >= 10.0);
write(true >= 10.1);
write(true >= -1);
write(true >= -10);
write(true >= -10.0);
write(true >= -10.1);
write(true >= Number.MAX_VALUE);
write(true >= Number.MIN_VALUE);
write(true >= Number.NaN);
write(true >= Number.POSITIVE_INFINITY);
write(true >= Number.NEGATIVE_INFINITY);
write(true >= new Number(NaN));
write(true >= new Number(+0));
write(true >= new Number(-0));
write(true >= new Number(0));
write(true >= new Number(0.0));
write(true >= new Number(-0.0));
write(true >= new Number(+0.0));
write(true >= new Number(1));
write(true >= new Number(10));
write(true >= new Number(10.0));
write(true >= new Number(10.1));
write(true >= new Number(-1));
write(true >= new Number(-10));
write(true >= new Number(-10.0));
write(true >= new Number(-10.1));
write(true >= new Number(Number.MAX_VALUE));
write(true >= new Number(Number.MIN_VALUE));
write(true >= new Number(Number.NaN));
write(true >= new Number(Number.POSITIVE_INFINITY));
write(true >= new Number(Number.NEGATIVE_INFINITY));
write(true >= '');
write(true >= 0xa);
write(true >= 04);
write(true >= 'hello');
write(true >= 'hel' + 'lo');
write(true >= String(''));
write(true >= String('hello'));
write(true >= String('h' + 'ello'));
write(true >= new String(''));
write(true >= new String('hello'));
write(true >= new String('he' + 'llo'));
write(true >= new Object());
write(true >= new Object());
write(true >= [1, 2, 3]);
write(true >= [1 ,2 , 3]);
write(true >= new Array(3));
write(true >= Array(3));
write(true >= new Array(1 ,2 ,3));
write(true >= Array(1));
write(true >= foo);
write(false >= undefined);
write(false >= null);
write(false >= true);
write(false >= false);
write(false >= Boolean(true));
write(false >= Boolean(false));
write(false >= new Boolean(true));
write(false >= new Boolean(false));
write(false >= NaN);
write(false >= +0);
write(false >= -0);
write(false >= 0);
write(false >= 0.0);
write(false >= -0.0);
write(false >= +0.0);
write(false >= 1);
write(false >= 10);
write(false >= 10.0);
write(false >= 10.1);
write(false >= -1);
write(false >= -10);
write(false >= -10.0);
write(false >= -10.1);
write(false >= Number.MAX_VALUE);
write(false >= Number.MIN_VALUE);
write(false >= Number.NaN);
write(false >= Number.POSITIVE_INFINITY);
write(false >= Number.NEGATIVE_INFINITY);
write(false >= new Number(NaN));
write(false >= new Number(+0));
write(false >= new Number(-0));
write(false >= new Number(0));
write(false >= new Number(0.0));
write(false >= new Number(-0.0));
write(false >= new Number(+0.0));
write(false >= new Number(1));
write(false >= new Number(10));
write(false >= new Number(10.0));
write(false >= new Number(10.1));
write(false >= new Number(-1));
write(false >= new Number(-10));
write(false >= new Number(-10.0));
write(false >= new Number(-10.1));
write(false >= new Number(Number.MAX_VALUE));
write(false >= new Number(Number.MIN_VALUE));
write(false >= new Number(Number.NaN));
write(false >= new Number(Number.POSITIVE_INFINITY));
write(false >= new Number(Number.NEGATIVE_INFINITY));
write(false >= '');
write(false >= 0xa);
write(false >= 04);
write(false >= 'hello');
write(false >= 'hel' + 'lo');
write(false >= String(''));
write(false >= String('hello'));
write(false >= String('h' + 'ello'));
write(false >= new String(''));
write(false >= new String('hello'));
write(false >= new String('he' + 'llo'));
write(false >= new Object());
write(false >= new Object());
write(false >= [1, 2, 3]);
write(false >= [1 ,2 , 3]);
write(false >= new Array(3));
write(false >= Array(3));
write(false >= new Array(1 ,2 ,3));
write(false >= Array(1));
write(false >= foo);
write(Boolean(true) >= undefined);
write(Boolean(true) >= null);
write(Boolean(true) >= true);
write(Boolean(true) >= false);
write(Boolean(true) >= Boolean(true));
write(Boolean(true) >= Boolean(false));
write(Boolean(true) >= new Boolean(true));
write(Boolean(true) >= new Boolean(false));
write(Boolean(true) >= NaN);
write(Boolean(true) >= +0);
write(Boolean(true) >= -0);
write(Boolean(true) >= 0);
write(Boolean(true) >= 0.0);
write(Boolean(true) >= -0.0);
write(Boolean(true) >= +0.0);
write(Boolean(true) >= 1);
write(Boolean(true) >= 10);
write(Boolean(true) >= 10.0);
write(Boolean(true) >= 10.1);
write(Boolean(true) >= -1);
write(Boolean(true) >= -10);
write(Boolean(true) >= -10.0);
write(Boolean(true) >= -10.1);
write(Boolean(true) >= Number.MAX_VALUE);
write(Boolean(true) >= Number.MIN_VALUE);
write(Boolean(true) >= Number.NaN);
write(Boolean(true) >= Number.POSITIVE_INFINITY);
write(Boolean(true) >= Number.NEGATIVE_INFINITY);
write(Boolean(true) >= new Number(NaN));
write(Boolean(true) >= new Number(+0));
write(Boolean(true) >= new Number(-0));
write(Boolean(true) >= new Number(0));
write(Boolean(true) >= new Number(0.0));
write(Boolean(true) >= new Number(-0.0));
write(Boolean(true) >= new Number(+0.0));
write(Boolean(true) >= new Number(1));
write(Boolean(true) >= new Number(10));
write(Boolean(true) >= new Number(10.0));
write(Boolean(true) >= new Number(10.1));
write(Boolean(true) >= new Number(-1));
write(Boolean(true) >= new Number(-10));
write(Boolean(true) >= new Number(-10.0));
write(Boolean(true) >= new Number(-10.1));
write(Boolean(true) >= new Number(Number.MAX_VALUE));
write(Boolean(true) >= new Number(Number.MIN_VALUE));
write(Boolean(true) >= new Number(Number.NaN));
write(Boolean(true) >= new Number(Number.POSITIVE_INFINITY));
write(Boolean(true) >= new Number(Number.NEGATIVE_INFINITY));
write(Boolean(true) >= '');
write(Boolean(true) >= 0xa);
write(Boolean(true) >= 04);
write(Boolean(true) >= 'hello');
write(Boolean(true) >= 'hel' + 'lo');
write(Boolean(true) >= String(''));
write(Boolean(true) >= String('hello'));
write(Boolean(true) >= String('h' + 'ello'));
write(Boolean(true) >= new String(''));
write(Boolean(true) >= new String('hello'));
write(Boolean(true) >= new String('he' + 'llo'));
write(Boolean(true) >= new Object());
write(Boolean(true) >= new Object());
write(Boolean(true) >= [1, 2, 3]);
write(Boolean(true) >= [1 ,2 , 3]);
write(Boolean(true) >= new Array(3));
write(Boolean(true) >= Array(3));
write(Boolean(true) >= new Array(1 ,2 ,3));
write(Boolean(true) >= Array(1));
write(Boolean(true) >= foo);
write(Boolean(false) >= undefined);
write(Boolean(false) >= null);
write(Boolean(false) >= true);
write(Boolean(false) >= false);
write(Boolean(false) >= Boolean(true));
write(Boolean(false) >= Boolean(false));
write(Boolean(false) >= new Boolean(true));
write(Boolean(false) >= new Boolean(false));
write(Boolean(false) >= NaN);
write(Boolean(false) >= +0);
write(Boolean(false) >= -0);
write(Boolean(false) >= 0);
write(Boolean(false) >= 0.0);
write(Boolean(false) >= -0.0);
write(Boolean(false) >= +0.0);
write(Boolean(false) >= 1);
write(Boolean(false) >= 10);
write(Boolean(false) >= 10.0);
write(Boolean(false) >= 10.1);
write(Boolean(false) >= -1);
write(Boolean(false) >= -10);
write(Boolean(false) >= -10.0);
write(Boolean(false) >= -10.1);
write(Boolean(false) >= Number.MAX_VALUE);
write(Boolean(false) >= Number.MIN_VALUE);
write(Boolean(false) >= Number.NaN);
write(Boolean(false) >= Number.POSITIVE_INFINITY);
write(Boolean(false) >= Number.NEGATIVE_INFINITY);
write(Boolean(false) >= new Number(NaN));
write(Boolean(false) >= new Number(+0));
write(Boolean(false) >= new Number(-0));
write(Boolean(false) >= new Number(0));
write(Boolean(false) >= new Number(0.0));
write(Boolean(false) >= new Number(-0.0));
write(Boolean(false) >= new Number(+0.0));
write(Boolean(false) >= new Number(1));
write(Boolean(false) >= new Number(10));
write(Boolean(false) >= new Number(10.0));
write(Boolean(false) >= new Number(10.1));
write(Boolean(false) >= new Number(-1));
write(Boolean(false) >= new Number(-10));
write(Boolean(false) >= new Number(-10.0));
write(Boolean(false) >= new Number(-10.1));
write(Boolean(false) >= new Number(Number.MAX_VALUE));
write(Boolean(false) >= new Number(Number.MIN_VALUE));
write(Boolean(false) >= new Number(Number.NaN));
write(Boolean(false) >= new Number(Number.POSITIVE_INFINITY));
write(Boolean(false) >= new Number(Number.NEGATIVE_INFINITY));
write(Boolean(false) >= '');
write(Boolean(false) >= 0xa);
write(Boolean(false) >= 04);
write(Boolean(false) >= 'hello');
write(Boolean(false) >= 'hel' + 'lo');
write(Boolean(false) >= String(''));
write(Boolean(false) >= String('hello'));
write(Boolean(false) >= String('h' + 'ello'));
write(Boolean(false) >= new String(''));
write(Boolean(false) >= new String('hello'));
write(Boolean(false) >= new String('he' + 'llo'));
write(Boolean(false) >= new Object());
write(Boolean(false) >= new Object());
write(Boolean(false) >= [1, 2, 3]);
write(Boolean(false) >= [1 ,2 , 3]);
write(Boolean(false) >= new Array(3));
write(Boolean(false) >= Array(3));
write(Boolean(false) >= new Array(1 ,2 ,3));
write(Boolean(false) >= Array(1));
write(Boolean(false) >= foo);
write(new Boolean(true) >= undefined);
write(new Boolean(true) >= null);
write(new Boolean(true) >= true);
write(new Boolean(true) >= false);
write(new Boolean(true) >= Boolean(true));
write(new Boolean(true) >= Boolean(false));
write(new Boolean(true) >= new Boolean(true));
write(new Boolean(true) >= new Boolean(false));
write(new Boolean(true) >= NaN);
write(new Boolean(true) >= +0);
write(new Boolean(true) >= -0);
write(new Boolean(true) >= 0);
write(new Boolean(true) >= 0.0);
write(new Boolean(true) >= -0.0);
write(new Boolean(true) >= +0.0);
write(new Boolean(true) >= 1);
write(new Boolean(true) >= 10);
write(new Boolean(true) >= 10.0);
write(new Boolean(true) >= 10.1);
write(new Boolean(true) >= -1);
write(new Boolean(true) >= -10);
write(new Boolean(true) >= -10.0);
write(new Boolean(true) >= -10.1);
write(new Boolean(true) >= Number.MAX_VALUE);
write(new Boolean(true) >= Number.MIN_VALUE);
write(new Boolean(true) >= Number.NaN);
write(new Boolean(true) >= Number.POSITIVE_INFINITY);
write(new Boolean(true) >= Number.NEGATIVE_INFINITY);
write(new Boolean(true) >= new Number(NaN));
write(new Boolean(true) >= new Number(+0));
write(new Boolean(true) >= new Number(-0));
write(new Boolean(true) >= new Number(0));
write(new Boolean(true) >= new Number(0.0));
write(new Boolean(true) >= new Number(-0.0));
write(new Boolean(true) >= new Number(+0.0));
write(new Boolean(true) >= new Number(1));
write(new Boolean(true) >= new Number(10));
write(new Boolean(true) >= new Number(10.0));
write(new Boolean(true) >= new Number(10.1));
write(new Boolean(true) >= new Number(-1));
write(new Boolean(true) >= new Number(-10));
write(new Boolean(true) >= new Number(-10.0));
write(new Boolean(true) >= new Number(-10.1));
write(new Boolean(true) >= new Number(Number.MAX_VALUE));
write(new Boolean(true) >= new Number(Number.MIN_VALUE));
write(new Boolean(true) >= new Number(Number.NaN));
write(new Boolean(true) >= new Number(Number.POSITIVE_INFINITY));
write(new Boolean(true) >= new Number(Number.NEGATIVE_INFINITY));
write(new Boolean(true) >= '');
write(new Boolean(true) >= 0xa);
write(new Boolean(true) >= 04);
write(new Boolean(true) >= 'hello');
write(new Boolean(true) >= 'hel' + 'lo');
write(new Boolean(true) >= String(''));
write(new Boolean(true) >= String('hello'));
write(new Boolean(true) >= String('h' + 'ello'));
write(new Boolean(true) >= new String(''));
write(new Boolean(true) >= new String('hello'));
write(new Boolean(true) >= new String('he' + 'llo'));
write(new Boolean(true) >= new Object());
write(new Boolean(true) >= new Object());
write(new Boolean(true) >= [1, 2, 3]);
write(new Boolean(true) >= [1 ,2 , 3]);
write(new Boolean(true) >= new Array(3));
write(new Boolean(true) >= Array(3));
write(new Boolean(true) >= new Array(1 ,2 ,3));
write(new Boolean(true) >= Array(1));
write(new Boolean(true) >= foo);
write(new Boolean(false) >= undefined);
write(new Boolean(false) >= null);
write(new Boolean(false) >= true);
write(new Boolean(false) >= false);
write(new Boolean(false) >= Boolean(true));
write(new Boolean(false) >= Boolean(false));
write(new Boolean(false) >= new Boolean(true));
write(new Boolean(false) >= new Boolean(false));
write(new Boolean(false) >= NaN);
write(new Boolean(false) >= +0);
write(new Boolean(false) >= -0);
write(new Boolean(false) >= 0);
write(new Boolean(false) >= 0.0);
write(new Boolean(false) >= -0.0);
write(new Boolean(false) >= +0.0);
write(new Boolean(false) >= 1);
write(new Boolean(false) >= 10);
write(new Boolean(false) >= 10.0);
write(new Boolean(false) >= 10.1);
write(new Boolean(false) >= -1);
write(new Boolean(false) >= -10);
write(new Boolean(false) >= -10.0);
write(new Boolean(false) >= -10.1);
write(new Boolean(false) >= Number.MAX_VALUE);
write(new Boolean(false) >= Number.MIN_VALUE);
write(new Boolean(false) >= Number.NaN);
write(new Boolean(false) >= Number.POSITIVE_INFINITY);
write(new Boolean(false) >= Number.NEGATIVE_INFINITY);
write(new Boolean(false) >= new Number(NaN));
write(new Boolean(false) >= new Number(+0));
write(new Boolean(false) >= new Number(-0));
write(new Boolean(false) >= new Number(0));
write(new Boolean(false) >= new Number(0.0));
write(new Boolean(false) >= new Number(-0.0));
write(new Boolean(false) >= new Number(+0.0));
write(new Boolean(false) >= new Number(1));
write(new Boolean(false) >= new Number(10));
write(new Boolean(false) >= new Number(10.0));
write(new Boolean(false) >= new Number(10.1));
write(new Boolean(false) >= new Number(-1));
write(new Boolean(false) >= new Number(-10));
write(new Boolean(false) >= new Number(-10.0));
write(new Boolean(false) >= new Number(-10.1));
write(new Boolean(false) >= new Number(Number.MAX_VALUE));
write(new Boolean(false) >= new Number(Number.MIN_VALUE));
write(new Boolean(false) >= new Number(Number.NaN));
write(new Boolean(false) >= new Number(Number.POSITIVE_INFINITY));
write(new Boolean(false) >= new Number(Number.NEGATIVE_INFINITY));
write(new Boolean(false) >= '');
write(new Boolean(false) >= 0xa);
write(new Boolean(false) >= 04);
write(new Boolean(false) >= 'hello');
write(new Boolean(false) >= 'hel' + 'lo');
write(new Boolean(false) >= String(''));
write(new Boolean(false) >= String('hello'));
write(new Boolean(false) >= String('h' + 'ello'));
write(new Boolean(false) >= new String(''));
write(new Boolean(false) >= new String('hello'));
write(new Boolean(false) >= new String('he' + 'llo'));
write(new Boolean(false) >= new Object());
write(new Boolean(false) >= new Object());
write(new Boolean(false) >= [1, 2, 3]);
write(new Boolean(false) >= [1 ,2 , 3]);
write(new Boolean(false) >= new Array(3));
write(new Boolean(false) >= Array(3));
write(new Boolean(false) >= new Array(1 ,2 ,3));
write(new Boolean(false) >= Array(1));
write(new Boolean(false) >= foo);
write(NaN >= undefined);
write(NaN >= null);
write(NaN >= true);
write(NaN >= false);
write(NaN >= Boolean(true));
write(NaN >= Boolean(false));
write(NaN >= new Boolean(true));
write(NaN >= new Boolean(false));
write(NaN >= NaN);
write(NaN >= +0);
write(NaN >= -0);
write(NaN >= 0);
write(NaN >= 0.0);
write(NaN >= -0.0);
write(NaN >= +0.0);
write(NaN >= 1);
write(NaN >= 10);
write(NaN >= 10.0);
write(NaN >= 10.1);
write(NaN >= -1);
write(NaN >= -10);
write(NaN >= -10.0);
write(NaN >= -10.1);
write(NaN >= Number.MAX_VALUE);
write(NaN >= Number.MIN_VALUE);
write(NaN >= Number.NaN);
write(NaN >= Number.POSITIVE_INFINITY);
write(NaN >= Number.NEGATIVE_INFINITY);
write(NaN >= new Number(NaN));
write(NaN >= new Number(+0));
write(NaN >= new Number(-0));
write(NaN >= new Number(0));
write(NaN >= new Number(0.0));
write(NaN >= new Number(-0.0));
write(NaN >= new Number(+0.0));
write(NaN >= new Number(1));
write(NaN >= new Number(10));
write(NaN >= new Number(10.0));
write(NaN >= new Number(10.1));
write(NaN >= new Number(-1));
write(NaN >= new Number(-10));
write(NaN >= new Number(-10.0));
write(NaN >= new Number(-10.1));
write(NaN >= new Number(Number.MAX_VALUE));
write(NaN >= new Number(Number.MIN_VALUE));
write(NaN >= new Number(Number.NaN));
write(NaN >= new Number(Number.POSITIVE_INFINITY));
write(NaN >= new Number(Number.NEGATIVE_INFINITY));
write(NaN >= '');
write(NaN >= 0xa);
write(NaN >= 04);
write(NaN >= 'hello');
write(NaN >= 'hel' + 'lo');
write(NaN >= String(''));
write(NaN >= String('hello'));
write(NaN >= String('h' + 'ello'));
write(NaN >= new String(''));
write(NaN >= new String('hello'));
write(NaN >= new String('he' + 'llo'));
write(NaN >= new Object());
write(NaN >= new Object());
write(NaN >= [1, 2, 3]);
write(NaN >= [1 ,2 , 3]);
write(NaN >= new Array(3));
write(NaN >= Array(3));
write(NaN >= new Array(1 ,2 ,3));
write(NaN >= Array(1));
write(NaN >= foo);
write(+0 >= undefined);
write(+0 >= null);
write(+0 >= true);
write(+0 >= false);
write(+0 >= Boolean(true));
write(+0 >= Boolean(false));
write(+0 >= new Boolean(true));
write(+0 >= new Boolean(false));
write(+0 >= NaN);
write(+0 >= +0);
write(+0 >= -0);
write(+0 >= 0);
write(+0 >= 0.0);
write(+0 >= -0.0);
write(+0 >= +0.0);
write(+0 >= 1);
write(+0 >= 10);
write(+0 >= 10.0);
write(+0 >= 10.1);
write(+0 >= -1);
write(+0 >= -10);
write(+0 >= -10.0);
write(+0 >= -10.1);
write(+0 >= Number.MAX_VALUE);
write(+0 >= Number.MIN_VALUE);
write(+0 >= Number.NaN);
write(+0 >= Number.POSITIVE_INFINITY);
write(+0 >= Number.NEGATIVE_INFINITY);
write(+0 >= new Number(NaN));
write(+0 >= new Number(+0));
write(+0 >= new Number(-0));
write(+0 >= new Number(0));
write(+0 >= new Number(0.0));
write(+0 >= new Number(-0.0));
write(+0 >= new Number(+0.0));
write(+0 >= new Number(1));
write(+0 >= new Number(10));
write(+0 >= new Number(10.0));
write(+0 >= new Number(10.1));
write(+0 >= new Number(-1));
write(+0 >= new Number(-10));
write(+0 >= new Number(-10.0));
write(+0 >= new Number(-10.1));
write(+0 >= new Number(Number.MAX_VALUE));
write(+0 >= new Number(Number.MIN_VALUE));
write(+0 >= new Number(Number.NaN));
write(+0 >= new Number(Number.POSITIVE_INFINITY));
write(+0 >= new Number(Number.NEGATIVE_INFINITY));
write(+0 >= '');
write(+0 >= 0xa);
write(+0 >= 04);
write(+0 >= 'hello');
write(+0 >= 'hel' + 'lo');
write(+0 >= String(''));
write(+0 >= String('hello'));
write(+0 >= String('h' + 'ello'));
write(+0 >= new String(''));
write(+0 >= new String('hello'));
write(+0 >= new String('he' + 'llo'));
write(+0 >= new Object());
write(+0 >= new Object());
write(+0 >= [1, 2, 3]);
write(+0 >= [1 ,2 , 3]);
write(+0 >= new Array(3));
write(+0 >= Array(3));
write(+0 >= new Array(1 ,2 ,3));
write(+0 >= Array(1));
write(+0 >= foo);
write(-0 >= undefined);
write(-0 >= null);
write(-0 >= true);
write(-0 >= false);
write(-0 >= Boolean(true));
write(-0 >= Boolean(false));
write(-0 >= new Boolean(true));
write(-0 >= new Boolean(false));
write(-0 >= NaN);
write(-0 >= +0);
write(-0 >= -0);
write(-0 >= 0);
write(-0 >= 0.0);
write(-0 >= -0.0);
write(-0 >= +0.0);
write(-0 >= 1);
write(-0 >= 10);
write(-0 >= 10.0);
write(-0 >= 10.1);
write(-0 >= -1);
write(-0 >= -10);
write(-0 >= -10.0);
write(-0 >= -10.1);
write(-0 >= Number.MAX_VALUE);
write(-0 >= Number.MIN_VALUE);
write(-0 >= Number.NaN);
write(-0 >= Number.POSITIVE_INFINITY);
write(-0 >= Number.NEGATIVE_INFINITY);
write(-0 >= new Number(NaN));
write(-0 >= new Number(+0));
write(-0 >= new Number(-0));
write(-0 >= new Number(0));
write(-0 >= new Number(0.0));
write(-0 >= new Number(-0.0));
write(-0 >= new Number(+0.0));
write(-0 >= new Number(1));
write(-0 >= new Number(10));
write(-0 >= new Number(10.0));
write(-0 >= new Number(10.1));
write(-0 >= new Number(-1));
write(-0 >= new Number(-10));
write(-0 >= new Number(-10.0));
write(-0 >= new Number(-10.1));
write(-0 >= new Number(Number.MAX_VALUE));
write(-0 >= new Number(Number.MIN_VALUE));
write(-0 >= new Number(Number.NaN));
write(-0 >= new Number(Number.POSITIVE_INFINITY));
write(-0 >= new Number(Number.NEGATIVE_INFINITY));
write(-0 >= '');
write(-0 >= 0xa);
write(-0 >= 04);
write(-0 >= 'hello');
write(-0 >= 'hel' + 'lo');
write(-0 >= String(''));
write(-0 >= String('hello'));
write(-0 >= String('h' + 'ello'));
write(-0 >= new String(''));
write(-0 >= new String('hello'));
write(-0 >= new String('he' + 'llo'));
write(-0 >= new Object());
write(-0 >= new Object());
write(-0 >= [1, 2, 3]);
write(-0 >= [1 ,2 , 3]);
write(-0 >= new Array(3));
write(-0 >= Array(3));
write(-0 >= new Array(1 ,2 ,3));
write(-0 >= Array(1));
write(-0 >= foo);
write(0 >= undefined);
write(0 >= null);
write(0 >= true);
write(0 >= false);
write(0 >= Boolean(true));
write(0 >= Boolean(false));
write(0 >= new Boolean(true));
write(0 >= new Boolean(false));
write(0 >= NaN);
write(0 >= +0);
write(0 >= -0);
write(0 >= 0);
write(0 >= 0.0);
write(0 >= -0.0);
write(0 >= +0.0);
write(0 >= 1);
write(0 >= 10);
write(0 >= 10.0);
write(0 >= 10.1);
write(0 >= -1);
write(0 >= -10);
write(0 >= -10.0);
write(0 >= -10.1);
write(0 >= Number.MAX_VALUE);
write(0 >= Number.MIN_VALUE);
write(0 >= Number.NaN);
write(0 >= Number.POSITIVE_INFINITY);
write(0 >= Number.NEGATIVE_INFINITY);
write(0 >= new Number(NaN));
write(0 >= new Number(+0));
write(0 >= new Number(-0));
write(0 >= new Number(0));
write(0 >= new Number(0.0));
write(0 >= new Number(-0.0));
write(0 >= new Number(+0.0));
write(0 >= new Number(1));
write(0 >= new Number(10));
write(0 >= new Number(10.0));
write(0 >= new Number(10.1));
write(0 >= new Number(-1));
write(0 >= new Number(-10));
write(0 >= new Number(-10.0));
write(0 >= new Number(-10.1));
write(0 >= new Number(Number.MAX_VALUE));
write(0 >= new Number(Number.MIN_VALUE));
write(0 >= new Number(Number.NaN));
write(0 >= new Number(Number.POSITIVE_INFINITY));
write(0 >= new Number(Number.NEGATIVE_INFINITY));
write(0 >= '');
write(0 >= 0xa);
write(0 >= 04);
write(0 >= 'hello');
write(0 >= 'hel' + 'lo');
write(0 >= String(''));
write(0 >= String('hello'));
write(0 >= String('h' + 'ello'));
write(0 >= new String(''));
write(0 >= new String('hello'));
write(0 >= new String('he' + 'llo'));
write(0 >= new Object());
write(0 >= new Object());
write(0 >= [1, 2, 3]);
write(0 >= [1 ,2 , 3]);
write(0 >= new Array(3));
write(0 >= Array(3));
write(0 >= new Array(1 ,2 ,3));
write(0 >= Array(1));
write(0 >= foo);
write(0.0 >= undefined);
write(0.0 >= null);
write(0.0 >= true);
write(0.0 >= false);
write(0.0 >= Boolean(true));
write(0.0 >= Boolean(false));
write(0.0 >= new Boolean(true));
write(0.0 >= new Boolean(false));
write(0.0 >= NaN);
write(0.0 >= +0);
write(0.0 >= -0);
write(0.0 >= 0);
write(0.0 >= 0.0);
write(0.0 >= -0.0);
write(0.0 >= +0.0);
write(0.0 >= 1);
write(0.0 >= 10);
write(0.0 >= 10.0);
write(0.0 >= 10.1);
write(0.0 >= -1);
write(0.0 >= -10);
write(0.0 >= -10.0);
write(0.0 >= -10.1);
write(0.0 >= Number.MAX_VALUE);
write(0.0 >= Number.MIN_VALUE);
write(0.0 >= Number.NaN);
write(0.0 >= Number.POSITIVE_INFINITY);
write(0.0 >= Number.NEGATIVE_INFINITY);
write(0.0 >= new Number(NaN));
write(0.0 >= new Number(+0));
write(0.0 >= new Number(-0));
write(0.0 >= new Number(0));
write(0.0 >= new Number(0.0));
write(0.0 >= new Number(-0.0));
write(0.0 >= new Number(+0.0));
write(0.0 >= new Number(1));
write(0.0 >= new Number(10));
write(0.0 >= new Number(10.0));
write(0.0 >= new Number(10.1));
write(0.0 >= new Number(-1));
write(0.0 >= new Number(-10));
write(0.0 >= new Number(-10.0));
write(0.0 >= new Number(-10.1));
write(0.0 >= new Number(Number.MAX_VALUE));
write(0.0 >= new Number(Number.MIN_VALUE));
write(0.0 >= new Number(Number.NaN));
write(0.0 >= new Number(Number.POSITIVE_INFINITY));
write(0.0 >= new Number(Number.NEGATIVE_INFINITY));
write(0.0 >= '');
write(0.0 >= 0xa);
write(0.0 >= 04);
write(0.0 >= 'hello');
write(0.0 >= 'hel' + 'lo');
write(0.0 >= String(''));
write(0.0 >= String('hello'));
write(0.0 >= String('h' + 'ello'));
write(0.0 >= new String(''));
write(0.0 >= new String('hello'));
write(0.0 >= new String('he' + 'llo'));
write(0.0 >= new Object());
write(0.0 >= new Object());
write(0.0 >= [1, 2, 3]);
write(0.0 >= [1 ,2 , 3]);
write(0.0 >= new Array(3));
write(0.0 >= Array(3));
write(0.0 >= new Array(1 ,2 ,3));
write(0.0 >= Array(1));
write(0.0 >= foo);
write(-0.0 >= undefined);
write(-0.0 >= null);
write(-0.0 >= true);
write(-0.0 >= false);
write(-0.0 >= Boolean(true));
write(-0.0 >= Boolean(false));
write(-0.0 >= new Boolean(true));
write(-0.0 >= new Boolean(false));
write(-0.0 >= NaN);
write(-0.0 >= +0);
write(-0.0 >= -0);
write(-0.0 >= 0);
write(-0.0 >= 0.0);
write(-0.0 >= -0.0);
write(-0.0 >= +0.0);
write(-0.0 >= 1);
write(-0.0 >= 10);
write(-0.0 >= 10.0);
write(-0.0 >= 10.1);
write(-0.0 >= -1);
write(-0.0 >= -10);
write(-0.0 >= -10.0);
write(-0.0 >= -10.1);
write(-0.0 >= Number.MAX_VALUE);
write(-0.0 >= Number.MIN_VALUE);
write(-0.0 >= Number.NaN);
write(-0.0 >= Number.POSITIVE_INFINITY);
write(-0.0 >= Number.NEGATIVE_INFINITY);
write(-0.0 >= new Number(NaN));
write(-0.0 >= new Number(+0));
write(-0.0 >= new Number(-0));
write(-0.0 >= new Number(0));
write(-0.0 >= new Number(0.0));
write(-0.0 >= new Number(-0.0));
write(-0.0 >= new Number(+0.0));
write(-0.0 >= new Number(1));
write(-0.0 >= new Number(10));
write(-0.0 >= new Number(10.0));
write(-0.0 >= new Number(10.1));
write(-0.0 >= new Number(-1));
write(-0.0 >= new Number(-10));
write(-0.0 >= new Number(-10.0));
write(-0.0 >= new Number(-10.1));
write(-0.0 >= new Number(Number.MAX_VALUE));
write(-0.0 >= new Number(Number.MIN_VALUE));
write(-0.0 >= new Number(Number.NaN));
write(-0.0 >= new Number(Number.POSITIVE_INFINITY));
write(-0.0 >= new Number(Number.NEGATIVE_INFINITY));
write(-0.0 >= '');
write(-0.0 >= 0xa);
write(-0.0 >= 04);
write(-0.0 >= 'hello');
write(-0.0 >= 'hel' + 'lo');
write(-0.0 >= String(''));
write(-0.0 >= String('hello'));
write(-0.0 >= String('h' + 'ello'));
write(-0.0 >= new String(''));
write(-0.0 >= new String('hello'));
write(-0.0 >= new String('he' + 'llo'));
write(-0.0 >= new Object());
write(-0.0 >= new Object());
write(-0.0 >= [1, 2, 3]);
write(-0.0 >= [1 ,2 , 3]);
write(-0.0 >= new Array(3));
write(-0.0 >= Array(3));
write(-0.0 >= new Array(1 ,2 ,3));
write(-0.0 >= Array(1));
write(-0.0 >= foo);
write(+0.0 >= undefined);
write(+0.0 >= null);
write(+0.0 >= true);
write(+0.0 >= false);
write(+0.0 >= Boolean(true));
write(+0.0 >= Boolean(false));
write(+0.0 >= new Boolean(true));
write(+0.0 >= new Boolean(false));
write(+0.0 >= NaN);
write(+0.0 >= +0);
write(+0.0 >= -0);
write(+0.0 >= 0);
write(+0.0 >= 0.0);
write(+0.0 >= -0.0);
write(+0.0 >= +0.0);
write(+0.0 >= 1);
write(+0.0 >= 10);
write(+0.0 >= 10.0);
write(+0.0 >= 10.1);
write(+0.0 >= -1);
write(+0.0 >= -10);
write(+0.0 >= -10.0);
write(+0.0 >= -10.1);
write(+0.0 >= Number.MAX_VALUE);
write(+0.0 >= Number.MIN_VALUE);
write(+0.0 >= Number.NaN);
write(+0.0 >= Number.POSITIVE_INFINITY);
write(+0.0 >= Number.NEGATIVE_INFINITY);
write(+0.0 >= new Number(NaN));
write(+0.0 >= new Number(+0));
write(+0.0 >= new Number(-0));
write(+0.0 >= new Number(0));
write(+0.0 >= new Number(0.0));
write(+0.0 >= new Number(-0.0));
write(+0.0 >= new Number(+0.0));
write(+0.0 >= new Number(1));
write(+0.0 >= new Number(10));
write(+0.0 >= new Number(10.0));
write(+0.0 >= new Number(10.1));
write(+0.0 >= new Number(-1));
write(+0.0 >= new Number(-10));
write(+0.0 >= new Number(-10.0));
write(+0.0 >= new Number(-10.1));
write(+0.0 >= new Number(Number.MAX_VALUE));
write(+0.0 >= new Number(Number.MIN_VALUE));
write(+0.0 >= new Number(Number.NaN));
write(+0.0 >= new Number(Number.POSITIVE_INFINITY));
write(+0.0 >= new Number(Number.NEGATIVE_INFINITY));
| arunetm/ChakraCore_0114 | test/Generated/ge.js | JavaScript | mit | 33,355 |
(function() {
'use strict';
/**
* @name config
* @description config block
*/
function config($stateProvider) {
$stateProvider
.state('root.home', {
url: '/',
views: {
'@': {
templateUrl: 'src/app/home/home.tpl.html',
controller: 'HomeCtrl as home',
}
}
});
}
/**
* @name HomeCtrl
* @description Controller
*/
function HomeCtrl() {
var vm = this;
}
angular.module('home', [])
.config(config)
.controller('HomeCtrl', HomeCtrl);
})();
| lealivran/Moonie | client/src/app/home/home.js | JavaScript | mit | 568 |
// Type definitions for bluebird 2.0.0
// Project: https://github.com/petkaantonov/bluebird
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts
// By: Campredon <https://github.com/fdecampredon/>
// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code):
// - https://github.com/borisyankov/DefinitelyTyped/issues/1563
// Note: replicate changes to all overloads in both definition and test file
// Note: keep both static and instance members inline (so similar)
// TODO fix remaining TODO annotations in both definition and test
// TODO verify support to have no return statement in handlers to get a Promise<void> (more overloads?)
declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*/
constructor(callback: (resolve: (thenableOrResult?: R | Promise.Thenable<R>) => void, reject: (error: any) => void) => void);
/**
* Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then<U>(onFulfill: (value: R) => U|Promise.Thenable<U>, onReject?: (error: any) => U|Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => U|Promise.Thenable<U>, onReject?: (error: any) => void|Promise.Thenable<void>, onProgress?: (note: any) => any): Promise<U>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch(onReject?: (error: any) => R|Promise.Thenable<R>|void|Promise.Thenable<void>): Promise<R>;
caught(onReject?: (error: any) => R|Promise.Thenable<R>|void|Promise.Thenable<void>): Promise<R>;
catch<U>(onReject?: (error: any) => U|Promise.Thenable<U>): Promise<U|R>;
caught<U>(onReject?: (error: any) => U|Promise.Thenable<U>): Promise<U|R>;
/**
* This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called.
*
* This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch(predicate: (error: any) => boolean, onReject: (error: any) => R|Promise.Thenable<R>|void|Promise.Thenable<void>): Promise<R>;
caught(predicate: (error: any) => boolean, onReject: (error: any) => R|Promise.Thenable<R>|void|Promise.Thenable<void>): Promise<R>;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U|Promise.Thenable<U>): Promise<U|R>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => U|Promise.Thenable<U>): Promise<U|R>;
catch(ErrorClass: Function, onReject: (error: any) => R|Promise.Thenable<R>|void|Promise.Thenable<void>): Promise<R>;
caught(ErrorClass: Function, onReject: (error: any) => R|Promise.Thenable<R>|void|Promise.Thenable<void>): Promise<R>;
catch<U>(ErrorClass: Function, onReject: (error: any) => U|Promise.Thenable<U>): Promise<U|R>;
caught<U>(ErrorClass: Function, onReject: (error: any) => U|Promise.Thenable<U>): Promise<U|R>;
/**
* Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections.
*/
error<U>(onReject: (reason: any) => Promise.Thenable<U>): Promise<U>;
error<U>(onReject: (reason: any) => U): Promise<U>;
/**
* Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally<U>(handler: () => Promise.Thenable<U>): Promise<R>;
finally<U>(handler: () => U): Promise<R>;
lastly<U>(handler: () => Promise.Thenable<U>): Promise<R>;
lastly<U>(handler: () => U): Promise<R>;
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
*/
bind(thisArg: any): Promise<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): void;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): void;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void;
/**
* Like `.finally()`, but not called for rejections.
*/
tap<U>(onFulFill: (value: R) => Promise.Thenable<U>): Promise<R>;
tap<U>(onFulfill: (value: R) => U): Promise<R>;
/**
* Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise.
*/
progressed(handler: (note: any) => any): Promise<R>;
/**
* Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
delay(ms: number): Promise<R>;
/**
* Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance.
*
* You may specify a custom error message with the `message` parameter.
*/
timeout(ms: number, message?: string): Promise<R>;
/**
* Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success.
* Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback: (err: any, value?: R) => void, options?: Promise.SpreadOption): Promise<R>;
nodeify(...sink: any[]): Promise<R>;
/**
* Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise.
*/
cancellable(): Promise<R>;
/**
* Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending.
*
* That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason.
*
* In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`.
*
* Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
*/
// TODO what to do with this?
cancel<U>(reason?: any): Promise<U>;
/**
* Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
*/
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Create an uncancellable promise based on this promise.
*/
uncancellable(): Promise<R>;
/**
* See if this promise can be cancelled.
*/
isCancellable(): boolean;
/**
* See if this `promise` has been fulfilled.
*/
isFulfilled(): boolean;
/**
* See if this `promise` has been rejected.
*/
isRejected(): boolean;
/**
* See if this `promise` is still defer.
*/
isPending(): boolean;
/**
* See if this `promise` is resolved -> either fulfilled or rejected.
*/
isResolved(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet.
*
* throws `TypeError`
*/
reason(): any;
/**
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
*/
inspect(): Promise.Inspection<R>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName: string, ...args: any[]): Promise<any>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
// TODO find way to fix get()
// get<U>(propertyName: string): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return(): Promise<any>;
thenReturn(): Promise<any>;
return<U>(value: U): Promise<U>;
thenReturn<U>(value: U): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: Error): Promise<R>;
thenThrow(reason: Error): Promise<R>;
/**
* Convert to String.
*/
toString(): string;
/**
* This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
*/
toJSON(): Object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
// TODO how to model instance.spread()? like Q?
spread<U>(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U>(onFulfill: Function, onReject?: (reason: any) => U): Promise<U>;
/*
// TODO or something like this?
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => U): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise<U>;
*/
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
all<U>(): Promise<U[]>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO how to model instance.props()?
props(): Promise<Object>;
/**
* Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
settle<U>(): Promise<Promise.Inspection<U>[]>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
any<U>(): Promise<U>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
some<U>(count: number): Promise<U[]>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
race<U>(): Promise<U>;
/**
* Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable<U>, options?: Promise.ConcurrencyOption): Promise<U[]>;
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise<U[]>;
/**
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
filter<U>(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable<boolean>, options?: Promise.ConcurrencyOption): Promise<U[]>;
filter<U>(filterer: (item: U, index: number, arrayLength: number) => boolean, options?: Promise.ConcurrencyOption): Promise<U[]>;
/**
* Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
each<R, U>(iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable<U>): Promise<R[]>;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
static try<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
static try<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
static attempt<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
static attempt<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
/**
* Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
static method(fn: Function): Function;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
static resolve(): Promise<void>;
static resolve<R>(value: Promise.Thenable<R>): Promise<R>;
static resolve<R>(value: R): Promise<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
static reject(reason: any): Promise<any>;
static reject<R>(reason: any): Promise<R>;
/**
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
*/
static defer<R>(): Promise.Resolver<R>;
/**
* Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
static cast<R>(value: Promise.Thenable<R>): Promise<R>;
static cast<R>(value: R): Promise<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
static bind(thisArg: any): Promise<void>;
/**
* See if `value` is a trusted Promise.
*/
static is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
static longStackTraces(): void;
/**
* Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise.
*/
// TODO enable more overloads
static delay<R>(value: Promise.Thenable<R>, ms: number): Promise<R>;
static delay<R>(value: R, ms: number): Promise<R>;
static delay(ms: number): Promise<void>;
/**
* Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
static promisify<T>(func: (callback: (err:any, result: T) => void) => void, receiver?: any): () => Promise<T>;
static promisify<T, A1>(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise<T>;
static promisify<T, A1, A2>(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise<T>;
static promisify<T, A1, A2, A3>(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise<T>;
static promisify<T, A1, A2, A3, A4>(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise<T>;
static promisify<T, A1, A2, A3, A4, A5>(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise<T>;
static promisify(nodeFunction: Function, receiver?: any): Function;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any;
/**
* Returns a promise that is resolved by a node style callback function.
*/
static fromNode(resolver: (callback: (err: any, result?: any) => void) => void): Promise<any>;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix coroutine GeneratorFunction
static coroutine<R>(generatorFunction: Function): Function;
/**
* Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix spawn GeneratorFunction
static spawn<R>(generatorFunction: Function): Promise<R>;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else.
*/
static noConflict(): typeof Promise;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
static onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
// TODO enable more overloads
// promise of array with promises of value
static all<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R[]>;
// promise of array with values
static all<R>(values: Promise.Thenable<R[]>): Promise<R[]>;
// array with promises of value
static all<R>(values: Promise.Thenable<R>[]): Promise<R[]>;
// array with promises of different types
static all<T1, T2>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>]): Promise<[T1, T2]>;
static all<T1, T2, T3>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>, Promise.Thenable<T3>]): Promise<[T1, T2, T3]>;
static all<T1, T2, T3, T4>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>, Promise.Thenable<T3>, Promise.Thenable<T4>]): Promise<[T1, T2, T3, T4]>;
static all<T1, T2, T3, T4, T5>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>, Promise.Thenable<T3>, Promise.Thenable<T4>, Promise.Thenable<T5>]): Promise<[T1, T2, T3, T4, T5]>;
// array with values
static all<R>(values: R[]): Promise<R[]>;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
// TODO verify this is correct
// trusted promise for object
static props(object: Promise<Object>): Promise<Object>;
// object
static props(object: Object): Promise<Object>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array.
*
* *original: The array is not modified. The input array sparsity is retained in the resulting array.*
*/
// promise of array with promises of value
static settle<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<Promise.Inspection<R>[]>;
// promise of array with values
static settle<R>(values: Promise.Thenable<R[]>): Promise<Promise.Inspection<R>[]>;
// array with promises of value
static settle<R>(values: Promise.Thenable<R>[]): Promise<Promise.Inspection<R>[]>;
// array with values
static settle<R>(values: R[]): Promise<Promise.Inspection<R>[]>;
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
// promise of array with promises of value
static any<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R>;
// promise of array with values
static any<R>(values: Promise.Thenable<R[]>): Promise<R>;
// array with promises of value
static any<R>(values: Promise.Thenable<R>[]): Promise<R>;
// array with values
static any<R>(values: R[]): Promise<R>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
// promise of array with promises of value
static race<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R>;
// promise of array with values
static race<R>(values: Promise.Thenable<R[]>): Promise<R>;
// array with promises of value
static race<R>(values: Promise.Thenable<R>[]): Promise<R>;
// array with values
static race<R>(values: R[]): Promise<R>;
/**
* Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
static some<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, count: number): Promise<R[]>;
// promise of array with values
static some<R>(values: Promise.Thenable<R[]>, count: number): Promise<R[]>;
// array with promises of value
static some<R>(values: Promise.Thenable<R>[], count: number): Promise<R[]>;
// array with values
static some<R>(values: R[], count: number): Promise<R[]>;
/**
* Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments.
*/
// variadic array with promises of value
static join<R>(...values: Promise.Thenable<R>[]): Promise<R[]>;
// variadic array with values
static join<R>(...values: R[]): Promise<R[]>;
/**
* Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
static map<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>, options?: Promise.ConcurrencyOption): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise<U[]>;
// promise of array with values
static map<R, U>(values: Promise.Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>, options?: Promise.ConcurrencyOption): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise<U[]>;
// array with promises of value
static map<R, U>(values: Promise.Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>, options?: Promise.ConcurrencyOption): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise<U[]>;
// array with values
static map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>, options?: Promise.ConcurrencyOption): Promise<U[]>;
static map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise<U[]>;
/**
* Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
// promise of array with promises of value
static reduce<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// promise of array with values
static reduce<R, U>(values: Promise.Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with promises of value
static reduce<R, U>(values: Promise.Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with values
static reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
// promise of array with promises of value
static filter<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>, option?: Promise.ConcurrencyOption): Promise<R[]>;
static filter<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise<R[]>;
// promise of array with values
static filter<R>(values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>, option?: Promise.ConcurrencyOption): Promise<R[]>;
static filter<R>(values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise<R[]>;
// array with promises of value
static filter<R>(values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>, option?: Promise.ConcurrencyOption): Promise<R[]>;
static filter<R>(values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise<R[]>;
// array with values
static filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>, option?: Promise.ConcurrencyOption): Promise<R[]>;
static filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise<R[]>;
/**
* Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well.
*
* Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*/
// promise of array with promises of value
static each<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable<U>): Promise<R[]>;
// array with promises of value
static each<R, U>(values: Promise.Thenable<R>[], iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable<U>): Promise<R[]>;
// array with values OR promise of array with values
static each<R, U>(values: R[] | Promise.Thenable<R[]>, iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable<U>): Promise<R[]>;
}
declare module Promise {
export interface RangeError extends Error {
}
export interface CancellationError extends Error {
}
export interface TimeoutError extends Error {
}
export interface TypeError extends Error {
}
export interface RejectionError extends Error {
}
export interface OperationalError extends Error {
}
export interface ConcurrencyOption {
concurrency: number;
}
export interface SpreadOption {
spread: boolean;
}
export interface PromisifyAllOptions {
suffix?: string;
filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean;
// The promisifier gets a reference to the original method and should return a function which returns a promise
promisifier?: (originalMethod: Function) => () => Thenable<any> ;
}
// Ideally, we'd define e.g. "export class RangeError extends Error {}",
// but as Error is defined as an interface (not a class), TypeScript doesn't
// allow extending Error, only implementing it.
// However, if we want to catch() only a specific error type, we need to pass
// a constructor function to it. So, as a workaround, we define them here as such.
export function RangeError(): RangeError;
export function CancellationError(): CancellationError;
export function TimeoutError(): TimeoutError;
export function TypeError(): TypeError;
export function RejectionError(): RejectionError;
export function OperationalError(): OperationalError;
export interface Thenable<R> {
then<U>(onFulfilled: (value: R) => U|Thenable<U>, onRejected?: (error: any) => U|Thenable<U>): Thenable<U>;
then<U>(onFulfilled: (value: R) => U|Thenable<U>, onRejected?: (error: any) => void|Thenable<void>): Thenable<U>;
}
export interface Resolver<R> {
/**
* Returns a reference to the controlled promise that can be passed to clients.
*/
promise: Promise<R>;
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value: R): void;
resolve(): void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
*/
reject(reason: any): void;
/**
* Progress the underlying promise with `value` as the progression value.
*/
progress(value: any): void;
/**
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values.
*/
// TODO specify resolver callback
callback: (err: any, value: R, ...values: R[]) => void;
}
export interface Inspection<R> {
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
isFulfilled(): boolean;
/**
* See if the underlying promise was rejected at the creation time of this inspection object.
*/
isRejected(): boolean;
/**
* See if the underlying promise was defer at the creation time of this inspection object.
*/
isPending(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
*
* throws `TypeError`
*/
reason(): any;
}
/**
* Changes how bluebird schedules calls a-synchronously.
*
* @param scheduler Should be a function that asynchronously schedules
* the calling of the passed in function
*/
export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void;
}
declare module 'bluebird' {
export = Promise;
}
| takenet/DefinitelyTyped | bluebird/bluebird.d.ts | TypeScript | mit | 40,725 |
// Flags: --expose-internals
'use strict';
require('../common');
const assert = require('assert');
const { sleep } = require('internal/util');
// Make sure we test 0ms timers, since they would had always wanted to run on
// the current tick, and greater than 0ms timers, for scenarios where the
// outer timer takes longer to complete than the delay of the nested timer.
// Since the process of recreating this is identical regardless of the timer
// delay, these scenarios are in one test.
const scenarios = [0, 100];
scenarios.forEach(function(delay) {
let nestedCalled = false;
setTimeout(function A() {
// Create the nested timer with the same delay as the outer timer so that it
// gets added to the current list of timers being processed by
// listOnTimeout.
setTimeout(function B() {
nestedCalled = true;
}, delay);
// Busy loop for the same timeout used for the nested timer to ensure that
// we are in fact expiring the nested timer.
sleep(delay);
// The purpose of running this assert in nextTick is to make sure it runs
// after A but before the next iteration of the libuv event loop.
process.nextTick(function() {
assert.ok(!nestedCalled);
});
// Ensure that the nested callback is indeed called prior to process exit.
process.on('exit', function onExit() {
assert.ok(nestedCalled);
});
}, delay);
});
| enclose-io/compiler | lts/test/parallel/test-timers-nested.js | JavaScript | mit | 1,406 |
module.exports = require('./lib/test.js');
| milesj/boost | packages/log/test.js | JavaScript | mit | 43 |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_12/models/bossbotHQ/BossbotGreenRoom_A',
'wantDoors': 1},
1001: {'type': 'editMgr',
'name': 'EditMgr',
'parentEntId': 0,
'insertEntity': None,
'removeEntity': None,
'requestNewEntity': None,
'requestSave': None},
0: {'type': 'zone',
'name': 'UberZone',
'comment': '',
'parentEntId': 0,
'scale': 1,
'description': '',
'visibility': []},
110301: {'type': 'door',
'name': '<unnamed>',
'comment': '',
'parentEntId': 110303,
'pos': Point3(0, 0, 0),
'hpr': Vec3(0, 0, 0),
'scale': 1,
'color': Vec4(1, 1, 1, 1),
'isLock0Unlocked': 1,
'isLock1Unlocked': 0,
'isLock2Unlocked': 1,
'isLock3Unlocked': 1,
'isOpen': 0,
'isOpenEvent': 0,
'isVisBlocker': 0,
'secondsOpen': 1,
'unlock0Event': 0,
'unlock1Event': 110302,
'unlock2Event': 0,
'unlock3Event': 0},
110302: {'type': 'golfGreenGame',
'name': '<unnamed>',
'comment': '',
'parentEntId': 0,
'pos': Point3(0, 0, 0),
'hpr': Vec3(0, 0, 0),
'scale': 1,
'cellId': 0,
'puzzleBase': 3,
'puzzlePerPlayer': 1,
'switchId': 0,
'timeToPlay': 120},
10002: {'type': 'nodepath',
'name': 'props',
'comment': '',
'parentEntId': 0,
'pos': Point3(0, 0, 0),
'hpr': Vec3(0, 0, 0),
'scale': 1},
110303: {'type': 'nodepath',
'name': '<unnamed>',
'comment': '',
'parentEntId': 0,
'pos': Point3(40.9635, 2, 0),
'hpr': Vec3(270, 0, 0),
'scale': Vec3(1, 1, 1)}}
Scenario0 = {}
levelSpec = {'globalEntities': GlobalEntities,
'scenarios': [Scenario0]}
| ksmit799/Toontown-Source | toontown/coghq/BossbotCountryClubGreenRoom_Action00.py | Python | mit | 2,122 |
// Time: O(nlogn + n * t), t is the value of target.
// Space: O(t)
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1, 0);
dp[0] = 1;
sort(nums.begin(), nums.end());
for (int i = 1; i <= target; ++i) {
for (int j = 0; j < nums.size() && nums[j] <= i; ++j) {
dp[i] += dp[i - nums[j]];
}
}
return dp[target];
}
};
| yiwen-luo/LeetCode | C++/combination-sum-iv.cpp | C++ | mit | 466 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace Foo {
public static class Utils {
public static DateTimeOffset ToDTO(DateTime dt) {
return new DateTimeOffset(dt);
}
public static DateTimeOffset? ToDTO(DateTime? dt) {
return dt == null ? (DateTimeOffset?) null : new DateTimeOffset(dt.Value);
}
public static DateTime ToDT(DateTimeOffset dto) {
return dto.DateTime;
}
public static DateTime? ToDT(DateTimeOffset? dto) {
return dto == null ? (DateTime?) null : dto.Value.DateTime;
}
}
public partial class Order {
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4OrderDate {
get { return Utils.ToDTO(OrderDate); }
set { OrderDate = Utils.ToDT(value); }
}
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4RequiredDate {
get { return Utils.ToDTO(RequiredDate); }
set { RequiredDate = Utils.ToDT(value); }
}
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4ShippedDate {
get { return Utils.ToDTO(ShippedDate); }
set { ShippedDate = Utils.ToDT(value); }
}
}
public partial class Employee {
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4BirthDate {
get { return Utils.ToDTO(BirthDate); }
set { BirthDate = Utils.ToDT(value); }
}
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4HireDate {
get { return Utils.ToDTO(HireDate); }
set { HireDate = Utils.ToDT(value); }
}
}
public partial class PreviousEmployee {
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4BirthDate {
get { return Utils.ToDTO(BirthDate); }
set { BirthDate = Utils.ToDT(value); }
}
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4HireDate {
get { return Utils.ToDTO(HireDate); }
set { HireDate = Utils.ToDT(value); }
}
}
public partial class Product {
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4DiscontinuedDate {
get { return Utils.ToDTO(DiscontinuedDate); }
set { DiscontinuedDate = Utils.ToDT(value); }
}
}
public partial class User {
[NotMapped]
public System.DateTimeOffset OData4CreatedDate {
get { return Utils.ToDTO(CreatedDate); }
set { CreatedDate = Utils.ToDT(value); }
}
[NotMapped]
public System.DateTimeOffset OData4ModifiedDate {
get { return Utils.ToDTO(ModifiedDate); }
set { ModifiedDate = Utils.ToDT(value); }
}
}
public partial class Comment {
[NotMapped]
public System.DateTimeOffset OData4CreatedOn {
get { return Utils.ToDTO(CreatedOn); }
set { CreatedOn = Utils.ToDT(value); }
}
}
public partial class UnusualDate {
[NotMapped]
public System.DateTimeOffset OData4ModificationDate {
get { return Utils.ToDTO(ModificationDate); }
set { ModificationDate = Utils.ToDT(value); }
}
[NotMapped]
public System.Nullable<System.DateTimeOffset> OData4ModificationDate2 {
get { return Utils.ToDTO(ModificationDate2); }
set { ModificationDate2 = Utils.ToDT(value); }
}
}
}
| gilesbradshaw/breeze.server.net | Tests/Model_NorthwindIB_CF.EF6/OData4Extns.cs | C# | mit | 3,373 |
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var UIWidgetAddNodeEditorTest = UIBaseLayer.extend({
ctor: function () {
this._super();
var root = this._parseUIFile("ccs-res/cocosui/UIEditorTest/UIWidgetAddNode/widget_add_node.json");
this._mainNode.addChild(root);
var back_label =ccui.helper.seekWidgetByName(root, "back");
back_label.addTouchEventListener(this.backEvent,this);
var sprite = new cc.Sprite("ccs-res/cocosui/ccicon.png");
sprite.x = 240;
sprite.y = 160;
root.addNode(sprite,9999);
}
});
| dios-game/dios-cocos | src/oslibs/cocos/cocos-src/tests/js-tests/src/CocoStudioTest/GUITest/UINodeContainerTest/UINodeContainerTest.js | JavaScript | mit | 1,893 |
module Fastlane
module Actions
module SharedValues
SIGH_PROFILE_PATH = :SIGH_PROFILE_PATH
SIGH_PROFILE_PATHS = :SIGH_PROFILE_PATHS
SIGH_UDID = :SIGH_UDID # deprecated
SIGH_UUID = :SIGH_UUID
SIGH_NAME = :SIGH_NAME
SIGH_PROFILE_TYPE ||= :SIGH_PROFILE_TYPE
end
class GetProvisioningProfileAction < Action
def self.run(values)
require 'sigh'
require 'credentials_manager/appfile_config'
Sigh.config = values # we already have the finished config
Sigh.config[:api_key] ||= Actions.lane_context[SharedValues::APP_STORE_CONNECT_API_KEY]
path = Sigh::Manager.start
Actions.lane_context[SharedValues::SIGH_PROFILE_PATH] = path # absolute path
Actions.lane_context[SharedValues::SIGH_PROFILE_PATHS] ||= []
Actions.lane_context[SharedValues::SIGH_PROFILE_PATHS] << path
uuid = ENV["SIGH_UUID"] || ENV["SIGH_UDID"] # the UUID of the profile
name = ENV["SIGH_NAME"] # the name of the profile
Actions.lane_context[SharedValues::SIGH_UUID] = Actions.lane_context[SharedValues::SIGH_UDID] = uuid if uuid
Actions.lane_context[SharedValues::SIGH_NAME] = Actions.lane_context[SharedValues::SIGH_NAME] = name if name
set_profile_type(values, ENV["SIGH_PROFILE_ENTERPRISE"])
return uuid # returs uuid of profile
end
def self.set_profile_type(values, enterprise)
profile_type = "app-store"
profile_type = "ad-hoc" if values[:adhoc]
profile_type = "development" if values[:development]
profile_type = "developer-id" if values[:developer_id]
profile_type = "enterprise" if enterprise
UI.message("Setting Provisioning Profile type to '#{profile_type}'")
Actions.lane_context[SharedValues::SIGH_PROFILE_TYPE] = profile_type
end
def self.description
"Generates a provisioning profile, saving it in the current folder (via _sigh_)"
end
def self.author
"KrauseFx"
end
# rubocop:disable Lint/MissingKeysOnSharedArea
def self.output
[
['SIGH_PROFILE_PATH', 'A path in which certificates, key and profile are exported'],
['SIGH_PROFILE_PATHS', 'Paths in which certificates, key and profile are exported'],
['SIGH_UUID', 'UUID (Universally Unique IDentifier) of a provisioning profile'],
['SIGH_NAME', 'The name of the profile'],
['SIGH_PROFILE_TYPE', 'The profile type, can be appstore, adhoc, development, enterprise']
]
end
def self.return_value
"The UUID of the profile sigh just fetched/generated"
end
def self.details
"**Note**: It is recommended to use [match](https://docs.fastlane.tools/actions/match/) according to the [codesigning.guide](https://codesigning.guide) for generating and maintaining your provisioning profiles. Use _sigh_ directly only if you want full control over what's going on and know more about codesigning."
end
def self.available_options
require 'sigh'
Sigh::Options.available_options
end
def self.is_supported?(platform)
[:ios, :mac].include?(platform)
end
def self.example_code
[
'get_provisioning_profile',
'sigh # alias for "get_provisioning_profile"',
'get_provisioning_profile(
adhoc: true,
force: true,
filename: "myFile.mobileprovision"
)'
]
end
def self.category
:code_signing
end
end
end
end
| Econa77/fastlane | fastlane/lib/fastlane/actions/get_provisioning_profile.rb | Ruby | mit | 3,605 |
/*jslint node: true */
"use strict";
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bower: {
install: {
options: {
install: true,
copy: false,
targetDir: './libs',
cleanTargetDir: true
}
}
},
jshint: {
all: ['Gruntfile.js', 'app/*.js', 'app/**/*.js']
},
karma: {
options: {
configFile: 'config/karma.conf.js'
},
unit: {
singleRun: true,
},
continuous: {
singleRun: false,
autoWatch: true
}
},
clean: {
temp: {
src: ['tmp']
}
},
uglify: {
dist: {
files: {
'dist/app.js': ['dist/app.js']
},
options: {
mangle: false
}
}
},
concat: {
options: {
separator: ';'
},
dist: {
src: ['app/js/*.js'],
dest: 'dist/js/app.js'
}
},
watch: {
dev: {
files: ['Gruntfile.js', 'app/js/*.js', '*.html', 'app/templates/*.html'],
tasks: ['jshint', 'karma:unit', 'concat:dist', 'clean:temp'],
options: {
atBegin: true
}
},
min: {
files: ['Gruntfile.js', 'app/*.js', '*.html'],
tasks: ['jshint', 'karma:unit', 'concat', 'clean:temp',
'uglify:dist'
],
options: {
atBegin: true
}
}
},
compress: {
dist: {
options: {
archive: 'dist/<%= pkg.name %>-<%= pkg.version %>.zip'
},
files: [{
src: ['index.html'],
dest: '/'
}, {
src: ['dist/**'],
dest: 'dist/'
}, {
src: ['assets/**'],
dest: 'assets/'
}, {
src: ['libs/**'],
dest: 'libs/'
}]
}
},
connect: {
server: {
options: {
hostname: 'localhost',
port: 8080
}
}
},
exec: {
initnpm: {
cmd: 'npm install',
},
initbower: {
cmd: 'bower install',
},
status: {
cmd: 'git status'
},
add: {
cmd: 'git add --all'
},
commit: {
cmd: 'git commit -m" Version<%= pkg.version %>"'
},
push: {
cmd: 'git push origin master'
}
},
bump: {
options: {
files: ['package.json'],
updateConfigs: [],
commit: true,
commitMessage: 'Release v%VERSION%',
commitFiles: ['-a'],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin',
gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
globalReplace: false,
prereleaseName: false,
regExp: false
}
},
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-html2js');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-bower-task');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-exec');
grunt.loadNpmTasks('grunt-bump');
grunt.registerTask('default', ['exec:initnpm', 'exec:initbower']);
grunt.registerTask('git', ['exec:status', 'exec:add', 'exec:commit', 'exec:push']);
grunt.registerTask('dev', ['bower', 'connect:server', 'watch:dev']);
grunt.registerTask('test', ['bower', 'jshint', 'karma:continuous']);
grunt.registerTask('minified', ['bower', 'connect:server', 'watch:min']);
grunt.registerTask('package', ['bower', 'jshint', 'karma:unit', 'concat:dist', 'uglify:dist', 'clean:temp', 'compress:dist']);
};
| Fountaintechies/distance-calculator | Gruntfile.js | JavaScript | mit | 3,923 |
var doc = require('./doc');
var dev = require('./dev');
var build = require('./build');
module.exports = {
transformAPIModel:doc.transformAPIModel,
updateOwnDependenciesFromLocalRepositories:dev.updateOwnDependenciesFromLocalRepositories,
buildDevEnv:dev.buildDevEnv,
extractImports:build.extractImports,
createImportBlock:build.createImportBlock,
sortFiles:build.sortFiles
};
| damianof/tools | src/index.js | JavaScript | mit | 390 |
var exec = require('child_process').exec,
fs = require('fs'),
path = require('path'),
EventEmitter = require('events').EventEmitter;
var temp = require('temp'),
tasks = require('./tasks'),
Q = require('q');
// Map of extensions to tasks
var extensions = {
gif: 'GIF',
jpg: 'JPEG',
jpeg: 'JPEG',
png: 'PNG'
};
var Job = module.exports = function (settings) {
var self = this;
this.queue = [];
this.report = {
fileCount: 0,
scanned: {},
size: {
start: 0,
end: 0
},
time: {
start: null,
end: null
}
};
this.settings = settings;
this.settings.inputs.forEach(function (input) {
var files = self.scan(input, 0);
files.forEach(function (file) {
self.add(file);
});
});
};
// Job extends EventEmitter
Job.prototype = new EventEmitter;
Job.prototype.add = function (filename) {
var self = this;
// Try to find a task for the current file. If nothing is found, no task is executed
var task = tasks[extensions[path.extname(filename).substr(1)]];
if (task) {
this.queue.push(function () {
return self.compress(filename, task);
});
return ++this.report.fileCount;
} else {
return false;
}
};
Job.prototype.compress = function (filename, task) {
var deferred = Q.defer(),
self = this;
temp.open('PULVERIZR', function (err, info) {
var scratchSpace = info.path;
// Copy the old file to a temporary spot
exec('cp "' + filename + '" ' + scratchSpace, function (error, stdout, stderr) {
task.call(this, {
original: filename,
filename: scratchSpace,
settings: self.settings,
deferred: deferred,
job: self
}).then(function (newStats) {
var oldStats = fs.statSync(filename);
self.report.size.start += oldStats.size;
self.report.size.end += newStats.size;
self.emit('compression', {
filename: filename,
oldSize: oldStats.size,
newSize: newStats.size
});
// If optimizations were made and this isn't a dry run, copy the new file over
if (!self.settings.dryRun && newStats.size < oldStats.size) {
fs.renameSync(scratchSpace, filename);
} else {
// Remove the temporary file
fs.unlinkSync(scratchSpace);
}
});
});
});
return deferred.promise;
};
Job.prototype.run = function () {
var self = this,
result = Q.resolve();
this.emit('start', {});
this.report.time.start = Date.parse(new Date());
// run the queue
this.queue.forEach(function (f) {
result = result.then(f);
});
result.then(function () {
var r = self.report;
r.time.end = Date.parse(new Date());
self.emit('finish', r);
});
};
Job.prototype.scan = function (filename, depth) {
var self = this,
files = [];
(function walk (filename, depth) {
var stats = fs.statSync(filename);
if (stats.isFile()) {
files.push(filename);
} else if ((self.settings.recursive || depth === 0) && !self.report.scanned[filename] && stats.isDirectory()) {
depth++;
fs.readdirSync(filename).forEach(function (_filename) {
// Scans the directory, and strips off a trailing slash if it exists
walk.call(this, (filename.replace(/(\/)$/g, '') + '/' + _filename), depth);
});
}
}(filename, 0));
return files;
};
| vdhwouter/GameNation | src/main/resources/static/node_modules/pulverizr/lib/job.js | JavaScript | mit | 3,488 |
namespace Nancy.Demo.Authentication.Forms
{
using System;
using System.Dynamic;
using Nancy.Authentication.Forms;
using Nancy.Extensions;
public class MainModule : NancyModule
{
public MainModule()
{
Get["/"] = x => {
return View["index"];
};
Get["/login"] = x =>
{
dynamic model = new ExpandoObject();
model.Errored = this.Request.Query.error.HasValue;
return View["login", model];
};
Post["/login"] = x => {
var userGuid = UserDatabase.ValidateUser((string)this.Request.Form.Username, (string)this.Request.Form.Password);
if (userGuid == null)
{
return this.Context.GetRedirect("~/login?error=true&username=" + (string)this.Request.Form.Username);
}
DateTime? expiry = null;
if (this.Request.Form.RememberMe.HasValue)
{
expiry = DateTime.Now.AddDays(7);
}
return this.LoginAndRedirect(userGuid.Value, expiry);
};
Get["/logout"] = x => {
return this.LogoutAndRedirect("~/");
};
}
}
} | dbolkensteyn/Nancy | src/Nancy.Demo.Authentication.Forms/MainModule.cs | C# | mit | 1,383 |